Token escrow, swaps, and fundraising
These examples show how Solana programs coordinate token movement between several participants. They cover direct escrow offers, pool-based swaps, and a time-bound fundraiser. In each case, the program controls when tokens leave custody and records the conditions for settlement.
System model
The three workflows use different settlement models for the same core problem: one party must not receive value unless the related obligation is met. The escrow and fundraiser hold tokens in program-controlled vaults. The swap pool holds shared reserves and uses a pricing rule to determine the amount returned.
Participant roles
Each workflow gives a different party control over the next action. The role matters because the signer and the program-controlled account together define who may move each asset.
| Workflow | Participants | Program-controlled custody |
|---|---|---|
| Escrow | Maker and taker | The maker's offered token sits in an offer vault until take or refund |
| Pool swap | Trader and liquidity providers | The pool authority controls both token reserves |
| Fundraiser | Maker and contributors | The fundraiser vault holds contributor payments until claim or refund |
Maker means the party that creates an offer or fundraiser. Taker means the party that accepts an escrow offer. A liquidity provider supplies both assets to a swap pool and receives pool-share tokens. A contributor supplies the asset requested by a fundraiser.
References: tokens/…/offer.rs• L3-12 tokens/…/state.rs• L3-31 tokens/…/fundraiser.rs• L3-13 tokens/…/contributor.rs• L3-7
Custody boundaries
The vault or pool account is the key custody boundary. A participant signs to move tokens from their own token account into program custody. The program-derived address (PDA) that owns the custody account signs when the program releases tokens.
This separates permission to act from ownership of the stored assets. The maker can refund an escrow offer because the offer records the maker and controls its vault. The fundraiser can return a contributor's recorded amount because its PDA controls the fundraiser vault. The swap pool can pay traders and providers because its pool authority controls both reserves.
References: tokens/…/make_offer.rs• L15-49 tokens/…/take_offer.rs• L64-70 tokens/…/initialize.rs• L15-37 tokens/…/refund.rs• L38-49 tokens/…/create_pool.rs• L44-89
Escrow offers
The escrow example implements a direct, fixed-price exchange between two users. The maker names one token and amount to offer, then names the token and amount wanted in return. The program keeps the offered tokens until it can settle both sides or return the maker's assets.
The same escrow workflow is also expressed through native and Pinocchio program paths. These paths keep the same maker, taker, vault, and PDA roles while checking that supplied accounts match the recorded offer and its canonical token accounts.
Offer creation
An offer is a durable record of the trade terms. Its identity binds the maker to an offer ID, while its token fields bind the offer to the two mints. The maker's offered tokens move to a vault owned by the offer PDA before the terms are saved.
This order gives the offer a custody record from the start. The taker does not need to trust the maker to send the offered asset after receiving payment. The native and Pinocchio paths also validate the offer address and the vault relationship before they record the terms.
References: tokens/…/lib.rs• L18-26 tokens/…/offer.rs• L3-12 tokens/…/make_offer.rs• L25-49 tokens/…/make_offer.rs• L56-81 tokens/…/make_offer.rs• L15-24 tokens/…/make_offer.rs• L47-68 tokens/…/make_offer.rs• L14-30 tokens/…/make_offer.rs• L47-57
Offer settlement
The taker settles an offer by sending the wanted token directly to the maker. The program then releases all tokens in the offer vault to the taker and closes the vault and offer record. These transfers occur within one instruction, so a failed leg does not leave a completed one-sided trade.
The escrow has no market price or partial fill path. Each offer describes one exchange of fixed amounts. The native and Pinocchio paths keep the same order: validate the recorded maker and mints, take the taker's payment, release the vault, and close the completed offer.
References: tokens/…/lib.rs• L28-31 tokens/…/take_offer.rs• L15-75 tokens/…/take_offer.rs• L77-129 tokens/…/take_offer.rs• L43-77 tokens/…/take_offer.rs• L102-128 tokens/…/take_offer.rs• L43-77 tokens/…/take_offer.rs• L102-128 tokens/…/test_escrow.rs• L169-201
Offer refund
The maker can cancel an open offer and recover the tokens in its vault. The refund requires the maker to sign and closes both the custody account and the offer record. The example has no time limit, so the maker remains responsible for deciding when an unfilled offer should end.
The native and Pinocchio paths verify the maker, the offer PDA, the vault, and the maker's receiving token account before returning funds. This keeps a refund tied to the offer that holds the assets rather than to any substitute account.
References: tokens/…/lib.rs• L33-35 tokens/…/refund_offer.rs• L10-44 tokens/…/refund_offer.rs• L46-87 tokens/…/refund_offer.rs• L42-70 tokens/…/refund_offer.rs• L72-115 tokens/…/refund_offer.rs• L32-73 tokens/…/refund_offer.rs• L75-94 tokens/…/test_escrow.rs• L203-230
Pool-based token swaps
The token-swap example replaces a two-party promise with shared liquidity. Liquidity providers place two tokens in a pool. Traders exchange one reserve asset for the other, and the pool uses a constant-product rule to calculate the output.
Pool lifecycle
An AMM configuration defines an administrator and a trading fee. A pool then binds one AMM to an ordered pair of token mints. The pool authority owns the two reserve accounts and the mint that issues pool-share tokens.
The lifecycle has three stages:
- Create the AMM configuration and the token pair pool.
- Deposit both assets in the pool and receive pool-share tokens.
- Swap against the reserves or burn pool-share tokens to withdraw a proportional share.
The pool-share token is the provider's claim on the reserves. It connects deposit accounting to later withdrawal without recording a separate position for every provider.
References: tokens/…/lib.rs• L11-43 tokens/…/state.rs• L3-35 tokens/…/create_pool.rs• L12-19 tokens/…/create_pool.rs• L21-99
Liquidity provision
The first deposit establishes the reserve relationship. Later deposits are adjusted to match the current reserve ratio, which keeps each provider's pool share aligned with the assets supplied. The program mints pool-share tokens after both deposits reach the pool.
The first deposit also leaves a minimum amount of liquidity locked. This prevents the pool from representing a completely removable initial reserve.
References: tokens/…/deposit_liquidity.rs• L13-80 tokens/…/deposit_liquidity.rs• L82-129 tokens/…/constants.rs• L3-10
Trade settlement
The trader requests an input amount and states the least output they will accept. The program uses no more than the input token balance available to the trader, applies the AMM fee to the amount used for pricing, and calculates the output from the reserve ratio. It then transfers the input into the pool and the calculated output from the pool to the trader.
This diagram shows the custody path and settlement checks for one swap.
flowchart LR
T[Trader token account] -->|input amount used| P[Pool reserve]
P -->|calculated output| T
F[AMM fee] --> P
G[Minimum output condition] --> S{Settlement check}
S -->|pass| C[Trade completes]
S -->|fail| R[Transaction rejects]
C --> I[Reserve invariant check]
I -->|pass| D[Balances settle]
I -->|fail| R
The output floor protects the trader from a worse result than the quoted limit. A post-trade reserve check protects the pool's pricing model from an invalid balance change. Checked arithmetic rejects values that cannot be calculated safely.
References: tokens/…/swap_exact_tokens_for_tokens.rs• L13-61 tokens/…/swap_exact_tokens_for_tokens.rs• L63-140 tokens/…/errors.rs• L3-21 tokens/…/test_token_swap.rs• L357-384
Liquidity withdrawal
A liquidity provider burns pool-share tokens to withdraw a proportional amount of both reserves. The pool authority signs the two reserve transfers, while the provider signs the burn. This makes the share token the input that authorizes the provider's claim without giving the provider direct control of the pool accounts.
References: tokens/…/withdraw_liquidity.rs• L12-75 tokens/…/withdraw_liquidity.rs• L78-177
Fundraising
The fundraiser example manages a target amount of one token over a fixed duration. The maker creates the campaign. Contributors send tokens to a fundraiser vault, and each contributor has a separate record so the program can return that contributor's amount if the target is not met.
Campaign setup
The fundraiser record stores the maker, the token mint, the target, the amount raised so far, the start time, and the duration. The vault is owned by the fundraiser PDA, so neither the maker nor a contributor can move campaign funds directly.
The target must meet a minimum size. Each contributor is limited to a percentage of the target, which prevents one contributor from filling the campaign alone.
References: tokens/…/initialize.rs• L15-38 tokens/…/initialize.rs• L40-61 tokens/…/constants.rs• L1-5
Contribution accounting
A contribution moves tokens from the contributor's token account to the fundraiser vault. The program updates both the campaign total and the contributor's personal record in the same operation.
Contributions are accepted only while the campaign is active. The program also checks the contribution size and the contributor's accumulated cap before it moves any tokens.
References: tokens/…/contribute.rs• L20-54 tokens/…/contribute.rs• L56-107 tokens/…/contributor.rs• L3-7
Target settlement
The maker can claim the vault when its balance reaches the target. The program transfers the full vault balance to the maker's token account and closes the fundraiser record. This path depends on the target condition. It does not require the campaign duration to end first.
References: tokens/…/checker.rs• L18-47 tokens/…/checker.rs• L49-82
Failed campaign refund
If the duration ends before the target is met, a contributor can reclaim the amount stored in that contributor's record. The refund transfers from the fundraiser vault, reduces the campaign total, and closes the contributor record. A refund before the deadline is rejected, and a refund is also rejected when the target was met.
This gives contributors a clear settlement rule: success pays the maker, while an expired shortfall returns each recorded contribution.
References: tokens/…/refund.rs• L18-52 tokens/…/refund.rs• L54-99 tokens/…/error.rs• L3-20
Related token workflows
This page is a child of Token program workflows. Read Core token minting and transfer operations for the token account and authority model used by these examples. Read Token-2022 extension patterns when a token's transfer rules or account extensions affect custody. Read NFT operations and Merkle token claims for token distribution flows that use ownership or proof checks instead of negotiated settlement.
Change checklist
When these files or sections are changed, remember to consider these:
- Keep every custody account's mint and authority aligned with the settlement path. A mismatch can make funds unrecoverable or allow the wrong asset to move.
- Keep the escrow offer terms aligned with its PDA seeds and vault. Changes to offer identity or mint binding affect take and refund paths in every escrow program variant.
- Keep account validation aligned across the Anchor, native, and Pinocchio escrow paths. A weaker check in one path can accept a substitute offer, vault, or receiving account.
- Keep pool pricing, fee treatment, input-balance handling, output limits, and reserve checks consistent. A change in one part can alter trader output or provider share value.
- Keep fundraiser target, duration, contributor cap, and refund conditions aligned. Contributors rely on these conditions to know whether funds are claimable or refundable.
- Keep per-participant records synchronized with vault movements. A stale contributor or pool-share record can cause an incorrect settlement amount.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Escrow taker payment is missing or below the wanted amount | The offer does not complete and the vault is not released | The taker path transfers the wanted amount before it releases the offered vault balance |
| Escrow account, vault, or receiving token account does not match the recorded offer | The native or Pinocchio path rejects the request rather than moving funds through a substitute account | The paths re-derive the offer PDA and check the canonical token-account relationships |
| Escrow maker cancels an offer that has already been taken | The refund account constraints no longer match an open offer | Offer settlement closes the offer and vault together |
| Swap request exceeds the trader's input-token balance | The program uses the available balance instead of the requested amount, which can produce less output than the caller expected | The caller must set a suitable minimum output for the amount that can be used |
| Swap output is below the trader's minimum | The trade rejects rather than accepting an unexpected price | min_output_amount is checked before reserve transfers |
| Reverse-direction swap maps input and output accounts incorrectly | The trade can move the wrong token amounts or fail | Keep the pricing direction and both transfer directions tied to the same asset pair |
| Post-trade reserve check uses the wrong reserve expression | A valid trade may fail or an invalid balance change may pass the guard | Compare the post-trade product of reserve A and reserve B with the pre-trade product |
| Arithmetic exceeds the supported range | The swap rejects instead of settling an unsafe amount | Checked multiplication, division, subtraction, and addition return MathOverflow |
| First pool deposit is too small | No usable pool share is issued | A minimum initial liquidity rule applies |
| Contribution exceeds the campaign or contributor limit | The vault and accounting remain unchanged | Contribution size, duration, and per-contributor checks run before transfer |
| Refund is requested before the fundraiser ends | The contributor cannot withdraw early | The refund requires the duration to have elapsed |
| Fundraiser target is not met at claim time | The maker cannot take the vault | The claim path requires the vault balance to reach the target |
Key files
| File | Why to read it |
|---|---|
| tokens/…/lib.rs | Shows the three escrow entry points and their order of operations |
| tokens/…/offer.rs | Defines the terms that bind an offer to its maker and token pair |
| tokens/…/take_offer.rs | Shows atomic two-sided settlement and vault closure |
| tokens/…/refund_offer.rs | Shows maker-controlled recovery of open escrow funds |
| tokens/…/test_escrow.rs | Verifies offer custody, settlement, refund, and maker authorization |
| tokens/…/lib.rs | Shows the native escrow instruction boundary |
| tokens/…/make_offer.rs | Shows native offer creation and deposit into PDA custody |
| tokens/…/take_offer.rs | Shows native two-sided settlement and account closure |
| tokens/…/refund_offer.rs | Shows native maker recovery and account validation |
| tokens/…/make_offer.rs | Shows the low-level escrow creation flow and PDA checks |
| tokens/…/take_offer.rs | Shows low-level payment, release, and closure order |
| tokens/…/refund_offer.rs | Shows low-level refund custody checks |
| tokens/…/lib.rs | Shows the pool lifecycle exposed to clients |
| tokens/…/state.rs | Defines AMM and pool relationships |
| tokens/…/swap_exact_tokens_for_tokens.rs | Shows fee-aware pricing, available-balance handling, output protection, and reserve settlement |
| tokens/…/errors.rs | Defines the swap guards for output, invariant, and arithmetic failures |
| tokens/…/test_token_swap.rs | Verifies pool setup, liquidity limits, both swap directions, and withdrawal |
| tokens/…/deposit_liquidity.rs | Shows how provider deposits become pool-share claims |
| tokens/…/withdraw_liquidity.rs | Shows proportional reserve withdrawal and share burning |
| tokens/…/fundraiser.rs | Defines campaign state and settlement inputs |
| tokens/…/contribute.rs | Shows contributor custody and accounting updates |
| tokens/…/checker.rs | Shows successful target settlement to the maker |
| tokens/…/refund.rs | Shows failed-campaign refunds and their time checks |