Crypto & Blockchain · Topic 8

Programmable money: tokenized deposits & stablecoins

Programmable money is money that carries its own rules. Instead of a person or a back-office batch job deciding when a payment happens, code on a shared ledger releases, holds, splits, or returns funds automatically when agreed conditions are met. This page explains the idea from first principles, compares the two variants banks actually use (tokenized deposits and stablecoins), shows how to build them, and walks through tested smart contracts for real use cases.

2 variants compared 7 tested smart contracts 10 use cases ≈ 60–75 min read

1. What is programmable money?

Today, money in a bank account is a number in a database that only the bank can change. To make a payment "smart" (pay when goods arrive, sweep excess cash at 5 p.m., release salary every second), you need extra systems around the money: escrow agents, letters of credit, batch jobs, reconciliations, and people checking documents.

Programmable money moves that logic next to the money. Money becomes a digital token on a shared ledger, and smart contracts (small programs on that same ledger) can hold and move tokens according to rules that every party can read and nobody can quietly change.

One-sentence definitionProgrammable money = trusted digital money (a token that is a claim on a bank or a regulated issuer) + a shared ledger (one source of truth) + code that controls when and where it moves.

The four building blocks

💵 Money token

A digital representation of a currency claim: a tokenized deposit (a bank liability) or a stablecoin (a liability of a regulated issuer backed by reserves).

📒 Shared ledger

A blockchain or other distributed ledger where balances and contract state live. Every participant sees the same state, so there is nothing to reconcile.

⚙️ Smart contract

Code deployed on the ledger. It can own tokens and moves them only when its rules say so: escrow, delivery-versus-payment, sweeps, streams.

🔌 Oracles & identity

Oracles bring real-world facts on-chain (shipment delivered, price, weather). Identity and KYC layers decide who may hold or receive the money.

Programmable money vs programmable payments

These terms get mixed up. The distinction matters to central banks and regulators:

Programmable paymentsProgrammable money
Where the logic livesOutside the money, in a contract or service that decides when to move otherwise ordinary tokensInside the token itself (e.g. a coin that can only be spent at pharmacies, or that expires)
Is the money still "money"?Yes. Once paid out, the token is fully fungibleRestricted. One dollar is no longer equal to another dollar
Regulator viewGenerally favoured; preserves the singleness of moneyUsed carefully, only for specific purposes
Example on this pageTradeEscrow, DvPSettlement, TreasurySweepPurposeBoundGrant (purpose-bound money: the restriction sits in a wrapper, not in the base token)
💡 Design rule of thumbKeep the base money token simple and fungible. Put business rules in separate contracts that hold the token. That way one dollar is always one dollar, and rules can change without re-issuing money. Every contract on this page follows this pattern.

What it lets you do that today's rails can't

2. Two variants: tokenized deposits vs stablecoins

Both put dollars (or euros, pounds, rupees…) on a programmable ledger. They differ in who owes you the money, where it can travel, and how it's regulated.

🏦 Variant 1 · Tokenized deposits

A normal bank deposit, recorded as a token. It's still the bank's liability, still on its balance sheet, and still (usually) covered by deposit insurance. Typically lives on a permissioned ledger where only KYC'd customers can hold it.

e.g. J.P. Morgan Kinexys · Citi Token Services · HSBC Tokenised Deposit Service

🪙 Variant 2 · Stablecoins

A token issued by a regulated issuer and backed 1:1 by reserves (cash, short-term government bills). It's a claim on the issuer, not on a bank. It usually lives on public blockchains, so anyone with a wallet can hold it.

e.g. USDC · USDT · PYUSD · EURC · SG-Forge EURCV

