From 9206154eb5746ccaff8335afd71d478b5820f606 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 11 Jul 2026 19:31:26 +0000 Subject: [PATCH 1/2] docs: FAQ sections and searchable H1s for finance example READMEs Each finance example directory is its own indexable page, so every finance README now titles itself 'Solana ()' and opens with a self-contained definition. The anchor variants gain FAQ sections written as the questions people actually ask, answering with the real instruction handler names. The root README gains a general FAQ, an explicit toolchain-currency line, and loses its em-dashes. --- README.md | 32 +++++++++++++-- finance/betting-market/anchor/README.md | 18 +++++++- finance/betting-market/quasar/README.md | 6 +-- finance/escrow/anchor/README.md | 20 ++++++++- finance/escrow/native/README.md | 2 +- finance/escrow/quasar/README.md | 4 +- finance/lending/anchor/README.md | 22 +++++++++- finance/lending/quasar/README.md | 2 +- finance/order-book/anchor/README.md | 24 +++++++++-- finance/order-book/quasar/README.md | 4 +- finance/perpetual-futures/anchor/README.md | 22 +++++++++- finance/perpetual-futures/quasar/README.md | 4 +- finance/prop-amm/anchor/README.md | 48 +++++++++++++++------- finance/prop-amm/quasar/README.md | 4 +- finance/token-fundraiser/anchor/README.md | 18 +++++++- finance/token-fundraiser/quasar/README.md | 4 +- finance/token-swap/anchor/README.md | 18 +++++++- finance/token-swap/quasar/README.md | 4 +- finance/vault-strategy/anchor/README.md | 16 +++++++- finance/vault-strategy/quasar/README.md | 4 +- 20 files changed, 224 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 0b08be1e..1f1c413e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ _Solana program examples ('smart contracts') in Anchor, Quasar, Pinocchio, native Rust, and sBPF assembly. Focused on financial software ('DeFi'), plus the basics, tokens, Token Extensions, state compression, and more._ -Working, tested, up-to-date examples of common Solana programs (what other chains call smart contracts), maintained by [Quicknode](https://www.quicknode.com/chains/solana). Every example builds and passes CI on a current toolchain — **Anchor 1.1**, the current multi-file program layout (one file per instruction handler, account type, etc), and [LiteSVM](https://github.com/LiteSVM/litesvm) tests rather than the older `solana-test-validator` / web3.js stack. +Working, tested, up-to-date examples of common Solana programs (what other chains call smart contracts), maintained by [Quicknode](https://www.quicknode.com/chains/solana). Current as of July 2026 (see [CHANGELOG.md](./CHANGELOG.md)): every example builds and passes CI on **Anchor 1.1**, the current multi-file program layout (one file per instruction handler, account type, etc), and [LiteSVM](https://github.com/LiteSVM/litesvm) tests rather than the older `solana-test-validator` / web3.js stack. [![Anchor](../../actions/workflows/anchor.yml/badge.svg)](../../actions/workflows/anchor.yml) [![Quasar](../../actions/workflows/quasar.yml/badge.svg)](../../actions/workflows/quasar.yml) [![Pinocchio](../../actions/workflows/pinocchio.yml/badge.svg)](../../actions/workflows/pinocchio.yml) [![Native](../../actions/workflows/native.yml/badge.svg)](../../actions/workflows/native.yml) [![ASM](../../actions/workflows/solana-asm.yml/badge.svg)](../../actions/workflows/solana-asm.yml) @@ -59,7 +59,7 @@ An exchange with no order book: swaps fill instantly against a shared liquidity ### Prop AMM -A **proprietary AMM**: a market-making firm funds a venue with its own capital and quotes both sides of it, selling the base token at the oracle price plus a spread and buying it back at the oracle price minus the spread. No pricing curve, no liquidity providers, no pool shares — the operator is the only capital in the market, can re-quote or pull its quotes at will, and earns the spread instead of a fee. Because the price comes from an oracle rather than the pool's balances, trades have no price impact and nothing to sandwich. This is the design behind venues like Lifinity, SolFi, and HumidiFi, which fill most Solana swap volume through Jupiter routing. +A **proprietary AMM**: a market-making firm funds a venue with its own capital and quotes both sides of it, selling the base token at the oracle price plus a spread and buying it back at the oracle price minus the spread. No pricing curve, no liquidity providers, no pool shares: the operator is the only capital in the market, can re-quote or pull its quotes at will, and earns the spread instead of a fee. Because the price comes from an oracle rather than the pool's balances, trades have no price impact and nothing to sandwich. This is the design behind venues like Lifinity, SolFi, and HumidiFi, which fill most Solana swap volume through Jupiter routing. [⚓ Anchor](./finance/prop-amm/anchor) [💫 Quasar](./finance/prop-amm/quasar) @@ -77,7 +77,7 @@ Parimutuel (pooled) prediction market - an admin opens an event with multiple ou ### Perpetual Futures -A perpetual futures exchange — a venue for making leveraged bets on an asset's price without ever owning the asset. Traders post collateral and open a **long** (betting the price rises) or **short** (betting it falls) sized up to several times their collateral; their profit or loss tracks the price move and is paid in the collateral token. Rather than matching buyers to sellers, every trade is against a shared **liquidity pool** that other users fund and that is the counterparty to all of it — the pool pays winners and keeps losers' collateral, and its providers earn the trading and funding fees in return. The price comes from an oracle, positions accrue a funding fee over time, and anyone can **liquidate** a position whose collateral can no longer cover its loss. This is the design behind venues like Jupiter Perpetuals and GMX. +A perpetual futures exchange: a venue for making leveraged bets on an asset's price without ever owning the asset. Traders post collateral and open a **long** (betting the price rises) or **short** (betting it falls) sized up to several times their collateral; their profit or loss tracks the price move and is paid in the collateral token. Rather than matching buyers to sellers, every trade is against a shared **liquidity pool** that other users fund and that is the counterparty to all of it: the pool pays winners and keeps losers' collateral, and its providers earn the trading and funding fees in return. The price comes from an oracle, positions accrue a funding fee over time, and anyone can **liquidate** a position whose collateral can no longer cover its loss. This is the design behind venues like Jupiter Perpetuals and GMX. [⚓ Anchor](./finance/perpetual-futures/anchor) [💫 Quasar](./finance/perpetual-futures/quasar) @@ -385,6 +385,32 @@ Generate an IDL from a native Rust program with [Shank](https://github.com/metap [🦀 Native](./tools/shank-and-codama/native) +## FAQ + +### Is a Solana program the same as a smart contract? + +Yes. "Program" is Solana's term for what other chains call a smart contract: code deployed onchain that holds state in accounts and executes instructions. Everything in this repository is a Solana program. + +### How do I build an escrow on Solana? + +Start with the [escrow example](./finance/escrow/anchor/), the best first finance program to learn: one state PDA, one vault, and three instruction handlers that swap two tokens atomically. There is also a [30-minute video walkthrough](https://www.youtube.com/watch?v=B5eBWWQfQuM) building it from scratch. + +### How do I test a Solana program without running a validator? + +Use [LiteSVM](https://www.anchor-lang.com/docs/testing/litesvm): Rust integration tests that run the program in-process, orders of magnitude faster than `solana-test-validator`. Every example in this repository tests this way, and `anchor init` scaffolds it by default since Anchor 1.0. + +### What is the difference between Anchor, Quasar, Pinocchio, and native Rust? + +[Anchor](https://www.anchor-lang.com/) is the most popular Solana framework, generating account validation and serialization from declarative constraints. [Quasar](https://quasar-lang.com/docs) offers Anchor-like ergonomics with zero-copy, `no_std` performance and smaller binaries. [Pinocchio](https://github.com/anza-xyz/pinocchio) is a zero-allocation library for hand-rolled programs, and native Rust uses Solana's crates directly with no framework. Most examples here ship several variants of the same program so you can compare. + +### What is the best way to learn Solana finance programming? + +Work through the [finance examples](#financial-software-defi) in order of complexity: [escrow](./finance/escrow/anchor/), then [token swap AMM](./finance/token-swap/anchor/), [order book](./finance/order-book/anchor/), [lending](./finance/lending/anchor/), and [perpetual futures](./finance/perpetual-futures/anchor/). Each README explains the financial mechanics in plain terms before the code. + +### Are these examples production-ready? + +They are teaching examples: every one builds and passes CI, and the finance programs additionally carry [Kani](https://github.com/model-checking/kani) formal-verification proofs of their money math. None are audited or deployed to mainnet, so treat them as reference implementations to learn from, not code to deploy as-is. + ## Acknowledgements Big thanks to Joe Caulfield and Solana Foundation for originally creating this repository. diff --git a/finance/betting-market/anchor/README.md b/finance/betting-market/anchor/README.md index d85417af..63202fbb 100644 --- a/finance/betting-market/anchor/README.md +++ b/finance/betting-market/anchor/README.md @@ -1,6 +1,6 @@ -# Betting Market +# Solana Betting Market (Anchor) -A parimutuel (pooled) betting market. An admin opens an **event**, adds the possible +A parimutuel (pooled) betting market on Solana. An admin opens an **event**, adds the possible **outcomes**, and bettors stake a token on the outcome they think will win. Every stake across every outcome goes into one pool. When the admin settles the event to the winning outcome, the losing stakes - minus a protocol fee - are split among the winners in proportion to their stake. @@ -116,3 +116,17 @@ anchor test ``` (`Anchor.toml` sets `test = "cargo test"`, so `cargo test` works too.) + +## FAQ + +### How does a prediction market work on Solana? + +This example uses the parimutuel (pooled) model: an admin opens an event with `create_event` and `add_outcome`, and bettors stake tokens on an outcome with `place_bet`. Every stake goes into one pool; after `settle_event` names the winning outcome, winners call `claim_winnings` to split the losing stakes, minus a protocol fee, in proportion to their own stake. + +### How are the odds set? + +By the crowd, not a bookmaker: each winner's payout scales with their share of the winning pool, so the implied odds shift as stakes arrive. This is the model used by Solana prediction-market platforms such as Hedgehog Markets and by racetrack tote boards. + +### What happens if an event is cancelled? + +The admin calls `cancel_event` and every bettor reclaims their full stake with `claim_refund`. After a settled event, losers reclaim their bet account's rent with `close_losing_bet`. diff --git a/finance/betting-market/quasar/README.md b/finance/betting-market/quasar/README.md index a8e30b4f..0cb993b6 100644 --- a/finance/betting-market/quasar/README.md +++ b/finance/betting-market/quasar/README.md @@ -1,6 +1,6 @@ -# Betting Market, Quasar port +# Solana Betting Market (Quasar) -A parimutuel betting market. An admin opens events (markets), adds the possible +A parimutuel betting market on Solana, written with Quasar. An admin opens events (markets), adds the possible outcomes, and later settles or cancels each one. Bettors stake a fixed token on the outcome they think will happen; when the event is settled, the winners split the losing side's stakes in proportion to their own, after a protocol fee. This @@ -107,7 +107,7 @@ cargo test # QuasarSVM integration tests (they load the compiled .so) [QuasarSVM](https://github.com/blueshift-gg/quasar-svm), an in-process SVM. The suite in `src/tests.rs` drives the full lifecycle (open a market, add outcomes, place opposing bets, settle, claim the winnings, close the losing bet) and the -cancel-and-refund path, asserting on-chain state, token balances, and fee +cancel-and-refund path, asserting onchain state, token balances, and fee accounting at each step, plus an admin-authorization rejection. ## Extending diff --git a/finance/escrow/anchor/README.md b/finance/escrow/anchor/README.md index 04eca86f..e88da57c 100644 --- a/finance/escrow/anchor/README.md +++ b/finance/escrow/anchor/README.md @@ -1,4 +1,4 @@ -# Anchor Escrow +# Solana Escrow (Anchor) This Solana [program](https://solana.com/docs/terminology#program) is an **escrow** - it lets a **maker** swap a specific amount of one token for a desired amount of another token with a **taker**, atomically and without either party having to trust the other. @@ -41,6 +41,24 @@ cargo test (`anchor test` runs the same command, per `Anchor.toml`.) The tests cover the make/take flow, the make/cancel flow, rejection of a non-maker cancel, token balances on every leg, and the rent refunds (the maker's lamports recover the offer and vault rent after both take and cancel). +## FAQ + +### How does an escrow work on Solana? + +A Solana escrow is a program that holds a maker's tokens in a program-controlled vault until a taker delivers the tokens the maker asked for, then releases both sides in one atomic transaction. This example implements the whole lifecycle in three instruction handlers: `make_offer`, `take_offer`, and `cancel_offer`. + +### Is this a good first Solana finance program to learn? + +Yes. Escrow is the smallest complete finance program: one state PDA, one vault, three instruction handlers, and the atomic swap idea that underlies every onchain exchange. Start here before the [AMM](../../token-swap/anchor/), [order book](../../order-book/anchor/), and [lending](../../lending/anchor/) examples. + +### How do I run and test this escrow example? + +Build with `anchor build`, then run `cargo test`. The tests are Rust integration tests against [LiteSVM](https://www.anchor-lang.com/docs/testing/litesvm), so no local validator is needed. + +### How is this escrow program verified? + +Two ways: LiteSVM integration tests covering the make, take, and cancel flows, and [Kani](https://github.com/model-checking/kani) proofs in [`../kani-proofs/`](../kani-proofs/) that check the money-math invariants over all possible inputs, not just test cases. + ## Credit Based on [Dean Little's Anchor Escrow](https://github.com/deanmlittle/anchor-escrow-2024), restructured for teaching. diff --git a/finance/escrow/native/README.md b/finance/escrow/native/README.md index 961f11b9..29e90181 100644 --- a/finance/escrow/native/README.md +++ b/finance/escrow/native/README.md @@ -1,4 +1,4 @@ -# Escrow (Native) +# Solana Escrow (Native) This Solana program is an **escrow** written directly against `solana-program`, with no framework. It lets a **maker** swap a specific amount of one token for a desired amount of another token with a **taker**, atomically and without either party having to trust the other. diff --git a/finance/escrow/quasar/README.md b/finance/escrow/quasar/README.md index 4df24634..5f36e221 100644 --- a/finance/escrow/quasar/README.md +++ b/finance/escrow/quasar/README.md @@ -1,6 +1,6 @@ -# Escrow (Quasar) +# Solana Escrow (Quasar) -Atomic token swap escrow between maker and taker. +An atomic token swap escrow on Solana, written with Quasar: the program holds a maker's tokens in a vault until a taker delivers the tokens the maker asked for, then releases both sides in one transaction. See also: the [repository catalog](../../../README.md). diff --git a/finance/lending/anchor/README.md b/finance/lending/anchor/README.md index a6a131a4..b499d81e 100644 --- a/finance/lending/anchor/README.md +++ b/finance/lending/anchor/README.md @@ -1,6 +1,6 @@ -# Lending +# Solana Lending (Anchor) -A Kamino/Solend-style borrow/lend program: suppliers earn interest on deposits, +A Kamino/Solend-style borrow/lend program on Solana: suppliers earn interest on deposits, borrowers post collateral and draw other assets against it, and liquidators keep the market solvent. It demonstrates the techniques the most-used Solana lending protocols share: share-token deposit accounting, a utilization-based interest @@ -173,3 +173,21 @@ anchor test # or: cargo test - runs the LiteSVM integration tests non-happy-path branches: interest accrual, borrowing at the LTV limit, stale reserve/price rejection, liquidation of an unhealthy obligation after a price move, the share-inflation guard, and rounding edges. + +## FAQ + +### How does a lending protocol work on Solana? + +Suppliers deposit a token with `deposit_reserve_liquidity` and receive share tokens that grow in value as borrowers pay interest. Borrowers post those shares as collateral (`deposit_obligation_collateral`) and draw a different token with `borrow_obligation_liquidity`, up to a loan-to-value limit. When a position's collateral no longer covers its debt, anyone can call `liquidate_obligation` to repay part of the debt in exchange for discounted collateral. + +### How does interest accrue without looping over every account? + +Through a cumulative interest index: `refresh_reserve` advances a per-reserve index along a utilization-based rate curve, and each obligation stores the index value from its last interaction. The gap between the two is the interest owed, so no per-account accrual loop is needed. This is the same technique the most-used Solana lending protocols share. + +### How are prices fed into the protocol? + +The admin `set_price` instruction handler stands in for an oracle feed in this example. `refresh_obligation` re-values collateral and debt at those prices before any borrow, withdraw, or liquidation is allowed, and stale reserves or prices are rejected. + +### How is this lending program tested and verified? + +`anchor build` then `cargo test` runs LiteSVM integration tests covering interest accrual, borrowing at the LTV limit, liquidation after a price move, and the share-inflation guard. The money math also has [Kani](https://github.com/model-checking/kani) proofs in [`../kani-proofs/`](../kani-proofs/). diff --git a/finance/lending/quasar/README.md b/finance/lending/quasar/README.md index 76d5a214..3ce9ba14 100644 --- a/finance/lending/quasar/README.md +++ b/finance/lending/quasar/README.md @@ -1,4 +1,4 @@ -# Lending (Quasar) +# Solana Lending (Quasar) A Kamino/Solend-style borrow/lend program written with [Quasar](https://quasar-lang.com), a zero-copy, `no_std` Solana framework. It is the Quasar counterpart to the Anchor diff --git a/finance/order-book/anchor/README.md b/finance/order-book/anchor/README.md index c836746b..4b02f583 100644 --- a/finance/order-book/anchor/README.md +++ b/finance/order-book/anchor/README.md @@ -1,8 +1,8 @@ -# Order Book: Central Limit Order Book (CLOB) Exchange +# Solana Order Book Exchange (Anchor) -This is an **[order book](https://www.investopedia.com/terms/o/order-book.asp)**: specifically, a **[central limit order +This Solana program is an **[order book](https://www.investopedia.com/terms/o/order-book.asp)** exchange: specifically, a **[central limit order book (CLOB)](https://www.investopedia.com/terms/l/limitorderbook.asp)**, the standard piece of market infrastructure used by -NYSE, NASDAQ, LSE, CME, and every crypto venues like Phoenix and Cube and OpenBook. An Anchor program that runs an onchain order book for a single pair of token mints: +NYSE, NASDAQ, LSE, CME, and crypto venues like Phoenix, Cube, and OpenBook. Written with Anchor, it runs an onchain order book for a single pair of token mints: users post buy or sell offers at the prices they want, the program matches crossing offers in price-time priority, and settles the resulting token movements. @@ -1609,3 +1609,21 @@ finance/order-book/anchor/ └── tests/ └── test_order_book.rs LiteSVM tests ``` + +## FAQ + +### How does an order book exchange work on Solana? + +Traders post limit orders with `place_order`: bids to buy and asks to sell, each at a named price. The program matches crossing orders in price-time priority, holds all funds in program-owned vaults, and pays out matched balances when a trader calls `settle_funds`. This is the same central limit order book (CLOB) design used by NYSE and by Solana venues like Phoenix and OpenBook. + +### How can order matching be fast enough onchain? + +Each side of the book is a critbit tree, so finding the best price takes O(log n) comparisons instead of a full scan; at 1024 resting orders that is at most 10 steps. The implementation is ported from [Openbook v2](https://github.com/openbook-dex/openbook-v2), a production Solana CLOB. + +### Why are matching and settlement separate steps? + +A taker crossing many makers would otherwise pay for a token transfer CPI per maker. Instead, fills only update the `unsettled_base` and `unsettled_quote` counters, and one later `settle_funds` call moves the tokens. Cancelling with `cancel_order` works the same way: it credits the counters, and the tokens move at settlement. + +### How does the exchange operator earn fees? + +Every fill charges the taker a fee in basis points, batched into a fee vault during `place_order`. The market authority sweeps it with `withdraw_fees`. diff --git a/finance/order-book/quasar/README.md b/finance/order-book/quasar/README.md index 445c5a34..1aec2327 100644 --- a/finance/order-book/quasar/README.md +++ b/finance/order-book/quasar/README.md @@ -1,6 +1,6 @@ -# Order Book: Central Limit Order Book (CLOB), Quasar port +# Solana Order Book Exchange (Quasar) -A [central limit order book (CLOB)](https://www.investopedia.com/terms/l/limitorderbook.asp), the market +A [central limit order book (CLOB)](https://www.investopedia.com/terms/l/limitorderbook.asp) on Solana, the market structure NYSE, NASDAQ, CME, and onchain venues like Phoenix and OpenBook run on. Users post buy or sell offers at prices they pick; the program matches crossing offers in **price-time priority** and settles the resulting token movements. diff --git a/finance/perpetual-futures/anchor/README.md b/finance/perpetual-futures/anchor/README.md index 709042f6..e7bf4d64 100644 --- a/finance/perpetual-futures/anchor/README.md +++ b/finance/perpetual-futures/anchor/README.md @@ -1,6 +1,6 @@ -# Perpetual Futures +# Solana Perpetual Futures (Anchor) -A perpetual futures exchange: a venue for making leveraged bets on an asset's price without ever owning the asset. It is modelled on the oracle-priced, pool-collateralized design used by [Jupiter Perpetuals](https://station.jup.ag/guides/perpetual-exchange/overview) and GMX (and the open-source [`solana-labs/perpetuals`](https://github.com/solana-labs/perpetuals) reference that [Adrena](https://github.com/AdrenaFoundation/adrena-program) and [Flash Trade](https://github.com/flash-trade/flash-perpetuals) fork), rather than the order-book design used by [Drift](https://docs.drift.trade/). +A perpetual futures exchange on Solana: a venue for making leveraged bets on an asset's price without ever owning the asset. It is modelled on the oracle-priced, pool-collateralized design used by [Jupiter Perpetuals](https://station.jup.ag/guides/perpetual-exchange/overview) and GMX (and the open-source [`solana-labs/perpetuals`](https://github.com/solana-labs/perpetuals) reference that [Adrena](https://github.com/AdrenaFoundation/adrena-program) and [Flash Trade](https://github.com/flash-trade/flash-perpetuals) fork), rather than the order-book design used by [Drift](https://docs.drift.trade/). The collateral is **USDC** (a dollar stablecoin), and the market tracks the price of **NVDAx**, a tokenised Nvidia share whose [oracle](#oracle) price follows the real stock. A second market could track **TSLAx** (Tesla); each market is one collateral token plus one price feed. In the tests these are mock [SPL tokens](https://solana.com/docs/terminology#token). @@ -213,3 +213,21 @@ cargo test --manifest-path programs/perpetual-futures/Cargo.toml ``` `anchor build` first, so the LiteSVM tests can load each program's compiled `.so` via `include_bytes!`. + +## FAQ + +### How do perpetual futures work on Solana? + +A perp is a derivative with no expiry: traders post USDC collateral and open a leveraged long or short with `open_position`, and their profit or loss tracks an oracle price, paid in the collateral token when they `close_position`. No stock or coin ever changes hands. + +### Who is the counterparty to each trade? + +A shared liquidity pool. Providers fund it with `add_liquidity` and earn the trading and funding fees; the pool pays winners and keeps losers' collateral. This is the pool-collateralized design used by Jupiter Perpetuals and GMX, as opposed to the order-book design used by Drift. + +### How does liquidation work? + +When a position's collateral can no longer cover its loss past the maintenance margin, anyone can call `liquidate_position` to close it. Prices come from the oracle feed on every check. + +### How do I run this example? + +`anchor build`, then `cargo test --manifest-path programs/perpetual-futures/Cargo.toml`. The tests run against LiteSVM with a mock price feed (`initialize_feed`, `set_price`) to drive deterministic price scenarios. diff --git a/finance/perpetual-futures/quasar/README.md b/finance/perpetual-futures/quasar/README.md index b9e7ed98..81ec35b0 100644 --- a/finance/perpetual-futures/quasar/README.md +++ b/finance/perpetual-futures/quasar/README.md @@ -1,6 +1,6 @@ -# Perpetual Futures (Quasar) +# Solana Perpetual Futures (Quasar) -A [Quasar](https://quasar-lang.com/docs) port of the perpetual-futures example. +A [Quasar](https://quasar-lang.com/docs) port of the Solana perpetual futures example. The design, math, and behaviour match the Anchor implementation at [`../anchor`](../anchor). Read that README for the full walkthrough of the oracle-priced, pool-collateralized model, the funding mechanism, and the money diff --git a/finance/prop-amm/anchor/README.md b/finance/prop-amm/anchor/README.md index 66495e5b..7259c58e 100644 --- a/finance/prop-amm/anchor/README.md +++ b/finance/prop-amm/anchor/README.md @@ -1,8 +1,8 @@ -# Prop AMM +# Solana Prop AMM (Anchor) -An oracle-quoted **proprietary AMM**: a market-making firm funds a trading -venue with its own capital and quotes both sides of it — anyone can buy the -base token at the oracle price plus a spread, or sell at the oracle price +An oracle-quoted **proprietary AMM** on Solana: a market-making firm funds a +trading venue with its own capital and quotes both sides of it. Anyone can buy +the base token at the oracle price plus a spread, or sell at the oracle price minus it. There is no pricing curve, there are no liquidity providers, and there are no pool shares: the operator is the only capital in the market, which is the property that gives the design its name. This is the @@ -12,9 +12,9 @@ via Jupiter routing rather than their own user interfaces. ## Programs -- **`prop-amm`** — the market: one operator, one base/quote pair, one oracle +- **`prop-amm`**: the market. One operator, one base/quote pair, one oracle feed, two vaults, five instruction handlers. -- **`mock-switchboard`** — a minimal stand-in for a Switchboard On-Demand +- **`mock-switchboard`**: a minimal stand-in for a Switchboard On-Demand price feed, so tests can drive deterministic price scenarios. Not for production. @@ -28,7 +28,7 @@ all of it: the firm quotes prices taken from an oracle, earns the spread instead of a fee, and risks only its own inventory. Because the price does not depend on the pool's balances, big trades pay the same unit price as small ones (no price impact), and there is nothing for a sandwich attacker to -squeeze — the classic front-run/back-run pattern needs a price that moves +squeeze: the classic front-run/back-run pattern needs a price that moves with each trade. ### The quote: oracle, spread, bid and ask @@ -46,7 +46,7 @@ raw oracle price, never exceeds the value coming in. The vault balances are not a pricing input; they only bound what the market can deliver. A swap bigger than the inventory is rejected whole (`InsufficientInventory`) rather than partially filled or mispriced. The -operator deposits and withdraws inventory freely — including all of it, at any +operator deposits and withdraws inventory freely, including all of it, at any time. Nobody else has a claim on the vaults, so there is no share mint, no pro-rata withdrawal math, and no inflation attack surface: the empty-pool games that plague shared pools need shares to dilute, and there are none. @@ -56,7 +56,7 @@ games that plague shared pools need shares to dilute, and there are none. A market maker's enemy is informed flow: traders who know the price is about to move and hit the stale side of the quote. The two defenses this program ships are the oracle gates (below) and `set_quote`, which lets the operator -widen the spread or pause quoting entirely. Real prop AMMs do exactly this — +widen the spread or pause quoting entirely. Real prop AMMs do exactly this: during fast markets their quotes vanish and return minutes later. ### Oracle staleness and confidence @@ -92,14 +92,14 @@ nobody else to account for. ### Step 3: Alice buys 10 NVDAx at the ask At $165 with a 10 bps spread the ask is $165.165. Alice's `swap` -(`Direction::BuyBase`) spends exactly 1,651.65 USDC for 10 NVDAx — +(`Direction::BuyBase`) spends exactly 1,651.65 USDC for 10 NVDAx; whether she bought 1 or 500, the unit price would be the same. ### Step 4: Bob sells 10 NVDAx at the bid The bid is $164.835, so Bob's `swap` (`Direction::SellBase`) receives exactly 1,648.35 USDC. A round trip through both sides costs exactly the -3.30 USDC spread — the spread is the fee, and it lands in the inventory, +3.30 USDC spread: the spread is the fee, and it lands in the inventory, not in a fee ledger. ### Step 5: The oracle reprices; the quote follows @@ -117,7 +117,7 @@ AMM gets from one price to another. ### Step 7: Maria withdraws her inventory `withdraw_inventory` returns every token in both vaults to the firm. The -market still exists but rejects fills — an empty prop AMM refuses rather than +market still exists but rejects fills: an empty prop AMM refuses rather than misprices. ## Design notes and further reading @@ -125,8 +125,8 @@ misprices. - Production prop AMMs on Solana are closed-source and considerably more sophisticated: they blend multiple price sources, run inventory-skewed quoting (shading the quote to reduce a lopsided inventory), and integrate - with aggregators via quote APIs. The skeleton — operator capital, oracle - price, spread, hard oracle gates — is this program. + with aggregators via quote APIs. The skeleton (operator capital, oracle + price, spread, hard oracle gates) is this program. - Lifinity's public design notes and the Helius write-up "Solana's Proprietary AMM Revolution" are good next reads. - The oracle reader deliberately reads raw bytes at fixed offsets and @@ -135,7 +135,7 @@ misprices. ## Limitations -- The oracle feed's owning program is not verified — the operator picks the +- The oracle feed's owning program is not verified: the operator picks the feed, and a bad choice loses the operator's money, not the traders'. A production reader must still check the account owner. - One flat spread both ways; no inventory skew, no size-dependent pricing. @@ -154,3 +154,21 @@ quote math to the minor unit in both directions, the exact round-trip spread, oracle repricing and re-quoting, and that every gate shuts: slippage, staleness, confidence, pause, zero amounts, inventory bounds, and operator access control. + +## FAQ + +### What is a proprietary AMM on Solana? + +A venue where a single market-making firm supplies all the capital and quotes both sides from an oracle price plus a spread, instead of pricing from pool reserves. The operator stocks it with `deposit_inventory`, traders call `swap`, and the operator adjusts or pauses the quote with `set_quote`. Venues like Lifinity, SolFi, and HumidiFi use this design. + +### Why do trades have no price impact? + +The price comes from the oracle, not from the pool's balances, so a large swap pays the same unit price as a small one. That also removes the sandwich-attack surface: front-running only pays when each trade moves the price. + +### How does the operator make money? + +The spread is the fee: buyers pay the oracle price plus `spread_bps`, sellers receive the oracle price minus it, and the difference accumulates in the operator's inventory. There is no separate fee ledger, and `withdraw_inventory` returns everything to the firm. + +### What stops the venue from quoting a stale price? + +Every `swap` re-validates the feed: the price must be fresh (no older than 150 slots), at the pinned scale, and inside the configured confidence band. A stale quote is a free option for whoever notices first, so the staleness checks are the business model, not hygiene. diff --git a/finance/prop-amm/quasar/README.md b/finance/prop-amm/quasar/README.md index 0d3b5970..dbc500f4 100644 --- a/finance/prop-amm/quasar/README.md +++ b/finance/prop-amm/quasar/README.md @@ -1,6 +1,6 @@ -# Prop AMM (Quasar) +# Solana Prop AMM (Quasar) -A [Quasar](https://quasar-lang.com/docs) port of the prop-amm example. The +A [Quasar](https://quasar-lang.com/docs) port of the Solana prop-amm example. The design, math, and behaviour match the Anchor implementation at [`../anchor`](../anchor). Read that README for the full walkthrough of the oracle-quoted, operator-owned model. This page only covers what differs in the diff --git a/finance/token-fundraiser/anchor/README.md b/finance/token-fundraiser/anchor/README.md index d160b7e4..3b1c5a2c 100644 --- a/finance/token-fundraiser/anchor/README.md +++ b/finance/token-fundraiser/anchor/README.md @@ -1,6 +1,6 @@ -# Token Fundraiser +# Solana Token Fundraiser (Anchor) -Create a fundraiser that collects tokens. A **maker** creates a fundraiser [account](https://solana.com/docs/terminology#account), specifies the [mint](https://solana.com/docs/terminology#token-mint) they want to receive, the target amount, and a duration in days. **Contributors** contribute while the window is open. If the target is reached, the maker claims the funds; if it is not reached by the deadline, contributors can refund, and once refunds are complete the maker can retire the fundraiser and open a new one. +Onchain crowdfunding on Solana: a program that collects tokens toward a target amount, like Kickstarter without a payment processor. A **maker** creates a fundraiser [account](https://solana.com/docs/terminology#account), specifies the [mint](https://solana.com/docs/terminology#token-mint) they want to receive, the target amount, and a duration in days. **Contributors** contribute while the window is open. If the target is reached, the maker claims the funds; if it is not reached by the deadline, contributors can refund, and once refunds are complete the maker can retire the fundraiser and open a new one. ## Architecture @@ -143,3 +143,17 @@ cargo test ``` The suite uses a nonzero duration and warps the LiteSVM `Clock` sysvar to exercise both sides of every deadline: contributing inside the window succeeds, contributing after the deadline fails, refunding before the deadline fails, and refunding after the deadline succeeds when the target was not met. It exercises both contribution caps (a single contribution over the 10% cap, and contributions that cumulatively exceed it), and verifies that the claim pays the maker and closes the vault, that direct vault donations do not unlock the claim, and that `close_fundraiser` retires a failed raise (only after the deadline, only when the target was missed, only once refunds are complete, sweeping direct donations to the maker) and lets the same maker initialize a fresh fundraiser. Assertions check token balances and decoded account state rather than just transaction success. + +## FAQ + +### How do I build crowdfunding on Solana? + +A maker opens a fundraiser with `initialize`, naming the token, target amount, and duration. Contributors deposit with `contribute` while the window is open, and the funds sit in a program-controlled vault that neither side can raid. When the target is reached, the maker claims the raise with `check_contributions`, which pays out the vault and closes the fundraiser. + +### What happens if the fundraiser misses its target? + +Contributors call `refund` after the deadline to reclaim exactly what they put in. Once refunds are complete, the maker calls `close_fundraiser` to retire the failed raise and can then open a new one. + +### How is this fundraiser tested and verified? + +`anchor build` then `cargo test` runs LiteSVM tests that warp the clock across the deadline to exercise contribution windows, per-contributor caps, claims, refunds, and closing. The money math has [Kani](https://github.com/model-checking/kani) proofs in [`../kani-proofs/`](../kani-proofs/). diff --git a/finance/token-fundraiser/quasar/README.md b/finance/token-fundraiser/quasar/README.md index 03116dad..3b951126 100644 --- a/finance/token-fundraiser/quasar/README.md +++ b/finance/token-fundraiser/quasar/README.md @@ -1,6 +1,6 @@ -# Token Fundraiser (Quasar) +# Solana Token Fundraiser (Quasar) -Onchain crowdfunding toward a target amount in a chosen token, written with [Quasar](https://quasar-lang.com/docs). A **maker** opens a fundraiser with a target amount and a deadline; **contributors** deposit tokens into a program-controlled vault. If the target is met the maker withdraws everything; if the deadline passes without the target being met, each contributor reclaims exactly what they put in. +Onchain crowdfunding on Solana toward a target amount in a chosen token, written with [Quasar](https://quasar-lang.com/docs). A **maker** opens a fundraiser with a target amount and a deadline; **contributors** deposit tokens into a program-controlled vault. If the target is met the maker withdraws everything; if the deadline passes without the target being met, each contributor reclaims exactly what they put in. See also: the [repository catalog](../../../README.md) and the [Anchor variant](../anchor/) of the same program. diff --git a/finance/token-swap/anchor/README.md b/finance/token-swap/anchor/README.md index 1be6d893..55e1f30b 100644 --- a/finance/token-swap/anchor/README.md +++ b/finance/token-swap/anchor/README.md @@ -1,6 +1,6 @@ -# Token Swap (AMM) (Anchor) +# Solana Token Swap AMM (Anchor) -Constant-product AMM pool: create pools, deposit liquidity, swap with slippage guards, and withdraw. +A constant-product AMM (automated market maker) on Solana: create pools, deposit liquidity, swap with slippage guards, and withdraw. This is the exchange design behind Solana venues like Raydium and Orca. See also: [Token Swap overview](../README.md) and the [repository catalog](../../../README.md). @@ -33,3 +33,17 @@ This runs `cargo test` as configured in `Anchor.toml`. Tests call instruction ha ## Usage Read the program `programs/` source and `Anchor.toml` for deployed program IDs. For deployment, use `anchor build && anchor deploy` against your target cluster. + +## FAQ + +### How does an AMM work on Solana? + +An automated market maker replaces the order book with a liquidity pool: anyone can create a pool with `create_pool`, fund it with `deposit_liquidity`, and trade against it with `swap_tokens`. Prices come from the constant-product invariant on the pool's balances, and liquidity providers earn a share of trading fees. Solana exchanges like Raydium and Orca use this design. + +### How is slippage handled? + +`swap_tokens` takes a `min_output_amount` guard: if the pool's balances move so the trade would return less than that minimum, the transaction fails instead of filling at a worse price. + +### Where is the full walkthrough for this example? + +The example-level [Token Swap overview](../README.md) covers the pool math, LP tokens, and lifecycle; this page covers the Anchor build and test commands. The money math has [Kani](https://github.com/model-checking/kani) proofs in [`../kani-proofs/`](../kani-proofs/). diff --git a/finance/token-swap/quasar/README.md b/finance/token-swap/quasar/README.md index e1621f4e..6bf03301 100644 --- a/finance/token-swap/quasar/README.md +++ b/finance/token-swap/quasar/README.md @@ -1,6 +1,6 @@ -# Token Swap (AMM) (Quasar) +# Solana Token Swap AMM (Quasar) -Constant-product AMM: pools, liquidity, swaps with slippage guards. +A constant-product AMM on Solana, written with Quasar: pools, liquidity, swaps with slippage guards. See also: [Token Swap overview](../README.md) and the [repository catalog](../../../README.md). diff --git a/finance/vault-strategy/anchor/README.md b/finance/vault-strategy/anchor/README.md index 63f1b025..512c1705 100644 --- a/finance/vault-strategy/anchor/README.md +++ b/finance/vault-strategy/anchor/README.md @@ -1,4 +1,4 @@ -# Vault Strategy +# Solana Vault Strategy (Anchor) A manager-run investment vault on Solana. Users deposit [USDC](https://www.investopedia.com/terms/u/usd-coin-usdc.asp) and receive shares representing proportional ownership of a portfolio of assets. The manager adds assets from a curated whitelist and sets their target weights; each deposit is deployed across those assets at its weights in the same transaction. The manager rebalances as prices drift, earns a fee, and depositors withdraw their proportional slice in kind when they choose. @@ -152,3 +152,17 @@ cargo test --manifest-path programs/vault-strategy/Cargo.toml ``` Tests live in `programs/vault-strategy/tests/vault_strategy.rs` and use [LiteSVM](https://github.com/LiteSVM/litesvm). Both `.so` files are loaded from `target/deploy/`, so build before testing. The suite covers the full lifecycle end to end (deposit with auto-deployment, a price move, rebalance back to target, a second depositor priced at the new NAV, a year's fee, in-kind withdrawal), retiring an asset with `set_weight` and reallocating to reopen deposits, and the rejection paths: non-whitelisted asset, weight overflow, over-cap fee and slippage, oracle-bounded deposit slippage, an under-allocated strategy, non-manager `set_weight`, unregistered router, and incomplete asset accounts on deposit. + +## FAQ + +### How do I build an onchain investment fund on Solana? + +A manager creates a strategy with `initialize_strategy`, registers whitelisted assets with `add_asset` at target weights, and investors `deposit` USDC for shares. Each deposit is deployed across the basket in the same transaction, and `withdraw` redeems a proportional slice of every vault in kind. + +### How are share prices calculated? + +Shares are priced at the strategy's net asset value: the total value of the vault balances at current prices divided by shares outstanding. A later depositor pays the current share price rather than diluting earlier ones. + +### How does the manager operate the fund? + +`rebalance` trades the vaults back to their target weights as prices drift, `set_weight` reweights or retires an asset, and a management fee accrues over time and is collected with `collect_fees`. diff --git a/finance/vault-strategy/quasar/README.md b/finance/vault-strategy/quasar/README.md index d274bae1..09175a5f 100644 --- a/finance/vault-strategy/quasar/README.md +++ b/finance/vault-strategy/quasar/README.md @@ -1,6 +1,6 @@ -# Vault Strategy, Quasar port +# Solana Vault Strategy (Quasar) -A tokenized multi-asset vault. A manager assembles a basket of whitelisted +A tokenized multi-asset vault on Solana, written with Quasar. A manager assembles a basket of whitelisted assets at target weights; anyone can deposit USDC and receive shares priced at the vault's net asset value, and each deposit is immediately deployed into the basket by swapping USDC into every asset at its weight. Withdrawals burn shares From 2ad6de5e690eaf977ad552134f0782535111343d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 11 Jul 2026 19:31:28 +0000 Subject: [PATCH 2/2] docs: add llms.txt and the example README template llms.txt gives LLM crawlers and answer engines a summary and link manifest for the finance examples. docs/example-readme-template.md is the template CONTRIBUTING.md already referenced but which did not exist; it records the H1 convention and definition-first opener. CONTRIBUTING.md style rules gain the H1 naming convention and the no-em-dash rule. --- CHANGELOG.md | 14 ++++++++++ CONTRIBUTING.md | 3 ++- docs/example-readme-template.md | 48 +++++++++++++++++++++++++++++++++ llms.txt | 28 +++++++++++++++++++ 4 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 docs/example-readme-template.md create mode 100644 llms.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index ce59ddc1..1b92f408 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to this repository are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [2026-07-11] - Discoverability and FAQ pass + +### Added + +- FAQ sections, written as the questions people actually ask, in the root README and every finance example's `anchor/` README. +- `llms.txt` at the repository root: a summary and link manifest for LLM crawlers and answer engines. +- `docs/example-readme-template.md`, the example-README template that `CONTRIBUTING.md` referenced but which did not exist. It documents the H1 convention and the definition-first opener. + +### Changed + +- Every finance example README now titles itself `# Solana ()` (e.g. `# Solana Escrow (Anchor)`) and opens with a self-contained definition that names Solana, so each example page stands alone in search results. +- The root README states its toolchain currency explicitly (Anchor 1.1, LiteSVM, July 2026) with a pointer to this changelog. +- `CONTRIBUTING.md` style rules now include the README H1 naming convention and the no-em-dash rule. + ## [2026-07-10] - Failed fundraisers can be retired ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d2096449..2f74096f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,7 +58,8 @@ Also update [CHANGELOG.md](./CHANGELOG.md) when you ship user-visible changes. Write American English in prose (e.g. "behavior", "initialize", "favor"). Code identifiers stay as-is. -- One H1 per markdown file. +- One H1 per markdown file. Example READMEs title it `# Solana ()`, e.g. `# Solana Escrow (Anchor)`. +- No em-dashes in prose. Use a colon, comma, or a new sentence. - Fenced code blocks include a language tag (` ```rust `, ` ```typescript `, ` ```bash `, ` ```toml `). - Link canonical Solana terms to the [terminology page](https://solana.com/docs/references/terminology) on first mention in READMEs. diff --git a/docs/example-readme-template.md b/docs/example-readme-template.md new file mode 100644 index 00000000..3b452956 --- /dev/null +++ b/docs/example-readme-template.md @@ -0,0 +1,48 @@ +# Example README template + +Copy this structure for every example's framework directory (`anchor/`, `quasar/`, `native/`, etc.). Replace the placeholder text; delete sections that genuinely do not apply. + +## Conventions + +- **H1 format**: `# Solana ()`, for example `# Solana Escrow (Anchor)`. One H1 per file. Each example directory is its own indexable page, so the H1 names the example the way someone would search for it. +- **Definition-first opener**: the first sentence must say what the program is, in a way that stands alone when quoted out of context, and include the word "Solana". Good: "A Solana escrow is a program that holds a maker's tokens in a vault until a taker delivers the requested tokens." Bad: "This directory contains the Anchor version." +- **No em-dashes** in prose. Use a colon, comma, or a new sentence. +- Write American English. Fenced code blocks include a language tag. Link canonical Solana terms to the [terminology page](https://solana.com/docs/references/terminology) on first mention. +- Name the actual instruction handlers (`make_offer`, `take_offer`) in lifecycle prose so readers can connect the narrative to the code. Confirm each identifier exists in the source before naming it. + +## Template + +```markdown +# Solana () + + + + + +## Major concepts + + + +## Lifecycle + + + +## Setup + + + +## Testing + + + +## FAQ + + +``` diff --git a/llms.txt b/llms.txt new file mode 100644 index 00000000..0092cabb --- /dev/null +++ b/llms.txt @@ -0,0 +1,28 @@ +# Solana Program Examples + +> Working, tested, up-to-date Solana program ('smart contract') examples, maintained by Quicknode. Focused on financial software ('DeFi'): every finance example ships LiteSVM integration tests and Kani formal-verification proofs of its money math, and builds in CI on Anchor 1.1. Most examples are available in several frameworks: Anchor, Quasar, Pinocchio, native Rust, and sBPF assembly. + +A Solana program is what other chains call a smart contract. These examples are reference implementations for learning: tested and formally verified, but not audited or deployed to mainnet. + +## Finance examples + +- [Solana Escrow](https://github.com/quicknode/solana-program-examples/tree/main/finance/escrow/anchor): the best first Solana finance program. Holds a maker's tokens in a vault until a taker delivers the requested tokens, then swaps both atomically. +- [Solana Lending](https://github.com/quicknode/solana-program-examples/tree/main/finance/lending/anchor): a Kamino/Solend-style borrow/lend market with share-token deposits, a utilization-based interest index, oracle-priced health, and liquidation. +- [Solana Order Book Exchange](https://github.com/quicknode/solana-program-examples/tree/main/finance/order-book/anchor): a central limit order book (CLOB) with price-time priority matching on a critbit tree, ported from Openbook v2. +- [Solana Token Swap AMM](https://github.com/quicknode/solana-program-examples/tree/main/finance/token-swap/anchor): a constant-product automated market maker with liquidity pools, LP tokens, and slippage guards, like Raydium or Orca. +- [Solana Prop AMM](https://github.com/quicknode/solana-program-examples/tree/main/finance/prop-amm/anchor): an oracle-quoted proprietary AMM where one market-making firm supplies all capital and earns the spread, like Lifinity or SolFi. +- [Solana Perpetual Futures](https://github.com/quicknode/solana-program-examples/tree/main/finance/perpetual-futures/anchor): a pool-collateralized leveraged perps exchange with funding, maintenance margin, and liquidation, like Jupiter Perpetuals. +- [Solana Vault Strategy](https://github.com/quicknode/solana-program-examples/tree/main/finance/vault-strategy/anchor): a manager-run onchain fund. Investors deposit USDC for shares priced at net asset value across a weighted asset basket. +- [Solana Betting Market](https://github.com/quicknode/solana-program-examples/tree/main/finance/betting-market/anchor): a parimutuel prediction market where winners split the losing pool in proportion to their stake. +- [Solana Token Fundraiser](https://github.com/quicknode/solana-program-examples/tree/main/finance/token-fundraiser/anchor): onchain crowdfunding toward a target amount, with refunds if the deadline passes unmet. + +## Getting started + +- [Repository README](https://github.com/quicknode/solana-program-examples/blob/main/README.md): full catalog including basics, tokens, Token Extensions, and state compression examples, plus setup instructions. +- [Contributing guidelines](https://github.com/quicknode/solana-program-examples/blob/main/CONTRIBUTING.md): how examples are structured, tested, and documented. +- [Changelog](https://github.com/quicknode/solana-program-examples/blob/main/CHANGELOG.md): release history and toolchain currency. + +## Testing and verification + +- Tests are Rust integration tests against [LiteSVM](https://www.anchor-lang.com/docs/testing/litesvm), run with `cargo test`; no local validator is needed. +- Every finance example has a `kani-proofs/` directory with [Kani](https://github.com/model-checking/kani) harnesses proving money-math invariants over all inputs, for example [escrow's proofs](https://github.com/quicknode/solana-program-examples/tree/main/finance/escrow/kani-proofs).