14 min read

An Agent's Wallet Belongs in the Ledger, Not in Your Code

Line diagram of a user wallet funding an AI agent through a ledger panel that tracks a hold and a budget balance.
On this page

If you're adding an AI agent to a wallet or business-banking app, it will start paying suppliers and subscriptions out of your customers' balances. So you give it a spending limit: before each payment, your code adds up what the agent has spent this week and blocks anything that would go over.

But the number your check reads, the agent's spent total for the week, only counts payments that have finished, so a payment still in flight is left out. Your code adds the new payment to that incomplete total, compares the sum with the weekly limit, and answers yes or no on whether the agent can spend.

Only after a yes does the ledger write the debit. When the agent retries a timed-out call, or two runs overlap, that second check runs before the first debit is written, sees the same total, and gets a yes too.

Say Bola runs a catering company on your business wallet app and turns on your purchasing agent with a $500 weekly limit. By Friday it has spent $320 when a $180 order times out and the retry goes through as well.

$680 has left a $500 week, from the same balance she uses to pay her staff, and she never approved the extra $180, so either you refund it or she stops trusting the agent.

Give the agent a balance of its own

Closing the gap between a limit in your code and money in the ledger starts with who owns that money. An agent isn't an account holder, so it can't own a balance or answer for a bad payment. Everything it spends is Bola's money, and Bola is the one you owe an explanation to.

That's why every movement the agent makes has to be recorded on a balance under her identity, so you can reverse a payment or look up the record later. It's the same reason a ledger has to stay accurate when AI agents move money.

So the agent's wallet is a second balance under Bola's identity. She funds it, and it's the only balance the agent can spend from.

Once the limit is money in a balance, your code no longer compares a spent total to a weekly cap. The ledger accepts the payment if the budget has enough available, and refuses it if it doesn't. Here are the four pieces:

  • Main balance. This is Bola's own money. Your app moves it only when she acts, and the agent never touches it.
  • Budget balance. Bola funds it with a transfer from her main balance, so whatever is available in it is what the agent can still spend.
  • Hold. When a purchase is waiting on approval or on the supplier's final amount, its money is set aside inside the budget, where the agent can't spend it again and the supplier hasn't been paid yet.
  • Supplier side. Once a payment goes through, the money waits here until your payout rail sends it to the supplier.

The design rests on a few rules, and each of them works on a regular database like Postgres:

  • The budget refuses any payment bigger than what's available in it, which is the balance minus whatever is on hold. The check and the write happen in the same database transaction, under a row lock on the balance, so two agent runs can't both pass.
  • Every movement carries a reference built from the order, with a unique index on it, so a second payment for the same order is refused.
  • A weekly limit is a funding transfer at the start of the week. Unspent money rolls over unless you sweep what's left back to main at the end of the week with the same kind of transfer.
  • Retiring the agent means sweeping the budget back to main and revoking the agent's credential, while the balance and its full history stay, so you can still answer questions about it later.

Setting up the budget

We'll use Blnk Core, our open-source ledger, to set the budget up, but the same approach works if you build the ledger yourself.

Bola gets one identity, and both of her balances point to it, so a balances filter on her identity_id returns her main balance and the agent's budget together. The balances live in a ledger for customer wallets, and the budget's metadata marks it as the purchasing agent's budget:

Request
import { BlnkInit } from "@blnkfinance/blnk-typescript";

const blnk = await BlnkInit(process.env.BLNK_ADMIN_KEY!, { baseUrl: process.env.BLNK_URL! });

const ledger = await blnk.Ledgers.create({ name: "Customer Wallets" });

const bola = await blnk.Identity.create({
  identity_type: "organization",
  organization_name: "Bola's Kitchen",
  email_address: "[email protected]",
});

const main = await blnk.LedgerBalances.create({
  ledger_id: ledger.data.ledger_id,
  identity_id: bola.data.identity_id,
  currency: "USD",
  meta_data: { purpose: "main" },
});

const budget = await blnk.LedgerBalances.create({
  ledger_id: ledger.data.ledger_id,
  identity_id: bola.data.identity_id,
  currency: "USD",
  meta_data: { purpose: "agent_budget", agent: "purchasing" },
});
201 Created
{
  "balance_id": "bln_7d2f4a10-3c8e-4b5a-9e61-2f0c8d4b7a93",
  "ledger_id": "ldg_1a6e9c42-5b7d-4f08-a3c1-8e2d6f9b0c57",
  "identity_id": "idt_4c9b2e71-8a3f-4d6e-b015-7f2a9c3e6d48",
  "currency": "USD",
  "balance": 0,
  "inflight_balance": 0,
  "credit_balance": 0,
  "debit_balance": 0,
  "inflight_debit_balance": 0,
  "inflight_credit_balance": 0,
  "meta_data": {
    "purpose": "agent_budget",
    "agent": "purchasing"
  }
}