DimensionTokenized depositStablecoin (fiat-backed)
Legal claimOn the bank (a deposit)On the issuer, backed by segregated reserves
Balance sheetStays on the bank's balance sheet; the bank can keep lending against it (fractional reserve)Reserves are held 100% outside the lending book (cash / T-bills)
Deposit insuranceUsually yes, as for any deposit (check your jurisdiction)No; protection comes from reserve rules and redemption rights
InterestCan pay interest like any depositRegulated payment stablecoins generally can't pay interest to holders (e.g. US GENIUS Act)
Typical ledgerPermissioned DLT run by a bank or consortium (increasingly also public L2s)Public chains (Ethereum and its L2s, Solana, etc.)
Who can hold itOnly onboarded (KYC'd) clients of participating banksAnyone with a wallet, unless the address is blocklisted
Cross-bank paymentsNeed an interbank settlement step (central bank money or a shared ledger)The same token moves anywhere; no interbank step
Main regulationBanking law, capital and liquidity rulesStablecoin regimes: EU MiCA, US GENIUS Act, HK, Singapore MAS, etc.
Best atWholesale and corporate banking, treasury, securities settlement, intraday liquidityGlobal reach, crypto/DeFi markets, cross-border retail and SME payments, machine payments
Main riskFragmentation (each bank's token is a separate island) and bank credit riskRun/de-peg risk if reserves are doubted; AML on open networks
🎯 The key insightBoth variants can run exactly the same smart contracts (escrow, DvP, sweeps), because both look like a standard ERC-20 token to the contract. What changes is who is allowed to participate and how money moves between institutions. Section 9 shows each use case built both ways.

3. How it works: the core loop

Every programmable-money use case is a variation of one loop: lock → check condition → release (or refund). Watch a $50,000 trade payment:

Buyer's wallet $50,000 in tokens Smart contract IF goods delivered AND before deadline THEN pay seller · ELSE refund Seller's wallet paid automatically Oracle: "shipment delivered" ① lock ③ release ② condition met $
Funds are locked in the contract, so the seller knows the money exists and the buyer knows it can't be released early. A data feed (oracle) proves delivery, and the contract pays without anyone pressing a button.
  1. TokenizeFiat becomes a token: a bank mints deposit tokens against an account debit, or an issuer mints stablecoins against reserves.
  2. Lock (commit)The payer moves tokens into a smart contract. Now the funds are provably there but can't be spent by anyone outside the rules.
  3. ObserveThe contract gets facts: signatures from parties, an oracle's data, time passing, or another token arriving (DvP).
  4. ExecuteWhen the rule is satisfied, the contract moves tokens. Settlement and payment are the same event.
  5. Fall backEvery rule needs an exit: deadline → refund, dispute → arbiter, incident → pause. Contracts without an exit trap money.
  6. De-tokenizeThe recipient keeps the tokens for the next payment, or redeems them into a normal bank balance.

4. Variant 1: tokenized deposits

A tokenized deposit is the same deposit you already have, in a new format. When a client tokenizes $100, the bank debits the client's normal account and credits a special omnibus account. It then mints 100.00 tokens to the client's wallet on the ledger. Legally nothing changes: the bank still owes the client $100.

SHARED PERMISSIONED LEDGER Alice's wallet aUSD = Bank A deposit Bob's wallet bUSD = Bank B deposit Bank A core banking Alice −$100 · omnibus +$100 Bank B core banking omnibus −$100 · Bob +$100 Central bank reserves / wholesale CBDC ③ Bank A pays Bank B $100 (interbank leg) ① mint ② pay $100 · 24/7 · seconds ④ redeem R $
Orange coin = Bank A's token (aUSD). It turns green (Bank B's bUSD) as it crosses banks, while the blue "R" coin settles the same amount between the two banks in central bank money. On unified-ledger designs (e.g. BIS Project Agorá) legs ② and ③ happen atomically.

Lifecycle, step by step

  1. OnboardThe client is already KYC'd. The bank registers the client's wallet address on the ledger's allowlist. The wallet is often bank-custodied, with keys in an HSM or MPC.
  2. MintCore banking debits the client's DDA and credits the omnibus account. The token service calls mint(wallet, amount, coreRef). Invariant: token supply = omnibus balance.
  3. Transfer & programTokens move peer-to-peer or into contracts (escrow, DvP, sweeps) in seconds, 24/7.
  4. Cross-bankIf the payee banks elsewhere, the payer's bank token is burned (or held) and the payee's bank mints its own. The banks settle in central bank money, or both banks' tokens live on one shared ledger (Partior, Agorá, RLN-style designs).
  5. RedeemThe holder calls redeem(), the token is burned, and core banking credits the client's normal account.

Real-world examples (public announcements, as of 2025)

InitiativeWhat it does
J.P. Morgan Kinexys (formerly Onyx / JPM Coin)Deposit-token payments between J.P. Morgan institutional clients, 24/7, with programmable features. Reported daily volumes are in the billions. In 2025 it piloted JPMD, a USD deposit token on Base, a public Ethereum layer-2.
Citi Token ServicesTokenized deposits for Citi's institutional clients: 24/7 cross-border liquidity and automated trade-finance flows.
HSBC Tokenised Deposit ServiceTokenized deposits for corporate clients (UK, then Hong Kong) for instant 24/7 transfers between client accounts.
Project Agorá (BIS + 7 central banks + 40+ private firms)Explores tokenized commercial bank deposits and wholesale central bank money on one programmable "unified ledger" for cross-border payments.
PartiorA shared ledger built by banks (J.P. Morgan, DBS, Standard Chartered and others) for real-time, multi-currency interbank settlement.

Sample contract: TokenizedDeposit.sol

A permissioned ERC-20 with the controls a bank needs: issuer-only minting tied to a core-banking reference, a KYC allowlist, account freezes, and an emergency pause. Every mint, burn, and transfer passes through one hook (_update), so the rules can't be bypassed.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Pausable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";

/// @title Bank A USD deposit token
/// @notice Each token is a deposit liability of Bank A, mirrored 1:1 by an
///         omnibus account in the core banking system. Only KYC'd customers
///         (and approved contracts such as escrows) can hold or move it.
contract TokenizedDeposit is ERC20, ERC20Pausable, AccessControl {
    bytes32 public constant ISSUER_ROLE     = keccak256("ISSUER_ROLE");     // treasury ops: mint
    bytes32 public constant COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE"); // allowlist, freeze

    mapping(address => bool) public allowlisted;
    mapping(address => bool) public frozen;

    event Minted(address indexed to, uint256 amount, bytes32 indexed coreRef);
    event RedemptionRequested(address indexed from, uint256 amount, bytes32 indexed accountRef);

    constructor(address admin) ERC20("Bank A USD Deposit", "aUSD") {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
    }

    /// Same precision as the core ledger (cents).
    function decimals() public pure override returns (uint8) { return 2; }

    /// Called only after core banking has debited the customer's account
    /// and credited the token omnibus account. coreRef = core transaction id.
    function mint(address to, uint256 amount, bytes32 coreRef) external onlyRole(ISSUER_ROLE) {
        _mint(to, amount);
        emit Minted(to, amount, coreRef);
    }

    /// Holder converts tokens back to a normal deposit. The bank's listener
    /// sees the event and credits the account identified by accountRef.
    function redeem(uint256 amount, bytes32 accountRef) external {
        _burn(msg.sender, amount);
        emit RedemptionRequested(msg.sender, amount, accountRef);
    }

    function setAllowlisted(address account, bool ok) external onlyRole(COMPLIANCE_ROLE) {
        allowlisted[account] = ok;
    }

    function setFrozen(address account, bool isFrozen) external onlyRole(COMPLIANCE_ROLE) {
        frozen[account] = isFrozen;
    }

    function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); }
    function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); }

    /// Every mint, burn and transfer passes through this hook (OpenZeppelin v5).
    function _update(address from, address to, uint256 value)
        internal
        override(ERC20, ERC20Pausable)
    {
        if (from != address(0)) require(allowlisted[from] && !frozen[from], "sender not permitted");
        if (to != address(0))   require(allowlisted[to] && !frozen[to], "receiver not permitted");
        super._update(from, to, value);
    }
}
⚠️ GotchaSmart contracts are addresses too. To use a deposit token in an escrow or DvP contract, the bank must allowlist that contract. In practice banks maintain an approved-contract registry and only allowlist audited templates.

5. Variant 2: stablecoins

A fiat-backed stablecoin is a token whose issuer promises to redeem it 1:1 for fiat and holds reserves (cash at banks and short-dated government bills) to back that promise. Because it lives on public blockchains, the same token can reach any wallet, exchange, or app worldwide without the issuer being involved in each transfer.

PUBLIC BLOCKCHAIN · ANYONE WITH A WALLET Corporate wallet holds xUSD Exchanges / DeFi liquidity, FX, other chains Supplier wallet any country, any time ④ transfer peer-to-peer, 24/7 Corporate's bank wires USD Stablecoin issuer mints & burns 1:1 Reserve assets cash + short T-bills ① ② ③ mint ⑤ redeem & burn $ $ x$
Green "$" = fiat in the banking system; orange "x$" = the stablecoin on-chain. The issuer is only involved at mint and redeem. In between, the token moves freely across wallets, venues, and apps.

Lifecycle, step by step

  1. Onboard with the issuerOnly minting and redeeming clients (corporates, exchanges, banks) are KYC'd by the issuer. Other holders are usually KYC'd by the exchange or wallet provider they use.
  2. FundThe client wires USD to the issuer's account at a reserve bank.
  3. MintThe issuer mints tokens to the client's wallet. Good designs cap minting at attested reserves (proof of reserve).
  4. CirculateThe token moves across the public chain: payments, exchanges, DeFi, bridges to other chains. Compliance relies on blocklists, on-chain analytics (Chainalysis, TRM, etc.), and the KYC done at on/off-ramps.
  5. RedeemAny eligible holder sends tokens back. The issuer burns them and pays USD out of reserves.

