Paymasters (Sponsored Transactions)
One of the biggest UX enhancements unlocked by Smart Wallet is the ability for app developers to sponsor their users' transactions. If your app supports Smart Wallet, you can start sponsoring your users' transactions by using standardized paymaster service communication enabled by new wallet RPC methods.
The code below is also in our Wagmi Smart Wallet template.
Using Wagmi + Permissionless in a Next.js app
Choose a paymaster service provider
As a prerequisite, you'll need to obtain a paymaster service URL from a paymaster service provider. To be compatible with Smart Wallet, the paymaster provider you choose must be ERC-7677-compliant.
We recommend the Coinbase Developer Platform paymaster, currently offering up to $15k in gas credits as part of the Base Gasless Campaign. You can find a full list of ERC-7677-compliant paymaster services here.
Once you choose a paymaster service provider and obtain a paymaster service URL, you can proceed to integration.
(Recommended) Setup your paymaster proxy
Creating an API to proxy calls to your paymaster service is important for two reasons.
- Allows you to protect any API secret.
- Allows you to add extra validation on what requests you want to sponsor.
Validate UserOperation
Before we write our proxy, let's write a willSponsor
function to add some extra validation.
The policies on many paymaster services are quite simple and limited. As your API will be exposed on the web,
you want to make sure in cannot abused: called to sponsor transaction you do not want to fund. The checks below
are a bit tedious, but highly recommended to be safe. See "Trust and Validation" here
for more on this.
The code below is built specifically for Smart Wallet. It would need to be updated to support other smart accounts.
import { ENTRYPOINT_ADDRESS_V06, UserOperation } from "permissionless";
import {
Address,
BlockTag,
Hex,
decodeAbiParameters,
decodeFunctionData,
} from "viem";
import { baseSepolia } from "viem/chains";
import {client} from "./config"
import {
coinbaseSmartWalletABI,
coinbaseSmartWalletFactoryAddress,
coinbaseSmartWalletProxyBytecode,
coinbaseSmartWalletV1Implementation,
erc1967ProxyImplementationSlot,
magicSpendAddress
} from "./constants"
import { myNFTABI, myNFTAddress } from "./myNFT";
export async function willSponsor({
chainId,
entrypoint,
userOp,
}: { chainId: number; entrypoint: string; userOp: UserOperation<"v0.6"> }) {
// check chain id
if (chainId !== baseSepolia.id) return false;
// check entrypoint
// not strictly needed given below check on implementation address, but leaving as example
if (entrypoint.toLowerCase() !== ENTRYPOINT_ADDRESS_V06.toLowerCase())
return false;
try {
// check the userOp.sender is a proxy with the expected bytecode
const code = await client.getBytecode({ address: userOp.sender });
if (!code) {
// no code at address, check that the initCode is deploying a Coinbase Smart Wallet
// factory address is first 20 bytes of initCode after '0x'
const factoryAddress = userOp.initCode.slice(0, 42);
if (factoryAddress.toLowerCase() !== coinbaseSmartWalletFactoryAddress.toLowerCase())
return false;
} else {
// code at address, check that it is a proxy to the expected implementation
if (code != coinbaseSmartWalletProxyBytecode) return false;
// check that userOp.sender proxies to expected implementation
const implementation = await client.request<{
Parameters: [Address, Hex, BlockTag];
ReturnType: Hex;
}>({
method: "eth_getStorageAt",
params: [userOp.sender, erc1967ProxyImplementationSlot, "latest"],
});
const implementationAddress = decodeAbiParameters(
[{ type: "address" }],
implementation
)[0];
if (implementationAddress != coinbaseSmartWalletV1Implementation)
return false;
}
// check that userOp.callData is making a call we want to sponsor
const calldata = decodeFunctionData({
abi: coinbaseSmartWalletABI,
data: userOp.callData,
});
// keys.coinbase.com always uses executeBatch
if (calldata.functionName !== "executeBatch") return false;
if (!calldata.args || calldata.args.length == 0) return false;
const calls = calldata.args[0] as {
target: Address;
value: bigint;
data: Hex;
}[];
// modify if want to allow batch calls to your contract
if (calls.length > 2) return false;
let callToCheckIndex = 0;
if (calls.length > 1) {
// if there is more than one call, check if the first is a MagicSpend call
if (calls[0].target.toLowerCase() !== magicSpendAddress.toLowerCase())
return false;
callToCheckIndex = 1;
}
if (
calls[callToCheckIndex].target.toLowerCase() !==
myNFTAddress.toLowerCase()
)
return false;
const innerCalldata = decodeFunctionData({
abi: myNFTABI,
data: calls[callToCheckIndex].data,
});
if (innerCalldata.functionName !== "safeMint") return false;
return true;
} catch (e) {
console.error(`willSponsor check failed: ${e}`);
return false;
}
}
Create Proxy
The proxy you create will need to handle the pm_getPaymasterStubData
and pm_getPaymasterData
JSON-RPC requests specified by ERC-7677.
import { paymasterClient } from "./config";
import { willSponsor } from "./utils";
export async function POST(r: Request) {
const req = await r.json();
const method = req.method;
const [userOp, entrypoint, chainId] = req.params;
const sponsorable = await willSponsor({ chainId, entrypoint, userOp });
if (!sponsorable) {
return Response.json({ error: "Not a sponsorable operation" });
}
if (method === "pm_getPaymasterStubData") {
const result = await paymasterClient.getPaymasterStubData({
userOperation: userOp,
});
return Response.json({ result });
} else if (method === "pm_getPaymasterData") {
const result = await paymasterClient.getPaymasterData({
userOperation: userOp,
});
return Response.json({ result });
}
return Response.json({ error: "Method not found" });
}
Send EIP-5792 requests with a paymaster service capability
Once you have your paymaster service set up, you can now pass its URL along to Wagmi's useWriteContracts
hook.
If you set up a proxy in your app's backend as recommended in step (2) above, you'll want to pass in the proxy URL you created.
import { useAccount } from "wagmi";
import { useCapabilities, useWriteContracts } from "wagmi/experimental";
import { useMemo, useState } from "react";
import { CallStatus } from "./CallStatus";
import { myNFTABI, myNFTAddress } from "./myNFT";
export function App() {
const account = useAccount();
const [id, setId] = useState<string | undefined>(undefined);
const { writeContracts } = useWriteContracts({
mutation: { onSuccess: (id) => setId(id) },
});
const { data: availableCapabilities } = useCapabilities({
account: account.address,
});
const capabilities = useMemo(() => {
if (!availableCapabilities || !account.chainId) return {};
const capabilitiesForChain = availableCapabilities[account.chainId];
if (
capabilitiesForChain["paymasterService"] &&
capabilitiesForChain["paymasterService"].supported
) {
return {
paymasterService: {
url: `${document.location.origin}/api/paymaster`,
},
};
}
return {};
}, [availableCapabilities, account.chainId]);
return (
<div>
<h2>Transact With Paymaster</h2>
<p>{JSON.stringify(capabilities)}</p>
<div>
<button
onClick={() => {
writeContracts({
contracts: [
{
address: myNFTAddress,
abi: myNFTABI,
functionName: "safeMint",
args: [account.address],
},
],
capabilities,
});
}}
>
Mint
</button>
{id && <CallStatus id={id} />}
</div>
</div>
);
}
That's it! Smart Wallet will handle the rest. If your paymaster service is able to sponsor the transaction, in the UI Smart Wallet will indicate to your user that the transaction is sponsored.