Funding the budget is an ordinary transaction from Bola's main balance. Your scheduler runs it at the start of each week, and the reference includes the week, so a scheduler that fires twice still funds once:

fundBudget.ts
async function fundBudget(mainId: string, budgetId: string, week: string) {
  return blnk.Transactions.create({
    precise_amount: 50000, // $500.00
    precision: 100,
    currency: "USD",
    source: mainId,
    destination: budgetId,
    reference: `budget_${budgetId}_${week}`,
    description: "Weekly purchasing agent budget",
    allow_overdraft: false,
  });
}

If Bola's main balance can't cover the $500, the funding fails and the agent has less to work with than you planned. That's the right outcome: you can't fund the budget with money that isn't in her main balance.

When the agent asks for more than it has

Funding the budget sets how much the agent can spend. What's left is what happens when it asks for more, and that depends on whether the limit lives in your code or in the budget.

When your app keeps the agent's spent total in an agent_settings row and checks it before debiting the wallet, the limit check is an if statement. It's correct only when nothing else runs between reading the counter and writing the debit, and an agent retry or a parallel tool call can land in that gap.

A row lock, or an UPDATE ... WHERE spent + $1 <= limit on the counter, makes that increment atomic, but the counter and the wallet debit are still two writes. The debit can fail after the counter has already moved, or another code path can debit the wallet without going through the same UPDATE and bypass the limit.

What you want is for the budget balance itself to refuse the debit. If the budget can't cover a purchase, nothing moves, and there's no second limit to keep in sync.

In Blnk, a transaction from a balance that can't cover it is rejected unless you set allow_overdraft to true, which you never do for the budget.

Before the agent commits to a purchase, its tool can ask the ledger first with a dry run, which is the same request with dry_run: true. Nothing is written and the reference isn't used, so the real post can reuse it.

The destination, @SupplierPayouts, is an internal balance for money owed to suppliers, and Blnk creates it the first time a real transaction uses it.

Request
async function previewSpend(budgetId: string, orderId: string, amountCents: number) {
  const preview = await blnk.Transactions.create({
    dry_run: true,
    precise_amount: amountCents,
    precision: 100,
    currency: "USD",
    source: budgetId,
    destination: "@SupplierPayouts",
    reference: `order_${orderId}`,
    description: `Agent purchase ${orderId}`,
    allow_overdraft: false,
  });
  return preview.data;
}
200 OK
{
  "dry_run": true,
  "would_apply": false,
  "rejection": {
    "code": "TXN_INSUFFICIENT_FUNDS",
    "reason": "insufficient_funds",
    "message": "insufficient funds in source balance"
  },
  "reference": "order_ord_8812",
  "currency": "USD",
  "amount": 180,
  "precise_amount": "18000",
  "precision": 100,
  "balances": [
    {
      "balance_id": "bln_7d2f4a10-3c8e-4b5a-9e61-2f0c8d4b7a93",
      "role": "source",
      "currency": "USD",
      "current_balance": "12000",
      "resulting_balance": "12000"
    },
    {
      "balance_id": "bln_9a4c7e21-6d3b-4f80-b2e5-1c8f0a6d3e79",
      "role": "destination",
      "currency": "USD",
      "current_balance": "264000",
      "resulting_balance": "264000"
    }
  ]
}

The response is a 200 even when the purchase wouldn't go through, so the tool reads would_apply, not the status code. When it's false and rejection.code is TXN_INSUFFICIENT_FUNDS, the agent can tell Bola it's out of budget for the week instead of trying a different supplier.

A dry run is a snapshot of balances as they stand now, so it isn't the real check. If the agent posts anyway, or a second run spends the money first, the ledger still refuses.

On the default queue the API first returns the transaction as QUEUED, then the worker records a separate REJECTED transaction with the reason in meta_data.blnk_rejection_reason and sends a transaction.rejected webhook.

That attempt sits in the ledger next to everything the agent did spend, which helps the first time someone asks what the agent tried to do.

