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?
Best Answer
You could simply replace the 2nd line in your code above and instead define the signer as follows:
You could also define a signer from a mnemonic instead of a private key, as follows:
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).