import { ensureLeading0x , normalizeAddressWith0x } from '@celo/base/lib/address' ; import { CeloTx , DefaultRpcCaller , Provider , RpcCaller } from '@celo/connect' ; import { privateKeyToAddress } from '@celo/utils/lib/address' ; import { UnlockableWallet } from '@celo/wallet-base' ; import { RemoteWallet } from '@celo/wallet-remote' ; import { RpcSigner } from './rpc-signer' ; export enum RpcWalletErrors { FetchAccounts = 'RpcWallet: failed to fetch accounts from server' , AccountAlreadyExists = 'RpcWallet: account already exists' } export class RpcWallet extends RemoteWallet < RpcSigner > implements UnlockableWallet { protected readonly rpc : RpcCaller ; constructor ( protected _provider ) { super ( ) ; this . rpc = new DefaultRpcCaller ( _provider ) ; } async loadAccountSigners ( ) { const addressToSigner = new Map < string , RpcSigner > ( ) ; const resp = await this . rpc . call ( 'eth_accounts' , [ ] ) ; if ( resp . error ) { throw new Error ( RpcWalletErrors . FetchAccounts ) ; } const accounts = resp . result ! ; accounts . forEach ( ( account ) => { addressToSigner . set ( account , new RpcSigner ( this . rpc , account ) ) ; } ) ; return addressToSigner ; } async addAccount ( privateKey , passphrase ) { const address = normalizeAddressWith0x ( privateKeyToAddress ( ensureLeading0x ( privateKey ) ) ) ; if ( this . hasAccount ( address ) ) { throw new Error ( RpcWalletErrors . AccountAlreadyExists ) ; } const signer = new RpcSigner ( this . rpc , address ) ; const resultantAddress = await signer . init ( privateKey , passphrase ) ; this . addSigner ( resultantAddress , signer ) ; return resultantAddress ; } async unlockAccount ( address , passphrase , duration ) { const signer = this . getSigner ( address ) ; return signer . unlock ( passphrase , duration ) ; } isAccountUnlocked ( address ) { const signer = this . getSigner ( address ) ; return signer . isUnlocked ( ) ; } param txParams dev async signTransaction ( txParams ) { const fromAddress = txParams . from ! . toString ( ) ; const signer = this . getSigner ( fromAddress ) ; return signer . signRawTransaction ( txParams ) ; } }