Skip to content
Embedded Wallet
Examples
Batch Transactions

Batching Transactions

Simple Crypto's wallet allows users to submit multiple transactions at once, also known as a batch transaction.

Batched transactions enable a superior user experience. For example, minting an NFT that requires 10 USDC to mint would typically require two transactions:

  • An approval transaction that allows the NFT contract to spend the user's 10 USDC
  • A mint transaction to actually mint the NFT

This would require the user to sign two separate transactions for seemingly the same action, which can be frustrating and confusing. Simple Crypto enables dapps to batch transactions so that users only need to ever sign once to complete a set of actions!

Examples

There's a couple different ways to submit batch transaction to Simple Crypto.

1. Submit multiple transactions at once

When multiple transactions are submitted at the same time, Simple Crypto will try to batch them together under the hood.

Check out the following example that uses ethers.js.

import { ethers } from "ethers";
import SimpleCryptoSDK from "@simplecrypto/wallet-sdk";

const simpleCryptoWallet = new SimpleCryptoSDK();

const provider = new ethers.providers.Web3Provider(simpleCryptoWallet);

const usdcContract = new ethers.Contract(
  USDC_ADDRESS,
  ["function approve(address spender, uint256 amount) returns (bool)"],
  provider, 
)

const nftContract = new ethers.Contract(
    NFT_CONTRACT,
    ["function mint(address recipient, uint256 amount) returns (bool)"],
     provider,
);

const approvePromise = usdcContract.approve(NFT_CONTRACT, 1_000_000); // approve 1 USDC
const mintPromise = nftContract.mint(USER_ADDRESS, 1); // mint 1 NFT

await Promise.all([approvePromise, transferPromise])

2. The sendBatchTransaction() function

The Simple Crypto SDK also exposes a sendBatchTransaction() function.

import { ethers, BigNumber } from "ethers";
import SimpleCryptoSDK from "@simplecrypto/wallet-sdk";

const simpleCryptoWallet = new SimpleCryptoSDK();

/**
 * Create the interfaces of the contracts to encode the function data
 */
const erc20Interface = new ethers.utils.Interface([
  "function approve(address spender, uint256 amount) returns (bool)"
]);

const nftInterface = new ethers.utils.Interface([
  "function mint(address recipient, uint256 amount) returns (bool)"
]);

/**
 * Encode the function data for each transaction
 */
// Approval data for 10 USDC (USDC has 6 decimals)
const approvalData = erc20Interface.encodeFunctionData("approve", [
  USER_ADDRESS,
  BigNumber.from(10).pow(7)
]);

// Mint data
const mintData = nftInterface.encodeFunctionData("mint", [USER_ADDRESS, 1]);

/**
 * Submit the batch transaction
 */
const result = await simpleCryptoWallet.sendBatchTransaction([
  {
    to: USDC_ADDRESS,
    data: approvalData,
  },
  {
    to: NFT_ADDRESS,
    data: mintData
  },
]);
Last updated on February 4, 2023