Pay a Request Link

This script creates and fulfills request links and completes them.

import peanut from '@squirrel-labs/peanut-sdk';
import { BigNumber, ethers } from 'ethers';

const recipientAddress = '0x42A5DC31169Da17639468e7Ffa271e90Fdb5e85A';
const tokenAddress = '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85'; // USDC on Optimism
const chainId = '10'; // Optimism
const tokenAmount = '10';
const tokenDecimals = '6';
const APIKey = 'api-key';
const apiUrl = 'api-url';
const userPrivateKey = 'your-private-key';

// Initialize provider and wallet
async function getSourceChainProvider() {
    const sourceChainProvider = await ethers.getDefaultProvider(chainId);
    return new ethers.Wallet(userPrivateKey, sourceChainProvider); // Connect wallet to the provider
}

const userSourceChainWallet = await getSourceChainProvider();

// Function to create a request link
async function createRequestLink(): Promise<string | null> {
    try {
        const { link } = await peanut.createRequestLink({
            chainId,
            tokenAddress,
            tokenAmount,
            tokenType: EPeanutLinkType.erc20, // or EPeanutLinkType.native
            tokenDecimals,
            recipientAddress,
            APIKey,
            apiUrl,
        });
        return link;
    } catch (error) {
        console.error('Error creating request link:', error);
        return null;
    }
}

// Function to fulfill a request link
async function fulfillRequestLink(link: string) {
    try {
        // Get the details of the request link
        const linkDetails = await peanut.getRequestLinkDetails({
            link,
            APIKey,
            apiUrl,
        });
        console.log('Got the link details!', linkDetails);

        // Prepare the unsigned transaction for fulfilling the request link
        const { unsignedTx } = peanut.prepareRequestLinkFulfillmentTransaction({
            recipientAddress,
            tokenAddress: linkDetails.tokenAddress,
            tokenAmount: linkDetails.tokenAmount,
            tokenDecimals: linkDetails.tokenDecimals,
            tokenType: EPeanutLinkType.erc20,
        });
        console.log('Prepared unsigned transaction', unsignedTx);

        // Sign and submit the transaction
        const { tx, txHash } = await signAndSubmitTx({
            unsignedTx,
            structSigner: {
                signer: userSourceChainWallet,
                gasLimit: BigNumber.from(2_000_000),
            },
        });
        console.log('Submitted transaction with tx hash', txHash);
        await tx.wait();
        console.log('Request link fulfillment completed!');
        
    } catch (error) {
        console.error('Error fulfilling request link:', error);
    }
}

(async () => {
    const link = await createRequestLink();
    if (link) {
        console.log('Created request link:', link);
        // Fulfill the request link
        await fulfillRequestLink(link);
    }
})();

Last updated