1

I would like to invoke a smart contract function using Ethers library. Since I have my own node I'm connecting using RPC connection and now I would like to invoke a transfer function (of an ERC20 contract), which according to the documentation requires me to use a signer:

const provider = new ethers.providers.JsonRpcProvider(NODE_URL)
const signer = provider.getSigner()

// Read-Write; By connecting to a Signer, allows:
// - Everything from Read-Only (except as Signer, not anonymous)
// - Sending transactions for non-constant functions
const erc20_rw = new ethers.Contract(erc20ContractAddress, abi, signer)
const tx = await erc20_rw.transfer(targetAddress, amount)

My question is: Where should I provide my private key? I mean - the provider requires me to give only a node url and the signer is provided by the provider. I'm invoking a transfer, which defiantly should require me to provide a private key at some point. What am I missing?

0

You could simply replace the 2nd line in your code above and instead define the signer as follows:

const signer = new ethers.Wallet(your_private_key_string, provider);

You could also define a signer from a mnemonic instead of a private key, as follows:

const account = utils.HDNode.fromMnemonic(your_mnemonic_string).derivePath(`m/44'/60'/0'/0/${your_selected_account}`);

const signer = new Wallet(account, provider);

Where your_selected_account is the account index to use, starting from 0.

Note: make sure to use the right derivation path for you (Ledger, MEW, Metamask, ..etc).

2
  • Thanks of that. I now understand that I need to update the question: I don't have a private key since the entity that holds the ERC20 token which I like to transfer is a smart-contract. How can I do that? Should the contract approve some wallet to do the transfer?
    – forhas
    Jul 15 at 7:45
  • 1
    @forhas the contract will not have any ability to transfer or approve the transfer of any tokens that it holds by default, unless it had such ability implemented by the contract creator. Jul 15 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.