Combine two transactions into one transaction

This guide demonstrates how to combine two simple transactions:

  • Set allowance on Uniswap
  • Swap on Uniswap
1

Get your free API key

Get your free API key and get instant access to every endpoint.

2

Install the Typescript SDK

npm install @compass-labs/api-sdk
3

Convert the two transactions into one transaction

import { CompassApiSDK } from "@compass-labs/api-sdk";
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet } from 'viem/chains';
import { http } from 'viem';

import { createWalletClient } from 'viem';

const PRIVATE_KEY = "9e84c7dadc475bf1cba49083b3c40584a5c7e4dc8da26ee910fdb18784d0dd47"

const compassApiSDK = new CompassApiSDK({
    apiKeyAuth: "Zp69nDSOYw9P02FiVnhZBaJkvkRcz0Pg1U7cjnhr",
});

async function run() {
    // First get the authorization
    const account = privateKeyToAccount(`0x${PRIVATE_KEY}`);


    const walletClient = createWalletClient({
        account,
        chain: mainnet,
        transport: http()
    });

    // 1. Get the authorization
    const auth = await compassApiSDK.transactionBatching.authorization({
        chain: "ethereum:mainnet",
        sender: account.address,
    });

    // 2. Sign the authorization
    const signedAuth = await walletClient.signAuthorization({
        account,
        address: auth.address,
    });

    // 3. Execute with the authorization

    // Then execute with the authorization
    const result = await compassApiSDK.transactionBatching.execute({
        chain: "ethereum:mainnet",
        sender: account.address,
        signedAuthorization: {
            nonce: signedAuth.nonce,
            address: signedAuth.address,
            chainId: signedAuth.chainId,
            r: signedAuth.r,
            s: signedAuth.s,
            yParity: signedAuth.yParity as number
        },
        actions: [
            {
                body: {
                    actionType: "ALLOWANCE_INCREASE",
                    token: "WETH",
                    contractName: "UniswapV3Router",
                    amount: "1000",
                },
            },
            {
                body: {
                    actionType: "UNISWAP_BUY_EXACTLY",
                    amount: 1,
                    fee: "0.01",
                    maxSlippagePercent: 0.5,
                    tokenIn: "WETH",
                    tokenOut: "USDC",
                    wrapEth: true,
                }
            }
        ]
    });

// Handle the result
    console.log(result);
}

run();