Ethers.js: TypeError: Cannot read property 'getCode' of undefined when using contractWithSigner

Created on 28 Nov 2018  ·  6Comments  ·  Source: ethers-io/ethers.js

Trying to create a new instance of the Contract with a Signer as follows

provider = ethers.getDefaultProvider('ropsten');
wallet = ethers.Wallet.createRandom();
contract = new ethers.Contract(address, abi, provider);
contractWithSigner = contract.connect(wallet);

When the contract is invoked, it doesn't work as expected

await contractWithSigner.update('msgString');

The error returned is ethers.js:289 Uncaught (in promise) TypeError: Cannot read property 'getCode' of undefined

link to gist with more details

discussion

Most helpful comment

Hi,
Try to set a provider to the wallet.

All 6 comments

Hi,
Try to set a provider to the wallet.

Ah yes. I guess I commented on the gist.

@marcelomorgado is correct. :)

Thanks, I was able to get it working after attaching provider to the wallet.

Similar issue with using mnemonic. Am I doing this wrong?

const wallet= await ethers.Wallet.fromMnemonic('...') //no provider
wallet.provider = provider //readonly; fails

Fails. provider is readonly so you cannot set.
You must first create and extract privateKey to new wallet.

The following solves, hope this is useful:

const temp = await ethers.Wallet.fromMnemonic('...')
const wallet = await new ethers.Wallet(temp.privateKey, provider)

However this begs the question:
Is there a way to provide the mnemonic and provider at once?

You cannot provide a provider at the same time, which is something I’ve considered doing, but then the signature starts looking crazy... I’ll make a note to look into it for v5.

However, fromMnemonic is synchronous, so you don’t need the awaits, and the connect method is what you are looking for. :)

const wallet = Wallet.fromMnemonic(“...”).connect(provider);

Amazing! I've just started with your library for my latest client project.

Besides a few small documentation details like this, I've found it to be quite awesome!

If I spot anything specific again and can fix, I will reach out with a PR.

Was this page helpful?
0 / 5 - 0 ratings