[Ethereum] Ethers js adding provider

dappsethers.jsjavascript

I have an app I am working on implementing ethers.js. There are two methods I am using to create a wallet: new ethers.Wallet(privateKey, provider); and new ethers.Wallet.createRandom();

With creating a random wallet, it doesnt seem like you can give it the provider like when importing a private key. That is fine, because once you log out and back in at a later time and get the wallet fromEncryptedJson, both from the private key import, and the creating a random wallet the provider is now undefined

Initially wallet.provider from the import account is there, but after logging out (encrypting the wallet) and then logging back in, after getting the wallet from encryption, provider is not defined. I need the provider at later times in the app, for instance using the method wallet.getTransactionCount();, this uses the provider, but it is undefined after logging back in. And if I do wallet.provider = provider I cant re-assign this value as it says its read only.

So is there a way to set the provider when you un-encrypt the wallet?

Best Answer

**** EDIT ****

Figured it out.

ethers.Wallet.fromEncryptedJson(encryptedWallet, passphrase).then((myWallet) => {
    const loggedInWallet = myWallet.connect(provider);
    // loggedInWallet will now have provider added
}

Currently the only solve I have been able to get to work is kinda hacky. Object assign does not seem to copy all the key pairs for some reason. I used Object.create and passed in the wallet once un-encrypted.

const LoggedInWallet = Object.create(walletFromUnencryption);
LoggedInWallet.__proto__ = myWallet.__proto__;
LoggedInWallet._ethersType = myWallet._ethersType;
LoggedInWallet.provider = provider;
LoggedInWallet.signingKey = myWallet.signingKey;

This gave me a wallet with the needed data for use while user is logged in.

Not ideal it would seem. I would think when un-encrypting the wallet you could do something like:

ethers.Wallet.fromEncryptedJson(encryptedWallet, passphrase, provider).then((walletFromUnencryption) => 

adding provider as an option passing in, but doesnt seem like thats possible. So I will resort to what I have working for now till I can find the solution how to get the provider when un-encrypting the wallet

Related Topic