Market & regulation snapshot (as of 2025, verify current status)

Sample contract: ReserveBackedStablecoin.sol

Permissionless transfers with a compliance blocklist, a hard cap that stops minting beyond attested reserves (with a staleness check on the reserve feed), and EIP-2612 permit so wallets can approve without paying gas.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";

/// Attested reserve balance (e.g. a proof-of-reserve feed updated from the
/// custodian banks' statements), in the same 6-decimal units as the token.
interface IReserveFeed {
    function reserves() external view returns (uint256 amount, uint256 updatedAt);
}

/// @title Fiat-backed stablecoin
/// @notice Anyone can hold and transfer it (permissionless), except addresses
///         on the blocklist. New supply can never exceed attested reserves.
contract ReserveBackedStablecoin is ERC20, ERC20Permit, AccessControl {
    bytes32 public constant MINTER_ROLE     = keccak256("MINTER_ROLE");
    bytes32 public constant COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE");

    IReserveFeed public immutable reserveFeed;
    uint256 public constant MAX_FEED_AGE = 1 days;

    mapping(address => bool) public blocked;

    event Redeemed(address indexed holder, uint256 amount);

    constructor(address admin, IReserveFeed feed)
        ERC20("Example USD", "xUSD")
        ERC20Permit("Example USD")
    {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        reserveFeed = feed;
    }

    function decimals() public pure override returns (uint8) { return 6; }

    /// Issuer mints after fiat has arrived in the reserve account.
    function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
        (uint256 reserveAmount, uint256 updatedAt) = reserveFeed.reserves();
        require(block.timestamp - updatedAt <= MAX_FEED_AGE, "reserve feed stale");
        require(totalSupply() + amount <= reserveAmount, "exceeds reserves");
        _mint(to, amount);
    }

    /// Holder sends tokens back to the issuer to be paid out in fiat off-chain.
    function redeem(uint256 amount) external {
        _burn(msg.sender, amount);
        emit Redeemed(msg.sender, amount);
    }

    function setBlocked(address account, bool isBlocked) external onlyRole(COMPLIANCE_ROLE) {
        blocked[account] = isBlocked;
    }

    function _update(address from, address to, uint256 value) internal override {
        require(!blocked[from] && !blocked[to], "address blocked");
        super._update(from, to, value);
    }
}
Compare the two token contractsThe deposit token checks an allowlist (deny by default: you must be a known customer). The stablecoin checks a blocklist (allow by default: everyone except sanctioned addresses). That one line of difference produces most of the business differences in section 2.

6. How to build it: reference architecture

A production platform has five layers plus cross-cutting services. The same stack serves both variants; the differences are in the token layer and the ledger choice.

Channels & clients corporate portal · treasury APIs · ERP / TMS connectors · AI agents Programmability layer audited templates: escrow · DvP / PvP · sweeps · streams · purpose-bound Money token tokenized deposit OR stablecoin · mint · burn · transfer · allow/blocklist · freeze Ledger permissioned (Besu, Quorum, Canton, Corda…) or public (Ethereum, L2s, Solana…) Bank systems core banking · omnibus account · payments hub · general ledger · reconciliation Identity & KYC Keys: HSM / MPC Oracles & data feeds AML · sanctions · travel rule Monitoring & audit
Left: the stack from client channels down to the bank's books. Right (blue): services every layer depends on.

Build roadmap

  1. Pick the money model and legal wrapperTokenized deposit (bank liability, banking licence) or stablecoin (separate issuer entity, stablecoin licence, segregated reserves)? Get the legal opinion on settlement finality: when is an on-chain transfer legally final?
  2. Choose the ledgerPermissioned (privacy, control, known validators) vs public (reach, composability, liquidity). Many banks start permissioned and add public-chain access later, as with JPMD on Base.
  3. Write the token contractStart from audited libraries (OpenZeppelin). Keep the token minimal: mint/burn roles, allow- or blocklist, freeze, pause, and possibly upgradeability behind a timelock and multi-sig.
  4. Integrate core bankingCreate the omnibus account. Mint only after a core debit and redeem only into a core credit, both idempotent. Run continuous reconciliation of supply vs omnibus.
  5. Wallets & keysCustodial wallets for most clients, with keys in HSM or MPC, policy engines (limits, approvals), and recovery procedures. Larger clients may self-custody.
  6. Programmability layerBuild a library of audited templates (escrow, DvP, sweep…) that clients parameterise. Don't let clients deploy arbitrary code against your token on day one.
  7. Oracles & eventsUse signed, multi-source data feeds for real-world conditions, and keeper bots to trigger time-based actions.
  8. ComplianceRun sanctions screening before allowlisting, transaction monitoring on-chain, Travel Rule data for transfers, and freeze/claw-back procedures.
  9. Test, audit, pilotUnit and fuzz tests, an external audit, a bug bounty, then a limited pilot (internal entities, then friendly clients) with volume caps.

Key design decisions

DecisionTokenized deposit (typical)Stablecoin (typical)
Access modelAllowlist (deny by default)Blocklist (allow by default)
Decimals2, matching the core ledger6 (USDC convention) or 18
PrivacyPrivate ledger, private transactions, or zero-knowledge proofsPublic by default; addresses are pseudonymous
Interbank / interopShared ledger, central bank money, or token bridges between bank networksCross-chain bridges or native multi-chain issuance (e.g. burn-and-mint transfer protocols)
Gas / feesBank-operated validators; no gas cost to clientsGas paid in the native coin; use paymasters and permit to hide it
UpgradeabilityProxy + timelock + bank multi-sigProxy + timelock + multi-sig; changes are publicly visible

7. Bank integration code (off-chain)

Smart contracts are maybe 20% of the work. The rest is connecting them safely to the bank. These TypeScript snippets (ethers v6) show the critical paths.

Mint service: core debit → tokens

// mint-service.ts — turns a core-banking debit into on-chain deposit tokens
import express from "express";
import { ethers } from "ethers";
import tokenAbi from "./abi/TokenizedDeposit.json";

const provider = new ethers.JsonRpcProvider(process.env.LEDGER_RPC_URL);
// Production: the issuer key lives in an HSM / MPC signer, never in an env var.
const issuer = new ethers.Wallet(process.env.ISSUER_KEY!, provider);
const aUSD = new ethers.Contract(process.env.AUSD_ADDRESS!, tokenAbi, issuer);

const app = express();
app.use(express.json());

