ICRC Token Payments on ICP: Transfers, Approvals, Subaccounts, and Payment Flows That Don’t Double-Charge Users

·

The earlier guide on Inter-Canister Calls on ICP focused on a rule that becomes especially important when money is involved: an await is a distributed-systems boundary, and retries cannot automatically be assumed safe. ICRC ledgers are a good place to put that rule into practice. At first glance, accepting an ICP, ckBTC, ckUSDC, or SNS-token payment seems simple. Call icrc1_transfer , wait for #Ok , and credit the user. Production payment systems have more to solve: fees can change, transfers can be submitted twice, users can pay from subaccounts, approvals can race, a transfer_from can fail after your application has already changed state, and transaction history should generally come from an index rather than an ever-growing scan of the ledger. This guide builds the architecture I would use for an ICRC payment flow and, more importantly, explains where the common implementations become unsafe. As of September 9, 2026, ICP's own ledger is fully ICRC-1 and ICRC-2 compatible, so most of the patterns here apply equally to ICP and other ICRC-compatible fungible assets. The ledger canister ID and token-specific parameters change but the payment model does not. Start with the account model An ICRC account is not just a principal. Conceptually it is (owner, subaccount) , where owner is a principal and subaccount is optional. In Motoko: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff type Account = { owner : Principal ; subaccount : ? Blob ; }; This matters because two accounts can share the same principal while representing different balances. If Alice owns principal aaaaa-... , these can all be separate ledger accounts: Alice's default account, Alice's payment subaccount, Alice's trading subaccount, or another application-defined subaccount. A system that stores only the owner principal is therefore not storing a complete ICRC account. That becomes particularly useful for payment processing. One payment canister does not need one principal per customer Suppose an application has 100,000 users and wants to accept deposits. One design is to ask everybody to send tokens into the same account and then try to identify who paid using memos. There is a cleaner ICRC-native design: assign each customer a deterministic subaccount owned by the payment canister. The resulting architecture is one canister principal with many ledger accounts: Payment Canister + subaccount(Alice) , Payment Canister + subaccount(Bob) , Payment Canister + subaccount(Carol) . Now the destination itself identifies the internal account being funded. That removes a large amount of ambiguity from deposit processing. Derive subaccounts deterministically A subaccount is 32 bytes. For a user-based payment system, I would derive it deterministically from something stable, such as the user's principal. For example, conceptually: subaccount = SHA-256(domain_separator || user_principal_bytes) . The domain separator matters if the same application derives subaccounts for different purposes. deposit:user and treasury:user , for example, should not accidentally produce the same account namespace. A production derivation function should be documented and immutable. Once users have sent funds to those addresses, changing the algorithm changes where your application looks for their money. This is a data-model decision, not a formatting helper. Do not hardcode token decimals A frontend often starts with an assumption like 1 token = 100_000_000 base units . That happens to match ICP's eight decimal places. It does not define ICRC because an ICRC ledger exposes icrc1_decimals , and applications should query it. The same applies to the ledger fee through icrc1_fee . ICP's current ledger guidance explicitly recommends querying both rather than hardcoding them. So if the user types 12.50 , the frontend should first know the token's decimals and convert that human-readable amount into integer base units. Never represent ledger amounts internally as JavaScript floating-point values . Use bigint . For example: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff function parseUnits ( value: string, decimals: number ): bigint { const [whole, fraction = "" ] = value. trim (). split ( "." ); if (! /^\d+$/ . test (whole || "0" ) || ! /^\d*$/ . test (fraction)) { throw new Error ( "Invalid amount" ); } if (fraction. length > decimals) { throw new Error ( `Token supports only ${decimals} decimal places` ); } const padded = fraction. padEnd (decimals, "0" ); return ( BigInt (whole || "0" ) * 10n ** BigInt (decimals) + BigInt (padded || "0" ) ); } This converts decimal text into exact ledger units without introducing floating-point rounding. Use the current frontend SDK There has been a tooling transition since many existing ICP token tutorials were written. The current recommended JavaScript package for interacting with well-known ICP canisters is @icp-sdk/canisters , using modular imports such as @icp-sdk/canisters/ledger/icrc . The older individual packages including @dfinity/ledger-icrc and @dfinity/ledger-icp remain available for backward compatibility, but DFINITY now labels the modular @icp-sdk/canisters library as the recommended entry point. A modern ICRC ledger client therefore looks like: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff import { HttpAgent } from "@icp-sdk/core/agent" ; import { IcrcLedgerCanister } from "@icp-sdk/canisters/ledger/icrc" ; const agent = await HttpAgent . create ({ identity, host : IC_HOST , }); const ledger = IcrcLedgerCanister . create ({ agent, canisterId : ledgerCanisterId, }); Recent releases also moved the generated Candid types into namespaces such as IcrcLedgerDid , so older import examples may no longer match the current SDK shape. (That is a good reason to pin SDK versions and upgrade them deliberately instead of copying an old ledger example and assuming its types are still current.) ICRC-1 is the direct-transfer path The basic ICRC-1 payment is a transfer from an account controlled by the caller to another account. For a wallet-like frontend, that means the user signs a call to the ledger and transfers directly to the merchant or application account. Conceptually, icrc1_transfer receives the destination account, amount, optional fee, memo, source subaccount, and optional created_at_time . The important part is that the ledger, not your frontend, is the authority over whether the transfer succeeded. Your UI saying "Payment sent" does not make a payment final. The ledger returning an accepted block index does. Do not hardcode the fee into the send form Suppose the application assumes a fee of 10_000 base units forever. If the ledger's fee changes, a transfer specifying the stale fee can return BadFee , including the ledger's expected_fee . Current ICRC ledger guidance recommends querying icrc1_fee at runtime. I generally prefer fetching token metadata and fee as part of the asset-loading layer and caching it briefly, then the send form can correctly check that the user has enough for both the amount and fee. For a balance B , transfer amount A , and fee F , the useful condition is A + F <= B , not merely A <= B . It sounds trivial until the user's "MAX" button produces a transaction that can never succeed. created_at_time is one of the most important fields in the interface Consider this payment: send 10 ICP to merchant . The frontend submits it. The network connection disappears before the frontend receives the result. Did the ledger process it? If the frontend simply submits the same transfer again, it may pay twice . ICRC ledgers solve this with transaction deduplication when created_at_time is supplied. The ledger tracks identical transactions within its deduplication window, currently 24 hours in the standard ledger implementation, and returns Duplicate { duplicate_of } rather than executing the same transfer again. Without created_at_time , identical submissions are distinct transfers. That means null is not the value I would use casually in production payment code. A duplicate is often success, not failure Suppose the first transfer succeeded at block 8421. The response was lost. Your retry returns Duplicate { duplicate_of = 8421 } . A naive UI displays "Transaction failed." But the ledger is telling you something much more useful: this exact transaction already succeeded, and here is the block index. For payment workflows, I would normalize both #Ok(blockIndex) and #Duplicate({ duplicate_of }) into a successful payment result. The business meaning is the same: exactly one matching transfer was accepted. That is idempotency provided by the ledger rather than reinvented in your application. It directly connects to the retry problem discussed in the Inter-Canister Calls guide . Save the timestamp before making the call Do not generate a new created_at_time every time your retry loop runs. That defeats deduplication. Generate the transaction parameters once: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff const createdAtTime = BigInt ( Date . now ()) * 1_000_000n ; const request = { to : destination, amount, createdAtTime, }; Then retry the same logical transaction using the same timestamp and other deduplication-relevant fields. A retry should mean "try submitting transaction X again," not "construct a new transaction that happens to look similar." That distinction becomes useful far beyond ledgers. Handle TooOld and CreatedInFuture Deduplication introduces two time-related errors. TooOld means the transaction timestamp has fallen outside the ledger's accepted deduplication window. CreatedInFuture means the submitted timestamp is ahead of the ledger's current time; the error includes ledger_time to help diagnose the difference. Do not respond to TooOld by silently generating a new timestamp and resubmitting a financially significant transfer. At that point, you need to determine whether the original transaction executed. Otherwise the "fix" for an old request can become a duplicate payment. For a user-facing wallet, I would surface the ambiguity and reconcile against transaction history before constructing a new payment. Memos are identifiers, not your accounting database ICRC transfers can include a memo, and a payment application might encode an invoice ID there. That can be useful, but I would not make the memo the only representation of application state. Your backend should still have an invoice record such as an invoice ID, expected ledger, expected destination account, expected amount, status, expiration, and eventual ledger block index. The ledger transaction is proof that funds moved and the invoice is your application's interpretation of why they moved. Keeping those separate makes reconciliation possible when either side experiences a temporary failure. Model payments as state machines I would not represent an invoice with only paid : Bool . Real payment processing has more states. A simple model might be #pending , #submitted , #confirmed , #expired , and #failed . The exact names are less important than the idea: payment is a workflow, not a single boolean transition. For example, the frontend can submit a ledger transaction successfully while the application's follow-up call that records the block index fails. The money really moved, but in that case your backend has not yet recorded it. If the only states are paid and not paid , you have created an awkward recovery problem. A state machine lets a reconciliation process finish incomplete workflows safely. Never credit from a frontend claim alone This backend API is dangerous: Plain text Bash / Shel