5

Is there any sample code in ethers.js to send raw transaction and to sign transactions?

4

to transfer some ETHs you could use the following code:

const Tx = require('ethereumjs-tx')
const ethers = require('ethers')

const sendEths = async ({
  to,
  from,
  fromPrivateKey,
  value,
  gasPrice,
  gasLimit = ethers.utils.hexlify(21000),
}) => {
  const txCount = await provider.getTransactionCount(from)
  // build the transaction
  const tx = new Tx({
    nonce: ethers.utils.hexlify(txCount),
    to,
    value: ethers.utils.parseEther(value).toHexString(),
    gasLimit,
    gasPrice,
  })
  // sign the transaction
  tx.sign(Buffer.from(fromPrivateKey, 'hex'))
  // send the transaction
  const { hash } = await provider.sendTransaction('0x' + tx.serialize().toString('hex'))
  await provider.waitForTransaction(hash)
}
2
0

Signing

Link: https://docs.ethers.io/ethers.js/html/cookbook-signing.html

or: https://docs.ethers.io/ethers.js/html/api-wallet.html#signing

Sending Raw Transaction Data

I don't know this for a fact, but my understanding is that provider.sendTransaction() sends the raw data over. It takes a hex string, and is mentioned under the second signing link above in the snippets.

1
  • Thanks How can I set the private key for provider.sendTransaction()? I see here there is not any account info, just provider, but provider do not contain private key, which account associate with provider? Can I change the private key? – Louis Mar 27 '20 at 13:42

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.