Skip to main content

Paymaster

Use Erc7677Paymaster to sponsor gas or let users pay gas in an ERC-20 token. It implements the standard ERC-7677 protocol, so it works with Candide and any other compliant provider. AbstractionKit also has a Candide-specific client, CandidePaymaster, for two-phase paymaster signing and Candide's token APIs.

Methods at a Glance​

MethodSignatureReturns
constructornew Erc7677Paymaster(rpc: string | Transport, options?: { chainId?: bigint; provider?: "auto" | Erc7677Provider })Erc7677Paymaster
createPaymasterUserOperationcreatePaymasterUserOperation(smartAccount, userOperation, bundlerRpc, context?, overrides?)Promise<{ userOperation; tokenQuote? }>
decodeTokenQuote (static)Erc7677Paymaster.decodeTokenQuote(userOperation, nodeRpcUrl, overrides?)Promise<DecodedTokenQuote | null>
getPaymasterStubDatagetPaymasterStubData(userOperation, entrypoint, chainIdHex, context?)Promise<Erc7677StubDataResult>
getPaymasterDatagetPaymasterData(userOperation, entrypoint, chainIdHex, context?)Promise<Erc7677PaymasterFields>
  • Sponsor gas: pass { sponsorshipPolicyId } as context.
  • ERC-20 gas: pass { token } as context. Set overrides.approveAmount to cap the token allowance.
  • getPaymasterStubData and getPaymasterData are the raw ERC-7677 calls. createPaymasterUserOperation makes both for you.

Which Paymaster Client to Use​

Both clients are supported; neither is deprecated. Erc7677Paymaster implements the standard ERC-7677 protocol, so integrations stay portable across providers (Candide, Pimlico, Alchemy, or self-hosted) with no vendor lock-in. CandidePaymaster is the dedicated client for Candide-hosted paymasters and adds features the standard does not cover, such as parallel signing phases.

FlowRecommended clientMethod
Sponsored gas, one-shotErc7677PaymasterRecommended standard path: createPaymasterUserOperation(..., context?)
ERC-20 token gasErc7677PaymastercreatePaymasterUserOperation(..., { token })
Provider metadata and supported token details for Candide/PimlicoErc7677PaymasterHandled automatically from the paymaster URL
Candide-specific one-shot sponsorshipCandidePaymasterSupported via createSponsorPaymasterUserOperation(...)
Two-phase paymaster signing to reduce user waiting timeCandidePaymastercreateSponsorPaymasterUserOperation(..., { signingPhase })

Erc7677Paymaster​

Erc7677Paymaster is a provider-agnostic ERC-7677 paymaster client. It speaks pm_getPaymasterStubData and pm_getPaymasterData, so it works with any compliant provider (Candide, Pimlico, Alchemy, or a self-hosted paymaster). Provider is auto-detected from the RPC URL; for Candide and Pimlico it also fetches exchange rates and paymaster addresses automatically for ERC-20 token flows.

For new one-shot sponsorship and ERC-20 gas flows, prefer Erc7677Paymaster. For Candide and Pimlico URLs, it handles provider-specific metadata and token quote details behind the scenes. CandidePaymaster also supports one-shot sponsorship, but it is most useful when you need Candide-specific APIs or two-phase paymaster signing with signingPhase: "commit" and signingPhase: "finalize", which lets the user sign while the paymaster prepares its signature in parallel and reduces wallet or remote-signer latency.

Usage​

Import​

import { Erc7677Paymaster } from "abstractionkit";
example.ts
import { Erc7677Paymaster } from "abstractionkit";

const bundlerRpc = "https://api.candide.dev/public/v3/11155111";
const paymaster = new Erc7677Paymaster(bundlerRpc);

// Use createUserOperation() to help you construct a userOp
let userOperation = await smartAccount.createUserOperation(/* ... */);

const { userOperation: sponsoredOp } = await paymaster.createPaymasterUserOperation(
smartAccount,
userOperation,
bundlerRpc,
{ sponsorshipPolicyId: "sp_..." }, // provider-specific context
);
userOperation = sponsoredOp;

ERC-20 token sponsorship​

Passing { token } in the context triggers the ERC-20 gas flow automatically. For Candide and Pimlico the exchange rate is fetched for you; for unknown providers, supply exchangeRate in the context. tokenQuote surfaces the exchange rate, token cost, approval spender (paymaster), and approveAmount applied to the UserOperation so you can display the charge to the user without a second round trip. tokenCost leaves out the paymaster's post-operation overhead and markup, so for the most the user can be charged use decodeTokenQuote.

Pass paymasterAddress in the context to pin the paymaster you expect. If the detected provider quotes a different paymaster, the flow throws a PAYMASTER_ERROR before building any approval. The flow also throws a PAYMASTER_ERROR if the final pm_getPaymasterData response is missing a paymaster or names a different one than the approval spender.

example.ts
const bundlerRpc = "https://api.candide.dev/public/v3/11155111";
const tokenAddress = "0xFa5854FBf9964330d761961F46565AB7326e5a3b"; // Candide Test Token (CTT) on Sepolia, supported by the Candide paymaster

// Candide or Pimlico (auto-detected): exchange rate fetched from the RPC
const { userOperation: tokenOp, tokenQuote } = await paymaster.createPaymasterUserOperation(
smartAccount,
userOperation,
bundlerRpc,
{ token: tokenAddress },
);
userOperation = tokenOp;