// Core banking calls this AFTER it has debited the customer's account
// and credited the token omnibus account (same amount, same reference).
app.post("/core-events/tokenize", async (req, res) => {
  const { coreTxId, wallet, amountCents } = req.body;
  const coreRef = ethers.id(coreTxId);                      // bytes32 reference

  // Idempotency: the Minted event is indexed by coreRef, so retries are safe.
  const seen = await aUSD.queryFilter(aUSD.filters.Minted(null, null, coreRef));
  if (seen.length > 0) return res.json({ status: "duplicate", txHash: seen[0].transactionHash });

  const tx = await aUSD.mint(wallet, BigInt(amountCents), coreRef);
  const receipt = await tx.wait();
  res.json({ status: "minted", txHash: receipt!.hash });
});

app.listen(8080);

Redemption listener: burned tokens → core credit

// redemption-listener.ts — turns burned tokens back into a normal deposit
import { ethers } from "ethers";
import { coreBanking } from "./core-banking-client";

aUSD.on(aUSD.filters.RedemptionRequested(), async (from, amount, accountRef, event) => {
  await coreBanking.postTransfer({
    debit: "TOKEN-OMNIBUS-USD",                  // omnibus shrinks as supply shrinks
    credit: ethers.decodeBytes32String(accountRef),
    amountCents: amount,
    reference: event.log.transactionHash,        // idempotency key on the core side
  });
});

Continuous reconciliation

// reconcile.ts — the one invariant a deposit-token bank must never break
//   on-chain totalSupply  ==  balance of the token omnibus account in core banking
async function reconcile() {
  const onChain: bigint = await aUSD.totalSupply();
  const omnibus: bigint = BigInt(await coreBanking.balance("TOKEN-OMNIBUS-USD"));

  if (onChain !== omnibus) {
    await alerts.page("token-ops", { onChain, omnibus, diff: onChain - omnibus });
    await aUSD.connect(adminSigner).pause();     // stop the bleeding, then investigate
  }
}
setInterval(reconcile, 60_000);                  // every minute, 24/7

Client side: pay on delivery, either variant

// pay-with-escrow.ts — a corporate client's ERP pays a supplier "on delivery".
// The ONLY difference between the two variants is which token address you use.
import { ethers } from "ethers";

const TOKENS = {
  deposit:    "0xA0…aUSD",   // Bank A tokenized deposit (permissioned ledger)
  stablecoin: "0xB0…xUSD",   // regulated stablecoin (public chain)
} as const;

export async function payOnDelivery(
  signer: ethers.Signer, rail: keyof typeof TOKENS,
  seller: string, amount: bigint, billOfLading: string, days = 30,
) {
  const token  = new ethers.Contract(TOKENS[rail], erc20Abi, signer);
  const escrow = new ethers.Contract(ESCROW_ADDRESS, escrowAbi, signer);

  await (await token.approve(ESCROW_ADDRESS, amount)).wait();
  const deadline = Math.floor(Date.now() / 1000) + days * 24 * 3600;
  const tx = await escrow.open(seller, TOKENS[rail], amount, ethers.id(billOfLading), deadline);
  return (await tx.wait())!.hash;
}

Oracle keeper: real world → contract

// oracle-keeper.ts — pushes real-world events on-chain, then triggers payout
// Production oracles use several signed sources (carrier + port + eBL registry).
async function checkShipment(dealId: number, billOfLading: string) {
  const doc = await fetch(`${EBL_REGISTRY}/bills/${billOfLading}`, { headers: auth })
    .then((r) => r.json());

  if (doc.status === "DELIVERED" && verifySignature(doc)) {
    await (await oracle.setDelivered(ethers.id(billOfLading), true)).wait();
    await (await escrow.release(dealId)).wait();  // seller is paid in the same minute
  }
}
⚠️ Common failure modes
  • Double mint on retry. Always mint with an idempotency key (here coreRef).
  • Mint before debit. Tokens must never exist without the matching core-banking entry.
  • Single-source oracle. One compromised API key pays out every escrow. Use multiple signed sources and limits.
  • Hot keys in env vars. Issuer and admin keys belong in an HSM or MPC behind approval policies.

8. Smart contract library with use cases

Each contract below accepts any ERC-20 cash token, so each works unchanged with a tokenized deposit or a stablecoin. All seven contracts on this page compile with solc 0.8.26 + OpenZeppelin 5.1 and pass the Hardhat tests at the end of this section. They are teaching samples: production code needs an external audit, upgrade strategy, and fuller event and error design.

8.1 Trade escrow: "pay when the goods arrive"

Use case: replaces a letter of credit or open-account trade. The buyer's money is provably committed, and the seller is paid the minute the bill of lading shows delivery. If nothing arrives by the deadline, the buyer is automatically refunded.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/// Reports whether a shipment has been delivered, e.g. fed by an electronic
/// bill-of-lading registry or a logistics provider's signed API.
interface IDeliveryOracle {
    function isDelivered(bytes32 shipmentId) external view returns (bool);
}

/// @title Trade escrow: "pay when the goods arrive"
/// @notice Works with any ERC-20 cash token: a tokenized deposit or a stablecoin.
contract TradeEscrow {
    using SafeERC20 for IERC20;

    enum State { None, Funded, Released, Refunded }

    struct Deal {
        address buyer;
        address seller;
        IERC20  token;
        uint256 amount;
        bytes32 shipmentId;
        uint64  deadline;
        State   state;
    }

    IDeliveryOracle public immutable oracle;
    mapping(uint256 => Deal) public deals;
    uint256 public nextId;

    event Opened(uint256 indexed id, address indexed buyer, address indexed seller, uint256 amount);
    event Released(uint256 indexed id);
    event Refunded(uint256 indexed id);

    constructor(IDeliveryOracle oracle_) { oracle = oracle_; }

    /// Buyer locks funds. Requires a prior token.approve(escrow, amount).
    function open(address seller, IERC20 token, uint256 amount, bytes32 shipmentId, uint64 deadline)
        external
        returns (uint256 id)
    {
        require(deadline > block.timestamp, "deadline in past");
        id = nextId++;
        deals[id] = Deal(msg.sender, seller, token, amount, shipmentId, deadline, State.Funded);
        token.safeTransferFrom(msg.sender, address(this), amount);
        emit Opened(id, msg.sender, seller, amount);
    }

    /// Anyone (seller, bank, keeper bot) can trigger payout once delivery is proven.
    function release(uint256 id) external {
        Deal storage d = deals[id];
        require(d.state == State.Funded, "not funded");
        require(oracle.isDelivered(d.shipmentId), "not delivered");
        d.state = State.Released;
        d.token.safeTransfer(d.seller, d.amount);
        emit Released(id);
    }

    /// If nothing was delivered by the deadline, the buyer gets the money back.
    function refund(uint256 id) external {
        Deal storage d = deals[id];
        require(d.state == State.Funded, "not funded");
        require(block.timestamp > d.deadline, "deadline not reached");
        require(!oracle.isDelivered(d.shipmentId), "already delivered");
        d.state = State.Refunded;
        d.token.safeTransfer(d.buyer, d.amount);
        emit Refunded(id);
    }
}

