// Tollbeam gas sponsorship: one complete, sponsored ERC-4337 operation. // // Creates a standard SimpleAccount (v0.6) owned by a fresh key, asks Tollbeam // to sponsor its first operation, signs it, sends it and waits for the // receipt. The account pays nothing. Defaults to Base Sepolia, so a free // sandbox app is enough. // // npm install viem // TOLLBEAM_API_KEY= npx tsx gas-sponsorship.ts // // Optional: OWNER_KEY=0x... to reuse an owner key; TOLLBEAM_CHAIN=base for // mainnet with a production app. import { concat, createPublicClient, encodeFunctionData, http, parseAbi, toHex, type Hex } from "viem"; import { base, baseSepolia } from "viem/chains"; import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; const API_KEY = process.env.TOLLBEAM_API_KEY; if (!API_KEY) throw new Error("Set TOLLBEAM_API_KEY to your app's API key."); const CHAIN = process.env.TOLLBEAM_CHAIN ?? "base-sepolia"; const TOLLBEAM_RPC = `https://api.tollbeam.com/v1/${CHAIN}/rpc`; const ENTRY_POINT = "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789"; // v0.6 const FACTORY = "0x9406Cc6185a346906296840746125a0E44976454"; // SimpleAccountFactory v0.6 // Sent while asking for sponsorship: the right length, so the account's // signature check runs during simulation instead of reverting (AA23). const PLACEHOLDER_SIGNATURE: Hex = "0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c"; const chain = createPublicClient({ chain: CHAIN === "base" ? base : baseSepolia, transport: http() }); const owner = privateKeyToAccount((process.env.OWNER_KEY as Hex | undefined) ?? generatePrivateKey()); const factoryAbi = parseAbi([ "function getAddress(address owner, uint256 salt) view returns (address)", "function createAccount(address owner, uint256 salt) returns (address)", ]); const accountAbi = parseAbi(["function execute(address dest, uint256 value, bytes func)"]); const entryPointAbi = parseAbi([ "function getNonce(address sender, uint192 key) view returns (uint256)", "function getUserOpHash((address sender, uint256 nonce, bytes initCode, bytes callData, uint256 callGasLimit, uint256 verificationGasLimit, uint256 preVerificationGas, uint256 maxFeePerGas, uint256 maxPriorityFeePerGas, bytes paymasterAndData, bytes signature) userOp) view returns (bytes32)", ]); // Tollbeam's JSON-RPC. Every refusal carries data.message saying how to fix it. async function tollbeam(method: string, params: unknown[]): Promise { const res = await fetch(TOLLBEAM_RPC, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${API_KEY}` }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), }); const body = await res.json(); if (body.error) throw new Error(`${method}: ${body.error.message} - ${body.error.data?.message ?? "no detail"}`); return body.result; } async function main() { // 1. The smart account's address, and whether it exists yet. const sender = await chain.readContract({ address: FACTORY, abi: factoryAbi, functionName: "getAddress", args: [owner.address, 0n] }); const deployed = ((await chain.getCode({ address: sender })) ?? "0x") !== "0x"; console.log(`owner ${owner.address}`); console.log(`smart account ${sender}${deployed ? "" : " (deployed by this operation)"}`); // 2. Build the operation: deploy the account if needed, then a call that does nothing. const initCode: Hex = deployed ? "0x" : concat([FACTORY, encodeFunctionData({ abi: factoryAbi, functionName: "createAccount", args: [owner.address, 0n] })]); const nonce = await chain.readContract({ address: ENTRY_POINT, abi: entryPointAbi, functionName: "getNonce", args: [sender, 0n] }); const fees = await chain.estimateFeesPerGas(); const maxFee = fees.maxFeePerGas ?? (await chain.getGasPrice()); const tip = fees.maxPriorityFeePerGas ?? 1_000_000n; const op: Record = { sender, nonce: toHex(nonce), initCode, callData: encodeFunctionData({ abi: accountAbi, functionName: "execute", args: [owner.address, 0n, "0x"] }), callGasLimit: toHex(100_000n), verificationGasLimit: toHex(400_000n), preVerificationGas: toHex(80_000n), maxFeePerGas: toHex(maxFee * 2n), maxPriorityFeePerGas: toHex(tip), paymasterAndData: "0x", signature: PLACEHOLDER_SIGNATURE, }; // 3. Sponsor, then copy in what comes back. Change nothing after this. const sponsored = await tollbeam("pm_sponsorUserOperation", [op, ENTRY_POINT]); for (const f of ["paymasterAndData", "callGasLimit", "verificationGasLimit", "preVerificationGas", "maxFeePerGas", "maxPriorityFeePerGas"]) { op[f] = sponsored[f]; } console.log(`sponsored, quote ${sponsored.quoteId}`); // 4. Sign last: the account signs over paymasterAndData. const hash = await chain.readContract({ address: ENTRY_POINT, abi: entryPointAbi, functionName: "getUserOpHash", args: [{ sender: op.sender, nonce: BigInt(op.nonce), initCode: op.initCode, callData: op.callData, callGasLimit: BigInt(op.callGasLimit), verificationGasLimit: BigInt(op.verificationGasLimit), preVerificationGas: BigInt(op.preVerificationGas), maxFeePerGas: BigInt(op.maxFeePerGas), maxPriorityFeePerGas: BigInt(op.maxPriorityFeePerGas), paymasterAndData: op.paymasterAndData, signature: "0x", }], }); op.signature = await owner.signMessage({ message: { raw: hash } }); // 5. Send, passing back the quoteId so the operation is matched to its sponsorship. const sent = await tollbeam("eth_sendUserOperation", [op, ENTRY_POINT, sponsored.quoteId]); const userOpHash: string = typeof sent === "string" ? sent : sent.userOpHash; console.log(`sent ${userOpHash}`); // 6. Wait for the receipt; it is null until the operation is included. for (let i = 0; i < 40; i++) { const receipt = await tollbeam("eth_getUserOperationReceipt", [userOpHash]); if (receipt) { const tx = receipt.receipt?.transactionHash; const explorer = CHAIN === "base" ? "basescan.org" : "sepolia.basescan.org"; console.log(`landed: success=${receipt.success}, gas ${BigInt(receipt.actualGasCost)} wei`); console.log(`https://${explorer}/tx/${tx}`); return; } await new Promise((r) => setTimeout(r, 3000)); } throw new Error("No receipt after two minutes; check eth_getUserOperationReceipt again later."); } main().catch((err) => { console.error(err.message); process.exit(1); });