// Unknown provider: supply exchangeRate, the token smallest-units per 1 ETH
// (USDC with 6 decimals at $3000/ETH: 3000 * 10^6)
const usdcAddress = "0x..."; // a token your paymaster provider supports
const { userOperation: tokenOp2 } = await paymaster.createPaymasterUserOperation(
smartAccount,
userOperation,
bundlerRpc,
{ token: usdcAddress, exchangeRate: "3000000000" },
);
userOperation = tokenOp2;

The prepended approve grants twice the quoted token cost by default. To choose the allowance, pass approveAmount (a bigint in the token's smallest unit) in the fifth argument, overrides. The flow throws a PAYMASTER_ERROR if it is below the quoted token cost. It is ignored when no approval is built, such as for sponsored operations.

example.ts
const { userOperation: cappedOp, tokenQuote: cappedQuote } = await paymaster.createPaymasterUserOperation(
smartAccount,
userOperation,
bundlerRpc,
{ token: tokenAddress },
{ approveAmount: 5_000_000n }, // at most 5 tokens with 6 decimals
);

Context​

The context object is forwarded to the paymaster RPC as the fourth argument of pm_getPaymasterStubData and pm_getPaymasterData, with any bigint values (including nested ones) converted to 0x-hex strings. Its shape is provider-specific, and providers ignore keys they don't recognize. Of the fields below, token, exchangeRate, and paymasterAddress are also read by Erc7677Paymaster to drive the ERC-20 gas flow.

keytypedescription
tokenstring?ERC-20 token address. Triggers the ERC-20 gas flow and prepends the token approval
sponsorshipPolicyIdstring?Sponsorship Policy ID if using a private gas policy (Candide)
exchangeRatebigint | string?Token smallest-units per 1 ETH (10^18 wei). Required for the token flow when no provider is auto-detected. Fetched automatically for Candide and Pimlico
paymasterAddressstring?The paymaster you expect the token approval to be granted to. If the detected provider quotes a different paymaster, the flow throws PAYMASTER_ERROR. When no provider is detected, it supplies the paymaster address
[key: string]unknownAny other provider-specific field. The whole context object, including the fields above, is forwarded to the paymaster RPC verbatim

decodeTokenQuote​

Reads the token payment a finished UserOperation commits to from the paymaster data the paymaster signed: the paymaster, token, exchange rate, validity window, and maxTokenCost, the most the user can be charged. In Candide's on-chain markup mode, the markup is read from the paymaster contract when decodeTokenQuote runs, so maxTokenCost reflects the markup at that moment. This is useful for co-signers who did not build the UserOperation and never saw its TokenQuote, so they can check the charge before signing.

decodeTokenQuote is a static method and needs no paymaster URL. It is available on both CandidePaymaster and Erc7677Paymaster, and works for any account, whichever client built the UserOperation. It supports Candide's token paymasters on EntryPoint v0.6 to v0.9 and Pimlico's on v0.6 to v0.8, identified by the paymaster address on the UserOperation.

  • Returns null when the UserOperation has no paymaster or is sponsored (no token payment).
  • Throws a PAYMASTER_ERROR if the paymaster is not a known deployment, and BAD_DATA if the paymaster data cannot be read.
  • Candide's paymaster data names the token by an on-chain slot, so the method makes one eth_call through nodeRpcUrl to read it. For Candide, nodeRpcUrl must be a node on the same chain as the UserOperation. For Pimlico, nodeRpcUrl is not used.

Usage​

example.ts
import { Erc7677Paymaster } from "abstractionkit";

const nodeRpcUrl = "https://ethereum-sepolia-rpc.publicnode.com";

// userOperation received from the account owner who built it
const quote = await Erc7677Paymaster.decodeTokenQuote(userOperation, nodeRpcUrl);

if (quote !== null) {
console.log(`Pays up to ${quote.maxTokenCost} of ${quote.token} to ${quote.paymaster}`);
}

Source code​

CandidePaymaster.decodeTokenQuote | Erc7677Paymaster.decodeTokenQuote | DecodedTokenQuote

Source code​

Erc7677Paymaster | createPaymasterUserOperation

Error Handling​

CandidePaymaster and Erc7677Paymaster follow one rule: the error code names who failed.

ErrorThrown when
AbstractionKitError with code: "PAYMASTER_ERROR"The paymaster failed or refused: a denied sponsorship policy, an unsupported EntryPoint or token, a malformed paymaster response, a final paymaster that differs from the approved one, or a paymaster rejection during gas estimation (EntryPoint AA3x or AA50, or bundler codes -32501 and -32508 when there is no AA code).
AbstractionKitError with code: "BUNDLER_ERROR"Gas estimation failed for a reason that is not the paymaster's, such as the account's own validation (AA23, AA24). It is the same error an account's createUserOperation throws.
RangeErrorThe UserOperation input is invalid, such as a negative gas override.

When the failure comes from an RPC call, the underlying error is on cause. Its JSON-RPC code is copied to errno, and an EntryPoint revert code to aaCode, so you can branch on the specific cause without parsing the message. An error the SDK raises itself, such as an unsupported or invalid token address, has no cause and no errno; CandidePaymaster's unsupported token error lists the accepted tokens on context.supportedTokens.

import { AbstractionKitError } from "abstractionkit";

try {
const { userOperation: sponsoredUserOperation } =
await paymaster.createPaymasterUserOperation(
smartAccount,
userOperation,
bundlerUrl,
{ sponsorshipPolicyId: "sp_..." },
);
} catch (error) {
if (error instanceof AbstractionKitError && error.code === "PAYMASTER_ERROR") {
// the paymaster refused: fall back to another way to pay for gas
console.log(error.message, error.errno, error.aaCode);
} else {
throw error;
}
}