8.2 Atomic DvP / PvP settlement

Use case: buy a tokenized bond, money-market-fund share, or repo collateral with cash tokens, or swap USD tokens for EUR tokens (PvP). Both legs settle in one transaction, so there's no settlement risk and no T+1/T+2 wait.

Seller holds tokenized bond DvP contract atomic: both legs or neither Buyer holds cash token ✓ settled in one transaction B $
Blue "B" = bond token, orange "$" = cash token. If either transfer would fail (no balance, no approval, not allowlisted), the entire transaction reverts, and neither side can end up with both assets.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/// @title Atomic delivery-versus-payment (also works as payment-versus-payment)
/// @notice Asset leg and cash leg move in ONE transaction: both or neither.
///         asset = tokenized bond / MMF share (DvP) or a second currency token (PvP).
contract DvPSettlement {
    using SafeERC20 for IERC20;

    struct Trade {
        address seller;     // delivers the asset
        address buyer;      // pays the cash
        IERC20  asset;
        uint256 assetQty;
        IERC20  cash;
        uint256 cashAmt;
        uint64  expiry;
        bool    sellerAffirmed;
        bool    buyerAffirmed;
        bool    settled;
    }

    mapping(uint256 => Trade) public trades;
    uint256 public nextId;

    event Proposed(uint256 indexed id);
    event Settled(uint256 indexed id);

    function propose(
        address seller, address buyer,
        IERC20 asset, uint256 assetQty,
        IERC20 cash, uint256 cashAmt,
        uint64 expiry
    ) external returns (uint256 id) {
        require(msg.sender == seller || msg.sender == buyer, "not a party");
        id = nextId++;
        trades[id] = Trade(seller, buyer, asset, assetQty, cash, cashAmt, expiry, false, false, false);
        emit Proposed(id);
    }

    /// Each party affirms after approving this contract for its leg.
    /// The second affirmation settles both legs atomically.
    function affirm(uint256 id) external {
        Trade storage t = trades[id];
        require(!t.settled, "settled");
        require(block.timestamp <= t.expiry, "expired");
        if (msg.sender == t.seller) t.sellerAffirmed = true;
        else if (msg.sender == t.buyer) t.buyerAffirmed = true;
        else revert("not a party");

        if (t.sellerAffirmed && t.buyerAffirmed) {
            t.settled = true;
            t.asset.safeTransferFrom(t.seller, t.buyer, t.assetQty); // delivery
            t.cash.safeTransferFrom(t.buyer, t.seller, t.cashAmt);   // payment
            emit Settled(id);                                        // any failure reverts both
        }
    }
}

8.3 Purpose-bound grant (purpose-bound money)

