DEV Community

Cover image for escrow: a two-party token swap on Solana in Anchor, and what it teaches about PDAs
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

escrow: a two-party token swap on Solana in Anchor, and what it teaches about PDAs

Two people want to swap tokens. Alice has token A and wants token B. Bob has B and wants A. Whoever sends first has to trust the other to send back. The classic answer is an escrow: a neutral party holds one side until the other side arrives, then releases both.

On a blockchain, the neutral party can be a program. That is why the escrow is a common early exercise on Solana: it is small, and it forces you to learn how a program can own tokens and sign for them. escrow is my version, a two-party token swap escrow in Anchor 1.2, written with token_interface so it works with both SPL Token and Token-2022.

The warning from the README first: not audited, devnet / localnet only. This is a learning project. Do not deploy it to mainnet or use it with real funds.

What it does

The whole flow fits in three lines:

maker ──make(deposit A, want B, deadline)──▶ vault (ATA of mint A, owned by the escrow PDA)
taker ──take()──▶ B goes to the maker, all of the vault goes to the taker, vault + escrow closed
maker ──refund()──▶ A goes back to the maker, vault + escrow closed
Enter fullscreen mode Exit fullscreen mode

There are two accounts behind it:

account address holds
Escrow PDA ["escrow", maker, seed.to_le_bytes()] maker, mint_a, mint_b, deposit, receive, expires_at, bump
vault ATA(mint_a, owner = escrow PDA) the deposited mint-A tokens

The seed is chosen by the maker, so one maker can have many open offers.

And three instructions:

  • make(seed, deposit, receive, expires_at) validates that the amounts are greater than 0 and that the two mints differ. expires_at is either 0 (no deadline) or in the future. It inits the escrow and the vault, then moves the deposit in with transfer_checked.
  • take() fails after expires_at. The taker sends receive of mint B to the maker; maker_ata_b is created if needed and paid for by the taker. The escrow PDA then signs a transfer of the whole vault to the taker and closes the vault, and close = maker returns the escrow's rent to the maker.
  • refund() is for the maker only and works at any time, including after expiry.

How to use it

Clone the repository, build, and run the tests:

git clone https://github.com/AbdeldjalilChougui/escrow.git
cd escrow
anchor build    # or: anchor build --tools-version v1.58 (whatever platform-tools you have)
cargo test      # LiteSVM, no validator
Enter fullscreen mode Exit fullscreen mode

There is no front end. The way to explore the program is to read the tests in programs/escrow/tests/escrow.rs and change them: move the clock past the deadline, swap in another mint, sign with another wallet, and see which constraint stops you.

What I built from scratch

The program is small on purpose. Each piece exists to answer one question.

Where do the tokens wait? In a vault: an associated token account for mint A whose owner is the escrow PDA. Nobody holds a private key for that owner. Only the program can produce its signature, and only inside an instruction that derives the same seeds.

Who can move them out? Two paths only. take moves the whole vault to the taker after the taker has paid. refund moves it back to the maker. In both, the escrow PDA signs the transfer.

What is left behind? Nothing. Both paths close the vault and the escrow account. The rent goes back to the maker.

Which token program? Either one. Using token_interface means the same instructions accept SPL Token and Token-2022 mints.

What I learned

A PDA is a signer without a key. This is the idea the escrow exists to teach. The vault's owner is an address derived from ["escrow", maker, seed]. When take or refund runs, the program signs the transfer with those seeds. The rules for when that signature is given are the escrow.

has_one pins the terms of the deal. The escrow account stores the maker, mint_a and mint_b. has_one = maker, mint_a, mint_b on take stops anyone from swapping in another mint. Without it, a taker could try to pay in a worthless token and take the vault.

Seeds are an access check. The escrow address includes the maker's key. A stranger who calls refund signs with a different key, so the seeds derived from that signer do not match the account, and the call fails with ConstraintSeeds. No explicit "is this the maker" comparison is needed for that case.

Atomicity is the safety net. If the taker does not have enough of mint B, the transaction fails as a whole. The vault is untouched. There is no state where B was partly paid or A partly released, because a Solana transaction either applies fully or not at all.

Deadlines need boundary tests. "Fails after expires_at" leaves a question: what about exactly at expires_at? The tests pin it down using the LiteSVM Clock sysvar: taking exactly at the deadline succeeds, and taking after it fails.

The full suite:

test checks
make_then_take balances on both sides, vault + escrow closed, maker gets the rent back
maker_can_refund full refund, accounts closed
stranger_cannot_refund wrong signer: the seeds derived from a non-maker signer don't match (ConstraintSeeds)
take_after_deadline_fails / take_exactly_at_deadline_succeeds deadline boundary, using the LiteSVM Clock sysvar
make_validates_inputs zero amount, past deadline, deposit larger than the balance
taker_without_enough_mint_b_fails_atomically the transaction rolls back and the vault is untouched
take_with_mismatched_mint_fails wrong mint: has_one = mint_b

Supporting Token-2022 is more than changing a type. token_interface makes the program accept Token-2022 mints, but it does not make every Token-2022 feature safe. The README is explicit: transfer-fee Token-2022 mints would deliver less than receive, and a real program would check the received amount. Accepting a newer token standard means thinking about its extensions too.

Things to know

  • Not audited. Devnet / localnet only. Do not deploy to mainnet or use with real funds.
  • Takes are all-or-nothing. There are no partial fills.
  • Transfer-fee Token-2022 mints would deliver less than receive to the maker. This program does not check the received amount.
  • refund works at any time, so the maker can cancel an offer before anyone takes it. The deadline only limits the taker.
  • The tests run in LiteSVM with no validator. The README describes no devnet deployment.

Why I built it

The escrow is the smallest program in which a Solana program holds someone's tokens and decides when to release them. Counters and to-do lists teach accounts; this teaches custody. I wanted my own version, with the deadline, the refund path and Token-2022 support, and above all with tests for the unfriendly cases: the wrong signer, the wrong mint, the late taker and the underfunded taker. Writing the attack as a test, and seeing which constraint rejects it, is how the constraints stopped being boilerplate for me.

Get the code

The program and the LiteSVM tests are on GitHub: https://github.com/AbdeldjalilChougui/escrow. It is MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)