diff --git a/animations/README.md b/animations/README.md new file mode 100644 index 00000000..99e01d0e --- /dev/null +++ b/animations/README.md @@ -0,0 +1,147 @@ +# Animated figures + +A chapter's figures, stepped through on screen: press a key and the next thing the program does happens. +Accounts are created, fields change, and tokens travel along their arrows. Every step is drawn in the book's +own figure vocabulary (`DIAGRAMS.md` in the companion plugin), with the chapter figures' columns, so the +screen version and the printed figures show the same map. + +The screen has no print limits, so a scene is drawn on a 16:9 canvas (1120 by 630 units). The extra width +puts every public-key account, mints included, beneath the one cluster curve. Colours live in `THEME` at +the top of `engine.js`. Each step has a title, with its caption in the frame beneath. + +There is a talk for every program in Part II, each a directory named for its chapter: + +| Directory | Chapter | Program | +| --- | --- | --- | +| `escrow/` | 11 Escrow | `finance/escrow` | +| `fundraiser/` | 12 The Fundraiser | `finance/fundraiser` | +| `betting-market/` | 13 The Betting Market | `finance/betting-market` | +| `order-book/` | 14 The Order Book Exchange | `finance/order-book` | +| `constant-product-amm/` | 15 The Constant-Product AMM | `finance/token-swap` | +| `prop-amm/` | 16 The Prop AMM | `finance/prop-amm` | +| `lending/` | 17 Lending and Borrowing | `finance/lending` | +| `managed-fund/` | 18 The Managed Fund | `finance/managed-fund` | +| `options/` | 19 Options | `finance/options` | +| `perpetual-futures/` | 20 Perpetual Futures | `finance/perpetual-futures` | + +`index.html` here links to every talk. Open a talk's own `index.html` in a browser. No build step and no server: it runs straight from disk. A talk's +own icons in `assets/icons` carry its directory's prefix (`escrow-`, `perps-`, ...); unprefixed icons are +shared, and mean the same idea in every talk. + +| Key | Does | +| --- | --- | +| `→`, `Space`, `PageDown`, `Enter`, click | next step | +| `←`, `PageUp`, `Backspace` | previous step | +| `Home` / `End` | first / last step | +| `P` | play / pause: each finished step holds for `hold` ms (3 seconds), then the next plays | +| `F` | full screen | + +A step plays once and then holds until the next key. A key pressed while a step is animating finishes that +step at once. `PageDown` and `PageUp` are what presentation remotes send. Open `index.html?autoplay` to start +playing on load. + +## The talk around the diagrams + +`index.html` opens a slide deck in the look of the Quicknode Solana Finance Keynote: a title slide, what you +should know and what you'll learn, card slides between the runs of diagram steps, where everyone ended up, +and the closing slides. One key advances through all of it: a diagram step plays its animation, and a slide +of cards builds them one at a time. + +- `deck.js` and `deck.css` are shared by every talk. A slide kind is a template filled from data, and + `[word]` in any text is set on the green highlight, `{word}` on the purple one. The kinds follow the + Quicknode Keynote template's layouts: + + | Kind | Layout | + | --- | --- | + | `title` | the series tag, a large title, the mark in a green square | + | `columns` | what you should know, and what you'll learn | + | `statement` | one large centred sentence | + | `versus` | two people side by side, a full-height panel each | + | `split` | the heading on the left, a stack of wide icon cards on the right | + | `grid` | the heading across the top, a grid of centred icon cards (`columns`: 2, 3 or 4) | + | `numbered` | cards tagged `// 01`, `// 02` | + | `cards` | tall cards in the slides' three tones | + | `chart` | a payoff chart, one line per side | + | `allocation` | a bar split by value: a fund's weights, or who owns its shares; with `from`, the parts move from earlier values to their own, to or from nothing (a losing stake paying the winners), after `delay` ms | + | `qr`, `follow` | the closing slides | + + Any slide with cards, or a chart's lines, builds one per key press unless it sets `build: false`. + A card's `icon` is one of the book's account glyphs (`wallet`, `token`, ...) or, as `tpl:name`, one of + the template's icons in `assets/icons`, named for the idea it stands for (`premium`, `price-rises`, + `insurance`). One icon means one idea throughout a talk: reuse it where the idea comes back, and never + give it to anything else. +- **A talk always matches its chapter.** Its people, assets, events, order of events and numbers are the + chapter's. A talk never invents a scenario, swaps one person for another, adds an event the chapter + doesn't describe, or shows a number the chapter doesn't state. A balance may follow from the chapter's + numbers by plain arithmetic, marked in a comment; a number the chapter leaves out stays out. A talk may + leave a minor branch out for time, never replace one. +- A term is defined where the talk first needs it: not before, where it means nothing yet, and not after, + where it was already used unexplained. Calls are defined just before Alice writes one, "covered" in the + step where her collateral lands in the vault, and "in the money" in the step where Bob exercises. +- `/slides.js` lists the talk's slides. A `diagram` slide names the scene steps it shows, `from` + and `to` by index, and together the diagram slides show every step once, in order; the deck refuses to + start otherwise. +- `assets/` holds the Quicknode mark (inlined in `deck.css` as a mask), a QR code generated from + solanabook.org, and in `assets/icons` the icons taken from the Quicknode Keynote template. + +The diagrams take the same palette: accounts are pastel cards on near-black (white for wallets, green for +token accounts, lavender for programs, grey for data accounts, cream for mints), a faded account is a dark +slab, and the step's action is the bright green. A step title marks its keyword in brackets, `Maria runs +[collect_fees()]`, and the step number sits in the corner as `// STEP n`. + +## How a scene is built + +- `engine.js` is shared by every scene. It draws accounts, arrows and coins, and animates each step's actions. +- `/scene.js` holds that chapter's layout and steps, and nothing else. + +The layout is placed by hand, as the figures are: each column's position and width is chosen in the scene. +A public-key account's dot is put on the curve with `clusterCurve().yAt()` and its box hangs 9.3 below it, +and a derived account's dot and seed list sit above its box, so the dots never drift off the curve. No two derived accounts share a seed list: the same seeds are the +same address, so a scene that repeats one is wrong, and the engine refuses to draw it. Name the seed that +tells them apart, the index, the order ID or the reserve, as the program does. A step +is a title, a caption, and a list of actions: + +| Action | Shows | +| --- | --- | +| `show` | accounts that already exist on chain fade in, with their lines; `focus: "shown"` draws them in full | +| `hide` | accounts the rest of the story no longer needs fade out, so others can take their columns | +| `focus` | which accounts are drawn in full; the rest fade to their heading | +| `call` | a handler lights up in the program box, and the focus moves to the accounts it touches; `also` lights handlers it calls in other programs, and a `call` with no handler is a step no program takes, such as a price moving | +| `highlight` | the lit handlers change within a call, as a deposit moves from one swap to the next | +| `create` | a new account grows in, with a `NEW` badge | +| `set` | fields or titles change; numbers count from the old value to the new | +| `transfer` | the arrow draws, a coin rides it, and both balances count to their new values; with `alone` it replaces the step's earlier arrows, and a side with no `value` (a router trading on the far side) shows no balance | +| `close` | an account is marked `CLOSED` and fades out, taking the step's arrows with it | + +A person appears in the step where they first do something, with the accounts that step uses: Bob and his +USDC when he buys, Maria when she opens the venue and her USDC only when she collects the fees. A scene +opens on one person and builds outward, so an audience new to Solana meets one account at a time. + +The running handler's line in a program box is bold, on the green band, in a face with a real bold weight: +Andale Mono has none, and a browser's made-up bold is too faint to pick out. Handler names elsewhere are +set like the words around them. + +A step can also carry a `key`, and a later step can start `from` that key instead of from the step before +it. That is how another possible ending branches off the story (the call expiring unused starts from the purchase, +not from the exercise before it) and how the story resumes afterwards. The jump between endings fades out +and back in, so it never reads as the program doing something. Each ending opens on a `statement` +slide that names it, "Outcome 1: nobody takes Alice's offer", "Outcome 2: Bob takes Alice's offer", and +a return to the main story on "Back to Outcome 1: …". A brief aside that is not an ending opens on +"What if …?". The steps after such a slide go straight to what happens, without "It's possible that". + +Every step's end state is computed by replaying the actions without motion. Going back, jumping, or +cutting an animation short therefore lands on exactly the picture the forward animation ends on. + +Order the actions as the handler in `quicknode/solana-program-examples` orders its work, not as the prose +lists it. `buy_option()` writes the holder, the status and `fees_owed`, and runs `check_custody()`, before +either transfer, so the scene does the same. + +## Checking a scene + +``` +node scripts/animation-frames.mjs options # each step's end state as build/animation-options-NN.png and .svg +node scripts/animation-frames.mjs managed-fund # the same for the Managed Fund talk +node scripts/animation-frames.mjs options --video # the whole animation, each step held, as build/animation-options.webm +``` + +The script fails if the page throws an error. diff --git a/animations/assets/book-cover.jpg b/animations/assets/book-cover.jpg new file mode 100644 index 00000000..ba8ed255 Binary files /dev/null and b/animations/assets/book-cover.jpg differ diff --git a/animations/assets/icons/amm-fee.png b/animations/assets/icons/amm-fee.png new file mode 100644 index 00000000..ff7795b7 Binary files /dev/null and b/animations/assets/icons/amm-fee.png differ diff --git a/animations/assets/icons/amm-formula.png b/animations/assets/icons/amm-formula.png new file mode 100644 index 00000000..733f1ffb Binary files /dev/null and b/animations/assets/icons/amm-formula.png differ diff --git a/animations/assets/icons/amm-instant.png b/animations/assets/icons/amm-instant.png new file mode 100644 index 00000000..8fa508ce Binary files /dev/null and b/animations/assets/icons/amm-instant.png differ diff --git a/animations/assets/icons/amm-pool.png b/animations/assets/icons/amm-pool.png new file mode 100644 index 00000000..a470bea0 Binary files /dev/null and b/animations/assets/icons/amm-pool.png differ diff --git a/animations/assets/icons/bargain.png b/animations/assets/icons/bargain.png new file mode 100644 index 00000000..c2db396d Binary files /dev/null and b/animations/assets/icons/bargain.png differ diff --git a/animations/assets/icons/betting-against.png b/animations/assets/icons/betting-against.png new file mode 100644 index 00000000..a9e10e1c Binary files /dev/null and b/animations/assets/icons/betting-against.png differ diff --git a/animations/assets/icons/betting-backs.png b/animations/assets/icons/betting-backs.png new file mode 100644 index 00000000..0815534e Binary files /dev/null and b/animations/assets/icons/betting-backs.png differ diff --git a/animations/assets/icons/betting-fee.png b/animations/assets/icons/betting-fee.png new file mode 100644 index 00000000..ff7795b7 Binary files /dev/null and b/animations/assets/icons/betting-fee.png differ diff --git a/animations/assets/icons/betting-film.png b/animations/assets/icons/betting-film.png new file mode 100644 index 00000000..deec21ae Binary files /dev/null and b/animations/assets/icons/betting-film.png differ diff --git a/animations/assets/icons/betting-house.png b/animations/assets/icons/betting-house.png new file mode 100644 index 00000000..0cb5d920 Binary files /dev/null and b/animations/assets/icons/betting-house.png differ diff --git a/animations/assets/icons/betting-odds.png b/animations/assets/icons/betting-odds.png new file mode 100644 index 00000000..72348071 Binary files /dev/null and b/animations/assets/icons/betting-odds.png differ diff --git a/animations/assets/icons/betting-pool.png b/animations/assets/icons/betting-pool.png new file mode 100644 index 00000000..02d508ce Binary files /dev/null and b/animations/assets/icons/betting-pool.png differ diff --git a/animations/assets/icons/betting-stake.png b/animations/assets/icons/betting-stake.png new file mode 100644 index 00000000..b3c3ab53 Binary files /dev/null and b/animations/assets/icons/betting-stake.png differ diff --git a/animations/assets/icons/betting-won.png b/animations/assets/icons/betting-won.png new file mode 100644 index 00000000..fc947709 Binary files /dev/null and b/animations/assets/icons/betting-won.png differ diff --git a/animations/assets/icons/contract.png b/animations/assets/icons/contract.png new file mode 100644 index 00000000..419f7744 Binary files /dev/null and b/animations/assets/icons/contract.png differ diff --git a/animations/assets/icons/escrow-atomic.png b/animations/assets/icons/escrow-atomic.png new file mode 100644 index 00000000..202536f6 Binary files /dev/null and b/animations/assets/icons/escrow-atomic.png differ diff --git a/animations/assets/icons/escrow-buy.png b/animations/assets/icons/escrow-buy.png new file mode 100644 index 00000000..58ef0a88 Binary files /dev/null and b/animations/assets/icons/escrow-buy.png differ diff --git a/animations/assets/icons/escrow-fee.png b/animations/assets/icons/escrow-fee.png new file mode 100644 index 00000000..ff7795b7 Binary files /dev/null and b/animations/assets/icons/escrow-fee.png differ diff --git a/animations/assets/icons/escrow-maker.png b/animations/assets/icons/escrow-maker.png new file mode 100644 index 00000000..7e86c18f Binary files /dev/null and b/animations/assets/icons/escrow-maker.png differ diff --git a/animations/assets/icons/escrow-middleman.png b/animations/assets/icons/escrow-middleman.png new file mode 100644 index 00000000..1f9152a7 Binary files /dev/null and b/animations/assets/icons/escrow-middleman.png differ diff --git a/animations/assets/icons/escrow-offer.png b/animations/assets/icons/escrow-offer.png new file mode 100644 index 00000000..63812d47 Binary files /dev/null and b/animations/assets/icons/escrow-offer.png differ diff --git a/animations/assets/icons/escrow-sell.png b/animations/assets/icons/escrow-sell.png new file mode 100644 index 00000000..c2db396d Binary files /dev/null and b/animations/assets/icons/escrow-sell.png differ diff --git a/animations/assets/icons/escrow-swap.png b/animations/assets/icons/escrow-swap.png new file mode 100644 index 00000000..6c69f05b Binary files /dev/null and b/animations/assets/icons/escrow-swap.png differ diff --git a/animations/assets/icons/escrow-taker.png b/animations/assets/icons/escrow-taker.png new file mode 100644 index 00000000..0815534e Binary files /dev/null and b/animations/assets/icons/escrow-taker.png differ diff --git a/animations/assets/icons/escrow-vault.png b/animations/assets/icons/escrow-vault.png new file mode 100644 index 00000000..6ee64a78 Binary files /dev/null and b/animations/assets/icons/escrow-vault.png differ diff --git a/animations/assets/icons/expertise.png b/animations/assets/icons/expertise.png new file mode 100644 index 00000000..79091330 Binary files /dev/null and b/animations/assets/icons/expertise.png differ diff --git a/animations/assets/icons/expire.png b/animations/assets/icons/expire.png new file mode 100644 index 00000000..e00fdd6b Binary files /dev/null and b/animations/assets/icons/expire.png differ diff --git a/animations/assets/icons/expiry.png b/animations/assets/icons/expiry.png new file mode 100644 index 00000000..2cee0dab Binary files /dev/null and b/animations/assets/icons/expiry.png differ diff --git a/animations/assets/icons/fundraiser-backer.png b/animations/assets/icons/fundraiser-backer.png new file mode 100644 index 00000000..0815534e Binary files /dev/null and b/animations/assets/icons/fundraiser-backer.png differ diff --git a/animations/assets/icons/fundraiser-claim.png b/animations/assets/icons/fundraiser-claim.png new file mode 100644 index 00000000..899c6009 Binary files /dev/null and b/animations/assets/icons/fundraiser-claim.png differ diff --git a/animations/assets/icons/fundraiser-deadline.png b/animations/assets/icons/fundraiser-deadline.png new file mode 100644 index 00000000..2cee0dab Binary files /dev/null and b/animations/assets/icons/fundraiser-deadline.png differ diff --git a/animations/assets/icons/fundraiser-maker.png b/animations/assets/icons/fundraiser-maker.png new file mode 100644 index 00000000..8e17347a Binary files /dev/null and b/animations/assets/icons/fundraiser-maker.png differ diff --git a/animations/assets/icons/fundraiser-receipt.png b/animations/assets/icons/fundraiser-receipt.png new file mode 100644 index 00000000..10ec9719 Binary files /dev/null and b/animations/assets/icons/fundraiser-receipt.png differ diff --git a/animations/assets/icons/fundraiser-refund.png b/animations/assets/icons/fundraiser-refund.png new file mode 100644 index 00000000..00e91475 Binary files /dev/null and b/animations/assets/icons/fundraiser-refund.png differ diff --git a/animations/assets/icons/fundraiser-target.png b/animations/assets/icons/fundraiser-target.png new file mode 100644 index 00000000..e6083a09 Binary files /dev/null and b/animations/assets/icons/fundraiser-target.png differ diff --git a/animations/assets/icons/holder.png b/animations/assets/icons/holder.png new file mode 100644 index 00000000..a4963e1b Binary files /dev/null and b/animations/assets/icons/holder.png differ diff --git a/animations/assets/icons/income.png b/animations/assets/icons/income.png new file mode 100644 index 00000000..04cf871f Binary files /dev/null and b/animations/assets/icons/income.png differ diff --git a/animations/assets/icons/insurance.png b/animations/assets/icons/insurance.png new file mode 100644 index 00000000..696efc04 Binary files /dev/null and b/animations/assets/icons/insurance.png differ diff --git a/animations/assets/icons/later.png b/animations/assets/icons/later.png new file mode 100644 index 00000000..2b98b457 Binary files /dev/null and b/animations/assets/icons/later.png differ diff --git a/animations/assets/icons/lending-cash.png b/animations/assets/icons/lending-cash.png new file mode 100644 index 00000000..447e0ada Binary files /dev/null and b/animations/assets/icons/lending-cash.png differ diff --git a/animations/assets/icons/lending-collateral.png b/animations/assets/icons/lending-collateral.png new file mode 100644 index 00000000..6ee64a78 Binary files /dev/null and b/animations/assets/icons/lending-collateral.png differ diff --git a/animations/assets/icons/lending-interest.png b/animations/assets/icons/lending-interest.png new file mode 100644 index 00000000..00cce068 Binary files /dev/null and b/animations/assets/icons/lending-interest.png differ diff --git a/animations/assets/icons/lending-liquidation.png b/animations/assets/icons/lending-liquidation.png new file mode 100644 index 00000000..202536f6 Binary files /dev/null and b/animations/assets/icons/lending-liquidation.png differ diff --git a/animations/assets/icons/lending-ltv.png b/animations/assets/icons/lending-ltv.png new file mode 100644 index 00000000..ff7795b7 Binary files /dev/null and b/animations/assets/icons/lending-ltv.png differ diff --git a/animations/assets/icons/lending-short.png b/animations/assets/icons/lending-short.png new file mode 100644 index 00000000..4edda1c4 Binary files /dev/null and b/animations/assets/icons/lending-short.png differ diff --git a/animations/assets/icons/orderbook-ask.png b/animations/assets/icons/orderbook-ask.png new file mode 100644 index 00000000..c2db396d Binary files /dev/null and b/animations/assets/icons/orderbook-ask.png differ diff --git a/animations/assets/icons/orderbook-bid.png b/animations/assets/icons/orderbook-bid.png new file mode 100644 index 00000000..58ef0a88 Binary files /dev/null and b/animations/assets/icons/orderbook-bid.png differ diff --git a/animations/assets/icons/orderbook-book.png b/animations/assets/icons/orderbook-book.png new file mode 100644 index 00000000..832611c8 Binary files /dev/null and b/animations/assets/icons/orderbook-book.png differ diff --git a/animations/assets/icons/orderbook-cross.png b/animations/assets/icons/orderbook-cross.png new file mode 100644 index 00000000..202536f6 Binary files /dev/null and b/animations/assets/icons/orderbook-cross.png differ diff --git a/animations/assets/icons/orderbook-limit.png b/animations/assets/icons/orderbook-limit.png new file mode 100644 index 00000000..e6083a09 Binary files /dev/null and b/animations/assets/icons/orderbook-limit.png differ diff --git a/animations/assets/icons/orderbook-spread.png b/animations/assets/icons/orderbook-spread.png new file mode 100644 index 00000000..bc676203 Binary files /dev/null and b/animations/assets/icons/orderbook-spread.png differ diff --git a/animations/assets/icons/perps-collateral.png b/animations/assets/icons/perps-collateral.png new file mode 100644 index 00000000..fc8290c5 Binary files /dev/null and b/animations/assets/icons/perps-collateral.png differ diff --git a/animations/assets/icons/perps-haircut.png b/animations/assets/icons/perps-haircut.png new file mode 100644 index 00000000..9eeedb92 Binary files /dev/null and b/animations/assets/icons/perps-haircut.png differ diff --git a/animations/assets/icons/perps-leverage.png b/animations/assets/icons/perps-leverage.png new file mode 100644 index 00000000..cb393388 Binary files /dev/null and b/animations/assets/icons/perps-leverage.png differ diff --git a/animations/assets/icons/perps-liquidation.png b/animations/assets/icons/perps-liquidation.png new file mode 100644 index 00000000..202536f6 Binary files /dev/null and b/animations/assets/icons/perps-liquidation.png differ diff --git a/animations/assets/icons/perps-no-expiry.png b/animations/assets/icons/perps-no-expiry.png new file mode 100644 index 00000000..1291bcb8 Binary files /dev/null and b/animations/assets/icons/perps-no-expiry.png differ diff --git a/animations/assets/icons/perps-pool.png b/animations/assets/icons/perps-pool.png new file mode 100644 index 00000000..02d508ce Binary files /dev/null and b/animations/assets/icons/perps-pool.png differ diff --git a/animations/assets/icons/perps-price-falls.png b/animations/assets/icons/perps-price-falls.png new file mode 100644 index 00000000..4edda1c4 Binary files /dev/null and b/animations/assets/icons/perps-price-falls.png differ diff --git a/animations/assets/icons/perps-size.png b/animations/assets/icons/perps-size.png new file mode 100644 index 00000000..74e62de5 Binary files /dev/null and b/animations/assets/icons/perps-size.png differ diff --git a/animations/assets/icons/premium.png b/animations/assets/icons/premium.png new file mode 100644 index 00000000..899c6009 Binary files /dev/null and b/animations/assets/icons/premium.png differ diff --git a/animations/assets/icons/price-rises.png b/animations/assets/icons/price-rises.png new file mode 100644 index 00000000..5719b17d Binary files /dev/null and b/animations/assets/icons/price-rises.png differ diff --git a/animations/assets/icons/propamm-ask.png b/animations/assets/icons/propamm-ask.png new file mode 100644 index 00000000..ce30e181 Binary files /dev/null and b/animations/assets/icons/propamm-ask.png differ diff --git a/animations/assets/icons/propamm-bid.png b/animations/assets/icons/propamm-bid.png new file mode 100644 index 00000000..1d1eceee Binary files /dev/null and b/animations/assets/icons/propamm-bid.png differ diff --git a/animations/assets/icons/propamm-instant.png b/animations/assets/icons/propamm-instant.png new file mode 100644 index 00000000..202536f6 Binary files /dev/null and b/animations/assets/icons/propamm-instant.png differ diff --git a/animations/assets/icons/propamm-inventory.png b/animations/assets/icons/propamm-inventory.png new file mode 100644 index 00000000..24af2908 Binary files /dev/null and b/animations/assets/icons/propamm-inventory.png differ diff --git a/animations/assets/icons/propamm-maker.png b/animations/assets/icons/propamm-maker.png new file mode 100644 index 00000000..d2ae59be Binary files /dev/null and b/animations/assets/icons/propamm-maker.png differ diff --git a/animations/assets/icons/propamm-oracle.png b/animations/assets/icons/propamm-oracle.png new file mode 100644 index 00000000..72348071 Binary files /dev/null and b/animations/assets/icons/propamm-oracle.png differ diff --git a/animations/assets/icons/propamm-spread.png b/animations/assets/icons/propamm-spread.png new file mode 100644 index 00000000..b6f40776 Binary files /dev/null and b/animations/assets/icons/propamm-spread.png differ diff --git a/animations/assets/icons/savings.png b/animations/assets/icons/savings.png new file mode 100644 index 00000000..04cf871f Binary files /dev/null and b/animations/assets/icons/savings.png differ diff --git a/animations/assets/icons/strike.png b/animations/assets/icons/strike.png new file mode 100644 index 00000000..e6083a09 Binary files /dev/null and b/animations/assets/icons/strike.png differ diff --git a/animations/assets/icons/underlying.png b/animations/assets/icons/underlying.png new file mode 100644 index 00000000..0fe49298 Binary files /dev/null and b/animations/assets/icons/underlying.png differ diff --git a/animations/assets/icons/venue.png b/animations/assets/icons/venue.png new file mode 100644 index 00000000..d2ae59be Binary files /dev/null and b/animations/assets/icons/venue.png differ diff --git a/animations/assets/icons/vetting.png b/animations/assets/icons/vetting.png new file mode 100644 index 00000000..fc8290c5 Binary files /dev/null and b/animations/assets/icons/vetting.png differ diff --git a/animations/assets/icons/writer.png b/animations/assets/icons/writer.png new file mode 100644 index 00000000..7e86c18f Binary files /dev/null and b/animations/assets/icons/writer.png differ diff --git a/animations/assets/qr-solanabook.svg b/animations/assets/qr-solanabook.svg new file mode 100644 index 00000000..b4efda81 --- /dev/null +++ b/animations/assets/qr-solanabook.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/animations/assets/quicknode-mark.png b/animations/assets/quicknode-mark.png new file mode 100644 index 00000000..680cb3da Binary files /dev/null and b/animations/assets/quicknode-mark.png differ diff --git a/animations/assets/sky.jpg b/animations/assets/sky.jpg new file mode 100644 index 00000000..f103f696 Binary files /dev/null and b/animations/assets/sky.jpg differ diff --git a/animations/betting-market/index.html b/animations/betting-market/index.html new file mode 100644 index 00000000..02ed1518 --- /dev/null +++ b/animations/betting-market/index.html @@ -0,0 +1,50 @@ + + + + + +Betting Market Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/betting-market/scene.js b/animations/betting-market/scene.js new file mode 100644 index 00000000..b77c9572 --- /dev/null +++ b/animations/betting-market/scene.js @@ -0,0 +1,531 @@ +// The Betting Market chapter as an animated scene: Maria opens a parimutuel +// market on this month's top-grossing film, Alice and Bob back Glowbugs 3 and +// Carol backs The Quiet Floor, Maria settles it, the winners claim, and every +// account the market created is closed. The other future the chapter names +// (the event cancelled and every stake refunded) branches off once the bets +// are in, and the story returns to settlement after it. +// +// The columns are the chapter figures' accounts spread across a 16:9 screen: +// the bettors and Maria under the curve, the event's accounts in a column of +// their own, and the program with its config on the right. Arrows run down +// the lane beside each bettor's column and along a corridor at the vault's +// height. The steps follow the handlers in quicknode/solana-program-examples +// finance/betting-market: place_bet() moves the stake before it writes the +// bet; settle_event() pays the fee before it records the result; a claim +// lowers open_bets before it pays. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + // As flat as the Managed Fund talk's: the event column needs the height. + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, drop: 60, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + const GAP3 = 37; + + // Columns, left to right: three bettors, Maria, the event's accounts, and + // the program. The gaps between them are the arrows' lanes. + const COLUMN = { + alice: [12, 140], + bob: [168, 132], + carol: [316, 140], + maria: [472, 132], + event: [636, 220], + program: [876, 232], + }; + const LANE = { alice: 160, bob: 308, carol: 464, maria: 620 }; + + const ata = (owner, x, y, w) => + derived("token", `${owner}'s USDC`, x, y, w, [`${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", "USDC MINT"]); + const bet = (owner, outcome, x, y, w) => + derived("struct", `${owner}'s bet`, x, y, w, [`"BET" + ${outcome} +`, `${owner.toUpperCase()}'S ADDRESS`]); + + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const carol = onCurve("wallet", "Carol", ...COLUMN.carol); + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const slot = (person, n) => person.y + 77 * n; + + // The event column hangs beneath the curve at its right edge. + const eventTop = curve.yAt(COLUMN.event[0] + COLUMN.event[1]) + 9 + GAP2; + const event = derived("struct", "event", COLUMN.event[0], eventTop, COLUMN.event[1], ['"EVENT" +', "EVENT ID"]); + const outcome0 = derived("struct", "outcome 0", COLUMN.event[0], event.y + tall(8) + GAP2, COLUMN.event[1], ['"OUTCOME" + EVENT\'S', "ADDRESS + INDEX 0"]); + const outcome1 = derived("struct", "outcome 1", COLUMN.event[0], outcome0.y + tall(3) + GAP2, COLUMN.event[1], ['"OUTCOME" + EVENT\'S', "ADDRESS + INDEX 1"]); + const vault = derived("token", "vault", COLUMN.event[0], outcome1.y + tall(3) + GAP3, COLUMN.event[1], ["EVENT'S ADDRESS +", "TOKEN PROGRAM +", "USDC MINT"]); + + const program = onCurve("program", "betting program", ...COLUMN.program); + const config = derived("struct", "config", COLUMN.program[0], program.y + 150 + GAP2, COLUMN.program[1], ['"CONFIG"']); + + const accounts = { + alice, + aliceUsdc: ata("Alice", COLUMN.alice[0], slot(alice, 1), COLUMN.alice[1]), + aliceBet: bet("Alice", "GLOWBUGS 3 OUTCOME", COLUMN.alice[0], slot(alice, 2), COLUMN.alice[1]), + bob, + bobUsdc: ata("Bob", COLUMN.bob[0], slot(bob, 1), COLUMN.bob[1]), + bobBet: bet("Bob", "GLOWBUGS 3 OUTCOME", COLUMN.bob[0], slot(bob, 2), COLUMN.bob[1]), + carol, + carolUsdc: ata("Carol", COLUMN.carol[0], slot(carol, 1), COLUMN.carol[1]), + carolBet: bet("Carol", "QUIET FLOOR OUTCOME", COLUMN.carol[0], slot(carol, 2), COLUMN.carol[1]), + maria, + mariaUsdc: ata("Maria", COLUMN.maria[0], slot(maria, 1), COLUMN.maria[1]), + event, outcome0, outcome1, vault, + program, config, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // A stake runs out of a bettor's USDC, down their lane, and along the + // corridor at the vault's height into its left edge. A payout runs back the + // other way a little lower, so the two never share a line. + + const IN_Y = vault.y + 22; + const OUT_Y = vault.y + 36; + + function stake(from, lane) { + const sx = from.x + from.w + 2, sy = from.y + 20; + return rounded([[sx, sy], [lane, sy], [lane, IN_Y], [vault.x - 2, IN_Y]]); + } + + function payout(to, lane) { + const ex = to.x + to.w + 2, ey = to.y + 28; + return rounded([[vault.x - 2, OUT_Y], [lane, OUT_Y], [lane, ey], [ex, ey]]); + } + + // A stake's label hangs below its corridor; a payout's sits above its own, + // clear of the caption. + const below = { dx: 0, dy: 20, anchor: "middle" }; + const above = { dx: 0, dy: -24, anchor: "middle" }; + const corridor = (x, y) => ({ x, y }); + + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + alone: true, + from: { id: from, value: fromValue }, + to: { id: to, value: toValue }, + arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + + const HANDLERS = [ + "initialize_config()", + "initialize_event()", + "add_outcome()", + "open_betting()", + "place_bet()", + "settle_event()", + "claim_winnings()", + "close_losing_bet()", + "cancel_event()", + "claim_refund()", + "close_outcome()", + "close_event()", + ]; + + // The focus of every step that touches the market's bookkeeping. + const MARKET = ["program", "event", "outcome0", "outcome1", "vault"]; + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "She keeps USDC, a token worth one US dollar, in a token account of her own. Every kind of token is " + + "defined by a mint, one of the three names its address is worked out from. It holds 1,000 USDC.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice wants to back [Glowbugs 3]", + caption: + "Alice is confident about school holidays: she thinks Glowbugs 3 will be this month's top-grossing film, " + + "and wants to stake $300 on it.", + actions: [{ type: "focus", ids: ["alice", "aliceUsdc"] }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs betting markets, and each line is an instruction " + + "handler anyone can call by sending a transaction. First, somebody has to open a market.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + + // ---- Maria sets the market up + { + title: "Maria runs [initialize_config()]", + caption: + "Maria runs the platform, for a fee. The config names her the admin, the only signer allowed to run the " + + "market, makes USDC the token every bet is in, and sets her fee: 200 basis points, hundredths of a percent, so 2%.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_config()", focus: ["maria", "program"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (admin)" }] }, + { + type: "create", id: "config", + lines: [ + field("admin: Maria"), + field("token_mint: USDC"), + field("fee_recipient: Maria"), + field("default_fee_bps: 200"), + ], + }, + ], + }, + { + title: "Maria runs [initialize_event()]", + caption: + "The event is this month's question, with the time betting closes, and a copy of the 2% fee that later " + + "changes to the config can't touch. Its vault is one token account for every stake, controlled by the event.", + actions: [ + { type: "call", handler: "initialize_event()", focus: ["maria", "program", "config"] }, + { + type: "create", id: "event", + lines: [ + field("status: Draft"), + field("betting_closes_at: month's end"), + field("fee_bps: 200"), + field("total_pool: 0 USDC"), + // A count, so zero until the first bet. The settlement fields are left out + // until settle_event() writes them, as in the chapter's figures. + field("open_bets: 0"), + ], + }, + { type: "create", id: "vault", lines: [balance("0 USDC"), note("authority: the event")] }, + ], + }, + { + title: "Maria runs [add_outcome()] twice", + caption: + "An outcome is one result people can bet on, each with an account counting what's staked on it. " + + "Outcomes can only be added while the event is a Draft.", + actions: [ + { type: "call", handler: "add_outcome()", focus: ["maria", "program", "event"] }, + { type: "create", id: "outcome0", lines: [field("label: Glowbugs 3"), field("total_amount: 0 USDC"), field("bet_count: 0")] }, + { type: "create", id: "outcome1", lines: [field("label: The Quiet Floor"), field("total_amount: 0 USDC"), field("bet_count: 0")] }, + ], + }, + { + title: "Maria runs [open_betting()]", + caption: + "The event becomes Open, and its outcome list is now fixed: nobody can stake on a list that might still " + + "change, and a market needs at least two outcomes, so the winners have losers to be paid from.", + actions: [ + { type: "call", handler: "open_betting()", focus: ["maria", "program", "event", "outcome0", "outcome1"] }, + { type: "set", changes: [{ id: "event", key: "status", value: "Open" }] }, + ], + }, + + // ---- The bets + { + title: "Alice runs [place_bet()]", + caption: + "Her first bet on an outcome creates her bet account, before the handler's code runs. Its outcome_index " + + "of 0 is Glowbugs 3.", + actions: [ + { type: "call", handler: "place_bet()", focus: ["alice", "aliceUsdc", ...MARKET] }, + { type: "set", changes: [{ id: "alice", title: "Alice (bettor)" }] }, + { type: "create", id: "aliceBet", lines: [field("outcome_index: 0"), field("amount: 0 USDC")] }, + ], + }, + { + title: "Alice's 300 USDC go into the [vault]", + caption: "The stake moves first. Alice signs the transfer herself; nothing from the program has to sign on the way in.", + actions: [ + transfer("aliceUsdc", "700 USDC", "vault", "300 USDC", { + id: "aliceStake", d: stake(A.aliceUsdc, LANE.alice), + coinNear: corridor(400, IN_Y), label: ["place_bet()", "300 USDC"], labelAt: below, + }), + ], + }, + { + title: "The pool records her [stake]", + caption: + "Then the handler fills in her bet, and adds her 300 to Glowbugs 3's total and to the event's total pool.", + actions: [ + { + type: "set", + changes: [ + { id: "aliceBet", key: "amount", value: "300 USDC" }, + { id: "outcome0", key: "total_amount", value: "300 USDC" }, + { id: "outcome0", key: "bet_count", value: "1" }, + { id: "event", key: "total_pool", value: "300 USDC" }, + { id: "event", key: "open_bets", value: "1" }, + ], + }, + ], + }, + { + title: "Bob backs Glowbugs 3 [too]", + caption: "Bob agrees with Alice, but has less to spend: 100 USDC on Glowbugs 3, through the same handler.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc"], + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "place_bet()", focus: ["bob", "bobUsdc", ...MARKET] }, + { type: "set", changes: [{ id: "bob", title: "Bob (bettor)" }] }, + { type: "create", id: "bobBet", lines: [field("outcome_index: 0"), field("amount: 0 USDC")] }, + transfer("bobUsdc", "900 USDC", "vault", "400 USDC", { + id: "bobStake", d: stake(A.bobUsdc, LANE.bob), + coinNear: corridor(480, IN_Y), label: ["place_bet()", "100 USDC"], labelAt: below, + }), + { + type: "set", + changes: [ + { id: "bobBet", key: "amount", value: "100 USDC" }, + { id: "outcome0", key: "total_amount", value: "400 USDC" }, + { id: "outcome0", key: "bet_count", value: "2" }, + { id: "event", key: "total_pool", value: "400 USDC" }, + { id: "event", key: "open_bets", value: "2" }, + ], + }, + ], + }, + { + key: "betsPlaced", + title: "Carol backs [The Quiet Floor]", + caption: + "Carol believes in word of mouth: 200 USDC on The Quiet Floor. The vault now holds 600 USDC, 400 on " + + "Glowbugs 3 and 200 on The Quiet Floor, all in one account.", + actions: [ + { + type: "show", + ids: ["carol", "carolUsdc"], + lines: { carol: [sol("1 SOL")], carolUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "place_bet()", focus: ["carol", "carolUsdc", ...MARKET] }, + { type: "set", changes: [{ id: "carol", title: "Carol (bettor)" }] }, + { type: "create", id: "carolBet", lines: [field("outcome_index: 1"), field("amount: 0 USDC")] }, + transfer("carolUsdc", "800 USDC", "vault", "600 USDC", { + id: "carolStake", d: stake(A.carolUsdc, LANE.carol), + coinNear: corridor(560, IN_Y), label: ["place_bet()", "200 USDC"], labelAt: below, + }), + { + type: "set", + changes: [ + { id: "carolBet", key: "amount", value: "200 USDC" }, + { id: "outcome1", key: "total_amount", value: "200 USDC" }, + { id: "outcome1", key: "bet_count", value: "1" }, + { id: "event", key: "total_pool", value: "600 USDC" }, + { id: "event", key: "open_bets", value: "3" }, + ], + }, + ], + }, + + // ---- Another future: the event is cancelled + { + title: "Maria runs [cancel_event()]", + caption: + "With both films pulled there's no result to report, so Maria cancels " + + "the event instead, and the market owes every bettor their exact stake back.", + actions: [ + { type: "call", handler: "cancel_event()", focus: ["maria", "program", "event"] }, + { type: "set", changes: [{ id: "event", key: "status", value: "Cancelled" }] }, + ], + }, + { + title: "Every bettor gets a [refund]", + caption: + "Each bettor calls claim_refund() for their whole stake, with no fee taken, and their bet account closes. " + + "Alice's 300 USDC come back; Bob and Carol do the same.", + actions: [ + { type: "call", handler: "claim_refund()", focus: ["alice", "aliceUsdc", "aliceBet", "program", "event", "vault"] }, + { type: "set", changes: [{ id: "event", key: "open_bets", value: "2" }] }, + transfer("vault", "300 USDC", "aliceUsdc", "1,000 USDC", { + id: "refund", d: payout(A.aliceUsdc, LANE.alice), + coinNear: corridor(400, OUT_Y), label: ["claim_refund()", "300 USDC"], labelAt: above, + }), + { type: "close", id: "aliceBet" }, + ], + }, + + // ---- Settlement + { + from: "betsPlaced", + title: "The month ends, and Maria runs [settle_event()]", + caption: + "Glowbugs 3 wins in the real world, and the program only learns it because Maria, " + + "the admin, signs to say so. Settling is reporting the result; it can't happen before betting closes.", + actions: [ + { type: "call", handler: "settle_event()", focus: ["maria", "program", "event", "outcome0", "vault"] }, + ], + }, + { + title: "Maria takes her 2% [fee]", + caption: + "The losing pool is 600 − 400 = 200 USDC, and the fee is 2% of the losing pool only: 4 USDC. So a winner " + + "never gets back less than their stake. The fee leaves the vault first.", + actions: [ + // 1,000: the chapter's figure shows 1,004 once the 4 USDC fee lands. + { type: "show", ids: ["mariaUsdc"], lines: { mariaUsdc: [balance("1,000 USDC")] }, focus: "shown" }, + transfer("vault", "596 USDC", "mariaUsdc", "1,004 USDC", { + id: "fee", + d: rounded([[vault.x - 2, OUT_Y], [LANE.maria, OUT_Y], [LANE.maria, A.mariaUsdc.y + 20], [A.mariaUsdc.x + A.mariaUsdc.w + 2, A.mariaUsdc.y + 20]]), + coinNear: { x: LANE.maria, y: 360 }, label: ["4 USDC"], labelAt: { dx: -14, dy: 4, anchor: "end" }, + }), + ], + }, + { + key: "settled", + title: "The event records the [result]", + caption: + "Then the event becomes Settled, and records the winner, the 400 USDC winning pool, and the 196 USDC left " + + "of the losing pool for the winners to share.", + actions: [ + // The settlement fields join the event box, then light up as written. + { + type: "show", + ids: ["event"], + lines: { + event: [ + field("status: Open"), + field("betting_closes_at: month's end"), + field("fee_bps: 200"), + field("total_pool: 600 USDC"), + field("open_bets: 3"), + field("winning_outcome_index: 0 (Glowbugs 3)"), + field("winning_pool: 400 USDC"), + field("distributable_losing_pool: 196 USDC"), + ], + }, + }, + { + type: "set", + changes: [ + { id: "event", key: "status", value: "Settled" }, + { id: "event", key: "winning_outcome_index", value: "0 (Glowbugs 3)" }, + { id: "event", key: "winning_pool", value: "400 USDC" }, + { id: "event", key: "distributable_losing_pool", value: "196 USDC" }, + ], + }, + ], + }, + + // ---- The winners claim + { + title: "Alice runs [claim_winnings()]", + caption: + "Her stake back, plus her share of the 196 in proportion to her stake: 300 + 300 × 196 ÷ 400 = 447 USDC. " + + "Her bet account closes as she is paid, so she can never claim twice.", + actions: [ + { type: "call", handler: "claim_winnings()", focus: ["alice", "aliceUsdc", "aliceBet", "program", "event", "vault"] }, + { type: "set", changes: [{ id: "event", key: "open_bets", value: "2" }] }, + transfer("vault", "149 USDC", "aliceUsdc", "1,147 USDC", { + id: "aliceWins", d: payout(A.aliceUsdc, LANE.alice), + coinNear: corridor(400, OUT_Y), label: ["claim_winnings()", "447 USDC"], labelAt: above, + }), + { type: "close", id: "aliceBet" }, + ], + }, + { + title: "Bob claims [149 USDC]", + caption: + "100 + 100 × 196 ÷ 400 = 149. Alice staked three times what Bob did, and won three times as much. " + + "When either of them bet made no difference: the payout reads the pools at the close.", + actions: [ + { type: "call", handler: "claim_winnings()", focus: ["bob", "bobUsdc", "bobBet", "program", "event", "vault"] }, + { type: "set", changes: [{ id: "event", key: "open_bets", value: "1" }] }, + transfer("vault", "0 USDC", "bobUsdc", "1,049 USDC", { + id: "bobWins", d: payout(A.bobUsdc, LANE.bob), + coinNear: corridor(480, OUT_Y), label: ["claim_winnings()", "149 USDC"], labelAt: above, + }), + { type: "close", id: "bobBet" }, + ], + }, + { + title: "Carol runs [close_losing_bet()]", + caption: + "Carol's 200 USDC went to the winners, but her bet account still holds the SOL it needed to exist, its " + + "rent. Closing it gives the rent back to her.", + actions: [ + { type: "call", handler: "close_losing_bet()", focus: ["carol", "carolBet", "program", "event"] }, + { type: "set", changes: [{ id: "event", key: "open_bets", value: "0" }] }, + { type: "close", id: "carolBet" }, + ], + }, + + // ---- Closing the market + { + title: "Maria runs [close_outcome()]", + caption: + "With no bets left open, Maria closes each outcome, and its rent comes back to her. An outcome can't close " + + "while any bet still names it.", + actions: [ + { type: "call", handler: "close_outcome()", focus: ["maria", "program", "event", "outcome0", "outcome1"] }, + { type: "close", id: "outcome0" }, + { type: "close", id: "outcome1" }, + ], + }, + { + title: "Maria runs [close_event()]", + caption: + "Last, the vault and the event close. Any dust the rounding left would go to the fee recipient; here the " + + "shares divided exactly, and the vault is empty.", + actions: [ + { type: "call", handler: "close_event()", focus: ["maria", "program", "event", "vault"] }, + { type: "close", id: "vault" }, + { type: "close", id: "event" }, + ], + }, + ]; + + window.BETTING_SCENE = { + title: "Betting Market", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 542, w: 540, h: 84, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/betting-market/slides.js b/animations/betting-market/slides.js new file mode 100644 index 00000000..fceb8b22 --- /dev/null +++ b/animations/betting-market/slides.js @@ -0,0 +1,152 @@ +// The Betting Market talk: the slides around the scene's diagram steps. +// Diagram runs name the scene steps they show, by index, and together they +// show every step once, in order. Each term is defined where the talk first +// needs it. + +(function () { + window.BETTING_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build a", "[betting market]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Betting Market chapter", + items: [ + "How a betting market works as a Solana program, with no bookmaker", + "How a program learns a fact from the real world, and what that costs in trust", + "How closing accounts stops anyone being paid twice", + ], + }, + ], + }, + + // ---- What people want, and how a betting pool gives it to them. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:betting-backs", who: "Alice", + name: "Thinks [Glowbugs 3] will win", + text: "She's confident about school holidays, and wants to put $300 on it being this month's top-grossing film.", + }, + { + tone: "lavender", icon: "tpl:betting-against", who: "Carol", + name: "Thinks [The Quiet Floor] will", + text: "She believes in word of mouth, and wants to put $200 on The Quiet Floor instead.", + }, + ], + }, + { + type: "split", + heading: "Two ways to [bet] on it", + sub: "Both let Alice and Carol put money on their view", + cards: [ + { icon: "tpl:betting-house", name: "With a bookmaker", text: "A house sets the odds, the payout for each dollar staked, and takes the other side of every bet, carrying the risk itself" }, + { icon: "tpl:betting-pool", name: "Without one: a parimutuel pool", text: "Every stake goes into one pool. When the result is known, the winners share the losers' stakes" }, + { icon: "tpl:betting-fee", name: "The house takes a fee", text: "instead of a side: here 2%, and only out of the losing stakes" }, + ], + }, + { + type: "grid", + tone: "lavender", + heading: "The words of a [parimutuel] market", + sub: "Devised in Paris in 1867, and still how racetrack pools work", + cards: [ + { icon: "tpl:betting-film", name: "Event", text: "The question being bet on: this month's top-grossing film" }, + { icon: "tpl:betting-stake", name: "Stake", text: "What a bettor puts in on one outcome" }, + { icon: "tpl:betting-odds", name: "Odds", text: "Set by the pools when betting closes, not when you bet, so they move as people bet" }, + { icon: "tpl:betting-won", name: "Winnings", text: "Proportional to stake: bet three times as much, win three times as much" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, Maria's market, and the three bets. + { type: "diagram", from: 0, to: 13 }, + { + type: "allocation", + heading: "The pool when betting [closes]", + sub: "600 USDC in one vault. Whoever wins, the losing side's stakes pay the winners", + parts: [ + { tone: "mint", name: "Glowbugs 3", text: "Alice 300 + Bob 100 = 400 USDC", value: 400 }, + { tone: "lavender", name: "The Quiet Floor", text: "Carol 200 USDC", value: 200 }, + ], + }, + // The cancelled future, then settlement. + { + type: "statement", + heading: "Outcome 1: the studio [pulls] both films", + }, + { type: "diagram", from: 14, to: 15 }, + { + type: "statement", + heading: "Outcome 2: Glowbugs 3 [wins]", + }, + { type: "diagram", from: 16, to: 18 }, + { + type: "allocation", + decimals: 1, + // Hold the stakes long enough to read before the losing side pays out. + delay: 2200, + heading: "Glowbugs 3 wins: the losing stake pays the [winners]", + sub: "From each bettor's stake to each bettor's payout. Carol's 200 goes to Alice and Bob in proportion to their stakes, less Maria's 4 USDC fee", + parts: [ + { tone: "mint", name: "Alice", fromText: "staked 300 USDC", text: "447 USDC: her 300, plus 147", from: 300, value: 447 }, + { tone: "lavender", name: "Bob", fromText: "staked 100 USDC", text: "149 USDC: his 100, plus 49", from: 100, value: 149 }, + { tone: "white", name: "Carol", fromText: "staked 200 USDC", text: "lost her stake", from: 200, value: 0 }, + { tone: "white", name: "Maria", text: "4 USDC fee", from: 0, value: 4, callout: true }, + ], + }, + // The claims, and closing the market. + { type: "diagram", from: 19, to: 23 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:betting-won", name: "Alice", text: "Won 147 USDC on her 300: three times Bob's winnings, for three times his stake" }, + { tone: "lavender", icon: "tpl:betting-won", name: "Bob", text: "Won 49 USDC on his 100, paid at the same final odds as Alice" }, + { tone: "mint", icon: "tpl:betting-against", name: "Carol", text: "Lost her 200 USDC to the winners, and got her account's rent back" }, + { tone: "white", icon: "tpl:betting-fee", name: "Maria the admin", text: "Earned 4 USDC, 2% of the losing pool, and never took a side" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/constant-product-amm/index.html b/animations/constant-product-amm/index.html new file mode 100644 index 00000000..3a67c92b --- /dev/null +++ b/animations/constant-product-amm/index.html @@ -0,0 +1,50 @@ + + + + + +Constant-Product AMM Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/constant-product-amm/scene.js b/animations/constant-product-amm/scene.js new file mode 100644 index 00000000..75007733 --- /dev/null +++ b/animations/constant-product-amm/scene.js @@ -0,0 +1,515 @@ +// The Constant-Product AMM chapter as an animated scene: Maria opens an +// ACME/USDC pool with its first deposit, Alice adds liquidity, Bob buys and +// Carol buys after him, Bob sells back, Maria sweeps the admin's share of the +// fees, and Alice withdraws. +// +// The columns are the chapter figures' accounts spread across a 16:9 screen: +// the four people, then the pool's two vaults and its LP mint, then the +// program and its two config accounts. The ACME and USDC mints are named only +// in seeds, as in the figures. Arrows run down a lane beside each person's +// column, along a corridor beneath them, and up the lane beside the vaults, +// one transfer on screen at a time. The steps follow the handlers in +// quicknode/solana-program-examples finance/token-swap: a swap records the +// admin's fee before any transfer, and pays out before it takes in when the +// input is USDC (token B), and takes in first when the input is ACME. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, drop: 60, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + const GAP3 = 37; + + const COLUMN = { + maria: [12, 120], + alice: [160, 120], + bob: [312, 124], + carol: [464, 124], + vaults: [624, 150], + program: [880, 224], + }; + + const ata = (owner, token, x, y, w) => + derived("token", `${owner}'s ${token}`, x, y, w, [`${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", `${token === "LP" ? "LP" : token.toUpperCase()} MINT`]); + + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const carol = onCurve("wallet", "Carol", ...COLUMN.carol); + const slot = (person, n) => person.y + 77 * n; + + // The pool's vaults and LP mint, in a column of their own. + const vaultSeeds = (token) => ["POOL CONFIG'S ADDRESS +", "TOKEN PROGRAM +", `${token} MINT`]; + const poolA = derived("token", "pool_a (ACME)", COLUMN.vaults[0], 150, COLUMN.vaults[1], vaultSeeds("ACME")); + const poolB = derived("token", "pool_b (USDC)", COLUMN.vaults[0], poolA.y + tall(2) + GAP3, COLUMN.vaults[1], vaultSeeds("USDC")); + const lpMint = derived("mint", "LP mint", COLUMN.vaults[0], poolB.y + tall(2) + GAP3, COLUMN.vaults[1], ["CONFIG'S ADDRESS +", "ACME MINT + USDC MINT +", '"LIQUIDITY"']); + + // The program and its two config accounts. + const program = onCurve("program", "AMM program", ...COLUMN.program); + const config = derived("struct", "config", COLUMN.program[0], program.y + 90 + GAP2, COLUMN.program[1], ['"CONFIG"']); + const poolConfig = derived("struct", "pool config", COLUMN.program[0], config.y + tall(3) + GAP2, COLUMN.program[1], ["CONFIG'S ADDRESS +", "ACME MINT + USDC MINT"]); + + const accounts = { + maria, + mariaAcme: ata("Maria", "ACME", COLUMN.maria[0], slot(maria, 1), COLUMN.maria[1]), + mariaUsdc: ata("Maria", "USDC", COLUMN.maria[0], slot(maria, 2), COLUMN.maria[1]), + mariaLp: ata("Maria", "LP", COLUMN.maria[0], slot(maria, 3), COLUMN.maria[1]), + alice, + aliceAcme: ata("Alice", "ACME", COLUMN.alice[0], slot(alice, 1), COLUMN.alice[1]), + aliceUsdc: ata("Alice", "USDC", COLUMN.alice[0], slot(alice, 2), COLUMN.alice[1]), + aliceLp: ata("Alice", "LP", COLUMN.alice[0], slot(alice, 3), COLUMN.alice[1]), + bob, + bobUsdc: ata("Bob", "USDC", COLUMN.bob[0], slot(bob, 1), COLUMN.bob[1]), + bobAcme: ata("Bob", "ACME", COLUMN.bob[0], slot(bob, 2), COLUMN.bob[1]), + carol, + carolUsdc: ata("Carol", "USDC", COLUMN.carol[0], slot(carol, 1), COLUMN.carol[1]), + carolAcme: ata("Carol", "ACME", COLUMN.carol[0], slot(carol, 2), COLUMN.carol[1]), + poolA, poolB, lpMint, + program, config, poolConfig, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // Each person has a lane on the right of their column; the corridor runs + // beneath every person's column; the vault lane runs up beside the vaults. + + const LANE = { maria: 146, alice: 296, bob: 450, carol: 600, vaults: 612 }; + const CORRIDOR = 448; + const right = (acc, dy = 20) => [acc.x + acc.w + 2, acc.y + dy]; + const left = (acc, dy = 26) => [acc.x - 2, acc.y + dy]; + + // From a person's account down their lane, along the corridor, and up into + // a vault or the LP mint. + function intoPool(from, lane, to) { + const [sx, sy] = right(from); + const [ex, ey] = left(to); + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [LANE.vaults, CORRIDOR], [LANE.vaults, ey], [ex, ey]], 6); + } + + // From a vault or the LP mint down to the corridor, and up a person's lane. + function outOfPool(from, lane, to) { + const [sx, sy] = left(from); + const [ex, ey] = right(to); + return rounded([[sx, sy], [LANE.vaults, sy], [LANE.vaults, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]], 6); + } + + // A coin sits on the corridor, its label beneath; for Carol, whose lane + // meets the vault lane at once, on her lane beneath her column. + const below = { dx: 0, dy: 22, anchor: "middle" }; + const leftOf = { dx: -14, dy: 4, anchor: "end" }; + const onCorridor = (lane) => ({ coinNear: { x: (lane + LANE.vaults) / 2, y: CORRIDOR }, labelAt: below }); + const onCarolsLane = { coinNear: { x: LANE.carol, y: 400 }, labelAt: leftOf }; + + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + alone: true, + from: { id: from, value: fromValue, key: from === "lpMint" ? "supply" : undefined }, + to: { id: to, value: toValue, key: to === "lpMint" ? "supply" : undefined }, + arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + const vault = (amount) => [balance(amount), note("authority: the pool config")]; + + const HANDLERS = [ + "initialize_config()", + "initialize_pool()", + "deposit_liquidity()", + "withdraw_liquidity()", + "swap_tokens()", + "claim_admin_fees()", + ]; + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "She keeps USDC, a token worth one US dollar, in a token account of her own. Every kind of token is " + + "defined by a mint, one of the three names its address is worked out from. It holds 1,000 USDC.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice owns 100 [ACME]", + caption: + "ACME is the stock of a robotics startup, launching on Solana today as a token. Alice works there, " + + "and holds a grant of 100 ACME in a second token account, one for each kind of token she owns.", + actions: [{ type: "show", ids: ["aliceAcme"], lines: { aliceAcme: [balance("100 ACME")] }, focus: "all" }], + }, + { + title: "Alice wants her ACME to [earn]", + caption: + "Alice wants to be a liquidity provider: to put her ACME, and the USDC that matches it, into a pool " + + "that traders swap against, and earn a share of every trade's fee.", + actions: [{ type: "focus", ids: ["alice", "aliceAcme", "aliceUsdc"] }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs automated market makers, and each line is an " + + "instruction handler anyone can call by sending a transaction. First, somebody has to open the pool.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + + // ---- The venue + { + title: "Maria runs [initialize_config()]", + caption: + "Maria operates the AMM. Her config sets the trading fee in basis points, hundredths of a percent: 30, " + + "so 0.3% of every trade. 1,667 basis points of that fee, about a sixth, is the admin's: hers.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_config()", focus: ["maria", "program"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (admin)" }] }, + { type: "create", id: "config", lines: [field("admin: Maria"), field("fee: 30 bps"), field("admin_share_bps: 1,667")] }, + ], + }, + { + title: "Maria runs [initialize_pool()]", + caption: + "She holds 400 ACME of founder stock. The pool config records the pair; the two vaults are token " + + "accounts only the pool config can sign for, and the LP mint is the mint for the pool's receipts.", + actions: [ + { + type: "show", + ids: ["mariaAcme", "mariaUsdc"], + lines: { mariaAcme: [balance("400 ACME")], mariaUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "initialize_pool()", focus: ["maria", "mariaAcme", "mariaUsdc", "program", "config"] }, + { + type: "create", id: "poolConfig", + lines: [field("mint_a: ACME"), field("mint_b: USDC"), field("admin_fees_owed_a: 0"), field("admin_fees_owed_b: 0")], + }, + { type: "create", id: "poolA", lines: vault("0 ACME") }, + { type: "create", id: "poolB", lines: vault("0 USDC") }, + { type: "create", id: "lpMint", lines: [field("supply: 0 LP"), note("authority: the pool config")] }, + { type: "create", id: "mariaLp", lines: [balance("0 LP")] }, + ], + }, + { + title: "Maria's 400 ACME go into the [pool]", + caption: + "The first deposit is taken by the instruction that creates the pool, so nobody else can set its " + + "launch price first.", + actions: [ + transfer("mariaAcme", "0 ACME", "poolA", "400 ACME", { + id: "mariaAcmeIn", d: intoPool(A.mariaAcme, LANE.maria, poolA), + ...onCorridor(LANE.maria), label: ["initialize_pool()", "400 ACME"], + }), + ], + }, + { + title: "900 USDC go in [alongside]", + caption: + "Her deposit sets the price: 900 ÷ 400 = $2.25 an ACME. Call the pool's ACME X and its USDC Y: " + + "K = X × Y = 360,000.", + actions: [ + transfer("mariaUsdc", "100 USDC", "poolB", "900 USDC", { + id: "mariaUsdcIn", d: intoPool(A.mariaUsdc, LANE.maria, poolB), + ...onCorridor(LANE.maria), label: ["900 USDC"], + }), + ], + }, + { + title: "Maria gets 599.9999 [LP tokens]", + caption: + "LP tokens are receipts: each is a claim on a slice of the pool. The first deposit mints √K = 600, less " + + "0.0001 never minted to anyone, so a donation can never make a later deposit round to nothing.", + actions: [ + transfer("lpMint", "599.9999 LP", "mariaLp", "599.9999 LP", { + id: "mariaMint", d: outOfPool(lpMint, LANE.maria, A.mariaLp), + ...onCorridor(LANE.maria), label: ["599.9999 LP"], + }), + ], + }, + + // ---- Alice adds liquidity + { + title: "Alice runs [deposit_liquidity()]", + caption: + "A liquidity provider can't change the pool's price, so her 100 ACME must come with 225 USDC: 100 × $2.25. " + + "The handler clamps her deposit to that ratio. Her LP account is created.", + actions: [ + { type: "call", handler: "deposit_liquidity()", focus: ["alice", "aliceAcme", "aliceUsdc", "program", "poolConfig", "poolA", "poolB", "lpMint"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (LP)" }] }, + { type: "create", id: "aliceLp", lines: [balance("0 LP")] }, + ], + }, + { + title: "Alice's 100 ACME go [in]", + caption: "Into the same vault as Maria's ACME.", + actions: [ + transfer("aliceAcme", "0 ACME", "poolA", "500 ACME", { + id: "aliceAcmeIn", d: intoPool(A.aliceAcme, LANE.alice, poolA), + ...onCorridor(LANE.alice), label: ["deposit_liquidity()", "100 ACME"], + }), + ], + }, + { + title: "225 USDC go in [alongside]", + caption: "X = 500 and Y = 1,125, so K grows to 562,500, and the price is still exactly $2.25. Deposits grow K without moving the price.", + actions: [ + transfer("aliceUsdc", "775 USDC", "poolB", "1,125 USDC", { + id: "aliceUsdcIn", d: intoPool(A.aliceUsdc, LANE.alice, poolB), + ...onCorridor(LANE.alice), label: ["225 USDC"], + }), + ], + }, + { + title: "Alice gets 150 [LP tokens]", + caption: + "Minted in proportion to what she added: 100 ACME against the 400 already there, times 600 LP counting " + + "the unminted floor. She owns a fifth of the pool.", + actions: [ + transfer("lpMint", "749.9999 LP", "aliceLp", "150 LP", { + id: "aliceMint", d: outOfPool(lpMint, LANE.alice, A.aliceLp), + ...onCorridor(LANE.alice), label: ["150 LP"], + }), + ], + }, + + // ---- Bob buys + { + title: "Bob runs [swap_tokens()]", + caption: + "Bob is early and bullish: he spends 100 USDC on ACME, with a min_output_amount, the least ACME he will " + + "accept, as his slippage check. His ACME account is created.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc"], + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "swap_tokens()", focus: ["bob", "bobUsdc", "program", "config", "poolConfig", "poolA", "poolB"] }, + { type: "set", changes: [{ id: "bob", title: "Bob (trader)" }] }, + { type: "create", id: "bobAcme", lines: [balance("0 ACME")] }, + ], + }, + { + title: "The [fee] comes off first", + caption: + "0.3% of 100 USDC is 30 cents. About 5 cents is recorded as owed to the admin, and stays in the vault " + + "until she claims it; the other 25 cents is the LPs'. The curve prices the remaining 99.70.", + actions: [{ type: "set", changes: [{ id: "poolConfig", key: "admin_fees_owed_b", value: "0.05" }] }], + }, + { + title: "The pool pays Bob ≈40.7 [ACME]", + caption: + "The amount that keeps X × Y at K: 562,500 ÷ (1,125 + 99.70) ≈ 459.3 ACME left. Paid by the pool config's " + + "signature, before Bob's USDC is taken in.", + actions: [ + transfer("poolA", "≈459.3 ACME", "bobAcme", "≈40.7 ACME", { + id: "bobBuyOut", d: outOfPool(poolA, LANE.bob, A.bobAcme), + ...onCorridor(LANE.bob), label: ["swap_tokens()", "≈40.7 ACME"], + }), + ], + }, + { + title: "Bob's 100 USDC go [in]", + caption: + "He paid ≈$2.46 an ACME, though the price was $2.25 before and is ≈$2.67 after: price impact, his own " + + "trade moving the price. Then the handler checks X × Y did not shrink, or it fails (InvariantViolated).", + actions: [ + transfer("bobUsdc", "900 USDC", "poolB", "1,225 USDC", { + id: "bobBuyIn", d: intoPool(A.bobUsdc, LANE.bob, poolB), + ...onCorridor(LANE.bob), label: ["100 USDC"], + }), + ], + }, + + // ---- Carol buys after him + { + title: "Carol runs [swap_tokens()]", + caption: + "Carol buys $50 of ACME at the price Bob's trade made. Of her 15 cents of fee, about 2.5 cents is owed " + + "to the admin. Her ACME account is created.", + actions: [ + { + type: "show", + ids: ["carol", "carolUsdc"], + lines: { carol: [sol("1 SOL")], carolUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "swap_tokens()", focus: ["carol", "carolUsdc", "program", "config", "poolConfig", "poolA", "poolB"] }, + { type: "set", changes: [{ id: "carol", title: "Carol (trader)" }] }, + { type: "create", id: "carolAcme", lines: [balance("0 ACME")] }, + { type: "set", changes: [{ id: "poolConfig", key: "admin_fees_owed_b", value: "0.075" }] }, + ], + }, + { + title: "Carol pays the price Bob [made]", + caption: "About 17.96 ACME out, at an average near $2.78, then her 50 USDC in. The price moves from $2.67 to ≈$2.89.", + actions: [ + transfer("poolA", "≈441.3 ACME", "carolAcme", "≈17.96 ACME", { + id: "carolOut", d: outOfPool(poolA, LANE.carol, A.carolAcme), + ...onCarolsLane, label: ["≈17.96 ACME"], + }), + transfer("carolUsdc", "950 USDC", "poolB", "1,275 USDC", { + id: "carolIn", d: intoPool(A.carolUsdc, LANE.carol, poolB), + ...onCarolsLane, label: ["50 USDC"], + }), + ], + }, + + // ---- Bob sells back + { + title: "Bob [sells] 20 ACME back", + caption: + "The same handler with the input flipped, so the fee comes off his ACME: 0.06 ACME, of which 0.01 is " + + "owed to the admin. The admin is now owed fees in both tokens.", + actions: [ + { type: "call", handler: "swap_tokens()", focus: ["bob", "bobUsdc", "bobAcme", "program", "config", "poolConfig", "poolA", "poolB"] }, + { type: "set", changes: [{ id: "poolConfig", key: "admin_fees_owed_a", value: "0.01" }] }, + ], + }, + { + title: "Bob's 20 ACME go [in]", + caption: "With ACME as the input, the handler takes it in before it pays out.", + actions: [ + transfer("bobAcme", "≈20.7 ACME", "poolA", "≈461.3 ACME", { + id: "bobSellIn", d: intoPool(A.bobAcme, LANE.bob, poolA), + ...onCorridor(LANE.bob), label: ["swap_tokens()", "20 ACME"], + }), + ], + }, + { + title: "The pool pays Bob ≈55.11 [USDC]", + caption: "An average near $2.76 an ACME, against the $2.46 he paid. The price falls back to ≈$2.64.", + actions: [ + transfer("poolB", "≈1,219.89 USDC", "bobUsdc", "≈955.11 USDC", { + id: "bobSellOut", d: outOfPool(poolB, LANE.bob, A.bobUsdc), + ...onCorridor(LANE.bob), label: ["≈55.11 USDC"], + }), + ], + }, + + // ---- The admin's fees + { + title: "Maria runs [claim_admin_fees()]", + caption: + "Only the config's admin may call it, and only when something is owed (NothingToClaim). It zeroes both " + + "counters before it pays.", + actions: [ + { type: "call", handler: "claim_admin_fees()", focus: ["maria", "mariaAcme", "mariaUsdc", "program", "config", "poolConfig", "poolA", "poolB"] }, + { + type: "set", + changes: [ + { id: "poolConfig", key: "admin_fees_owed_a", value: "0" }, + { id: "poolConfig", key: "admin_fees_owed_b", value: "0" }, + ], + }, + ], + }, + { + title: "Maria sweeps her [fees]", + caption: "One transfer per token, however many swaps accrued it: 0.01 ACME and ≈0.075 USDC.", + actions: [ + transfer("poolA", "≈461.3 ACME", "mariaAcme", "≈0.01 ACME", { + id: "claimA", d: outOfPool(poolA, LANE.maria, A.mariaAcme), + ...onCorridor(LANE.maria), label: ["claim_admin_fees()", "0.01 ACME"], + }), + transfer("poolB", "≈1,219.81 USDC", "mariaUsdc", "≈100.08 USDC", { + id: "claimB", d: outOfPool(poolB, LANE.maria, A.mariaUsdc), + ...onCorridor(LANE.maria), label: ["≈0.075 USDC"], + }), + ], + }, + + // ---- Alice withdraws + { + title: "Alice runs [withdraw_liquidity()]", + caption: + "She gets a slice of both vaults, less what the admin is still owed: her 150 LP over the supply plus the " + + "unminted floor, 750. A fifth of each.", + actions: [ + { type: "call", handler: "withdraw_liquidity()", focus: ["alice", "aliceAcme", "aliceUsdc", "aliceLp", "program", "config", "poolConfig", "poolA", "poolB", "lpMint"] }, + ], + }, + { + title: "Alice receives her [slice]", + caption: "≈92.27 ACME and ≈243.96 USDC. The pool's mix has shifted since she deposited 100 ACME and 225 USDC.", + actions: [ + transfer("poolA", "≈369.1 ACME", "aliceAcme", "≈92.27 ACME", { + id: "withdrawA", d: outOfPool(poolA, LANE.alice, A.aliceAcme), + ...onCorridor(LANE.alice), label: ["withdraw_liquidity()", "≈92.27 ACME"], + }), + transfer("poolB", "≈975.85 USDC", "aliceUsdc", "≈1,018.96 USDC", { + id: "withdrawB", d: outOfPool(poolB, LANE.alice, A.aliceUsdc), + ...onCorridor(LANE.alice), label: ["≈243.96 USDC"], + }), + ], + }, + { + title: "Her 150 LP are [burned]", + caption: + "At $2.64 she holds ≈$487.93; had she kept her tokens, ≈$489.41. That gap is impermanent loss: a pool " + + "sells what rises, so an LP trails just holding when the price moves. The fees are what pay for it.", + actions: [ + transfer("aliceLp", "0 LP", "lpMint", "599.9999 LP", { + id: "burn", d: intoPool(A.aliceLp, LANE.alice, lpMint), + ...onCorridor(LANE.alice), label: ["burn 150 LP"], + }), + ], + }, + ]; + + window.AMM_SCENE = { + title: "Constant-Product AMM", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 532, w: 540, h: 92, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/constant-product-amm/slides.js b/animations/constant-product-amm/slides.js new file mode 100644 index 00000000..a8510e74 --- /dev/null +++ b/animations/constant-product-amm/slides.js @@ -0,0 +1,143 @@ +// The Constant-Product AMM talk: the slides around the scene's diagram steps. +// Diagram runs name the scene steps they show, by index, and together they +// show every step once, in order. Each term is defined where the talk first +// needs it. + +(function () { + window.AMM_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build an", "[automated market maker]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Constant-Product AMM chapter", + items: [ + "How a pool prices every trade with one formula", + "How liquidity providers earn fees, and when they'd have done better just holding", + "Why the program checks its own arithmetic after every trade", + ], + }, + ], + }, + + // ---- What people want, and how a pool gives it to them, before any Solana. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:income", who: "Alice", + name: "Wants her tokens to [earn]", + text: "She holds ACME, a newly launched stock token, and some USDC. She'd like them to earn fees from " + + "traders, without posting prices or watching a screen all day.", + }, + { + tone: "lavender", icon: "tpl:amm-instant", who: "Bob", + name: "Wants to trade [instantly]", + text: "ACME launched today. On an exchange where people post prices, he might wait all day for a " + + "seller. He wants to buy now.", + }, + ], + }, + { + type: "split", + heading: "A [liquidity pool] gives both what they want", + sub: "An automated market maker, or AMM: nobody posts prices", + cards: [ + { icon: "tpl:amm-pool", name: "Liquidity providers fill a pool", text: "Alice and others deposit both tokens. They are called liquidity providers, or LPs" }, + { icon: "tpl:amm-formula", name: "A formula sets the price", text: "Bob trades against the pool at once, at whatever price the formula gives" }, + { icon: "tpl:amm-fee", name: "Every trade pays a fee", text: "0.3% of each trade, most of it kept in the pool for the LPs" }, + ], + }, + { + type: "numbered", + heading: "[X × Y = K] prices every trade", + sub: "The pool holds X of one token and Y of the other", + cards: [ + { name: "K is X times Y", text: "400 ACME and 900 USDC make K = 360,000" }, + { name: "A trade keeps K fixed", text: "Add USDC, and the pool pays out the ACME that keeps X × Y at K" }, + { name: "The price is Y ÷ X", text: "So every buy makes the next one dearer, and every sell makes it cheaper" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, and Maria opening the pool. + { type: "diagram", from: 0, to: 10 }, + // Alice adds liquidity. + { type: "diagram", from: 11, to: 14 }, + { + type: "allocation", + heading: "Who owns the [pool]", + sub: "Each LP token is a claim on a slice of the pool. The 0.0001 LP floor is never minted to anyone", + parts: [ + { tone: "mint", name: "Maria", text: "599.9999 LP", value: 599.9999 }, + { tone: "lavender", name: "Alice", text: "150 LP: a fifth", value: 150 }, + ], + }, + // Bob and Carol trade, Maria claims, and Alice withdraws. + { type: "diagram", from: 15, to: 28 }, + { + type: "chart", + heading: "LPs win when fees outrun [impermanent loss]", + sub: "Alice's $450 position at withdrawal, against just holding, at different ACME prices", + x: [1, 9], xStep: 1, + y: [-250, 100], yStep: 50, + xLabel: "ACME's price at withdrawal", + yLabel: "LP minus holding ($)", + marks: [{ at: 2.25, label: "LAUNCH $2.25" }], + series: [ + { tone: "purple", label: "No fees", points: [[1.13, -19], [1.69, -4], [2.25, 0], [2.81, -3], [4.5, -39], [9, -225]], labelAt: [1.1, -60] }, + { tone: "green", label: "With $50 of fees", points: [[1.13, 31], [1.69, 46], [2.25, 50], [2.81, 47], [4.5, 11], [9, -175]], labelAt: [5.0, 60] }, + ], + }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:venue", name: "Maria the admin", text: "Collected the admin's share of every fee, and still holds 599.9999 LP" }, + { tone: "lavender", icon: "tpl:income", name: "Alice", text: "Earned her share of the fees, but trails just holding by ≈$1.50: the price moved on light trading" }, + { tone: "mint", icon: "tpl:amm-instant", name: "Bob", text: "Traded the moment he wanted: bought ≈40.7 ACME at ≈$2.46, and sold 20 at ≈$2.76" }, + { tone: "white", icon: "tpl:price-rises", name: "Carol", text: "Paid ≈$2.78 an ACME: the price Bob's buy had made" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/deck.css b/animations/deck.css new file mode 100644 index 00000000..ecc416c4 --- /dev/null +++ b/animations/deck.css @@ -0,0 +1,331 @@ +/* The slides around the animated diagrams, in the look of the Quicknode + Solana Finance Keynote: Helvetica Neue for words, Andale Mono for tags, + a green and a purple highlight, and four card colours. Sizes are in cqw, + hundredths of the stage's width, so a slide scales as one picture. */ + +@font-face { font-family: "DejaVu Sans Mono"; src: url("../assets/fonts/DejaVuSansMono.ttf"); } +@font-face { font-family: "DejaVu Sans Mono"; src: url("../assets/fonts/DejaVuSansMono-Bold.ttf"); font-weight: bold; } + +:root { + --black: #040406; + --dark: #131313; + --slab: #2f2f2f; + --paper: #f4f4f4; + --white: #fcfcfc; + --lavender: #efeafe; + --mint: #d9fbda; + --green: #95fc86; + --purple: #987bf2; + --ink: #2a2a2a; + --sans: "Helvetica Neue", Helvetica, Arial, sans-serif; + --mono: "Andale Mono", "DejaVu Sans Mono", Menlo, monospace; + --mark: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQEAAADbCAYAAABtPiQAAAAOI0lEQVR4nO2doZMcxxXGf3JFG24B3RmZyAbnP0ACPnM7qRoHhcREDnH4CQWFSCJBMZFDEi4JxOYSiBViYh2ITIzu5KrIxncGEzA70Wqzd9rd6573dff3q3q1UpU029Pd+817r990X2LgMqZ1fo5ugInhEnAA3IluiJHkh/nnv+efz4AXwI/Adwt/fz5900wqfhHdACPN1aXP/XP+7Q8MYvE1g0A8AQ7zNc2kwiJgUnF1bstCccogCF/OzcIgxiVgB/gG2A1ui2mHQwaP4e8MAnEa2xwzcgD0NluAPQVuA3uYcGbAPeInha1dO2GYg+flH8wEdMAR8RPCZrMgBOMQwaZiRwyCsIOZnBlwn/hJYLONdsTgrZqJ6XCIYNOy0TuYYSZjxlBdGD34NtuyWQy25NKW/28GfI9rC4wej4HPcFHS2ryx5f87Bd4CPgaO0zXHmAuzz1B38AgnESfDtQU2ZXOY8Bq2DQdW4RDBKPMF8Adcovx/bBsOrGIMET7FIYLR41OGh1QX2ww9UnoCi8yAvzB0vDFqHANvY68ASOsJLHIK/B74AHsFRo9dhncUbkc3pCVcfmxTtSP89uJkeBXBpmwHNEqunMB5dMDneBXB6NFkriBXTuA8HjKsItwK+G5jzmPMFdyMbkhL+A1Fm6o1kzSMCAdW0eEQwejRRHgQEQ6s4iFDZ9+NbYYxr7DLUGBU9eqBiiewiMuPjSK3qPQhpeIJLOI3FI0id2h4GTES1xbY1Ky6hKFiOLAKhwhGiQfAb6IbkYpSRGDkJvAnLAabcAr8xKuHir6OK3MDeJeXZxGalxwC70U3IgWliQDYK1jmlOEA0PEg0PHPL0h/3PgOgzhcB64BN+Z/rzp7fg5VCEGJIgDDpHsa3YggDoF/AP+af6b+oW/LHoM4fDT/bEWkqxCCUjkhPkk0hZV6Tt+MoQjsPvVvVd/qAymc6IHPaY+or359j0HMahWER+m6yqxDR/yg+4e/PTsMS7+1CcK9lJ1kzmZGPaHACUMBSstbY+8zCGD0WKQyFxRlZkYdT4+ntPPUX5eaCsMsBBkpXQAeUV6Cb2pmDD+i0sfax6lnoOQzEP3j35zSxeAEH3qSlFI3KvUR2hen5DDhKEN/NMke8YO5qY0JP5OOGUMuJXpsN7X7OTqjJUpMBD7CbmBOOsqbE04CX4CSlo68QeV0lBgiOCe0BSXlAfz0j6GjnJoR5wc2ZEb8oK1rdzL1gVmPkkJGVxRuQAmDegK8n6sDzMaUsoTs+oE1KCEMOMLuvyIlzJ2TbHdfCSWEAX5bTJs99PMEXjY8B/Uw4It8t24SUkKewKsFK1B35Vz8UxbqQuDVgiXUXw+2AJSJuhB4Xi2gXPjhgSobZSHwS0ZzdogfDAtA3SgLgRPN6A6Ok4B1oSwETScJO+IHYJV9m/GeTRw7aOaemvYGFJXZhUB18zHxc2yVNekNdMR3/LI5UdMGisvRTZ5doOgFdDlv2Eih+Jp6l/OG1eiI7/Bl80pAe6g9iJrKDah1vqu32kRx67omcgMd8R29bM4DtIvaK8hNeANqsZjDAKPmmVbtDai5Xw4DDOjNy6q9AbV3BBwGmBG1sKBK1DYM8d6AZhmlasIqw9SO+I4dzVWBZhUd8XNztCq3IVNKvnR5b9UUjFLiuqoEoVLixclAcx5Kc7WqBKFSQrDLe6umApS8gWpQCQXsBZh1UPIGqjjabp/4jhyty3urpiJUvIEqQgKVUMBegNkEJW+geFTWXrvM92nqQ8UbKDokUFFTewFmG24SP3d7Cg8JVEIBnwZrtkXFky0WlVUBVweabVF5p6DLdYNv5Loww86uuxmvvy6PgdPoRphi+Vt0A+Z8FN2AbVCJp7rM92nqRyFBmO1dgpyewCcZr70JX0U3wBTPl9ENYAhpL0c3YlMUEipFZ1WNDCqvwWdZKszlCeyhkYz7c3QDTBWcMuSWorme46K5RCBLY7fAoYBJhUJIkCU5mEsEFDKZXhUwKVEQgV0y5AVq9gQUBs3UwyEaD5XkD9hcIqBQH2ARMKlRqBm4kfqCOURAYUukUwblNiYlCjkmBS/7tSgUCXlp0ORAYakwedFQDk9AISnoUMDk4JT4vEDyoqEcIvBOhmtuikXA5EJhbiXNC9SaE3A+wORCQQSupbxYahHYSXy9bTiOboCpmu+iG0Bibzu1CFxJfL1tUBgkUy9PohuAuCegsHyh4K6ZelFIDib9naUWAYWkoIJSm7qJ9jaTFuOlFoGkbsqWvIhugKmer6MbQMJlwhpzAl4ZMLmJ9gQg4W8ttQi8m/h6mxIdq5k2UBCBZKF3ahG4mvh6m/Is+PtNGyjMszdTXSjnHoMR/BjdANME9gTOQGE7MQWFNvWjEHZK5gQUVgbsCZipiBYChwNn4OVBMxU/BX+/pCeggMMBMxX/Cf5+SRFQqBY0ZiqivU6HA2egkLU1ZgokPQFjWqKa0DOlCCRzT4wx05FSBBTeGzDGbIjDAWMaxyJgTONYBIxpnJQi4OU5YwrEnoAx21FNcVxtIqDwEpMxU5CsYrE2ETCmFZK9MZtSBBQqqFyrYKYieiu9ZNTmCVgETCtIhgMKqwPOCZipiN5PU1IEjDHTkeyhm1IEordbAo1j0Ez9KBy8m4zUnkC0EDgnYKZAYZ4lS8SnFoHofdeSntFmzBkoeJyS4QDAPxNfbxuSndFmzBkoVAvKJgaj910DuBHdAFM9CqtQz1NdKLUIeJnQtEC0J5A091ajCCjEa6Zu9oK/P2l1bmoRUDi33SJgcqKwPJj0YZtaBJLFKRcg2lUzdaMwv56kvFiOisHoWoEZXiEw+fgougEUIAJJG7glCgNl6kQh3Ey6ClerCHiZ0ORiP7oBwGHKi9UqAr+LboCpkuhVAYCnqS+YQwQUVghcPmxyoBBmJl+GzyECz4lPDgJ00Q0w1aEgAl+mvmCu/QQUioYUBszUhUI+QCHcXos7QB9sJ9nv0rTEPvFzus9xY7k8AQW1mqGRyDF1oJBsfpzjorlE4EGm626KQwKTCoW5pPBw3YjnxLtOR9nv0rTAHvFzuUcjJ7ERCnmBHocE5uLcI34e97luLuduwyquyyfRDTDFoxAKZMkHTEG0cvZ4lcBcjI74OdwDB5nvMxuPiO+8HocEZns8hy/ITeI7r2cYSGM2ZUb83O0pPMGt0ok9GjvCmLJQSQjey32juVFYKuwZViuMWZcZwxM4et72FBwKjBwQ34k9ThCazeiIn7M9hYcCIyqFFj0FZ1jN5Kh4AcWHAiMqGVZ7A2YdOuLn6mjFhwIjKiFBj70B83pUvIAqQoFFojt0tBOGpI8xq1B6YFUTCoyohARVdq5JgtKKQE+FDyulBGFPRbGWSYZKXUBPxQVuJ8R3bvWdbLZCqbCtp+I9MpXirZ6hrNkY0AoDqksILqPkDThJaMAPp8lR2WxkNIcFbaMWBvQ08GBS7PTqldeciVIY0NPQypXScmGPw4JWUQsDehqah2rLhT0NJGPMK7xP/Jxbtma8gBE1b6AHbme9Y6OCWlHQaM14ASOK3kCP8wMtoCgAzXkBI4reQI+rCWvmC+Ln1yprzgsYUVwp6HGisFYUE4E9DXsBI2p1A6MdYSGoCVUB8Dybo1RF6AGqD5Vdr1eZc1BzlAfJQlA2HfFz6Ly5ZRZ4SvygWAjqoiN+7pxnxR0wmhvVJUMLQZmo5gBGaz4ZeBaqScJFIfAhJvqoC4AfKK9BsZBj0U6wG6eMah3AonW5br4W1MOC0bxrsRYz4Fvi58XrzGHAmqiHBaPdx26dAnvoe5A9DgM2poRB9cDGox7/L1qXpwvqpZSwYDSHB9MyQ/fdk1XmMGBLlIuIVpm9gmm4iW6V6VnzwlyAktR+NHsFedilzPngB0MCSskPLNoRjgFTUkqyeNn8bkAidijL/Vu0R/hJcBEOKHfs7REm5mPiB/Uidg+LwSZ0lOkBjvZt8h4xQFnLQeeJgXcuOpuSn/yjOUGcmRLKQtexpzhnsEgNP34LwISUmCE+b9K0GirsUddY9gwrGGYilPcf2NZG76BmQdhj2Nq9hqf+srkgaGJU945PKQgH1JE/2Gf4gdT4w1+0LlF/mQ2oXQhGO2F4WekmZexnMD7ta3P1X2dF1gRcim5AAmbA97QVi50CT4Cvga+AF8BhQDsuAzeAa8B14NfA1YB2qHAIvBfdiE2pQQSgTSFYxSgOz4DvGMRh/Bzt5zWuc3n+eWVu7wBvMvzY35nbNerOXWzLA+C3DGNRBLWIAFgIjBa3gLvRjViHmkQABiH4hjqSaaZ8jhm8gsfRDTmPN6IbkJhThpjsQXRDjOHlW4+t1oGEU+pbZ7Y6Tfat0trCgWUOGMTAGBWOgbcRShzWFg4scxf4AKEON82zy1D3cRuREKF2T2DEKwdGkWPgM+BhZCNq9wRGToG3GN5ANEaFXYYktreun5jSNi+1tWMhOxG1Eg4s4/DAqDJ5bUEr4cAyY3hwK7ohxiwxeW1Bq57AIvYKjCrHwB+Bv+b8EovAS1xTYFTJWlvQajiwirvAL4l5JdeY85CrLWiBjjY2K7GVZ7Llx7VSyw64tvrMtQUTMmPI1EYPus22ynzK0YRYDGyq5hBhYiwGNlXzvgUTM4qBE4g2JTtiw12PXSeQhg74HBccGR3Wri1wnUAaHjKUIb+H31Q0Goy1BQ4RAulo7/ANm6Y5cRjMDAuCTcNcWyCABcGmYK/UFjgxGMs+8CHwK3xWgpmW/21tZhHQYcZwnt+HDOf77cc2xzTCHYuANnsMwnCNQRiu45jOpOXYIlAelxkOBB3FwQeEmotgEaiQUSTg5WnCV+Z/X/wzC//GtMuz/wI/Ylg1wtrNhQAAAABJRU5ErkJggg=="); +} + +html, body { margin: 0; height: 100%; background: var(--black); overflow: hidden; } +body { display: grid; place-items: center; font-family: var(--sans); } + +/* The frame is 16:9 at the largest size the window allows. */ +#stage { + position: relative; + width: min(100vw, 100vh * 16 / 9); + aspect-ratio: 16 / 9; + container-type: size; + cursor: pointer; + overflow: hidden; + background: var(--black); +} +#stage > .layer { position: absolute; inset: 0; width: 100%; height: 100%; } +/* A diagram sits beneath the series bar, scaled to the height that leaves. */ +#stage > svg.layer { top: 3.3cqw; height: calc(100% - 3.3cqw); overflow: visible; } +#stage > .diagram-bar { position: absolute; inset: 0 0 auto; height: auto; z-index: 2; } +#stage > svg { display: block; } +.slide { position: relative; width: 100%; height: 100%; } +.layer { transition: opacity 0.35s; } +.layer.hidden { opacity: 0; pointer-events: none; } + +#hint { + position: fixed; right: 12px; bottom: 10px; + font: 12px var(--sans); color: #8d9196; + transition: opacity 0.6s; +} +#hint.hidden { opacity: 0; } +kbd { font-family: inherit; border: 1px solid #444; border-radius: 3px; padding: 0 4px; } + +/* ---- Slide frame ------------------------------------------------------- */ + +.slide { box-sizing: border-box; color: var(--ink); } +.slide.light { background: var(--paper); } +.slide.dotted { + background-color: var(--paper); + background-image: radial-gradient(#d6d6d6 0.09cqw, transparent 0.1cqw); + background-size: 2.4cqw 2.4cqw; +} +.slide.lavender { background: var(--lavender); } +.slide.mint { background: var(--mint); } +.slide.dark { background: var(--dark); color: #f0f0f0; } + +/* The bar across the top: the mark, the series name, the handle, a rule. */ +.bar { + /* 3.3cqw including its rule, so a diagram placed beneath it never covers it. */ + box-sizing: border-box; + height: 3.3cqw; + display: flex; align-items: center; gap: 1.6cqw; + padding: 0 2.4cqw 0 3cqw; + border-bottom: 0.12cqw solid #555; + font: 0.7cqw var(--mono); letter-spacing: 0.08cqw; text-transform: uppercase; +} +.bar .handle { margin-left: auto; } +.light .bar, .dotted .bar { background: #e6e6e6; color: #444; } +.lavender .bar { background: var(--lavender); color: #2b2160; } +.mint .bar { background: #d2fbd3; color: #134d1a; } +.dark .bar { background: #2b2b2b; color: #bdbdbd; } + +/* The Quicknode mark, recoloured from one mask. The mask is inlined + (assets/quicknode-mark.png) because a page opened from disk may not use + another file as a mask. */ +.mark { + display: inline-block; width: 1.25cqw; aspect-ratio: 257 / 219; + background: currentColor; + -webkit-mask: var(--mark) center / contain no-repeat; + mask: var(--mark) center / contain no-repeat; +} + +.body { padding: 4.5cqw 6cqw; } + +/* Highlights: green on light and dark slides. On a pastel, a highlight takes + the saturated form of that pastel's own hue: green on anything mint, + purple on anything lavender. */ +mark { background: var(--green); color: var(--ink); padding: 0 0.3cqw; } +mark.purple { background: var(--purple); color: #fff; } +:is(.slide.mint, .panel.mint, .card.mint, .seg-box.mint, .grid-card.mint) mark { background: var(--green); color: var(--ink); } +:is(.slide.lavender, .panel.lavender, .card.lavender, .seg-box.lavender, .grid-card.lavender) mark { background: var(--purple); color: #fff; } + +.tag { + display: inline-block; + font: 1.1cqw var(--mono); letter-spacing: 0.1cqw; text-transform: uppercase; + padding: 0.35cqw 0.8cqw; +} +.tag.outline { border: 0.12cqw solid #222; } +.tag.purple { background: var(--purple); color: #fff; } +.tag.green { background: var(--green); color: #134d1a; } + +/* ---- Title ------------------------------------------------------------- */ + +.title-slide h1 { + font-weight: 400; font-size: 6.4cqw; line-height: 1.12; letter-spacing: -0.12cqw; + margin: 2.2cqw 0 0; color: var(--ink); +} +.title-slide .logo { + position: absolute; right: 2.6cqw; bottom: 3.6cqw; + width: 6cqw; aspect-ratio: 1; background: var(--green); + display: grid; place-items: center; color: #111; +} +.title-slide .logo .mark { width: 4cqw; } + +/* ---- Know and learn ---------------------------------------------------- */ + +.columns { display: grid; grid-template-columns: 1fr 1fr; gap: 5cqw; } +.columns h2 { font-weight: 400; font-size: 3.2cqw; margin: 0; } +.columns .sub { font-size: 1.15cqw; color: #555; margin: 0.6cqw 0 1.6cqw; } +.columns ul, .qr-slide ul { margin: 0; padding-left: 1.8cqw; } +.columns li, .qr-slide li { font-size: 1.9cqw; line-height: 1.55; margin-bottom: 0.7cqw; } +.columns li::marker, .qr-slide li::marker { font-size: 1.4cqw; } + +/* ---- Cards ------------------------------------------------------------- */ + +.cards-slide { + height: calc(100% - 3.3cqw); box-sizing: border-box; + display: flex; flex-direction: column; justify-content: center; +} +.cards-slide .tag { align-self: flex-start; } +.cards-slide .heading { font-weight: 400; font-size: 2.8cqw; margin: 0 0 3cqw; text-align: center; color: #f0f0f0; } +.light .cards-slide .heading { color: var(--ink); text-align: left; } +.cards { display: flex; gap: 1.6cqw; justify-content: center; } +.card { + box-sizing: border-box; width: 17cqw; min-height: 15cqw; + padding: 2.4cqw 2.4cqw 2.2cqw; + display: flex; flex-direction: column; gap: 0.7cqw; + transition: opacity 0.4s, transform 0.4s; +} +.card.waiting { opacity: 0; transform: translateY(1cqw); } +.card svg { width: 2cqw; height: 2cqw; margin-bottom: 1.6cqw; } +.card .name { font-size: 1.6cqw; line-height: 1.25; } +.card .text { font-size: 1.15cqw; line-height: 1.4; opacity: 0.85; } +.card.slab { background: var(--slab); color: #f0f0f0; } +.card.lavender { background: var(--lavender); color: var(--ink); } +.card.mint { background: var(--mint); color: var(--ink); } +.card.white { background: var(--white); color: var(--ink); } +.cards.five .card { width: 15.6cqw; min-height: 17cqw; padding: 2cqw 1.8cqw; } + +/* ---- Template layouts: statement, split, grid, numbered, chart --------- */ + +.slide-heading { font-weight: 400; font-size: 3cqw; line-height: 1.2; margin: 0; } +.slide-sub { font-size: 1.3cqw; color: #666; margin: 0.8cqw 0 0; line-height: 1.4; } +.dark .slide-sub { color: #a8a8a8; } +.waiting { opacity: 0; transform: translateY(1cqw); } +.row-card, .grid-card, .series { transition: opacity 0.4s, transform 0.4s; } + +.tpl-icon { width: 2.2cqw; height: 2.2cqw; display: block; } +.dark .tpl-icon, .card.slab .tpl-icon { filter: invert(1); } + +.statement { + position: absolute; inset: 3.3cqw 0 0; display: flex; flex-direction: column; + align-items: center; justify-content: center; text-align: center; padding: 0 12cqw; +} +.statement h2 { font-weight: 400; font-size: 4.6cqw; line-height: 1.2; margin: 0; } +.statement p { font-size: 1.6cqw; color: #a8a8a8; margin: 2cqw 0 0; line-height: 1.45; } +.light .statement p, .lavender .statement p, .mint .statement p { color: #555; } + +.versus { + position: absolute; inset: 3.3cqw 0 0; display: grid; grid-template-columns: 1fr 1fr; + gap: 1.6cqw; padding: 3cqw; +} +.panel { + display: flex; flex-direction: column; justify-content: center; padding: 4cqw 4.5cqw; + transition: opacity 0.5s, transform 0.5s; +} +.panel.mint { background: var(--mint); color: var(--ink); } +.panel.lavender { background: var(--lavender); color: var(--ink); } +.panel .tpl-icon { width: 3.4cqw; height: 3.4cqw; margin-bottom: 2.4cqw; filter: none; } +/* The person's name is a badge in the saturated form of its panel's hue: + green on the mint panel, purple on the lavender one. */ +.panel .who { + align-self: flex-start; padding: 0.45cqw 1cqw; + font: 1.5cqw var(--mono); letter-spacing: 0.15cqw; text-transform: uppercase; +} +.panel.mint .who { background: var(--green); color: #134d1a; } +.panel.lavender .who { background: var(--purple); color: #fff; } +.panel h2 { font-weight: 400; font-size: 4.2cqw; line-height: 1.15; margin: 1cqw 0 2cqw; } +.panel p { font-size: 1.75cqw; line-height: 1.5; margin: 0; } + +.split { display: grid; grid-template-columns: 30% 1fr; gap: 5cqw; padding-top: 5.5cqw; } +.stack { display: flex; flex-direction: column; gap: 1.4cqw; } +.row-card { + background: var(--white); display: grid; grid-template-columns: auto 1fr; gap: 2.4cqw; + align-items: center; padding: 2cqw 2.6cqw; +} +.dark .row-card { background: var(--slab); color: #f0f0f0; } +.row-card .name, .grid-card .name { font-size: 1.6cqw; line-height: 1.3; } +.row-card .text, .grid-card .text { font-size: 1.2cqw; line-height: 1.45; opacity: 0.8; margin-top: 0.3cqw; } + +.grid { display: grid; gap: 1.4cqw; margin-top: 3cqw; } +.grid.cols-3 { grid-template-columns: repeat(3, 1fr); } +.grid.cols-2 { grid-template-columns: repeat(2, 1fr); } +.grid.cols-4 { grid-template-columns: repeat(4, 1fr); } +.grid-card { + background: var(--white); display: flex; flex-direction: column; align-items: center; + text-align: center; gap: 0.6cqw; padding: 2.2cqw 2cqw; +} +.grid-card .tpl-icon { margin-bottom: 0.8cqw; } +.dark .grid-card { background: var(--slab); color: #f0f0f0; } + +.cards.numbered { justify-content: flex-start; margin-top: 3.4cqw; } +.cards.numbered .card { width: 26cqw; min-height: 13cqw; } +.cards.numbered .tag { align-self: flex-start; font-size: 0.9cqw; margin-bottom: 1.2cqw; } + +.chart { display: block; width: 100%; height: 33cqw; margin-top: 1.4cqw; font-family: var(--sans); } +.chart .gridline { stroke: #2c2c2c; stroke-width: 1; } +.chart .zero { stroke: #777; stroke-width: 1.5; } +.chart .tick { fill: #8a8a8a; font-size: 14px; } +.chart .axis { fill: #a8a8a8; font-size: 15px; } +.chart .mark-line { stroke: #555; stroke-dasharray: 5 4; } +.chart .mark-label { fill: #bdbdbd; font: 13px var(--mono); letter-spacing: 1px; } +.chart .series path { fill: none; stroke-width: 4; stroke-linejoin: round; } +.chart .series.green path { stroke: var(--green); } +.chart .series.purple path { stroke: var(--purple); } +.chart .series-label { font-size: 17px; } +.chart .series.green .series-label { fill: var(--green); } +.chart .series.purple .series-label { fill: #b9a4ff; } + +.alloc { display: flex; gap: 0.5cqw; margin-top: 5cqw; } +.seg { flex-basis: 0; min-width: 12cqw; display: flex; flex-direction: column; transition: flex-grow 1.6s ease-in-out; } +.seg .pct { font: 1.4cqw var(--mono); margin-bottom: 0.8cqw; color: #bdbdbd; } +.light .seg .pct, .lavender .seg .pct, .mint .seg .pct { color: #555; } +.seg-box { + flex: 1; min-height: 11cqw; padding: 2cqw 2.2cqw; display: flex; flex-direction: column; + justify-content: center; gap: 0.4cqw; +} +.seg-box .tpl-icon { margin-bottom: 0.8cqw; filter: none; } +.seg-box .name { font-size: 2cqw; } +.seg-box .text { font-size: 1.25cqw; opacity: 0.8; } +.seg-box.mint { background: var(--mint); color: var(--ink); } +.seg-box.lavender { background: var(--lavender); color: var(--ink); } +.seg-box.white { background: var(--white); color: var(--ink); } +.seg.thin { min-width: 0.5cqw; position: relative; } +/* A part moving to or from nothing: no minimum width, and its words fade + out as it shrinks to nothing, or in once it has grown. */ +.seg.moving { min-width: 0; overflow: hidden; white-space: nowrap; } +.seg.thin.moving { overflow: visible; } +.seg.to-zero.moved > * { opacity: 0; transition: opacity 0.8s; } +.seg.to-zero.moved { margin-right: -0.5cqw; transition: flex-grow 1.6s ease-in-out, margin 1.6s ease-in-out; } +.seg.from-zero .callout { opacity: 0; transition: opacity 0.6s 1.4s; } +.seg.from-zero.moved .callout { opacity: 1; } +.seg.thin .seg-box { padding: 0; } +.callout { + position: absolute; top: calc(100% + 3.4cqw); right: 0; white-space: nowrap; + font-size: 1.5cqw; color: #e0e0e0; +} +.callout-name { font-size: 2cqw; } +/* The arrow from the label up to the thin part. */ +.callout::before { + content: ""; position: absolute; right: 0.15cqw; bottom: calc(100% + 0.4cqw); + height: 2.6cqw; border-left: 0.15cqw solid #e0e0e0; +} +.callout::after { + content: ""; position: absolute; right: -0.35cqw; bottom: calc(100% + 2.9cqw); + border: 0.55cqw solid transparent; border-bottom: 0.8cqw solid #e0e0e0; border-top: 0; +} + +.photo-slide { overflow: hidden; } +.photo-slide .photo { + position: absolute; inset: 3.3cqw 0 0; background-size: cover; background-position: center 60%; + animation: photo-drift 16s ease-out forwards; +} +.photo-slide .statement { z-index: 1; } +.photo-slide .statement h2 { font-size: 10cqw; letter-spacing: -0.2cqw; color: var(--ink); } +.photo-slide .statement p { font: 1.6cqw var(--mono); letter-spacing: 0.1cqw; color: #333; text-transform: uppercase; } +@keyframes photo-drift { from { transform: scale(1.14); } to { transform: scale(1); } } + +/* ---- QR and follow ----------------------------------------------------- */ + +.qr-slide h2 { font-weight: 400; font-size: 3cqw; margin: 0 0 0.6cqw; } +.qr-slide .url { font: 1.1cqw var(--mono); color: #aaa; margin-bottom: 2.4cqw; } +.qr-slide .row { display: grid; grid-template-columns: auto 1fr; gap: 4cqw; align-items: center; } +.qr-slide img { width: 22cqw; background: #fff; padding: 1cqw; display: block; } +.qr-slide.with-cover .body { + display: grid; grid-template-columns: 1fr auto; gap: 5cqw; align-items: center; + height: calc(100% - 3.3cqw); box-sizing: border-box; padding-top: 3cqw; padding-bottom: 3cqw; +} +.qr-slide.with-cover ul { margin-bottom: 2.6cqw; } +.qr-slide.with-cover img.qr { width: 13cqw; } +.qr-slide.with-cover img.cover { + height: 42cqw; width: auto; padding: 0; background: none; + box-shadow: 0 1.2cqw 3cqw rgba(0, 0, 0, 0.6); +} + +.follow-slide { + background-color: var(--black); + background-image: radial-gradient(#1d1d22 0.1cqw, transparent 0.11cqw); + background-size: 2.4cqw 2.4cqw; + overflow: hidden; +} +/* The handle sits in the upper half, the transfer runs beneath it across the + whole slide, and the thanks sits under the transfer at the right. */ +.follow-slide .body { position: relative; padding-top: 6.5cqw; } +.follow-slide .lead { font-size: 3.2cqw; margin: 2cqw 0 2.6cqw; color: #f0f0f0; } +.follow-slide .handle-big { font-size: 7.6cqw; letter-spacing: -0.12cqw; line-height: 1.1; } +.follow-slide .handle-big mark { padding: 0 1cqw; } +.follow-slide .thanks { + position: absolute; right: 6cqw; bottom: 4.5cqw; font-size: 4cqw; color: #f0f0f0; + border-bottom: 0.35cqw solid var(--green); +} + +.follow-transfer { position: absolute; left: 0; top: 3.3cqw; width: 100%; height: calc(100% - 3.3cqw); } +.follow-transfer .transfer { + fill: none; stroke: var(--green); stroke-width: 4; + stroke-dasharray: 1800; stroke-dashoffset: 1800; + animation: follow-draw-transfer 1.2s 0.3s ease-out forwards; +} +.follow-transfer .coin circle { fill: var(--black); stroke: var(--green); stroke-width: 3; } +@keyframes follow-draw-transfer { to { stroke-dashoffset: 0; } } diff --git a/animations/deck.js b/animations/deck.js new file mode 100644 index 00000000..b7f6aab6 --- /dev/null +++ b/animations/deck.js @@ -0,0 +1,423 @@ +// A slide deck around an animated scene. A deck is a list of slides: some are +// HTML (title, what you'll learn, cards, closing), and some are a run of the +// scene's diagram steps. One key advances through all of them: a diagram step +// plays its animation, and a slide of cards builds them one at a time. +// +// The deck has the same small interface as the diagram player (count, goto, +// next, prev, autoplay), so the page's keys and scripts/animation-frames.mjs +// drive either. + +(function () { + const escape = (s) => String(s).replace(/&/g, "&").replace(//g, ">"); + + // [word] becomes the green highlight; {word} the purple one. + function marked(text) { + return escape(text) + .replace(/\[([^\]]+)\]/g, "$1") + .replace(/\{([^}]+)\}/g, '$1'); + } + + // A card's icon: one of the book's account glyphs by kind ("wallet", + // "token", ...), drawn in the card's text colour, or with "tpl:" one of the + // Quicknode template's icons in assets/icons, inverted on a dark card. + function icon(kind, deck) { + if (kind.startsWith("tpl:")) { + return ``; + } + const { ICONS, THEME } = AccountAnimation; + return `${ICONS[kind].replaceAll(THEME.boxText, "currentColor")}`; + } + + const waiting = (i, shown) => (i < shown ? "" : "waiting"); + + function heading(s) { + return `${s.heading ? `

${marked(s.heading)}

` : ""}${ + s.sub ? `

${marked(s.sub)}

` : "" + }`; + } + + // The payoff of an option at expiry, against the underlying's price: one + // line per side, built one at a time. Each series is a list of [price, profit]. + function payoffChart(s, shown) { + const W = 900, H = 420, L = 70, R = 30, T = 20, B = 50; + const [x0, x1] = s.x, [y0, y1] = s.y; + const X = (v) => L + ((v - x0) / (x1 - x0)) * (W - L - R); + const Y = (v) => T + ((y1 - v) / (y1 - y0)) * (H - T - B); + let out = ``; + for (let v = y0; v <= y1; v += s.yStep) { + out += ``; + out += `${v > 0 ? "+" : ""}${v}`; + } + for (let v = x0; v <= x1; v += s.xStep) { + out += `$${v}`; + } + for (const m of s.marks || []) { + out += ``; + out += `${escape(m.label)}`; + } + s.series.forEach((series, i) => { + const d = series.points.map(([px, py], k) => `${k ? "L" : "M"} ${X(px)},${Y(py)}`).join(" "); + const [lx, ly] = series.labelAt; + out += ``; + out += `${escape(series.label)}`; + }); + out += `${escape(s.xLabel)}`; + out += `${escape(s.yLabel)}`; + return out + ""; + } + + function bar(series) { + return `
${escape(series)}@QuicknodeSolana
`; + } + + // Each slide kind renders to HTML; `shown` is how many of its cards have + // been built so far. + const RENDER = { + title: (s, deck) => ` +
${bar(deck.series)} +
+ // ${escape(deck.series)} +

${s.lines.map(marked).join("
")}

+
+ +
`, + + columns: (s, deck) => ` +
${bar(deck.series)} +
+ ${s.columns + .map( + (c) => `

${marked(c.heading)}

${escape(c.sub || "")}

+
    ${c.items.map((i) => `
  • ${marked(i)}
  • `).join("")}
`, + ) + .join("")} +
+
`, + + cards: (s, deck, shown) => ` +
${bar(deck.series)} +
+ ${s.tag ? `// ${escape(s.tag)}
` : ""} + ${s.heading ? `

${marked(s.heading)}

` : ""} +
+ ${s.cards + .map( + (c, i) => `
${icon(c.icon, deck)} +
${marked(c.name)}
${marked(c.text)}
`, + ) + .join("")} +
+
+
`, + + // A big centred sentence, and a line beneath it. + statement: (s, deck) => ` +
${bar(deck.series)} +

${marked(s.heading)}

${s.sub ? `

${marked(s.sub)}

` : ""}
+
`, + + // Two people side by side, each a full-height panel: who they are, what + // they want, and why. Built one panel at a time. + versus: (s, deck, shown) => ` +
${bar(deck.series)} +
${s.cards + .map( + (c, i) => `
${icon(c.icon, deck)} +
// ${escape(c.who)}

${marked(c.name)}

${marked(c.text)}

`, + ) + .join("")}
+
`, + + // A big centred sentence over one of the template's photographs, which + // drifts slowly closer while the slide is up. + photo: (s, deck) => ` +
${bar(deck.series)} +
+

${marked(s.heading)}

${s.sub ? `

${marked(s.sub)}

` : ""}
+
`, + + // The heading on the left, and a stack of wide icon cards on the right. + split: (s, deck, shown) => ` +
${bar(deck.series)} +
${heading(s)}
+
${s.cards + .map( + (c, i) => `
${icon(c.icon, deck)} +
${marked(c.name)}
${marked(c.text)}
`, + ) + .join("")}
+
+
`, + + // The heading across the top, and a grid of centred icon cards. + grid: (s, deck, shown) => ` +
${bar(deck.series)} +
${heading(s)} +
${s.cards + .map( + (c, i) => `
${icon(c.icon, deck)} +
${marked(c.name)}
${marked(c.text)}
`, + ) + .join("")}
+
+
`, + + // Cards numbered with a green tag, for things that happen in order or + // are counted. + numbered: (s, deck, shown) => ` +
${bar(deck.series)} +
${heading(s)} +
${s.cards + .map( + (c, i) => `
+ // ${String(i + 1).padStart(2, "0")} +
${marked(c.name)}
${marked(c.text)}
`, + ) + .join("")}
+
+
`, + + // A bar split by value, each part labelled with its share of the whole: + // a fund's allocation, or who owns its shares. + // With `from`, a part opens at an earlier value and grows or shrinks to + // its own, the bar, its percentage and its words changing together: the + // weights drifting as a price moves, or a rebalance pulling them back. + allocation: (s, deck) => { + const total = s.parts.reduce((sum, p) => sum + p.value, 0); + const fromTotal = s.parts.reduce((sum, p) => sum + (p.from ?? p.value), 0); + const pct = (v, t = total) => ((v / t) * 100).toFixed(s.decimals ?? 0); + // A part moving to or from nothing may be as thin as nothing, and its + // words leave or arrive with it. + const moving = (p) => (p.from != null ? ` moving${p.value === 0 ? " to-zero" : ""}${p.from === 0 ? " from-zero" : ""}` : ""); + const motion = (p) => + p.from != null + ? ` data-grow="${p.value}" data-pct-from="${pct(p.from, fromTotal)}" data-pct-to="${pct(p.value)}" data-decimals="${s.decimals ?? 0}"` + : ""; + return ` +
${bar(deck.series)} +
${heading(s)} +
${s.parts + .map((p) => + // A part too thin to hold its words is drawn at its true width, + // with its label outside the bar and an arrow to it. + p.callout + ? `
 
+
+
${marked(p.name)} · ${marked(p.text)} · ${pct(p.value)}%
` + : p.from != null + ? `
+
${pct(p.from, fromTotal)}%
+
${p.icon ? icon(p.icon, deck) : ""} +
${marked(p.name)}
${marked(p.fromText || p.text)}
` + : `
+
${pct(p.value)}%
+
${p.icon ? icon(p.icon, deck) : ""} +
${marked(p.name)}
${marked(p.text)}
`, + ) + .join("")}
+
+
`; + }, + + chart: (s, deck, shown) => ` +
${bar(deck.series)} +
${heading(s)}${payoffChart(s, shown)}
+
`, + + // A link to share: the heading, its address, bullets and a QR code, and + // with `cover` the book's cover beside them. + qr: (s, deck) => s.cover + ? ` +
${bar(deck.series)} +
+
+

${marked(s.heading)}

+
${escape(s.url)}
+
    ${s.items.map((i) => `
  • ${marked(i)}
  • `).join("")}
+ QR code for ${escape(s.url)} +
+ +
+
` + : ` +
${bar(deck.series)} +
+

${marked(s.heading)}

+
${escape(s.url)}
+
QR code for ${escape(s.url)} +
    ${s.items.map((i) => `
  • ${marked(i)}
  • `).join("")}
+
+
`, + + // The closing slide: the talk's own picture, a cluster curve drawing + // itself across the slide with accounts appearing on it, and above it a + // token transfer between two accounts off either edge, coins streaming + // along its arrow. + follow: (s, deck) => { + const coin = [[10, 3], [0, 0], [-10, 3]].map(([x, y]) => ``).join(""); + // A transfer between two accounts off either edge, beneath the handle. + const arrow = "M -80,620 L 1680,620"; + const coins = [0, 1, 2, 3] + // Each coin is hidden until its first run starts, then runs edge to edge. + .map((k) => `${coin}`) + .join(""); + return ` + `; + }, + }; + + class Deck { + constructor(deck, scene, stage) { + this.deck = deck; + this.scene = scene; + this.stage = stage; + this.svg = stage.querySelector("svg"); + this.svg.classList.add("layer"); + this.html = document.createElement("div"); + this.html.className = "layer"; + stage.appendChild(this.html); + // The series bar sits above the diagrams too, as on every slide. + stage.insertAdjacentHTML("afterbegin", `
${bar(deck.series)}
`); + this.player = new AccountAnimation.Player(scene, this.svg); + this.autoplay = null; + + // One entry per key press: each diagram step, and each build of a slide. + this.items = []; + for (const slide of deck.slides) { + if (slide.type === "diagram") { + for (let i = slide.from; i <= slide.to; i++) this.items.push({ step: i }); + } else { + // A slide of cards, or a chart's lines, builds one per key press. + const parts = slide.cards || slide.series; + if (parts && slide.build !== false) { + for (let shown = 1; shown <= parts.length; shown++) this.items.push({ slide, shown }); + } else { + this.items.push({ slide, shown: parts ? parts.length : 1 }); + } + } + } + const steps = this.items.filter((it) => "step" in it).length; + if (steps !== scene.steps.length) { + throw new Error(`the deck shows ${steps} diagram steps; the scene has ${scene.steps.length}`); + } + this.index = 0; + this.show(0, false); + } + + get count() { + return this.items.length; + } + + get busy() { + return this.player.busy; + } + + async show(i, forward) { + const item = this.items[i]; + const prev = forward ? this.items[i - 1] : null; + if ("step" in item) { + this.html.classList.add("hidden"); + this.svg.classList.remove("hidden"); + if (forward && item.step > 0) { + // Land on the step before without motion, then play this one. + if (this.player.index !== item.step - 1 || !(prev && "step" in prev)) await this.player.goto(item.step - 1); + await this.player.next(); + } else { + await this.player.goto(item.step); + } + return; + } + const sameSlide = prev && prev.slide === item.slide; + if (sameSlide) { + // Build the next card in place. + const next = this.html.querySelector(".waiting"); + if (next) next.classList.remove("waiting"); + return; + } + this.html.innerHTML = RENDER[item.slide.type](item.slide, this.deck, item.shown); + this.html.classList.remove("hidden"); + this.svg.classList.add("hidden"); + this.moveAllocation(); + } + + // Moves an allocation's parts from their `from` values to their own once + // the slide has faded in: the bars grow, the percentages count, and the + // words change as the move ends. + moveAllocation() { + const segs = [...this.html.querySelectorAll(".seg[data-grow]")]; + if (segs.length === 0) return; + const delay = Number(this.html.querySelector(".alloc").dataset.delay); + setTimeout(() => { + for (const seg of segs) { + seg.style.flexGrow = seg.dataset.grow; + seg.classList.add("moved"); + } + const start = performance.now(); + const frame = (now) => { + const p = Math.min(1, (now - start) / 1600); + const e = p < 0.5 ? 2 * p * p : 1 - (-2 * p + 2) ** 2 / 2; + for (const seg of segs) { + if (seg.classList.contains("thin")) continue; + const a = Number(seg.dataset.pctFrom), b = Number(seg.dataset.pctTo); + seg.querySelector(".pct").textContent = `${(a + (b - a) * e).toFixed(Number(seg.dataset.decimals))}%`; + } + if (p < 1) return requestAnimationFrame(frame); + for (const seg of segs) { + const text = seg.querySelector(".text"); + if (text) text.innerHTML = text.dataset.to; + } + }; + requestAnimationFrame(frame); + }, delay); + } + + async goto(i) { + await this.player.interrupt(); + this.index = Math.max(0, Math.min(this.count - 1, i)); + await this.show(this.index, false); + } + + async next() { + if (this.player.busy) return this.player.interrupt(); + if (this.index >= this.count - 1) return; + this.index += 1; + await this.show(this.index, true); + } + + prev() { + this.stopAutoplay(); + return this.goto(this.index - 1); + } + + // Plays every remaining item, holding each finished one for `hold` ms. + startAutoplay(hold = this.scene.hold || 3000) { + this.stopAutoplay(); + const token = {}; + this.autoplay = token; + const tick = async () => { + if (this.autoplay !== token) return; + if (this.index >= this.count - 1) return this.stopAutoplay(); + await this.next(); + if (this.autoplay === token) token.timer = setTimeout(tick, hold); + }; + token.timer = setTimeout(tick, hold); + } + + stopAutoplay() { + if (this.autoplay) clearTimeout(this.autoplay.timer); + this.autoplay = null; + } + } + + window.AccountDeck = { Deck }; +})(); diff --git a/animations/engine.js b/animations/engine.js new file mode 100644 index 00000000..3658f70e --- /dev/null +++ b/animations/engine.js @@ -0,0 +1,766 @@ +// A stepper for animated account figures. A scene file supplies the layout +// (hand-placed, on a 16:9 canvas) and an ordered list of steps; this file +// draws the scene in the book's figure vocabulary (DIAGRAMS.md in the +// companion plugin), in the colours of the Quicknode Solana Finance slides, +// and animates each step. +// +// Every step's end state is computed by replaying the actions without motion, +// so going back, jumping, or interrupting an animation always lands on the +// same picture the forward animation ends on. +// +// Classic script rather than a module, so index.html opens straight from disk. + +(function () { + // The slides' palette: near-black paper, accounts as pastel cards with dark + // text, one bright green for what the step does. Each account kind keeps + // one fill, so the kind reads from the colour as well as the icon. + const THEME = { + paper: "#040406", + ink: "#f4f4f4", + caption: "#b9bdc2", + seed: "#8a8f94", + curve: "#4f8a3c", + boxText: "#161616", + boxMuted: "#5d5d66", + boxRule: "#c4c4cc", + // Green on the dark paper, for arrows, coins and the headline's keyword. + accent: "#95fc86", + // Green dark enough to read on a pastel card, for changes inside one. + accentInk: "#1f7a2a", + fill: { + wallet: "#f4f4f4", + token: "#d9fbda", + program: "#efeafe", + struct: "#e9eaee", + mint: "#f4f9e3", + }, + }; + const ACTIVE_HANDLER_STYLE = (t) => `font-family="${t}" font-weight="bold" fill="#161616" stroke="#161616" stroke-width="0.35"`; + // On the dark paper a faded card reads as the slides' dark grey slab. + const FADE = 0.22; + const MONO = "'Andale Mono', 'DejaVu Sans Mono', Menlo, monospace"; + // The running handler: Andale Mono has no bold, and a browser's made-up + // bold is faint, so this line is set in a face with a real bold weight and + // thickened by a hairline of its own colour. + const ACTIVE_FONT = "'DejaVu Sans Mono', Menlo, monospace"; + const ACTIVE_HANDLER = ACTIVE_HANDLER_STYLE(ACTIVE_FONT); + const SVG_NS = "http://www.w3.org/2000/svg"; + + // The five account glyphs, verbatim from the book's figures with the ink + // swapped for the theme's: each fills the 14-unit glyph box once placed. + const ICONS = Object.fromEntries( + Object.entries({ + struct: ``, + token: ``, + wallet: ``, + mint: ``, + program: ``, + }).map(([kind, svg]) => [kind, svg.replaceAll("#111", THEME.boxText)]), + ); + + // Three rings with a halo in the paper colour, so the mark occludes any + // stroke beneath it. + const COIN = ``; + + const HALO = `stroke="${THEME.paper}" stroke-width="4" paint-order="stroke" stroke-linejoin="round"`; + + const escape = (s) => String(s).replace(/&/g, "&").replace(//g, ">"); + const lerp = (a, b, t) => a + (b - a) * t; + const clamp01 = (t) => Math.max(0, Math.min(1, t)); + + // The cluster curve: flat at the top left, sloping down to the right, as + // one quadratic across the whole canvas. yAt() puts an address dot on it. + function clusterCurve(width, { top = 33, drop = 80, control = 0.625 } = {}) { + const cx = width * control; + // Past the canvas at both ends the curve runs on along its own tangent, + // flat at the left and sloping at the right, so where the page shows + // more than the canvas the curve still reaches the very edge. + const reach = width / 2; + const slope = drop / (width - cx); + const d = + `M ${-reach},${top} L 0,${top} Q ${cx},${top} ${width},${top + drop}` + + ` L ${width + reach},${top + drop + reach * slope}`; + // x(t) = 2(1-t)t·cx + t²·width, solved for t; y follows from t. + const yAt = (x) => { + const a = width - 2 * cx; + const b = 2 * cx; + const t = Math.abs(a) < 1e-9 ? x / b : (-b + Math.sqrt(b * b + 4 * a * x)) / (2 * a); + return top + drop * t * t; + }; + return { d, yAt }; + } + + // ---- State --------------------------------------------------------------- + + function initialState() { + // `changed` lists the lines this step changed, as "account:line", so they + // stay marked until the next step starts. + return { exists: [], focus: [], isNew: [], titles: {}, lines: {}, handlers: [], arrows: [], changed: [] }; + } + + function lineIndex(lines, key) { + if (key == null) return 0; + return lines.findIndex((l) => l.text.startsWith(key + ": ")); + } + + function lineText(key, value) { + return key == null ? value : `${key}: ${value}`; + } + + // Applies one action to a state, with no motion. The animator plays the + // same actions and then lands on the state this produces. + function reduce(state, action) { + const s = structuredClone(state); + switch (action.type) { + case "show": + for (const id of action.ids) if (!s.exists.includes(id)) s.exists.push(id); + for (const [id, lines] of Object.entries(action.lines || {})) s.lines[id] = lines; + // focus: "all" draws everything in full, "shown" adds the arriving + // accounts to what is already in full, and a list replaces it. + if (action.focus === "all") s.focus = [...s.exists]; + else if (action.focus === "shown") s.focus = [...new Set([...s.focus, ...action.ids])]; + else if (action.focus) s.focus = [...action.focus]; + break; + case "focus": + s.focus = action.ids === "all" ? [...s.exists] : [...action.ids]; + break; + // A call lights its handler, and with `also` the handlers it calls in + // other programs; a call with no handler is a step no program takes, + // such as the market moving. + case "call": + s.handlers = [action.handler, ...(action.also || [])].filter(Boolean); + s.arrows = []; + s.isNew = []; + s.focus = [...action.focus]; + break; + case "create": + if (!s.exists.includes(action.id)) s.exists.push(action.id); + if (!s.focus.includes(action.id)) s.focus.push(action.id); + s.isNew.push(action.id); + s.lines[action.id] = action.lines; + break; + // An account a step changes, or moves tokens into or out of, is drawn + // in full: the reader can't follow a balance on a faded slab. + case "set": + for (const change of action.changes) { + if (!s.focus.includes(change.id)) s.focus.push(change.id); + if (change.title) s.titles[change.id] = change.title; + if (change.value != null) { + const lines = s.lines[change.id]; + const index = lineIndex(lines, change.key); + lines[index].text = lineText(change.key, change.value); + s.changed.push(`${change.id}:${index}`); + } + } + break; + case "hide": + s.arrows = []; + s.exists = s.exists.filter((id) => !action.ids.includes(id)); + s.focus = s.focus.filter((id) => !action.ids.includes(id)); + break; + // A closed account takes the step's arrows with it: an arrow left + // pointing at an account that is gone points at nothing. + case "close": + s.arrows = []; + s.exists = s.exists.filter((id) => id !== action.id); + s.focus = s.focus.filter((id) => id !== action.id); + s.isNew = s.isNew.filter((id) => id !== action.id); + break; + // Within a call, a lit handler can change, as when a deposit moves from + // buying one asset through the router to buying the next. + case "highlight": + s.handlers = [...action.handlers]; + break; + // An `alone` transfer replaces the step's earlier arrows rather than + // adding to them, for a handler that makes many transfers in a row. A + // side without a `value` is an account with no balance to show, such as + // a program that trades on the far side. + case "transfer": + if (action.alone) s.arrows = []; + s.arrows.push(action.arrow); + for (const change of [action.from, action.to]) { + if (!s.focus.includes(change.id)) s.focus.push(change.id); + if (change.value == null) continue; + const lines = s.lines[change.id]; + const index = lineIndex(lines, change.key); + lines[index].text = lineText(change.key, change.value); + s.changed.push(`${change.id}:${index}`); + } + break; + default: + throw new Error(`unknown action ${action.type}`); + } + return s; + } + + // ---- Drawing ------------------------------------------------------------- + + // An account's expanded height is the book's anatomy: a 21-unit title bar, + // 12 units a line (10 for handler lists), and the bottom padding. + function expandedHeight(acc, lineCount) { + if (lineCount === 0) return 22; + return acc.kind === "program" ? 21 + lineCount * 10 + 9 : 21 + lineCount * 12 + 7; + } + + function lineAttrs(acc, line, state) { + if (acc.kind === "program") { + const active = state.handlers.includes(line.text); + return `font-size="8.5" ${active ? ACTIVE_HANDLER : `font-family="${MONO}" fill="${THEME.boxMuted}"`}`; + } + switch (line.style) { + case "sol": return `font-size="9.5" fill="${THEME.boxMuted}"`; + case "balance": return `font-size="9" fill="${THEME.boxText}"`; + case "note": return `font-size="9" font-style="italic" fill="${THEME.boxMuted}"`; + default: return `font-size="9.5" fill="${THEME.boxText}"`; + } + } + + function accountMarkup(acc, state) { + const lines = state.lines[acc.id] || []; + const title = state.titles[acc.id] || acc.title; + const r = acc.onCurve ? 5 : 4.5; + const step = acc.kind === "program" ? 10 : 12; + let out = ``; + // The opaque disc keeps a faded dot from letting the curve show through. + out += ``; + out += ``; + out += ``; + (acc.seeds?.lines || []).forEach((seed, i) => { + out += `${escape(seed)}`; + }); + out += ``; + out += `${ICONS[acc.kind]}`; + out += `${escape(title)}`; + out += ``; + out += ``; + lines.forEach((line, i) => { + const y = acc.y + 32 + i * step; + if (acc.kind === "program") { + // The running handler sits on the slides' green highlight, marked ▶, + // so it reads at a glance from the back of the room. + const on = state.handlers.includes(line.text) ? 1 : 0; + out += ``; + out += ``; + out += `▶`; + out += `${escape(line.text)}`; + return; + } + // A value the step changed stays on the green band, in bold, until the + // next step, so the new number is easy to find after it stops counting. + if (state.changed.includes(`${acc.id}:${i}`)) { + out += changedBand(acc, y); + out += `${escape(line.text)}`; + return; + } + out += `${escape(line.text)}`; + }); + out += ``; + out += `NEW`; + out += `CLOSED`; + out += ``; + return out; + } + + // The band behind a changed value: the same green as the running handler. + function changedBand(acc, y) { + return ``; + } + + // Sets an account's drawn focus: 0 is faded to its heading, 1 is expanded + // with its lines. appear scales the group's opacity, for a new account. + function applyFocus(scene, g, t, appear = 1) { + const acc = scene.accounts[g.dataset.id]; + const lineCount = g.querySelectorAll(".lines text[data-line]").length; + const e = lineCount > 0 ? t : 0; + g.querySelector(".box").setAttribute("height", lerp(22, expandedHeight(acc, lineCount), e)); + g.querySelector(".icon").setAttribute("transform", `translate(${acc.x + 8},${acc.y + lerp(4, 3.5, e)})`); + g.querySelector(".title").setAttribute("y", acc.y + lerp(14.5, 14.175, e)); + g.querySelector(".rule").setAttribute("opacity", lineCount > 0 ? clamp01((e - 0.6) / 0.4) : 0); + g.querySelector(".lines").setAttribute("opacity", clamp01((e - 0.85) / 0.15)); + g.querySelector(".body").setAttribute("opacity", lerp(FADE, 1, t) * appear); + g.querySelector(".backing").setAttribute("opacity", appear); + g.dataset.t = t; + } + + // An arrow names where its coin sits as a fraction of its length; the + // label hangs off the coin, so both stay on the stroke if the path moves. + function arrowMarkup(arrow, { partial = false } = {}) { + let out = ``; + out += ``; + out += ``; + arrow.label.forEach((text, i) => { + out += `${escape(text)}`; + }); + out += `${COIN}`; + return out; + } + + // Places an arrow's coin on its stroke and its label beside the coin. The + // coin sits at `coinAt`, a fraction of the stroke's length, or at the point + // of the stroke nearest `coinNear`, for a routed arrow whose straight runs + // are easier to name by place than by length. + function placeArrow(g, arrow) { + const path = g.querySelector(".stroke"); + const length = path.getTotalLength(); + let pt = path.getPointAtLength(length * (arrow.coinAt ?? 0.5)); + if (arrow.coinNear) { + let best = Infinity; + for (let i = 0; i <= 400; i++) { + const q = path.getPointAtLength((length * i) / 400); + const d = (q.x - arrow.coinNear.x) ** 2 + (q.y - arrow.coinNear.y) ** 2; + if (d < best) { best = d; pt = q; } + } + } + g.querySelector(".coin").setAttribute("transform", `translate(${pt.x},${pt.y})`); + g.querySelector(".label").setAttribute("transform", `translate(${pt.x},${pt.y})`); + } + + function sceneMarkup(scene, state, stepIndex) { + const { width, height } = scene.canvas; + const step = scene.steps[stepIndex]; + const c = scene.caption; + let out = ``; + out += ``; + out += ``; + out += `${escape(scene.network.text.toUpperCase())}`; + out += `
${escape(stepTag(stepIndex))}
`; + out += `
${headlineHtml(step.title)}
`; + out += `
${escape(step.caption)}
`; + out += ``; + for (const id of scene.order) { + if (state.exists.includes(id)) out += accountMarkup(scene.accounts[id], state); + } + out += ``; + for (const arrow of state.arrows) out += arrowMarkup(arrow); + out += `
`; + const progress = scene.steps.length > 1 ? stepIndex / (scene.steps.length - 1) : 1; + out += ``; + return out; + } + + // A title marks its keyword in brackets, "Maria runs [collect_fees()]", + // and the keyword is set on the slides' green highlight. + function headlineHtml(title) { + return escape(title).replace( + /\[([^\]]+)\]/g, + `$1`, + ); + } + + function stepTag(i) { + return `// STEP ${i + 1}`; + } + + // ---- Motion -------------------------------------------------------------- + + const easeInOut = (p) => (p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2); + + // Parses the one number in a line, so a balance can count from one value + // to the next: "1,024.75 USDC" is 1024.75 with two decimals. + function numberIn(text) { + const m = text.match(/-?\d[\d,]*(?:\.\d+)?/); + if (!m) return null; + const value = Number(m[0].replace(/,/g, "")); + const decimals = (m[0].split(".")[1] || "").length; + return { value, decimals, before: text.slice(0, m.index), after: text.slice(m.index + m[0].length) }; + } + + function formatNumber(value, decimals) { + return value.toLocaleString("en-US", { minimumFractionDigits: decimals, maximumFractionDigits: decimals }); + } + + // Two derived accounts with the same seeds would be one address, so a scene + // that draws two is wrong: refuse it rather than show it. + function assertUniqueSeeds(scene) { + const owners = {}; + for (const acc of Object.values(scene.accounts)) { + if (!acc.seeds) continue; + const seeds = acc.seeds.lines.join(" "); + if (owners[seeds]) { + throw new Error(`${owners[seeds]} and ${acc.id} have the same seeds, ${seeds}, so they would be one address`); + } + owners[seeds] = acc.id; + } + } + + class Player { + constructor(scene, svg, { onStep } = {}) { + assertUniqueSeeds(scene); + this.scene = scene; + this.svg = svg; + this.onStep = onStep || (() => {}); + this.skip = false; + this.busy = null; + this.speed = 1; + this.autoplay = null; + // states[i] is the picture once step i has finished. A step starts + // from the one before it, or, with `from`, from the end of the step + // carrying that key: how another future branches off the story, and how + // the story resumes after it. + this.states = []; + this.bases = []; + const keys = {}; + scene.steps.forEach((step, i) => { + if (step.from != null && !(step.from in keys)) throw new Error(`step ${i + 1} starts from unknown key ${step.from}`); + const base = i === 0 ? null : step.from != null ? keys[step.from] : i - 1; + // A step's changed lines are its own: the next step starts unmarked. + let s = { ...(base == null ? initialState() : this.states[base]), changed: [] }; + for (const action of step.actions) s = reduce(s, action); + this.states.push(s); + this.bases.push(base); + if (step.key != null) keys[step.key] = i; + }); + this.index = 0; + this.render(this.states[0], 0); + } + + get count() { + return this.scene.steps.length; + } + + render(state, stepIndex) { + this.svg.innerHTML = sceneMarkup(this.scene, state, stepIndex); + for (const g of this.svg.querySelectorAll(".acc")) { + applyFocus(this.scene, g, state.focus.includes(g.dataset.id) ? 1 : 0); + g.querySelector(".new").setAttribute("opacity", state.isNew.includes(g.dataset.id) ? 1 : 0); + } + for (const g of this.svg.querySelectorAll(".arrows .arrow")) { + placeArrow(g, state.arrows.find((a) => a.id === g.dataset.id)); + } + } + + // Jumps to a step's end state, with no motion. + async goto(i) { + await this.interrupt(); + this.index = Math.max(0, Math.min(this.count - 1, i)); + this.render(this.states[this.index], this.index); + this.onStep(this.index); + } + + async next() { + if (this.busy) return this.interrupt(); + if (this.index >= this.count - 1) return; + this.index += 1; + this.onStep(this.index); + const run = this.play(this.index); + this.busy = run; + await run; + if (this.busy === run) this.busy = null; + } + + prev() { + this.stopAutoplay(); + return this.goto(this.index - 1); + } + + // Plays every remaining step, holding each finished one for `hold` ms. + startAutoplay(hold = this.scene.hold || 3000) { + this.stopAutoplay(); + const token = {}; + this.autoplay = token; + const tick = async () => { + if (this.autoplay !== token) return; + if (this.index >= this.count - 1) return this.stopAutoplay(); + await this.next(); + if (this.autoplay === token) token.timer = setTimeout(tick, hold); + }; + token.timer = setTimeout(tick, hold); + } + + stopAutoplay() { + if (this.autoplay) clearTimeout(this.autoplay.timer); + this.autoplay = null; + } + + // Finishes the running animation at once, on its end state. + async interrupt() { + if (!this.busy) return; + this.skip = true; + await this.busy; + this.skip = false; + this.busy = null; + } + + tween(ms, fn) { + return new Promise((resolve) => { + if (this.skip || ms <= 0) { fn(1); return resolve(); } + const start = performance.now(); + const frame = (now) => { + const p = this.skip ? 1 : Math.min(1, (now - start) / (ms / this.speed)); + fn(easeInOut(p)); + if (p < 1) requestAnimationFrame(frame); + else resolve(); + }; + requestAnimationFrame(frame); + }); + } + + wait(ms) { + return this.tween(ms, () => {}); + } + + async play(i) { + const base = this.bases[i]; + let state = { ...this.states[base], changed: [] }; + if (base !== i - 1) { + // A jump between futures: fade to the state this step starts from. + await this.tween(300, (p) => this.svg.querySelector(".scene").setAttribute("opacity", 1 - p)); + this.render(state, i - 1); + this.svg.querySelector(".scene").setAttribute("opacity", 0); + await this.tween(300, (p) => this.svg.querySelector(".scene").setAttribute("opacity", p)); + } else { + this.render(state, i - 1); + } + await this.retitle(i); + for (const action of this.scene.steps[i].actions) { + await this.animate(state, action); + state = reduce(state, action); + } + // Land exactly on the computed end state, whatever the motion left. + this.render(this.states[i], i); + } + + // Swaps in the step's headline and caption, and moves the progress bar. + async retitle(i) { + const step = this.scene.steps[i]; + const headline = this.svg.querySelector(".headline"); + const tag = this.svg.querySelector(".step-tag"); + const caption = this.svg.querySelector(".caption div"); + const bar = this.svg.querySelector(".progress"); + const from = Number(bar.getAttribute("width")); + const to = (this.scene.canvas.width * i) / (this.count - 1); + await this.tween(250, (p) => { + headline.style.opacity = 1 - p; + caption.style.opacity = 1 - p; + }); + headline.innerHTML = headlineHtml(step.title); + tag.textContent = stepTag(i); + caption.textContent = step.caption; + await this.tween(300, (p) => { + headline.style.opacity = p; + caption.style.opacity = p; + bar.setAttribute("width", lerp(from, to, p)); + }); + } + + // Draws in full any account this action brings into focus, before the + // action plays on it. + async refocusIfNeeded(state, next) { + if (next.focus.every((id) => state.focus.includes(id))) return; + await this.refocus(next); + } + + // Lights the named handler lines in every program box, and dims the rest. + lightHandlers(handlers) { + for (const g of this.svg.querySelectorAll(".acc")) { + if (this.scene.accounts[g.dataset.id].kind !== "program") continue; + for (const t of g.querySelectorAll(".lines text[data-line]")) { + const active = handlers.includes(t.textContent); + t.setAttribute("fill", active ? THEME.boxText : THEME.boxMuted); + t.setAttribute("font-weight", active ? "bold" : "normal"); + t.setAttribute("font-family", active ? ACTIVE_FONT : MONO); + t.setAttribute("stroke", active ? THEME.boxText : "none"); + t.setAttribute("stroke-width", active ? "0.35" : "0"); + const band = g.querySelector(`.running[data-for="${t.dataset.line}"]`); + const from = Number(band.getAttribute("opacity")); + const to = active ? 1 : 0; + if (from !== to) this.tween(300, (p) => band.setAttribute("opacity", lerp(from, to, p))); + } + } + } + + accountGroup(id) { + return this.svg.querySelector(`.acc[data-id="${id}"]`); + } + + // Moves every account from its focus in one state to its focus in the next. + refocus(to) { + const groups = [...this.svg.querySelectorAll(".acc")]; + const starts = groups.map((g) => Number(g.dataset.t)); + const ends = groups.map((g) => (to.focus.includes(g.dataset.id) ? 1 : 0)); + return this.tween(700, (p) => groups.forEach((g, k) => applyFocus(this.scene, g, lerp(starts[k], ends[k], p)))); + } + + // Counts a line from its old value to its new one, tinted with the accent + // while it changes, then settles back to the ink. + async changeLine(id, key, value) { + const g = this.accountGroup(id); + const lines = [...g.querySelectorAll(".lines text[data-line]")]; + const el = lines.find((t) => (key == null ? t.dataset.line === "0" : t.textContent.startsWith(key + ": "))); + const fromText = el.textContent; + const toText = lineText(key, value); + const a = numberIn(fromText); + const b = numberIn(toText); + el.style.transition = "fill 0.3s"; + el.style.fill = THEME.accentInk; + if (a && b && a.before === b.before && a.after === b.after) { + const decimals = Math.max(a.decimals, b.decimals); + await this.tween(900, (p) => { + el.textContent = p >= 1 ? toText : a.before + formatNumber(lerp(a.value, b.value, p), decimals) + a.after; + }); + } else { + await this.tween(250, (p) => el.setAttribute("opacity", 1 - p)); + el.textContent = toText; + await this.tween(250, (p) => el.setAttribute("opacity", p)); + } + // Settle on the band, in bold ink, rather than fading back to plain text. + const acc = this.scene.accounts[id]; + const holder = document.createElementNS(SVG_NS, "g"); + holder.innerHTML = changedBand(acc, Number(el.getAttribute("y"))); + const band = holder.firstElementChild; + const already = el.previousElementSibling?.classList.contains("changed"); + band.setAttribute("opacity", already ? 1 : 0); + if (!already) el.parentNode.insertBefore(band, el); + el.setAttribute("font-weight", "bold"); + el.style.fill = THEME.boxText; + await this.tween(300, (p) => band.setAttribute("opacity", p)); + } + + async animate(state, action) { + const next = reduce(state, action); + switch (action.type) { + case "show": + case "focus": { + // Accounts already on screen move to their new focus; ones arriving + // fade in where they stand. + const starts = Object.fromEntries([...this.svg.querySelectorAll(".acc")].map((g) => [g.dataset.id, Number(g.dataset.t)])); + this.svg.querySelector(".accounts").innerHTML = this.scene.order + .filter((id) => next.exists.includes(id)) + .map((id) => accountMarkup(this.scene.accounts[id], next)) + .join(""); + const groups = [...this.svg.querySelectorAll(".acc")]; + // Redrawn accounts keep their NEW badges only if they are still new. + for (const g of groups) g.querySelector(".new").setAttribute("opacity", next.isNew.includes(g.dataset.id) ? 1 : 0); + const end = (g) => (next.focus.includes(g.dataset.id) ? 1 : 0); + await this.tween(700, (p) => + groups.forEach((g) => { + const id = g.dataset.id; + if (id in starts) applyFocus(this.scene, g, lerp(starts[id], end(g), p)); + else applyFocus(this.scene, g, end(g), p); + }), + ); + return; + } + case "call": { + // Fade out the last call's arrows and NEW badges, and only those: + // a hidden badge must stay hidden, not flash on and fade. + const old = [...this.svg.querySelectorAll(".arrows .arrow, .acc .new")].filter( + (el) => el.getAttribute("opacity") !== "0", + ); + await this.tween(300, (p) => old.forEach((el) => el.setAttribute("opacity", 1 - p))); + for (const el of this.svg.querySelectorAll(".arrows .arrow")) el.remove(); + this.lightHandlers(next.handlers); + await this.refocus(next); + return this.wait(200); + } + case "highlight": + this.lightHandlers(next.handlers); + return this.wait(200); + case "create": { + const holder = document.createElementNS(SVG_NS, "g"); + holder.innerHTML = accountMarkup(this.scene.accounts[action.id], next); + const g = holder.firstElementChild; + // Keep the scene's drawing order, so a box never lands on top of a later one. + const layer = this.svg.querySelector(".accounts"); + const order = this.scene.order; + const after = [...layer.children].find((el) => order.indexOf(el.dataset.id) > order.indexOf(action.id)); + layer.insertBefore(g, after || null); + const badge = g.querySelector(".new"); + badge.setAttribute("opacity", 0); + applyFocus(this.scene, g, 0, 0); + await this.tween(350, (p) => applyFocus(this.scene, g, 0, p)); + await this.tween(600, (p) => applyFocus(this.scene, g, p, 1)); + await this.tween(250, (p) => badge.setAttribute("opacity", p)); + return this.wait(250); + } + case "set": { + await this.refocusIfNeeded(state, next); + await Promise.all( + action.changes.map(async (change) => { + if (change.title) { + const el = this.accountGroup(change.id).querySelector(".title"); + await this.tween(250, (p) => el.setAttribute("opacity", 1 - p)); + el.textContent = change.title; + await this.tween(250, (p) => el.setAttribute("opacity", p)); + } + if (change.value != null) await this.changeLine(change.id, change.key, change.value); + }), + ); + return this.wait(300); + } + case "hide": { + const groups = [...action.ids.map((id) => this.accountGroup(id)).filter(Boolean), ...this.svg.querySelectorAll(".arrows .arrow")]; + await this.tween(500, (p) => groups.forEach((g) => g.setAttribute("opacity", 1 - p))); + groups.forEach((g) => g.remove()); + return; + } + case "close": { + const g = this.accountGroup(action.id); + g.querySelector(".new").setAttribute("opacity", 0); + const badge = g.querySelector(".closed"); + await this.tween(250, (p) => badge.setAttribute("opacity", p)); + await this.wait(700); + const arrows = [...this.svg.querySelectorAll(".arrows .arrow")]; + await this.tween(600, (p) => [g, ...arrows].forEach((el) => el.setAttribute("opacity", 1 - p))); + g.remove(); + arrows.forEach((el) => el.remove()); + return this.wait(200); + } + case "transfer": { + if (action.alone) { + const old = [...this.svg.querySelectorAll(".arrows .arrow")]; + await this.tween(250, (p) => old.forEach((el) => el.setAttribute("opacity", 1 - p))); + old.forEach((el) => el.remove()); + } + await this.refocusIfNeeded(state, next); + const layer = this.svg.querySelector(".arrows"); + layer.insertAdjacentHTML("beforeend", arrowMarkup(action.arrow, { partial: true })); + const g = layer.lastElementChild; + placeArrow(g, action.arrow); + const path = g.querySelector(".stroke"); + const marks = [g.querySelector(".label"), g.querySelector(".coin")]; + marks.forEach((el) => el.setAttribute("opacity", 0)); + const length = path.getTotalLength(); + path.setAttribute("stroke-dasharray", `${length} ${length}`); + await this.tween(600, (p) => path.setAttribute("stroke-dashoffset", length * (1 - p))); + path.removeAttribute("stroke-dasharray"); + path.removeAttribute("stroke-dashoffset"); + path.setAttribute("marker-end", "url(#anim-arr)"); + // The tokens leave the source as a coin sets off along the arrow, + // and arrive in the destination as it lands. + const mover = document.createElementNS(SVG_NS, "g"); + mover.innerHTML = COIN; + this.svg.querySelector(".movers").appendChild(mover); + const leaving = action.from.value == null ? null : this.changeLine(action.from.id, action.from.key, action.from.value); + await this.tween(1300, (p) => { + const pt = path.getPointAtLength(length * p); + mover.setAttribute("transform", `translate(${pt.x},${pt.y})`); + }); + mover.remove(); + await Promise.all([leaving, action.to.value == null ? null : this.changeLine(action.to.id, action.to.key, action.to.value)]); + await this.tween(300, (p) => marks.forEach((el) => el.setAttribute("opacity", p))); + return this.wait(200); + } + default: + throw new Error(`unknown action ${action.type}`); + } + } + } + + // A path through waypoints, straight between them and turning each corner + // on a quarter curve of radius r, so the stroke stays smooth at every join. + function rounded(points, r = 8) { + let d = `M ${points[0][0]},${points[0][1]}`; + for (let i = 1; i < points.length - 1; i++) { + const [px, py] = points[i - 1], [x, y] = points[i], [nx, ny] = points[i + 1]; + const into = Math.hypot(x - px, y - py), out = Math.hypot(nx - x, ny - y); + const k = Math.min(r, into / 2, out / 2); + d += ` L ${x - ((x - px) / into) * k},${y - ((y - py) / into) * k}`; + d += ` Q ${x},${y} ${x + ((nx - x) / out) * k},${y + ((ny - y) / out) * k}`; + } + const [lx, ly] = points[points.length - 1]; + return `${d} L ${lx},${ly}`; + } + + window.AccountAnimation = { Player, reduce, clusterCurve, rounded, THEME, ICONS }; +})(); diff --git a/animations/escrow/index.html b/animations/escrow/index.html new file mode 100644 index 00000000..eb22a4c7 --- /dev/null +++ b/animations/escrow/index.html @@ -0,0 +1,50 @@ + + + + + +Escrow Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/escrow/scene.js b/animations/escrow/scene.js new file mode 100644 index 00000000..03e1973f --- /dev/null +++ b/animations/escrow/scene.js @@ -0,0 +1,309 @@ +// The Escrow chapter as an animated scene: Alice offers 250 USDC for one +// TSLAx, the program holds her USDC in a vault only it can move, and either +// Bob takes the offer or Alice cancels it. +// +// The columns are the chapter figures' columns spread across a 16:9 screen: +// Alice, Bob, the two mints beneath the curve, and the program with the offer +// and its vault. The steps follow the handlers in +// quicknode/solana-program-examples finance/escrow (anchor-v1): make_offer() +// moves the USDC before it writes the offer's fields, and take_offer() checks +// the taker's terms before any token moves. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + + const COLUMN = { alice: [150, 170], bob: [390, 160], program: [880, 224] }; + const ata = (person, n, owner, token, [x, w]) => + derived("token", `${owner}'s ${token}`, x, person.y + 77 * n, w, [ + `${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", `${token.toUpperCase()} MINT`, + ]); + + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const program = onCurve("program", "escrow program", ...COLUMN.program); + const offer = derived("struct", "offer account", COLUMN.program[0], program.y + tall(3) + 4 + GAP2, COLUMN.program[1], ['"OFFER" + ALICE\'S', "ADDRESS + ID"]); + const vault = derived("token", "vault", COLUMN.program[0], offer.y + tall(5) + GAP2, COLUMN.program[1], ["OFFER'S ADDRESS + TOKEN", "PROGRAM + USDC MINT"]); + + const accounts = { + alice, + aliceUsdc: ata(alice, 1, "Alice", "USDC", COLUMN.alice), + aliceTslax: ata(alice, 2, "Alice", "TSLAx", COLUMN.alice), + bob, + bobUsdc: ata(bob, 1, "Bob", "USDC", COLUMN.bob), + bobTslax: ata(bob, 2, "Bob", "TSLAx", COLUMN.bob), + usdcMint: onCurve("mint", "USDC mint", 590, 120), + tslaxMint: onCurve("mint", "TSLAx mint", 730, 120), + program, + offer, + vault, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // Alice's lane runs down the gap between her column and Bob's; the program + // lane down the gap beside the program's column. + + const ALICE_LANE = (COLUMN.alice[0] + COLUMN.alice[1] + COLUMN.bob[0]) / 2; + const PROGRAM_LANE = COLUMN.program[0] - 24; + const vaultY = vault.y + 26; + + // From Alice's USDC down her lane and straight across, under every column, + // into the vault; and the same route back. + const intoVault = rounded([ + [A.aliceUsdc.x + A.aliceUsdc.w + 2, A.aliceUsdc.y + 20], [ALICE_LANE, A.aliceUsdc.y + 20], + [ALICE_LANE, vaultY], [vault.x - 2, vaultY], + ]); + const outOfVault = rounded([ + [vault.x - 2, vaultY], [ALICE_LANE, vaultY], + [ALICE_LANE, A.aliceUsdc.y + 20], [A.aliceUsdc.x + A.aliceUsdc.w + 2, A.aliceUsdc.y + 20], + ]); + // Bob's TSLAx straight across the lane into Alice's. + const bobToAlice = rounded([ + [A.bobTslax.x - 2, A.bobTslax.y + 20], [ALICE_LANE, A.bobTslax.y + 20], + [ALICE_LANE, A.aliceTslax.y + 20], [A.aliceTslax.x + A.aliceTslax.w + 2, A.aliceTslax.y + 20], + ]); + // From the vault up the program lane and across into Bob's USDC. + const vaultToBob = rounded([ + [vault.x - 2, vaultY], [PROGRAM_LANE, vaultY], + [PROGRAM_LANE, A.bobUsdc.y + 20], [A.bobUsdc.x + A.bobUsdc.w + 2, A.bobUsdc.y + 20], + ]); + + const below = { dx: 0, dy: 22, anchor: "middle" }; + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", alone: true, + from: { id: from, value: fromValue }, to: { id: to, value: toValue }, arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + const HANDLERS = ["make_offer()", "take_offer()", "cancel_offer()"]; + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Every token has a [mint]", + caption: + "Each kind of token is defined by one mint account. This is the mint for USDC, a token worth one US dollar.", + actions: [{ type: "show", ids: ["usdcMint"], focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "Alice keeps her USDC in a token account of her own. Its address, the dot off the curve, is worked out " + + "from the three names above it rather than held by anyone. It holds 1,000 USDC: a thousand dollars.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice wants a share of [Tesla]", + caption: + "TSLAx is a token that tracks one share of Tesla stock, with a mint of its own. Alice will pay 250 USDC " + + "for one, but whoever pays first has to trust the other to deliver.", + actions: [{ type: "show", ids: ["tslaxMint"], focus: "all" }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one is an escrow, and each line is an instruction handler " + + "anyone can call by sending a transaction. First, Alice makes her offer.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + + // ---- Alice makes the offer + { + title: "Alice runs [make_offer()]", + caption: + "Alice, the maker, offers 250 USDC for 1 TSLAx. The transaction creates an offer account at a PDA, a vault for " + + "her USDC whose authority is the offer, so only the program can move it, and her own TSLAx account, so Bob " + + "never has to. Alice pays their rent: the SOL an account holds to exist.", + actions: [ + { type: "call", handler: "make_offer()", focus: ["alice", "aliceUsdc", "program", "usdcMint", "tslaxMint"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (maker)" }] }, + { type: "create", id: "aliceTslax", lines: [balance("0 TSLAx")] }, + { + type: "create", id: "offer", + lines: [field("id: —"), field("maker: —"), field("token_mint_a: —"), field("token_mint_b: —"), field("token_b_wanted_amount: —")], + }, + { type: "create", id: "vault", lines: [balance("0 USDC"), note("authority: the offer PDA")] }, + ], + }, + { + title: "Alice's 250 USDC go into the [vault]", + caption: + "The handler refuses an offer of zero tokens on either side (ZeroAmount), then moves Alice's 250 USDC into " + + "the vault, with Alice signing. From here, no person can move them: only the escrow program's code.", + actions: [ + transfer("aliceUsdc", "750 USDC", "vault", "250 USDC", { + id: "make", d: intoVault, coinNear: { x: 640, y: vaultY }, + label: ["make_offer()", "250 USDC"], labelAt: below, + }), + ], + }, + { + key: "offered", + title: "The offer records the [terms]", + caption: + "Last, the handler writes the offer's fields. Amounts are stored in minor units, the token's smallest unit: " + + "TSLAx has eight decimals, so 1 TSLAx is 100,000,000. The fields never change after this.", + actions: [ + { + type: "set", + changes: [ + { id: "offer", key: "id", value: "1" }, + { id: "offer", key: "maker", value: "Alice" }, + { id: "offer", key: "token_mint_a", value: "USDC" }, + { id: "offer", key: "token_mint_b", value: "TSLAx" }, + { id: "offer", key: "token_b_wanted_amount", value: "100,000,000" }, + ], + }, + ], + }, + + // ---- Another future: nobody takes it, and Alice cancels + { + title: "Alice runs [cancel_offer()]", + caption: + "Alice can cancel her offer, and only she can: the offer's address " + + "is worked out again from the signer's address, and a different signer finds no offer there.", + actions: [ + { type: "call", handler: "cancel_offer()", focus: ["alice", "aliceUsdc", "program", "offer", "vault"] }, + ], + }, + { + title: "Alice's USDC comes [back]", + caption: + "The program signs for the vault with the offer's seeds, and returns all 250 USDC to Alice.", + actions: [ + transfer("vault", "0 USDC", "aliceUsdc", "1,000 USDC", { + id: "cancel", d: outOfVault, coinNear: { x: 640, y: vaultY }, + label: ["cancel_offer()", "250 USDC"], labelAt: below, + }), + ], + }, + { + title: "The vault and the offer [close]", + caption: + "Both accounts close, and their rent goes back to Alice. She has her 1,000 USDC again, and keeps the TSLAx " + + "account make_offer() opened for her.", + actions: [ + // Clear the last arrow first, so nothing points at a closed account. + { type: "hide", ids: [] }, + { type: "close", id: "vault" }, + { type: "close", id: "offer" }, + ], + }, + + // ---- Bob takes the offer + { + from: "offered", + title: "Bob runs [take_offer()]", + caption: + "Bob holds a TSLAx and likes the price. He passes the terms he saw: at least 250 USDC " + + "out, at most 1 TSLAx in. If the offer has changed, the handler refuses (OfferTermsChanged) before any token moves.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc", "bobTslax"], + // 1,000 USDC: every character starts with it (the chapter's opening), and the take + // figure's 1,250 is that plus the vault's 250. + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")], bobTslax: [balance("1 TSLAx")] }, + focus: "shown", + }, + { type: "call", handler: "take_offer()", focus: ["bob", "bobUsdc", "bobTslax", "aliceTslax", "program", "offer", "vault"] }, + { type: "set", changes: [{ id: "bob", title: "Bob (taker)" }] }, + ], + }, + { + title: "Bob pays Alice [directly]", + caption: + "Bob's TSLAx goes straight into Alice's TSLAx account, with Bob signing. The program never holds it, and " + + "Alice doesn't need to be online: her signature on make_offer() was enough.", + actions: [ + transfer("bobTslax", "0 TSLAx", "aliceTslax", "1 TSLAx", { + id: "pay", d: bobToAlice, coinNear: { x: ALICE_LANE, y: (A.bobTslax.y + A.aliceTslax.y) / 2 + 20 }, + label: ["1 TSLAx"], labelAt: { dx: 0, dy: 24, anchor: "middle" }, + }), + ], + }, + { + title: "The vault pays [Bob]", + caption: "The program signs for the vault with the offer's seeds, and the vault's 250 USDC goes to Bob.", + actions: [ + transfer("vault", "0 USDC", "bobUsdc", "1,250 USDC", { + id: "release", d: vaultToBob, coinNear: { x: PROGRAM_LANE, y: (vaultY + A.bobUsdc.y) / 2 }, + label: ["250 USDC"], labelAt: { dx: -14, dy: 4, anchor: "end" }, + }), + ], + }, + { + title: "The vault and the offer [close]", + caption: + "Both accounts close, and all their rent goes back to Alice. Each side received the whole of what the other " + + "offered, and nobody took a fee.", + actions: [ + { type: "hide", ids: [] }, + { type: "close", id: "vault" }, + { type: "close", id: "offer" }, + ], + }, + ]; + + window.ESCROW_SCENE = { + title: "Escrow", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 520, w: 540, h: 100, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/escrow/slides.js b/animations/escrow/slides.js new file mode 100644 index 00000000..d784eceb --- /dev/null +++ b/animations/escrow/slides.js @@ -0,0 +1,136 @@ +// The Escrow talk: the slides around the scene's diagram steps. Diagram runs +// name the scene steps they show, by index, and together they show every +// step once, in order. Each term is defined where the talk first needs it. + +(function () { + window.ESCROW_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build an", "[escrow]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Escrow chapter", + items: [ + "How two strangers swap tokens without trusting each other", + "How a program holds tokens that only its own code can move", + "Why every open offer needs a way out", + ], + }, + ], + }, + + // ---- What people want, and how an escrow gives it to them, before any Solana. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:escrow-buy", who: "Alice", + name: "Wants a share of [Tesla]", + text: "She has 1,000 USDC and will pay 250 for one share. But if she pays first, the seller could " + + "keep her money and never send the share.", + }, + { + tone: "lavender", icon: "tpl:escrow-sell", who: "Bob", + name: "Wants to [sell] his share", + text: "He holds a Tesla share and likes Alice's price. But if he sends it first, she could keep it " + + "and never pay.", + }, + ], + }, + { + type: "split", + heading: "The usual answer: a [middleman]", + sub: "How traditional finance makes strangers trade", + cards: [ + { icon: "tpl:escrow-middleman", name: "Both sides send to a trusted third party", text: "Alice sends her money to it, and it holds the money in escrow until Bob has sent his share" }, + { icon: "tpl:escrow-swap", name: "It passes each side on", text: "Once both have arrived, Alice's money goes to Bob and Bob's share to Alice" }, + { icon: "tpl:escrow-fee", name: "And it takes a fee", text: "A slice for the service, kept from what it holds on each side" }, + ], + }, + { + type: "split", + tone: "dark", + heading: "A [program] can be the middleman", + sub: "Code that both sides can read, and nobody can change", + cards: [ + { icon: "tpl:escrow-vault", name: "It holds Alice's tokens", text: "In a vault that only the program's own code can move, not any person" }, + { icon: "tpl:escrow-atomic", name: "Bob's side and Alice's move together", text: "In one transaction: either both happen, or neither does" }, + { icon: "tpl:escrow-fee", name: "And it takes no fee", text: "Nobody runs it, so each side receives the whole of what the other offered" }, + ], + }, + { + type: "grid", + tone: "lavender", + heading: "The [roles] in an escrow", + sub: "The program names them the same way", + cards: [ + { icon: "tpl:escrow-maker", name: "Maker", text: "Creates the offer, and posts what they're offering up front: Alice" }, + { icon: "tpl:escrow-taker", name: "Taker", text: "Accepts the offer exactly as it stands: Bob" }, + { icon: "tpl:escrow-offer", name: "Offer", text: "What the maker gives, and what they want back: 250 USDC for 1 TSLAx" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, her accounts, the offer, the cancel, and Bob's take. + { type: "diagram", from: 0, to: 8 }, + { + type: "statement", + heading: "Outcome 1: nobody [takes] Alice's offer", + }, + { type: "diagram", from: 9, to: 11 }, + { + type: "statement", + heading: "Outcome 2: Bob [takes] Alice's offer", + }, + { type: "diagram", from: 12, to: 15 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:escrow-buy", name: "Alice", text: "Paid 250 USDC for her Tesla share, and got back the rent for the offer and the vault" }, + { tone: "lavender", icon: "tpl:escrow-sell", name: "Bob", text: "Sold his share for the full 250 USDC, without trusting Alice" }, + { tone: "mint", icon: "program", name: "The escrow program", text: "Took no fee: nobody runs it, and nobody can sign for its vaults" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/fundraiser/index.html b/animations/fundraiser/index.html new file mode 100644 index 00000000..dc5aff08 --- /dev/null +++ b/animations/fundraiser/index.html @@ -0,0 +1,50 @@ + + + + + +Fundraiser Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/fundraiser/scene.js b/animations/fundraiser/scene.js new file mode 100644 index 00000000..0bf6acde --- /dev/null +++ b/animations/fundraiser/scene.js @@ -0,0 +1,492 @@ +// The Fundraiser chapter as an animated scene: Maria starts an all-or-nothing +// raise for 9,000 USDC, Alice, Bob and Carol back it, and then the story +// branches. In one future eight more backers meet the target, Maria claims the +// vault, and every receipt and the fundraiser close. In the other, Dave backs +// it too but the deadline passes short of the target, and every backer is +// refunded exactly what they brought. +// +// The columns are the chapter figures' accounts spread across a 16:9 screen. +// Contributions and payouts run down the lane beside each person's column, +// along a corridor beneath the columns, and up the lane beside the vault. +// The steps follow the handlers in quicknode/solana-program-examples +// finance/fundraiser (anchor-v1): contribute() counts the contribution +// before it moves the tokens, and refund() zeroes the receipt before it pays. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, drop: 60, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + const GAP3 = 37; + + // Columns, left to right: Maria, the three backers drawn in both futures, + // Dave, the USDC mint, and the program. + const COLUMN = { + maria: [12, 130], + alice: [154, 140], + bob: [306, 140], + carol: [458, 140], + dave: [610, 130], + mint: [752, 110], + program: [878, 230], + }; + + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const carol = onCurve("wallet", "Carol", ...COLUMN.carol); + const dave = onCurve("wallet", "Dave", ...COLUMN.dave); + const usdcMint = onCurve("mint", "USDC mint", ...COLUMN.mint); + const program = onCurve("program", "fundraiser program", ...COLUMN.program); + + const usdc = (person, owner) => + derived("token", `${owner}'s USDC`, person.x, person.y + 77, person.w, [`${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", "USDC MINT"]); + const receipt = (person, owner) => + derived("struct", `${owner}'s receipt`, person.x, person.y + 154, person.w, ['"CONTRIBUTION" +', "FUNDRAISER +", `${owner.toUpperCase()}'S ADDRESS`]); + + const fundraiser = derived("struct", "fundraiser", COLUMN.program[0], program.y + 90 + GAP2, COLUMN.program[1], ['"FUNDRAISER" +', "MARIA'S ADDRESS"]); + const vault = derived("token", "vault", COLUMN.program[0], fundraiser.y + tall(8) + GAP3, COLUMN.program[1], ["FUNDRAISER'S ADDRESS +", "TOKEN PROGRAM +", "USDC MINT"]); + + const accounts = { + maria, mariaUsdc: usdc(maria, "Maria"), + alice, aliceUsdc: usdc(alice, "Alice"), aliceReceipt: receipt(alice, "Alice"), + bob, bobUsdc: usdc(bob, "Bob"), bobReceipt: receipt(bob, "Bob"), + carol, carolUsdc: usdc(carol, "Carol"), carolReceipt: receipt(carol, "Carol"), + dave, daveUsdc: usdc(dave, "Dave"), daveReceipt: receipt(dave, "Dave"), + usdcMint, program, fundraiser, vault, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // Each person's lane is the gap on the right of their column; the corridor + // runs beneath every column; the vault's lane is the gap on its left. + + const laneRight = (acc) => acc.x + acc.w + 6; + const VAULT_LANE = 870; + const CORRIDOR = 330; + + // From a person's USDC down their lane, along the corridor, and up into the vault. + function intoVault(from) { + const sx = from.x + from.w + 2, sy = from.y + 20; + const lane = laneRight(from); + const ex = vault.x - 2, ey = vault.y + 26; + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [VAULT_LANE, CORRIDOR], [VAULT_LANE, ey], [ex, ey]]); + } + + // From the vault along the corridor and up a person's lane into their USDC. + function outOfVault(to) { + const sx = vault.x - 2, sy = vault.y + 26; + const lane = laneRight(to); + const ex = to.x + to.w + 2, ey = to.y + 20; + return rounded([[sx, sy], [VAULT_LANE, sy], [VAULT_LANE, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + } + + // The coin sits on the corridor, beside the person's own lane. + const below = { dx: 0, dy: 22, anchor: "middle" }; + const corridorNear = (acc) => ({ x: laneRight(acc) + 70, y: CORRIDOR }); + + const contribution = (who, from, to, label) => ({ + type: "transfer", + alone: true, + from: { id: `${who}Usdc`, value: from }, + to: { id: "vault", value: to }, + arrow: { id: `${who}-${to}`, d: intoVault(A[`${who}Usdc`]), coinNear: corridorNear(A[`${who}Usdc`]), label, labelAt: below }, + }); + const payout = (who, from, to, label) => ({ + type: "transfer", + alone: true, + from: { id: "vault", value: from }, + to: { id: `${who}Usdc`, value: to }, + arrow: { id: `${who}-out-${from}`, d: outOfVault(A[`${who}Usdc`]), coinNear: corridorNear(A[`${who}Usdc`]), label, labelAt: below }, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + + const HANDLERS = [ + "initialize_fundraiser()", + "contribute()", + "check_contributions()", + "close_contribution()", + "refund()", + "close_fundraiser()", + ]; + + const backer = (who, name) => ({ + type: "show", + ids: [who, `${who}Usdc`], + lines: { [who]: [sol("1 SOL")], [`${who}Usdc`]: [balance("1,000 USDC")] }, + focus: "shown", + }); + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Every token has a [mint]", + caption: "Each kind of token is defined by one mint account. This is the mint for USDC, a token worth one US dollar.", + actions: [{ type: "show", ids: ["usdcMint"], focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "Alice keeps her USDC in a token account of her own. Its address, the dot off the curve, is worked out " + + "from the three names above it rather than held by anyone. It holds 1,000 USDC: a thousand dollars.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice wants to [back] a machine", + caption: + "Alice runs three cafes and wants Maria's espresso machine on her counters. She'll put in her 1,000 USDC, " + + "as long as she gets it back if the machine can't be built.", + actions: [{ type: "focus", ids: ["alice", "aliceUsdc"] }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs fundraisers, and each line is an instruction " + + "handler anyone can call by sending a transaction. First, Maria has to start her fundraiser.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + + // ---- The raise opens + { + title: "Maria runs [initialize_fundraiser()]", + caption: + "Maria is the maker. She sets a target of 9,000 USDC and a duration of 7 days, and nothing lets her change " + + "either later. The fundraiser records the terms; the vault is a token account only the program can sign for.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_fundraiser()", focus: ["maria", "program", "usdcMint"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (maker)" }] }, + { + type: "create", id: "fundraiser", + lines: [ + field("maker: Maria"), + field("mint_to_raise: USDC"), + field("amount_to_raise: 9,000 USDC"), + field("current_amount: 0 USDC"), + field("time_started: today"), + field("duration: 7 days"), + field("claimed: false"), + field("open_contributions: 0"), + ], + }, + { type: "create", id: "vault", lines: [balance("0 USDC"), note("authority: the fundraiser")] }, + ], + }, + + // ---- The backers + { + title: "Alice runs [contribute()]", + caption: + "Her first contribution creates a receipt: a contribution account the program writes for itself, " + + "at an address made from the fundraiser and Alice's address. It will record what she put in.", + actions: [ + { type: "call", handler: "contribute()", focus: ["alice", "aliceUsdc", "program", "fundraiser", "vault"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (backer)" }] }, + { type: "create", id: "aliceReceipt", lines: [field("amount: 0 USDC")] }, + ], + }, + { + title: "The program [counts] it first", + caption: + "Before a token moves, current_amount rises by 1,000, Alice's receipt records 1,000, and open_contributions " + + "counts one open receipt.", + actions: [ + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "1,000 USDC" }, + { id: "aliceReceipt", key: "amount", value: "1,000 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "1" }, + ], + }, + ], + }, + { + title: "Alice's 1,000 USDC go into the [vault]", + caption: "Only the program can move them out again, and only to Maria if the target is met, or back to Alice if it isn't.", + actions: [contribution("alice", "0 USDC", "1,000 USDC", ["contribute()", "1,000 USDC"])], + }, + { + title: "Bob backs it with [800]", + caption: "Bob distributes restaurant equipment and wants a new product line to carry. He gets his own receipt.", + actions: [ + backer("bob"), + { type: "call", handler: "contribute()", focus: ["bob", "bobUsdc", "program", "fundraiser", "vault"] }, + { type: "set", changes: [{ id: "bob", title: "Bob (backer)" }] }, + { type: "create", id: "bobReceipt", lines: [field("amount: 0 USDC")] }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "1,800 USDC" }, + { id: "bobReceipt", key: "amount", value: "800 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "2" }, + ], + }, + contribution("bob", "200 USDC", "1,800 USDC", ["800 USDC"]), + ], + }, + { + title: "Carol backs it with [500]", + caption: "Carol is an espresso enthusiast who wants one at home badly enough to help it exist.", + actions: [ + backer("carol"), + { type: "call", handler: "contribute()", focus: ["carol", "carolUsdc", "program", "fundraiser", "vault"] }, + { type: "set", changes: [{ id: "carol", title: "Carol (backer)" }] }, + { type: "create", id: "carolReceipt", lines: [field("amount: 0 USDC")] }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "2,300 USDC" }, + { id: "carolReceipt", key: "amount", value: "500 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "3" }, + ], + }, + contribution("carol", "500 USDC", "2,300 USDC", ["500 USDC"]), + ], + }, + { + key: "carolDone", + title: "Carol comes back with [500 more]", + caption: + "A later contribution adds to the same receipt: Carol's reaches 1,000 USDC, and the fundraiser still counts " + + "one open receipt for her.", + actions: [ + { type: "call", handler: "contribute()", focus: ["carol", "carolUsdc", "carolReceipt", "program", "fundraiser", "vault"] }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "2,800 USDC" }, + { id: "carolReceipt", key: "amount", value: "1,000 USDC" }, + ], + }, + contribution("carol", "0 USDC", "2,800 USDC", ["500 USDC"]), + ], + }, + + // ---- First ending: the target is met + { + title: "Eight more backers reach the [target]", + caption: + "Eight more backers, not drawn here, contribute 6,200 USDC between them. That's eleven receipts and 9,000 USDC: " + + "the target is met.", + actions: [ + { type: "call", handler: "contribute()", focus: ["program", "fundraiser", "vault"] }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "9,000 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "11" }, + { id: "vault", value: "9,000 USDC" }, + ], + }, + ], + }, + { + title: "Maria runs [check_contributions()]", + caption: + "The claim compares the target with current_amount, the program's own count, never the vault's balance, " + + "which anyone can raise by sending tokens in. It sets claimed. Maria's USDC account holds the standard 1,000 USDC.", + actions: [ + { type: "show", ids: ["mariaUsdc"], lines: { mariaUsdc: [balance("1,000 USDC")] }, focus: "shown" }, + { type: "call", handler: "check_contributions()", focus: ["maria", "mariaUsdc", "program", "fundraiser", "vault"] }, + { type: "set", changes: [{ id: "fundraiser", key: "claimed", value: "true" }] }, + ], + }, + { + title: "Maria receives the [9,000 USDC]", + caption: "The whole vault goes to Maria, signed by the fundraiser. A second claim, or a late contribution, now fails.", + // Maria's 1,000 USDC plus the 9,000 claimed: the figure's 10,000. + actions: [payout("maria", "0 USDC", "10,000 USDC", ["check_contributions()", "9,000 USDC"])], + }, + { + title: "Maria runs [close_contribution()]", + caption: + "Maria sends one for each of the eleven receipts, and each one's rent goes back to its backer. The fundraiser " + + "stays open until open_contributions reaches zero, so a new raise at the same address can never read an old receipt.", + actions: [ + { type: "call", handler: "close_contribution()", focus: ["maria", "alice", "bob", "carol", "program", "fundraiser", "aliceReceipt", "bobReceipt", "carolReceipt"] }, + { type: "set", changes: [{ id: "fundraiser", key: "open_contributions", value: "0" }] }, + { type: "close", id: "aliceReceipt" }, + { type: "close", id: "bobReceipt" }, + { type: "close", id: "carolReceipt" }, + ], + }, + { + title: "Maria runs [close_fundraiser()]", + caption: + "With no receipt open, the vault and the fundraiser close and their rent goes back to Maria. " + + "Whether she builds the machine is outside the program, as it is on Kickstarter.", + actions: [ + { type: "call", handler: "close_fundraiser()", focus: ["maria", "program", "fundraiser", "vault"] }, + { type: "close", id: "vault" }, + { type: "close", id: "fundraiser" }, + ], + }, + + // ---- Second ending: the target is missed + { + from: "carolDone", + title: "Dave backs it with [800]", + caption: + "Dave, who runs a catering company, contributes 800 USDC, and nobody else comes: " + + "3,600 USDC against a 9,000 USDC target.", + actions: [ + backer("dave"), + { type: "call", handler: "contribute()", focus: ["dave", "daveUsdc", "program", "fundraiser", "vault"] }, + { type: "set", changes: [{ id: "dave", title: "Dave (backer)" }] }, + { type: "create", id: "daveReceipt", lines: [field("amount: 0 USDC")] }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "3,600 USDC" }, + { id: "daveReceipt", key: "amount", value: "800 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "4" }, + ], + }, + contribution("dave", "200 USDC", "3,600 USDC", ["800 USDC"]), + ], + }, + { + title: "The [deadline] passes", + caption: + "Seven days pass with the target missed. No handler marks the raise as failed: refund() simply starts " + + "accepting calls, and the claim can never succeed.", + actions: [{ type: "call", handler: null, focus: ["fundraiser", "vault"] }], + }, + { + title: "Alice runs [refund()]", + caption: + "It checks the deadline has passed and the target was missed. Then, before any token moves, it takes Alice's " + + "1,000 off current_amount, zeroes her receipt, and counts one fewer open receipt.", + actions: [ + { type: "call", handler: "refund()", focus: ["alice", "aliceUsdc", "aliceReceipt", "program", "fundraiser", "vault"] }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "2,600 USDC" }, + { id: "aliceReceipt", key: "amount", value: "0 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "3" }, + ], + }, + ], + }, + { + title: "Alice gets her 1,000 USDC [back]", + caption: "Exactly what she brought, and her receipt closes with its rent, so she can't be refunded twice.", + actions: [ + payout("alice", "2,600 USDC", "1,000 USDC", ["refund()", "1,000 USDC"]), + { type: "close", id: "aliceReceipt" }, + ], + }, + { + title: "Everyone is [refunded]", + caption: + "Bob and Carol are refunded the same way. Dave hasn't come back for his 800 USDC, so Maria sends his refund " + + "herself: a refund needs nobody's signature, because the tokens can only go to the backer.", + actions: [ + // Maria sends Dave's refund, so she is in this step too. + { type: "focus", ids: ["maria", "alice", "aliceUsdc", "bob", "bobUsdc", "bobReceipt", "carol", "carolUsdc", "carolReceipt", "dave", "daveUsdc", "daveReceipt", "program", "fundraiser", "vault"] }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "1,800 USDC" }, + { id: "bobReceipt", key: "amount", value: "0 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "2" }, + ], + }, + payout("bob", "1,800 USDC", "1,000 USDC", ["refund()", "800 USDC"]), + { type: "close", id: "bobReceipt" }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "800 USDC" }, + { id: "carolReceipt", key: "amount", value: "0 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "1" }, + ], + }, + payout("carol", "800 USDC", "1,000 USDC", ["refund()", "1,000 USDC"]), + { type: "close", id: "carolReceipt" }, + { + type: "set", + changes: [ + { id: "fundraiser", key: "current_amount", value: "0 USDC" }, + { id: "daveReceipt", key: "amount", value: "0 USDC" }, + { id: "fundraiser", key: "open_contributions", value: "0" }, + ], + }, + payout("dave", "0 USDC", "1,000 USDC", ["refund()", "800 USDC"]), + { type: "close", id: "daveReceipt" }, + ], + }, + { + title: "Maria runs [close_fundraiser()]", + caption: + "With every backer repaid, the vault and the fundraiser close and their rent goes back to Maria. " + + "Nothing of the failed raise remains, and she can try again with a smaller target.", + actions: [ + { type: "call", handler: "close_fundraiser()", focus: ["maria", "program", "fundraiser", "vault"] }, + { type: "close", id: "vault" }, + { type: "close", id: "fundraiser" }, + ], + }, + ]; + + window.FUNDRAISER_SCENE = { + title: "Fundraiser", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 520, w: 540, h: 104, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/fundraiser/slides.js b/animations/fundraiser/slides.js new file mode 100644 index 00000000..50d09a7e --- /dev/null +++ b/animations/fundraiser/slides.js @@ -0,0 +1,129 @@ +// The Fundraiser talk: the slides around the scene's diagram steps. Diagram +// runs name the scene steps they show, by index, and together they show every +// step once, in order. Each term is defined where the talk first needs it. + +(function () { + window.FUNDRAISER_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build an", "[all-or-nothing fundraiser]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Fundraiser chapter", + items: [ + "How a program holds many people's money until one shared condition is met", + "Why a program trusts its own count, never a balance anyone can top up", + "How every backer gets back exactly what they put in", + ], + }, + ], + }, + + // ---- What people want, and how a fundraiser gives it to them, before any Solana. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:fundraiser-maker", who: "Maria", + name: "Needs [9,000] dollars, or nothing", + text: "She has designed an espresso machine, and the factory quotes $9,000 to cut the mold for the first run. " + + "$6,000 buys not two-thirds of a run, but nothing at all.", + }, + { + tone: "lavender", icon: "tpl:fundraiser-backer", who: "Alice", + name: "Wants the machine, not the [risk]", + text: "She'd put in $1,000 to see the machine made. But if Maria can't raise enough to build it, " + + "she wants every dollar back.", + }, + ], + }, + { + type: "split", + heading: "An [all-or-nothing fundraiser] gives both what they want", + sub: "The promise Kickstarter makes, kept by code instead of a company", + cards: [ + { icon: "tpl:fundraiser-target", name: "Maria names a target", text: "and a deadline. Backers contribute until then" }, + { icon: "tpl:fundraiser-claim", name: "If the target is met, Maria gets it all", text: "every contribution, in one payment" }, + { icon: "tpl:fundraiser-refund", name: "If it's missed, everyone is refunded", text: "each backer gets back exactly what they put in" }, + ], + }, + { + type: "grid", + tone: "lavender", + columns: 4, + heading: "The [terms] of a fundraiser", + sub: "Every fundraiser names these", + cards: [ + { icon: "tpl:fundraiser-maker", name: "Maker", text: "Starts the fundraiser and is paid if it succeeds: Maria" }, + { icon: "tpl:fundraiser-target", name: "Target", text: "The amount that must be raised: $9,000" }, + { icon: "tpl:fundraiser-deadline", name: "Deadline", text: "When contributions close: 7 days after the start" }, + { icon: "tpl:fundraiser-backer", name: "Backers", text: "Everyone who contributes: Alice, Bob, Carol and more" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, the raise opening, and the first backers. + { type: "diagram", from: 0, to: 12 }, + { + type: "statement", + heading: "Outcome 1: the target is [met]", + sub: "Eight more backers come, and the counter reaches 9,000", + }, + { type: "diagram", from: 13, to: 17 }, + { + type: "statement", + heading: "Outcome 2: the target is [missed]", + sub: "The same raise, but only Dave comes after Carol", + }, + { type: "diagram", from: 18, to: 23 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:fundraiser-maker", name: "Maria the maker", text: "Met: 9,000 USDC for the mold. Missed: nothing, and free to try again" }, + { tone: "lavender", icon: "tpl:fundraiser-backer", name: "Alice, Bob and Carol", text: "Met: Maria is paid the 9,000 USDC to make the machine. Missed: every dollar back" }, + { tone: "mint", icon: "tpl:fundraiser-receipt", name: "Their receipts", text: "Closed either way, their rent back to each backer" }, + { tone: "white", icon: "tpl:fundraiser-refund", name: "Dave", text: "Refunded 800 USDC without coming back: Maria sent it for him" }, + ], + }, + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/index.html b/animations/index.html new file mode 100644 index 00000000..2068ffc3 --- /dev/null +++ b/animations/index.html @@ -0,0 +1,90 @@ + + + + + +Solana Finance Talks + + + +
Quicknode Solana Finance@QuicknodeSolana
+
+ // Building Financial Software on Solana +

One talk for every program in the book

+

Each talk explains what people want from a financial product, then builds it on Solana, one + account, handler and token transfer at a time.

+ + + +
+ In a talk, → or Space moves on, ← goes back, P plays through and + F goes full screen. The book is at solanabook.org. +
+
+ + diff --git a/animations/lending/index.html b/animations/lending/index.html new file mode 100644 index 00000000..9e8b69ad --- /dev/null +++ b/animations/lending/index.html @@ -0,0 +1,50 @@ + + + + + +Lending Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/lending/scene.js b/animations/lending/scene.js new file mode 100644 index 00000000..b9da8bdf --- /dev/null +++ b/animations/lending/scene.js @@ -0,0 +1,800 @@ +// The Lending chapter as an animated scene, following the chapter's own +// story and numbers: Maria opens a market with USDC, NVDAx and SPCXx +// reserves; Alice supplies 1,000 USDC and four SPCXx; Bob pledges five NVDAx +// and borrows 750 USDC; Carol pledges 1,000 USDC and borrows three SPCXx to +// short SpaceX; SPCXx rallies from $250 to $300 and Dave liquidates Carol +// twice; then Bob repays with interest and takes his NVDAx back, Maria +// collects her fee, and Alice redeems her shares with their yield. +// +// Every number is one the chapter or its figures state, or a balance that +// follows by adding or subtracting them; those are marked where they appear. +// Like the chapter, the scene leaves out the interest on Carol's loan, and +// Maria's opening deposits of 1,001 minor units into each reserve. +// +// Three people columns on the left, and a column per asset (its price feed, +// reserve, liquidity vault and share mint) beside the program on the right. +// People take each other's columns while they wait, as in the Options talk: +// Carol takes Alice's while Alice's deposit sits, Dave takes Maria's, and +// both hand them back for the ending. Arrows run down the lanes between +// columns and along a corridor beneath them, one transfer on screen at a +// time. The steps follow the handlers in quicknode/solana-program-examples +// finance/lending: state is written before tokens move, a deposit transfers +// before it mints, a redemption burns before it pays, and a liquidation +// takes the repayment before it hands over the seized shares. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, drop: 60, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + // Heights of boxes in full: the title bar, 12 a line, and padding. + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + const GAP3 = 37; + + // Three people columns, then a column per asset, then the program. + const COLUMN = { + p1: [12, 136], + p2: [156, 136], + p3: [300, 136], + usdc: [452, 172], + nvdax: [632, 132], + spcx: [774, 136], + program: [920, 188], + }; + + // A person's token account, its three seeds set in two lines. + const ata = (owner, mint, x, y, w, title) => + derived("token", title, x, y, w, [`${owner.toUpperCase()}'S ADDRESS + TOKEN`, `PROGRAM + ${mint}`]); + + const alice = onCurve("wallet", "Alice", ...COLUMN.p1); + const carol = onCurve("wallet", "Carol", ...COLUMN.p1); + const bob = onCurve("wallet", "Bob", ...COLUMN.p2); + const maria = onCurve("wallet", "Maria", ...COLUMN.p3); + const dave = onCurve("wallet", "Dave", ...COLUMN.p3); + // Each box below a wallet sits one slot lower: a 40-unit box and its seeds. + const slot = (person, n) => person.y + 68.6 * n; + + const obligationOf = (owner, person, [x, w]) => + derived("struct", "obligation", x, slot(person, 4), w, ['"OBLIGATION" + MARKET +', `${owner.toUpperCase()}'S ADDRESS`]); + // Seeds name which reserve and whose obligation: two vaults with the same + // seed list would be one address. + const vaultOf = (obligation, reserve, owner, [x, w]) => + derived("token", "collateral vault", x, obligation.y + tall(2) + GAP3, w, [ + '"OBLIGATION_SHARE_VAULT" +', + `${reserve} RESERVE +`, + `${owner.toUpperCase()}'S OBLIGATION`, + ]); + const bobObligation = obligationOf("Bob", bob, COLUMN.p2); + const carolObligation = obligationOf("Carol", carol, COLUMN.p1); + + // An asset's column: its price feed, its reserve, and the reserve's two + // accounts, the liquidity vault and the share mint. + function assetColumn(asset, [x, w], reserveLines) { + const mint = `${asset.toUpperCase()} MINT`; + const feed = derived("struct", `${asset} price feed`, x, 150, w, ['"PRICE_FEED" + MARKET +', mint]); + const reserve = derived("struct", `${asset} reserve`, x, feed.y + tall(1) + GAP2, w, ['"RESERVE" + MARKET +', mint]); + // Each reserve has its own vault and share mint, so the seeds name which. + const reserveAddress = `${asset.toUpperCase()} RESERVE'S ADDRESS`; + const vault = derived("token", `${asset} vault`, x, reserve.y + tall(reserveLines) + GAP2, w, ['"LIQUIDITY_VAULT" +', reserveAddress]); + const shareMint = derived("mint", "share mint", x, vault.y + tall(1) + GAP2, w, ['"SHARE_MINT" +', reserveAddress]); + return [feed, reserve, vault, shareMint]; + } + const [usdcFeed, usdcReserve, usdcVault, usdcShareMint] = assetColumn("USDC", COLUMN.usdc, 4); + const [nvdaxFeed, nvdaxReserve, nvdaxVault, nvdaxShareMint] = assetColumn("NVDAx", COLUMN.nvdax, 1); + const [spcxFeed, spcxReserve, spcxVault, spcxShareMint] = assetColumn("SPCXx", COLUMN.spcx, 2); + + const program = onCurve("program", "lending program", ...COLUMN.program); + const lendingMarket = derived("struct", "lending market", COLUMN.program[0], program.y + 190 + GAP2, COLUMN.program[1], ['"LENDING_MARKET" +', "MARKET ID"]); + + const p1 = COLUMN.p1, p2 = COLUMN.p2, p3 = COLUMN.p3; + const accounts = { + alice, + aliceUsdc: ata("Alice", "USDC MINT", p1[0], slot(alice, 1), p1[1], "Alice's USDC"), + aliceUsdcShares: ata("Alice", "USDC SHARE MINT", p1[0], slot(alice, 2), p1[1], "USDC shares"), + aliceSpcx: ata("Alice", "SPCXX MINT", p1[0], slot(alice, 3), p1[1], "Alice's SPCXx"), + aliceSpcxShares: ata("Alice", "SPCXX SHARE MINT", p1[0], slot(alice, 4), p1[1], "SPCXx shares"), + carol, + carolUsdc: ata("Carol", "USDC MINT", p1[0], slot(carol, 1), p1[1], "Carol's USDC"), + carolShares: ata("Carol", "USDC SHARE MINT", p1[0], slot(carol, 2), p1[1], "USDC shares"), + carolSpcx: ata("Carol", "SPCXX MINT", p1[0], slot(carol, 3), p1[1], "Carol's SPCXx"), + carolObligation, + carolVault: vaultOf(carolObligation, "USDC", "Carol", p1), + bob, + bobNvdax: ata("Bob", "NVDAX MINT", p2[0], slot(bob, 1), p2[1], "Bob's NVDAx"), + bobShares: ata("Bob", "NVDAX SHARE MINT", p2[0], slot(bob, 2), p2[1], "NVDAx shares"), + bobUsdc: ata("Bob", "USDC MINT", p2[0], slot(bob, 3), p2[1], "Bob's USDC"), + bobObligation, + bobVault: vaultOf(bobObligation, "NVDAX", "Bob", p2), + maria, + mariaUsdc: ata("Maria", "USDC MINT", p3[0], slot(maria, 1), p3[1], "Maria's USDC"), + dave, + daveSpcx: ata("Dave", "SPCXX MINT", p3[0], slot(dave, 1), p3[1], "Dave's SPCXx"), + daveShares: ata("Dave", "USDC SHARE MINT", p3[0], slot(dave, 2), p3[1], "USDC shares"), + usdcFeed, usdcReserve, usdcVault, usdcShareMint, + nvdaxFeed, nvdaxReserve, nvdaxVault, nvdaxShareMint, + spcxFeed, spcxReserve, spcxVault, spcxShareMint, + program, lendingMarket, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + + // Each people column's lane is the gap to its right; each asset column's + // lane is the gap to its left. + const LANE = { p1: 152, p2: 296, p3: 440, usdc: 447, nvdax: 627, spcx: 769 }; + // Beneath every column, above the caption. + const CORRIDOR = 526; + const right = (acc, dy = 20) => [acc.x + acc.w + 2, acc.y + dy]; + const left = (acc, dy = 26) => [acc.x - 2, acc.y + dy]; + + // From a person's account down their lane, along the corridor, and up an + // asset's lane into one of its accounts. + const into = (from, lane, to, assetLane) => { + const [sx, sy] = right(from); + const [ex, ey] = left(to); + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [assetLane, CORRIDOR], [assetLane, ey], [ex, ey]]); + }; + // The reverse: out of an asset's account and up into a person's. + const outOf = (from, assetLane, to, lane) => { + const [sx, sy] = left(from); + const [ex, ey] = right(to); + return rounded([[sx, sy], [assetLane, sy], [assetLane, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + }; + // Within one column, down its lane from one account's right edge to another's. + const within = (from, to, lane) => { + const [sx, sy] = right(from); + const [ex, ey] = right(to); + return rounded([[sx, sy], [lane, sy], [lane, ey], [ex, ey]]); + }; + // Between two people's columns, along the corridor beneath the one between. + const between = (from, fromLane, to, toLane) => { + const [sx, sy] = right(from); + const [ex, ey] = right(to); + return rounded([[sx, sy], [fromLane, sy], [fromLane, CORRIDOR], [toLane, CORRIDOR], [toLane, ey], [ex, ey]]); + }; + + // A label sits above a corridor coin, clear of the caption beneath it, or + // beside a lane coin. + const above = { dx: 0, dy: -12, anchor: "middle" }; + const above2 = { dx: 0, dy: -25, anchor: "middle" }; + const rightOf = { dx: 14, dy: 4, anchor: "start" }; + const leftOf = { dx: -14, dy: 4, anchor: "end" }; + const onCorridor = (x) => ({ x, y: CORRIDOR }); + + const supply = (id) => (/ShareMint$/.test(id) ? "supply" : undefined); + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + alone: true, + from: { id: from, value: fromValue, key: supply(from) }, + to: { id: to, value: toValue, key: supply(to) }, + arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + + // In the order the chapter's figures list them. + const HANDLERS = [ + "initialize_lending_market()", + "initialize_reserve()", + "update_reserve_config()", + "set_price()", + "refresh_reserve()", + "refresh_obligation()", + "deposit_reserve_liquidity()", + "redeem_reserve_collateral()", + "initialize_obligation()", + "deposit_obligation_collateral()", + "withdraw_obligation_collateral()", + "borrow_obligation_liquidity()", + "repay_obligation_liquidity()", + "liquidate_obligation()", + "close_obligation()", + "collect_program_fees()", + ]; + + const set = (...changes) => ({ type: "set", changes }); + const ch = (id, key, value) => ({ id, key, value }); + + const aliceIds = ["alice", "aliceUsdc", "aliceUsdcShares", "aliceSpcx", "aliceSpcxShares"]; + const carolIds = ["carol", "carolUsdc", "carolShares", "carolSpcx", "carolObligation", "carolVault"]; + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "She keeps USDC, a token worth one US dollar, in a token account of her own. Every kind of token is " + + "defined by a mint, one of the three names its address is worked out from. It holds 1,000 USDC.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice owns four SpaceX [shares]", + caption: "SPCXx is a token that tracks one share of SpaceX stock, at $250. Alice holds four in a second token account.", + actions: [{ type: "show", ids: ["aliceSpcx"], lines: { aliceSpcx: [balance("4 SPCXx")] }, focus: "all" }], + }, + { + title: "Alice wants her savings to earn [interest]", + caption: "Her USDC and her SPCXx sit idle. She would lend them out, if she could be sure of getting them back.", + actions: [{ type: "focus", ids: ["alice", "aliceUsdc", "aliceSpcx"] }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs lending markets, and each line is an instruction " + + "handler anyone can call by sending a transaction. First, somebody has to open a market.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + + // ---- The market opens + { + title: "Maria runs [initialize_lending_market()]", + caption: + "Maria runs the market, for a cut of the interest. Its lending market account records her as owner, and " + + "USDC as the currency every value is measured in.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_lending_market()", focus: ["maria", "program"] }, + set({ id: "maria", title: "Maria (owner)" }), + { type: "create", id: "lendingMarket", lines: [field("owner: Maria"), field("quote_currency_mint: USDC")] }, + ], + }, + { + title: "Maria runs [set_price()] three times", + caption: + "A price feed is an account holding an asset's price. Here only Maria may write one, and a price older " + + "than 25 slots is refused. USDC is $1, NVDAx, one NVIDIA share, $200, and SPCXx $250.", + actions: [ + { type: "call", handler: "set_price()", focus: ["maria", "program", "lendingMarket"] }, + { type: "create", id: "usdcFeed", lines: [field("price_mantissa: 1")] }, + { type: "create", id: "nvdaxFeed", lines: [field("price_mantissa: 200")] }, + { type: "create", id: "spcxFeed", lines: [field("price_mantissa: 250")] }, + ], + }, + { + title: "Maria runs [initialize_reserve()] three times", + caption: + "A reserve is a pool of one asset. Its vault holds the tokens, and its share mint issues suppliers' claims " + + "on them, called shares. Maria seeds each reserve with a sliver of its asset, too small to draw.", + actions: [ + { type: "call", handler: "initialize_reserve()", focus: ["maria", "program", "lendingMarket", "usdcFeed", "nvdaxFeed", "spcxFeed"] }, + { + type: "create", id: "usdcReserve", + lines: [ + field("available_liquidity: 0"), + field("borrowed_principal: 0"), + field("borrow_accumulation_factor: 1.0"), + field("accumulated_program_fees: 0"), + ], + }, + { type: "create", id: "usdcVault", lines: [balance("0 USDC")] }, + { type: "create", id: "usdcShareMint", lines: [field("supply: 0 shares")] }, + { type: "create", id: "nvdaxReserve", lines: [field("available_liquidity: 0")] }, + { type: "create", id: "nvdaxVault", lines: [balance("0 NVDAx")] }, + { type: "create", id: "nvdaxShareMint", lines: [field("supply: 0 shares")] }, + { type: "create", id: "spcxReserve", lines: [field("available_liquidity: 0"), field("borrowed_principal: 0")] }, + { type: "create", id: "spcxVault", lines: [balance("0 SPCXx")] }, + { type: "create", id: "spcxShareMint", lines: [field("supply: 0 shares")] }, + ], + }, + + // ---- Alice supplies + { + title: "Alice runs [deposit_reserve_liquidity()]", + caption: + "Alice supplies her USDC to the USDC reserve. The reserve records the deposit before any token moves. " + + "She opened an account for the shares first.", + actions: [ + { type: "show", ids: ["aliceUsdcShares"], lines: { aliceUsdcShares: [balance("0 shares")] }, focus: "shown" }, + { type: "call", handler: "deposit_reserve_liquidity()", focus: ["alice", "aliceUsdc", "aliceUsdcShares", "program", "usdcReserve", "usdcVault", "usdcShareMint"] }, + set({ id: "alice", title: "Alice (supplier)" }, ch("usdcReserve", "available_liquidity", "1,000")), + ], + }, + { + title: "Alice's 1,000 USDC go into the [vault]", + caption: "The USDC lands in the reserve's liquidity vault, the pool every borrower draws from.", + actions: [ + transfer("aliceUsdc", "0 USDC", "usdcVault", "1,000 USDC", { + id: "aliceIn", d: into(A.aliceUsdc, LANE.p1, usdcVault, LANE.usdc), + coinNear: onCorridor(320), label: ["deposit_reserve_liquidity()", "1,000 USDC"], labelAt: above2, + }), + ], + }, + { + title: "Alice gets 1,000 [shares]", + caption: + "The share mint mints her 1,000 USDC shares, one per USDC. As borrowers pay interest the pool grows " + + "while the shares stay put, so each share redeems for more. No lender's interest is recorded anywhere.", + actions: [ + transfer("usdcShareMint", "1,000 shares", "aliceUsdcShares", "1,000 shares", { + id: "aliceMint", d: outOf(usdcShareMint, LANE.usdc, A.aliceUsdcShares, LANE.p1), + coinNear: onCorridor(320), label: ["1,000 USDC shares"], labelAt: above, + }), + ], + }, + { + title: "Alice supplies her [SPCXx] too", + caption: "She does the same with her four SPCXx: the SPCXx reserve records them, and they land in its vault.", + actions: [ + { type: "show", ids: ["aliceSpcxShares"], lines: { aliceSpcxShares: [balance("0 shares")] }, focus: "shown" }, + { type: "call", handler: "deposit_reserve_liquidity()", focus: ["alice", "aliceSpcx", "aliceSpcxShares", "program", "spcxReserve", "spcxVault", "spcxShareMint"] }, + set(ch("spcxReserve", "available_liquidity", "4")), + transfer("aliceSpcx", "0 SPCXx", "spcxVault", "4 SPCXx", { + id: "aliceSpcxIn", d: into(A.aliceSpcx, LANE.p1, spcxVault, LANE.spcx), + coinNear: onCorridor(700), label: ["deposit_reserve_liquidity()", "4 SPCXx"], labelAt: above2, + }), + ], + }, + { + title: "Alice gets 4 SPCXx [shares]", + caption: "Four SPCXx shares are minted to her: her claim on the SPCXx pool.", + actions: [ + transfer("spcxShareMint", "4 shares", "aliceSpcxShares", "4 shares", { + id: "aliceSpcxMint", d: outOf(spcxShareMint, LANE.spcx, A.aliceSpcxShares, LANE.p1), + coinNear: onCorridor(700), label: ["4 SPCXx shares"], labelAt: above, + }), + ], + }, + + // ---- Bob borrows against his NVDAx + { + title: "Bob runs [deposit_reserve_liquidity()]", + caption: + "Bob needs $750 in cash but doesn't want to sell his five NVDAx, worth $200 each. First he supplies them " + + "to the NVDAx reserve, like Alice did.", + actions: [ + { + type: "show", + ids: ["bob", "bobNvdax", "bobShares"], + lines: { bob: [sol("1 SOL")], bobNvdax: [balance("5 NVDAx")], bobShares: [balance("0 shares")] }, + focus: "shown", + }, + { type: "call", handler: "deposit_reserve_liquidity()", focus: ["bob", "bobNvdax", "bobShares", "program", "nvdaxReserve", "nvdaxVault", "nvdaxShareMint"] }, + set({ id: "bob", title: "Bob (borrower)" }, ch("nvdaxReserve", "available_liquidity", "5")), + ], + }, + { + title: "Bob's 5 NVDAx go into the [vault]", + caption: "The five NVDAx land in the NVDAx reserve's vault.", + actions: [ + transfer("bobNvdax", "0 NVDAx", "nvdaxVault", "5 NVDAx", { + id: "bobIn", d: into(A.bobNvdax, LANE.p2, nvdaxVault, LANE.nvdax), + coinNear: onCorridor(520), label: ["deposit_reserve_liquidity()", "5 NVDAx"], labelAt: above2, + }), + ], + }, + { + title: "Bob gets 5 NVDAx [shares]", + caption: "Five NVDAx shares are minted to Bob. He still owns his NVIDIA position, through the shares.", + actions: [ + transfer("nvdaxShareMint", "5 shares", "bobShares", "5 shares", { + id: "bobMint", d: outOf(nvdaxShareMint, LANE.nvdax, A.bobShares, LANE.p2), + coinNear: onCorridor(520), label: ["5 NVDAx shares"], labelAt: above, + }), + ], + }, + { + title: "Bob runs [initialize_obligation()]", + caption: + "An obligation is a borrower's loan file: what they have pledged, what they owe, and what that is worth. " + + "Bob gets one per market.", + actions: [ + { type: "call", handler: "initialize_obligation()", focus: ["bob", "program", "lendingMarket"] }, + { type: "create", id: "bobObligation", lines: [field("deposits: none"), field("borrowed_value: $0")] }, + ], + }, + { + title: "Bob runs [deposit_obligation_collateral()]", + caption: + "Bob pledges his shares as collateral: they move into a vault his obligation controls. Pledged shares " + + "keep earning what any supplier earns.", + actions: [ + { type: "call", handler: "deposit_obligation_collateral()", focus: ["bob", "bobShares", "program", "bobObligation", "nvdaxReserve"] }, + { type: "create", id: "bobVault", lines: [balance("0 shares")] }, + set(ch("bobObligation", "deposits", "5 NVDAx shares")), + transfer("bobShares", "0 shares", "bobVault", "5 shares", { + id: "bobPledge", d: within(A.bobShares, A.bobVault, LANE.p2), + coinNear: { x: LANE.p2, y: 330 }, label: ["5 shares"], labelAt: rightOf, + }), + ], + }, + { + title: "Bob runs [borrow_obligation_liquidity()]", + caption: + "His collateral is worth $1,000, and the loan-to-value is 75%: he may borrow up to $750 of USDC, and does. " + + "The obligation and the USDC reserve record the loan first.", + actions: [ + { type: "show", ids: ["bobUsdc"], lines: { bobUsdc: [balance("1,000 USDC")] }, focus: "shown" }, + { type: "call", handler: "borrow_obligation_liquidity()", focus: ["bob", "bobUsdc", "program", "bobObligation", "nvdaxFeed", "usdcReserve", "usdcVault"] }, + set( + ch("bobObligation", "borrowed_value", "$750"), + // 1,000 supplied less the 750 lent. + ch("usdcReserve", "available_liquidity", "250"), + ch("usdcReserve", "borrowed_principal", "750"), + ), + ], + }, + { + title: "Bob receives [750 USDC]", + caption: + "The USDC comes out of the reserve's vault: Alice's deposit, lent to Bob. His NVDAx is not sold, " + + "and he gets it back when he repays.", + actions: [ + // Bob's standard 1,000 USDC plus the loan; the chapter's figure shows 992.50 after he repays 757.50. + transfer("usdcVault", "250 USDC", "bobUsdc", "1,750 USDC", { + id: "loan", d: outOf(usdcVault, LANE.usdc, A.bobUsdc, LANE.p2), + coinNear: onCorridor(360), label: ["borrow_obligation_liquidity()", "750 USDC"], labelAt: above2, + }), + ], + }, + + // ---- Carol shorts SpaceX + { + title: "Carol runs [deposit_reserve_liquidity()]", + caption: + "Carol thinks SpaceX is overvalued, and wants to profit if it falls. She starts by supplying 1,000 USDC " + + "to the USDC reserve, as Alice did. Alice's deposits sit untouched, so Carol takes her column.", + actions: [ + { type: "hide", ids: aliceIds }, + { + type: "show", + ids: ["carol", "carolUsdc", "carolShares"], + lines: { carol: [sol("1 SOL")], carolUsdc: [balance("1,000 USDC")], carolShares: [balance("0 shares")] }, + focus: "shown", + }, + { type: "call", handler: "deposit_reserve_liquidity()", focus: ["carol", "carolUsdc", "carolShares", "program", "usdcReserve", "usdcVault", "usdcShareMint"] }, + // 250 left after Bob's loan, plus Carol's 1,000. + set(ch("usdcReserve", "available_liquidity", "1,250")), + ], + }, + { + title: "Carol's 1,000 USDC go into the [vault]", + caption: "Her USDC joins what is left of Alice's in the vault.", + actions: [ + transfer("carolUsdc", "0 USDC", "usdcVault", "1,250 USDC", { + id: "carolIn", d: into(A.carolUsdc, LANE.p1, usdcVault, LANE.usdc), + coinNear: onCorridor(320), label: ["deposit_reserve_liquidity()", "1,000 USDC"], labelAt: above2, + }), + ], + }, + { + title: "Carol gets 1,000 [shares]", + caption: "1,000 USDC shares are minted to her. She and Alice now each hold half the reserve's shares.", + actions: [ + transfer("usdcShareMint", "2,000 shares", "carolShares", "1,000 shares", { + id: "carolMint", d: outOf(usdcShareMint, LANE.usdc, A.carolShares, LANE.p1), + coinNear: onCorridor(320), label: ["1,000 USDC shares"], labelAt: above, + }), + ], + }, + { + title: "Carol pledges her shares as [collateral]", + caption: + "Like Bob, she runs initialize_obligation() for a loan file, then deposit_obligation_collateral() to move " + + "her 1,000 USDC shares into a vault her obligation controls.", + actions: [ + { type: "call", handler: "initialize_obligation()", focus: ["carol", "program", "lendingMarket"] }, + { type: "create", id: "carolObligation", lines: [field("borrows: none"), field("borrowed_value: $0")] }, + { type: "highlight", handlers: ["deposit_obligation_collateral()"] }, + { type: "create", id: "carolVault", lines: [balance("0 shares")] }, + transfer("carolShares", "0 shares", "carolVault", "1,000 shares", { + id: "carolPledge", d: within(A.carolShares, A.carolVault, LANE.p1), + coinNear: { x: LANE.p1, y: 330 }, label: ["1,000 shares"], labelAt: rightOf, + }), + ], + }, + { + title: "Carol runs [borrow_obligation_liquidity()]", + caption: + "She borrows three SPCXx at $250 each: $750, the most her $1,000 of collateral allows at 75%. " + + "She owes the asset itself, not dollars. Her obligation and the SPCXx reserve record it first.", + actions: [ + { type: "show", ids: ["carolSpcx"], lines: { carolSpcx: [balance("0 SPCXx")] }, focus: "shown" }, + { type: "call", handler: "borrow_obligation_liquidity()", focus: ["carol", "carolSpcx", "program", "carolObligation", "carolVault", "spcxFeed", "spcxReserve", "spcxVault"] }, + set( + { id: "carol", title: "Carol (borrower)" }, + ch("carolObligation", "borrows", "3 SPCXx"), + ch("carolObligation", "borrowed_value", "$750"), + // Alice's four, less the three lent. + ch("spcxReserve", "available_liquidity", "1"), + ch("spcxReserve", "borrowed_principal", "3"), + ), + ], + }, + { + title: "Carol receives [3 SPCXx]", + caption: "Three of Alice's SPCXx leave the SPCXx vault for Carol.", + actions: [ + transfer("spcxVault", "1 SPCXx", "carolSpcx", "3 SPCXx", { + id: "carolBorrow", d: outOf(spcxVault, LANE.spcx, A.carolSpcx, LANE.p1), + coinNear: onCorridor(700), label: ["borrow_obligation_liquidity()", "3 SPCXx"], labelAt: above2, + }), + ], + }, + { + title: "Carol sells them, and is [short]", + caption: + "She sells the three SPCXx elsewhere for $750. That is a short: if SpaceX falls she buys them back " + + "cheaper and keeps the difference. If it rises, her debt rises with it, and her collateral does not.", + actions: [ + { type: "call", handler: null, focus: ["carol", "carolSpcx", "carolUsdc", "carolObligation"] }, + // Out of this market: the chapter says only that she sells them for $750. + set(ch("carolSpcx", null, "0 SPCXx"), ch("carolUsdc", null, "750 USDC")), + ], + }, + + // ---- SpaceX rallies, and Dave liquidates Carol + { + title: "SpaceX rallies to [$300]", + caption: "SPCXx rises from $250 to $300, and Maria's price feed says so.", + actions: [ + { type: "call", handler: "set_price()", focus: ["maria", "program", "spcxFeed"] }, + set(ch("spcxFeed", "price_mantissa", "300")), + ], + }, + { + title: "Carol's loan passes the [liquidation threshold]", + caption: + "Anyone may run refresh_obligation(). Carol now owes 3 × $300 = $900 against $1,000 of collateral, past " + + "her liquidation threshold of 80%, $800. The market will now pay anyone to fix that.", + actions: [ + { type: "call", handler: "refresh_obligation()", focus: ["program", "carol", "carolObligation", "carolVault", "spcxFeed"] }, + set(ch("carolObligation", "borrowed_value", "$900")), + ], + }, + { + title: "Dave runs [liquidate_obligation()]", + caption: + "Dave watches for loans like Carol's. He has bought 1.5 SPCXx elsewhere for $450. The close factor lets one " + + "liquidation repay at most 50% of a debt: 1.5 of her 3. The records change before any token moves.", + actions: [ + { type: "hide", ids: ["maria"] }, + { + type: "show", + ids: ["dave", "daveSpcx", "daveShares"], + lines: { dave: [sol("1 SOL")], daveSpcx: [balance("1.5 SPCXx")], daveShares: [balance("0 shares")] }, + focus: "shown", + }, + { + type: "call", handler: "liquidate_obligation()", also: ["refresh_reserve()", "refresh_obligation()"], + focus: ["dave", "daveSpcx", "daveShares", "program", "carolObligation", "carolVault", "spcxFeed", "spcxReserve", "spcxVault"], + }, + set( + { id: "dave", title: "Dave (liquidator)" }, + ch("carolObligation", "borrows", "1.5 SPCXx"), + ch("carolObligation", "borrowed_value", "$450"), + // 1 left in the pool, plus Dave's 1.5. + ch("spcxReserve", "available_liquidity", "2.5"), + ch("spcxReserve", "borrowed_principal", "1.5"), + ), + ], + }, + { + title: "Dave repays [1.5 SPCXx]", + caption: "Dave pays 1.5 SPCXx into the SPCXx reserve on Carol's behalf: $450 of her debt.", + actions: [ + transfer("daveSpcx", "0 SPCXx", "spcxVault", "2.5 SPCXx", { + id: "daveRepay1", d: into(A.daveSpcx, LANE.p3, spcxVault, LANE.spcx), + coinNear: onCorridor(700), label: ["liquidate_obligation()", "1.5 SPCXx"], labelAt: above2, + }), + ], + }, + { + title: "Dave seizes 472.50 [shares]", + caption: + "In return he takes $450 of Carol's collateral plus a 5% bonus, his fee for the service: $450 × 1.05 = " + + "$472.50, paid in her USDC shares. Carol still owes 1.5 SPCXx, and is still slightly unhealthy.", + actions: [ + transfer("carolVault", "527.50 shares", "daveShares", "472.50 shares", { + id: "daveSeize1", d: between(A.carolVault, LANE.p1, A.daveShares, LANE.p3), + coinNear: onCorridor(230), label: ["472.50 USDC shares"], labelAt: above, + }), + ], + }, + { + title: "Dave runs [liquidate_obligation()] again", + caption: + "He buys another 0.75 SPCXx elsewhere, for $225, and goes again: half of the remaining 1.5 SPCXx debt.", + actions: [ + { type: "call", handler: "liquidate_obligation()", also: ["refresh_reserve()", "refresh_obligation()"], focus: ["dave", "daveSpcx", "daveShares", "program", "carolObligation", "carolVault", "spcxFeed", "spcxReserve", "spcxVault"] }, + set( + ch("daveSpcx", null, "0.75 SPCXx"), + ch("carolObligation", "borrows", "0.75 SPCXx"), + ch("carolObligation", "borrowed_value", "$225"), + // 2.5 in the pool, plus Dave's 0.75. + ch("spcxReserve", "available_liquidity", "3.25"), + ch("spcxReserve", "borrowed_principal", "0.75"), + ), + ], + }, + { + title: "Dave repays [0.75 SPCXx]", + caption: "Another 0.75 SPCXx into the reserve, $225 of Carol's debt.", + actions: [ + transfer("daveSpcx", "0 SPCXx", "spcxVault", "3.25 SPCXx", { + id: "daveRepay2", d: into(A.daveSpcx, LANE.p3, spcxVault, LANE.spcx), + coinNear: onCorridor(700), label: ["liquidate_obligation()", "0.75 SPCXx"], labelAt: above2, + }), + ], + }, + { + title: "Dave seizes 236.25 more [shares]", + caption: + "$225 plus the 5% bonus: $236.25. Carol's loan is healthy again, still hers. Across both passes Dave " + + "repaid $675 and collected $708.75: a $33.75 profit for keeping the market solvent.", + actions: [ + transfer("carolVault", "291.25 shares", "daveShares", "708.75 shares", { + id: "daveSeize2", d: between(A.carolVault, LANE.p1, A.daveShares, LANE.p3), + coinNear: onCorridor(230), label: ["236.25 USDC shares"], labelAt: above, + }), + ], + }, + + // ---- Interest, repayment, and everyone settling up + { + title: "Five weeks pass, and interest [accrues]", + caption: + "Anyone may run refresh_reserve(). It grows the USDC reserve's borrow accumulation factor, which every " + + "debt is multiplied by, to 1.01, and sets 10% of the interest aside for Maria. Bob owes $757.50; no token moved.", + actions: [ + { type: "call", handler: "refresh_reserve()", also: ["refresh_obligation()"], focus: ["program", "usdcReserve", "bob", "bobObligation"] }, + set( + ch("usdcReserve", "borrow_accumulation_factor", "1.01"), + ch("usdcReserve", "accumulated_program_fees", "0.75"), + ch("bobObligation", "borrowed_value", "$757.50"), + ), + ], + }, + { + title: "Bob runs [repay_obligation_liquidity()]", + caption: "Bob no longer needs the cash. He repays the 750 he borrowed plus 7.50 of interest.", + actions: [ + { type: "call", handler: "repay_obligation_liquidity()", focus: ["bob", "bobUsdc", "program", "bobObligation", "usdcReserve", "usdcVault"] }, + set( + ch("bobObligation", "borrowed_value", "$0"), + // 1,250 in the pool, plus the 757.50 repaid. + ch("usdcReserve", "available_liquidity", "2,007.50"), + ch("usdcReserve", "borrowed_principal", "0"), + ), + transfer("bobUsdc", "992.50 USDC", "usdcVault", "2,007.50 USDC", { + id: "repay", d: into(A.bobUsdc, LANE.p2, usdcVault, LANE.usdc), + coinNear: onCorridor(360), label: ["repay_obligation_liquidity()", "757.50 USDC"], labelAt: above2, + }), + ], + }, + { + title: "Bob runs [withdraw_obligation_collateral()]", + caption: + "With nothing owed, Bob's shares come back out of the collateral vault. The emptied vault closes, and " + + "its rent returns to Bob.", + actions: [ + { type: "call", handler: "withdraw_obligation_collateral()", focus: ["bob", "bobShares", "program", "bobObligation", "bobVault", "nvdaxReserve"] }, + set(ch("bobObligation", "deposits", "none")), + transfer("bobVault", "0 shares", "bobShares", "5 shares", { + id: "bobUnpledge", d: within(A.bobVault, A.bobShares, LANE.p2), + coinNear: { x: LANE.p2, y: 330 }, label: ["5 shares"], labelAt: rightOf, + }), + { type: "close", id: "bobVault" }, + ], + }, + { + title: "Bob runs [redeem_reserve_collateral()]", + caption: "His five shares are burned first, then the reserve pays him five NVDAx. He kept his stock, and paid about $7.50 for five weeks of cash.", + actions: [ + { type: "call", handler: "redeem_reserve_collateral()", focus: ["bob", "bobShares", "bobNvdax", "program", "nvdaxReserve", "nvdaxVault", "nvdaxShareMint"] }, + set(ch("nvdaxReserve", "available_liquidity", "0")), + transfer("bobShares", "0 shares", "nvdaxShareMint", "0 shares", { + id: "bobBurn", d: into(A.bobShares, LANE.p2, nvdaxShareMint, LANE.nvdax), + coinNear: onCorridor(520), label: ["burn 5 shares"], labelAt: above, + }), + transfer("nvdaxVault", "0 NVDAx", "bobNvdax", "5 NVDAx", { + id: "bobOut", d: outOf(nvdaxVault, LANE.nvdax, A.bobNvdax, LANE.p2), + coinNear: onCorridor(520), label: ["5 NVDAx"], labelAt: above, + }), + ], + }, + { + title: "Maria runs [collect_program_fees()]", + caption: "Maria collects the 10% of the interest set aside for her: 75 cents. Dave is done, so she takes back her column.", + actions: [ + { type: "hide", ids: ["dave", "daveSpcx", "daveShares"] }, + { type: "show", ids: ["maria", "mariaUsdc"], lines: { maria: [sol("1 SOL")], mariaUsdc: [balance("1,000 USDC")] }, focus: "shown" }, + { type: "call", handler: "collect_program_fees()", focus: ["maria", "mariaUsdc", "program", "lendingMarket", "usdcReserve", "usdcVault"] }, + // 2,007.50 less the 0.75 paid out. + set(ch("usdcReserve", "accumulated_program_fees", "0"), ch("usdcReserve", "available_liquidity", "2,006.75")), + transfer("usdcVault", "2,006.75 USDC", "mariaUsdc", "1,000.75 USDC", { + id: "fees", d: rounded([left(usdcVault, 20), [LANE.usdc, usdcVault.y + 20], [LANE.usdc, A.mariaUsdc.y + 20], right(A.mariaUsdc)]), + coinNear: { x: LANE.usdc, y: 250 }, label: ["0.75 USDC"], labelAt: leftOf, + }), + ], + }, + { + title: "Alice runs [redeem_reserve_collateral()]", + caption: + "Alice takes her USDC yield. Her 1,000 shares are burned first, half the reserve's, so she is paid half " + + "its 2,006.75 USDC: 1,003.375. Her SPCXx stay supplied.", + actions: [ + { type: "hide", ids: carolIds }, + { + type: "show", + ids: aliceIds, + lines: { + alice: [sol("1 SOL")], + aliceUsdc: [balance("0 USDC")], + aliceUsdcShares: [balance("1,000 shares")], + aliceSpcx: [balance("0 SPCXx")], + aliceSpcxShares: [balance("4 shares")], + }, + focus: ["alice", "aliceUsdc", "aliceUsdcShares"], + }, + { type: "call", handler: "redeem_reserve_collateral()", focus: ["alice", "aliceUsdc", "aliceUsdcShares", "program", "usdcReserve", "usdcVault", "usdcShareMint"] }, + // 2,006.75 less the 1,003.375 paid to Alice. + set(ch("usdcReserve", "available_liquidity", "1,003.375")), + transfer("aliceUsdcShares", "0 shares", "usdcShareMint", "1,000 shares", { + id: "aliceBurn", d: into(A.aliceUsdcShares, LANE.p1, usdcShareMint, LANE.usdc), + coinNear: onCorridor(320), label: ["burn 1,000 shares"], labelAt: above, + }), + transfer("usdcVault", "1,003.375 USDC", "aliceUsdc", "1,003.375 USDC", { + id: "aliceOut", d: outOf(usdcVault, LANE.usdc, A.aliceUsdc, LANE.p1), + coinNear: onCorridor(320), label: ["1,003.375 USDC"], labelAt: above, + }), + ], + }, + ]; + + window.LENDING_SCENE = { + title: "Lending", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 550, w: 600, h: 78, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/lending/slides.js b/animations/lending/slides.js new file mode 100644 index 00000000..0e6076ac --- /dev/null +++ b/animations/lending/slides.js @@ -0,0 +1,166 @@ +// The Lending talk: the slides around the scene's diagram steps. Diagram +// runs name the scene steps they show, by index, and together they show every +// step once, in order. Each term is defined where the talk first needs it. + +(function () { + window.LENDING_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build a", "[lending market]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Lending and Borrowing chapter", + items: [ + "How lending and borrowing work as a Solana program", + "How interest grows every debt without moving a token", + "How liquidators keep the market solvent when prices move", + ], + }, + ], + }, + + // ---- What people want, and how a lending market gives it to them. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:savings", who: "Alice", + name: "Wants her savings to earn [interest]", + text: "She has $1,000 doing nothing. She'd lend it to someone, as long as she's sure to get it back.", + }, + { + tone: "lavender", icon: "tpl:lending-cash", who: "Bob", + name: "Wants [cash] without selling", + text: "He owns five NVIDIA shares worth $1,000 and needs $750 now. He expects NVIDIA to rise, " + + "so he doesn't want to sell.", + }, + ], + }, + { + type: "split", + heading: "A [lending market] gives both what they want", + sub: "Like a bank, with a program in place of the banker", + cards: [ + { icon: "tpl:savings", name: "Alice deposits her dollars", text: "and earns interest on them for as long as they stay in" }, + { icon: "tpl:lending-collateral", name: "Bob pledges his NVIDIA shares", text: "and borrows dollars against them. He gets the shares back when he repays" }, + { icon: "tpl:lending-interest", name: "Bob pays interest", text: "most of it to Alice, and a slice to whoever runs the market" }, + ], + }, + { + type: "grid", + tone: "lavender", + heading: "The [terms] of a loan", + sub: "Every lending market sets these", + cards: [ + { icon: "tpl:lending-collateral", name: "Collateral", text: "What the borrower pledges, and can lose: Bob's NVIDIA shares" }, + { icon: "tpl:lending-ltv", name: "Loan-to-value", text: "How much of the collateral's value may be borrowed: 75%, so $750 against $1,000" }, + { icon: "tpl:lending-interest", name: "Interest", text: "What borrowers pay for the loan, at a yearly rate that rises as more of the pool is lent out" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, the market, Alice's deposits, and Bob's loan. + { type: "diagram", from: 0, to: 20 }, + { + type: "allocation", + heading: "Bob's loan against his [collateral]", + sub: "He may borrow up to 75% of its value", + parts: [ + { tone: "lavender", name: "Debt", text: "750 USDC", value: 750 }, + { tone: "mint", name: "Not borrowed against", text: "$250 of $1,000", value: 250 }, + ], + }, + { + type: "statement", + heading: "Carol wants to [short] SpaceX", + sub: "Borrow the asset, sell it now, and buy it back later, cheaper if she is right. A lending market is where shorts are built", + }, + // Carol borrows SPCXx and sells it, and SpaceX rallies. + { type: "diagram", from: 21, to: 29 }, + { + type: "allocation", + heading: "SpaceX rallies, and Carol's debt passes [80%]", + sub: "Against her $1,000 of collateral. Past 80%, $800, the loan can be liquidated", + parts: [ + { tone: "lavender", name: "Debt", fromText: "3 SPCXx at $250: $750", text: "3 SPCXx at $300: $900", from: 750, value: 900 }, + { tone: "mint", name: "Not borrowed against", fromText: "$250 of $1,000", text: "$100 of $1,000", from: 250, value: 100 }, + ], + }, + { + type: "numbered", + heading: "How a [liquidation] works", + sub: "Anyone may repay part of an unhealthy loan, and is paid in its collateral", + cards: [ + { name: "Only past the threshold", text: "A loan below 80% of its collateral's value cannot be touched" }, + { name: "At most half at a time", text: "The close factor caps one liquidation at 50% of the debt" }, + { name: "Paid with a bonus", text: "The liquidator takes collateral worth the repayment plus 5%" }, + ], + }, + // Dave's two liquidations. + { type: "diagram", from: 30, to: 35 }, + { + type: "allocation", + decimals: 1, + delay: 1800, + heading: "Carol's collateral, [paid down]", + sub: "Her 1,000 USDC shares: what is left of them, and what Dave took for repaying $675 of her debt", + parts: [ + { tone: "mint", name: "Carol", fromText: "1,000 shares", text: "291.25 shares", from: 1000, value: 291.25 }, + { tone: "lavender", name: "Dave", fromText: "0 shares", text: "708.75 shares", from: 0, value: 708.75 }, + ], + }, + // Interest, Bob's repayment, Maria's fee, and Alice's yield. + { type: "diagram", from: 36, to: 41 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:savings", name: "Alice", text: "About $3.38 for five weeks of otherwise idle capital" }, + { tone: "lavender", icon: "tpl:lending-cash", name: "Bob", text: "Five weeks of cash for about $7.50, and he kept his stock" }, + { tone: "mint", icon: "tpl:lending-short", name: "Carol", text: "$1,000 became about $816.25: the price moved against her short, and $33.75 went to Dave" }, + { tone: "white", icon: "tpl:lending-liquidation", name: "Dave", text: "$33.75 for repaying $675 of Carol's debt" }, + { tone: "lavender", icon: "tpl:venue", name: "Maria the market owner", text: "$0.75: her 10% of the interest on Bob's loan" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/managed-fund/index.html b/animations/managed-fund/index.html new file mode 100644 index 00000000..eec99b81 --- /dev/null +++ b/animations/managed-fund/index.html @@ -0,0 +1,50 @@ + + + + + +Managed Fund Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/managed-fund/scene.js b/animations/managed-fund/scene.js new file mode 100644 index 00000000..42b9ba43 --- /dev/null +++ b/animations/managed-fund/scene.js @@ -0,0 +1,618 @@ +// The Managed Fund chapter as an animated scene: Victor approves the assets, +// Maria creates a fund and sets its weights, Alice deposits, NVIDIA rises and +// the fund is rebalanced, Bob buys in at the new price, Maria's fee is minted +// to her, and Alice withdraws in kind. +// +// The columns are the chapter figures' accounts spread across a 16:9 screen: +// every public-key account hangs beneath the one curve, the swap router with +// the fund's vaults beneath it. Arrows run down the lanes between columns and +// along a corridor beneath them, one transfer on screen at a time. The steps +// follow the handlers in quicknode/solana-program-examples +// finance/managed-fund: a deposit values the fund before it takes the USDC +// in, deploys it, and mints the shares last; a withdrawal burns first. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + // A flatter curve than the Options talk's: the program column here holds + // five accounts and needs the height. + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, drop: 60, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + // Heights of the boxes in full, for stacking: the title bar, 12 a line, and + // padding; 10 a line for a program's handlers. + const tall = (lines) => 21 + lines * 12 + 7; + // The gap above a box that carries a two- or three-line seed list. + const GAP2 = 28.6; + const GAP3 = 37; + + // Columns, left to right, with lanes between some of them for arrows. + const COLUMN = { + victor: [12, 148], + alice: [172, 140], + bob: [356, 128], + maria: [528, 136], + router: [712, 136], + program: [884, 224], + }; + + const ata = (owner, token, x, y, w) => + derived("token", `${owner}'s ${token}`, x, y, w, [`${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", `${token.toUpperCase()} MINT`]); + + // Victor's column: his wallet, the registry, the approved assets, and the + // price accounts they name. + const victor = onCurve("wallet", "Victor", ...COLUMN.victor); + const registry = derived("struct", "registry", COLUMN.victor[0], victor.y + tall(1) + GAP2, COLUMN.victor[1], ['"REGISTRY" +', "VICTOR'S ADDRESS"]); + const approvedTsla = derived("struct", "ApprovedAsset", COLUMN.victor[0], registry.y + tall(1) + GAP3, COLUMN.victor[1], ['"APPROVED_ASSET" +', "REGISTRY +", "TSLAX MINT"]); + const approvedNvda = derived("struct", "ApprovedAsset", COLUMN.victor[0], approvedTsla.y + tall(2) + GAP3, COLUMN.victor[1], ['"APPROVED_ASSET" +', "REGISTRY +", "NVDAX MINT"]); + const pythTsla = derived("struct", "Pyth TSLA", COLUMN.victor[0], approvedNvda.y + tall(2) + GAP2, COLUMN.victor[1], ["SHARD +", "TSLA FEED ID"]); + const pythNvda = derived("struct", "Pyth NVDA", COLUMN.victor[0], pythTsla.y + tall(2) + GAP2, COLUMN.victor[1], ["SHARD +", "NVDA FEED ID"]); + + // Each investor's column: wallet, USDC, shares, and the assets a + // withdrawal pays out. + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const slot = (person, n) => person.y + 77 * n; + + // The router hangs beneath the curve, and the fund's vaults beneath it. + const router = onCurve("program", "swap router", ...COLUMN.router); + const usdcVault = derived("token", "USDC vault", COLUMN.router[0], router.y + 50 + GAP2, COLUMN.router[1], ["FUND'S ADDRESS + TOKEN", "PROGRAM + USDC MINT"]); + const tslaxVault = derived("token", "TSLAx vault", COLUMN.router[0], usdcVault.y + tall(2) + GAP2, COLUMN.router[1], ["FUND'S ADDRESS + TOKEN", "PROGRAM + TSLAX MINT"]); + const nvdaxVault = derived("token", "NVDAx vault", COLUMN.router[0], tslaxVault.y + tall(2) + GAP2, COLUMN.router[1], ["FUND'S ADDRESS + TOKEN", "PROGRAM + NVDAX MINT"]); + + // The program, the fund, its asset configs, and its share mint. + const program = onCurve("program", "managed-fund program", ...COLUMN.program); + const fund = derived("struct", "fund", COLUMN.program[0], program.y + 120 + GAP2, COLUMN.program[1], ['"FUND" +', "INDEX"]); + const assetConfig0 = derived("struct", "asset config 0", COLUMN.program[0], fund.y + tall(6) + GAP2, COLUMN.program[1], ['"ASSET" + FUND +', "INDEX 0"]); + const assetConfig1 = derived("struct", "asset config 1", COLUMN.program[0], assetConfig0.y + tall(2) + GAP2, COLUMN.program[1], ['"ASSET" + FUND +', "INDEX 1"]); + const shareMint = derived("mint", "share mint", COLUMN.program[0], assetConfig1.y + tall(2) + GAP2, COLUMN.program[1], ['"SHARE_MINT" +', "FUND'S ADDRESS"]); + + const accounts = { + victor, registry, approvedTsla, approvedNvda, pythTsla, pythNvda, + alice, + aliceUsdc: ata("Alice", "USDC", COLUMN.alice[0], slot(alice, 1), COLUMN.alice[1]), + aliceShares: derived("token", "Alice's shares", COLUMN.alice[0], slot(alice, 2), COLUMN.alice[1], ["ALICE'S ADDRESS +", "TOKEN PROGRAM +", "SHARE MINT"]), + aliceTslax: ata("Alice", "TSLAx", COLUMN.alice[0], slot(alice, 3), COLUMN.alice[1]), + aliceNvdax: ata("Alice", "NVDAx", COLUMN.alice[0], slot(alice, 4), COLUMN.alice[1]), + bob, + bobUsdc: ata("Bob", "USDC", COLUMN.bob[0], slot(bob, 1), COLUMN.bob[1]), + bobShares: derived("token", "Bob's shares", COLUMN.bob[0], slot(bob, 2), COLUMN.bob[1], ["BOB'S ADDRESS +", "TOKEN PROGRAM +", "SHARE MINT"]), + maria, + mariaShares: derived("token", "Maria's shares", COLUMN.maria[0], slot(maria, 1), COLUMN.maria[1], ["MARIA'S ADDRESS +", "TOKEN PROGRAM +", "SHARE MINT"]), + router, usdcVault, tslaxVault, nvdaxVault, + program, fund, assetConfig0, assetConfig1, shareMint, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // Lanes run down the gaps between columns; the corridor runs beneath every + // column but the program's. An arrow leaves the flat of an edge, follows + // lanes and the corridor, and arrives on the flat of an edge. + + const LANE = { + alice: 338, // between Alice and Bob + bob: 510, // between Bob and Maria + toRouter: 684, // between Maria and the router, for arrows heading right + toMaria: 690, // the same gap, for arrows heading left into Maria's column + program: 858, // between the router's column and the program's + }; + const CORRIDOR = 448; + const right = (acc, dy = 20) => [acc.x + acc.w + 2, acc.y + dy]; + const left = (acc, dy = 26) => [acc.x - 2, acc.y + dy]; + + // From an investor's account down their lane, along the corridor, and up + // into a vault in the router's column. + function intoVault(from, lane, to) { + const [sx, sy] = right(from); + const [ex, ey] = left(to); + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [LANE.toRouter, CORRIDOR], [LANE.toRouter, ey], [ex, ey]]); + } + + // From a vault down to the corridor, and up a lane into an investor's account. + function outOfVault(from, lane, to) { + const [sx, sy] = left(from); + const [ex, ey] = right(to); + return rounded([[sx, sy], [LANE.toRouter, sy], [LANE.toRouter, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + } + + // Between a vault and the router, round the lane on the router's left. + function loop(from, fromDy, to, toDy) { + const [sx, sy] = left(from, fromDy); + const [ex, ey] = left(to, toDy); + return rounded([[sx, sy], [LANE.toRouter, sy], [LANE.toRouter, ey], [ex, ey]]); + } + + // From the share mint, out under the router's column, along the corridor, + // and up a lane into a shareholder's account. + function minted(lane, to) { + const [sx, sy] = left(shareMint); + const [ex, ey] = right(to); + return rounded([[sx, sy], [LANE.program, sy], [LANE.program, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + } + + // The reverse: shares burned, from a shareholder's account to the mint. + function burned(lane, from) { + const [sx, sy] = right(from); + const [ex, ey] = left(shareMint); + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [LANE.program, CORRIDOR], [LANE.program, ey], [ex, ey]]); + } + + // A label hangs below a corridor coin, or to the left of a lane coin. + const below = { dx: 0, dy: 22, anchor: "middle" }; + const leftOf = { dx: -14, dy: 4, anchor: "end" }; + + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + alone: true, + from: { id: from, value: fromValue, key: fromValue && from === "shareMint" ? "supply" : undefined }, + to: { id: to, value: toValue, key: toValue && to === "shareMint" ? "supply" : undefined }, + arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + const vault = (amount) => [balance(amount), note("authority: the fund")]; + + const HANDLERS = [ + "initialize_registry()", + "approve_asset()", + "initialize_fund()", + "add_asset()", + "set_weight()", + "deposit()", + "rebalance()", + "collect_fees()", + "withdraw()", + ]; + const BUY = "swap_usdc_for_asset()"; + const SELL = "swap_asset_for_usdc()"; + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "She keeps USDC, a token worth one US dollar, in a token account of her own. Every kind of token is " + + "defined by a mint, one of the three names its address is worked out from. It holds 1,000 USDC.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice wants her savings [invested]", + caption: + "Alice wants to put $900 into stocks, picked by an expert, without handing the expert her money.", + actions: [{ type: "focus", ids: ["alice", "aliceUsdc"] }], + }, + + // ---- The registry + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs managed funds, and each line is an instruction " + + "handler anyone can call by sending a transaction. First, somebody decides which stocks a fund may hold.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + { + title: "Victor runs [initialize_registry()]", + caption: + "Victor is a curator: he decides which assets any fund on his platform may hold, and his reputation rests " + + "on funds not failing. His registry records him as its authority. He is not a fund manager.", + actions: [ + { type: "show", ids: ["victor"], lines: { victor: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_registry()", focus: ["victor", "program"] }, + { type: "set", changes: [{ id: "victor", title: "Victor (curator)" }] }, + { type: "create", id: "registry", lines: [field("authority: Victor")] }, + ], + }, + { + title: "Pyth publishes the [prices]", + caption: + "TSLAx and NVDAx are tokens that track one share of Tesla and of NVIDIA. Pyth, an oracle, publishes their " + + "prices onto Solana: each price feed is an account owned by the Pyth Receiver program.", + actions: [ + { + type: "show", + ids: ["pythTsla", "pythNvda"], + lines: { + pythTsla: [field("price: $250"), field("owner: Pyth Receiver")], + pythNvda: [field("price: $180"), field("owner: Pyth Receiver")], + }, + focus: "shown", + }, + ], + }, + { + title: "Victor runs [approve_asset()]", + caption: + "For each asset Victor vets, an ApprovedAsset binds its mint to its official price feed. A manager can " + + "then neither list a token they minted themselves, nor pair a real asset with a price feed they control.", + actions: [ + { type: "call", handler: "approve_asset()", focus: ["victor", "program", "registry", "pythTsla", "pythNvda"] }, + { type: "create", id: "approvedTsla", lines: [field("mint: TSLAx"), field("price_feed: Pyth TSLA")] }, + { type: "create", id: "approvedNvda", lines: [field("mint: NVDAx"), field("price_feed: Pyth NVDA")] }, + ], + }, + + // ---- The fund + { + title: "Maria runs [initialize_fund()]", + caption: + "Maria, the fund manager, sets her fee in basis points, hundredths of a percent: 100, so 1% a year. Her slippage " + + "limit, also 1%, caps how far below Pyth's price a trade may fill. The fund gets a mint for its shares, and a USDC " + + "vault: a token account the program controls.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_fund()", focus: ["maria", "program", "registry"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (manager)" }] }, + { + type: "create", id: "fund", + lines: [ + field("manager: Maria"), + field("registry: Victor's"), + field("fee_bps: 100"), + field("max_slippage_bps: 100"), + field("total_shares: 0"), + field("total_weight_bps: 0"), + ], + }, + { type: "create", id: "shareMint", lines: [field("supply: 0 shares"), note("mint authority: the fund")] }, + { type: "create", id: "usdcVault", lines: vault("0 USDC") }, + ], + }, + { + title: "Maria runs [add_asset()] to set the weights", + caption: + "40% TSLAx and 60% NVDAx, each with its own vault. add_asset() only takes an asset with an ApprovedAsset, " + + "and copies its price feed from there. Nobody can deposit until the weights reach 100%.", + actions: [ + { type: "call", handler: "add_asset()", focus: ["maria", "program", "fund", "approvedTsla", "approvedNvda"] }, + { type: "create", id: "assetConfig0", lines: [field("mint: TSLAx"), field("weight_bps: 4,000")] }, + { type: "create", id: "tslaxVault", lines: vault("0 TSLAx") }, + { type: "create", id: "assetConfig1", lines: [field("mint: NVDAx"), field("weight_bps: 6,000")] }, + { type: "create", id: "nvdaxVault", lines: vault("0 NVDAx") }, + { type: "set", changes: [{ id: "fund", key: "total_weight_bps", value: "10,000" }] }, + ], + }, + + // ---- Alice's deposit + { + key: "aliceCalls", + title: "Alice runs [deposit()]", + caption: + "First the program values the fund: every holding times its Pyth price, its net asset value, NAV. An empty " + + "fund's NAV is zero, so Alice's 900 USDC will buy 900 shares, one-to-one. Her share account is created.", + actions: [ + { type: "call", handler: "deposit()", focus: ["alice", "aliceUsdc", "program", "fund", "pythTsla", "pythNvda", "usdcVault", "shareMint"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (investor)" }] }, + { type: "create", id: "aliceShares", lines: [balance("0 shares")] }, + ], + }, + { + title: "Alice's 900 USDC go into the [fund]", + caption: "The USDC lands in the fund's USDC vault. From here the program, not Maria, decides where it goes.", + actions: [ + transfer("aliceUsdc", "100 USDC", "usdcVault", "900 USDC", { + id: "aliceIn", d: intoVault(A.aliceUsdc, LANE.alice, usdcVault), + coinNear: { x: 490, y: CORRIDOR }, label: ["deposit()", "900 USDC"], labelAt: below, + }), + ], + }, + { + title: "The fund buys [TSLAx] with 40%", + caption: + "The swap router is a program that trades one token for another, like Jupiter. 40% of 900 is 360 USDC, " + + "which buys TSLAx at $250. The fund signs, and the router is the one fixed when Maria created the fund.", + actions: [ + { type: "show", ids: ["router"], lines: { router: [field(BUY), field(SELL)] }, focus: "shown" }, + { type: "highlight", handlers: ["deposit()", BUY] }, + transfer("usdcVault", "540 USDC", "router", null, { + id: "aliceTslaOut", d: loop(usdcVault, 20, router, 32), + coinNear: { x: LANE.toRouter, y: 140 }, label: ["360 USDC"], labelAt: leftOf, + }), + ], + }, + { + title: "1.44 TSLAx come [back]", + caption: + "The program sets the worst price it will accept from Pyth's price, at most 1% below it, or the whole " + + "deposit reverts. Maria never supplies that minimum, so she can't approve a bad trade.", + actions: [ + transfer("router", null, "tslaxVault", "1.44 TSLAx", { + id: "aliceTslaIn", d: loop(router, 40, tslaxVault, 26), + coinNear: { x: LANE.toRouter, y: 200 }, label: ["1.44 TSLAx"], labelAt: leftOf, + }), + ], + }, + { + title: "The fund buys [NVDAx] with 60%", + caption: "60% of 900 is 540 USDC, which buys NVDAx at $180, through the same router, under the same floor.", + actions: [ + transfer("usdcVault", "0 USDC", "router", null, { + id: "aliceNvdaOut", d: loop(usdcVault, 20, router, 32), + coinNear: { x: LANE.toRouter, y: 140 }, label: ["540 USDC"], labelAt: leftOf, + }), + ], + }, + { + title: "3 NVDAx come [back]", + caption: "The program counts what each swap actually moved into its vaults, and records it as the fund's holdings.", + actions: [ + transfer("router", null, "nvdaxVault", "3 NVDAx", { + id: "aliceNvdaIn", d: loop(router, 40, nvdaxVault, 26), + coinNear: { x: LANE.toRouter, y: 280 }, label: ["3 NVDAx"], labelAt: leftOf, + }), + ], + }, + { + key: "aliceShares", + title: "Alice gets 900 [shares]", + caption: + "Last, the share mint mints 900 shares into Alice's account: her slice of everything the fund holds. " + + "Only the program's own math can mint them.", + actions: [ + { type: "highlight", handlers: ["deposit()"] }, + transfer("shareMint", "900 shares", "aliceShares", "900 shares", { + id: "aliceMint", d: minted(LANE.alice, A.aliceShares), + coinNear: { x: 600, y: CORRIDOR }, label: ["900 shares"], labelAt: below, + }), + { type: "set", changes: [{ id: "fund", key: "total_shares", value: "900" }] }, + ], + }, + + // ---- The market moves, and the fund is rebalanced + { + title: "NVIDIA rises to [$200]", + caption: + "Pyth's NVDA price moves from $180 to $200. The fund's 1.44 TSLAx and 3 NVDAx are now worth $960, so each " + + "of the 900 shares is worth about $1.07. Nobody stores that price: it's worked out at each deposit.", + actions: [ + { type: "call", handler: null, focus: ["pythNvda", "pythTsla", "tslaxVault", "nvdaxVault", "fund"] }, + { type: "set", changes: [{ id: "pythNvda", key: "price", value: "$200" }] }, + ], + }, + { + title: "Anyone runs [rebalance()]", + caption: + "NVDAx is now 62.5% of the fund against its 60% weight: $24 too much, and TSLAx $24 too little. Anyone may " + + "call this, but the program decides the trade, and only once drift passes the threshold Maria set: 2 points.", + actions: [ + { type: "call", handler: "rebalance()", focus: ["program", "fund", "pythTsla", "pythNvda", "router", "usdcVault", "tslaxVault", "nvdaxVault"] }, + ], + }, + { + title: "The fund sells 0.12 [NVDAx]", + caption: "$24 of NVDAx at $200 is 0.12 NVDAx, sold through the same router, under an oracle-anchored floor.", + actions: [ + { type: "highlight", handlers: ["rebalance()", SELL] }, + transfer("nvdaxVault", "2.88 NVDAx", "router", null, { + id: "sellNvda", d: loop(nvdaxVault, 20, router, 32), + coinNear: { x: LANE.toRouter, y: 300 }, label: ["0.12 NVDAx"], labelAt: leftOf, + }), + ], + }, + { + title: "24 USDC come [back]", + caption: "The USDC lands in the fund's own USDC vault. It never passes through an account the caller controls.", + actions: [ + transfer("router", null, "usdcVault", "24 USDC", { + id: "sellBack", d: loop(router, 40, usdcVault, 26), + coinNear: { x: LANE.toRouter, y: 150 }, label: ["24 USDC"], labelAt: leftOf, + }), + ], + }, + { + title: "The fund buys [TSLAx] with it", + caption: "The 24 USDC goes straight back out through the router for TSLAx at $250.", + actions: [ + { type: "highlight", handlers: ["rebalance()", BUY] }, + transfer("usdcVault", "0 USDC", "router", null, { + id: "buyTsla", d: loop(usdcVault, 20, router, 32), + coinNear: { x: LANE.toRouter, y: 140 }, label: ["24 USDC"], labelAt: leftOf, + }), + ], + }, + { + key: "rebalanced", + title: "0.096 TSLAx come [back]", + caption: + "The weights are back at 40/60: 1.536 TSLAx and 2.88 NVDAx. A second call straight after would find nothing " + + "to sell, and fail.", + actions: [ + transfer("router", null, "tslaxVault", "1.536 TSLAx", { + id: "buyBack", d: loop(router, 40, tslaxVault, 26), + coinNear: { x: LANE.toRouter, y: 200 }, label: ["0.096 TSLAx"], labelAt: leftOf, + }), + ], + }, + + // ---- Bob buys in + { + title: "Bob runs [deposit()]", + caption: + "Bob, a later investor, deposits 480 USDC. Valued from Pyth's prices, the NAV is now $960 against 900 shares, " + + "so 480 USDC buys 450 shares, not 480: Alice's gains stay hers. His share account is created.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc"], + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "deposit()", focus: ["bob", "bobUsdc", "program", "fund", "pythTsla", "pythNvda", "router", "usdcVault", "tslaxVault", "nvdaxVault", "shareMint"] }, + { type: "set", changes: [{ id: "bob", title: "Bob (investor)" }] }, + { type: "create", id: "bobShares", lines: [balance("0 shares")] }, + ], + }, + { + title: "Bob's USDC buys at [40/60]", + caption: + "His 480 USDC goes in and out at today's prices, same as Alice's did: 192 USDC for 0.768 TSLAx, " + + "and 288 USDC for 1.44 NVDAx.", + actions: [ + transfer("bobUsdc", "520 USDC", "usdcVault", "480 USDC", { + id: "bobIn", d: intoVault(A.bobUsdc, LANE.bob, usdcVault), + coinNear: { x: 570, y: CORRIDOR }, label: ["deposit()", "480 USDC"], labelAt: below, + }), + { type: "highlight", handlers: ["deposit()", BUY] }, + transfer("usdcVault", "288 USDC", "router", null, { + id: "bobTslaOut", d: loop(usdcVault, 20, router, 32), + coinNear: { x: LANE.toRouter, y: 140 }, label: ["192 USDC"], labelAt: leftOf, + }), + transfer("router", null, "tslaxVault", "2.304 TSLAx", { + id: "bobTslaIn", d: loop(router, 40, tslaxVault, 26), + coinNear: { x: LANE.toRouter, y: 200 }, label: ["0.768 TSLAx"], labelAt: leftOf, + }), + transfer("usdcVault", "0 USDC", "router", null, { + id: "bobNvdaOut", d: loop(usdcVault, 20, router, 32), + coinNear: { x: LANE.toRouter, y: 140 }, label: ["288 USDC"], labelAt: leftOf, + }), + transfer("router", null, "nvdaxVault", "4.32 NVDAx", { + id: "bobNvdaIn", d: loop(router, 40, nvdaxVault, 26), + coinNear: { x: LANE.toRouter, y: 280 }, label: ["1.44 NVDAx"], labelAt: leftOf, + }), + ], + }, + { + title: "Bob gets 450 [shares]", + caption: "Last, 450 shares are minted to Bob. 1,350 shares now exist.", + actions: [ + { type: "highlight", handlers: ["deposit()"] }, + transfer("shareMint", "1,350 shares", "bobShares", "450 shares", { + id: "bobMint", d: minted(LANE.bob, A.bobShares), + coinNear: { x: 680, y: CORRIDOR }, label: ["450 shares"], labelAt: below, + }), + { type: "set", changes: [{ id: "fund", key: "total_shares", value: "1,350" }] }, + ], + }, + + // ---- The fee + { + title: "Anyone runs [collect_fees()]", + caption: + "A year on, the 1% fee is due: 1% of 1,350 shares is 13.5. Instead of selling assets, the program mints new " + + "shares to the manager, diluting every holder equally. The fee rate can never be changed.", + actions: [ + { type: "call", handler: "collect_fees()", focus: ["maria", "program", "fund", "shareMint"] }, + { type: "create", id: "mariaShares", lines: [balance("0 shares")] }, + ], + }, + { + key: "feesPaid", + title: "Maria gets 13.5 [shares]", + caption: "No token leaves any vault. Maria's shares are a claim on the fund, like everyone else's.", + actions: [ + transfer("shareMint", "1,363.5 shares", "mariaShares", "13.5 shares", { + id: "feeMint", d: minted(LANE.toMaria, A.mariaShares), + coinNear: { x: 760, y: CORRIDOR }, label: ["collect_fees()", "13.5 shares"], labelAt: below, + }), + { type: "set", changes: [{ id: "fund", key: "total_shares", value: "1,363.5" }] }, + ], + }, + + // ---- Alice withdraws + { + title: "Alice runs [withdraw()]", + caption: + "Alice cashes out. The program sells nothing: it pays her slice of every vault in kind, as the tokens " + + "themselves. She has opened TSLAx and NVDAx accounts to receive them.", + actions: [ + { + type: "show", + ids: ["aliceTslax", "aliceNvdax"], + lines: { aliceTslax: [balance("0 TSLAx")], aliceNvdax: [balance("0 NVDAx")] }, + focus: "shown", + }, + { type: "call", handler: "withdraw()", focus: ["alice", "aliceShares", "aliceTslax", "aliceNvdax", "program", "fund", "shareMint", "usdcVault", "tslaxVault", "nvdaxVault"] }, + ], + }, + { + title: "Alice's 900 shares are [burned]", + // 66% is 900 ÷ 1,363.5, from the chapter's share counts. + caption: "Her 900 shares are destroyed first, leaving 463.5. Her slice of each vault is 900 of the 1,363.5 shares, about 66%.", + actions: [ + transfer("aliceShares", "0 shares", "shareMint", "463.5 shares", { + id: "burn", d: burned(LANE.alice, A.aliceShares), + coinNear: { x: 600, y: CORRIDOR }, label: ["withdraw()", "burn 900 shares"], labelAt: below, + }), + { type: "set", changes: [{ id: "fund", key: "total_shares", value: "463.5" }] }, + ], + }, + { + title: "Alice receives her [TSLAx]", + caption: "Her slice of the TSLAx vault's 2.304 TSLAx is about 1.52, rounded down, in the fund's favour.", + actions: [ + // The chapter and its figure give these to two places, as approximate. + transfer("tslaxVault", "≈0.78 TSLAx", "aliceTslax", "≈1.52 TSLAx", { + id: "payTsla", d: outOfVault(tslaxVault, LANE.alice, A.aliceTslax), + coinNear: { x: 490, y: CORRIDOR }, label: ["≈1.52 TSLAx"], labelAt: below, + }), + ], + }, + { + title: "Alice receives her [NVDAx]", + caption: + "And about 2.85 of the 4.32 NVDAx. She came in with $900, rode NVIDIA up, paid Maria's 1% by dilution, " + + "and leaves with about $950 of shares in Tesla and NVIDIA.", + actions: [ + transfer("nvdaxVault", "≈1.47 NVDAx", "aliceNvdax", "≈2.85 NVDAx", { + id: "payNvda", d: outOfVault(nvdaxVault, LANE.alice, A.aliceNvdax), + coinNear: { x: 490, y: CORRIDOR }, label: ["≈2.85 NVDAx"], labelAt: below, + }), + ], + }, + ]; + + window.FUND_SCENE = { + title: "Managed Fund", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 532, w: 540, h: 92, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/managed-fund/slides.js b/animations/managed-fund/slides.js new file mode 100644 index 00000000..fe3866f0 --- /dev/null +++ b/animations/managed-fund/slides.js @@ -0,0 +1,151 @@ +// The Managed Fund talk: the slides around the scene's diagram steps. Diagram +// runs name the scene steps they show, by index, and together they show every +// step once, in order. Each term is defined where the talk first needs it. + +(function () { + window.FUND_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to make an", "[investment fund]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Managed Fund chapter", + items: [ + "How an investment fund works as a Solana program", + "Why the manager can trade the fund's assets, but never take them", + "How shares price every investor fairly, early or late", + ], + }, + ], + }, + + // ---- What people want, and how a fund gives it to them, before any Solana. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:savings", who: "Alice", + name: "Wants her savings [invested]", + text: "She has $900 for the stock market, but not the time or the expertise to pick stocks. " + + "She'd pay someone to do it, as long as they can't walk off with her money.", + }, + { + tone: "lavender", icon: "tpl:expertise", who: "Maria", + name: "Wants to be paid for her [expertise]", + text: "She's good at picking stocks, and wants to earn a fee for managing other people's money.", + }, + ], + }, + { + type: "numbered", + heading: "A [managed fund] gives both what they want", + sub: "The same idea as a mutual fund", + cards: [ + { name: "Investors put money in", text: "and receive shares: each investor's slice of everything the fund holds" }, + { name: "The manager picks the assets", text: "and how much of the fund goes to each, its weight. The fund buys them" }, + { name: "The manager earns a fee", text: "a small slice of the fund each year, whatever the market does" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, the curator, the fund, and Alice's deposit. + { type: "diagram", from: 0, to: 16 }, + { + type: "allocation", + heading: "The fund holds its [target weights]", + sub: "Alice's 900 USDC, deployed at 40/60 on deposit", + parts: [ + { tone: "mint", name: "TSLAx", text: "1.44 TSLAx at $250: $360", value: 360 }, + { tone: "lavender", name: "NVDAx", text: "3 NVDAx at $180: $540", value: 540 }, + ], + }, + // The market moves. + { type: "diagram", from: 17, to: 17 }, + { + type: "allocation", + decimals: 1, + heading: "NVIDIA rallies, and the weights [drift]", + sub: "Nothing traded, but NVDAx is now worth more than its 60% share", + parts: [ + { tone: "mint", name: "TSLAx", text: "1.44 TSLAx at $250: $360", value: 360, from: 360 }, + { tone: "lavender", name: "NVDAx", fromText: "3 NVDAx at $180: $540", text: "3 NVDAx at $200: $600", value: 600, from: 540 }, + ], + }, + // The rebalance. + { type: "diagram", from: 18, to: 22 }, + { + type: "allocation", + heading: "Back to [40/60]", + sub: "The rebalance sold $24 of NVDAx and bought $24 of TSLAx", + parts: [ + { tone: "mint", name: "TSLAx", fromText: "1.44 TSLAx at $250: $360", text: "1.536 TSLAx at $250: $384", value: 384, from: 360 }, + { tone: "lavender", name: "NVDAx", fromText: "3 NVDAx at $200: $600", text: "2.88 NVDAx at $200: $576", value: 576, from: 600 }, + ], + }, + // Bob, and the fee. + { type: "diagram", from: 23, to: 27 }, + { + type: "allocation", + decimals: 1, + heading: "Maria is paid by [dilution]", + sub: "Who owns the fund's 1,363.5 shares, after 13.5 new shares were minted to Maria", + parts: [ + { tone: "mint", name: "Alice", text: "900 shares", value: 900 }, + { tone: "lavender", name: "Bob", text: "450 shares", value: 450 }, + { tone: "white", name: "Maria", text: "13.5 shares", value: 13.5, callout: true }, + ], + }, + // Alice withdraws. + { type: "diagram", from: 28, to: 31 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:savings", name: "Alice", text: "Came in with $900, rode NVIDIA up, paid Maria by dilution, and left with about $950 of TSLAx and NVDAx" }, + { tone: "lavender", icon: "tpl:later", name: "Bob", text: "Still holds his 450 shares, unrealized" }, + { tone: "mint", icon: "tpl:expertise", name: "Maria the manager", text: "Holds 13.5 shares, about $14, for managing the fund" }, + { tone: "white", icon: "tpl:vetting", name: "Victor the curator", text: "Took no fee: his business is a platform whose funds don't fail" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/options/index.html b/animations/options/index.html new file mode 100644 index 00000000..0503f18e --- /dev/null +++ b/animations/options/index.html @@ -0,0 +1,50 @@ + + + + + +Options Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/options/scene.js b/animations/options/scene.js new file mode 100644 index 00000000..05b0bd20 --- /dev/null +++ b/animations/options/scene.js @@ -0,0 +1,684 @@ +// The Options chapter as an animated scene: the venue opens, Alice writes a +// covered call that Bob buys and exercises, Carol writes a cash-secured put +// that Dave buys and lets expire, and Maria collects the fees. The two +// futures the chapter sets aside (the call expiring unused, the put +// exercised) branch off the story and return to it. +// +// The columns are the chapter figures' columns spread across a 16:9 screen, +// which leaves room for the mints beneath the one curve. Carol and Dave take +// Alice's and Bob's columns once the call is done, as they do in the figures. +// The steps follow the handlers in quicknode/solana-program-examples +// finance/options: state is written and check_custody() runs before any +// transfer. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + // The curve starts lower than in the figures, leaving the top of the slide + // to the headline. + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, control: 700 / WIDTH }); + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + // Each person's column stacks the wallet, two token accounts, and the + // writer's option, 77 units apart as in the figures. + const SLOT = { second: 77, third: 154, option: 222.6 }; + const ata = (person, slot, owner, token, x, w) => + derived("token", `${owner}'s ${token}`, x, person.y + SLOT[slot], w, [ + `${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", `${token.toUpperCase()} MINT`, + ]); + const optionAt = (writer, owner, x, w) => + derived("struct", "option", x, writer.y + SLOT.option, w, ['"OPTION" + MARKET\'S ADDRESS +', `${owner.toUpperCase()}'S ADDRESS + ID`]); + + // Columns: Maria, the writer (Alice, then Carol), the holder (Bob, then + // Dave), the two mints, and the program. The gap between the writer's and + // the holder's columns is the lane arrows take between them. + const COLUMN = { maria: [16, 150], writer: [182, 200], holder: [430, 160], program: [884, 220] }; + + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const alice = onCurve("wallet", "Alice", ...COLUMN.writer); + const bob = onCurve("wallet", "Bob", ...COLUMN.holder); + const carol = onCurve("wallet", "Carol", ...COLUMN.writer); + const dave = onCurve("wallet", "Dave", ...COLUMN.holder); + const program = onCurve("program", "options program", ...COLUMN.program); + const market = derived("struct", "market", COLUMN.program[0], program.y + 110 + 28.6, COLUMN.program[1], ['"MARKET" + NVDAX &', "USDC MINT ADDRESSES"]); + const underlyingVault = derived("token", "underlying vault", COLUMN.program[0], market.y + 112 + 37, COLUMN.program[1], ['"UNDERLYING_VAULT" +', "MARKET'S ADDRESS"]); + const quoteVault = derived("token", "quote vault", COLUMN.program[0], underlyingVault.y + 52 + 40, COLUMN.program[1], ['"QUOTE_VAULT" +', "MARKET'S ADDRESS"]); + + const accounts = { + maria, + mariaUsdc: ata(maria, "second", "Maria", "USDC", ...COLUMN.maria), + alice, + aliceNvdax: ata(alice, "second", "Alice", "NVDAx", ...COLUMN.writer), + aliceUsdc: ata(alice, "third", "Alice", "USDC", ...COLUMN.writer), + option: optionAt(alice, "Alice", ...COLUMN.writer), + bob, + bobUsdc: ata(bob, "second", "Bob", "USDC", ...COLUMN.holder), + bobNvdax: ata(bob, "third", "Bob", "NVDAx", ...COLUMN.holder), + carol, + carolNvdax: ata(carol, "second", "Carol", "NVDAx", ...COLUMN.writer), + carolUsdc: ata(carol, "third", "Carol", "USDC", ...COLUMN.writer), + putOption: optionAt(carol, "Carol", ...COLUMN.writer), + dave, + // Dave's USDC sits level with Carol's, so his premium crosses the lane. + daveNvdax: ata(dave, "second", "Dave", "NVDAx", ...COLUMN.holder), + daveUsdc: ata(dave, "third", "Dave", "USDC", ...COLUMN.holder), + nvdaxMint: onCurve("mint", "NVDAx mint", 606, 120), + usdcMint: onCurve("mint", "USDC mint", 742, 120), + program, + market, + underlyingVault, + quoteVault, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // Each runs from the flat of one box's edge to the flat of another's. The + // writer-to-holder lane is the middle of the gap between those columns. + + const LANE = (COLUMN.writer[0] + COLUMN.writer[1] + COLUMN.holder[0]) / 2; + const rightEdge = (acc, dy) => [acc.x + acc.w + 2, acc.y + dy]; + const leftEdge = (acc, dy) => [acc.x - 2, acc.y + dy]; + + // Across the page, from a right edge to the left edge of a program-column + // account: out level, then down (or up) and in level. + function across(from, fromDy, to, toDy) { + const [sx, sy] = rightEdge(from, fromDy); + const [ex, ey] = leftEdge(to, toDy); + const pull = (ex - sx) / 2; + return `M ${sx},${sy} C ${sx + pull},${sy} ${ex - pull},${ey} ${ex},${ey}`; + } + + // Back from a program-column account's left edge to a right edge. + function back(from, fromDy, to, toDy) { + const [sx, sy] = leftEdge(from, fromDy); + const [ex, ey] = rightEdge(to, toDy); + const pull = (sx - ex) / 2; + return `M ${sx},${sy} C ${sx - pull},${sy} ${ex + pull},${ey} ${ex},${ey}`; + } + + // From a program-column account into a writer's account, up the lane, so + // the arrow passes beside the holder's column rather than through it. + function upLane(from, fromDy, to, toDy) { + const [sx, sy] = leftEdge(from, fromDy); + const [ex, ey] = rightEdge(to, toDy); + const turn = ey + 70; + return `M ${sx},${sy} C ${sx - 220},${sy} ${LANE},${sy - 40} ${LANE},${turn} C ${LANE},${ey + 25} ${LANE - 6},${ey} ${ex},${ey}`; + } + + // From a writer's account down the lane, then across to the program column. + function downLane(from, fromDy, to, toDy) { + const [sx, sy] = rightEdge(from, fromDy); + const [ex, ey] = leftEdge(to, toDy); + const turn = sy + 70; + return `M ${sx},${sy} C ${LANE - 6},${sy} ${LANE},${sy + 25} ${LANE},${turn} C ${LANE},${ey - 40} ${ex - 220},${ey} ${ex},${ey}`; + } + + // From the bottom of the holder's USDC into the writer's USDC, which sits + // one slot lower in the next column. + function premium(from, to) { + const sx = from.x + 12; + const sy = from.y + 42; + const [ex, ey] = rightEdge(to, 24); + return `M ${sx},${sy} C ${sx},${sy + 35} ${sx + 8},${ey} ${ex},${ey}`; + } + + // Straight across the lane, between two accounts at the same height. + function acrossLane(from, to) { + const y = (Math.max(from.y, to.y) + Math.min(from.y, to.y) + 40) / 2; + return `M ${from.x - 2},${y} L ${to.x + to.w + 2},${y}`; + } + + // From the quote vault, beneath everything, up into Maria's USDC. + function toMaria() { + const [sx, sy] = leftEdge(quoteVault, 26); + const ex = A.mariaUsdc.x + 75; + const ey = A.mariaUsdc.y + 42; + return `M ${sx},${sy} C ${sx - 420},${sy - 30} ${ex},${ey + 300} ${ex},${ey}`; + } + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + + const HANDLERS = [ + "initialize_market()", + "write_option()", + "buy_option()", + "cancel_option()", + "exercise_option()", + "collect_proceeds()", + "reclaim_collateral()", + "collect_fees()", + ]; + + const optionLines = ({ id, writer, kind, strike, premium }) => [ + field(`id: ${id}`), + field("market: the NVDAx/USDC market"), + field(`writer: ${writer}`), + field("holder: none yet"), + field(`kind: ${kind}`), + field("status: Listed"), + field("underlying_amount: 5 NVDAx"), + field(`strike_amount: ${strike} USDC`), + field(`premium: ${premium} USDC`), + field("expiry: one week out"), + ]; + + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + from: { id: from, value: fromValue }, + to: { id: to, value: toValue }, + arrow, + }); + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana: one account at a time. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Every token has a [mint]", + caption: + "Each kind of token is defined by one mint account. Here are two: USDC, a token worth one US dollar, " + + "and NVDAx, a token that tracks one share of NVIDIA stock.", + actions: [{ type: "show", ids: ["nvdaxMint", "usdcMint"], focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "Alice keeps her USDC in a token account of her own. Its address, the dot off the curve, is worked out " + + "from the three names above it rather than held by anyone. It holds 1,000 USDC: a thousand dollars.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice owns five shares of [NVIDIA]", + caption: + "Alice holds five NVDAx in a second token account, one for each kind of token she owns. " + + "NVIDIA trades at $165, so her five shares are worth $825.", + actions: [{ type: "show", ids: ["aliceNvdax"], lines: { aliceNvdax: [balance("5 NVDAx")] }, focus: "all" }], + }, + { + title: "Alice wants to be paid to [wait]", + caption: + "Alice wants to write an option: the right to buy her five NVDAx at $180 any time this week, " + + "for a premium of 25 USDC.", + actions: [{ type: "focus", ids: ["alice", "aliceNvdax"] }], + }, + + // ---- The venue opens + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs an options venue, and each line is an instruction " + + "handler anyone can call by sending a transaction. First, somebody has to open the venue.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + { + title: "Maria runs [initialize_market()] to open the venue", + caption: + "Maria runs the venue, for 1% of every premium. One transaction creates the market, which records what the " + + "venue owes, and two vaults: token accounts the program controls, an underlying vault for NVDAx and a quote " + + "vault for USDC. Maria pays their rent, the SOL an account holds to exist.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_market()", focus: ["maria", "program", "nvdaxMint", "usdcMint"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (admin)" }] }, + { + type: "create", id: "market", + lines: [ + field("admin: Maria"), + field("underlying_mint: NVDAx"), + field("quote_mint: USDC"), + field("underlying_owed: 0 NVDAx"), + field("quote_owed: 0 USDC"), + field("fees_owed: 0 USDC"), + field("fee_bps: 100"), + ], + }, + { type: "create", id: "underlyingVault", lines: [balance("0 NVDAx"), note("authority: the market")] }, + { type: "create", id: "quoteVault", lines: [balance("0 USDC"), note("authority: the market")] }, + ], + }, + + // ---- The call + { + title: "Alice runs [write_option()] for a call", + caption: + "Alice calls write_option(): a call on 5 NVDAx, a strike amount of 900 USDC, a premium of 25 USDC, " + + "and an expiry one week out. The handler writes the option as Listed, for sale, with no holder.", + actions: [ + { type: "call", handler: "write_option()", focus: ["alice", "aliceNvdax", "program", "market", "underlyingVault"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (writer)" }] }, + { type: "create", id: "option", lines: optionLines({ id: 1, writer: "Alice", kind: "Call", strike: 900, premium: 25 }) }, + ], + }, + { + title: "The market records what it will [owe]", + caption: + "Before any token moves, the market's underlying_owed rises by 5 NVDAx, and check_custody() confirms " + + "the underlying vault will still cover everything the market owes.", + actions: [{ type: "set", changes: [{ id: "market", key: "underlying_owed", value: "5 NVDAx" }] }], + }, + { + title: "Alice's 5 NVDAx move into the [vault]", + caption: + "Alice's 5 NVDAx move into the underlying vault: her collateral. The call is covered, since everything a " + + "holder could claim is already in the vault, so nobody ever has to chase Alice to deliver.", + actions: [ + transfer("aliceNvdax", "0 NVDAx", "underlyingVault", "5 NVDAx", { + id: "write", d: downLane(A.aliceNvdax, 20, underlyingVault, 26), coinAt: 0.7, + label: ["write_option()", "5 NVDAx"], + labelAt: { dx: 0, dy: -24, anchor: "middle" }, + }), + ], + }, + { + title: "Bob runs [buy_option()]", + caption: + "Bob thinks NVIDIA will pass $180 this week, and has 1,000 USDC. He calls buy_option() with the terms he " + + "read, and the handler refuses if the option is no longer Listed, has expired, or has changed terms.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc"], + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "buy_option()", focus: ["bob", "bobUsdc", "aliceUsdc", "option", "program", "market", "quoteVault"] }, + ], + }, + { + title: "The option records its [holder]", + caption: + "Before a token moves, the handler records Bob as the holder and the option as Held, sold, and adds Maria's " + + "1% fee, 0.25 USDC, to fees_owed.", + actions: [ + { + type: "set", + changes: [ + { id: "bob", title: "Bob (holder)" }, + { id: "option", key: "holder", value: "Bob" }, + { id: "option", key: "status", value: "Held" }, + { id: "market", key: "fees_owed", value: "0.25 USDC" }, + ], + }, + ], + }, + { + title: "Bob pays Alice the [premium]", + caption: "24.75 USDC goes straight from Bob to Alice. It is hers from this moment, whatever Bob does later.", + actions: [ + transfer("bobUsdc", "975.25 USDC", "aliceUsdc", "1,024.75 USDC", { + id: "premium", d: premium(A.bobUsdc, A.aliceUsdc), coinAt: 0.4, + label: ["1. buy_option()", "24.75 USDC"], + labelAt: { dx: 14, dy: -2 }, + }), + ], + }, + { + key: "callBought", + title: "Bob pays Maria's [fee]", + caption: + "Maria's 0.25 USDC fee goes into the quote vault. The 5 NVDAx do not move: Bob's downside is fixed at " + + "the 25 USDC he paid, and Alice's upside is capped at $180 a share until the week is out.", + actions: [ + transfer("bobUsdc", "975 USDC", "quoteVault", "0.25 USDC", { + id: "fee", d: across(A.bobUsdc, 20, quoteVault, 26), coinAt: 0.5, + label: ["2. Maria's fee · 0.25 USDC"], + labelAt: { dx: -14, dy: 4, anchor: "end" }, + }), + ], + }, + + // ---- The call is exercised + { + title: "Bob runs [exercise_option()]", + caption: + "NVDAx moves to $200: the option is in the money, worth exercising. It is American, so Bob may exercise at " + + "any moment before expiry; a European option would wait for expiry. His NVDAx account is created at his expense.", + actions: [ + { type: "call", handler: "exercise_option()", focus: ["bob", "bobUsdc", "program", "option", "market", "underlyingVault", "quoteVault"] }, + { type: "create", id: "bobNvdax", lines: [balance("0 NVDAx")] }, + ], + }, + { + title: "The ledger moves [before] the tokens", + caption: + "The option becomes Exercised. underlying_owed falls by 5 NVDAx, collateral no longer owed to anyone, " + + "and quote_owed rises by 900 USDC, the strike now owed to Alice.", + actions: [ + { + type: "set", + changes: [ + { id: "option", key: "status", value: "Exercised" }, + { id: "market", key: "underlying_owed", value: "0 NVDAx" }, + { id: "market", key: "quote_owed", value: "900 USDC" }, + ], + }, + ], + }, + { + title: "Bob pays the [strike]", + caption: + "Bob pays the strike, 5 times 180 USDC, into the quote vault. This is physical settlement: the tokens " + + "themselves change hands, so the program never reads a price. Cash settlement would need a price feed.", + actions: [ + transfer("bobUsdc", "75 USDC", "quoteVault", "900.25 USDC", { + id: "strike", d: across(A.bobUsdc, 20, quoteVault, 26), coinAt: 0.5, + label: ["1. exercise_option() · 900 USDC"], + labelAt: { dx: -14, dy: 4, anchor: "end" }, + }), + ], + }, + { + key: "callExercised", + title: "Bob [receives] the shares", + caption: + "The underlying vault pays Bob the 5 NVDAx, worth $1,000 at $200. He spent 925 USDC to get them: " + + "25 of premium and 900 of strike.", + actions: [ + transfer("underlyingVault", "0 NVDAx", "bobNvdax", "5 NVDAx", { + id: "shares", d: back(underlyingVault, 26, A.bobNvdax, 20), coinAt: 0.3, + label: ["2. Bob receives 5 NVDAx"], + labelAt: { dx: 0, dy: 20, anchor: "middle" }, + }), + ], + }, + + // ---- Another future: the call expires + { + from: "callBought", + title: "Alice runs [reclaim_collateral()]", + caption: + "At $165 the option is out of the money: Bob would not pay 900 for shares the market sells " + + "for 825, so he lets it expire. Then Alice calls reclaim_collateral(), and underlying_owed falls by 5 NVDAx.", + actions: [ + { type: "call", handler: "reclaim_collateral()", focus: ["alice", "aliceNvdax", "program", "option", "market", "underlyingVault"] }, + { type: "set", changes: [{ id: "market", key: "underlying_owed", value: "0 NVDAx" }] }, + ], + }, + { + title: "Alice [keeps] her shares", + caption: + "Alice's 5 NVDAx come back and the option closes, its rent returned to her. Bob's 25 USDC bought a right " + + "he never used; Alice keeps 24.75 of it and her shares.", + actions: [ + transfer("underlyingVault", "0 NVDAx", "aliceNvdax", "5 NVDAx", { + id: "reclaimCall", d: upLane(underlyingVault, 26, A.aliceNvdax, 20), coinAt: 0.3, + label: ["reclaim_collateral() · 5 NVDAx"], + labelAt: { dx: 0, dy: 20, anchor: "middle" }, + }), + { type: "close", id: "option" }, + ], + }, + + // ---- The writer collects the strike + { + from: "callExercised", + title: "Alice runs [collect_proceeds()]", + caption: + "Alice calls collect_proceeds(), which only the writer may call, and only once " + + "the option is Exercised. quote_owed falls by the 900 USDC it held for her.", + actions: [ + { type: "call", handler: "collect_proceeds()", focus: ["alice", "aliceUsdc", "program", "option", "market", "quoteVault"] }, + { type: "set", changes: [{ id: "market", key: "quote_owed", value: "0 USDC" }] }, + ], + }, + { + title: "Alice is [paid], and the option closes", + caption: + "Alice sold her five NVDAx for 900 USDC and was paid 24.75 USDC for agreeing to. She holds 1,924.75 USDC, " + + "an effective $184.95 a share against the $200 they now trade at.", + actions: [ + transfer("quoteVault", "0.25 USDC", "aliceUsdc", "1,924.75 USDC", { + id: "proceeds", d: upLane(quoteVault, 26, A.aliceUsdc, 20), coinAt: 0.3, + label: ["collect_proceeds() · 900 USDC"], + labelAt: { dx: 0, dy: 20, anchor: "middle" }, + }), + { type: "close", id: "option" }, + ], + }, + + // ---- The put + { + title: "Carol runs [write_option()] for a put", + caption: + "Carol has 1,000 USDC and would buy NVDAx at $150. She calls write_option() for a put: 5 NVDAx, a strike " + + "amount of 750 USDC, a premium of 20 USDC. She has no NVDAx account, so the handler creates one.", + actions: [ + // Alice and Bob are done; Carol takes the writer's column. + { type: "hide", ids: ["alice", "aliceNvdax", "aliceUsdc", "bob", "bobUsdc", "bobNvdax"] }, + { + type: "show", + ids: ["carol", "carolUsdc"], + lines: { carol: [sol("1 SOL")], carolUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "write_option()", focus: ["carol", "carolUsdc", "program", "market", "quoteVault"] }, + { type: "set", changes: [{ id: "carol", title: "Carol (writer)" }] }, + { type: "create", id: "carolNvdax", lines: [balance("0 NVDAx")] }, + { type: "create", id: "putOption", lines: optionLines({ id: 2, writer: "Carol", kind: "Put", strike: 750, premium: 20 }) }, + ], + }, + { + title: "The market records what it will [owe]", + caption: + "A put writer's collateral is the strike amount, so quote_owed rises by 750 USDC before any token moves, " + + "and check_custody() confirms the quote vault will cover it.", + actions: [{ type: "set", changes: [{ id: "market", key: "quote_owed", value: "750 USDC" }] }], + }, + { + title: "Carol's 750 USDC move into the [vault]", + caption: + "The put is cash-secured: everything Dave could claim on exercise is already in custody. " + + "Of her 1,000 USDC, Carol has 250 left.", + actions: [ + transfer("carolUsdc", "250 USDC", "quoteVault", "750.25 USDC", { + id: "writePut", d: downLane(A.carolUsdc, 20, quoteVault, 26), coinAt: 0.7, + label: ["write_option()", "750 USDC"], + labelAt: { dx: 0, dy: -24, anchor: "middle" }, + }), + ], + }, + { + title: "Dave runs [buy_option()]", + caption: + "Dave holds five NVDAx and 1,000 USDC, and wants insurance against a fall below $150 this week. " + + "This is a protective put, meant like fire insurance to expire unused.", + actions: [ + { + type: "show", + ids: ["dave", "daveNvdax", "daveUsdc"], + lines: { dave: [sol("1 SOL")], daveNvdax: [balance("5 NVDAx")], daveUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "buy_option()", focus: ["dave", "daveUsdc", "carolUsdc", "putOption", "program", "market", "quoteVault"] }, + ], + }, + { + title: "The option records its [holder]", + caption: + "Before a token moves, the handler records Dave as the holder and the option as Held, and adds Maria's " + + "1% fee, 0.20 USDC, to fees_owed.", + actions: [ + { + type: "set", + changes: [ + { id: "dave", title: "Dave (holder)" }, + { id: "putOption", key: "holder", value: "Dave" }, + { id: "putOption", key: "status", value: "Held" }, + { id: "market", key: "fees_owed", value: "0.45 USDC" }, + ], + }, + ], + }, + { + title: "Dave pays Carol the [premium]", + caption: "19.80 USDC goes straight from Dave to Carol, hers whatever happens next.", + actions: [ + transfer("daveUsdc", "980.20 USDC", "carolUsdc", "269.80 USDC", { + id: "putPremium", d: acrossLane(A.daveUsdc, A.carolUsdc), coinAt: 0.5, + label: ["1. buy_option()", "19.80 USDC"], + labelAt: { dx: 6, dy: 36 }, + }), + ], + }, + { + key: "putBought", + title: "Dave pays Maria's [fee]", + caption: "Maria's 0.20 USDC fee goes into the quote vault, beside Carol's 750 USDC of collateral.", + actions: [ + transfer("daveUsdc", "980 USDC", "quoteVault", "750.45 USDC", { + id: "putFee", d: across(A.daveUsdc, 20, quoteVault, 26), coinAt: 0.5, + label: ["2. Maria's fee · 0.20 USDC"], + labelAt: { dx: -14, dy: 4, anchor: "end" }, + }), + ], + }, + + // ---- The put expires + { + title: "The put expires, and Carol runs [reclaim_collateral()]", + caption: + "The week passes with NVDAx above $150, and Dave does nothing. Once the expiry has passed, Carol calls " + + "reclaim_collateral(), and quote_owed falls by 750 USDC.", + actions: [ + { type: "call", handler: "reclaim_collateral()", focus: ["carol", "carolUsdc", "program", "putOption", "market", "quoteVault"] }, + { type: "set", changes: [{ id: "market", key: "quote_owed", value: "0 USDC" }] }, + ], + }, + { + key: "putReclaimed", + title: "Carol's 750 USDC come [back]", + caption: + "The option closes, its rent returned to Carol. Her return is the 19.80 USDC premium on a purchase that " + + "never happened. Dave's insurance cost him 20 USDC and paid nothing.", + actions: [ + transfer("quoteVault", "0.45 USDC", "carolUsdc", "1,019.80 USDC", { + id: "reclaimPut", d: upLane(quoteVault, 26, A.carolUsdc, 20), coinAt: 0.3, + label: ["reclaim_collateral() · 750 USDC"], + labelAt: { dx: 0, dy: 20, anchor: "middle" }, + }), + { type: "close", id: "putOption" }, + ], + }, + + // ---- Another future: the put is exercised + { + from: "putBought", + title: "Dave runs [exercise_option()]", + caption: + "Below $150, Dave exercises. The option becomes Exercised, quote_owed falls by the 750 USDC " + + "strike, and underlying_owed rises by the 5 NVDAx now owed to Carol.", + actions: [ + { type: "call", handler: "exercise_option()", focus: ["dave", "daveUsdc", "daveNvdax", "program", "putOption", "market", "underlyingVault", "quoteVault"] }, + { + type: "set", + changes: [ + { id: "putOption", key: "status", value: "Exercised" }, + { id: "market", key: "quote_owed", value: "0 USDC" }, + { id: "market", key: "underlying_owed", value: "5 NVDAx" }, + ], + }, + ], + }, + { + title: "The tokens [change hands]", + caption: + "Dave delivers his 5 NVDAx and takes 750 USDC. The shares wait in the vault for Carol, who bought at $150 " + + "what the market now sells for less.", + actions: [ + transfer("daveNvdax", "0 NVDAx", "underlyingVault", "5 NVDAx", { + id: "deliver", d: across(A.daveNvdax, 20, underlyingVault, 26), coinAt: 0.5, + label: ["1. exercise_option() · 5 NVDAx"], + labelAt: { dx: -14, dy: 4, anchor: "end" }, + }), + transfer("quoteVault", "0.45 USDC", "daveUsdc", "1,730 USDC", { + id: "putStrike", d: back(quoteVault, 26, A.daveUsdc, 20), coinAt: 0.3, + label: ["2. Dave receives 750 USDC"], + labelAt: { dx: 0, dy: 20, anchor: "middle" }, + }), + ], + }, + + // ---- The operator collects the fees + { + from: "putReclaimed", + title: "Maria runs [collect_fees()]", + caption: + "Maria calls collect_fees(), which zeroes fees_owed, 0.45 USDC across the two " + + "sales, before it pays her. It refuses to run with nothing to collect (NothingToCollect).", + actions: [ + { type: "show", ids: ["mariaUsdc"], lines: { mariaUsdc: [balance("1,000 USDC")] }, focus: "shown" }, + { type: "call", handler: "collect_fees()", focus: ["maria", "mariaUsdc", "program", "market", "quoteVault"] }, + { type: "set", changes: [{ id: "market", key: "fees_owed", value: "0 USDC" }] }, + ], + }, + { + title: "Maria is paid, and the vaults are [empty]", + caption: + "Every token that entered the vaults has left to the party it was owed to. Alice sold at her price, Bob " + + "gained $75 after the premium, Carol was paid to wait, Dave bought insurance he did not need, and Maria " + + "earned 1% of every premium.", + actions: [ + transfer("quoteVault", "0 USDC", "mariaUsdc", "1,000.45 USDC", { + id: "fees", d: toMaria(), coinAt: 0.35, + label: ["collect_fees() · 0.45 USDC"], + labelAt: { dx: 0, dy: 20, anchor: "middle" }, + }), + ], + }, + ]; + + window.OPTIONS_SCENE = { + title: "Options", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + // The caption sits in the open space beneath the people's columns. + caption: { x: 16, y: 520, w: 540, h: 100, fontSize: 13 }, + // How long autoplay holds each finished step, in ms. + hold: 3000, + program: "program", + // Drawing order: later accounts paint over earlier ones. + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/options/slides.js b/animations/options/slides.js new file mode 100644 index 00000000..359777bc --- /dev/null +++ b/animations/options/slides.js @@ -0,0 +1,193 @@ +// The Options talk: the slides around the scene's diagram steps. Diagram +// runs name the scene steps they show, by index, and together they show every +// step once, in order. + +(function () { + window.OPTIONS_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build an", "[options venue]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Options chapter", + items: [ + "How options work as a Solana program", + "Why a venue that holds everything up front never has to chase anyone", + "How a program records what it owes before it moves a token", + ], + }, + ], + }, + + // ---- Options trading, before any Solana: the deal, the terms, the endings. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:income", who: "Alice", + name: "Wants to be paid for [waiting]", + text: "She holds five NVDAx, a token that tracks a share of NVIDIA, trading at $165. " + + "She would be happy to sell at $180, and she would like to be paid while she waits.", + }, + { + tone: "lavender", icon: "tpl:bargain", who: "Bob", + name: "Wants to buy [below the market]", + text: "He thinks NVIDIA will pass $180 within the week, and he wants that upside for less than " + + "the $825 five shares would cost him.", + }, + ], + }, + { + type: "split", + heading: "An [option] gives both what they want", + sub: "The right, but not the obligation, to trade at a price fixed today", + cards: [ + { icon: "tpl:contract", name: "Bob pays Alice $25 now", text: "For the right to buy her five shares at $180, any time this week" }, + { icon: "tpl:price-rises", name: "If NVIDIA passes $180, Bob buys", text: "He pays $180 a share for shares the market prices higher, and Alice sells at the price she chose" }, + { icon: "tpl:expire", name: "If it doesn't, the option expires", text: "Bob loses the $25, and Alice keeps it as income on shares she still owns" }, + ], + }, + { + type: "grid", + tone: "lavender", + heading: "The [terms] of an option", + sub: "Every option names these", + cards: [ + { icon: "tpl:underlying", name: "Underlying", text: "The asset the option is about: NVIDIA shares" }, + { icon: "tpl:strike", name: "Strike", text: "The price the trade happens at: $180 a share" }, + { icon: "tpl:expiry", name: "Expiry", text: "When the right lapses: one week from now" }, + { icon: "tpl:premium", name: "Premium", text: "What the buyer pays for the right, once, up front: $25" }, + { icon: "tpl:writer", name: "Writer", text: "Creates the option, and must trade if the holder asks: Alice" }, + { icon: "tpl:holder", name: "Holder", text: "Buys the option, and may use the right it carries: Bob" }, + ], + }, + { + type: "numbered", + heading: "A sold option has [two endings]", + sub: "Where the price lands inside each ending decides how much each side made", + cards: [ + { name: "The holder exercises", text: "Before expiry, Bob uses the right: he pays $900 and takes Alice's five shares" }, + { name: "The option expires", text: "Bob lets the right lapse. Alice keeps the $25 premium, and her shares" }, + ], + }, + { + type: "chart", + heading: "The holder's loss is capped at the [premium]", + sub: "Profit at expiry for each side of Alice and Bob's option. Bob profits past $185: the strike plus the premium", + // The prices and results of the chapter's payoff figure: $160, $180, + // $185 and $200, with +-25, +-25, 0 and -+75. + x: [160, 200], xStep: 5, + y: [-100, 100], yStep: 25, + xLabel: "NVIDIA's price at expiry", + yLabel: "Profit, five shares ($)", + marks: [{ at: 165, label: "TODAY $165" }, { at: 180, label: "STRIKE $180" }], + series: [ + { tone: "green", label: "Bob, the holder: loses at most $25", points: [[160, -25], [180, -25], [185, 0], [200, 75]], labelAt: [160.5, -45] }, + { tone: "purple", label: "Alice, the writer: earns at most $25", points: [[160, 25], [180, 25], [185, 0], [200, -75]], labelAt: [160.5, 40] }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, her accounts, and the deal she wants. + { type: "diagram", from: 0, to: 6 }, + // The venue opens, and the call is written, bought, exercised, and paid out. + { type: "diagram", from: 7, to: 7 }, + // "Call" is first needed here: the next step writes one. + { + type: "statement", + heading: "Alice's option is a [call]", + sub: "The right to buy the underlying at the strike, worth using when the price rises above it", + }, + { type: "diagram", from: 8, to: 14 }, + { + type: "statement", + heading: "Outcome 1: NVDAx [moves] to $200, and Bob exercises", + }, + { type: "diagram", from: 15, to: 18 }, + { + type: "statement", + heading: "Outcome 2: NVDAx [stays] at $165", + }, + { type: "diagram", from: 19, to: 20 }, + { + type: "statement", + heading: "Back to Outcome 1: Alice [collects] the strike", + }, + { type: "diagram", from: 21, to: 22 }, + { + type: "statement", + heading: "Now a [put]: the right to sell", + sub: "Worth using when the price falls below the strike: insurance for an owner. " + + "A put writer posts cash instead of shares, and the holder delivers the shares if they exercise", + }, + + // The put is written, bought, and expires; the fees are collected. + { type: "diagram", from: 23, to: 29 }, + { + type: "statement", + heading: "Outcome 1: the put [expires] unused", + }, + { type: "diagram", from: 30, to: 31 }, + { + type: "statement", + heading: "Outcome 2: NVDAx [falls] below $150", + }, + { type: "diagram", from: 32, to: 33 }, + { + type: "statement", + heading: "Back to Outcome 1: Maria [collects] the fees", + }, + { type: "diagram", from: 34, to: 35 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:premium", name: "Alice", text: "Earned a premium and sold her shares at her price" }, + { tone: "lavender", icon: "tpl:price-rises", name: "Bob", text: "Bought five NVDAx at $180 against a $200 market: $75 ahead after the premium" }, + { tone: "mint", icon: "tpl:expire", name: "Carol", text: "Was paid 19.80 USDC to wait for a purchase that never came" }, + { tone: "white", icon: "tpl:insurance", name: "Dave", text: "Paid 20 USDC for insurance he did not need" }, + { tone: "lavender", icon: "tpl:venue", name: "Maria the venue operator", text: "Earned 1% of every premium" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/order-book/index.html b/animations/order-book/index.html new file mode 100644 index 00000000..9c994802 --- /dev/null +++ b/animations/order-book/index.html @@ -0,0 +1,50 @@ + + + + + +Order Book Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/order-book/scene.js b/animations/order-book/scene.js new file mode 100644 index 00000000..29511046 --- /dev/null +++ b/animations/order-book/scene.js @@ -0,0 +1,554 @@ +// The Order Book Exchange chapter as an animated scene: Maria opens an +// NVDAx/USDC market, Alice rests an ask, Bob rests a bid below it, Carol's +// ask crosses and fills against Bob's bid, Bob cancels the rest, Bob and +// Carol settle, Maria withdraws the fee, and the finished accounts close. +// +// The columns are the chapter figures' accounts spread across a 16:9 screen. +// The order book is created from a key pair, so its dot sits on the curve. +// Arrows run down the lanes between columns and along a corridor beneath +// them, one transfer on screen at a time. The steps follow the handlers in +// quicknode/solana-program-examples finance/order-book: place_order() takes +// the order's tokens before it matches, credits unsettled balances for each +// fill, moves the fee in one transfer at the end, and rests the remainder. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, drop: 60, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + const GAP3 = 37; + + // Columns, left to right, with a lane after each person's for arrows. + const COLUMN = { + maria: [10, 120], + alice: [146, 148], + bob: [312, 148], + carol: [478, 148], + book: [652, 196], + program: [872, 236], + }; + + const ata = (owner, token, x, y, w) => + derived("token", `${owner}'s ${token}`, x, y, w, [`${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", `${token.toUpperCase()} MINT`]); + const marketUser = (owner, x, y, w) => + derived("struct", `${owner}'s market user`, x, y, w, ['"MARKET_USER" +', "MARKET ADDRESS +", `${owner.toUpperCase()}'S ADDRESS`]); + // The seed is the order book's next_order_id when the order is placed: 1, 2 and 3. + const order = (owner, id, x, y, w) => derived("struct", `${owner}'s order`, x, y, w, ['"ORDER" +', "MARKET ADDRESS +", `ORDER ID ${id}`]); + + // Each person's column: wallet, token accounts, market user, order. + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const carol = onCurve("wallet", "Carol", ...COLUMN.carol); + const below = (y, h) => y + h + GAP3; + + const aliceNvdax = ata("Alice", "NVDAx", COLUMN.alice[0], below(alice.y, 40), COLUMN.alice[1]); + const aliceUser = marketUser("Alice", COLUMN.alice[0], below(aliceNvdax.y, 40), COLUMN.alice[1]); + const aliceOrder = order("Alice", 1, COLUMN.alice[0], below(aliceUser.y, tall(3)), COLUMN.alice[1]); + + const bobUsdc = ata("Bob", "USDC", COLUMN.bob[0], below(bob.y, 40), COLUMN.bob[1]); + const bobNvdax = ata("Bob", "NVDAx", COLUMN.bob[0], below(bobUsdc.y, 40), COLUMN.bob[1]); + const bobUser = marketUser("Bob", COLUMN.bob[0], below(bobNvdax.y, 40), COLUMN.bob[1]); + const bobOrder = order("Bob", 2, COLUMN.bob[0], below(bobUser.y, tall(3)), COLUMN.bob[1]); + + const carolNvdax = ata("Carol", "NVDAx", COLUMN.carol[0], below(carol.y, 40), COLUMN.carol[1]); + const carolUsdc = ata("Carol", "USDC", COLUMN.carol[0], below(carolNvdax.y, 40), COLUMN.carol[1]); + const carolUser = marketUser("Carol", COLUMN.carol[0], below(carolUsdc.y, 40), COLUMN.carol[1]); + const carolOrder = order("Carol", 3, COLUMN.carol[0], below(carolUser.y, tall(3)), COLUMN.carol[1]); + + const mariaUsdc = ata("Maria", "USDC", COLUMN.maria[0], below(maria.y, 40), COLUMN.maria[1]); + + // The order book: a public key, created from a key pair by Maria's client. + const orderBook = onCurve("struct", "order book", ...COLUMN.book); + + // The program, the market and its three vaults. + const program = onCurve("program", "order-book program", ...COLUMN.program); + const P = COLUMN.program; + const market = derived("struct", "market", P[0], program.y + 130 + GAP2, P[1], ['"MARKET" + NVDAX MINT +', "USDC MINT ADDRESS"]); + const baseVault = derived("token", "base vault", P[0], market.y + tall(5) + GAP2, P[1], ['"BASE_VAULT" +', "MARKET ADDRESS"]); + const quoteVault = derived("token", "quote vault", P[0], baseVault.y + tall(2) + GAP2, P[1], ['"QUOTE_VAULT" +', "MARKET ADDRESS"]); + const feeVault = derived("token", "fee vault", P[0], quoteVault.y + tall(2) + GAP2, P[1], ['"FEE_VAULT" +', "MARKET ADDRESS"]); + + const accounts = { + maria, mariaUsdc, + alice, aliceNvdax, aliceUser, aliceOrder, + bob, bobUsdc, bobNvdax, bobUser, bobOrder, + carol, carolNvdax, carolUsdc, carolUser, carolOrder, + orderBook, + program, market, baseVault, quoteVault, feeVault, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // Lanes run down the gap after each person's column; the corridor runs + // beneath every column; the vault lane runs down beside the program column. + + const LANE = { maria: 137, alice: 303, bob: 469, carol: 639, vaults: 860, fees: 856 }; + const CORRIDOR = 518; + const right = (acc, dy = 20) => [acc.x + acc.w + 2, acc.y + dy]; + const left = (acc, dy = 26) => [acc.x - 2, acc.y + dy]; + + function intoVault(from, lane, to) { + const [sx, sy] = right(from); + const [ex, ey] = left(to); + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [LANE.vaults, CORRIDOR], [LANE.vaults, ey], [ex, ey]]); + } + + function outOfVault(from, lane, to) { + const [sx, sy] = left(from); + const [ex, ey] = right(to); + return rounded([[sx, sy], [LANE.vaults, sy], [LANE.vaults, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + } + + const feeLoop = (() => { + const [sx, sy] = left(quoteVault, 20); + const [ex, ey] = left(feeVault, 26); + return rounded([[sx, sy], [LANE.fees, sy], [LANE.fees, ey], [ex, ey]]); + })(); + + // Coins on the corridor sit beneath the order book's column, which is + // empty below the book, with their labels above them. + const onCorridor = { x: 750, y: CORRIDOR }; + const above = { dx: 0, dy: -10, anchor: "middle" }; + const above2 = { dx: 0, dy: -23, anchor: "middle" }; + const leftOf = { dx: -14, dy: 4, anchor: "end" }; + + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + alone: true, + from: { id: from, value: fromValue }, + to: { id: to, value: toValue }, + arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + const vault = (amount) => [balance(amount), note("authority: the market")]; + const userLines = () => [field("unsettled_base: 0"), field("unsettled_quote: 0"), field("open_orders: [ ]")]; + const orderLines = (side, price, quantity) => [ + field(`side: ${side}`), + field(`price: ${price}`), + field(`original_quantity: ${quantity}`), + field("filled_quantity: 0"), + field("status: Open"), + ]; + + const HANDLERS = [ + "initialize_market()", + "initialize_market_user()", + "place_order()", + "cancel_order()", + "settle_funds()", + "close_order()", + "close_market_user()", + "withdraw_fees()", + "pause_market()", + "resume_market()", + ]; + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Alice owns ten shares of [NVIDIA]", + caption: + "NVDAx is a token that tracks one share of NVIDIA stock. Alice keeps hers in a token account, whose address " + + "is worked out from the three names above it. Every kind of token is defined by a mint, one of those names.", + actions: [{ type: "show", ids: ["aliceNvdax"], lines: { aliceNvdax: [balance("10 NVDAx")] }, focus: "all" }], + }, + { + title: "Alice wants to [sell]", + caption: + "Alice wants to post an ask: sell her ten NVDAx at $265 or more. Nobody is bidding that yet, " + + "so her order has to wait on a book until somebody is.", + actions: [{ type: "focus", ids: ["alice", "aliceNvdax"] }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs an exchange, and each line is an instruction " + + "handler anyone can call by sending a transaction. First, somebody has to open a market.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + + // ---- The market opens + { + title: "Maria runs [initialize_market()]", + caption: + "Maria runs the exchange for a 0.25% fee on every trade, 25 basis points. The order book is too big for a " + + "program to create, so her client makes it from a key pair: its address is a public key, on the curve.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_market()", focus: ["maria", "program"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (authority)" }] }, + { type: "create", id: "orderBook", lines: [field("next_order_id: 1"), field("bids_root: empty"), field("asks_root: empty")] }, + { + type: "create", id: "market", + lines: [ + field("authority: Maria"), + field("base_mint: NVDAx"), + field("quote_mint: USDC"), + field("fee_basis_points: 25"), + field("is_active: true"), + ], + }, + ], + }, + { + title: "The market gets three [vaults]", + caption: + "Vaults are token accounts the program controls: NVDAx, the base token, waits in the base vault, and USDC, " + + "the quote token prices are stated in, in the quote vault. Maria's fees get a vault of their own.", + actions: [ + { type: "create", id: "baseVault", lines: vault("0 NVDAx") }, + { type: "create", id: "quoteVault", lines: vault("0 USDC") }, + { type: "create", id: "feeVault", lines: vault("0 USDC") }, + ], + }, + + // ---- Alice's ask + { + title: "Alice runs [initialize_market_user()]", + caption: + "Her market user account will record what the exchange owes her, as unsettled balances, " + + "and lists her open orders: at most 20.", + actions: [ + { type: "call", handler: "initialize_market_user()", focus: ["alice", "program", "market"] }, + { type: "create", id: "aliceUser", lines: userLines() }, + ], + }, + { + title: "Alice runs [place_order()]", + caption: + "An ask: ten NVDAx at 265. The handler checks the market is open and the order is big enough, " + + "and that Alice has fewer than 20 open orders. Each order gets an account of its own.", + actions: [ + { type: "call", handler: "place_order()", focus: ["alice", "aliceNvdax", "aliceUser", "program", "market", "orderBook", "baseVault"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (seller)" }] }, + { type: "create", id: "aliceOrder", lines: orderLines("Ask", 265, 10) }, + ], + }, + { + title: "Alice's 10 NVDAx move into the [base vault]", + caption: + "The tokens move before anything else happens, so every order on the book is backed by tokens in a vault. " + + "An ask pays in shares; a bid would pay in USDC.", + actions: [ + transfer("aliceNvdax", "0 NVDAx", "baseVault", "10 NVDAx", { + id: "aliceAsk", d: intoVault(A.aliceNvdax, LANE.alice, baseVault), + coinNear: onCorridor, label: ["place_order()", "10 NVDAx"], labelAt: above2, + }), + ], + }, + { + title: "Alice's ask [rests] on the book", + caption: + "Nobody bids 265, so there is nothing to match. Her order waits in the order book's ask tree: a resting order. " + + "Placing it cost her no exchange fee: fees only apply to trades.", + actions: [ + { + type: "set", + changes: [ + { id: "orderBook", key: "asks_root", value: "Alice's ask, 10 @ 265" }, + { id: "orderBook", key: "next_order_id", value: "2" }, + { id: "aliceUser", key: "open_orders", value: "[1]" }, + ], + }, + ], + }, + + // ---- Bob's bid + { + title: "Bob runs [initialize_market_user()]", + caption: "Bob wants to buy NVDAx, but won't pay more than $250. He has 1,000 USDC, and opens his market user account.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc"], + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "initialize_market_user()", focus: ["bob", "bobUsdc", "program", "market"] }, + { type: "create", id: "bobUser", lines: userLines() }, + ], + }, + { + title: "Bob runs [place_order()]", + caption: "A bid: four NVDAx at 250. A bid pays in the quote token, price times quantity: 4 × 250 = 1,000 USDC.", + actions: [ + { type: "call", handler: "place_order()", focus: ["bob", "bobUsdc", "bobUser", "program", "market", "orderBook", "quoteVault"] }, + { type: "set", changes: [{ id: "bob", title: "Bob (buyer)" }] }, + { type: "create", id: "bobOrder", lines: orderLines("Bid", 250, 4) }, + ], + }, + { + title: "Bob's 1,000 USDC move into the [quote vault]", + caption: "Every dollar he has, committed the moment the order is placed.", + actions: [ + transfer("bobUsdc", "0 USDC", "quoteVault", "1,000 USDC", { + id: "bobBid", d: intoVault(A.bobUsdc, LANE.bob, quoteVault), + coinNear: onCorridor, label: ["place_order()", "1,000 USDC"], labelAt: above2, + }), + ], + }, + { + key: "spread", + title: "Bob's bid rests, and the book has a [spread]", + caption: + "Bob's 250 doesn't reach Alice's 265, so his bid waits in the bid tree. The book now shows bid 250, " + + "ask 265: a $15 spread. None of it goes to Maria; her only revenue is the fee.", + actions: [ + { + type: "set", + changes: [ + { id: "orderBook", key: "bids_root", value: "Bob's bid, 4 @ 250" }, + { id: "orderBook", key: "next_order_id", value: "3" }, + { id: "bobUser", key: "open_orders", value: "[2]" }, + ], + }, + ], + }, + + // ---- Carol's crossing ask + { + title: "Carol runs [initialize_market_user()]", + caption: "Carol owns three NVDAx and wants out now, so she'll take whatever the best bid is, down to $245.", + actions: [ + { + type: "show", + ids: ["carol", "carolNvdax", "carolUsdc"], + lines: { carol: [sol("1 SOL")], carolNvdax: [balance("3 NVDAx")], carolUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "initialize_market_user()", focus: ["carol", "carolNvdax", "program", "market"] }, + { type: "create", id: "carolUser", lines: userLines() }, + ], + }, + { + title: "Carol runs [place_order()], and it crosses", + caption: + "An ask: three NVDAx at 245, at or below Bob's 250, so it crosses. The handler walks the bids best price first, " + + "and checks that the accounts Carol passed for Bob's order match the ones it found.", + actions: [ + { type: "call", handler: "place_order()", focus: ["carol", "carolNvdax", "carolUser", "bobUser", "bobOrder", "program", "market", "orderBook", "baseVault"] }, + { type: "set", changes: [{ id: "carol", title: "Carol (seller)" }] }, + { type: "create", id: "carolOrder", lines: orderLines("Ask", 245, 3) }, + ], + }, + { + title: "Carol's 3 NVDAx move into the [base vault]", + caption: "Even an order that trades at once pays its tokens in first.", + actions: [ + transfer("carolNvdax", "0 NVDAx", "baseVault", "13 NVDAx", { + id: "carolAsk", d: intoVault(A.carolNvdax, LANE.carol, baseVault), + coinNear: onCorridor, label: ["place_order()", "3 NVDAx"], labelAt: above2, + }), + ], + }, + { + title: "Carol's ask [fills] Bob's bid at 250", + caption: + "Three shares at Bob's price, 750 USDC. Carol receives the USDC, so she pays the 1.875 fee: she's owed 748.125, " + + "and Bob three shares. Unsettled balances are just numbers; tokens move when each settles.", + actions: [ + { + type: "set", + changes: [ + { id: "carolUser", key: "unsettled_quote", value: "748.125" }, + { id: "bobUser", key: "unsettled_base", value: "3" }, + { id: "bobOrder", key: "filled_quantity", value: "3" }, + { id: "bobOrder", key: "status", value: "PartiallyFilled" }, + { id: "orderBook", key: "bids_root", value: "Bob's bid, 1 @ 250" }, + { id: "orderBook", key: "next_order_id", value: "4" }, + { id: "carolOrder", key: "filled_quantity", value: "3" }, + { id: "carolOrder", key: "status", value: "Filled" }, + ], + }, + ], + }, + { + key: "filled", + title: "Maria's [fee] moves to the fee vault", + caption: + "The fees of every fill in the order move in one transfer at the end, so they never mix with what traders are owed. " + + "Bob signed nothing for this fill: a maker signs once, when placing.", + actions: [ + transfer("quoteVault", "998.125 USDC", "feeVault", "1.875 USDC", { + id: "fee", d: feeLoop, coinNear: { x: LANE.fees, y: (quoteVault.y + feeVault.y) / 2 + 20 }, + label: ["1.875 USDC"], labelAt: leftOf, + }), + ], + }, + + // ---- Bob cancels + { + title: "Bob runs [cancel_order()]", + caption: + "Three shares is enough for Bob. His last share at 250 means 250 USDC of his is still in the quote vault, " + + "so the exchange now owes it back to him. His order leaves the book, Cancelled.", + actions: [ + { type: "call", handler: "cancel_order()", focus: ["bob", "bobUser", "bobOrder", "program", "market", "orderBook"] }, + { + type: "set", + changes: [ + { id: "bobUser", key: "unsettled_quote", value: "250" }, + { id: "bobUser", key: "open_orders", value: "[ ]" }, + { id: "orderBook", key: "bids_root", value: "empty" }, + { id: "bobOrder", key: "status", value: "Cancelled" }, + ], + }, + ], + }, + + // ---- Settlement + { + title: "Bob runs [settle_funds()]", + caption: + "Settling turns his claims into tokens. The handler copies what he's owed and zeroes the counters first, " + + "so calling it twice pays nothing. His NVDAx account receives the shares.", + actions: [ + { type: "show", ids: ["bobNvdax"], lines: { bobNvdax: [balance("0 NVDAx")] }, focus: "shown" }, + { type: "call", handler: "settle_funds()", focus: ["bob", "bobUsdc", "bobNvdax", "bobUser", "program", "market", "baseVault", "quoteVault"] }, + { + type: "set", + changes: [ + { id: "bobUser", key: "unsettled_base", value: "0" }, + { id: "bobUser", key: "unsettled_quote", value: "0" }, + ], + }, + ], + }, + { + title: "Bob receives 3 [NVDAx]", + caption: "The market's PDA signs for the vault: only the program's own handlers can move these tokens.", + actions: [ + transfer("baseVault", "10 NVDAx", "bobNvdax", "3 NVDAx", { + id: "bobShares", d: outOfVault(baseVault, LANE.bob, A.bobNvdax), + coinNear: onCorridor, label: ["settle_funds()", "3 NVDAx"], labelAt: above2, + }), + ], + }, + { + title: "Bob's 250 USDC come [back]", + caption: "Bob paid 750 USDC for three NVDAx, $250 a share, exactly his limit.", + actions: [ + transfer("quoteVault", "748.125 USDC", "bobUsdc", "250 USDC", { + id: "bobRefund", d: outOfVault(quoteVault, LANE.bob, A.bobUsdc), + coinNear: onCorridor, label: ["250 USDC"], labelAt: above, + }), + ], + }, + { + title: "Carol runs [settle_funds()]", + caption: "Her counter is copied and zeroed the same way.", + actions: [ + { type: "call", handler: "settle_funds()", focus: ["carol", "carolUsdc", "carolUser", "program", "market", "quoteVault"] }, + { type: "set", changes: [{ id: "carolUser", key: "unsettled_quote", value: "0" }] }, + ], + }, + { + title: "Carol receives 748.125 [USDC]", + caption: "She asked 245 a share and got Bob's 250: any difference always favours the taker. The quote vault is empty.", + actions: [ + transfer("quoteVault", "0 USDC", "carolUsdc", "1,748.125 USDC", { + id: "carolPaid", d: outOfVault(quoteVault, LANE.carol, A.carolUsdc), + coinNear: onCorridor, label: ["settle_funds()", "748.125 USDC"], labelAt: above2, + }), + ], + }, + + // ---- Fees + { + title: "Maria runs [withdraw_fees()]", + caption: + "Only the market's authority may, and the whole fee vault goes to her token account. With nothing to withdraw " + + "it succeeds and does nothing, so Maria can run it on a schedule.", + actions: [ + { type: "show", ids: ["mariaUsdc"], lines: { mariaUsdc: [balance("1,000 USDC")] }, focus: "shown" }, + { type: "call", handler: "withdraw_fees()", focus: ["maria", "mariaUsdc", "program", "market", "feeVault"] }, + transfer("feeVault", "0 USDC", "mariaUsdc", "1,001.875 USDC", { + id: "fees", d: outOfVault(feeVault, LANE.maria, A.mariaUsdc), + coinNear: onCorridor, label: ["withdraw_fees()", "1.875 USDC"], labelAt: above2, + }), + ], + }, + + // ---- Closing + { + title: "Bob and Carol run [close_order()]", + caption: "A Filled or Cancelled order holds nothing the book still needs, so its owner closes it and gets its rent back.", + actions: [ + { type: "call", handler: "close_order()", focus: ["bob", "carol", "bobOrder", "carolOrder", "program"] }, + { type: "close", id: "bobOrder" }, + { type: "close", id: "carolOrder" }, + ], + }, + { + title: "Bob and Carol run [close_market_user()]", + caption: + "With no open orders and nothing owed, their market user accounts close too. Alice's ask still rests at 265, " + + "so her accounts stay open, waiting for a buyer.", + actions: [ + { type: "call", handler: "close_market_user()", focus: ["bob", "carol", "bobUser", "carolUser", "program", "aliceUser", "aliceOrder", "orderBook"] }, + { type: "close", id: "bobUser" }, + { type: "close", id: "carolUser" }, + ], + }, + ]; + + window.ORDERBOOK_SCENE = { + title: "Order Book Exchange", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 536, w: 540, h: 94, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/order-book/slides.js b/animations/order-book/slides.js new file mode 100644 index 00000000..b2ad5919 --- /dev/null +++ b/animations/order-book/slides.js @@ -0,0 +1,130 @@ +// The Order Book talk: the slides around the scene's diagram steps. Diagram +// runs name the scene steps they show, by index, and together they show every +// step once, in order. Each term is defined where the talk first needs it. + +(function () { + window.ORDERBOOK_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build an", "[order book exchange]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Order Book Exchange chapter", + items: [ + "How an exchange like NASDAQ works as a Solana program", + "Why every order on the book is backed by tokens in a vault", + "How the exchange records what it owes, and pays it out later", + ], + }, + ], + }, + + // ---- What people want, and how an order book gives it to them. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:orderbook-ask", who: "Alice", + name: "Wants to sell at [her price]", + text: "She owns ten NVIDIA shares and thinks AI is overhyped. She wants out, " + + "but not at any price: $265 a share or more.", + }, + { + tone: "lavender", icon: "tpl:orderbook-bid", who: "Bob", + name: "Wants to buy at [his price]", + text: "He wants in, but he isn't prepared to pay more than $250 a share.", + }, + ], + }, + { + type: "split", + heading: "An [order book] lets both wait for their price", + sub: "The way NYSE and NASDAQ work", + cards: [ + { icon: "tpl:orderbook-ask", name: "Alice posts her price", text: "Sell ten shares at $265 or more" }, + { icon: "tpl:orderbook-bid", name: "Bob posts his", text: "Buy four shares at $250 or less" }, + { icon: "tpl:orderbook-book", name: "Both wait in the book", text: "until somebody arrives willing to take one of those prices" }, + ], + }, + { + type: "grid", + tone: "lavender", + heading: "The [terms] of an order book", + sub: "Every exchange uses these", + cards: [ + { icon: "tpl:orderbook-limit", name: "Limit order", text: "An order with a price its owner refuses to cross" }, + { icon: "tpl:orderbook-bid", name: "Bid", text: "Buy, but only at or below this price: Bob's $250" }, + { icon: "tpl:orderbook-ask", name: "Ask", text: "Sell, but only at or above this price: Alice's $265" }, + { icon: "tpl:orderbook-book", name: "Order book", text: "The bids and the asks, each sorted best price first" }, + { icon: "tpl:orderbook-spread", name: "Spread", text: "The gap between the best bid and the best ask: $15" }, + { icon: "tpl:orderbook-cross", name: "Crossing", text: "An order whose limit reaches across the spread trades at once" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, the market, Alice's ask, Bob's bid, and Carol's ask arriving. + { type: "diagram", from: 0, to: 17 }, + { + type: "numbered", + heading: "How a [fill] works", + sub: "Carol's ask crosses Bob's bid", + cards: [ + { name: "Maker and taker", text: "Bob's resting order is the maker; Carol's arriving order is the taker" }, + { name: "The maker's price", text: "The fill happens at the price on the book, 250, not Carol's 245" }, + { name: "The fee", text: "Whoever receives the USDC pays Maria's 0.25%: here, Carol" }, + ], + }, + // The fill, the cancel, settlement, the fee, and closing up. + { type: "diagram", from: 18, to: 28 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:orderbook-ask", name: "Alice", text: "Her ask for ten shares at $265 still rests on the book, waiting for a buyer" }, + { tone: "lavender", icon: "tpl:orderbook-bid", name: "Bob", text: "Bought three NVDAx at $250, his limit, and got his unused 250 USDC back" }, + { tone: "mint", icon: "tpl:orderbook-cross", name: "Carol", text: "Sold three NVDAx right away, at $250 rather than the $245 she'd have taken" }, + { tone: "white", icon: "tpl:venue", name: "Maria the exchange operator", text: "Earned 1.875 USDC, 0.25% of the one fill" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/perpetual-futures/index.html b/animations/perpetual-futures/index.html new file mode 100644 index 00000000..798f5688 --- /dev/null +++ b/animations/perpetual-futures/index.html @@ -0,0 +1,50 @@ + + + + + +Perpetual Futures Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/perpetual-futures/scene.js b/animations/perpetual-futures/scene.js new file mode 100644 index 00000000..faa56d11 --- /dev/null +++ b/animations/perpetual-futures/scene.js @@ -0,0 +1,495 @@ +// The Perpetual Futures chapter as an animated scene: Maria creates a pool, +// Carol and eleven others fund it, Alice opens a 5x long and Bob a 5x short, +// NVDAx rallies, Dave liquidates Bob, Alice closes at $120, and Maria +// collects her fees. +// +// The columns are the chapter figures' accounts spread across a 16:9 screen: +// every public-key account hangs beneath the one curve, the oracle's price +// feed included. Arrows run down the gaps between columns and along a +// corridor beneath them, one transfer on screen at a time. The steps follow +// the handlers in quicknode/solana-program-examples finance/perpetual-futures: +// each records the pool's accounting before it moves a token, a liquidation +// pays the liquidator before the trader's refund, and add_liquidity() takes +// the deposit before it mints the shares. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, drop: 60, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + + // Columns, left to right; the 12-unit gaps between them are the lanes. + const COLUMN = { + alice: [12, 140], + bob: [164, 140], + carol: [316, 140], + dave: [468, 130], + maria: [610, 130], + oracle: [752, 120], + program: [884, 224], + }; + const laneAfter = (column) => COLUMN[column][0] + COLUMN[column][1] + 6; + + const ata = (owner, x, y, w) => + derived("token", `${owner}'s USDC`, x, y, w, [`${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", "USDC MINT"]); + const slot = (person, n) => person.y + 77 * n; + + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const carol = onCurve("wallet", "Carol", ...COLUMN.carol); + const dave = onCurve("wallet", "Dave", ...COLUMN.dave); + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const oracle = onCurve("struct", "oracle feed", ...COLUMN.oracle); + + const program = onCurve("program", "perps program", ...COLUMN.program); + const pool = derived("struct", "Pool", COLUMN.program[0], program.y + 110 + GAP2, COLUMN.program[1], ['"POOL" + COLLATERAL MINT +', "ORACLE FEED ADDRESS"]); + const vault = derived("token", "custody vault", COLUMN.program[0], pool.y + tall(6) + GAP2, COLUMN.program[1], ['"VAULT" +', "POOL'S ADDRESS"]); + const lpMint = derived("mint", "LP share mint", COLUMN.program[0], vault.y + tall(2) + GAP2, COLUMN.program[1], ['"LP_MINT" +', "POOL'S ADDRESS"]); + + const position = (owner, side, x, y, w) => + derived("struct", `${owner}'s ${side}`, x, y, w, ['"POSITION" + POOL +', `${owner.toUpperCase()}'S ADDRESS + "${side.toUpperCase()}"`]); + + const accounts = { + alice, + aliceUsdc: ata("Alice", COLUMN.alice[0], slot(alice, 1), COLUMN.alice[1]), + aliceLong: position("Alice", "long", COLUMN.alice[0], slot(alice, 2) - 8, COLUMN.alice[1]), + bob, + bobUsdc: ata("Bob", COLUMN.bob[0], slot(bob, 1), COLUMN.bob[1]), + bobShort: position("Bob", "short", COLUMN.bob[0], slot(bob, 2) - 8, COLUMN.bob[1]), + carol, + carolUsdc: ata("Carol", COLUMN.carol[0], slot(carol, 1), COLUMN.carol[1]), + carolShares: derived("token", "Carol's shares", COLUMN.carol[0], slot(carol, 2), COLUMN.carol[1], ["CAROL'S ADDRESS +", "TOKEN PROGRAM +", "LP SHARE MINT"]), + dave, + daveUsdc: ata("Dave", COLUMN.dave[0], slot(dave, 1), COLUMN.dave[1]), + maria, + mariaUsdc: ata("Maria", COLUMN.maria[0], slot(maria, 1), COLUMN.maria[1]), + oracle, + program, pool, vault, lpMint, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + // Out of an account's right edge, down the lane beside it, along the + // corridor beneath every column, and up the lane before the program column + // into the vault; or the reverse. + + const CORRIDOR = 452; + const PROGRAM_LANE = COLUMN.program[0] - 6; + const right = (acc, dy = 20) => [acc.x + acc.w + 2, acc.y + dy]; + const left = (acc, dy = 26) => [acc.x - 2, acc.y + dy]; + + function intoVault(from, lane) { + const [sx, sy] = right(from); + const [ex, ey] = left(vault); + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [PROGRAM_LANE, CORRIDOR], [PROGRAM_LANE, ey], [ex, ey]]); + } + + function outOfVault(lane, to) { + const [sx, sy] = left(vault, 34); + const [ex, ey] = right(to); + return rounded([[sx, sy], [PROGRAM_LANE, sy], [PROGRAM_LANE, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + } + + function minted(lane, to) { + const [sx, sy] = left(lpMint); + const [ex, ey] = right(to); + return rounded([[sx, sy], [PROGRAM_LANE, sy], [PROGRAM_LANE, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + } + + const below = { dx: 0, dy: 22, anchor: "middle" }; + + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + alone: true, + from: { id: from, value: fromValue }, + to: { id: to, value: toValue }, + arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + + const HANDLERS = [ + "initialize_pool()", + "add_liquidity()", + "remove_liquidity()", + "open_position()", + "close_position()", + "liquidate_position()", + "update_price_average()", + "collect_fees()", + ]; + + const positionLines = (collateral) => [ + field(`collateral: ${collateral}`), + field("size: 5,000"), + field("entry_price: $100"), + field("entry_funding: 0"), + ]; + + const changes = (id, pairs) => ({ + type: "set", + changes: Object.entries(pairs).map(([key, value]) => ({ id, key, value })), + }); + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "She keeps USDC, a token worth one US dollar, in a token account of her own. Every kind of token is " + + "defined by a mint, one of the three names its address is worked out from. It holds 1,000 USDC.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice wants to go [long] with leverage", + caption: + "Alice expects NVDAx, a token that tracks NVIDIA stock, to rise from $100. She wants a 5,000 USDC position " + + "backed by her 1,000 USDC: five times the exposure her money buys.", + actions: [{ type: "focus", ids: ["alice", "aliceUsdc"] }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs a perpetual futures venue, and each line is an " + + "instruction handler anyone can call by sending a transaction. First, the venue needs a price.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + { + title: "An oracle publishes the [price]", + caption: + "An oracle publishes NVDAx's price to an account, a price feed. Here a test program, mock-price-feed, " + + "stands in for a real oracle so the price can be moved. NVDAx is at $100.", + actions: [ + { + type: "show", + ids: ["oracle"], + lines: { oracle: [field("price: $100"), field("owner: mock-price-feed")] }, + focus: "shown", + }, + ], + }, + + // ---- The pool + { + title: "Maria runs [initialize_pool()]", + caption: + "Maria sets the market's rules once: the fees, the collateral every position needs, and the liquidation fee. " + + "No handler can change them later. Her income is a share of the fees, and she has no path to anyone's collateral.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_pool()", focus: ["maria", "program", "oracle"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (authority)" }] }, + { + type: "create", id: "pool", + lines: [ + field("liquidity: 0 USDC"), + field("total_collateral: 0"), + field("program_fees: 0"), + field("insurance_fund: 0"), + field("long_size: 0"), + field("short_size: 0"), + ], + }, + { type: "create", id: "vault", lines: [balance("0 USDC"), note("authority: the pool")] }, + { type: "create", id: "lpMint", lines: [note("mint authority: the pool")] }, + ], + }, + { + title: "Carol runs [add_liquidity()]", + caption: + "Carol is a liquidity provider, an LP. The LPs' pool is the other side of every trade: it pays the traders who win " + + "and keeps what the losers lose. The pool records her 1,000 USDC first, and her share account is created.", + actions: [ + { + type: "show", + ids: ["carol", "carolUsdc"], + lines: { carol: [sol("1 SOL")], carolUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "add_liquidity()", focus: ["carol", "carolUsdc", "program", "pool", "vault", "lpMint", "oracle"] }, + { type: "set", changes: [{ id: "carol", title: "Carol (LP)" }] }, + { type: "create", id: "carolShares", lines: [balance("0 LP")] }, + changes("pool", { liquidity: "1,000 USDC" }), + ], + }, + { + title: "Carol's 1,000 USDC go into the [vault]", + caption: "One vault holds everything: the LPs' liquidity, traders' collateral and fees. The Pool's fields record whose is whose.", + actions: [ + transfer("carolUsdc", "0 USDC", "vault", "1,000 USDC", { + id: "carolIn", d: intoVault(A.carolUsdc, laneAfter("carol")), + coinNear: { x: 650, y: CORRIDOR }, label: ["add_liquidity()", "1,000 USDC"], labelAt: below, + }), + ], + }, + { + // Derived: the LP mint has the collateral's 6 decimals, so 1,000 USDC less MINIMUM_LIQUIDITY's + // 1,000 minor units (the chapter's "tenth of a cent") is 999.999 shares. + title: "Carol gets 999.999 [LP shares]", + caption: + "Her shares are her slice of the pool. As the first depositor, she gets her deposit less a tenth of a cent, " + + "MINIMUM_LIQUIDITY, which no one will ever own: the defense against a first-depositor attack.", + actions: [ + transfer("lpMint", null, "carolShares", "999.999 LP", { + id: "carolMint", d: minted(laneAfter("carol"), A.carolShares), + coinNear: { x: 650, y: CORRIDOR }, label: ["999.999 LP"], labelAt: below, + }), + ], + }, + { + title: "Eleven more LPs [deposit]", + caption: + "Eleven more providers follow Carol over the morning, each priced against the pool's value at that moment. " + + "The pool opens for trading with 12,000 USDC of liquidity.", + actions: [ + { type: "call", handler: "add_liquidity()", focus: ["program", "pool", "vault", "lpMint", "oracle"] }, + changes("pool", { liquidity: "12,000 USDC" }), + { type: "set", changes: [{ id: "vault", value: "12,000 USDC" }] }, + ], + }, + + // ---- Alice's long + { + title: "Alice runs [open_position()]", + caption: + "Side Long, 1,000 USDC of collateral, size 5,000 USDC: 5x leverage, so each 1% move in NVDAx moves her stake " + + "about 5%. Her position account records the trade, at an entry price of $100.", + actions: [ + { type: "call", handler: "open_position()", focus: ["alice", "aliceUsdc", "program", "pool", "vault", "oracle"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (long)" }] }, + { type: "create", id: "aliceLong", lines: positionLines(995) }, + ], + }, + { + title: "The pool takes a 5 USDC [open fee]", + caption: + "The fee is 0.1% of her size, not her collateral, leaving 995 at work. Half goes to Maria's program_fees, half to the " + + "insurance_fund. Her 995 clears the initial margin: 10% of size, the least a position may open with.", + actions: [ + changes("pool", { total_collateral: "995", program_fees: "2.50", insurance_fund: "2.50", long_size: "5,000" }), + ], + }, + { + title: "Alice's 1,000 USDC go into the [vault]", + caption: + "That is the only token that moves. The pool sets nothing aside for her: whether it can pay her profit is decided " + + "when she closes.", + actions: [ + transfer("aliceUsdc", "0 USDC", "vault", "13,000 USDC", { + id: "aliceIn", d: intoVault(A.aliceUsdc, laneAfter("alice")), + coinNear: { x: 650, y: CORRIDOR }, label: ["open_position()", "1,000 USDC"], labelAt: below, + }), + ], + }, + + // ---- Bob's short + { + title: "Bob runs [open_position()] to go short", + caption: + "Bob thinks NVIDIA's run is over. A short profits as the price falls. He opens the mirror image of Alice's position: " + + "1,000 USDC of collateral, size 5,000, entry $100, and the same 5 USDC fee, split the same way.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc"], + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "open_position()", focus: ["bob", "bobUsdc", "program", "pool", "vault", "oracle"] }, + { type: "set", changes: [{ id: "bob", title: "Bob (short)" }] }, + { type: "create", id: "bobShort", lines: positionLines(995) }, + changes("pool", { total_collateral: "1,990", program_fees: "5", insurance_fund: "5", short_size: "5,000" }), + ], + }, + { + title: "Bob's 1,000 USDC go into the [vault]", + caption: "Two positions are open: one long, one short, both against the pool.", + actions: [ + transfer("bobUsdc", "0 USDC", "vault", "14,000 USDC", { + id: "bobIn", d: intoVault(A.bobUsdc, laneAfter("bob")), + coinNear: { x: 650, y: CORRIDOR }, label: ["open_position()", "1,000 USDC"], labelAt: below, + }), + ], + }, + + // ---- The rally + { + title: "NVDAx rallies to [$110]", + caption: + "Profit is size × price change ÷ entry price: Alice is up 500, Bob down 500. Bob's equity, his 995 plus his loss, " + + "is 495. The maintenance margin, 5% of size, is 250: above it, a position is safe.", + actions: [ + { type: "call", handler: null, focus: ["oracle", "aliceLong", "bobShort"] }, + changes("oracle", { price: "$110" }), + ], + }, + { + title: "At [$115], Bob is under the line", + caption: + "Bob's equity is 995 − 750 = 245, below the 250 maintenance margin. He should close, but he keeps putting it off. " + + "Now anyone may liquidate his position: close it for him, for a fee.", + actions: [ + { type: "call", handler: null, focus: ["oracle", "bobShort"] }, + changes("oracle", { price: "$115" }), + ], + }, + { + title: "Dave runs [liquidate_position()]", + caption: + "Dave runs a bot that liquidates any position at or under its maintenance margin. The handler checks the position's " + + "health, not who calls. The LPs take the 750 Bob lost, and his short leaves the pool's books.", + actions: [ + { + type: "show", + ids: ["dave", "daveUsdc"], + // The book's standard wallet: every character starts with one SOL and 1,000 USDC. + lines: { dave: [sol("1 SOL")], daveUsdc: [balance("1,000 USDC")] }, + focus: "shown", + }, + { type: "call", handler: "liquidate_position()", focus: ["dave", "daveUsdc", "bobShort", "bobUsdc", "program", "pool", "vault", "oracle"] }, + { type: "set", changes: [{ id: "dave", title: "Dave (liquidator)" }] }, + changes("pool", { liquidity: "12,750 USDC", total_collateral: "995", short_size: "0" }), + ], + }, + { + title: "Dave takes the 50 USDC [liquidation fee]", + caption: "1% of the 5,000 size, paid out of Bob's remaining equity. Dave put up no capital: he's paid for sending the transaction.", + actions: [ + transfer("vault", "13,950 USDC", "daveUsdc", "1,050 USDC", { + id: "daveFee", d: outOfVault(laneAfter("dave"), A.daveUsdc), + coinNear: { x: 700, y: CORRIDOR }, label: ["liquidate_position()", "50 USDC"], labelAt: below, + }), + ], + }, + { + title: "Bob gets back [195 USDC]", + caption: + "The rest of his 245 of equity, and his position account closes, its rent back to him. Bob turned 1,000 USDC " + + "into 195 by being wrong, and slow.", + actions: [ + transfer("vault", "13,755 USDC", "bobUsdc", "195 USDC", { + id: "bobRefund", d: outOfVault(laneAfter("bob"), A.bobUsdc), + coinNear: { x: 560, y: CORRIDOR }, label: ["195 USDC"], labelAt: below, + }), + { type: "close", id: "bobShort" }, + ], + }, + + // ---- Alice closes + { + title: "NVDAx reaches [$120]", + caption: + "Alice's profit is 5,000 × 20 ÷ 100 = 1,000 USDC. Her position has been open longer than the pool's ten-slot " + + "warm-up, so she may take it.", + actions: [ + { type: "call", handler: null, focus: ["oracle", "aliceLong"] }, + changes("oracle", { price: "$120" }), + ], + }, + { + title: "Alice runs [close_position()]", + caption: + "The pool's 12,755 USDC of backing, liquidity plus insurance, covers her 1,000 profit, so the haircut is 1: paid in " + + "full. The LPs pay her profit, and a 5 USDC close fee splits like the open fee.", + actions: [ + { type: "call", handler: "close_position()", focus: ["alice", "aliceUsdc", "aliceLong", "program", "pool", "vault", "oracle"] }, + changes("pool", { liquidity: "11,750 USDC", total_collateral: "0", program_fees: "7.50", insurance_fund: "7.50", long_size: "0" }), + ], + }, + { + title: "Alice receives [1,990 USDC]", + caption: + "995 + 1,000 − 5. Her stake nearly doubled on a 20% move: that is what 5x leverage means. Her position account " + + "closes, its rent back to her.", + actions: [ + transfer("vault", "11,765 USDC", "aliceUsdc", "1,990 USDC", { + id: "aliceOut", d: outOfVault(laneAfter("alice"), A.aliceUsdc), + coinNear: { x: 560, y: CORRIDOR }, label: ["close_position()", "1,990 USDC"], labelAt: below, + }), + { type: "close", id: "aliceLong" }, + ], + }, + + // ---- Maria's fees + { + title: "Maria runs [collect_fees()]", + caption: + "program_fees holds 7.50 USDC: half the fees on two opens and one close. The other half stays in the insurance fund. " + + "Only Maria may collect, and it zeroes the balance before it pays her.", + actions: [ + // The book's standard wallet: every character starts with one SOL and 1,000 USDC. + { type: "show", ids: ["mariaUsdc"], lines: { mariaUsdc: [balance("1,000 USDC")] }, focus: "shown" }, + { type: "call", handler: "collect_fees()", focus: ["maria", "mariaUsdc", "program", "pool", "vault"] }, + changes("pool", { program_fees: "0" }), + ], + }, + { + title: "Maria receives [7.50 USDC]", + caption: "The only handler that needs her signature once the pool exists, and the oracle is not even read.", + actions: [ + transfer("vault", "11,757.50 USDC", "mariaUsdc", "1,007.50 USDC", { + id: "fees", d: outOfVault(laneAfter("maria"), A.mariaUsdc), + coinNear: { x: 820, y: CORRIDOR }, label: ["collect_fees()", "7.50 USDC"], labelAt: below, + }), + ], + }, + ]; + + window.PERPS_SCENE = { + title: "Perpetual Futures", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 532, w: 540, h: 92, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/perpetual-futures/slides.js b/animations/perpetual-futures/slides.js new file mode 100644 index 00000000..6bcce5ed --- /dev/null +++ b/animations/perpetual-futures/slides.js @@ -0,0 +1,161 @@ +// The Perpetual Futures talk: the slides around the scene's diagram steps. +// Diagram runs name the scene steps they show, by index, and together they +// show every step once, in order. Each term is defined where the talk first +// needs it. + +(function () { + window.PERPS_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build a", "[perpetual futures]", "venue on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Perpetual Futures chapter", + items: [ + "How a pool can be the other side of every leveraged trade", + "How a program checks it can pay every winner without reading every position", + "Why a stranger is paid to close a losing position", + ], + }, + ], + }, + + // ---- What people want, and how a perpetual future gives it to them. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:price-rises", who: "Alice", + name: "Wants [more upside] than her money buys", + text: "She thinks NVIDIA is about to have a very good quarter. She could buy NVIDIA and wait, " + + "but she wants more exposure than her $1,000 buys.", + }, + { + tone: "lavender", icon: "tpl:perps-price-falls", who: "Bob", + name: "Wants to profit if it [falls]", + text: "He thinks NVIDIA's run is over, and wants to profit if it falls, which owning the stock " + + "cannot give him.", + }, + ], + }, + { + type: "split", + heading: "A [perpetual future] gives both what they want", + sub: "A contract that pays the movement of a price, without anyone holding the asset", + cards: [ + { icon: "tpl:price-rises", name: "Alice goes long", text: "She profits as the price rises, and loses as it falls" }, + { icon: "tpl:perps-price-falls", name: "Bob goes short", text: "He profits as the price falls, and loses as it rises" }, + { icon: "tpl:perps-no-expiry", name: "It never expires", text: "Unlike a traditional future, a position stays open until its owner closes it" }, + ], + }, + { + type: "grid", + tone: "lavender", + heading: "The [terms] of a position", + sub: "Every position names these", + cards: [ + { icon: "tpl:perps-collateral", name: "Collateral", text: "What the trader puts up, and can lose: Alice's $1,000" }, + { icon: "tpl:perps-size", name: "Size", text: "The exposure the position controls: $5,000 of NVIDIA" }, + { icon: "tpl:perps-leverage", name: "Leverage", text: "Size divided by collateral: 5x, so a 1% move moves her stake 5%" }, + ], + }, + { + type: "chart", + heading: "Five times the gain, and five times the [loss]", + sub: "Alice's profit at each NVIDIA price, with her 5x long and with $1,000 of the stock", + x: [90, 120], xStep: 5, + y: [-500, 1000], yStep: 500, + xLabel: "NVIDIA's price", + yLabel: "Profit ($)", + marks: [{ at: 100, label: "TODAY $100" }], + series: [ + // Both lines follow from the chapter by arithmetic: the long's profit is size × price change ÷ + // entry price (5,000 × (p − 100) ÷ 100, so +1,000 at $120 as the chapter states), and $1,000 of + // the stock at the chapter's $100 entry is ten shares, the chapter's "buy NVDAx and wait". + { tone: "green", label: "Alice's 5x long", points: [[90, -500], [120, 1000]], labelAt: [91, 380] }, + { tone: "purple", label: "Owning $1,000 of NVIDIA", points: [[90, -100], [120, 200]], labelAt: [111, -140] }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, the venue, the LPs, and both positions opening. + { type: "diagram", from: 0, to: 15 }, + { + type: "numbered", + heading: "A perpetual never expires, so traders pay [funding]", + sub: "To keep the numbers clean, this walkthrough's pool sets the funding rate to zero", + cards: [ + { name: "The heavier side pays", text: "The side with more open interest pays a fee for every second it stays open" }, + { name: "The pool is the other side", text: "It takes the heavier side's payment, and pays the lighter side at the same rate" }, + { name: "One index for every position", text: "Each position remembers the index when it opened, so settling it reads one account" }, + ], + }, + // The rally, and Bob's liquidation. + { type: "diagram", from: 16, to: 21 }, + { + type: "grid", + columns: 4, + heading: "Where a loss too big to pay [goes]", + sub: "Decided in advance, in this order", + cards: [ + { icon: "tpl:perps-liquidation", name: "Liquidation", text: "Takes it from the loser, while collateral remains" }, + { icon: "tpl:insurance", name: "Insurance fund", text: "Takes it from a pot filled from half of every fee" }, + { icon: "tpl:perps-pool", name: "The LPs", text: "Take what the insurance fund can't" }, + { icon: "tpl:perps-haircut", name: "A haircut", text: "Pays every winner the same fraction of their profit when the pool can't pay in full" }, + ], + }, + // Alice closes, and Maria collects. + { type: "diagram", from: 22, to: 25 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:price-rises", name: "Alice", text: "Turned 1,000 USDC into 1,990 by being right with leverage" }, + { tone: "lavender", icon: "tpl:perps-price-falls", name: "Bob", text: "Turned 1,000 USDC into 195 by being wrong, and slow" }, + { tone: "mint", icon: "tpl:perps-liquidation", name: "Dave", text: "Collected 50 USDC for one well-timed transaction" }, + { tone: "white", icon: "tpl:perps-pool", name: "Carol", text: "Owns a twelfth of a pool that took Bob's 750 and paid Alice's 1,000: down about 21 USDC" }, + { tone: "lavender", icon: "tpl:venue", name: "Maria", text: "Collected 7.50 USDC of fees, and could touch nothing else" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/animations/prop-amm/index.html b/animations/prop-amm/index.html new file mode 100644 index 00000000..08fa5da8 --- /dev/null +++ b/animations/prop-amm/index.html @@ -0,0 +1,50 @@ + + + + + +Prop AMM Talk + + + +
+
→ next · ← back · P play / pause · F full screen
+ + + + + + + diff --git a/animations/prop-amm/scene.js b/animations/prop-amm/scene.js new file mode 100644 index 00000000..caadf1f5 --- /dev/null +++ b/animations/prop-amm/scene.js @@ -0,0 +1,427 @@ +// The Prop AMM chapter as an animated scene: an oracle publishes NVDAx's +// price, Maria opens a market and stocks it with her firm's own capital, +// Alice buys at the ask, Bob sells at the bid, the price moves, Maria widens +// the spread and pauses, then withdraws everything and closes the market. +// +// The columns are the chapter figures' accounts spread across a 16:9 screen: +// the three people, the two mints and the price feed beneath the one curve, +// and the program with the market and its vaults on the right. Arrows run +// down the lanes between the people's columns, along a corridor beneath +// them, and up the lane beside the vaults, one transfer on screen at a time. +// The steps follow the handlers in quicknode/solana-program-examples +// finance/prop-amm: swap() reads the price feed and prices the fill before +// the trader pays in, then the vault pays out. + +(function () { + const WIDTH = 1120; + const HEIGHT = 630; + const curve = AccountAnimation.clusterCurve(WIDTH, { top: 62, control: 700 / WIDTH }); + const rounded = AccountAnimation.rounded; + + // A public-key account hugs its dot: the dot sits on the curve over the + // box's right edge, and the box top 9.3 below it. + function onCurve(kind, title, x, w) { + const cx = x + w - 8; + const cy = curve.yAt(cx); + return { kind, title, x, w, y: cy + 9.3, dot: { cx, cy }, onCurve: true }; + } + + // A derived account hangs at a given top, its dot and seed list above it. + function derived(kind, title, x, y, w, seeds) { + const three = seeds.length === 3; + return { + kind, title, x, y, w, + dot: { cx: x + 8, cy: y - (three ? 18.5 : 14) }, + seeds: { x: x + 18, y: y - (three ? 24 : 15), lines: seeds }, + }; + } + + const tall = (lines) => 21 + lines * 12 + 7; + const GAP2 = 28.6; + + const COLUMN = { + alice: [16, 150], + bob: [182, 150], + maria: [348, 150], + nvdaxMint: [516, 104], + usdcMint: [630, 104], + priceFeed: [744, 132], + program: [884, 220], + }; + + const ata = (owner, token, person, slot, [x, w]) => + derived("token", `${owner}'s ${token}`, x, person.y + 77 * slot, w, [ + `${owner.toUpperCase()}'S ADDRESS +`, "TOKEN PROGRAM +", `${token.toUpperCase()} MINT`, + ]); + + const alice = onCurve("wallet", "Alice", ...COLUMN.alice); + const bob = onCurve("wallet", "Bob", ...COLUMN.bob); + const maria = onCurve("wallet", "Maria", ...COLUMN.maria); + const program = onCurve("program", "prop amm program", ...COLUMN.program); + const market = derived("struct", "market", COLUMN.program[0], program.y + tall(6) + 2 + GAP2, COLUMN.program[1], ['"MARKET" + NVDAX &', "USDC MINT ADDRESSES"]); + const baseVault = derived("token", "base vault", COLUMN.program[0], market.y + tall(5) + GAP2, COLUMN.program[1], ['"BASE_VAULT" +', "MARKET'S ADDRESS"]); + const quoteVault = derived("token", "quote vault", COLUMN.program[0], baseVault.y + tall(2) + GAP2, COLUMN.program[1], ['"QUOTE_VAULT" +', "MARKET'S ADDRESS"]); + + const accounts = { + alice, + aliceUsdc: ata("Alice", "USDC", alice, 1, COLUMN.alice), + aliceNvdax: ata("Alice", "NVDAx", alice, 2, COLUMN.alice), + bob, + bobUsdc: ata("Bob", "USDC", bob, 1, COLUMN.bob), + bobNvdax: ata("Bob", "NVDAx", bob, 2, COLUMN.bob), + maria, + mariaUsdc: ata("Maria", "USDC", maria, 1, COLUMN.maria), + mariaNvdax: ata("Maria", "NVDAx", maria, 2, COLUMN.maria), + nvdaxMint: onCurve("mint", "NVDAx mint", ...COLUMN.nvdaxMint), + usdcMint: onCurve("mint", "USDC mint", ...COLUMN.usdcMint), + // Created from a key pair by the oracle's deployer, so its dot is on the curve. + // Named as the chapter's figures name it. + priceFeed: onCurve("struct", "NVDAx feed", ...COLUMN.priceFeed), + program, + market, + baseVault, + quoteVault, + }; + for (const [id, acc] of Object.entries(accounts)) acc.id = id; + const A = accounts; + + // ---- Arrows -------------------------------------------------------------- + + const LANE = { + alice: 174, // between Alice and Bob + bob: 340, // between Bob and Maria + maria: 506, // between Maria and the mints + vaults: 862, // beside the vaults, below the price feed + }; + const CORRIDOR = 440; + const right = (acc, dy = 20) => [acc.x + acc.w + 2, acc.y + dy]; + const left = (acc, dy = 26) => [acc.x - 2, acc.y + dy]; + + // From a person's account down their lane, along the corridor, and up or + // down the vaults' lane into a vault. + function intoVault(from, lane, to) { + const [sx, sy] = right(from); + const [ex, ey] = left(to); + return rounded([[sx, sy], [lane, sy], [lane, CORRIDOR], [LANE.vaults, CORRIDOR], [LANE.vaults, ey], [ex, ey]]); + } + + // From a vault along the corridor and up a lane into a person's account. + function outOfVault(from, lane, to) { + const [sx, sy] = left(from); + const [ex, ey] = right(to); + return rounded([[sx, sy], [LANE.vaults, sy], [LANE.vaults, CORRIDOR], [lane, CORRIDOR], [lane, ey], [ex, ey]]); + } + + const below = { dx: 0, dy: 22, anchor: "middle" }; + + const transfer = (from, fromValue, to, toValue, arrow) => ({ + type: "transfer", + alone: true, + from: { id: from, value: fromValue }, + to: { id: to, value: toValue }, + arrow, + }); + + // ---- Lines --------------------------------------------------------------- + + const sol = (text) => ({ text, style: "sol" }); + const balance = (text) => ({ text, style: "balance" }); + const field = (text) => ({ text }); + const note = (text) => ({ text, style: "note" }); + const vault = (amount) => [balance(amount), note("authority: the market")]; + + const HANDLERS = [ + "initialize_market()", + "deposit_inventory()", + "swap()", + "set_quote()", + "withdraw_inventory()", + "close_market()", + ]; + + // ---- Steps --------------------------------------------------------------- + + const steps = [ + // ---- The opening, for an audience new to Solana. + { + title: "This is [Solana Devnet]", + // One idea a line: a caption keeps its line breaks. + caption: + "It is a global computer\nFinancial products are programs that run on this computer\n" + + "All data is stored in accounts\nEach account has an address\n" + + "Some addresses are public keys, others are made from ‘seeds’ chosen by programmers", + actions: [], + }, + { + title: "Meet [Alice]", + caption: + "Each rounded box is an account. Alice's sits at her address, the dot on the curve, and holds " + + "1 SOL: Solana's own currency, which pays for her transactions.", + actions: [{ type: "show", ids: ["alice"], lines: { alice: [sol("1 SOL")] }, focus: "all" }], + }, + { + title: "Every token has a [mint]", + caption: + "Each kind of token is defined by one mint account. Here are two: USDC, a token worth one US dollar, " + + "and NVDAx, a token that tracks one share of NVIDIA stock.", + actions: [{ type: "show", ids: ["nvdaxMint", "usdcMint"], focus: "all" }], + }, + { + title: "Alice has a [thousand dollars]", + caption: + "Alice keeps her USDC in a token account of her own. Its address, the dot off the curve, is worked out " + + "from the three names above it rather than held by anyone. It holds 1,000 USDC: a thousand dollars.", + actions: [{ type: "show", ids: ["aliceUsdc"], lines: { aliceUsdc: [balance("1,000 USDC")] }, focus: "all" }], + }, + { + title: "Alice wants five NVIDIA shares [now]", + caption: + "Alice wants 5 NVDAx right away, at the market price, without waiting for someone to sell to her.", + actions: [{ type: "focus", ids: ["alice", "aliceUsdc"] }], + }, + { + title: "Programs are [accounts] too", + caption: + "A program is an account that holds code. This one runs a market, and each line is an instruction " + + "handler anyone can call by sending a transaction. First, somebody has to open the market.", + actions: [{ type: "show", ids: ["program"], lines: { program: HANDLERS.map(field) }, focus: "all" }], + }, + + // ---- The market opens + { + title: "An oracle publishes the [price]", + caption: + "An oracle is a service that writes real-world facts onto Solana. Its price feed is an account, owned by " + + "the oracle's program, that it keeps updated with NVDAx's market price: $165.", + actions: [ + { + type: "show", + ids: ["priceFeed"], + lines: { priceFeed: [field("price: $165.00"), field("owner: mock-price-feed")] }, + focus: "shown", + }, + ], + }, + { + title: "Maria runs [initialize_market()]", + caption: + "Maria runs a market-making firm. Her market reads that price feed, and quotes a spread_bps of 10, in basis " + + "points, hundredths of a percent: buyers pay the price plus 0.1%, sellers get the price minus 0.1%. " + + "It has two vaults, token accounts the program controls.", + actions: [ + { type: "show", ids: ["maria"], lines: { maria: [sol("1 SOL")] }, focus: "shown" }, + { type: "call", handler: "initialize_market()", focus: ["maria", "program", "priceFeed", "nvdaxMint", "usdcMint"] }, + { type: "set", changes: [{ id: "maria", title: "Maria (operator)" }] }, + { + type: "create", id: "market", + lines: [ + field("operator: Maria"), + field("oracle_feed: the NVDAx feed"), + field("spread_bps: 10"), + field("max_confidence_bps: 100"), + field("paused: false"), + ], + }, + { type: "create", id: "baseVault", lines: vault("0 NVDAx") }, + { type: "create", id: "quoteVault", lines: vault("0 USDC") }, + ], + }, + { + title: "Maria runs [deposit_inventory()]", + caption: + "Her firm's own capital is the market's inventory, what every trade fills from. 1,000 NVDAx go into the " + + "base vault. Nobody else deposits, so there are no shares to mint.", + actions: [ + { + type: "show", + ids: ["mariaUsdc", "mariaNvdax"], + // The chapter: her own 1,000 USDC plus the firm's 200,000 USDC, and 1,000 NVDAx. + lines: { mariaUsdc: [balance("201,000 USDC")], mariaNvdax: [balance("1,000 NVDAx")] }, + focus: "shown", + }, + { type: "call", handler: "deposit_inventory()", focus: ["maria", "mariaUsdc", "mariaNvdax", "program", "market", "baseVault", "quoteVault"] }, + transfer("mariaNvdax", "0 NVDAx", "baseVault", "1,000 NVDAx", { + id: "stockBase", d: intoVault(A.mariaNvdax, LANE.maria, baseVault), + coinNear: { x: 690, y: CORRIDOR }, label: ["deposit_inventory()", "1,000 NVDAx"], labelAt: below, + }), + ], + }, + { + title: "200,000 USDC go into the [quote vault]", + caption: "Now Maria can sell NVDAx to buyers, and pay USDC to sellers.", + actions: [ + transfer("mariaUsdc", "1,000 USDC", "quoteVault", "200,000 USDC", { + id: "stockQuote", d: intoVault(A.mariaUsdc, LANE.maria, quoteVault), + coinNear: { x: 690, y: CORRIDOR }, label: ["200,000 USDC"], labelAt: below, + }), + ], + }, + + // ---- Alice buys at the ask + { + title: "Alice runs [swap()] to buy", + caption: + "The handler checks the price feed is fresh and belongs to the oracle Maria chose, then prices Alice at " + + "the ask: $165 plus 0.1% is $165.165, rounded up. Her 825.825 USDC buy exactly 5 NVDAx.", + actions: [ + { type: "call", handler: "swap()", focus: ["alice", "aliceUsdc", "program", "priceFeed", "market", "baseVault", "quoteVault"] }, + { type: "set", changes: [{ id: "alice", title: "Alice (trader)" }] }, + { type: "create", id: "aliceNvdax", lines: [balance("0 NVDAx")] }, + ], + }, + { + title: "Alice pays the [ask]", + caption: "825.825 USDC go into the quote vault. Her NVDAx account was created in the same transaction.", + actions: [ + transfer("aliceUsdc", "174.175 USDC", "quoteVault", "200,825.825 USDC", { + id: "aliceIn", d: intoVault(A.aliceUsdc, LANE.alice, quoteVault), + coinNear: { x: 520, y: CORRIDOR }, label: ["swap()", "825.825 USDC"], labelAt: below, + }), + ], + }, + { + title: "Alice receives 5 [NVDAx]", + caption: + "The vault pays out. A fund buying 500 NVDAx would pay $165.165 each too: the price never depends on " + + "the trade's size or the vaults' balances, so there is no price impact.", + actions: [ + transfer("baseVault", "995 NVDAx", "aliceNvdax", "5 NVDAx", { + id: "aliceOut", d: outOfVault(baseVault, LANE.alice, A.aliceNvdax), + coinNear: { x: 520, y: CORRIDOR }, label: ["5 NVDAx"], labelAt: below, + }), + ], + }, + + // ---- Bob sells at the bid + { + title: "Bob runs [swap()] to sell", + caption: + "Bob needs USDC for a down payment, and sells the 5 NVDAx he holds. He gets the bid: $165 minus 0.1% is " + + "$164.835, rounded down, the rounding again in the market's favour.", + actions: [ + { + type: "show", + ids: ["bob", "bobUsdc", "bobNvdax"], + lines: { bob: [sol("1 SOL")], bobUsdc: [balance("1,000 USDC")], bobNvdax: [balance("5 NVDAx")] }, + focus: "shown", + }, + { type: "call", handler: "swap()", focus: ["bob", "bobUsdc", "bobNvdax", "program", "priceFeed", "market", "baseVault", "quoteVault"] }, + { type: "set", changes: [{ id: "bob", title: "Bob (trader)" }] }, + ], + }, + { + title: "Bob delivers 5 [NVDAx]", + caption: "The trader pays in first, then the vault pays out, both in one transaction or neither.", + actions: [ + transfer("bobNvdax", "0 NVDAx", "baseVault", "1,000 NVDAx", { + id: "bobIn", d: intoVault(A.bobNvdax, LANE.bob, baseVault), + coinNear: { x: 600, y: CORRIDOR }, label: ["swap()", "5 NVDAx"], labelAt: below, + }), + ], + }, + { + key: "bobSold", + title: "Bob receives the [bid]", + caption: + "824.175 USDC to Bob. Alice paid 825.825 for the same 5 NVDAx, so 1.65 USDC stays in the quote vault: " + + "the spread, and all of Maria's revenue.", + actions: [ + transfer("quoteVault", "200,001.65 USDC", "bobUsdc", "1,824.175 USDC", { + id: "bobOut", d: outOfVault(quoteVault, LANE.bob, A.bobUsdc), + coinNear: { x: 600, y: CORRIDOR }, label: ["824.175 USDC"], labelAt: below, + }), + ], + }, + + // ---- The chapter's hypothetical: the oracle reprices + { + title: "The price feed reprices to [$170]", + caption: + "NVIDIA reports earnings and the price feed reprices to $170. The very next swap fills at a " + + "$170.17 ask. But a quote can be seconds old, and a trader who knows the price moved fills it first: " + + "adverse selection, a loss Maria bears.", + actions: [ + { type: "call", handler: null, focus: ["priceFeed", "market"] }, + { type: "set", changes: [{ id: "priceFeed", key: "price", value: "$170.00" }] }, + ], + }, + + // ---- Maria manages the risk + { + from: "bobSold", + key: "widened", + title: "Maria runs [set_quote()] to widen the spread", + caption: + "When volatility rises, Maria widens the spread to 50 basis points. The next buyer " + + "would pay $165.825 per NVDAx, paying her more for the risk of a stale quote.", + actions: [ + { type: "call", handler: "set_quote()", focus: ["maria", "program", "market"] }, + { type: "set", changes: [{ id: "market", key: "spread_bps", value: "50" }] }, + ], + }, + // The chapter pauses only when Maria's view diverges from the price feed; its + // withdrawal figure shows the market unpaused, so the pause is a branch. + { + title: "Maria runs [set_quote()] to pause", + caption: + "Maria's view of the market diverges from the price feed entirely, so set_quote() sets " + + "paused, and every swap is refused with MarketPaused until she calls it again with paused false.", + actions: [ + { type: "call", handler: "set_quote()", focus: ["maria", "program", "market"] }, + { type: "set", changes: [{ id: "market", key: "paused", value: "true" }] }, + ], + }, + + // ---- Maria takes her capital back, from the widened, unpaused market + { + from: "widened", + title: "Maria runs [withdraw_inventory()]", + caption: + "Her capital comes back whenever she wants it, with nobody's permission and no shares to work out. " + + "Only the operator can call it.", + actions: [ + { type: "call", handler: "withdraw_inventory()", focus: ["maria", "mariaUsdc", "mariaNvdax", "program", "market", "baseVault", "quoteVault"] }, + transfer("baseVault", "0 NVDAx", "mariaNvdax", "1,000 NVDAx", { + id: "drainBase", d: outOfVault(baseVault, LANE.maria, A.mariaNvdax), + coinNear: { x: 690, y: CORRIDOR }, label: ["withdraw_inventory()", "1,000 NVDAx"], labelAt: below, + }), + ], + }, + { + title: "Maria takes the [USDC] back", + caption: + "Every NVDAx came back, and 1.65 USDC more than she put in: the spread both traders paid.", + actions: [ + transfer("quoteVault", "0 USDC", "mariaUsdc", "201,001.65 USDC", { + id: "drainQuote", d: outOfVault(quoteVault, LANE.maria, A.mariaUsdc), + coinNear: { x: 690, y: CORRIDOR }, label: ["200,001.65 USDC"], labelAt: below, + }), + ], + }, + { + title: "Maria runs [close_market()]", + caption: + "It refuses while either vault holds a token (InventoryNotEmpty). Both vaults and the market close, " + + "and the rent Maria paid for all three, the SOL each account holds to exist, comes back to her.", + actions: [ + { type: "call", handler: "close_market()", focus: ["maria", "program", "market", "baseVault", "quoteVault"] }, + { type: "close", id: "baseVault" }, + { type: "close", id: "quoteVault" }, + { type: "close", id: "market" }, + ], + }, + ]; + + window.PROPAMM_SCENE = { + title: "Prop AMM", + canvas: { width: WIDTH, height: HEIGHT }, + curve, + network: { text: "Solana Devnet", x: WIDTH - 12, y: curve.yAt(1000) - 12 }, + caption: { x: 16, y: 520, w: 540, h: 100, fontSize: 13 }, + hold: 3000, + program: "program", + order: Object.keys(accounts), + accounts, + steps, + }; +})(); diff --git a/animations/prop-amm/slides.js b/animations/prop-amm/slides.js new file mode 100644 index 00000000..eb63ea69 --- /dev/null +++ b/animations/prop-amm/slides.js @@ -0,0 +1,144 @@ +// The Prop AMM talk: the slides around the scene's diagram steps. Diagram +// runs name the scene steps they show, by index, and together they show every +// step once, in order. Each term is defined where the talk first needs it. + +(function () { + window.PROPAMM_DECK = { + series: "Quicknode Solana Finance", + // Relative to the talk's index.html. + assets: "../assets/", + slides: [ + { type: "title", lines: ["How to build a", "[prop AMM]", "on Solana"] }, + { + type: "columns", + columns: [ + { + heading: "What you should {know}", + sub: "Before you start", + items: [ + "Users interact with Solana by making transactions containing many instructions", + "Solana programs have instruction handler functions", + "Programs save data in PDAs with seeds", + ], + }, + { + heading: "What you'll {learn}", + sub: "From the Prop AMM chapter", + items: [ + "How a market-making firm quotes its own capital on Solana", + "Why a price read from an oracle has no price impact", + "How a market maker protects itself when prices move fast", + ], + }, + ], + }, + + // ---- What people want, and how a prop AMM gives it to them, before any Solana. + { + type: "versus", + cards: [ + { + tone: "mint", icon: "tpl:propamm-spread", who: "Maria", + name: "Wants to earn the [spread]", + text: "She runs a market-making firm: it stands ready to buy from anyone and sell to anyone, " + + "selling a little above the market price and buying a little below it. The difference is her income.", + }, + { + tone: "lavender", icon: "tpl:propamm-instant", who: "Alice", + name: "Wants to buy [right now]", + text: "She wants five NVIDIA shares at a fair price, without waiting for someone who happens to be " + + "selling, and without her own purchase pushing the price up.", + }, + ], + }, + { + type: "numbered", + heading: "A [prop AMM] gives both what they want", + sub: "“Prop” is short for proprietary: the firm trades its own capital, and nobody else's", + cards: [ + { name: "Maria quotes both sides", text: "Anyone may buy from her, or sell to her, at any moment" }, + { name: "An oracle sets the price", text: "Her prices follow the market price an oracle publishes, plus or minus her margin" }, + { name: "Maria keeps the difference", text: "What buyers pay above the market, and sellers take below it, is all she earns" }, + ], + }, + { + type: "grid", + tone: "lavender", + heading: "The [terms] of a prop AMM", + sub: "Every market maker's quote names these", + cards: [ + { icon: "tpl:propamm-maker", name: "Market maker", text: "A firm that stands ready to buy and to sell: Maria" }, + { icon: "tpl:propamm-oracle", name: "Oracle price", text: "The market price an oracle publishes: $165 for NVIDIA" }, + { icon: "tpl:propamm-ask", name: "Ask", text: "What a buyer pays: the oracle price plus Maria's margin" }, + { icon: "tpl:propamm-bid", name: "Bid", text: "What a seller receives: the oracle price minus the same margin" }, + { icon: "tpl:propamm-spread", name: "Spread", text: "The gap between the ask and the bid: Maria's income" }, + { icon: "tpl:propamm-inventory", name: "Inventory", text: "The firm's own tokens that every trade fills from" }, + ], + }, + { + type: "statement", + heading: "Now let's build it on [Solana]", + sub: "Every account, every handler, and every token that moves", + }, + + // Solana, Alice, the price feed, the market, and both trades. + { type: "diagram", from: 0, to: 15 }, + { + type: "statement", + heading: "A round trip costs [1.65 USDC]", + sub: "Alice paid 825.825 USDC for 5 NVDAx, and Bob got 824.175 for the same 5. The difference stays in the market", + }, + // The price moves, Maria manages her risk, and closes the market. + { + type: "statement", + heading: "What if NVIDIA [reprices] to $170?", + }, + { type: "diagram", from: 16, to: 16 }, + { + type: "statement", + heading: "Back at $165: Maria [manages] the risk", + }, + { type: "diagram", from: 17, to: 17 }, + { + type: "statement", + heading: "What if Maria [distrusts] the price?", + }, + { type: "diagram", from: 18, to: 18 }, + { + type: "statement", + heading: "Back to the open market: Maria [withdraws]", + }, + { type: "diagram", from: 19, to: 21 }, + { + type: "cards", + tone: "light", + tag: "Where everyone ended up", + cards: [ + { tone: "white", icon: "tpl:propamm-instant", name: "Alice", text: "Bought 5 NVDAx at once, for 825.825 USDC: the quoted price, with no price impact" }, + { tone: "lavender", icon: "tpl:propamm-bid", name: "Bob", text: "Sold his 5 NVDAx at the bid, for 824.175 USDC towards his down payment" }, + { tone: "mint", icon: "tpl:propamm-spread", name: "Maria the market maker", text: "Earned the 1.65 USDC spread, carried every risk, and took all her capital back" }, + ], + }, + + { + type: "qr", + heading: "Building [Financial Software] on Solana", + url: "solanabook.org", + qr: "../assets/qr-solanabook.svg", + cover: "../assets/book-cover.jpg", + items: [ + "The definitive guide to building financial products on the most active blockchain", + "Options trading, Exchanges, Betting Markets, Perpetual Futures.", + "#3 in “Financial Engineering” category on Amazon", + ], + }, + { + type: "follow", + tag: "Follow Quicknode on X", + lead: "To [learn] more on Solana development:", + handle: "[@QuicknodeSolana]", + thanks: "Thanks!", + }, + ], + }; +})(); diff --git a/building-financial-products-in-solana/figures/betting-alice-claim.svg b/building-financial-products-in-solana/figures/betting-alice-claim.svg index cb23a63d..b170a62d 100644 --- a/building-financial-products-in-solana/figures/betting-alice-claim.svg +++ b/building-financial-products-in-solana/figures/betting-alice-claim.svg @@ -151,7 +151,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 0 outcome 0: Glowbugs 3 @@ -161,7 +161,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 1 outcome 1: The Quiet Floor diff --git a/building-financial-products-in-solana/figures/betting-maria-close.svg b/building-financial-products-in-solana/figures/betting-maria-close.svg index 9f763f09..b392e865 100644 --- a/building-financial-products-in-solana/figures/betting-maria-close.svg +++ b/building-financial-products-in-solana/figures/betting-maria-close.svg @@ -111,7 +111,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 0 outcome 0: Glowbugs 3 @@ -123,7 +123,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 1 outcome 1: The Quiet Floor diff --git a/building-financial-products-in-solana/figures/betting-maria-setup.svg b/building-financial-products-in-solana/figures/betting-maria-setup.svg index 0917bd98..1e2294cd 100644 --- a/building-financial-products-in-solana/figures/betting-maria-setup.svg +++ b/building-financial-products-in-solana/figures/betting-maria-setup.svg @@ -117,7 +117,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 0 outcome 0: Glowbugs 3 @@ -128,7 +128,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 1 outcome 1: The Quiet Floor diff --git a/building-financial-products-in-solana/figures/betting-place-bets.svg b/building-financial-products-in-solana/figures/betting-place-bets.svg index ec9ee038..9a2a323a 100644 --- a/building-financial-products-in-solana/figures/betting-place-bets.svg +++ b/building-financial-products-in-solana/figures/betting-place-bets.svg @@ -164,7 +164,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 0 outcome 0: Glowbugs 3 @@ -174,7 +174,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 1 outcome 1: The Quiet Floor diff --git a/building-financial-products-in-solana/figures/betting-settlement.svg b/building-financial-products-in-solana/figures/betting-settlement.svg index 40caa09c..7bd410b5 100644 --- a/building-financial-products-in-solana/figures/betting-settlement.svg +++ b/building-financial-products-in-solana/figures/betting-settlement.svg @@ -151,7 +151,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 0 outcome 0: Glowbugs 3 @@ -161,7 +161,7 @@ "OUTCOME" + EVENT - ADDRESS + INDEX + ADDRESS + INDEX 1 outcome 1: The Quiet Floor diff --git a/building-financial-products-in-solana/figures/fund-create.svg b/building-financial-products-in-solana/figures/fund-create.svg index c1da146d..9c40f81d 100644 --- a/building-financial-products-in-solana/figures/fund-create.svg +++ b/building-financial-products-in-solana/figures/fund-create.svg @@ -144,7 +144,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 0 asset config 0 @@ -156,7 +156,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 1 asset config 1 diff --git a/building-financial-products-in-solana/figures/fund-deposit-bob.svg b/building-financial-products-in-solana/figures/fund-deposit-bob.svg index 029e9395..2f5683db 100644 --- a/building-financial-products-in-solana/figures/fund-deposit-bob.svg +++ b/building-financial-products-in-solana/figures/fund-deposit-bob.svg @@ -161,7 +161,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 0 asset config 0 @@ -174,7 +174,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 1 asset config 1 diff --git a/building-financial-products-in-solana/figures/fund-deposit.svg b/building-financial-products-in-solana/figures/fund-deposit.svg index fbfc6ee2..d63e87fd 100644 --- a/building-financial-products-in-solana/figures/fund-deposit.svg +++ b/building-financial-products-in-solana/figures/fund-deposit.svg @@ -150,7 +150,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 0 asset config 0 @@ -163,7 +163,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 1 asset config 1 diff --git a/building-financial-products-in-solana/figures/fund-rebalance.svg b/building-financial-products-in-solana/figures/fund-rebalance.svg index 39ab7e60..97b7b17f 100644 --- a/building-financial-products-in-solana/figures/fund-rebalance.svg +++ b/building-financial-products-in-solana/figures/fund-rebalance.svg @@ -144,7 +144,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 0 asset config 0 @@ -157,7 +157,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 1 asset config 1 diff --git a/building-financial-products-in-solana/figures/fund-withdraw-in-kind.svg b/building-financial-products-in-solana/figures/fund-withdraw-in-kind.svg index 23cb4f20..a6d9bca4 100644 --- a/building-financial-products-in-solana/figures/fund-withdraw-in-kind.svg +++ b/building-financial-products-in-solana/figures/fund-withdraw-in-kind.svg @@ -165,7 +165,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 0 asset config 0 @@ -178,7 +178,7 @@ - "ASSET" + FUND + INDEX + "ASSET" + FUND + INDEX 1 asset config 1 diff --git a/building-financial-products-in-solana/figures/lending-borrow-ltv.svg b/building-financial-products-in-solana/figures/lending-borrow-ltv.svg index 382e5bc5..b842bb9d 100644 --- a/building-financial-products-in-solana/figures/lending-borrow-ltv.svg +++ b/building-financial-products-in-solana/figures/lending-borrow-ltv.svg @@ -81,9 +81,10 @@ stale: true - - "OBLIGATION_SHARE_ - VAULT" + RESERVE + + + "OBLIGATION_SHARE_ + VAULT" + NVDAX + RESERVE + BOB'S OBLIGATION @@ -212,7 +213,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -236,7 +237,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -255,7 +256,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-collect-fees.svg b/building-financial-products-in-solana/figures/lending-collect-fees.svg index e6d746a0..c9f6fa19 100644 --- a/building-financial-products-in-solana/figures/lending-collect-fees.svg +++ b/building-financial-products-in-solana/figures/lending-collect-fees.svg @@ -148,8 +148,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -221,7 +221,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -240,7 +240,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -256,7 +256,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-deposit-shares.svg b/building-financial-products-in-solana/figures/lending-deposit-shares.svg index a6fa2672..9df11534 100644 --- a/building-financial-products-in-solana/figures/lending-deposit-shares.svg +++ b/building-financial-products-in-solana/figures/lending-deposit-shares.svg @@ -159,7 +159,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -169,7 +169,7 @@ - "SHARE_MINT" + RESERVE + "SHARE_MINT" + USDC RESERVE USDC share mint @@ -204,14 +204,14 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault - "SHARE_MINT" + RESERVE + "SHARE_MINT" + NVDAX RESERVE NVDAx share mint @@ -235,14 +235,14 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault - "SHARE_MINT" + RESERVE + "SHARE_MINT" + SPCXX RESERVE SPCXx share mint diff --git a/building-financial-products-in-solana/figures/lending-liquidation-second-call.svg b/building-financial-products-in-solana/figures/lending-liquidation-second-call.svg index 546ac5b3..b01d8c1c 100644 --- a/building-financial-products-in-solana/figures/lending-liquidation-second-call.svg +++ b/building-financial-products-in-solana/figures/lending-liquidation-second-call.svg @@ -72,8 +72,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -200,9 +200,10 @@ obligation - - "OBLIGATION_SHARE_ - VAULT" + RESERVE + + + "OBLIGATION_SHARE_ + VAULT" + NVDAX + RESERVE + BOB'S OBLIGATION @@ -255,7 +256,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -271,7 +272,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -292,7 +293,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-liquidation.svg b/building-financial-products-in-solana/figures/lending-liquidation.svg index a6af4ee9..63eb24f8 100644 --- a/building-financial-products-in-solana/figures/lending-liquidation.svg +++ b/building-financial-products-in-solana/figures/lending-liquidation.svg @@ -72,8 +72,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -200,9 +200,10 @@ obligation - - "OBLIGATION_SHARE_ - VAULT" + RESERVE + + + "OBLIGATION_SHARE_ + VAULT" + NVDAX + RESERVE + BOB'S OBLIGATION @@ -255,7 +256,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -271,7 +272,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -292,7 +293,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-open-market.svg b/building-financial-products-in-solana/figures/lending-open-market.svg index a98836a0..f6baa305 100644 --- a/building-financial-products-in-solana/figures/lending-open-market.svg +++ b/building-financial-products-in-solana/figures/lending-open-market.svg @@ -151,7 +151,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -162,7 +162,7 @@ - "SHARE_MINT" + RESERVE + "SHARE_MINT" + USDC RESERVE USDC share mint @@ -212,7 +212,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -223,7 +223,7 @@ - "SHARE_MINT" + RESERVE + "SHARE_MINT" + NVDAX RESERVE NVDAx share mint @@ -261,7 +261,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault @@ -272,7 +272,7 @@ - "SHARE_MINT" + RESERVE + "SHARE_MINT" + SPCXX RESERVE SPCXx share mint diff --git a/building-financial-products-in-solana/figures/lending-open-reserves.svg b/building-financial-products-in-solana/figures/lending-open-reserves.svg index 5c56b28b..5f0be0ad 100644 --- a/building-financial-products-in-solana/figures/lending-open-reserves.svg +++ b/building-financial-products-in-solana/figures/lending-open-reserves.svg @@ -123,7 +123,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -132,8 +132,9 @@ authority: the reserve - - "SHARE_MINT" + RESERVE + + "SHARE_MINT" + + USDC RESERVE USDC share mint @@ -179,7 +180,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -188,8 +189,9 @@ authority: the reserve - - "SHARE_MINT" + RESERVE + + "SHARE_MINT" + + NVDAX RESERVE NVDAx share mint @@ -235,7 +237,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault @@ -244,8 +246,9 @@ authority: the reserve - - "SHARE_MINT" + RESERVE + + "SHARE_MINT" + + SPCXX RESERVE SPCXx share mint diff --git a/building-financial-products-in-solana/figures/lending-redeem-collateral.svg b/building-financial-products-in-solana/figures/lending-redeem-collateral.svg index 5a486e5b..a1975f76 100644 --- a/building-financial-products-in-solana/figures/lending-redeem-collateral.svg +++ b/building-financial-products-in-solana/figures/lending-redeem-collateral.svg @@ -152,8 +152,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -201,7 +201,7 @@ "SHARE_MINT" + - RESERVE + NVDAX RESERVE NVDAx share mint @@ -220,7 +220,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -241,7 +241,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -260,7 +260,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-redeem-yield.svg b/building-financial-products-in-solana/figures/lending-redeem-yield.svg index 0a2d0c39..a335561d 100644 --- a/building-financial-products-in-solana/figures/lending-redeem-yield.svg +++ b/building-financial-products-in-solana/figures/lending-redeem-yield.svg @@ -152,8 +152,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -201,7 +201,7 @@ "SHARE_MINT" + - RESERVE + USDC RESERVE USDC share mint @@ -225,7 +225,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -244,7 +244,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -260,7 +260,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-repay.svg b/building-financial-products-in-solana/figures/lending-repay.svg index 1cf654fc..63f37bc9 100644 --- a/building-financial-products-in-solana/figures/lending-repay.svg +++ b/building-financial-products-in-solana/figures/lending-repay.svg @@ -108,9 +108,10 @@ stale: true - - "OBLIGATION_SHARE_ - VAULT" + RESERVE + + + "OBLIGATION_SHARE_ + VAULT" + NVDAX + RESERVE + BOB'S OBLIGATION @@ -162,8 +163,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -224,7 +225,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -243,7 +244,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -259,7 +260,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-short-borrow.svg b/building-financial-products-in-solana/figures/lending-short-borrow.svg index 66106ed7..f6b8ea7c 100644 --- a/building-financial-products-in-solana/figures/lending-short-borrow.svg +++ b/building-financial-products-in-solana/figures/lending-short-borrow.svg @@ -103,9 +103,10 @@ obligation - - "OBLIGATION_SHARE_ - VAULT" + RESERVE + + + "OBLIGATION_SHARE_ + VAULT" + NVDAX + RESERVE + BOB'S OBLIGATION @@ -162,8 +163,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -210,7 +211,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -226,7 +227,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -247,7 +248,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-short-collateral.svg b/building-financial-products-in-solana/figures/lending-short-collateral.svg index 88624042..52b0107f 100644 --- a/building-financial-products-in-solana/figures/lending-short-collateral.svg +++ b/building-financial-products-in-solana/figures/lending-short-collateral.svg @@ -103,9 +103,10 @@ obligation - - "OBLIGATION_SHARE_ - VAULT" + RESERVE + + + "OBLIGATION_SHARE_ + VAULT" + NVDAX + RESERVE + BOB'S OBLIGATION @@ -153,8 +154,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -205,7 +206,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -221,7 +222,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -237,7 +238,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/lending-withdraw-collateral.svg b/building-financial-products-in-solana/figures/lending-withdraw-collateral.svg index 25597ab0..35b72203 100644 --- a/building-financial-products-in-solana/figures/lending-withdraw-collateral.svg +++ b/building-financial-products-in-solana/figures/lending-withdraw-collateral.svg @@ -108,9 +108,10 @@ stale: true - - "OBLIGATION_SHARE_ - VAULT" + RESERVE + + + "OBLIGATION_SHARE_ + VAULT" + NVDAX + RESERVE + BOB'S OBLIGATION @@ -169,8 +170,8 @@ "OBLIGATION_SHARE_ - VAULT" + RESERVE + - OBLIGATION + VAULT" + USDC RESERVE + + CAROL'S OBLIGATION collateral vault @@ -226,7 +227,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + USDC RESERVE USDC liquidity vault @@ -242,7 +243,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + NVDAX RESERVE NVDAx liquidity vault @@ -258,7 +259,7 @@ "LIQUIDITY_VAULT" - + RESERVE + + SPCXX RESERVE SPCXx liquidity vault diff --git a/building-financial-products-in-solana/figures/order-book-alice-ask.svg b/building-financial-products-in-solana/figures/order-book-alice-ask.svg index 0ed3399a..c82c28e7 100644 --- a/building-financial-products-in-solana/figures/order-book-alice-ask.svg +++ b/building-financial-products-in-solana/figures/order-book-alice-ask.svg @@ -145,7 +145,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 1 Alice's order diff --git a/building-financial-products-in-solana/figures/order-book-cancel.svg b/building-financial-products-in-solana/figures/order-book-cancel.svg index c9fb4d77..62101efa 100644 --- a/building-financial-products-in-solana/figures/order-book-cancel.svg +++ b/building-financial-products-in-solana/figures/order-book-cancel.svg @@ -142,7 +142,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 1 Alice's order @@ -151,7 +151,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 2 Bob's order @@ -167,7 +167,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 3 Carol's order diff --git a/building-financial-products-in-solana/figures/order-book-match.svg b/building-financial-products-in-solana/figures/order-book-match.svg index c329cf4b..69b7f0d3 100644 --- a/building-financial-products-in-solana/figures/order-book-match.svg +++ b/building-financial-products-in-solana/figures/order-book-match.svg @@ -149,7 +149,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 1 Alice's order @@ -158,7 +158,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 2 Bob's order @@ -174,7 +174,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 3 Carol's order diff --git a/building-financial-products-in-solana/figures/order-book-settle.svg b/building-financial-products-in-solana/figures/order-book-settle.svg index 48edc753..1cc824e9 100644 --- a/building-financial-products-in-solana/figures/order-book-settle.svg +++ b/building-financial-products-in-solana/figures/order-book-settle.svg @@ -160,7 +160,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 2 Bob's order @@ -169,7 +169,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 3 Carol's order diff --git a/building-financial-products-in-solana/figures/order-book-withdraw-fees.svg b/building-financial-products-in-solana/figures/order-book-withdraw-fees.svg index 46adcae8..e8791766 100644 --- a/building-financial-products-in-solana/figures/order-book-withdraw-fees.svg +++ b/building-financial-products-in-solana/figures/order-book-withdraw-fees.svg @@ -138,7 +138,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 1 Alice's order @@ -147,7 +147,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 2 Bob's order @@ -156,7 +156,7 @@ "ORDER" + MARKET ADDRESS + - ORDER ID + ORDER ID 3 Carol's order diff --git a/package.json b/package.json index 0c2f6bcd..37188534 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "1.0.0", "description": "Manuscript and build tooling for Building Financial Software on Solana", "scripts": { + "animation-frames": "node scripts/animation-frames.mjs", "build-pdf-digital": "FINAL=1 node scripts/build-pdf.mjs", "build-pdf-draft": "node scripts/build-pdf.mjs", "build-pdf-website-preview": "npm run build-pdf-digital && node scripts/build-website-preview.mjs", diff --git a/scripts/animation-frames.mjs b/scripts/animation-frames.mjs new file mode 100644 index 00000000..88ed7672 --- /dev/null +++ b/scripts/animation-frames.mjs @@ -0,0 +1,81 @@ +// Render an animated scene's steps to PNG, so each step's end state can be +// looked at without pressing through the animation, and optionally record the +// whole animation as a video. +// +// node scripts/animation-frames.mjs [--video] +// +// is a directory under animations/ (e.g. options). Frames land in +// build/animation--.png and the end-state SVG beside each one; +// --video plays every step in order and saves build/animation-.webm. +// Exits nonzero if the page throws. A missing Denim INK font is not an error: +// the face is not in the repository, and the page falls back to Helvetica. + +import { chromium } from "playwright-core"; +import { existsSync, mkdirSync, renameSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const args = process.argv.slice(2); +const name = args.find((a) => !a.startsWith("--")); +const video = args.includes("--video"); +if (!name) { + console.error("Usage: node scripts/animation-frames.mjs [--video]"); + process.exit(1); +} +const page_ = join(repoRoot, "animations", name, "index.html"); +if (!existsSync(page_)) { + console.error(`No scene at ${page_}`); + process.exit(1); +} +const outDir = join(repoRoot, "build"); +mkdirSync(outDir, { recursive: true }); + +const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH ?? "/opt/pw-browsers/chromium" }); +// 16:9, the frame the scene is drawn for. +const viewport = { width: 1280, height: 720 }; +const context = await browser.newContext({ + viewport, + deviceScaleFactor: 2, + ...(video ? { recordVideo: { dir: outDir, size: viewport } } : {}), +}); +const page = await context.newPage(); +const errors = []; +page.on("pageerror", (e) => errors.push(e.message)); +await page.goto(pathToFileURL(page_).href); +await page.waitForFunction(() => window.player); +const count = await page.evaluate(() => window.player.count); +// The key hint is for a person at the keyboard, not for a frame or a recording. +await page.addStyleTag({ content: "#hint { display: none; }" }); + +if (video) { + // next() resolves when its step's animation ends; then hold the finished + // step as autoplay does. + const hold = await page.evaluate(() => window.player.scene.hold ?? 3000); + await page.waitForTimeout(hold); + for (let i = 1; i < count; i++) { + await page.evaluate(() => window.player.next()); + await page.waitForTimeout(hold); + } + const path = await page.video().path(); + await context.close(); + renameSync(path, join(outDir, `animation-${name}.webm`)); + console.log(join(outDir, `animation-${name}.webm`)); +} else { + const stage = page.locator("#stage"); + for (let i = 0; i < count; i++) { + await page.evaluate((n) => window.player.goto(n), i); + // Let a cross-fade between a slide and a diagram, or a card's build, finish. + await page.waitForTimeout(500); + const step = String(i + 1).padStart(2, "0"); + await stage.screenshot({ path: join(outDir, `animation-${name}-${step}.png`) }); + const svg = await page.evaluate(() => new XMLSerializer().serializeToString(document.querySelector("#stage svg"))); + writeFileSync(join(outDir, `animation-${name}-${step}.svg`), svg); + } + console.log(`${count} frames in ${outDir}/animation-${name}-*.png`); +} +await browser.close(); +if (errors.length > 0) { + console.error(errors.join("\n")); + process.exit(1); +} diff --git a/scripts/lint-manuscript.mjs b/scripts/lint-manuscript.mjs index e1b34ad4..6d4cdb2d 100644 --- a/scripts/lint-manuscript.mjs +++ b/scripts/lint-manuscript.mjs @@ -697,6 +697,45 @@ for (const file of svgFiles) { failures += 1; console.error(`${file}: markup after is not part of the figure; move it inside the root element\n ${trailing.slice(0, 160)}`); } + // A derived address is its seeds, so two accounts drawn with the same seed + // list would be one account: whatever tells them apart (an index, an order + // ID, which reserve, whose obligation) belongs in the list. A seed list is + // a run of seed-face lines (7-unit mono) at one x, a line apart. Thirty + // figures once drew "LIQUIDITY_VAULT" + RESERVE three times over. + const seedLists = new Map(); + let run = null; + const closeRun = () => { + if (!run) return; + const seeds = run.lines.join(" ").replace(/\s+/g, " ").trim(); + seedLists.set(seeds, [...(seedLists.get(seeds) || []), run.line]); + run = null; + }; + source.split("\n").forEach((line, index) => { + for (const m of line.matchAll(/]*)>([^<]*)<\/text>/g)) { + const [, attrs, body] = m; + if (!/font-size="7"/.test(attrs) || !/Mono/.test(attrs) || !body.trim()) { + closeRun(); + continue; + } + const x = attrs.match(/\bx="([\d.]+)"/)?.[1]; + const y = Number(attrs.match(/\by="([\d.]+)"/)?.[1]); + if (run && run.x === x && y - run.y > 0 && y - run.y <= 10) { + run.lines.push(body.trim()); + run.y = y; + } else { + closeRun(); + run = { x, y, lines: [body.trim()], line: index + 1 }; + } + } + }); + closeRun(); + for (const [seeds, at] of seedLists) { + if (at.length < 2) continue; + failures += 1; + console.error(`${file}:${at.join(",")}: ${at.length} accounts drawn with the same seeds, ${seeds}; ` + + "two derived accounts with the same seeds are one address, so name what tells them apart"); + } + const lines = source.split("\n"); lines.forEach((line, index) => { for (const [pattern, reason] of svgRules) {