Sending a Transaction

To send a transaction, you must construct a valid transaction object and then prompt the user to sign the transaction with their private key.

Direct Sending

Triggering this directly would look make use of the provider request function and look like this:

const result = await provider.request({
        method: 'eth_sendTransaction',
        params: [
          {
            from: address,
            to: '0x6aDdF38602487b7a159D926bc08151eBaEEF2B70',
            value: '0x0',
            gasLimit: '0x5028',
            gasPrice: '0x2540be400',
            type: '0x0',
          },
        ],
});

However, there are several other parts of a transaction object that might need to be specfied, and therefore it is suggested to make use of a web3 library that abstracts away a lot of this complexity, like ethers.js

Using Ethers.js

Below is a code example that builds out a valid transaction object and prompts the transaction to send with permission from the signer, utilizing ethers.js

import { TransactionResponse, Web3Provider } from "@ethersproject/providers";
import { utils } from "ethers";

/**
 * Send 1 wei from the connected wallet to itself
 * @param {Web3Provider} provider a web3 provider
 * @returns {Promise<TransactionResponse>} a raw transaction object
 */
export async function sendTransaction(
  provider: Web3Provider
): Promise<TransactionResponse> {
  try {
    const signer = provider.getSigner();
    const address = await signer.getAddress();
    const gasPrice = await provider.getGasPrice();
    const transactionParameters = {
      nonce: await provider.getTransactionCount(address),
      gasPrice,
      gasLimit: utils.hexlify(100000),
      to: address,
      from: address,
      value: utils.parseUnits("1", "wei"),
    };
    return signer.sendTransaction(transactionParameters);
  } catch (error) {
    console.warn(error);
    throw new Error("Error sending transaction");
  }
}

You'll notice a lot more structure with the parameters needed to invoke signer.sendTransaction . Due to the abstraction and wide use of libraries like ethers, we recommend this method when constructing your evm transactions.

Last updated