Skip to main content

Send transactions

Handle EVM transactions in your JavaScript dapp. With the SDK, you can:

  • Send transactions.
  • Track transaction status in real time.
  • Estimate gas costs accurately.
  • Handle transaction errors gracefully.
  • Manage complex transaction patterns.

You can implement transaction handling directly in JavaScript. The following are examples of sending a basic transaction and an advanced transaction with gas estimation.

Send a basic transaction

import { MetaMaskSDK } from '@metamask/sdk'
import { createPublicClient, createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'

// Initialize SDK
const MMSDK = new MetaMaskSDK()
const provider = MMSDK.getProvider()

const publicClient = createPublicClient({ chain: mainnet, transport: custom(provider) })
const walletClient = createWalletClient({ chain: mainnet, transport: custom(provider) })

// data for the transaction
const destination = '0xRECIPIENT_ADDRESS'
const amount = parseEther('0.0001')
const address = await walletClient.getAddresses()

// Submit transaction to the blockchain
const hash = await walletClient.sendTransaction({
account: address[0],
to: destination,
value: amount,
})

const receipt = await publicClient.waitForTransactionReceipt({ hash })

Send an advanced transaction with gas estimation

To add gas estimation, use the eth_estimateGas RPC method.

async function estimateGas(transaction) {
try {
const gasEstimate = await ethereum.request({
method: 'eth_estimateGas',
params: [transaction],
})

// Add 20% buffer for safety
return (BigInt(gasEstimate) * 120n) / 100n
} catch (error) {
console.error('Gas estimation failed:', error)
throw error
}
}

Best practices

Follow these best practices when handling transactions.

Transaction security

  • Always validate inputs before sending transactions.
  • Check wallet balances to ensure sufficient funds.
  • Verify addresses are valid.

Error handling

  • Handle common errors like user rejection and insufficient funds.
  • Provide clear error messages to users.
  • Implement proper error recovery flows.
  • Consider network congestion in gas estimates.

User experience

  • Display clear loading states during transactions.
  • Show transaction progress in real time.
  • Provide detailed transaction information.

Common errors

Error codeDescriptionSolution
4001User rejected transactionShow a retry option and a clear error message.
-32603Insufficient fundsCheck the balance before sending a transaction.
-32000Gas too lowIncrease the gas limit or add a buffer to the estimation.
-32002Request already pendingPrevent multiple concurrent transactions.

Next steps

See the following guides to add more functionality to your dapp: