From 5e65908365e9af535d216e9fcb241116c89510a1 Mon Sep 17 00:00:00 2001 From: bakasura980 Date: Thu, 29 Oct 2026 12:55:23 +0200 Subject: [PATCH] refactor(tessera): keep the quote current with keep-alive --- crates/core/src/scenarios/README.md | 2 +- .../scenarios/protocols/tessera/v1/README.md | 95 +++++------- .../protocols/tessera/v1/keep-alive.yaml | 33 ++++ .../protocols/tessera/v1/overrides.yaml | 62 ++------ crates/core/src/scenarios/registry.rs | 33 ++-- crates/core/src/tests/tessera/mod.rs | 143 +++++++++++++----- 6 files changed, 211 insertions(+), 157 deletions(-) create mode 100644 crates/core/src/scenarios/protocols/tessera/v1/keep-alive.yaml diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 45e1fa469..199011cbb 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -21,7 +21,7 @@ Protocols that are natively supported by Surfpool will have their IDLs included - **Pump v1** - Bonding curve launchpad with curve reserve and global config override templates - **Phoenix Eternal** - Perpetuals venue with trader collateral, mark price, maintenance margin, market fee, withdraw limit, trader capability, stop-loss trigger and delegated permission templates. See [protocols/phoenix-eternal/README.md](./protocols/phoenix-eternal/README.md) - **PumpSwap v1** - Constant-product AMM with pool state and global config override templates, including canonical pool derivation for migrated pump.fun coins -- **Tessera V** - Proprietary market maker (no published IDL), with price, freshness, ladder depth, ladder curve and halt templates; callers choose the market account. See [protocols/tessera/v1/README.md](./protocols/tessera/v1/README.md) +- **Tessera V** - Proprietary market maker (no published IDL), with price, ladder depth, ladder curve and halt templates; its quote is kept alive. Callers choose the market account. See [protocols/tessera/v1/README.md](./protocols/tessera/v1/README.md) For custom protocols, an IDL can be registered at runtime using the [`surfnet_registerIdl`](https://docs.surfpool.run/rpc/cheatcodes#surfnet-registeridl) RPC cheatcode. diff --git a/crates/core/src/scenarios/protocols/tessera/v1/README.md b/crates/core/src/scenarios/protocols/tessera/v1/README.md index 64d5039d5..3ecd824f0 100644 --- a/crates/core/src/scenarios/protocols/tessera/v1/README.md +++ b/crates/core/src/scenarios/protocols/tessera/v1/README.md @@ -1,7 +1,8 @@ # Tessera V -A proprietary market maker (PMM), not an AMM. Five templates control its price, quote freshness, -ladder depth, ladder curve and a full halt. +A proprietary market maker (PMM), not an AMM. Four templates control its price, ladder depth, +ladder curve and a full halt. Surfpool keeps the quote current on its own once a scenario overrides a +market. Tessera does not derive its price from vault ratios. Its maker writes one price per swap direction into the market account, and two directional ladders of twenty levels decide how much fills at @@ -15,7 +16,6 @@ Program: `TessVdML9pBGgG9yGks7o4HewRaXVAMuoVj4x83GLQH`. | Template | Overrides | | ------------------- | ------------------------------------------------------ | | `tessera-price` | the price Tessera uses for each swap direction | -| `tessera-freshness` | whether Tessera's quote is current or stale | | `tessera-depth` | how much each ladder level fills before the next one | | `tessera-curve` | the output factor applied at each ladder level | | `tessera-halt` | whether any level quotes at all | @@ -29,7 +29,6 @@ Program: `TessVdML9pBGgG9yGks7o4HewRaXVAMuoVj4x83GLQH`. | `*_level_N_amount` | capacity in atoms of the swap's input token | sell side of SOL/USDC: `1000000000` = 1 SOL | | `*_level_N_factor` | output factor in millionths, below `1000000` | `990000` pays 1% less than the bare price | | `*_levels_enabled` | enabled flag of all twenty levels on one side | `0` halts that side | -| `last_update_slot` | offset from the materialization slot | `0` = updated now, `-20` = twenty slots old | Price conversion, with both decimals taken from the two mints: @@ -45,8 +44,8 @@ sell output = floor(base_in × quote_atoms_per_base_atom_x1e15 × sell_level_0_ buy output = floor(quote_in × base_atoms_per_quote_atom_x1e15 × buy_level_0_factor / 10^21) ``` -The formulas hold for a quote younger than its grace period (see -[How a quote ages](#how-a-quote-ages)) and with neutral quote-start configs. The five quote-start configs at offset 1136 can lower a fill or make it skip leading levels. Which +The formulas hold for a quote younger than its grace period, which keep-alive keeps it (see +[How a quote ages](#how-a-quote-ages)), and with neutral quote-start configs. The five quote-start configs at offset 1136 can lower a fill or make it skip leading levels. Which one applies depends on how many slots ago the config account `BAT1Ndpu5gbLTp2AZkSXP79LJBZfCH4B3zGhi6LtvdhK` was updated. A surfnet never updates it, so after about 300 slots the last config applies. Configs that each hold `0`, `1000000` and `0` change @@ -58,11 +57,13 @@ The market account is 1264 bytes. Offsets not listed are not written by any temp | Offset | Field | Encoding | Unit | | --------- | -------------------------------------- | ----------------- | ------------------------ | +| 0 | buy depth used since the publication | u64, keep-alive | quote atoms | +| 8 | sell depth used since the publication | u64, keep-alive | base atoms | | 24 | base mint | pubkey, read-only | - | | 56 | quote mint | pubkey, read-only | - | | 88 | freshness limit | u64, read-only | slots | | 96 | grace period | u64, read-only | slots | -| 120 | last update slot | `slot` | slot offset | +| 120 | last update slot | u64, keep-alive | slot | | 128 | quote atoms per base atom | u128 | × 10^15 | | 144 | base atoms per quote atom | u128 | × 10^15 | | 160 + 24n | sell level n capacity | u64 | base atoms | @@ -100,23 +101,31 @@ Use `fetchBeforeUse: true` so the selected market is loaded into the local VM fr datasource before its bytes are changed. A later override that builds on an earlier one in the same scenario uses `false`, or the re-fetch undoes the earlier write. -## Two rules that prevent misleading scenarios +## Keep-alive (Surfpool handles it) -**1. Keep the quote fresh.** Tessera rejects a quote whose last update is at least the market's -freshness limit old with custom error 65535, so a correct price or depth change can appear to do -nothing. Before that, an ageing quote fills worse; see [How a quote ages](#how-a-quote-ages). Apply -`tessera-freshness` with `last_update_slot: 0` alongside every price, depth or curve change, and -schedule it again, with `fetchBeforeUse: false`, at least every 4 slots where a quote is needed. +On mainnet the maker republishes each market's quote every slot or two. Each publication writes the +slot (offset 120) and clears the depth swaps have used since the last one (offsets 0 and 8). Nobody +runs the maker against a surfnet, so Surfpool republishes the quote every slot +([keep-alive](../../README.md#keep-alive)): the quote stays 0 slots old, and every slot starts with +the full ladder. Swaps in one slot still use up the ladder as on mainnet; the next slot gives it back. +There is nothing to schedule. -**2. Change a ladder as a whole.** The stored ladder has a different number of enabled levels on +Every template keeps the market it writes quoting. Keep-alive starts in the slot the override plays +and runs until the network is reset. + +## A rule that prevents misleading scenarios + +**Change a ladder as a whole.** The stored ladder has a different number of enabled levels on each market and side, and the maker can pull a side at any moment. Read the selected market account first, scale every enabled level on the side you stress by one ratio, and keep factors descending. ## How a quote ages -A quote younger than the market's grace period (offset 96, 5 slots on the featured markets) fills -at the formula. From then on each slot lowers the fill by a growing amount, in both directions, -until the quote rejects at its freshness limit. Measured on SOL / USDC: +Keep-alive keeps a market a scenario overrides 0 slots old. A market no override names is not +republished, and ages like this. A quote younger than the market's grace period (offset 96, 5 slots +on the featured markets) fills at the formula. From then on each slot lowers the fill by a growing +amount, in both directions, until the quote rejects at its freshness limit (offset 88). Measured on +SOL / USDC: | Slots since the update | Fill | | ---------------------- | ----------- | @@ -129,8 +138,7 @@ until the quote rejects at its freshness limit. Measured on SOL / USDC: | 15 to 19 | -0.5% (cap) | | 20 | rejected (`65535`) | -cbBTC / USDC loses half as much per slot. Schedule `tessera-freshness` at least every 4 slots for a -stable price. +cbBTC / USDC loses half as much per slot. ## Scenario ideas @@ -141,8 +149,7 @@ Use this to test whether a router or strategy reacts when Tessera's SOL price mo 1. Choose **SOL / USDC** in `tessera-price`. 2. Set both price fields from the formula. $100 per SOL is `100000000000000` and `10000000000000000`. -3. Add `tessera-freshness` with `last_update_slot: 0`. -4. Compare both swap directions before and after. Doubling the price doubles a sell's output and +3. Compare both swap directions before and after. Doubling the price doubles a sell's output and halves a buy's. ### Maker widens one side @@ -152,7 +159,7 @@ Use this to test a maker that still quotes but pays less in one direction. 1. Choose the market in `tessera-curve`. 2. Multiply all twenty sell factors by one ratio to make selling base worse, or the buy factors to make buying base worse. The other side is unaffected. -3. Keep the quote fresh and compare equal-size swaps in both directions. +3. Compare equal-size swaps in both directions. ### Thin liquidity for large orders @@ -162,15 +169,6 @@ Use this to test order splitting when Tessera's depth drops. 2. Multiply every enabled capacity on one side by one ratio, for example 10%. 3. Swap a small and a large amount. The small fill is unchanged; the large one gets worse. -### Stale maker - -Use this to test fallback routing when Tessera stops updating. - -1. Choose the market in `tessera-freshness`. -2. Set `last_update_slot` to minus the market's freshness limit (the u64 at bytes 88..96), for - example `-20` on SOL / USDC. -3. Confirm both directions fail with custom error 65535 and that one slot younger still fills. - ### Maker pulls all liquidity 1. Apply `tessera-halt` with both fields `0`. @@ -180,8 +178,9 @@ Use this to test fallback routing when Tessera stops updating. Use this to test a router's slippage limit when Tessera reprices after the router quoted it. -1. Add `tessera-freshness` with `last_update_slot: 0` at the first slot, so the stored price quotes. -2. Two slots later, add `tessera-price` 1% lower in both directions and `tessera-freshness` again. +1. Add `tessera-price` at the first slot with the stored price, so keep-alive keeps the market + quoting. +2. Two slots later, add `tessera-price` 1% lower in both directions. 3. Quote a swap in the first slot and fill it after the move. The fill pays 1% less, and a tight slippage limit must reject it. @@ -190,7 +189,7 @@ Use this to test a router's slippage limit when Tessera reprices after the route Use this to test an arbitrage bot across Tessera and an AMM pool. 1. Read the SOL / USDC price of an AMM pool, for example Orca Whirlpool. -2. Set Tessera's SOL / USDC price 2% above it with `tessera-price` and keep the quote fresh. +2. Set Tessera's SOL / USDC price 2% above it with `tessera-price`. 3. Buying SOL on the AMM and selling it into Tessera should clear both venues' fees. # Recipes @@ -206,27 +205,6 @@ base_atoms_per_quote_atom_x1e15: "10000000000000000" Set both fields. Offset 128 alone moves only sells and offset 144 alone moves only buys, so a single-field write creates a one-sided price. -## Keep the quote current - -```text -template: tessera-freshness -last_update_slot: 0 -``` - -A fresh quote fills at the formula for its grace period and is rejected at its freshness limit. -Schedule the template again, with `fetchBeforeUse: false`, at least every 4 slots where a quote is -needed. - -## Make the quote stale - -```text -template: tessera-freshness -last_update_slot: -20 # the SOL / USDC freshness limit is 20 slots -``` - -The boundary is exclusive: `-19` still fills in the slot it lands, `-20` rejects, and every later -slot ages the quote by one more. Do not schedule a fresh override after it. - ## Reduce depth ```text @@ -263,7 +241,7 @@ Tessera fills swaps only through a router. A direct call must carry the DFlow se `8xeaWCsJYxRoudEZGJWURdfrtFhLYZz9b4iHJnW5tb3d` as a signer. To send one on a local surfnet: 1. Start surfpool with `--skip-signature-verification`, so the sentinel needs no key. -2. Play the scenario. Studio pauses the clock, so the quote stays fresh until Complete. +2. Play the scenario. Keep-alive keeps the quote fresh. 3. Simulate the swap before sending it. On a fresh surfnet the send otherwise fails with "Failed to fetch accounts from remote". @@ -279,13 +257,12 @@ one per mint, and the USDC vault is shared by every USDC market. | Symptom | Fix | | ----------------------------------------------------- | ------------------------------------------------------------------------------------- | -| `Custom(65535)` after a price, depth or curve change | The quote is stale. Add `tessera-freshness` with `last_update_slot: 0` in that slot | +| `Custom(65535)` on a market you did not override | Expected: nothing republishes a market no override names, so it went stale | | `Custom(65535)` on a market you did not halt | The maker pulled that side upstream; every level on it is disabled | | `Custom(8)` | A curve factor is not lower than the level before it; scale all factors by one ratio | | `Custom(7)` | A curve factor is `1000000` or more; factors stay below it | -| A fill lands below the formula without an error | The quote is past its grace period; refresh it with `tessera-freshness` | +| A second swap in one slot fills worse than the first | Not a bug: swaps use up the ladder; the next slot's republication gives it back | | Only one direction repriced | Set both price fields; 128 prices sells and 144 prices buys | | A depth change has no visible effect | The fill was smaller than the first level; use a larger swap | | A price change lands on the wrong account | No owner or size check exists on raw writes; pick a featured market or check that a typed address is a Tessera market account | | `buy_levels_enabled: 1` re-enabled maker-disabled levels | Only 0 is supported; 1 makes the program quote levels the maker had pulled | -| A stale override stops rejecting | A later `tessera-freshness` with a non-negative offset refreshed it; remove it | diff --git a/crates/core/src/scenarios/protocols/tessera/v1/keep-alive.yaml b/crates/core/src/scenarios/protocols/tessera/v1/keep-alive.yaml new file mode 100644 index 000000000..f28c75d78 --- /dev/null +++ b/crates/core/src/scenarios/protocols/tessera/v1/keep-alive.yaml @@ -0,0 +1,33 @@ +protocol: Tessera +version: v1 +account_type: MarketState + +raw_layout: true + +templates: + - id: tessera-quote-publication + name: Quote publication + description: The maker republishing a market's quote + idl_account_name: MarketState + address: + type: pubkey + properties: + - path: last_update_slot + offset: 120 + encoding: u64 + description: >- + Slot the quote was published in. A quote younger than the market's grace period (offset + 96) fills at the price formula, an older one fills worse, and one as old as the market's + limit (offset 88) rejects with custom error 65535. + - path: buy_depth_used + offset: 0 + encoding: u64 + description: >- + Quote atoms buys have taken from the buy ladder since the last publication. Swaps add to + it and a publication clears it, so a later buy starts at the first level again. + - path: sell_depth_used + offset: 8 + encoding: u64 + description: >- + Base atoms sells have taken from the sell ladder since the last publication. Swaps add to + it and a publication clears it. diff --git a/crates/core/src/scenarios/protocols/tessera/v1/overrides.yaml b/crates/core/src/scenarios/protocols/tessera/v1/overrides.yaml index 28ff347bd..dccd45af6 100644 --- a/crates/core/src/scenarios/protocols/tessera/v1/overrides.yaml +++ b/crates/core/src/scenarios/protocols/tessera/v1/overrides.yaml @@ -9,6 +9,11 @@ tags: - prop-amm - swap +keep_alive: + - template: tessera-quote-publication + address: { type: override } + values: { last_update_slot: $slot, buy_depth_used: 0, sell_depth_used: 0 } + llm_context: | FINDING THE MARKET WHEN THE USER NAMES A PAIR OR STUDIO DOES NOT LIST IT: 1. Resolve both token symbols with get_token_address, both calls at once; each result also @@ -55,9 +60,9 @@ templates: Base atoms paid per quote atom, times 10^15. Prices quote-to-base buys; the integer floor of 10^30 divided by quote_atoms_per_base_atom_x1e15. llm_context: | - PRECONDITION - THE QUOTE MUST BE FRESH. Tessera rejects a quote whose last update is at least - the market's freshness limit old with custom error 65535 (0xffff), so a correct price can - appear to do nothing. Also apply tessera-freshness with last_update_slot 0 in the same slot. + THE QUOTE STAYS CURRENT BY ITSELF. From the slot this override plays, Surfpool republishes this + market's quote every slot, as the maker does on mainnet, so this price keeps filling at the + formula in later slots and every slot starts with the full ladder. Tessera stores one price per direction in raw atoms. Offset 128 alone moves base-to-quote sells, offset 144 alone moves quote-to-base buys, so set both as one invariant. Take @@ -74,7 +79,7 @@ templates: sell output = floor(base_in * quote_atoms_per_base_atom_x1e15 * sell_level_0_factor / 10^21) buy output = floor(quote_in * base_atoms_per_quote_atom_x1e15 * buy_level_0_factor / 10^21) Factors are in millionths and always below 1000000. The formula holds for a quote younger than - its grace period (see tessera-freshness) and with neutral quote-start configs. The five 12-byte quote-start configs + its grace period, which keep-alive keeps it, and with neutral quote-start configs. The five 12-byte quote-start configs at market bytes 1136..1196 can lower a fill or make it skip leading levels. Which one applies depends on how many slots ago the config account BAT1Ndpu5gbLTp2AZkSXP79LJBZfCH4B3zGhi6LtvdhK was updated; a surfnet never updates it, so after about 300 slots the last config applies. @@ -88,46 +93,6 @@ templates: quote_atoms_per_base_atom_x1e15: "1000000000000000000" base_atoms_per_quote_atom_x1e15: "1000000000000" - - id: tessera-freshness - name: Override Quote Freshness - description: Keep a Tessera quote current or age it past the market's freshness limit - idl_account_name: MarketState - address: - type: pubkey - properties: - - path: last_update_slot - offset: 120 - encoding: - slot: - lead: 0 - label: Last-update offset - description: >- - Relative to the slot where the override materializes; 0 means updated now, a negative - value ages the quote by that many slots. - llm_context: | - This one template covers both a fresh and a stale quote. The stored word is an absolute slot; - the value is an offset from the slot where the override materializes, clamped at zero. - - Tessera rejects a quote whose age is at least the market's own limit, a u64 at market bytes - 88..96. The boundary is exclusive: last_update_slot -(limit - 1) still fills in the slot it - materializes, -limit rejects both swap directions with custom error 65535 (0xffff), and every - later slot ages the quote by one more. - - AGE: a quote younger than the market's grace period, the u64 at market bytes 96..104 (5 slots - on the featured markets), fills at the price formula. From the grace period on, each slot - lowers the fill by a growing amount, both directions. Measured on SOL / USDC: -50 ppm at 5 - slots, -200 at 6, -800 at 8, -1800 at 10, -3200 at 12, -5000 (a 0.5% cap) at 15 to 19, and - rejected at its 20-slot limit. cbBTC / USDC loses half as much per slot. For a stable price, - schedule this template again at least every 4 slots. - - HOW TO USE: - 1. For a fresh quote set last_update_slot to 0 - 2. For a stale quote set it to -10000, past every market's limit; use minus the limit only to - land on the boundary, e.g. -20 on a 20-slot market - 3. A fresh quote fills at the formula for its grace period and is rejected at its limit; - schedule this template again with fetchBeforeUse: false at least every 4 slots where a - quote is needed, and never after a stale override you want to keep stale - - id: tessera-depth name: Override Depth description: Change how much Tessera fills at each level of its sell and buy ladders @@ -176,8 +141,9 @@ templates: - { path: buy_level_18_amount, offset: 1072, encoding: u64, label: "Buy level 19 capacity", description: "Capacity of this level in input-token atoms; scale it, and keep it nonzero where the maker quotes." } - { path: buy_level_19_amount, offset: 1096, encoding: u64, label: "Buy level 20 capacity", description: "Capacity of this level in input-token atoms; scale it, and keep it nonzero where the maker quotes." } llm_context: | - PRECONDITION - THE QUOTE MUST BE FRESH. Apply tessera-freshness with last_update_slot 0, - otherwise the swap rejects with custom error 65535 and the new depth is never used. + THE QUOTE STAYS CURRENT BY ITSELF. From the slot this override plays, Surfpool republishes this + market's quote every slot, so this depth keeps filling in later slots. Swaps in one slot use up + the ladder; the next slot starts with the full ladder again, as after a maker publication. Each side is a ladder of twenty 24-byte levels: a u64 capacity at +0, a u64 output factor at +8 and a u8 enabled flag at +16. The sell ladder starts at 160 and fills base-to-quote sells @@ -246,8 +212,8 @@ templates: - { path: buy_level_18_factor, offset: 1080, encoding: u64, label: "Buy level 19 output factor", description: "Output factor of this level in millionths; must be lower than the previous level's factor." } - { path: buy_level_19_factor, offset: 1104, encoding: u64, label: "Buy level 20 output factor", description: "Output factor of this level in millionths; must be lower than the previous level's factor." } llm_context: | - PRECONDITION - THE QUOTE MUST BE FRESH. Apply tessera-freshness with last_update_slot 0, - otherwise the swap rejects with custom error 65535 and the new curve is never used. + THE QUOTE STAYS CURRENT BY ITSELF. From the slot this override plays, Surfpool republishes this + market's quote every slot, so this curve keeps filling in later slots. The factor multiplies the directional price: output = input * price * factor / 10^21. Factors are in millionths and must stay below 1000000; 1000000 or more rejects with custom error 7, and diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index 1884c8702..eb302d256 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -51,6 +51,7 @@ pub const KAMINO_LIQUIDITY_OVERRIDES_CONTENT: &str = include_str!("./protocols/kamino/liquidity/v1/overrides.yaml"); pub const TESSERA_OVERRIDES_CONTENT: &str = include_str!("./protocols/tessera/v1/overrides.yaml"); +pub const TESSERA_KEEP_ALIVE_CONTENT: &str = include_str!("./protocols/tessera/v1/keep-alive.yaml"); pub const DRIFT_V2_IDL_CONTENT: &str = include_str!("./protocols/drift/v2/idl.json"); pub const DRIFT_V2_OVERRIDES_CONTENT: &str = include_str!("./protocols/drift/v2/overrides.yaml"); @@ -282,6 +283,7 @@ impl TemplateRegistry { pub fn load_tessera_overrides(&mut self) { self.load_raw_layout_overrides(TESSERA_OVERRIDES_CONTENT, "tessera"); + self.load_keep_alive(None, TESSERA_KEEP_ALIVE_CONTENT, "tessera"); } pub fn load_drift_overrides(&mut self) { @@ -748,12 +750,12 @@ templates: // Pyth (1) + Jupiter (1) + Raydium CLMM (1) + Raydium AMM v4 (4) + Drift (4) + Meteora (2) // + Kamino (Lend 17, Scope 3, Farms 5, Swap 2, Vault 5, Liquidity 4 = 36) - // + Whirlpool (6) + SPL Token (2) + Pump (2) + PumpSwap (3) + Tessera (5) + Phoenix Eternal (19) - // = 86 + // + Whirlpool (6) + SPL Token (2) + Pump (2) + PumpSwap (3) + Tessera (4) + Phoenix Eternal (19) + // = 85 assert_eq!( registry.count(), - 86, - "Registry should load 86 templates total" + 85, + "Registry should load 85 templates total" ); assert!(registry.contains("pyth-price-feed-v2")); @@ -825,7 +827,10 @@ templates: assert!(registry.contains("pump-amm-canonical-pool")); assert!(registry.contains("pump-amm-global-config")); assert!(registry.contains("tessera-price")); - assert!(registry.contains("tessera-freshness")); + assert!( + !registry.contains("tessera-freshness"), + "keep-alive republishes the Tessera quote" + ); assert!(registry.contains("tessera-depth")); assert!(registry.contains("tessera-curve")); assert!(registry.contains("tessera-halt")); @@ -1314,8 +1319,8 @@ templates: [] let tessera_templates = registry.by_protocol("Tessera"); assert_eq!( tessera_templates.len(), - 5, - "Should have 5 Tessera templates" + 4, + "Should have 4 Tessera templates" ); let phoenix_templates = registry.by_protocol("Phoenix Eternal"); @@ -2058,7 +2063,6 @@ templates: [] let mut checked = 0; for id in [ "tessera-price", - "tessera-freshness", "tessera-depth", "tessera-curve", "tessera-halt", @@ -2087,7 +2091,7 @@ templates: [] } } assert_eq!( - checked, 85, + checked, 84, "every shipped Tessera property must be checked" ); } @@ -2096,7 +2100,7 @@ templates: [] fn tessera_templates_require_caller_selected_accounts() { let registry = TemplateRegistry::new(); let templates = registry.by_protocol("Tessera"); - assert_eq!(templates.len(), 5); + assert_eq!(templates.len(), 4); for template in templates { let id = &template.id; assert_eq!( @@ -2114,6 +2118,15 @@ templates: [] ), "{id} must say how to find its account on the program" ); + let [import] = template.keep_alive.as_slice() else { + panic!("{id} must keep its market quoting"); + }; + assert_eq!(import.template, "tessera-quote-publication"); + assert_eq!( + import.address, + surfpool_types::KeepAliveAddress::Override, + "{id}" + ); } } } diff --git a/crates/core/src/tests/tessera/mod.rs b/crates/core/src/tests/tessera/mod.rs index 4242f7840..e4e62cf81 100644 --- a/crates/core/src/tests/tessera/mod.rs +++ b/crates/core/src/tests/tessera/mod.rs @@ -16,10 +16,10 @@ use solana_program_runtime::{ }; use solana_pubkey::Pubkey; use solana_signer::Signer; -use surfpool_types::{AccountAddress, OverrideInstance, Scenario}; +use surfpool_types::{AccountAddress, KeepAliveClock, OverrideInstance, Scenario}; use crate::{ - scenarios::TemplateRegistry, + scenarios::{TemplateRegistry, template_registry}, surfnet::{GetAccountResult, remote::SurfnetRemoteClient, svm::SurfnetSvm}, tests::helpers::diff_indices, }; @@ -266,6 +266,18 @@ fn swap( route: Route, market_data: Vec, ) -> Result { + swap_and_market(fixture, market, amount_in, direction, route, market_data).map(|(out, _)| out) +} + +/// The swap's output and the market account as the swap left it. +fn swap_and_market( + fixture: &TesseraFixture, + market: &MarketFixture, + amount_in: u64, + direction: u8, + route: Route, + market_data: Vec, +) -> Result<(u64, Vec), String> { let spec = market.spec; let mut market_account = market.market.clone(); market_account.data = market_data; @@ -386,9 +398,12 @@ fn swap( transaction.signatures[0] = taker.sign_message(&transaction.message.serialize()); svm.send_transaction(transaction) .map_err(|e| format!("{:?}", e.err))?; - Ok(read_u64( - &svm.get_account(&destination).expect("destination").data, - 64, + Ok(( + read_u64( + &svm.get_account(&destination).expect("destination").data, + 64, + ), + svm.get_account(&spec.address).expect("market").data, )) } @@ -417,6 +432,26 @@ fn apply_raw(id: &str, data: &[u8], values: &[(String, serde_json::Value)], slot .unwrap_or_else(|e| panic!("{id}: {e}")) } +/// What keep-alive writes to a market republished in `slot`: tessera-price's shipped import. +fn tessera_keep_alive(market: &[u8], slot: u64) -> Vec { + let registry = template_registry(); + let import = registry + .get("tessera-price") + .and_then(|template| template.keep_alive.first()) + .expect("tessera-price keeps its market quoting"); + let values = import + .values_at(&KeepAliveClock { + slot, + unix_time_ms: 0, + }) + .expect("keep-alive values"); + registry + .keep_alive_template(&import.template) + .expect("keep-alive template") + .materialize_raw_layout(market, &values, slot) + .unwrap_or_else(|e| panic!("{}: {e}", import.template)) +} + fn values( pairs: [(&str, serde_json::Value); N], ) -> Vec<(String, serde_json::Value)> { @@ -586,7 +621,7 @@ async fn tessera_featured_markets_match_their_market_accounts() { async fn tessera_templates_write_only_proven_bytes_on_every_market() { let registry = TemplateRegistry::new(); let all_templates = registry.by_protocol("Tessera"); - assert_eq!(all_templates.len(), 5); + assert_eq!(all_templates.len(), 4); let addresses = ALL_MARKETS.map(pubkey); let markets = fetch(&addresses).await; @@ -594,11 +629,6 @@ async fn tessera_templates_write_only_proven_bytes_on_every_market() { let data = &account.data; assert_eq!(account.owner, PROGRAM, "{address}"); assert_eq!(data.len(), MARKET_SIZE, "{address}"); - assert!( - read_u64(data, 88) < 10_000, - "{address} freshness limit must stay below the -10000 the guidance uses for a stale quote" - ); - for template in &all_templates { assert_eq!( apply_raw(&template.id, data, &[], 0), @@ -630,6 +660,18 @@ async fn tessera_templates_write_only_proven_bytes_on_every_market() { ); assert_eq!(read_u128(&priced, 128), 1_000_000_000_000_000); assert_eq!(read_u128(&priced, 144), 1_000_000_000_000_000); + let republished = tessera_keep_alive(data, 1_000_000); + assert!( + diff_indices(data, &republished) + .iter() + .all(|i| (0..16).contains(i) || (120..128).contains(i)), + "{address} escaped the keep-alive write set" + ); + assert_eq!(read_u64(&republished, 120), 1_000_000); + assert_eq!( + (read_u64(&republished, 0), read_u64(&republished, 8)), + (0, 0) + ); let halted = apply_raw( "tessera-halt", data, @@ -655,18 +697,15 @@ async fn tessera_scenario_materializes_once_through_surfnet_svm() { let target = AccountAddress::Pubkey(market_key.to_string()); let price = price_values(100_000_000_000_000); - let mut scenario = Scenario::new("Tessera SOL at 100".into(), "price and freshness".into()); + // Keep-alive republishes the quote from the slot the price plays: no freshness override. + let mut scenario = Scenario::new("Tessera SOL at 100".into(), "price".into()); scenario.add_override( - OverrideInstance::new("tessera-price".into(), 0, target.clone()) + OverrideInstance::new("tessera-price".into(), 0, target) .with_values(price.iter().cloned().collect()), ); - scenario.add_override( - OverrideInstance::new("tessera-freshness".into(), 0, target).with_values(HashMap::from([ - ("last_update_slot".to_string(), serde_json::json!(0)), - ])), - ); let (mut svm, _events, _geyser) = SurfnetSvm::default(); + svm.set_latest_absolute_slot(BASE_SLOT); svm.inner .set_account(market_key, fixture.sol.market.clone()) .unwrap(); @@ -677,13 +716,17 @@ async fn tessera_scenario_materializes_once_through_surfnet_svm() { let read = |svm: &SurfnetSvm| svm.inner.get_account(&market_key).unwrap().unwrap().data; let materialized = read(&svm); assert_eq!(read_u64(&materialized, 120), BASE_SLOT); + assert_eq!( + (read_u64(&materialized, 0), read_u64(&materialized, 8)), + (0, 0) + ); assert_eq!(read_u128(&materialized, 128), 100_000_000_000_000); assert_eq!(read_u128(&materialized, 144), 10_000_000_000_000_000); assert!( diff_indices(&original, &materialized) .iter() - .all(|i| (120..160).contains(i)), - "materialization escaped the price and freshness write set" + .all(|i| (0..16).contains(i) || (120..160).contains(i)), + "materialization escaped the price and keep-alive write set" ); svm.materialize_overrides_for_slot(&None, BASE_SLOT + 1) @@ -771,37 +814,24 @@ async fn tessera_price_formula_reprices_both_directions() { assert_eq!(u128::from(buy(at_100).unwrap()), expected_buy); } +/// Tessera rejects a quote as old as the market's limit. A republication one slot younger still +/// fills, so keep-alive writing the current slot every slot is what keeps a market quoting. #[tokio::test] -async fn tessera_freshness_boundary_follows_each_market_limit() { +async fn tessera_keep_alive_boundary_follows_each_market_limit() { let mut fixture = fixture().await; set_quote_start(&mut fixture.sol.market.data, 0); pin_ladder(&mut fixture.sol.market.data, SOL_SELL_UNIT, SOL_BUY_UNIT); let sol = &fixture.sol; let upstream_limit = read_u64(&sol.market.data, 88); let slot = clock_slot(sol); - let aged = |data: &[u8], lead: i64| { - apply_raw( - "tessera-freshness", - data, - &values([("last_update_slot", serde_json::json!(lead))]), - slot, - ) - }; for limit in [upstream_limit, 25, 55] { let mut configured = sol.market.data.clone(); write_u64(&mut configured, 88, limit); - let fresh = aged(&configured, 0); + let fresh = tessera_keep_alive(&configured, slot); assert_eq!(read_u64(&fresh, 120), slot); - assert!( - diff_indices(&configured, &fresh) - .iter() - .all(|i| (120..128).contains(i)) - ); - let lead = -(limit as i64); - let just_fresh = aged(&configured, lead + 1); - let stale = aged(&configured, lead); - assert_eq!(read_u64(&stale, 120), slot - limit); + let just_fresh = tessera_keep_alive(&configured, slot - (limit - 1)); + let stale = tessera_keep_alive(&configured, slot - limit); for (direction, amount) in [(1, SOL_SELL), (0, SOL_BUY)] { let run = |data: Vec| swap(&fixture, sol, amount, direction, Route::DFlow, data); assert!(run(fresh.clone()).expect("a fresh quote fills") > 0); @@ -815,6 +845,41 @@ async fn tessera_freshness_boundary_follows_each_market_limit() { } } +/// Every swap adds its input to the side's used depth, so a second equal sale in the same slot fills +/// further down the ladder. A republication clears it, as the maker's does, so the next slot's sale +/// fills like the first. +#[tokio::test] +async fn tessera_keep_alive_restores_the_depth_swaps_use_up() { + let mut fixture = fixture().await; + set_quote_start(&mut fixture.sol.market.data, 0); + pin_ladder(&mut fixture.sol.market.data, SOL_SELL_UNIT, SOL_BUY_UNIT); + let sol = &fixture.sol; + let slot = clock_slot(sol); + let sell = |data: Vec| { + swap_and_market(&fixture, sol, SOL_SELL_UNIT, 1, Route::DFlow, data).expect("sale") + }; + + let (first, after_first) = sell(tessera_keep_alive(&sol.market.data, slot)); + assert_eq!( + read_u64(&after_first, 8), + SOL_SELL_UNIT, + "the sale must add its input to the used sell depth" + ); + let (second, _) = sell(after_first.clone()); + assert!( + second < first, + "a second sale in the same slot must fill lower on the ladder: {second} vs {first}" + ); + + let republished = tessera_keep_alive(&after_first, slot); + assert_eq!(read_u64(&republished, 8), 0); + let (after_republication, _) = sell(republished); + assert_eq!( + after_republication, first, + "after a republication a sale must fill like the first" + ); +} + #[tokio::test] async fn tessera_depth_thins_only_large_fills() { let mut fixture = fixture().await;