Esc

wallet-merchant

@megaeth-labs/wallet-merchantAI Generated

The server side of sponsored transactions. When a user sends a transaction, the wallet asks your sponsor URL to pay for it; this package's handler decides whether to, caps the fee and signs the payment from your merchant account. It works with any server that handles a POST and needs no RPC endpoint. See Sponsoring Gas.

pnpm add @megaeth-labs/wallet-merchant viem

Creating the Handler#

createMerchant#

Creates the sponsor handler for your merchant account, an EIP-7702 smart account that pays the fees. See Create the Sponsor Wallet and Choosing What to Sponsor.

tsTypes
createMerchant: (options: MerchantOptions) => Merchant;

type MerchantOptions = {
    address: `0x${string}`; // Your merchant account
    key: `0x${string}` | { type: 'secp256k1' | 'p256'; privateKey: `0x${string}` };
    sponsor?: boolean | ((request: SponsorRequest) => boolean | Promise<boolean>); // Defaults to true
    paymentMaxAmount?: bigint; // Fixed fee cap per transaction, in the fee token's smallest unit
    paymentGasBudget?: bigint; // Gas budget for the default fee cap
};

type Merchant = {
    fetch: (request: Request) => Promise<Response>;
    handle: (body: unknown) => Promise<MerchantResult>;
};

type SponsorRequest = {
    intent: JsonRpcIntent; // The unsigned intent the wallet built
    domain: IntentDigestDomain;
    keyType?: IntentSigningKeyType; // The type of key the user will sign with
};

type MerchantResult =
    | { status: 200; body: SponsorResponse }
    | { status: 400 | 403 | 500; body: SponsorErrorResponse };

type JsonRpcIntent = {
    eoa: Address;
    executionData: Hex;
    nonce: Hex;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: Hex;
    paymentPerGas: Hex;
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: Hex;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: Hex;
    gasFloor: Hex;
    txMode: number;
};

type IntentDigestDomain = {
    name: string;
    version: string;
    chainId: number;
    verifyingContract: Address;
};

type IntentSigningKeyType = 'address' | 'p256' | 'secp256k1' | 'webauthn-p256';

type SponsorResponse = {
    intent: JsonRpcIntent; // The intent, with your account as payer and your payment signature
    digest: `0x${string}`; // What the user signs
};

type SponsorErrorResponse = {
    error: { code: number; message: string };
};
tsExample
import { decodeExecutionData, fromJsonRpcIntent } from '@megaeth-labs/wallet-intent';
import { createMerchant } from '@megaeth-labs/wallet-merchant';

const MY_CONTRACT = '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C';

export const merchant = createMerchant({
    address: process.env.MERCHANT_ADDRESS as `0x${string}`,
    key: process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
    // Only pay for transactions that call your own contract.
    sponsor: ({ intent }) => {
        const calls = decodeExecutionData(fromJsonRpcIntent(intent).executionData);
        return calls.every((call) => call.to.toLowerCase() === MY_CONTRACT.toLowerCase());
    },
});

Handling Requests#

merchant.fetch#

Handles a sponsor request as a Fetch API Request and returns a Response, for servers that use them: Hono, Next.js, Bun, Deno and Cloudflare Workers. See Create the Sponsor Endpoints.

tsTypes
fetch: (request: Request) => Promise<Response>;

// The JSON body of the request.
type SponsorRequest = {
    intent: JsonRpcIntent; // The unsigned intent the wallet built
    domain: IntentDigestDomain;
    keyType?: IntentSigningKeyType; // The type of key the user will sign with
};

// The JSON body of a 200 response.
type SponsorResponse = {
    intent: JsonRpcIntent; // The intent, with your account as payer and your payment signature
    digest: `0x${string}`; // What the user signs
};

// The JSON body of a 400, 403 or 500 response.
type SponsorErrorResponse = {
    error: { code: number; message: string };
};

type JsonRpcIntent = {
    eoa: Address;
    executionData: Hex;
    nonce: Hex;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: Hex;
    paymentPerGas: Hex;
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: Hex;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: Hex;
    gasFloor: Hex;
    txMode: number;
};

type IntentDigestDomain = {
    name: string;
    version: string;
    chainId: number;
    verifyingContract: Address;
};

type IntentSigningKeyType = 'address' | 'p256' | 'secp256k1' | 'webauthn-p256';
tsExample
// Next.js: app/sponsor/route.ts
export const POST = (request: Request) => merchant.fetch(request);

merchant.handle#

Handles a sponsor request body your server has already parsed and returns the status and body to send, for servers such as Express and Fastify. It never throws. See Create the Sponsor Endpoints.

tsTypes
handle: (body: unknown) => Promise<MerchantResult>;

type MerchantResult =
    | { status: 200; body: SponsorResponse }
    | { status: 400 | 403 | 500; body: SponsorErrorResponse };

type SponsorResponse = {
    intent: JsonRpcIntent;
    digest: `0x${string}`;
};

type SponsorErrorResponse = {
    error: { code: number; message: string };
};

type JsonRpcIntent = {
    eoa: Address;
    executionData: Hex;
    nonce: Hex;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: Hex;
    paymentPerGas: Hex;
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: Hex;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: Hex;
    gasFloor: Hex;
    txMode: number;
};
tsExample
import express from 'express';

const app = express();

app.post('/sponsor', express.json(), async (req, res) => {
    const { status, body } = await merchant.handle(req.body);
    res.status(status).json(body);
});

Error Codes#

The code in an error response.

StatusCodeWhen
400-32700The body isn't JSON (fetch only)
400-32600The body isn't a valid sponsor request
403-32003sponsor declined the request
500-32000Something failed while preparing the intent