Use case: government subsidies, disaster relief, corporate expense budgets, education grants, or insurance claims that can only be spent with approved merchants before a date. Unspent money returns to the sponsor. (The concept is popularised by MAS's Project Orchid "purpose-bound money".)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/// @title Purpose-bound money: a grant that can only be spent with approved
///        merchants before an expiry date. Unspent funds return to the sponsor.
/// @dev The underlying money stays a normal token; the PURPOSE lives in this
///      wrapper, so it can be removed without changing the money itself.
contract PurposeBoundGrant {
    using SafeERC20 for IERC20;

    IERC20  public immutable money;
    address public immutable sponsor;
    uint64  public immutable expiry;

    mapping(address => uint256) public spendable;        // beneficiary => amount
    mapping(address => bool)    public approvedMerchant; // e.g. pharmacies, schools

    event Allocated(address indexed beneficiary, uint256 amount);
    event Spent(address indexed beneficiary, address indexed merchant, uint256 amount);
    event Reclaimed(uint256 amount);

    modifier onlySponsor() { require(msg.sender == sponsor, "only sponsor"); _; }

    constructor(IERC20 money_, address sponsor_, uint64 expiry_) {
        money = money_;
        sponsor = sponsor_;
        expiry = expiry_;
    }

    function setMerchant(address merchant, bool ok) external onlySponsor {
        approvedMerchant[merchant] = ok;
    }

    function allocate(address beneficiary, uint256 amount) external onlySponsor {
        require(block.timestamp <= expiry, "expired");
        money.safeTransferFrom(sponsor, address(this), amount);
        spendable[beneficiary] += amount;
        emit Allocated(beneficiary, amount);
    }

    function spend(address merchant, uint256 amount) external {
        require(block.timestamp <= expiry, "expired");
        require(approvedMerchant[merchant], "merchant not approved");
        spendable[msg.sender] -= amount; // reverts on underflow (Solidity 0.8)
        money.safeTransfer(merchant, amount);
        emit Spent(msg.sender, merchant, amount);
    }

    function reclaim() external onlySponsor {
        require(block.timestamp > expiry, "not expired");
        uint256 left = money.balanceOf(address(this));
        money.safeTransfer(sponsor, left);
        emit Reclaimed(left);
    }
}

8.4 Treasury sweep

Use case: corporate liquidity management. Every subsidiary is kept at a target balance, excess cash flows to the group's concentration account (where it can earn yield or repay debt), and shortfalls are topped up. It runs every hour, 24/7, instead of in a nightly batch.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/// @title Corporate treasury sweep
/// @notice Keeps each subsidiary wallet at a target balance: excess is swept to
///         the group's concentration wallet, shortfalls are topped up from it.
///         Each subsidiary and the concentration wallet approve this contract.
contract TreasurySweep {
    using SafeERC20 for IERC20;

    struct Rule { uint256 target; bool active; }

    IERC20  public immutable cash;
    address public immutable treasurer;
    address public immutable concentration;
    mapping(address => Rule) public rules;

    event Swept(address indexed subsidiary, int256 moved); // + = to pool, - = to subsidiary

    constructor(IERC20 cash_, address treasurer_, address concentration_) {
        cash = cash_;
        treasurer = treasurer_;
        concentration = concentration_;
    }

    function setRule(address subsidiary, uint256 target, bool active) external {
        require(msg.sender == treasurer, "only treasurer");
        rules[subsidiary] = Rule(target, active);
    }

    /// Called by an automation keeper (e.g. every hour, or at 17:00 local time).
    function sweep(address subsidiary) external {
        Rule memory r = rules[subsidiary];
        require(r.active, "no rule");
        uint256 bal = cash.balanceOf(subsidiary);
        if (bal > r.target) {
            uint256 excess = bal - r.target;
            cash.safeTransferFrom(subsidiary, concentration, excess);
            emit Swept(subsidiary, int256(excess));
        } else if (bal < r.target) {
            uint256 shortfall = r.target - bal;
            cash.safeTransferFrom(concentration, subsidiary, shortfall);
            emit Swept(subsidiary, -int256(shortfall));
        }
    }
}

8.5 Payroll streaming

Use case: earned-wage access, contractor and gig payouts, subscriptions, and rent. Pay accrues per second, and the worker withdraws whenever they want. If the employer cancels, the earned portion is paid and the rest refunded in the same transaction.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/// @title Salary streaming: pay accrues every second, withdraw any time
contract PayrollStream {
    using SafeERC20 for IERC20;

    struct Stream {
        address employer;
        address employee;
        uint256 ratePerSecond;
        uint64  start;
        uint64  stop;
        uint256 withdrawn;
    }

    IERC20 public immutable cash;
    mapping(uint256 => Stream) public streams;
    uint256 public nextId;

    event Withdrawn(uint256 indexed id, uint256 amount);
    event Cancelled(uint256 indexed id, uint256 toEmployee, uint256 toEmployer);

    constructor(IERC20 cash_) { cash = cash_; }

    /// Employer pre-funds the whole period (e.g. one month of salary).
    function create(address employee, uint256 ratePerSecond, uint64 start, uint64 stop)
        external
        returns (uint256 id)
    {
        require(stop > start, "bad period");
        id = nextId++;
        streams[id] = Stream(msg.sender, employee, ratePerSecond, start, stop, 0);
        cash.safeTransferFrom(msg.sender, address(this), ratePerSecond * (stop - start));
    }

    function earned(uint256 id) public view returns (uint256) {
        Stream memory s = streams[id];
        if (block.timestamp <= s.start) return 0;
        uint256 end = block.timestamp < s.stop ? block.timestamp : s.stop;
        return s.ratePerSecond * (end - s.start);
    }

    function withdraw(uint256 id) external {
        Stream storage s = streams[id];
        require(msg.sender == s.employee, "not employee");
        uint256 amount = earned(id) - s.withdrawn;
        s.withdrawn += amount;
        cash.safeTransfer(s.employee, amount);
        emit Withdrawn(id, amount);
    }

    /// Employer ends the stream: employee keeps what was earned, the rest is refunded.
    function cancel(uint256 id) external {
        Stream storage s = streams[id];
        require(msg.sender == s.employer, "not employer");
        uint256 total = s.ratePerSecond * (s.stop - s.start);
        uint256 earnedNow = earned(id);
        uint256 owed = earnedNow - s.withdrawn;
        uint256 refund = total - earnedNow;
        // Freeze the stream at "now" so nothing more accrues.
        s.withdrawn = earnedNow;
        s.stop = uint64(block.timestamp < s.stop ? block.timestamp : s.stop);
        if (s.stop < s.start) s.stop = s.start;
        cash.safeTransfer(s.employee, owed);
        cash.safeTransfer(s.employer, refund);
        emit Cancelled(id, owed, refund);
    }
}

8.6 Tests: same contracts, both variants

Mocks used by the tests (in production these are real, signed data feeds):

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/// Test doubles: in production these are a real logistics feed and a real
/// proof-of-reserve feed signed by the custodian / auditor.
contract MockDeliveryOracle {
    mapping(bytes32 => bool) public isDelivered;
    function setDelivered(bytes32 shipmentId, bool d) external { isDelivered[shipmentId] = d; }
}

contract MockReserveFeed {
    uint256 public amount;
    uint256 public updatedAt;
    function set(uint256 a) external { amount = a; updatedAt = block.timestamp; }
    function reserves() external view returns (uint256, uint256) { return (amount, updatedAt); }
}

contract MockBond is ERC20 {
    constructor(address holder) ERC20("Tokenized 2Y Note", "BOND") { _mint(holder, 1_000); }
    function decimals() public pure override returns (uint8) { return 0; }
}

The escrow test runs twice, once per variant. Note the one extra step for the deposit token: allowlisting the escrow contract.

const { expect } = require("chai");
const { ethers } = require("hardhat");
const { time } = require("@nomicfoundation/hardhat-network-helpers");

describe("Programmable money", function () {
  let bank, compliance, buyer, seller, outsider;
  let aUSD, xUSD, oracle, feed, escrow;
  const SHIP = ethers.id("BL-2026-000123");             // bill-of-lading id
  const REF = ethers.encodeBytes32String("CORE-TX-1");  // core banking reference

  beforeEach(async () => {
    [bank, compliance, buyer, seller, outsider] = await ethers.getSigners();

    // Variant 1: tokenized deposit (permissioned)
    aUSD = await ethers.deployContract("TokenizedDeposit", [bank.address]);
    await aUSD.grantRole(await aUSD.ISSUER_ROLE(), bank.address);
    await aUSD.grantRole(await aUSD.COMPLIANCE_ROLE(), compliance.address);

    // Variant 2: stablecoin (permissionless, reserve-capped)
    feed = await ethers.deployContract("MockReserveFeed");
    xUSD = await ethers.deployContract("ReserveBackedStablecoin", [bank.address, await feed.getAddress()]);
    await xUSD.grantRole(await xUSD.MINTER_ROLE(), bank.address);

    oracle = await ethers.deployContract("MockDeliveryOracle");
    escrow = await ethers.deployContract("TradeEscrow", [await oracle.getAddress()]);
  });

  it("tokenized deposit: only allowlisted holders can transact", async () => {
    await aUSD.connect(compliance).setAllowlisted(buyer.address, true);
    await aUSD.mint(buyer.address, 100_00, REF);                        // $100.00
    await expect(aUSD.connect(buyer).transfer(outsider.address, 1))
      .to.be.revertedWith("receiver not permitted");
  });

  it("stablecoin: cannot mint beyond attested reserves", async () => {
    await feed.set(1_000_000n * 10n ** 6n);                             // $1m in reserve
    await xUSD.mint(buyer.address, 1_000_000n * 10n ** 6n);
    await expect(xUSD.mint(buyer.address, 1)).to.be.revertedWith("exceeds reserves");
    await xUSD.connect(buyer).transfer(outsider.address, 5n * 10n ** 6n); // anyone can receive
    expect(await xUSD.balanceOf(outsider.address)).to.equal(5n * 10n ** 6n);
  });

  for (const variant of ["tokenized deposit", "stablecoin"]) {
    it(`escrow pays seller after delivery (${variant})`, async () => {
      let token;
      if (variant === "tokenized deposit") {
        token = aUSD;
        // The escrow contract itself must be allowlisted to hold deposit tokens.
        for (const a of [buyer.address, seller.address, await escrow.getAddress()])
          await aUSD.connect(compliance).setAllowlisted(a, true);
        await aUSD.mint(buyer.address, 50_000_00, REF);
      } else {
        token = xUSD;
        await feed.set(50_000n * 10n ** 6n);
        await xUSD.mint(buyer.address, 50_000n * 10n ** 6n);
      }
      const amount = await token.balanceOf(buyer.address);
      const deadline = (await time.latest()) + 30 * 24 * 3600;

      await token.connect(buyer).approve(await escrow.getAddress(), amount);
      await escrow.connect(buyer).open(seller.address, await token.getAddress(), amount, SHIP, deadline);
      await expect(escrow.release(0)).to.be.revertedWith("not delivered");

      await oracle.setDelivered(SHIP, true);                             // carrier confirms
      await escrow.connect(outsider).release(0);                         // anyone can trigger
      expect(await token.balanceOf(seller.address)).to.equal(amount);
    });
  }

  it("escrow refunds buyer after the deadline", async () => {
    await feed.set(1_000n * 10n ** 6n);
    await xUSD.mint(buyer.address, 1_000n * 10n ** 6n);
    const deadline = (await time.latest()) + 3600;
    await xUSD.connect(buyer).approve(await escrow.getAddress(), 1_000n * 10n ** 6n);
    await escrow.connect(buyer).open(seller.address, await xUSD.getAddress(), 1_000n * 10n ** 6n, SHIP, deadline);
    await time.increase(3601);
    await escrow.refund(0);
    expect(await xUSD.balanceOf(buyer.address)).to.equal(1_000n * 10n ** 6n);
  });

  it("DvP settles bond and cash atomically", async () => {
    const dvp = await ethers.deployContract("DvPSettlement");
    const bond = await ethers.deployContract("MockBond", [seller.address]);
    await feed.set(99_000n * 10n ** 6n);
    await xUSD.mint(buyer.address, 99_000n * 10n ** 6n);

    const expiry = (await time.latest()) + 3600;
    await dvp.connect(seller).propose(seller.address, buyer.address,
      await bond.getAddress(), 100, await xUSD.getAddress(), 99_000n * 10n ** 6n, expiry);
    await bond.connect(seller).approve(await dvp.getAddress(), 100);
    await xUSD.connect(buyer).approve(await dvp.getAddress(), 99_000n * 10n ** 6n);

    await dvp.connect(seller).affirm(0);
    await dvp.connect(buyer).affirm(0);                                  // settles both legs
    expect(await bond.balanceOf(buyer.address)).to.equal(100);
    expect(await xUSD.balanceOf(seller.address)).to.equal(99_000n * 10n ** 6n);
  });

  it("DvP reverts BOTH legs if one leg fails", async () => {
    const dvp = await ethers.deployContract("DvPSettlement");
    const bond = await ethers.deployContract("MockBond", [seller.address]);
    const expiry = (await time.latest()) + 3600;
    await dvp.connect(seller).propose(seller.address, buyer.address,
      await bond.getAddress(), 100, await xUSD.getAddress(), 1n, expiry);
    await bond.connect(seller).approve(await dvp.getAddress(), 100);
    await dvp.connect(seller).affirm(0);
    await expect(dvp.connect(buyer).affirm(0)).to.be.reverted;           // buyer has no cash
    expect(await bond.balanceOf(seller.address)).to.equal(1_000);        // bond never moved
  });
});
$ npx hardhat test
  Programmable money
    ✔ tokenized deposit: only allowlisted holders can transact
    ✔ stablecoin: cannot mint beyond attested reserves
    ✔ escrow pays seller after delivery (tokenized deposit)
    ✔ escrow pays seller after delivery (stablecoin)
    ✔ escrow refunds buyer after the deadline
    ✔ DvP settles bond and cash atomically
    ✔ DvP reverts BOTH legs if one leg fails

9. Use cases: built with tokenized deposits vs stablecoins

For each use case, the smart-contract logic is the same. What changes is the plumbing: who must be onboarded, how money crosses institutions, and where the parties can be.

#Use caseContract patternWith tokenized depositsWith stablecoins
1Cross-border B2B payment + FXPvP (DvPSettlement)USD token of Bank A ↔ EUR token of Bank B on a shared ledger, settled atomically. Both parties are bank clients.USDC ↔ EURC swap on an exchange or on-chain FX venue. The supplier can be anywhere with a wallet.
2Trade finance (LC replacement)TradeEscrow + eBL oracleBuyer's bank locks deposit tokens. The seller's bank is on the same network, and the bank may add financing to the escrow.Buyer locks stablecoins. Works with exporters in markets without access to the buyer's bank network.
3Securities settlementDvPSettlementTokenized bond or MMF ↔ deposit token on the bank's ledger. This is the dominant institutional model today.Tokenized treasury fund ↔ stablecoin on a public chain, used by crypto-native funds and on-chain collateral.
4Intraday repoDvP + time-locked unwindCash token ↔ collateral token for hours instead of overnight; the unwind is programmed at a set time.Possible, but rarely used by banks today because of capital treatment and counterparty concerns.
5Treasury sweeps & poolingTreasurySweepNatural fit: all subsidiaries bank with the same group bank. Interest can be paid on the pool.Works for multi-bank or crypto-native treasuries, but the pool can't earn interest from the issuer.
6Payroll & gig payoutsPayrollStreamEmployees of the bank's corporate clients get streamed deposit tokens and can redeem instantly into their accounts.Global contractors paid in stablecoin to any wallet, cashed out locally through ramps.
7Grants, subsidies, claimsPurposeBoundGrantGovernment or insurer works with banks whose merchant clients are allowlisted. Strong KYC on both sides.Aid to unbanked recipients via mobile wallets, where the merchant allowlist is the control.
8Supply-chain financeEscrow + auto-discountingWhen the buyer approves an invoice on-chain, the bank's financing contract pays the supplier early at a discount and collects from the buyer at maturity.Same flow, with funding from on-chain lenders or credit pools.
9Parametric insuranceEscrow + weather/flight oracleInsurer's premium pool in deposit tokens pays out automatically when the oracle reports a flight delay or rainfall below a threshold.Same, paying travellers or farmers directly to their wallets anywhere.
10Machine & AI-agent paymentsPay-per-use / streamingEV chargers or IoT devices of corporate clients settling with each other inside one bank network.APIs charging AI agents per call (e.g. HTTP 402-style payment flows): micro-payments that cards can't do economically.

Walkthrough A: cross-border supplier payment

🏦 Tokenized deposit way

  1. A US importer (Bank A client) tokenizes $1m into aUSD.
  2. An FX desk quotes EUR. A DvPSettlement trade is proposed: aUSD ↔ bEUR (Bank B, Europe).
  3. Both affirm, and the PvP settles atomically, so no Herstatt risk.
  4. The German exporter (Bank B client) receives bEUR and redeems to its EUR account in seconds, on a Sunday.

Needs: both banks on the same network (or connected networks); both clients onboarded.

🪙 Stablecoin way

  1. The importer converts USD to USDC via its bank or an on-ramp.
  2. USDC is swapped to EURC on a regulated venue (or the exporter simply accepts USDC).
  3. The importer transfers EURC to the exporter's wallet in seconds.
  4. The exporter holds EURC or off-ramps to EUR with any MiCA-licensed provider.

Needs: wallets and ramps on both sides; the exporter's bank doesn't have to be involved.

Walkthrough B: delivery-versus-payment for a tokenized bond

🏦 Tokenized deposit way

An asset manager buys a $100m digitally issued bond. The bond token and the bank's deposit token sit on the same permissioned ledger, and DvPSettlement swaps them instantly. The cash never leaves the banking system and is still a deposit, so it can be lent and earn interest.

🪙 Stablecoin way

A crypto-native fund buys a tokenized T-bill fund share on a public chain with USDC through the same DvP contract. It settles instantly too, but the cash leg is a claim on Circle's reserves rather than on a bank.

Walkthrough C: disaster-relief grant

🏦 Tokenized deposit way

The government deposits funds with participating banks, which mint deposit tokens into a PurposeBoundGrant. Approved pharmacies and grocers (bank clients) are allowlisted. Recipients spend through their banking app, and unspent funds return after 90 days.

🪙 Stablecoin way

An NGO funds the grant with USDC. Recipients without bank accounts receive phone-wallet allowances. Local merchants are approved in the contract and cash out through local ramps. It reaches people banks can't, with weaker identity guarantees.

10. Try it: programmable escrow simulator

A buyer has locked $50,000 in TradeEscrow. Change the conditions and the rail to see what the contracts on this page would do.

    11. Why programmable money is good for banks

    🛡️ Defend the deposit base

    If corporates move cash into stablecoins to get 24/7 programmable payments, deposits leave the bank's balance sheet. Tokenized deposits give clients the same features while the money stays a deposit that funds lending.

    ⏱️ 24/7 instant settlement

    No cut-offs, weekends, or holiday gaps. Treasurers can move liquidity across entities and time zones whenever they need to, which is a major selling point for multinational clients.

    💧 Intraday liquidity efficiency

    Atomic DvP/PvP removes the need to pre-fund or post large buffers. Intraday repo lets banks borrow cash for hours against collateral, which lowers liquidity costs.

    🧾 Less reconciliation & ops cost

    One shared ledger instead of many mismatched books means fewer breaks, exceptions, and manual checks. Settlement and payment are the same event.

    💼 New fee revenue

    Programmable treasury services, escrow-as-a-service, conditional trade-finance products, DvP settlement for tokenized assets, and API/automation fees.

    🔍 Compliance by design

    Allowlists, freezes, limits, and audit trails are enforced in code on every transfer. Regulators can get read-only views of the ledger.

    🔗 Tokenized-asset gateway

    Tokenized bonds, funds, and deposits need on-chain cash. The bank that provides the cash leg sits at the centre of tokenized capital markets.

    🪙 Stablecoin business lines

    Even without issuing its own coin, a bank can hold issuer reserves, provide custody, run fiat on/off-ramps, offer settlement accounts for crypto firms, or issue a stablecoin through a subsidiary where the law allows.

    Which variant should a bank choose?

    GoalBetter fitWhy
    Keep deposits on balance sheet, serve corporate treasuryTokenized depositKeeps deposit funding and lending capacity, can pay interest, and is covered by existing banking rules.
    Settle tokenized securities with institutional clientsTokenized depositThe cash leg is in commercial bank money with strong legal certainty. This is the model used by most bank-led platforms.
    Reach clients and counterparties outside your networkStablecoinPublic-chain reach. Any wallet worldwide, with no need for every party to join one bank network.
    Serve crypto/DeFi markets and fintech partnersStablecoinThat's where the liquidity and integrations already are.
    Earn fee income without balance-sheet useStablecoin servicesReserve custody, ramps, and settlement accounts.
    🎯 TakeawayFor most banks the answer is both: tokenized deposits for their own clients and balance sheet, and stablecoin services (custody, ramps, reserve banking) to take part in the open-network economy. The smart-contract layer can be shared, because all the contracts on this page are token-agnostic.

    12. Risks, controls & regulation

    RiskWhat can go wrongControls
    Smart-contract bugsFunds locked forever or drainedAudited libraries, external audits, formal verification for core contracts, caps, pause switch, bug bounty
    Oracle manipulationA fake "delivered" signal releases escrowMultiple signed sources, thresholds, dispute windows, amount limits
    Key compromiseAttacker mints or moves fundsHSM/MPC, multi-sig with role separation, timelocks on admin actions, mint limits per period
    FragmentationEach bank's token is an island, and money isn't "single"Shared ledgers, central-bank-money settlement, interoperability standards
    PrivacyCompetitors see payment flows on a shared ledgerPermissioned ledgers, private transactions, zero-knowledge proofs
    Legal finalityOn-chain transfer not recognised as final in insolvencyLegal opinions, rulebooks, designated settlement-system status
    Stablecoin run / de-pegDoubts about reserves trigger mass redemptionsHigh-quality liquid reserves, frequent attestations, on-chain proof of reserve, redemption SLAs
    Capital treatmentHolding crypto assets is expensive for banksUnder the Basel crypto-asset standard, tokenized traditional assets (e.g. deposit tokens) can qualify for treatment like the underlying, while stablecoins face extra tests. The standard is being reviewed, especially for permissionless chains, so follow your regulator.

    Self-check quiz

    Score: 0 / 0 answered

    1 · What is the main legal difference between a tokenized deposit and a fiat-backed stablecoin?
    C. Both are programmable tokens. The core difference is whose liability the token is, which drives deposit insurance, interest, balance-sheet treatment, and regulation.
    2 · A bank's escrow contract keeps reverting when clients try to lock deposit tokens in it. What's the most likely cause?
    B. With an allowlist token, every receiver, including contracts, must be permitted. The oracle only matters at release(), not at open().
    3 · Which property removes settlement (Herstatt) risk in an FX or securities trade?
    D. Atomic DvP/PvP means no party can deliver without receiving. That works with either cash variant.
    4 · What invariant must a deposit-token bank continuously reconcile?
    A. Every token must be matched 1:1 by money moved into the omnibus account. A mismatch means a double mint, a missed redemption, or worse. Pause and investigate.
    5 · Why do regulators generally prefer "programmable payments" over restrictions coded into the money itself?
    C. If some dollars can't be spent everywhere, they're no longer equal to other dollars. Keeping rules in separate contracts (like PurposeBoundGrant) avoids this.
    6 · A bank wants to stop corporate deposits leaking into stablecoins while offering 24/7 programmable treasury. Which is the best first move?
    B. Tokenized deposits give clients the features they want while the money stays a deposit on the bank's balance sheet. A stablecoin must be backed by high-quality liquid reserves, not loans.