TL;DR
To give an AI agent its own crypto wallet with spending limits, create one Openfort backend wallet per agent and attach an account-scoped signing policy to it. The policy caps the value of each transaction (ETH, ERC-20 amounts such as USDC, SOL, and SPL tokens), allowlists recipients, contracts, and chains, and rejects anything no rule matches. On EVM, pre-flight each send with policies.evaluate() and send only when it returns allowed. Policies limit single transactions, so track daily or monthly totals in your own system.
TLDR: Prompt an AI with this guide. Copy the prompt below into Claude, ChatGPT, or any LLM along with your Openfort credentials. It will scaffold the entire project for you.
_11Prompt: Using sk_test_XXXX (API secret key) and WALLET_SECRET_HERE (wallet secret)_11from Openfort, follow the guide in openfort-backend-wallet-usdc-guide.md to create_11a TypeScript project that:_11_111. Creates a backend wallet_112. Sets up a gas sponsorship that charges gas in USDC_113. Sends a USDC transfer on Base Sepolia with sendTransaction, which_11handles the EIP-7702 delegation automatically_114. Adds an account-scoped spending-limit policy and pre-flight check_11_11Create the project in TypeScript.Replace
sk_test_XXXXwith your API secret key andWALLET_SECRET_HEREwith your wallet secret from the Openfort Dashboard.
Agent wallets are server-side wallets that execute blockchain transactions autonomously. They power automated trading, scheduled payments, AI-driven commerce, and any workflow where a backend needs to sign and submit transactions without human intervention.
This guide walks through building one from scratch using Openfort backend wallets. By the end, you'll have a TypeScript project that creates a wallet, configures USDC gas sponsorship, sends a USDC transfer on Base Sepolia with gas paid in USDC (Openfort handles the EIP-7702 delegation on the first send), and caps what the agent can spend.
Prerequisites
You need two things from the Openfort Dashboard:
- API Secret Key (
sk_test_...): Found in your project settings - Wallet Secret: Generated when you enable backend wallets
You also need Node.js 18+ and a package manager (npm, pnpm, or yarn).
Project Setup
Initialize a TypeScript project and install the Openfort Node SDK:
_10mkdir agent-wallet && cd agent-wallet_10npm init -y_10npm install @openfort/openfort-node viem dotenv_10npm install -D typescript tsx @types/node_10npx tsc --init
Create a .env file with your credentials:
_10OPENFORT_SECRET_KEY=sk_test_XXXX_10OPENFORT_WALLET_SECRET=WALLET_SECRET_HERE_10CHAIN_ID=84532
Step 1: Create a Backend Wallet
Backend wallets are EOAs managed by Openfort's TEE infrastructure. Keys are generated and stored inside a secure enclave and never leave it.
_10import Openfort from "@openfort/openfort-node";_10import "dotenv/config";_10_10const openfort = new Openfort(process.env.OPENFORT_SECRET_KEY!, {_10 walletSecret: process.env.OPENFORT_WALLET_SECRET,_10});_10_10const account = await openfort.accounts.evm.backend.create();_10console.log("Account ID:", account.id);_10console.log("Address:", account.address);
This creates a new EOA with a private key secured in a TEE. The account.id is your Openfort identifier for this wallet, and account.address is the standard Ethereum address you'll use onchain.
You can also import an existing wallet if you have one:
_10const imported = await openfort.accounts.evm.backend.import({_10 privateKey: "0x...",_10});
Step 2: Pay gas in USDC
Agents hold USDC, so they should pay gas in USDC too. That way you never manage an ETH balance per agent. Openfort's paymaster pays the gas and charges the wallet in USDC at a live exchange rate. Two linked objects set this up: a policy that says which transactions qualify, and a gas sponsorship that says who pays and in which token.
| Sponsor schema | Who pays the gas |
|---|---|
pay_for_user | You, from your project balance |
charge_custom_tokens | The wallet, in an ERC-20 token at a live exchange rate |
fixed_rate | The wallet, a fixed ERC-20 amount per transaction |
For agent wallets, charge_custom_tokens is the right choice.
Register the USDC contract with Openfort:
_10const chainId = Number(process.env.CHAIN_ID); // 84532 for Base Sepolia_10const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; // USDC on Base Sepolia_10_10const usdcContract = await openfort.contracts.create({_10 name: "USDC on Base Sepolia",_10 chainId,_10 address: USDC,_10});
Create a policy that accepts sponsorship on this chain, then a gas sponsorship that charges USDC. Leaving out the token amount turns on automatic pricing:
_22const gasPolicy = await openfort.policies.create({_22 scope: "project",_22 description: "Sponsor agent transactions on Base Sepolia",_22 rules: [_22 {_22 action: "accept",_22 operation: "sponsorEvmTransaction",_22 criteria: [{ type: "evmNetwork", operator: "in", chainIds: [chainId] }],_22 },_22 ],_22});_22_22const sponsorship = await openfort.feeSponsorship.create({_22 name: "Agent gas in USDC",_22 strategy: {_22 sponsorSchema: "charge_custom_tokens",_22 tokenContracts: [{ contract: usdcContract.id }],_22 },_22 policyId: gasPolicy.id,_22});_22_22console.log("Gas sponsorship ID:", sponsorship.id); // pol_...
The sponsorship ID starts with pol_, and the policy ID with ply_. Transactions take the sponsorship ID, not the policy ID.
Step 3: Send a USDC transfer with gas paid in USDC
sendTransaction handles the full flow in one call. On the wallet's first transaction it upgrades the backend wallet to an EIP-7702 delegated account, so the address and its balances stay the same. It then creates, signs and submits the transaction through the paymaster. You don't send a separate delegation transaction.
Encode the USDC transfer with viem and send it with the gas sponsorship:
_14import { encodeFunctionData, erc20Abi } from "viem";_14_14const data = encodeFunctionData({_14 abi: erc20Abi,_14 functionName: "transfer",_14 args: ["0xRECIPIENT_ADDRESS", 1_000_000n], // 1 USDC (6 decimals)_14});_14_14const result = await openfort.accounts.evm.backend.sendTransaction({_14 account,_14 chainId,_14 interactions: [{ to: USDC, data }],_14 policy: sponsorship.id,_14});
sendTransaction resolves once the transaction intent exists, which isn't the same as the transaction landing onchain. Confirm a hash before you record the transfer:
_12async function waitForHash(id: string, tries = 20) {_12 for (let i = 0; i < tries; i++) {_12 const intent = await openfort.transactionIntents.get(id);_12 const hash = intent.response?.transactionHash;_12 if (hash) return hash;_12 await new Promise((resolve) => setTimeout(resolve, 1000));_12 }_12 throw new Error(`Transaction ${id} produced no hash`);_12}_12_12const hash = result.response?.transactionHash ?? (await waitForHash(result.id));_12console.log("Transaction hash:", hash);
The paymaster pays the gas and charges the wallet the equivalent in USDC. The agent wallet only needs USDC. One call can batch up to 9 interactions in a single transaction. See send gasless transactions for the details.
Step 4: Add spending limits
An agent wallet without limits signs whatever the agent asks for, and a prompt injection or a bug can drain it. Give each agent its own backend wallet and attach an account-scoped signing policy to it. Openfort evaluates the policy outside your agent's process and fails closed: once a policy exists, any operation no rule accepts is rejected.
| Limit | How to set it | Enforced when |
|---|---|---|
| Max ETH per transaction | ethValue criterion | EVM: in policies.evaluate() before the send |
| Max USDC or other ERC-20 per transaction | evmData with an args limit on transfer amount | EVM: in policies.evaluate() before the send |
| Max SOL or SPL tokens per transaction | solValue, splValue, mintAddress | Solana: at signing |
| Approved recipients and contracts | evmAddress, evmData args.to, solAddress, splAddress, programId | Same as above |
| Approved chains | evmNetwork, solNetwork | Same as above |
| Daily or monthly total | Your own database | Before your code calls the SDK |
This policy lets the agent send up to 100 USDC per transfer, only to approved recipients, on Base Sepolia. It uses the criteria from the Ethereum policy rules:
_32const erc20Abi = JSON.stringify([_32 {_32 type: "function",_32 name: "transfer",_32 inputs: [_32 { name: "to", type: "address" },_32 { name: "amount", type: "uint256" },_32 ],_32 outputs: [{ type: "bool" }],_32 },_32]);_32_32const spendingLimit = await openfort.policies.create({_32 scope: "account",_32 accountId: account.id,_32 description: "Agent: up to 100 USDC per transfer to approved recipients",_32 rules: [_32 {_32 action: "accept",_32 operation: "signEvmTransaction",_32 criteria: [_32 { type: "evmNetwork", operator: "in", chainIds: [84532] },_32 { type: "evmAddress", operator: "in", addresses: ["0x036CbD53842c5426634e7929541eC2318f3dCF7e"] },_32 { type: "evmData", operator: "<=", abi: erc20Abi, functionName: "transfer", args: { amount: "100000000" } },_32 { type: "evmData", operator: "in", abi: erc20Abi, functionName: "transfer", args: { to: ["{{RECIPIENT_ADDRESS}}"] } },_32 ],_32 },_32 { action: "reject", operation: "signEvmTransaction" },_32 // A backend send is signed as a user operation hash. Without this rule every send fails._32 { action: "accept", operation: "signEvmHash" },_32 ],_32});
On EVM chains, sendTransaction() reaches the policy engine only as the signEvmHash of its user operation, and the signEvmHash rule lets every send through. The transfer rules run when you pre-flight the exact call, so the agent's send path must check first:
_10// data is the encoded transfer(to, amount) call_10const check = await openfort.policies.evaluate({_10 operation: "signEvmTransaction",_10 accountId: account.id,_10 payload: { chainId: 84532, to: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", data },_10});_10if (!check.allowed) throw new Error(`Blocked by policy: ${check.reason}`);
On Solana, accounts.solana.backend.sendTransaction() and transfer() are evaluated as signSolTransaction, so solValue and splValue caps apply at signing with no separate pre-flight. The Solana policy rules include a combined SOL and USDC limit example.
Keep the spending policy and the gas sponsorship as two separate policies. Linking a signing policy to a gas sponsorship turns it into a sponsorship policy, and policies.evaluate() then allows everything. The agentic wallets guide covers both, plus one wallet per agent and webhooks on every transaction.
If the funds belong to a user rather than to the agent, keep them in the user's embedded wallet and have the user grant the agent a session key. The session key is limited to the contracts the user approves, an expiry, and an optional call count.
Putting It All Together
Here's the complete flow in a single script:
_66import Openfort from "@openfort/openfort-node";_66import { encodeFunctionData, erc20Abi } from "viem";_66import "dotenv/config";_66_66const openfort = new Openfort(process.env.OPENFORT_SECRET_KEY!, {_66 walletSecret: process.env.OPENFORT_WALLET_SECRET,_66});_66_66const chainId = Number(process.env.CHAIN_ID); // 84532_66const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; // USDC on Base Sepolia_66const RECIPIENT = process.argv[2] as `0x${string}` | undefined;_66_66async function main() {_66 // 1. Create a backend wallet_66 const account = await openfort.accounts.evm.backend.create();_66 console.log(`Wallet: ${account.address}`);_66_66 // 2. Charge gas in USDC_66 const usdcContract = await openfort.contracts.create({_66 name: "USDC on Base Sepolia",_66 chainId,_66 address: USDC,_66 });_66 const gasPolicy = await openfort.policies.create({_66 scope: "project",_66 description: "Sponsor agent transactions on Base Sepolia",_66 rules: [_66 {_66 action: "accept",_66 operation: "sponsorEvmTransaction",_66 criteria: [{ type: "evmNetwork", operator: "in", chainIds: [chainId] }],_66 },_66 ],_66 });_66 const sponsorship = await openfort.feeSponsorship.create({_66 name: "Agent gas in USDC",_66 strategy: {_66 sponsorSchema: "charge_custom_tokens",_66 tokenContracts: [{ contract: usdcContract.id }],_66 },_66 policyId: gasPolicy.id,_66 });_66_66 // 3. Fund the wallet with test USDC from https://faucet.circle.com/,_66 // then rerun with a recipient: npx tsx main.ts 0xRECIPIENT_ADDRESS_66 if (!RECIPIENT) {_66 console.log(`Fund ${account.address} with Base Sepolia USDC, then pass a recipient.`);_66 return;_66 }_66_66 // 4. Send 1 USDC with gas paid in USDC_66 const data = encodeFunctionData({_66 abi: erc20Abi,_66 functionName: "transfer",_66 args: [RECIPIENT, 1_000_000n],_66 });_66 const result = await openfort.accounts.evm.backend.sendTransaction({_66 account,_66 chainId,_66 interactions: [{ to: USDC, data }],_66 policy: sponsorship.id,_66 });_66 console.log("Transaction intent:", result.id);_66}_66_66main().catch(console.error);
The script creates a new wallet on every run. In a real agent, create the wallet, contract and sponsorship once, store their IDs, and reuse them. Then add the Step 4 spending policy and pre-flight check before each send.
Run it with:
_10npx tsx main.ts
What You Can Build With This
Agent wallets are the building block for autonomous onchain systems:
- AI-powered trading agents that execute strategies without manual approval
- Automated payment processing — payroll, subscriptions, disbursements
- DCA (Dollar-Cost Averaging) bots that buy tokens on a schedule
- Cross-border remittance systems that convert and send stablecoins
- Backend services that interact with smart contracts as part of your application logic
Combine this with wallet permissions to let users grant agents scoped access to their accounts, or with programmable wallet controls to enforce spending limits and contract allowlists at the infrastructure level.
Key References
| Resource | Link |
|---|---|
| Openfort Node SDK | github.com/openfort-xyz/openfort-node |
| Backend Wallets Docs | openfort.io/docs/products/server |
| Gas Sponsorship Docs | openfort.io/docs/configuration/gas-sponsorship |
| EIP-7702 Deep Dive | openfort.io/blog/eip-7702 |
| Recipes Hub | github.com/openfort-xyz/recipes-hub |
| USDC Faucet (Base Sepolia) | faucet.circle.com |
Agent wallets turn your backend into a first-class blockchain participant. TEE-secured keys, EIP-7702 smart account powers, and USDC gas sponsorship — everything an autonomous agent needs to transact onchain without managing ETH balances or exposing private keys.
Ready to build? Get your API keys from the Openfort Dashboard and start with the code above, or explore the recipes hub for more complete examples.