Holding money while someone approves

The budget refuses a purchase it can't cover, but some purchases it can cover still shouldn't settle the moment the agent places the order. Bola might want to approve anything over $150, or the supplier only confirms the final amount once they've packed the order.

When the limit is a spent counter and a wallet debit, there's nowhere to put that money in between. It's either still in the wallet, where the agent can spend it again, or the wallet has already been debited.

A hold covers the gap. The money leaves what the agent can spend but doesn't reach the supplier until it's approved or the supplier confirms the final amount. In Blnk that's an inflight transaction, and it moves through three steps:

  1. The agent holds the amount

    The agent's tool posts the purchase from the budget with inflight: true and an inflight_expiry_date. The amount moves to the budget's inflight debit, so it's out of what the agent can spend.

  2. Someone approves or verifies

    Bola approves in your app, or your supplier integration confirms the final amount. This part is your code, outside the ledger, in a service the agent can't call.

  3. The hold is committed or voided

    Once approved, the hold is committed, in full or for the smaller final amount. If it's declined, it's voided and the money is available in the budget again. If it's still INFLIGHT at the expiry date, Blnk voids it for you.

holdAndSettle.ts
// Agent tool: reserve the money, never settle it.
async function holdPurchase(budgetId: string, orderId: string, amountCents: number) {
  const expiresAt = new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString();
  return blnk.Transactions.create({
    precise_amount: amountCents,
    precision: 100,
    currency: "USD",
    source: budgetId,
    destination: "@SupplierPayouts",
    reference: `order_${orderId}`,
    description: `Agent purchase ${orderId}`,
    inflight: true,
    inflight_expiry_date: expiresAt,
    skip_queue: true,
    meta_data: { order_id: orderId, requested_by: "purchasing_agent" },
  });
}

// Approval service: settle what the supplier actually confirmed.
async function settlePurchase(holdId: string, orderId: string, finalCents: number | null) {
  if (finalCents === null) {
    return blnk.Transactions.updateStatus(holdId, {
      status: "void",
      reference: `void_${orderId}`,
      skip_queue: true,
    });
  }
  return blnk.Transactions.updateStatus(holdId, {
    status: "commit",
    precise_amount: finalCents,
    reference: `commit_${orderId}`,
    skip_queue: true,
  });
}

Say the agent holds $180 and the supplier confirms $164 because one item was out of stock. The approval service commits $164. The other $16 stays on hold until you void it, at which point it's back in the budget for next time.

The skip_queue flag on each call applies the hold or settlement in the same request, so the agent gets an INFLIGHT transaction back immediately instead of a queued one.

If you've held each seller's share separately in a marketplace, this is the same idea, with the agent's purchase in place of the seller's share.

Retries that pay once

A budget refuses what it can't cover, and a hold reserves what's waiting on approval, but neither can tell that two requests are the same order.

Back to Friday. The supplier's API timed out, so the agent didn't know whether the order went through, and it tried again. Here's the tool it was calling both times.

payVendor.ts
async function payVendor(userId: string, orderId: string, amountCents: number) {
  const { rows } = await db.query(
    "SELECT weekly_limit_cents, spent_this_week_cents FROM agent_settings WHERE user_id = $1",
    [userId],
  );
  if (rows[0].spent_this_week_cents + amountCents > rows[0].weekly_limit_cents) {
    throw new Error("over agent limit");
  }
  await db.query(
    "UPDATE wallets SET balance_cents = balance_cents - $1 WHERE user_id = $2",
    [amountCents, userId],
  );
  await db.query(
    "UPDATE agent_settings SET spent_this_week_cents = spent_this_week_cents + $1 WHERE user_id = $2",
    [amountCents, userId],
  );
  await suppliers.pay(orderId, amountCents);
}

Retrying is the right call for an agent. The problem in payVendor.ts is that each attempt debits the wallet and increments the spent counter again, and neither write uses the order id.

The reference is what makes a retry safe to repeat. Built from the order, order_${orderId}, the first post records the hold, and a second post with the same reference is refused with 409 TXN_DUPLICATE_REFERENCE, so the retry can't take another $180 out of the budget.

The commit and void calls above carry their own references for the same reason: if the approval service crashes after committing and runs again with the same reference and amount, Blnk returns the original commit instead of applying a second one, so the hold isn't settled twice.

The one case Blnk refuses is the same reference with a different amount or action, which returns 409 TXN_DUPLICATE_REFERENCE.

