Skip to content

· Updated

How to Build an Agent Wallet

Joan Alavedra, Co-Founder at Openfort•10 min read
Build an agent wallet with Openfort backend wallets and EIP-7702 delegation

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.


_11
Prompt: Using sk_test_XXXX (API secret key) and WALLET_SECRET_HERE (wallet secret)
_11
from Openfort, follow the guide in openfort-backend-wallet-usdc-guide.md to create
_11
a TypeScript project that:
_11
_11
1. Creates a backend wallet
_11
2. Sets up a gas sponsorship that charges gas in USDC
_11
3. Sends a USDC transfer on Base Sepolia with sendTransaction, which
_11
handles the EIP-7702 delegation automatically
_11
4. Adds an account-scoped spending-limit policy and pre-flight check
_11
_11
Create the project in TypeScript.

Replace sk_test_XXXX with your API secret key and WALLET_SECRET_HERE with 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:


_10
mkdir agent-wallet && cd agent-wallet
_10
npm init -y
_10
npm install @openfort/openfort-node viem dotenv
_10
npm install -D typescript tsx @types/node
_10
npx tsc --init

Create a .env file with your credentials:


_10
OPENFORT_SECRET_KEY=sk_test_XXXX
_10
OPENFORT_WALLET_SECRET=WALLET_SECRET_HERE
_10
CHAIN_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.


_10
import Openfort from "@openfort/openfort-node";
_10
import "dotenv/config";
_10
_10
const openfort = new Openfort(process.env.OPENFORT_SECRET_KEY!, {
_10
walletSecret: process.env.OPENFORT_WALLET_SECRET,
_10
});
_10
_10
const account = await openfort.accounts.evm.backend.create();
_10
console.log("Account ID:", account.id);
_10
console.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:


_10
const 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 schemaWho pays the gas
pay_for_userYou, from your project balance
charge_custom_tokensThe wallet, in an ERC-20 token at a live exchange rate
fixed_rateThe wallet, a fixed ERC-20 amount per transaction

For agent wallets, charge_custom_tokens is the right choice.

Register the USDC contract with Openfort:


_10
const chainId = Number(process.env.CHAIN_ID); // 84532 for Base Sepolia
_10
const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; // USDC on Base Sepolia
_10
_10
const 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:


_22
const 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
_22
const 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
_22
console.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:


_14
import { encodeFunctionData, erc20Abi } from "viem";
_14
_14
const data = encodeFunctionData({
_14
abi: erc20Abi,
_14
functionName: "transfer",
_14
args: ["0xRECIPIENT_ADDRESS", 1_000_000n], // 1 USDC (6 decimals)
_14
});
_14
_14
const 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:


_12
async 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
_12
const hash = result.response?.transactionHash ?? (await waitForHash(result.id));
_12
console.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.

LimitHow to set itEnforced when
Max ETH per transactionethValue criterionEVM: in policies.evaluate() before the send
Max USDC or other ERC-20 per transactionevmData with an args limit on transfer amountEVM: in policies.evaluate() before the send
Max SOL or SPL tokens per transactionsolValue, splValue, mintAddressSolana: at signing
Approved recipients and contractsevmAddress, evmData args.to, solAddress, splAddress, programIdSame as above
Approved chainsevmNetwork, solNetworkSame as above
Daily or monthly totalYour own databaseBefore 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:


_32
const 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
_32
const 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
_10
const check = await openfort.policies.evaluate({
_10
operation: "signEvmTransaction",
_10
accountId: account.id,
_10
payload: { chainId: 84532, to: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", data },
_10
});
_10
if (!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:


_66
import Openfort from "@openfort/openfort-node";
_66
import { encodeFunctionData, erc20Abi } from "viem";
_66
import "dotenv/config";
_66
_66
const openfort = new Openfort(process.env.OPENFORT_SECRET_KEY!, {
_66
walletSecret: process.env.OPENFORT_WALLET_SECRET,
_66
});
_66
_66
const chainId = Number(process.env.CHAIN_ID); // 84532
_66
const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; // USDC on Base Sepolia
_66
const RECIPIENT = process.argv[2] as `0x${string}` | undefined;
_66
_66
async 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
_66
main().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:


_10
npx 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


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.

Share this article

Related Articles

  1. How to create a USDC wallet

    In this tutorial, you'll learn how to integrate Openfort smart wallets into a mobile app to provide a usdc compatible wallet for your users.

  2. How to Build a Telegram Bot with Built-In Crypto Wallets

    Build a Telegram bot where /start creates a wallet and /send moves USDC gas-free, using Openfort backend wallets, plus the Mini App path for React.

  3. How to build a Stablecoin Wallet: A step-by-step guide

    In this guide, we'll show you how to create a simple stablecoin wallet using Openfort's embedded wallet technology.

  4. Meet the Openfort CLI

    Manage wallets, gas sponsorship, policies, and transaction flows from your terminal across EVM and Solana.

  5. Send and deposit assets with Openfort UI

    This update turns the Openfort wallet widget from a passive viewer into an actionable money console—without you rebuilding flows from scratch.

  6. Openfort MCP Server: Use Openfort from Claude Code and Cursor

    Use Openfort from Claude Code or Cursor: the docs MCP server, the CLI MCP server for wallets and policies, agent skills, and llms.txt for AI coding agents.

  7. How to Set Up Gasless Transactions

    Set up gasless transactions on Ethereum and Solana with Openfort's paymaster: code examples, policy configuration, and gas sponsorship for users and agents.

  8. How to Build Wallet Permissions with Session Keys

    Build wallet permissions using session keys on smart accounts. Learn to grant agents time-limited, revocable spending power without transferring custody.

Ship your first wallet in minutes

No credit card required • 2,000 operations free