Node.js Only: This function uses CDP (Coinbase Developer Platform) server wallets and is only available in Node.js environments. For browser/client-side applications, use
prepareCharge instead.The
charge function executes subscription charges automatically from your backend. It uses a CDP smart wallet as the subscription owner, handling all transaction details including wallet management, transaction signing, and optional gas sponsorship. No manual transaction management required.How It Works
When you callcharge(), the function:
- Initializes a CDP client with your credentials
- Retrieves the existing smart wallet (subscription owner)
- Prepares the charge transaction calls
- Executes the charge using the smart wallet
- Optionally uses a paymaster for gas sponsorship
- Returns the transaction hash
Parameters
The subscription ID (permission hash) returned from
subscribe().Pattern: ^0x[0-9a-fA-F]{64}$Amount to charge as a string (e.g., “10.50”) or
'max-remaining-charge' to charge the full remaining amount in the current period.Whether to use Base Sepolia testnet. Must match the network used in
subscribe(). Default: falseCDP API key ID. Falls back to
CDP_API_KEY_ID environment variable.CDP API key secret. Falls back to
CDP_API_KEY_SECRET environment variable.CDP wallet secret. Falls back to
CDP_WALLET_SECRET environment variable.Optional custom wallet name for the CDP smart wallet. Default: “subscription owner”
Use Default: Most applications should omit this parameter and use the default. Only specify if you used a custom name in
getOrCreateSubscriptionOwnerWallet().Paymaster URL for transaction sponsorship (gasless transactions). Falls back to
PAYMASTER_URL environment variable.Optional recipient address to receive the charged USDC. If not provided, USDC stays in the subscription owner wallet.Pattern:
^0x[0-9a-fA-F]{40}$Returns
Charge execution result.
Setup
Before usingcharge(), you need CDP credentials. Get them from the CDP Portal.
Set as environment variables:
Error Handling
Always wrapcharge() calls in try-catch blocks:
Common Errors
Missing CDP Credentials
Missing CDP Credentials
CDP_API_KEY_ID, CDP_API_KEY_SECRET, and CDP_WALLET_SECRET are set as environment variables or passed as parameters.Subscription Not Found
Subscription Not Found
getSubscriptionStatus to verify.No Remaining Charge
No Remaining Charge
Wallet Does Not Exist
Wallet Does Not Exist
getOrCreateSubscriptionOwnerWallet to set up the wallet.Usage Pattern
Typical implementation in a backend service:Scheduled Charging Service