Two things have to be true for a retry to hit the same reference. It comes from something stable in your system, like your order id, rather than a timestamp the agent generates on each attempt, which would give every retry a new reference. And it exists before the first call, so every retry sends the same value.

Knowing which agent moved the money

The budget refuses overspending and repeated references, but when every call comes in on the same master key, it can't say which agent posted. When Bola asks why $164 left her budget on Friday, you want the answer in the ledger, not in a log you have to search.

That's what a scoped API key per agent gives you, in place of a shared master key. Your tool layer holds the key and sends it with every call the agent makes:

Request
const agentKey = await blnk.ApiKeys.create({
  name: "Purchasing agent: Bola's Kitchen",
  owner: "agent-purchasing",
  scopes: ["transactions:write", "balances:read"],
  expires_at: "2027-06-30T00:00:00Z",
});
201 Created
{
  "api_key_id": "api_key_3e8a1d52-7c4b-4f19-a6d0-9b2e5f7c1a84",
  "key": "q7Vn2LwX9sPkR4tYc8ZbHf1mJ6dGe3uA0oNiT5yWxQs=",
  "name": "Purchasing agent: Bola's Kitchen",
  "owner_id": "agent-purchasing",
  "scopes": [
    "transactions:write",
    "balances:read"
  ],
  "expires_at": "2027-06-30T00:00:00Z",
  "created_at": "2026-12-03T10:30:00Z",
  "last_used_at": "0001-01-01T00:00:00Z",
  "is_revoked": false
}

Blnk shows the key only once, so it goes straight into your secrets manager. From then on, every transaction the agent creates with that key carries the key's id in meta_data.BLNK_GENERATED_BY. Blnk adds it on POST requests, so the agent can't leave it out.

Filter transactions on meta_data.BLNK_GENERATED_BY and you have every movement that agent created, including every hold it opened.

It's worth being clear about what the key does and doesn't limit. Scopes are resource:action pairs. transactions:write lets a key create transactions from any balance, and it also covers commit and void, since those are writes on the same resource.

A key can't be limited to one balance or one amount. Those two limits come from elsewhere:

  • Your tool layer sets which balance the agent spends from. The agent asks for a purchase, and your code fills in source with Bola's budget balance id. The agent never sees the key, the main balance id, or the approval service.
  • The budget sets the amount. With overdrafts off, even a buggy tool can't spend more than the budget has available.

When Bola turns the agent off, your app sweeps what's left in the budget back to her main balance and revokes the key with DELETE /api-keys/{id}?owner=agent-purchasing. Anything still holding the old key gets 401 AUTH_EXPIRED_API_KEY on its next request.

Watching the budget

So far the ledger reacts when a payment arrives: it refuses an overspend, rejects a repeated reference, or records which agent sent it. None of that warns you that the budget is running low, and you want to hear about that before Bola does.

A balance monitor watches one amount on a balance and sends a balance.monitor webhook to your global webhook URL when it crosses a line you set:

watchBudget.ts
await blnk.BalanceMonitor.create({
  balance_id: budgetId,
  condition: {
    field: "balance",
    operator: "<",
    value: 100,
    precision: 100,
  },
  trigger: "edge",
  description: "Purchasing agent budget below $100",
});

With trigger: "edge", you get one webhook when the budget's balance drops below $100, and another only if it goes back above and drops again.

balance counts settled money only, so a hold doesn't move it until the hold is committed. A second monitor on inflight_debit_balance fires when the amount sitting in holds crosses a threshold you set.

Monitors and transaction hooks notify you, but they don't refuse the payment. A PRE_TRANSACTION hook that returns a non-2xx only retries the delivery; it doesn't veto the transaction.

The cap is the budget's available balance and the approval gate is the hold, so the webhooks are for the human side: messaging Bola, pausing the agent in your app, or opening a ticket.

What changes for your agent

With the budget in place, Bola can hand an agent a limit the ledger enforces. The agent can preview, hold, and retry without paying twice. Every purchase and hold the agent opens carries its key id in meta_data.BLNK_GENERATED_BY, and you can retire the agent by sweeping the budget back to main and revoking the key, without losing its history.

You'll probably keep the agent_settings row, since your app still needs to show Bola her weekly limit. But the number that stops the agent is now the budget's available balance, and the ledger refuses any debit larger than that.

You can run this on Blnk Core, or create a Blnk Cloud workspace to try it against a hosted ledger.

Related posts