14

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

2 Answers 2

13

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);
};
4
  • 1
    Stupid question probably but what is/can be provider here? Commented Jun 4, 2021 at 15:57
  • 1
    please check the ethers.js docs - docs.ethers.io/v5/api/providers
    – Andrew
    Commented Jun 6, 2021 at 13:44
  • thanks, waitForTransaction works :) Commented Oct 2, 2021 at 9:33
  • This code could use an update, it doesn't work anymore
    – Jasperan
    Commented Feb 20, 2022 at 20:17
1

Signing

Link: https://docs.ethers.io/v5/cookbook/transactions/#cookbook--compute-raw-transaction

or: https://docs.ethers.io/v5/api/signer/#Signer--signing-methods

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
    Commented Mar 27, 2020 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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