From 6743c54bfc0f4943bcae72783c8e03b778c961bc Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 16 Oct 2026 11:21:58 +0300 Subject: [PATCH 01/24] feat(scenarios): add the Pyth Pro receiver price feed template --- crates/core/src/scenarios/README.md | 2 +- .../scenarios/protocols/pyth/pro/v2/idl.json | 130 ++++++++++++++++ .../protocols/pyth/pro/v2/overrides.yaml | 70 +++++++++ crates/core/src/scenarios/registry.rs | 50 +++++- crates/core/src/tests/mod.rs | 2 + crates/core/src/tests/pyth/mod.rs | 143 ++++++++++++++++++ crates/mcp/src/surfpool/mod.rs | 4 +- 7 files changed, 392 insertions(+), 9 deletions(-) create mode 100644 crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json create mode 100644 crates/core/src/scenarios/protocols/pyth/pro/v2/overrides.yaml create mode 100644 crates/core/src/tests/pyth/mod.rs diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 65e2d5683..4579e14d4 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -13,7 +13,7 @@ For Surfpool to understand how to serialize and deserialize account data, it nee Protocols that are natively supported by Surfpool will have their IDLs included by default. **Currently supported protocols:** -- **Pyth v2** - Price oracle with 4 price feed templates (SOL/USD, BTC/USD, ETH/BTC, ETH/USD) +- **Pyth v2** - Price oracle with a price feed template for the default receiver (`pyth-price-feed-v2`) and one for the Pyth Pro-compatible receiver (`pyth-pro-price-feed-v2`) - **Jupiter v6** - DEX aggregator with TokenLedger manipulation template - **Switchboard On-Demand** - On-demand oracle with QuoteAccount override template - **Kamino** – Lending (v1.23.0), Scope oracle, Farms, Swap/LIMO, Earn vaults and Liquidity, across six programs. See [protocols/kamino/README.md](./protocols/kamino/README.md) diff --git a/crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json b/crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json new file mode 100644 index 000000000..36978697a --- /dev/null +++ b/crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json @@ -0,0 +1,130 @@ +{ + "address": "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp", + "metadata": { + "name": "price_feed", + "version": "0.1.0", + "spec": "0.1.0", + "description": "Created with Anchor" + }, + "instructions": [], + "accounts": [ + { + "name": "PriceUpdateV2", + "discriminator": [34, 241, 35, 99, 157, 126, 244, 205] + } + ], + "types": [ + { + "name": "PriceFeedMessage", + "type": { + "kind": "struct", + "fields": [ + { + "name": "feed_id", + "docs": [ + "`FeedId` but avoid the type alias because of compatibility issues with Anchor's `idl-build` feature." + ], + "type": { + "array": ["u8", 32] + } + }, + { + "name": "price", + "type": "i64" + }, + { + "name": "conf", + "type": "u64" + }, + { + "name": "exponent", + "type": "i32" + }, + { + "name": "publish_time", + "docs": ["The timestamp of this price update in seconds"], + "type": "i64" + }, + { + "name": "prev_publish_time", + "docs": [ + "The timestamp of the previous price update. This field is intended to allow users to", + "identify the single unique price update for any moment in time:", + "for any time t, the unique update is the one such that prev_publish_time < t <= publish_time.", + "", + "Note that there may not be such an update while we are migrating to the new message-sending logic,", + "as some price updates on pythnet may not be sent to other chains (because the message-sending", + "logic may not have triggered). We can solve this problem by making the message-sending mandatory", + "(which we can do once publishers have migrated over).", + "", + "Additionally, this field may be equal to publish_time if the message is sent on a slot where", + "where the aggregation was unsuccesful. This problem will go away once all publishers have", + "migrated over to a recent version of pyth-agent." + ], + "type": "i64" + }, + { + "name": "ema_price", + "type": "i64" + }, + { + "name": "ema_conf", + "type": "u64" + } + ] + } + }, + { + "name": "PriceUpdateV2", + "type": { + "kind": "struct", + "fields": [ + { + "name": "write_authority", + "type": "pubkey" + }, + { + "name": "verification_level", + "type": { + "defined": { + "name": "VerificationLevel" + } + } + }, + { + "name": "price_message", + "type": { + "defined": { + "name": "PriceFeedMessage" + } + } + }, + { + "name": "posted_slot", + "type": "u64" + } + ] + } + }, + { + "name": "VerificationLevel", + "type": { + "kind": "enum", + "variants": [ + { + "name": "Partial", + "fields": [ + { + "name": "num_signatures", + "type": "u8" + } + ] + }, + { + "name": "Full" + } + ] + } + } + ] +} diff --git a/crates/core/src/scenarios/protocols/pyth/pro/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/pro/v2/overrides.yaml new file mode 100644 index 000000000..c0c137781 --- /dev/null +++ b/crates/core/src/scenarios/protocols/pyth/pro/v2/overrides.yaml @@ -0,0 +1,70 @@ +protocol: Pyth +version: v2 +account_type: PriceUpdateV2 +idl_file_path: idl.json + +tags: + - oracle + - price-feed + - defi + +templates: + - id: pyth-pro-price-feed-v2 + name: Override Pyth Pro-compatible Price Account + description: Override a price account of the Pyth Pro-compatible receiver, found by address + idl_account_name: PriceUpdateV2 + properties: + - path: price_message.price + label: Price + description: Price as a scaled integer - multiply the USD value by 10^-exponent + - path: price_message.conf + label: Confidence + description: Uncertainty band around the price, in the same scale as price + - path: price_message.exponent + label: Exponent + description: Decimal exponent, normally -8 and -10 on some feeds. Rescales every price field + - path: price_message.publish_time + label: Publish Time + description: Unix seconds of this update, interpreted against the Surfnet clock + - path: price_message.prev_publish_time + label: Previous Publish Time + description: Unix seconds of the preceding update + - path: price_message.ema_price + label: EMA Price + description: Exponential moving average price, in the same scale as price + - path: price_message.ema_conf + label: EMA Confidence + description: Exponential moving average confidence, in the same scale as conf + - path: posted_slot + label: Posted Slot + description: Slot the update was posted at, for consumers that measure freshness in slots + address: + type: pubkey + llm_context: | + FINDING THE PRICE ACCOUNT: + Pyth runs two receivers on Solana with the same feed ids at different addresses, and a + consumer reads only one. This template writes price accounts owned by the Pyth + Pro-compatible receiver rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp; for the default + receiver rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ use pyth-price-feed-v2. + 1. Take the price account from the account that reads it: the consumer's protocol templates + say which field names it. A price account the user gives is used as is. + 2. Read it with getAccountInfo, encoding "jsonParsed". Its owner must be + rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp; price_message.exponent gives the scale. + 3. Put it in the override's account as {"pubkey":""}. + + Set fetchBeforeUse: true to pull the account from upstream first; false only for a later + override that builds on state an earlier override in the same scenario prepared. + + PRICE: price_message.price = usd_price x 10^-exponent, so with exponent -8, $145.00 is + 14500000000. ema_price, conf and ema_conf use the same scale. Move ema_price with price: + consumers use the EMA for some checks and the spot price for others. + + TIME: leave publish_time, prev_publish_time and posted_slot unset. fetchBeforeUse: true + brings the upstream account's current values when the override plays, so the price is as + fresh as upstream's. A time written into the scenario is fixed when the scenario is created + and ages until it plays. To make a price stale on purpose, follow the TIME FIELDS steps of + pyth-price-feed-v2. + + EXAMPLE - "SOL drops to $20" on an account with exponent -8: + price_message.price: 2000000000 + price_message.ema_price: 2000000000 diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index edef806d0..036ed0d89 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -7,6 +7,9 @@ use surfpool_types::{OverrideInstance, OverrideTemplate, YamlOverrideTemplateCol pub const PYTH_V2_IDL_CONTENT: &str = include_str!("./protocols/pyth/v2/idl.json"); pub const PYTH_V2_OVERRIDES_CONTENT: &str = include_str!("./protocols/pyth/v2/overrides.yaml"); +pub const PYTH_PRO_V2_IDL_CONTENT: &str = include_str!("./protocols/pyth/pro/v2/idl.json"); +pub const PYTH_PRO_V2_OVERRIDES_CONTENT: &str = + include_str!("./protocols/pyth/pro/v2/overrides.yaml"); pub const JUPITER_V6_IDL_CONTENT: &str = include_str!("./protocols/jupiter/v6/idl.json"); pub const JUPITER_V6_OVERRIDES_CONTENT: &str = @@ -122,6 +125,11 @@ impl TemplateRegistry { pub fn load_pyth_overrides(&mut self) { self.load_protocol_overrides(PYTH_V2_IDL_CONTENT, PYTH_V2_OVERRIDES_CONTENT, "pyth"); + self.load_protocol_overrides( + PYTH_PRO_V2_IDL_CONTENT, + PYTH_PRO_V2_OVERRIDES_CONTENT, + "pyth", + ); } pub fn load_jupiter_overrides(&mut self) { @@ -604,16 +612,17 @@ mod tests { fn test_registry_loads_all_protocols() { let registry = TemplateRegistry::new(); - // Pyth (1) + Jupiter (1) + Raydium CLMM (1) + Raydium AMM v4 (4) + Drift (4) + Meteora (2) + // Pyth (2) + 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) + Phoenix Eternal (8) = 70 + // + Whirlpool (6) + SPL Token (2) + Pump (2) + PumpSwap (3) + Phoenix Eternal (8) = 71 assert_eq!( registry.count(), - 70, - "Registry should load 70 templates total" + 71, + "Registry should load 71 templates total" ); assert!(registry.contains("pyth-price-feed-v2")); + assert!(registry.contains("pyth-pro-price-feed-v2")); assert!(registry.contains("jupiter-token-ledger-override")); @@ -916,7 +925,7 @@ templates: [] let registry = TemplateRegistry::new(); let pyth_templates = registry.by_protocol("Pyth"); - assert_eq!(pyth_templates.len(), 1, "Should have 1 Pyth template"); + assert_eq!(pyth_templates.len(), 2, "Should have 2 Pyth templates"); let jupiter_templates = registry.by_protocol("Jupiter"); assert_eq!(jupiter_templates.len(), 1, "Should have 1 Jupiter template"); @@ -1025,8 +1034,8 @@ templates: [] let oracle_templates = registry.by_tags(&[vec!["oracle".to_string()]].concat()); assert_eq!( oracle_templates.len(), - 4, - "Should find 4 oracle templates (Pyth + 3 Kamino Scope)" + 5, + "Should find 5 oracle templates (2 Pyth + 3 Kamino Scope)" ); let rewards_templates = registry.by_tags(&[vec!["rewards".to_string()]].concat()); @@ -1074,6 +1083,7 @@ templates: [] assert!(ids.contains(&"raydium-amm-custom".to_string())); assert!(ids.contains(&"jupiter-token-ledger-override".to_string())); assert!(ids.contains(&"pyth-price-feed-v2".to_string())); + assert!(ids.contains(&"pyth-pro-price-feed-v2".to_string())); assert!(ids.contains(&"meteora-dlmm-sol-usdc".to_string())); assert!(ids.contains(&"kamino-reserve-state".to_string())); assert!(ids.contains(&"kamino-reserve-config".to_string())); @@ -1296,6 +1306,32 @@ templates: [] ); } + #[test] + fn test_pyth_pro_price_feed_takes_a_caller_selected_account() { + let registry = TemplateRegistry::new(); + let pro = registry.get("pyth-pro-price-feed-v2").unwrap(); + + assert_eq!( + pro.idl().address, + "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp" + ); + assert_eq!( + pro.address, + AccountAddress::Pubkey(String::new()), + "the price account must be chosen by the caller" + ); + assert!( + pro.constants.is_empty(), + "the template must not embed a feed catalog" + ); + assert!( + pro.llm_context.as_deref().is_some_and( + |context| context.contains("rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp") + ), + "the template must say which receiver owns its accounts" + ); + } + #[test] fn test_get_pda_seed_references() { use surfpool_types::AccountAddress; diff --git a/crates/core/src/tests/mod.rs b/crates/core/src/tests/mod.rs index f43607e64..bc35c2748 100644 --- a/crates/core/src/tests/mod.rs +++ b/crates/core/src/tests/mod.rs @@ -7,4 +7,6 @@ pub mod phoenix; pub mod plugin; #[cfg(feature = "integration-tests")] pub mod pump; +#[cfg(feature = "integration-tests")] +pub mod pyth; pub mod simnet_events; diff --git a/crates/core/src/tests/pyth/mod.rs b/crates/core/src/tests/pyth/mod.rs new file mode 100644 index 000000000..fab851e14 --- /dev/null +++ b/crates/core/src/tests/pyth/mod.rs @@ -0,0 +1,143 @@ +//! Pyth integration tests. +//! +//! These fetch a real price feed from mainnet, so they need a network connection and are compiled +//! only behind a feature: +//! +//! ```text +//! cargo test -p surfpool-core --features integration-tests pyth +//! ``` +//! +//! Set `SURFPOOL_TEST_RPC_URL` to use a private endpoint if the public one rate-limits. + +use std::collections::HashMap; + +use solana_commitment_config::CommitmentConfig; +use solana_pubkey::Pubkey; +use surfpool_types::{AccountAddress, OverrideInstance, Scenario}; + +use crate::{ + scenarios::TemplateRegistry, + surfnet::{ + GetAccountResult, locker::SurfnetSvmLocker, remote::SurfnetRemoteClient, svm::SurfnetSvm, + }, +}; + +const RPC_URL_ENV: &str = "SURFPOOL_TEST_RPC_URL"; +const DEFAULT_RPC_URL: &str = "https://api.mainnet-beta.solana.com"; + +const PYTH_PRO_COMPATIBLE_RECEIVER: &str = "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp"; +const PRO_SOL_USD_FEED: &str = "7AviUf9nL62mcxNbQGKm4nKDQnPjswo6c5MX4D57HmyE"; +const SOL_USD_FEED_ID: &str = "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"; + +async fn fetch(address: &str) -> solana_account::Account { + let client = SurfnetRemoteClient::new( + std::env::var(RPC_URL_ENV).unwrap_or_else(|_| DEFAULT_RPC_URL.to_string()), + ); + match client + .get_multiple_accounts( + &[Pubkey::from_str_const(address)], + CommitmentConfig::confirmed(), + ) + .await + .unwrap_or_else(|e| panic!("failed to fetch {address} from mainnet: {e}")) + .remove(0) + { + GetAccountResult::FoundAccount(_, account, _) + | GetAccountResult::FoundCoupledAccount((_, account), _, _) => account, + GetAccountResult::None(_) => { + panic!("{address} no longer exists on mainnet; the test needs a new address") + } + } +} + +/// Runs the template through the scenario path on the account the caller names, so the IDL comes +/// from the account's owner. +#[tokio::test(flavor = "multi_thread")] +async fn pro_price_feed_touches_only_price_fields() { + let live = fetch(PRO_SOL_USD_FEED).await; + assert_eq!(live.owner.to_string(), PYTH_PRO_COMPATIBLE_RECEIVER); + // A Partial verification level shifts every offset below by one. + assert_eq!(live.data[40], 1, "verification level should be Full"); + let feed_id = hex::decode(SOL_USD_FEED_ID.trim_start_matches("0x")).unwrap(); + assert_eq!(&live.data[41..73], feed_id.as_slice(), "feed_id at 41"); + + let registry = TemplateRegistry::new(); + let template = registry.get("pyth-pro-price-feed-v2").unwrap(); + + // (path, offset, width, value). Each value differs from the live one, so a skipped write fails. + let rows: [(&str, usize, usize, i64); 8] = [ + ("price_message.price", 73, 8, 9_100_000_000_000), + ("price_message.conf", 81, 8, 500_000_000), + ("price_message.exponent", 89, 4, -10), + ("price_message.publish_time", 93, 8, 1_800_000_000), + ("price_message.prev_publish_time", 101, 8, 1_799_999_940), + ("price_message.ema_price", 109, 8, 9_050_000_000_000), + ("price_message.ema_conf", 117, 8, 450_000_000), + ("posted_slot", 125, 8, 500_000_000), + ]; + for path in template.property_paths() { + assert!( + rows.iter().any(|(row, ..)| *row == path), + "{path} has no row" + ); + } + + let target = Pubkey::from_str_const(PRO_SOL_USD_FEED); + let (svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); + let identity = svm + .get_forged_account_data(&target, &live.data, template.idl(), &HashMap::new()) + .unwrap(); + assert_eq!(identity, live.data, "no-op round trip changed bytes"); + + let values: HashMap = rows + .iter() + .map(|(path, _, _, value)| (path.to_string(), serde_json::json!(value))) + .collect(); + + let locker = SurfnetSvmLocker::new(svm); + locker.with_svm_writer(|svm| svm.set_account(&target, live.clone()).unwrap()); + let mut scenario = Scenario::new( + "Pyth Pro-compatible SOL/USD".to_string(), + "Move every price field of the live feed".to_string(), + ); + scenario.add_override( + OverrideInstance::new( + template.id.clone(), + 0, + AccountAddress::Pubkey(PRO_SOL_USD_FEED.to_string()), + ) + .with_values(values), + ); + locker.register_scenario(scenario, Some(100)).unwrap(); + locker + .materialize_overrides_for_slot(&None, 100) + .await + .unwrap(); + + let forged = locker + .with_svm_reader(|svm| svm.get_account(&target)) + .unwrap() + .expect("the feed should exist"); + assert_eq!(forged.owner, live.owner); + assert_eq!(forged.lamports, live.lamports); + assert_eq!(forged.data.len(), live.data.len()); + + let diffs: Vec = (0..live.data.len()) + .filter(|&i| forged.data[i] != live.data[i]) + .collect(); + let written = |i: &usize| { + rows.iter() + .any(|(_, offset, width, _)| (*offset..offset + width).contains(i)) + }; + assert!( + !diffs.is_empty() && diffs.iter().all(written), + "changed {diffs:?}" + ); + for (path, offset, width, value) in rows { + assert_eq!( + &forged.data[offset..offset + width], + &value.to_le_bytes()[..width], + "{path}" + ); + } +} diff --git a/crates/mcp/src/surfpool/mod.rs b/crates/mcp/src/surfpool/mod.rs index 9e23884ce..8653ca44b 100644 --- a/crates/mcp/src/surfpool/mod.rs +++ b/crates/mcp/src/surfpool/mod.rs @@ -198,7 +198,9 @@ pub struct CallSurfnetRpcParams { A list of all the RPC methods available can be found at str:///rpc_endpoints" )] pub method: String, - #[schemars(description = "The parameters to pass to the RPC method")] + #[schemars( + description = "The parameters to pass to the RPC method. Wrap every value at every depth by its type: a string as {\"String\":\"...\"}, a whole number as {\"Number\":5}, a boolean as {\"Bool\":true}, a list as {\"Array\":[...]} and an object as {\"Object\":{\"key\":}}; object keys stay plain. Example for getProgramAccounts with a filter: [{\"String\":\"\"},{\"Object\":{\"encoding\":{\"String\":\"base64\"},\"filters\":{\"Array\":[{\"Object\":{\"memcmp\":{\"Object\":{\"offset\":{\"Number\":0},\"bytes\":{\"String\":\"\"}}}}}]}}}]" + )] pub params: Vec, } From 69b0a9e0551893b3d32a18d5315543ed2c9989ee Mon Sep 17 00:00:00 2001 From: failfmi Date: Wed, 7 Oct 2026 13:43:14 +0300 Subject: [PATCH 02/24] ci: claude code review --- .github/workflows/claude-review.yml | 141 ++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 .github/workflows/claude-review.yml diff --git a/.github/workflows/claude-review.yml b/.github/workflows/claude-review.yml new file mode 100644 index 000000000..844c44d68 --- /dev/null +++ b/.github/workflows/claude-review.yml @@ -0,0 +1,141 @@ +name: Perform a code review when a pull request is created. +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + claude: + # Skip drafts, and skip fork PRs: on `pull_request` they don't get the + # ANTHROPIC_API_KEY secret, so the review would only fail. + if: >- + !github.event.pull_request.draft && + github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + structured_output: ${{ steps.run_claude.outputs.structured_output }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + # Explicitly check out the PR's merge commit. + ref: refs/pull/${{ github.event.pull_request.number }}/merge + persist-credentials: false + + - name: Pre-fetch base and head refs for the PR + env: + PR_BASE_REF: ${{ github.event.pull_request.base.ref }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + # Pass GitHub expressions through env and quote shell expansions. + git fetch --no-tags origin \ + "$PR_BASE_REF" \ + "+refs/pull/$PR_NUMBER/head" + + # If you want Claude to build and run code, install any dependencies that + # need to be downloaded before the "Run Claude" step, and add the commands + # it may run to --allowedTools below (e.g. "Bash(npm test:*)"). Any tool + # not listed there is denied. + + - name: Run Claude + id: run_claude + uses: anthropics/claude-code-action@86d88e619d8e6caf07b5c3944dd14f441c533718 # v1.0.243 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + # Use this job's read-only token instead of the Claude GitHub App, + # which needs `id-token: write` and would get write access. + github_token: ${{ github.token }} + prompt: | + This is PR #${{ github.event.pull_request.number }} for ${{ github.repository }}. + + Review ONLY the changes introduced by the PR, so consider: + git log --oneline ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} + git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} + + Suggest any improvements, potential bugs, or issues. + Be concise and specific in your feedback. + + Return your review in two parts: + - `summary`: a short Markdown overview of the PR and your overall assessment. + - `comments`: one entry per specific issue, anchored to the line it concerns. + `path` is relative to the repository root. `line` is the line number in + the PR head version of the file (${{ github.event.pull_request.head.sha }}), + and must be a line shown in the diff above. The working tree is the merge + commit, so its line numbers can differ; check them with + `git show ${{ github.event.pull_request.head.sha }}:`. + Put issues that don't belong to a single line in `summary` instead. + + Pull request title and body: + ---- + ${{ github.event.pull_request.title }} + ${{ github.event.pull_request.body }} + claude_args: | + --allowedTools "Read,Grep,Glob,Bash(git log:*),Bash(git diff:*),Bash(git show:*)" + --json-schema '{ + "type": "object", + "properties": { + "summary": { + "type": "string", + "description": "Overall review as Markdown, posted as the review body." + }, + "comments": { + "type": "array", + "description": "Inline comments, each anchored to one line of the PR diff.", + "items": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "File path relative to the repository root." }, + "line": { "type": "integer", "minimum": 1, "description": "Line number in the PR head version of the file. Must be within the diff." }, + "body": { "type": "string", "description": "The comment, as Markdown." } + }, + "required": ["path", "line", "body"] + } + } + }, + "required": ["summary", "comments"] + }' + + post_feedback: + runs-on: ubuntu-latest + needs: claude + if: needs.claude.outputs.structured_output != '' + permissions: + issues: write + pull-requests: write + steps: + - name: Report Claude feedback + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 + env: + CLAUDE_STRUCTURED_OUTPUT: ${{ needs.claude.outputs.structured_output }} + with: + github-token: ${{ github.token }} + script: | + const { summary = '', comments = [] } = JSON.parse(process.env.CLAUDE_STRUCTURED_OUTPUT); + const pr = context.payload.pull_request; + if (!summary.trim() && comments.length === 0) { + core.info('Claude returned an empty review; nothing to post.'); + return; + } + + try { + await github.rest.pulls.createReview({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pr.number, + commit_id: pr.head.sha, + event: 'COMMENT', + body: summary.trim() || 'See inline comments.', + comments: comments.map(({ path, line, body }) => ({ path, line, side: 'RIGHT', body })), + }); + } catch (error) { + // GitHub rejects the whole review if any comment points outside the + // diff. Fall back to a single PR comment so no feedback is lost. + core.warning(`Could not post inline review (${error.message}); posting a plain comment instead.`); + const details = comments.map(({ path, line, body }) => `**\`${path}:${line}\`**\n\n${body}`); + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pr.number, + body: [summary.trim(), ...details].filter(Boolean).join('\n\n---\n\n'), + }); + } From 3dfacb1866c37bb5a8b63f58b9f2a212eb476e02 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 19 Oct 2026 17:18:46 +0300 Subject: [PATCH 03/24] fix(scenarios): name the Pyth Pro collection in its load errors --- crates/core/src/scenarios/registry.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index 036ed0d89..6a1415c78 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -128,7 +128,7 @@ impl TemplateRegistry { self.load_protocol_overrides( PYTH_PRO_V2_IDL_CONTENT, PYTH_PRO_V2_OVERRIDES_CONTENT, - "pyth", + "pyth-pro", ); } From 5891b4e4821cf49556b11cde3ec258918c5286b2 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Thu, 29 Oct 2026 09:24:39 +0200 Subject: [PATCH 04/24] refactor(scenarios): name the receiver template Pyth Core Compatible and bundle its full published IDL --- crates/core/src/scenarios/README.md | 2 +- .../pyth/core-compatible/v2/README.md | 25 + .../pyth/core-compatible/v2/idl.json | 1002 +++++++++++++++++ .../v2/overrides.yaml | 10 +- .../scenarios/protocols/pyth/pro/v2/idl.json | 130 --- crates/core/src/scenarios/registry.rs | 29 +- crates/core/src/tests/pyth/mod.rs | 18 +- 7 files changed, 1057 insertions(+), 159 deletions(-) create mode 100644 crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md create mode 100644 crates/core/src/scenarios/protocols/pyth/core-compatible/v2/idl.json rename crates/core/src/scenarios/protocols/pyth/{pro => core-compatible}/v2/overrides.yaml (91%) delete mode 100644 crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 4579e14d4..8bec29c43 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -13,7 +13,7 @@ For Surfpool to understand how to serialize and deserialize account data, it nee Protocols that are natively supported by Surfpool will have their IDLs included by default. **Currently supported protocols:** -- **Pyth v2** - Price oracle with a price feed template for the default receiver (`pyth-price-feed-v2`) and one for the Pyth Pro-compatible receiver (`pyth-pro-price-feed-v2`) +- **Pyth v2** - Price oracle with a price feed template for the default receiver (`pyth-price-feed-v2`) and one for the Pyth Core Compatible receiver (`pyth-core-compatible-price-feed-v2`) - **Jupiter v6** - DEX aggregator with TokenLedger manipulation template - **Switchboard On-Demand** - On-demand oracle with QuoteAccount override template - **Kamino** – Lending (v1.23.0), Scope oracle, Farms, Swap/LIMO, Earn vaults and Liquidity, across six programs. See [protocols/kamino/README.md](./protocols/kamino/README.md) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md new file mode 100644 index 000000000..7d4b203b9 --- /dev/null +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md @@ -0,0 +1,25 @@ +# Pyth Core Compatible + +Pyth runs two price receivers on Solana, both deployments of the `pyth_solana_receiver` program, as +listed on [Pyth's Solana contract addresses](https://docs.pyth.network/price-feeds/contract-addresses/solana): + +| Receiver | Program | Template | +|---|---|---| +| Pyth Core | `rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ` | `pyth-price-feed-v2` | +| Pyth Core Compatible | `rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` | `pyth-core-compatible-price-feed-v2` | + +They hold separate price accounts for the same feeds, and a consumer reads the accounts of one of +them. Take the price account from the consumer's own account that names it. + +# IDL + +`idl.json` is the IDL the program publishes in its Anchor IDL account +`raeUSn8gguFWVFs4iw3YathYM3mdb95W5Bfiu3tqE7F` (`pyth_solana_receiver` 0.2.1, legacy format, sha256 +`9ec4718f66a71fc524ecdd533770ca5a8a3984f8e1fb603f01f5e31ff0ab0caa`), converted with +`anchor idl convert --program-id rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` (anchor-cli 0.31.1, +output sha256 `29ab79ef705a3429b3ced2b1222e1b5efdcd4b40fed547177d31c16ebd8473fc`). + +One change is made before the conversion: the account names `priceUpdateV2` and `twapUpdate` are +written `PriceUpdateV2` and `TwapUpdate`, as the program's Rust types are named. Anchor derives an +account's discriminator from its name, and only the capitalized names give the discriminator the +live price accounts carry. diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/idl.json b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/idl.json new file mode 100644 index 000000000..c9b8013ae --- /dev/null +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/idl.json @@ -0,0 +1,1002 @@ +{ + "address": "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp", + "metadata": { + "name": "pyth_solana_receiver", + "version": "0.2.1", + "spec": "0.1.0" + }, + "instructions": [ + { + "name": "initialize", + "discriminator": [ + 175, + 175, + 109, + 31, + 13, + 152, + 155, + 237 + ], + "accounts": [ + { + "name": "payer", + "writable": true, + "signer": true + }, + { + "name": "config", + "writable": true + }, + { + "name": "system_program" + } + ], + "args": [ + { + "name": "initial_config", + "type": { + "defined": { + "name": "Config" + } + } + } + ] + }, + { + "name": "request_governance_authority_transfer", + "discriminator": [ + 92, + 18, + 67, + 156, + 27, + 151, + 183, + 224 + ], + "accounts": [ + { + "name": "payer", + "signer": true + }, + { + "name": "config", + "writable": true + } + ], + "args": [ + { + "name": "target_governance_authority", + "type": "pubkey" + } + ] + }, + { + "name": "cancel_governance_authority_transfer", + "discriminator": [ + 39, + 93, + 70, + 137, + 137, + 90, + 248, + 154 + ], + "accounts": [ + { + "name": "payer", + "signer": true + }, + { + "name": "config", + "writable": true + } + ], + "args": [] + }, + { + "name": "accept_governance_authority_transfer", + "discriminator": [ + 254, + 39, + 222, + 79, + 64, + 217, + 205, + 127 + ], + "accounts": [ + { + "name": "payer", + "signer": true + }, + { + "name": "config", + "writable": true + } + ], + "args": [] + }, + { + "name": "set_data_sources", + "discriminator": [ + 107, + 73, + 15, + 119, + 195, + 116, + 91, + 210 + ], + "accounts": [ + { + "name": "payer", + "signer": true + }, + { + "name": "config", + "writable": true + } + ], + "args": [ + { + "name": "valid_data_sources", + "type": { + "vec": { + "defined": { + "name": "DataSource" + } + } + } + } + ] + }, + { + "name": "set_fee", + "discriminator": [ + 18, + 154, + 24, + 18, + 237, + 214, + 19, + 80 + ], + "accounts": [ + { + "name": "payer", + "signer": true + }, + { + "name": "config", + "writable": true + } + ], + "args": [ + { + "name": "single_update_fee_in_lamports", + "type": "u64" + } + ] + }, + { + "name": "set_wormhole_address", + "discriminator": [ + 154, + 174, + 252, + 157, + 91, + 215, + 179, + 156 + ], + "accounts": [ + { + "name": "payer", + "signer": true + }, + { + "name": "config", + "writable": true + } + ], + "args": [ + { + "name": "wormhole", + "type": "pubkey" + } + ] + }, + { + "name": "set_minimum_signatures", + "discriminator": [ + 5, + 210, + 206, + 124, + 43, + 68, + 104, + 149 + ], + "accounts": [ + { + "name": "payer", + "signer": true + }, + { + "name": "config", + "writable": true + } + ], + "args": [ + { + "name": "minimum_signatures", + "type": "u8" + } + ] + }, + { + "name": "post_update_atomic", + "docs": [ + "Post a price update using a VAA and a MerklePriceUpdate.", + "This function allows you to post a price update in a single transaction.", + "Compared to `post_update`, it only checks whatever signatures are present in the provided VAA and doesn't fail if the number of signatures is lower than the Wormhole quorum of two thirds of the guardians.", + "The number of signatures that were in the VAA is stored in the `VerificationLevel` of the `PriceUpdateV2` account.", + "", + "We recommend using `post_update_atomic` with 5 signatures. This is close to the maximum signatures you can verify in one transaction without exceeding the transaction size limit.", + "", + "# Warning", + "", + "Using partially verified price updates is dangerous, as it lowers the threshold of guardians that need to collude to produce a malicious price update." + ], + "discriminator": [ + 49, + 172, + 84, + 192, + 175, + 180, + 52, + 234 + ], + "accounts": [ + { + "name": "payer", + "writable": true, + "signer": true + }, + { + "name": "guardian_set", + "docs": [ + "Instead we do the same steps in deserialize_guardian_set_checked." + ] + }, + { + "name": "config" + }, + { + "name": "treasury", + "writable": true + }, + { + "name": "price_update_account", + "docs": [ + "The constraint is such that either the price_update_account is uninitialized or the write_authority is the write_authority.", + "Pubkey::default() is the SystemProgram on Solana and it can't sign so it's impossible that price_update_account.write_authority == Pubkey::default() once the account is initialized" + ], + "writable": true, + "signer": true + }, + { + "name": "system_program" + }, + { + "name": "write_authority", + "signer": true + } + ], + "args": [ + { + "name": "params", + "type": { + "defined": { + "name": "PostUpdateAtomicParams" + } + } + } + ] + }, + { + "name": "post_update", + "docs": [ + "Post a price update using an encoded_vaa account and a MerklePriceUpdate calldata.", + "This should be called after the client has already verified the Vaa via the Wormhole contract.", + "Check out target_chains/solana/cli/src/main.rs for an example of how to do this." + ], + "discriminator": [ + 133, + 95, + 207, + 175, + 11, + 79, + 118, + 44 + ], + "accounts": [ + { + "name": "payer", + "writable": true, + "signer": true + }, + { + "name": "encoded_vaa" + }, + { + "name": "config" + }, + { + "name": "treasury", + "writable": true + }, + { + "name": "price_update_account", + "docs": [ + "The constraint is such that either the price_update_account is uninitialized or the write_authority is the write_authority.", + "Pubkey::default() is the SystemProgram on Solana and it can't sign so it's impossible that price_update_account.write_authority == Pubkey::default() once the account is initialized" + ], + "writable": true, + "signer": true + }, + { + "name": "system_program" + }, + { + "name": "write_authority", + "signer": true + } + ], + "args": [ + { + "name": "params", + "type": { + "defined": { + "name": "PostUpdateParams" + } + } + } + ] + }, + { + "name": "post_twap_update", + "docs": [ + "Post a TWAP (time weighted average price) update for a given time window.", + "This should be called after the client has already verified the VAAs via the Wormhole contract.", + "Check out target_chains/solana/cli/src/main.rs for an example of how to do this." + ], + "discriminator": [ + 232, + 176, + 212, + 105, + 69, + 121, + 18, + 30 + ], + "accounts": [ + { + "name": "payer", + "writable": true, + "signer": true + }, + { + "name": "start_encoded_vaa" + }, + { + "name": "end_encoded_vaa" + }, + { + "name": "config" + }, + { + "name": "treasury", + "writable": true + }, + { + "name": "twap_update_account", + "docs": [ + "The constraint is such that either the price_update_account is uninitialized or the write_authority is the write_authority.", + "Pubkey::default() is the SystemProgram on Solana and it can't sign so it's impossible that price_update_account.write_authority == Pubkey::default() once the account is initialized" + ], + "writable": true, + "signer": true + }, + { + "name": "system_program" + }, + { + "name": "write_authority", + "signer": true + } + ], + "args": [ + { + "name": "params", + "type": { + "defined": { + "name": "PostTwapUpdateParams" + } + } + } + ] + }, + { + "name": "reclaim_rent", + "discriminator": [ + 218, + 200, + 19, + 197, + 227, + 89, + 192, + 22 + ], + "accounts": [ + { + "name": "payer", + "writable": true, + "signer": true + }, + { + "name": "price_update_account", + "writable": true + } + ], + "args": [] + }, + { + "name": "reclaim_twap_rent", + "discriminator": [ + 84, + 3, + 32, + 238, + 108, + 217, + 135, + 39 + ], + "accounts": [ + { + "name": "payer", + "writable": true, + "signer": true + }, + { + "name": "twap_update_account", + "writable": true + } + ], + "args": [] + } + ], + "accounts": [ + { + "name": "Config", + "discriminator": [ + 155, + 12, + 170, + 224, + 30, + 250, + 204, + 130 + ] + }, + { + "name": "PriceUpdateV2", + "discriminator": [ + 34, + 241, + 35, + 99, + 157, + 126, + 244, + 205 + ] + }, + { + "name": "TwapUpdate", + "discriminator": [ + 104, + 192, + 188, + 72, + 246, + 166, + 12, + 81 + ] + } + ], + "errors": [ + { + "code": 6000, + "name": "InvalidWormholeMessage", + "msg": "Received an invalid wormhole message" + }, + { + "code": 6001, + "name": "DeserializeMessageFailed", + "msg": "An error occurred when deserializing the message" + }, + { + "code": 6002, + "name": "InvalidPriceUpdate", + "msg": "Received an invalid price update" + }, + { + "code": 6003, + "name": "UnsupportedMessageType", + "msg": "This type of message is not supported currently" + }, + { + "code": 6004, + "name": "InvalidDataSource", + "msg": "The tuple emitter chain, emitter doesn't match one of the valid data sources." + }, + { + "code": 6005, + "name": "InsufficientFunds", + "msg": "Funds are insufficient to pay the receiving fee" + }, + { + "code": 6006, + "name": "FeedIdMismatch", + "msg": "Cannot calculate TWAP, end slot must be greater than start slot" + }, + { + "code": 6007, + "name": "ExponentMismatch", + "msg": "The start and end messages must have the same feed ID" + }, + { + "code": 6008, + "name": "InvalidTwapSlots", + "msg": "The start and end messages must have the same exponent" + }, + { + "code": 6009, + "name": "InvalidTwapStartMessage", + "msg": "Start message is not the first update for its timestamp" + }, + { + "code": 6010, + "name": "InvalidTwapEndMessage", + "msg": "End message is not the first update for its timestamp" + }, + { + "code": 6011, + "name": "TwapCalculationOverflow", + "msg": "Overflow in TWAP calculation" + }, + { + "code": 6012, + "name": "WrongWriteAuthority", + "msg": "This signer can't write to price update account" + }, + { + "code": 6013, + "name": "WrongVaaOwner", + "msg": "The posted VAA account has the wrong owner." + }, + { + "code": 6014, + "name": "DeserializeVaaFailed", + "msg": "An error occurred when deserializing the VAA." + }, + { + "code": 6015, + "name": "InsufficientGuardianSignatures", + "msg": "The number of guardian signatures is below the minimum" + }, + { + "code": 6016, + "name": "InvalidVaaVersion", + "msg": "Invalid VAA version" + }, + { + "code": 6017, + "name": "GuardianSetMismatch", + "msg": "Guardian set version in the VAA doesn't match the guardian set passed" + }, + { + "code": 6018, + "name": "InvalidGuardianOrder", + "msg": "Guardian signature indices must be increasing" + }, + { + "code": 6019, + "name": "InvalidGuardianIndex", + "msg": "Guardian index exceeds the number of guardians in the set" + }, + { + "code": 6020, + "name": "InvalidSignature", + "msg": "A VAA signature is invalid" + }, + { + "code": 6021, + "name": "InvalidGuardianKeyRecovery", + "msg": "The recovered guardian public key doesn't match the guardian set" + }, + { + "code": 6022, + "name": "WrongGuardianSetOwner", + "msg": "The guardian set account is owned by the wrong program" + }, + { + "code": 6023, + "name": "InvalidGuardianSetPda", + "msg": "The Guardian Set account doesn't match the PDA derivation" + }, + { + "code": 6024, + "name": "GuardianSetExpired", + "msg": "The Guardian Set is expired" + }, + { + "code": 6025, + "name": "GovernanceAuthorityMismatch", + "msg": "The signer is not authorized to perform this governance action" + }, + { + "code": 6026, + "name": "TargetGovernanceAuthorityMismatch", + "msg": "The signer is not authorized to accept the governance authority" + }, + { + "code": 6027, + "name": "NonexistentGovernanceAuthorityTransferRequest", + "msg": "The governance authority needs to request a transfer first" + }, + { + "code": 6028, + "name": "ZeroMinimumSignatures", + "msg": "The minimum number of signatures should be at least 1" + } + ], + "types": [ + { + "name": "PriceFeedMessage", + "type": { + "kind": "struct", + "fields": [ + { + "name": "feed_id", + "type": { + "array": [ + "u8", + 32 + ] + } + }, + { + "name": "price", + "type": "i64" + }, + { + "name": "conf", + "type": "u64" + }, + { + "name": "exponent", + "type": "i32" + }, + { + "name": "publish_time", + "type": "i64" + }, + { + "name": "prev_publish_time", + "type": "i64" + }, + { + "name": "ema_price", + "type": "i64" + }, + { + "name": "ema_conf", + "type": "u64" + } + ] + } + }, + { + "name": "TwapPrice", + "docs": [ + "The time weighted average price & conf for a feed over the window [start_time, end_time].", + "This type is used to persist the calculated TWAP in TwapUpdate accounts on Solana." + ], + "type": { + "kind": "struct", + "fields": [ + { + "name": "feed_id", + "type": { + "array": [ + "u8", + 32 + ] + } + }, + { + "name": "start_time", + "type": "i64" + }, + { + "name": "end_time", + "type": "i64" + }, + { + "name": "price", + "type": "i64" + }, + { + "name": "conf", + "type": "u64" + }, + { + "name": "exponent", + "type": "i32" + }, + { + "name": "down_slots_ratio", + "docs": [ + "Ratio out of 1_000_000, where a value of 1_000_000 represents", + "all slots were missed and 0 represents no slots were missed." + ], + "type": "u32" + } + ] + } + }, + { + "name": "MerklePriceUpdate", + "type": { + "kind": "struct", + "fields": [ + { + "name": "message", + "type": "bytes" + }, + { + "name": "proof", + "type": { + "vec": { + "array": [ + "u8", + 20 + ] + } + } + } + ] + } + }, + { + "name": "DataSource", + "type": { + "kind": "struct", + "fields": [ + { + "name": "chain", + "type": "u16" + }, + { + "name": "emitter", + "type": "pubkey" + } + ] + } + }, + { + "name": "PostUpdateAtomicParams", + "type": { + "kind": "struct", + "fields": [ + { + "name": "vaa", + "type": "bytes" + }, + { + "name": "merkle_price_update", + "type": { + "defined": { + "name": "MerklePriceUpdate" + } + } + }, + { + "name": "treasury_id", + "type": "u8" + } + ] + } + }, + { + "name": "PostUpdateParams", + "type": { + "kind": "struct", + "fields": [ + { + "name": "merkle_price_update", + "type": { + "defined": { + "name": "MerklePriceUpdate" + } + } + }, + { + "name": "treasury_id", + "type": "u8" + } + ] + } + }, + { + "name": "PostTwapUpdateParams", + "type": { + "kind": "struct", + "fields": [ + { + "name": "start_merkle_price_update", + "type": { + "defined": { + "name": "MerklePriceUpdate" + } + } + }, + { + "name": "end_merkle_price_update", + "type": { + "defined": { + "name": "MerklePriceUpdate" + } + } + }, + { + "name": "treasury_id", + "type": "u8" + } + ] + } + }, + { + "name": "VerificationLevel", + "docs": [ + "* This enum represents how many guardian signatures were checked for a Pythnet price update\n * If full, guardian quorum has been attained\n * If partial, at least config.minimum signatures have been verified, but in the case config.minimum_signatures changes in the future we also include the number of signatures that were checked" + ], + "type": { + "kind": "enum", + "variants": [ + { + "name": "Partial", + "fields": [ + { + "name": "num_signatures", + "type": "u8" + } + ] + }, + { + "name": "Full" + } + ] + } + }, + { + "name": "Config", + "type": { + "kind": "struct", + "fields": [ + { + "name": "governance_authority", + "type": "pubkey" + }, + { + "name": "target_governance_authority", + "type": { + "option": "pubkey" + } + }, + { + "name": "wormhole", + "type": "pubkey" + }, + { + "name": "valid_data_sources", + "type": { + "vec": { + "defined": { + "name": "DataSource" + } + } + } + }, + { + "name": "single_update_fee_in_lamports", + "type": "u64" + }, + { + "name": "minimum_signatures", + "type": "u8" + } + ] + } + }, + { + "name": "PriceUpdateV2", + "type": { + "kind": "struct", + "fields": [ + { + "name": "write_authority", + "type": "pubkey" + }, + { + "name": "verification_level", + "type": { + "defined": { + "name": "VerificationLevel" + } + } + }, + { + "name": "price_message", + "type": { + "defined": { + "name": "PriceFeedMessage" + } + } + }, + { + "name": "posted_slot", + "type": "u64" + } + ] + } + }, + { + "name": "TwapUpdate", + "type": { + "kind": "struct", + "fields": [ + { + "name": "write_authority", + "type": "pubkey" + }, + { + "name": "twap", + "type": { + "defined": { + "name": "TwapPrice" + } + } + } + ] + } + } + ] +} \ No newline at end of file diff --git a/crates/core/src/scenarios/protocols/pyth/pro/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml similarity index 91% rename from crates/core/src/scenarios/protocols/pyth/pro/v2/overrides.yaml rename to crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index c0c137781..f784499f7 100644 --- a/crates/core/src/scenarios/protocols/pyth/pro/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -9,9 +9,9 @@ tags: - defi templates: - - id: pyth-pro-price-feed-v2 - name: Override Pyth Pro-compatible Price Account - description: Override a price account of the Pyth Pro-compatible receiver, found by address + - id: pyth-core-compatible-price-feed-v2 + name: Override Pyth Core Compatible Price Account + description: Override a price account of the Pyth Core Compatible receiver, found by address idl_account_name: PriceUpdateV2 properties: - path: price_message.price @@ -43,8 +43,8 @@ templates: llm_context: | FINDING THE PRICE ACCOUNT: Pyth runs two receivers on Solana with the same feed ids at different addresses, and a - consumer reads only one. This template writes price accounts owned by the Pyth - Pro-compatible receiver rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp; for the default + consumer reads only one. This template writes price accounts owned by the Pyth Core + Compatible receiver rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp; for the Pyth Core receiver rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ use pyth-price-feed-v2. 1. Take the price account from the account that reads it: the consumer's protocol templates say which field names it. A price account the user gives is used as is. diff --git a/crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json b/crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json deleted file mode 100644 index 36978697a..000000000 --- a/crates/core/src/scenarios/protocols/pyth/pro/v2/idl.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "address": "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp", - "metadata": { - "name": "price_feed", - "version": "0.1.0", - "spec": "0.1.0", - "description": "Created with Anchor" - }, - "instructions": [], - "accounts": [ - { - "name": "PriceUpdateV2", - "discriminator": [34, 241, 35, 99, 157, 126, 244, 205] - } - ], - "types": [ - { - "name": "PriceFeedMessage", - "type": { - "kind": "struct", - "fields": [ - { - "name": "feed_id", - "docs": [ - "`FeedId` but avoid the type alias because of compatibility issues with Anchor's `idl-build` feature." - ], - "type": { - "array": ["u8", 32] - } - }, - { - "name": "price", - "type": "i64" - }, - { - "name": "conf", - "type": "u64" - }, - { - "name": "exponent", - "type": "i32" - }, - { - "name": "publish_time", - "docs": ["The timestamp of this price update in seconds"], - "type": "i64" - }, - { - "name": "prev_publish_time", - "docs": [ - "The timestamp of the previous price update. This field is intended to allow users to", - "identify the single unique price update for any moment in time:", - "for any time t, the unique update is the one such that prev_publish_time < t <= publish_time.", - "", - "Note that there may not be such an update while we are migrating to the new message-sending logic,", - "as some price updates on pythnet may not be sent to other chains (because the message-sending", - "logic may not have triggered). We can solve this problem by making the message-sending mandatory", - "(which we can do once publishers have migrated over).", - "", - "Additionally, this field may be equal to publish_time if the message is sent on a slot where", - "where the aggregation was unsuccesful. This problem will go away once all publishers have", - "migrated over to a recent version of pyth-agent." - ], - "type": "i64" - }, - { - "name": "ema_price", - "type": "i64" - }, - { - "name": "ema_conf", - "type": "u64" - } - ] - } - }, - { - "name": "PriceUpdateV2", - "type": { - "kind": "struct", - "fields": [ - { - "name": "write_authority", - "type": "pubkey" - }, - { - "name": "verification_level", - "type": { - "defined": { - "name": "VerificationLevel" - } - } - }, - { - "name": "price_message", - "type": { - "defined": { - "name": "PriceFeedMessage" - } - } - }, - { - "name": "posted_slot", - "type": "u64" - } - ] - } - }, - { - "name": "VerificationLevel", - "type": { - "kind": "enum", - "variants": [ - { - "name": "Partial", - "fields": [ - { - "name": "num_signatures", - "type": "u8" - } - ] - }, - { - "name": "Full" - } - ] - } - } - ] -} diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index 6a1415c78..04162faf9 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -7,9 +7,10 @@ use surfpool_types::{OverrideInstance, OverrideTemplate, YamlOverrideTemplateCol pub const PYTH_V2_IDL_CONTENT: &str = include_str!("./protocols/pyth/v2/idl.json"); pub const PYTH_V2_OVERRIDES_CONTENT: &str = include_str!("./protocols/pyth/v2/overrides.yaml"); -pub const PYTH_PRO_V2_IDL_CONTENT: &str = include_str!("./protocols/pyth/pro/v2/idl.json"); -pub const PYTH_PRO_V2_OVERRIDES_CONTENT: &str = - include_str!("./protocols/pyth/pro/v2/overrides.yaml"); +pub const PYTH_CORE_COMPATIBLE_V2_IDL_CONTENT: &str = + include_str!("./protocols/pyth/core-compatible/v2/idl.json"); +pub const PYTH_CORE_COMPATIBLE_V2_OVERRIDES_CONTENT: &str = + include_str!("./protocols/pyth/core-compatible/v2/overrides.yaml"); pub const JUPITER_V6_IDL_CONTENT: &str = include_str!("./protocols/jupiter/v6/idl.json"); pub const JUPITER_V6_OVERRIDES_CONTENT: &str = @@ -126,9 +127,9 @@ impl TemplateRegistry { pub fn load_pyth_overrides(&mut self) { self.load_protocol_overrides(PYTH_V2_IDL_CONTENT, PYTH_V2_OVERRIDES_CONTENT, "pyth"); self.load_protocol_overrides( - PYTH_PRO_V2_IDL_CONTENT, - PYTH_PRO_V2_OVERRIDES_CONTENT, - "pyth-pro", + PYTH_CORE_COMPATIBLE_V2_IDL_CONTENT, + PYTH_CORE_COMPATIBLE_V2_OVERRIDES_CONTENT, + "pyth-core-compatible", ); } @@ -622,7 +623,7 @@ mod tests { ); assert!(registry.contains("pyth-price-feed-v2")); - assert!(registry.contains("pyth-pro-price-feed-v2")); + assert!(registry.contains("pyth-core-compatible-price-feed-v2")); assert!(registry.contains("jupiter-token-ledger-override")); @@ -1083,7 +1084,7 @@ templates: [] assert!(ids.contains(&"raydium-amm-custom".to_string())); assert!(ids.contains(&"jupiter-token-ledger-override".to_string())); assert!(ids.contains(&"pyth-price-feed-v2".to_string())); - assert!(ids.contains(&"pyth-pro-price-feed-v2".to_string())); + assert!(ids.contains(&"pyth-core-compatible-price-feed-v2".to_string())); assert!(ids.contains(&"meteora-dlmm-sol-usdc".to_string())); assert!(ids.contains(&"kamino-reserve-state".to_string())); assert!(ids.contains(&"kamino-reserve-config".to_string())); @@ -1307,25 +1308,25 @@ templates: [] } #[test] - fn test_pyth_pro_price_feed_takes_a_caller_selected_account() { + fn test_pyth_core_compatible_price_feed_takes_a_caller_selected_account() { let registry = TemplateRegistry::new(); - let pro = registry.get("pyth-pro-price-feed-v2").unwrap(); + let template = registry.get("pyth-core-compatible-price-feed-v2").unwrap(); assert_eq!( - pro.idl().address, + template.idl().address, "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp" ); assert_eq!( - pro.address, + template.address, AccountAddress::Pubkey(String::new()), "the price account must be chosen by the caller" ); assert!( - pro.constants.is_empty(), + template.constants.is_empty(), "the template must not embed a feed catalog" ); assert!( - pro.llm_context.as_deref().is_some_and( + template.llm_context.as_deref().is_some_and( |context| context.contains("rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp") ), "the template must say which receiver owns its accounts" diff --git a/crates/core/src/tests/pyth/mod.rs b/crates/core/src/tests/pyth/mod.rs index fab851e14..0390d8c6b 100644 --- a/crates/core/src/tests/pyth/mod.rs +++ b/crates/core/src/tests/pyth/mod.rs @@ -25,8 +25,8 @@ use crate::{ const RPC_URL_ENV: &str = "SURFPOOL_TEST_RPC_URL"; const DEFAULT_RPC_URL: &str = "https://api.mainnet-beta.solana.com"; -const PYTH_PRO_COMPATIBLE_RECEIVER: &str = "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp"; -const PRO_SOL_USD_FEED: &str = "7AviUf9nL62mcxNbQGKm4nKDQnPjswo6c5MX4D57HmyE"; +const PYTH_CORE_COMPATIBLE_RECEIVER: &str = "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp"; +const CORE_COMPATIBLE_SOL_USD_FEED: &str = "7AviUf9nL62mcxNbQGKm4nKDQnPjswo6c5MX4D57HmyE"; const SOL_USD_FEED_ID: &str = "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"; async fn fetch(address: &str) -> solana_account::Account { @@ -53,16 +53,16 @@ async fn fetch(address: &str) -> solana_account::Account { /// Runs the template through the scenario path on the account the caller names, so the IDL comes /// from the account's owner. #[tokio::test(flavor = "multi_thread")] -async fn pro_price_feed_touches_only_price_fields() { - let live = fetch(PRO_SOL_USD_FEED).await; - assert_eq!(live.owner.to_string(), PYTH_PRO_COMPATIBLE_RECEIVER); +async fn core_compatible_price_feed_touches_only_price_fields() { + let live = fetch(CORE_COMPATIBLE_SOL_USD_FEED).await; + assert_eq!(live.owner.to_string(), PYTH_CORE_COMPATIBLE_RECEIVER); // A Partial verification level shifts every offset below by one. assert_eq!(live.data[40], 1, "verification level should be Full"); let feed_id = hex::decode(SOL_USD_FEED_ID.trim_start_matches("0x")).unwrap(); assert_eq!(&live.data[41..73], feed_id.as_slice(), "feed_id at 41"); let registry = TemplateRegistry::new(); - let template = registry.get("pyth-pro-price-feed-v2").unwrap(); + let template = registry.get("pyth-core-compatible-price-feed-v2").unwrap(); // (path, offset, width, value). Each value differs from the live one, so a skipped write fails. let rows: [(&str, usize, usize, i64); 8] = [ @@ -82,7 +82,7 @@ async fn pro_price_feed_touches_only_price_fields() { ); } - let target = Pubkey::from_str_const(PRO_SOL_USD_FEED); + let target = Pubkey::from_str_const(CORE_COMPATIBLE_SOL_USD_FEED); let (svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); let identity = svm .get_forged_account_data(&target, &live.data, template.idl(), &HashMap::new()) @@ -97,14 +97,14 @@ async fn pro_price_feed_touches_only_price_fields() { let locker = SurfnetSvmLocker::new(svm); locker.with_svm_writer(|svm| svm.set_account(&target, live.clone()).unwrap()); let mut scenario = Scenario::new( - "Pyth Pro-compatible SOL/USD".to_string(), + "Pyth Core Compatible SOL/USD".to_string(), "Move every price field of the live feed".to_string(), ); scenario.add_override( OverrideInstance::new( template.id.clone(), 0, - AccountAddress::Pubkey(PRO_SOL_USD_FEED.to_string()), + AccountAddress::Pubkey(CORE_COMPATIBLE_SOL_USD_FEED.to_string()), ) .with_values(values), ); From 691c52900aa852d1ffb5c96b8dcde23b241efb8a Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Thu, 29 Oct 2026 09:47:33 +0200 Subject: [PATCH 05/24] fix(scenarios): scale the confidence with the price in the Pyth Core Compatible template guidance --- .../protocols/pyth/core-compatible/v2/overrides.yaml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index f784499f7..ed69f3e33 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -57,7 +57,9 @@ templates: PRICE: price_message.price = usd_price x 10^-exponent, so with exponent -8, $145.00 is 14500000000. ema_price, conf and ema_conf use the same scale. Move ema_price with price: - consumers use the EMA for some checks and the spot price for others. + consumers use the EMA for some checks and the spot price for others. Scale conf and ema_conf + by the same factor as the price: consumers refuse a price whose confidence is too wide a share + of it, so a large drop that keeps the live conf can be refused. TIME: leave publish_time, prev_publish_time and posted_slot unset. fetchBeforeUse: true brings the upstream account's current values when the override plays, so the price is as @@ -65,6 +67,8 @@ templates: and ages until it plays. To make a price stale on purpose, follow the TIME FIELDS steps of pyth-price-feed-v2. - EXAMPLE - "SOL drops to $20" on an account with exponent -8: + EXAMPLE - "SOL drops to $20" on an account with exponent -8, live price p and ema_price q: price_message.price: 2000000000 price_message.ema_price: 2000000000 + price_message.conf: the live conf x 2000000000 / p + price_message.ema_conf: the live ema_conf x 2000000000 / q From 0df95762f3cb50f63926f3fb9fc31d5cfbab2eaf Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 3 Nov 2026 08:53:27 +0200 Subject: [PATCH 06/24] docs(scenarios): call rec5 the Pyth Core receiver --- crates/core/src/scenarios/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 8bec29c43..f80a45b11 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -13,7 +13,7 @@ For Surfpool to understand how to serialize and deserialize account data, it nee Protocols that are natively supported by Surfpool will have their IDLs included by default. **Currently supported protocols:** -- **Pyth v2** - Price oracle with a price feed template for the default receiver (`pyth-price-feed-v2`) and one for the Pyth Core Compatible receiver (`pyth-core-compatible-price-feed-v2`) +- **Pyth v2** - Price oracle with a price feed template for the Pyth Core receiver (`pyth-price-feed-v2`) and one for the Pyth Core Compatible receiver (`pyth-core-compatible-price-feed-v2`) - **Jupiter v6** - DEX aggregator with TokenLedger manipulation template - **Switchboard On-Demand** - On-demand oracle with QuoteAccount override template - **Kamino** – Lending (v1.23.0), Scope oracle, Farms, Swap/LIMO, Earn vaults and Liquidity, across six programs. See [protocols/kamino/README.md](./protocols/kamino/README.md) From 8886ae14ee27836da1ae8ec024ecc68ac18178a2 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 11:10:29 +0200 Subject: [PATCH 07/24] feat(scenarios): keep Pyth price feeds published with keep-alive --- crates/core/src/scenarios/README.md | 2 +- .../pyth/core-compatible/v2/README.md | 9 ++ .../pyth/core-compatible/v2/keep-alive.yaml | 17 +++ .../pyth/core-compatible/v2/overrides.yaml | 16 ++- .../protocols/pyth/v2/keep-alive.yaml | 17 +++ .../protocols/pyth/v2/overrides.yaml | 37 +++--- crates/core/src/scenarios/registry.rs | 46 ++++++++ crates/core/src/tests/pyth/mod.rs | 111 +++++++++++++++++- 8 files changed, 222 insertions(+), 33 deletions(-) create mode 100644 crates/core/src/scenarios/protocols/pyth/core-compatible/v2/keep-alive.yaml create mode 100644 crates/core/src/scenarios/protocols/pyth/v2/keep-alive.yaml diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 80de68afc..9dab570e4 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -13,7 +13,7 @@ For Surfpool to understand how to serialize and deserialize account data, it nee Protocols that are natively supported by Surfpool will have their IDLs included by default. **Currently supported protocols:** -- **Pyth v2** - Price oracle with a price feed template for the Pyth Core receiver (`pyth-price-feed-v2`) and one for the Pyth Core Compatible receiver (`pyth-core-compatible-price-feed-v2`) +- **Pyth v2** - Price oracle with a price feed template for the Pyth Core receiver (`pyth-price-feed-v2`) and one for the Pyth Core Compatible receiver (`pyth-core-compatible-price-feed-v2`); both keep the price they write published - **Jupiter v6** - DEX aggregator with TokenLedger manipulation template - **Switchboard On-Demand** - On-demand oracle with QuoteAccount override template - **Kamino** – Lending (v1.23.0), Scope oracle, Farms, Swap/LIMO, Earn vaults and Liquidity, across six programs. See [protocols/kamino/README.md](./protocols/kamino/README.md) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md index 7d4b203b9..fb1111d2c 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md @@ -11,6 +11,15 @@ listed on [Pyth's Solana contract addresses](https://docs.pyth.network/price-fee They hold separate price accounts for the same feeds, and a consumer reads the accounts of one of them. Take the price account from the consumer's own account that names it. +# Keep-alive + +Nobody publishes Pyth prices on a surfnet, so both templates import a +[keep-alive](../../../../README.md#keep-alive): from the slot an override plays until the network +is reset, Surfpool writes the Clock's unix seconds to `price_message.publish_time` and the slot to +`posted_slot` every slot, time travels included. The price, confidence and EMA fields stay as the +scenario wrote them. A price account no override names is not republished and ages against the +Surfnet clock. + # IDL `idl.json` is the IDL the program publishes in its Anchor IDL account diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/keep-alive.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/keep-alive.yaml new file mode 100644 index 000000000..854ba956a --- /dev/null +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/keep-alive.yaml @@ -0,0 +1,17 @@ +protocol: Pyth +version: v2 +account_type: PriceUpdateV2 +idl_file_path: idl.json + +templates: + - id: pyth-core-compatible-price-publication + name: Price publication + description: The Pyth publisher republishing a price + idl_account_name: PriceUpdateV2 + address: + type: pubkey + properties: + - path: price_message.publish_time + description: Unix seconds the price was published at, checked against the Clock + - path: posted_slot + description: Slot the price was posted in, for consumers that measure freshness in slots diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index ed69f3e33..b6a24e88b 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -8,6 +8,11 @@ tags: - price-feed - defi +keep_alive: + - template: pyth-core-compatible-price-publication + address: { type: override } + values: { price_message.publish_time: $unix_s, posted_slot: $slot } + templates: - id: pyth-core-compatible-price-feed-v2 name: Override Pyth Core Compatible Price Account @@ -61,11 +66,12 @@ templates: by the same factor as the price: consumers refuse a price whose confidence is too wide a share of it, so a large drop that keeps the live conf can be refused. - TIME: leave publish_time, prev_publish_time and posted_slot unset. fetchBeforeUse: true - brings the upstream account's current values when the override plays, so the price is as - fresh as upstream's. A time written into the scenario is fixed when the scenario is created - and ages until it plays. To make a price stale on purpose, follow the TIME FIELDS steps of - pyth-price-feed-v2. + THE PRICE STAYS PUBLISHED BY ITSELF. From the slot this override plays until the network is + reset, Surfpool republishes this price account every slot, as the Pyth publisher does on + mainnet: publish_time becomes the Surfnet clock's unix seconds and posted_slot the slot, also + after a time travel. Price, conf and the EMA fields keep the values this override wrote. A + value set for publish_time or posted_slot never takes effect, so leave both unset. A price + account no override names is not republished and ages against the Surfnet clock. EXAMPLE - "SOL drops to $20" on an account with exponent -8, live price p and ema_price q: price_message.price: 2000000000 diff --git a/crates/core/src/scenarios/protocols/pyth/v2/keep-alive.yaml b/crates/core/src/scenarios/protocols/pyth/v2/keep-alive.yaml new file mode 100644 index 000000000..b435dfe68 --- /dev/null +++ b/crates/core/src/scenarios/protocols/pyth/v2/keep-alive.yaml @@ -0,0 +1,17 @@ +protocol: Pyth +version: v2 +account_type: PriceUpdateV2 +idl_file_path: idl.json + +templates: + - id: pyth-price-publication + name: Price publication + description: The Pyth publisher republishing a price + idl_account_name: PriceUpdateV2 + address: + type: pubkey + properties: + - path: price_message.publish_time + description: Unix seconds the price was published at, checked against the Clock + - path: posted_slot + description: Slot the price was posted in, for consumers that measure freshness in slots diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index bdc65802d..a8ac0d6fc 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -9,6 +9,11 @@ tags: - defi - clock-sensitive +keep_alive: + - template: pyth-price-publication + address: { type: override } + values: { price_message.publish_time: $unix_s, posted_slot: $slot } + constants: price_feed: label: Price Feed @@ -255,31 +260,17 @@ templates: unless the scenario is specifically about an exponent error. If you do change it, restate every scaled field to match. - price_message.ema_price and price_message.ema_conf use the same scales as price and conf. - - posted_slot is a slot number, not a timestamp. Some consumers measure freshness in slots - rather than in seconds. - - TIME FIELDS - READ BEFORE SETTING publish_time: - publish_time and prev_publish_time are unix seconds interpreted against the SURFNET clock, not - the real-world clock. The two can differ by an arbitrary amount, so a timestamp taken from the - real current time will look far in the future inside the simulation and will NOT produce a - stale price. - Do not try to backdate the timestamp either - the Surfnet clock only moves forward. To build a - stale-price scenario, make the price fresh and then advance time past the consumer's limit: - 1. surfnet_pauseClock so the elapsed time is exact rather than dependent on slot production. - It returns an EpochInfo, which carries no timestamp - step 2 is how you read the time. - 2. read the Surfnet clock with getAccountInfo on - SysvarC1ock11111111111111111111111111111111 using the jsonParsed encoding, and take - result.value.data.parsed.info.unixTimestamp, which is in SECONDS. Set publish_time to - that value, which makes the price fresh. - 3. surfnet_timeTravel forward by more than the consumer's staleness limit. Its - absoluteTimestamp is in MILLISECONDS, so multiply the value from step 2 by 1000 before - adding your offset. - 4. send the transaction - the consumer now sees an aged price and should reject it + THE PRICE STAYS PUBLISHED BY ITSELF. From the slot this override plays until the network is + reset, Surfpool republishes this price account every slot, as the Pyth publisher does on + mainnet: publish_time becomes the Surfnet clock's unix seconds and posted_slot the slot, also + after a time travel. Price, conf and the EMA fields keep the values this override wrote. A + value set for publish_time or posted_slot never takes effect, so leave both unset. - UNITS WARNING for step 3: surfnet_timeTravel's absoluteTimestamp is in MILLISECONDS, while - publish_time and the Clock sysvar are in SECONDS. Multiply by 1000 when passing a value read - from the clock, or the call fails with a "past timestamp" error. + STALE PRICE: a price account no override of this template names is not republished and ages + against the Surfnet clock. To test a consumer's staleness check, leave that feed without an + override and surfnet_timeTravel past the consumer's limit. Its absoluteTimestamp is in + MILLISECONDS, while publish_time and the Clock sysvar are in SECONDS. address: type: pda program_id: pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index 830961cb5..009d7d2a5 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -10,10 +10,13 @@ use surfpool_types::{ pub const PYTH_V2_IDL_CONTENT: &str = include_str!("./protocols/pyth/v2/idl.json"); pub const PYTH_V2_OVERRIDES_CONTENT: &str = include_str!("./protocols/pyth/v2/overrides.yaml"); +pub const PYTH_V2_KEEP_ALIVE_CONTENT: &str = include_str!("./protocols/pyth/v2/keep-alive.yaml"); pub const PYTH_CORE_COMPATIBLE_V2_IDL_CONTENT: &str = include_str!("./protocols/pyth/core-compatible/v2/idl.json"); pub const PYTH_CORE_COMPATIBLE_V2_OVERRIDES_CONTENT: &str = include_str!("./protocols/pyth/core-compatible/v2/overrides.yaml"); +pub const PYTH_CORE_COMPATIBLE_V2_KEEP_ALIVE_CONTENT: &str = + include_str!("./protocols/pyth/core-compatible/v2/keep-alive.yaml"); pub const JUPITER_V6_IDL_CONTENT: &str = include_str!("./protocols/jupiter/v6/idl.json"); pub const JUPITER_V6_OVERRIDES_CONTENT: &str = @@ -232,11 +235,20 @@ impl TemplateRegistry { pub fn load_pyth_overrides(&mut self) { self.load_protocol_overrides(PYTH_V2_IDL_CONTENT, PYTH_V2_OVERRIDES_CONTENT, "pyth"); + let idl = serde_json::from_str(PYTH_V2_IDL_CONTENT).expect("pyth idl"); + self.load_keep_alive(Some(idl), PYTH_V2_KEEP_ALIVE_CONTENT, "pyth"); self.load_protocol_overrides( PYTH_CORE_COMPATIBLE_V2_IDL_CONTENT, PYTH_CORE_COMPATIBLE_V2_OVERRIDES_CONTENT, "pyth-core-compatible", ); + let idl = serde_json::from_str(PYTH_CORE_COMPATIBLE_V2_IDL_CONTENT) + .expect("pyth core compatible idl"); + self.load_keep_alive( + Some(idl), + PYTH_CORE_COMPATIBLE_V2_KEEP_ALIVE_CONTENT, + "pyth-core-compatible", + ); } pub fn load_jupiter_overrides(&mut self) { @@ -1687,6 +1699,40 @@ templates: [] ); } + #[test] + fn pyth_price_feeds_keep_their_price_published() { + let registry = TemplateRegistry::new(); + for (id, publication) in [ + ("pyth-price-feed-v2", "pyth-price-publication"), + ( + "pyth-core-compatible-price-feed-v2", + "pyth-core-compatible-price-publication", + ), + ] { + let template = registry.get(id).unwrap(); + let [import] = template.keep_alive.as_slice() else { + panic!("{id} must keep its price published"); + }; + assert_eq!(import.template, publication, "{id}"); + assert_eq!( + import.address, + surfpool_types::KeepAliveAddress::Override, + "{id}" + ); + let mut paths: Vec<&str> = import.values.keys().map(String::as_str).collect(); + paths.sort(); + assert_eq!( + paths, + ["posted_slot", "price_message.publish_time"], + "{id} must leave the scenario's price alone" + ); + assert!( + !registry.contains(publication), + "{publication} is never listed" + ); + } + } + #[test] fn test_get_pda_seed_references() { use surfpool_types::AccountAddress; diff --git a/crates/core/src/tests/pyth/mod.rs b/crates/core/src/tests/pyth/mod.rs index 0390d8c6b..6b2705cfb 100644 --- a/crates/core/src/tests/pyth/mod.rs +++ b/crates/core/src/tests/pyth/mod.rs @@ -11,6 +11,7 @@ use std::collections::HashMap; +use solana_clock::Clock; use solana_commitment_config::CommitmentConfig; use solana_pubkey::Pubkey; use surfpool_types::{AccountAddress, OverrideInstance, Scenario}; @@ -25,6 +26,8 @@ use crate::{ const RPC_URL_ENV: &str = "SURFPOOL_TEST_RPC_URL"; const DEFAULT_RPC_URL: &str = "https://api.mainnet-beta.solana.com"; +const PYTH_CORE_RECEIVER: &str = "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ"; +const CORE_SOL_USD_FEED: &str = "7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE"; const PYTH_CORE_COMPATIBLE_RECEIVER: &str = "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp"; const CORE_COMPATIBLE_SOL_USD_FEED: &str = "7AviUf9nL62mcxNbQGKm4nKDQnPjswo6c5MX4D57HmyE"; const SOL_USD_FEED_ID: &str = "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"; @@ -114,10 +117,14 @@ async fn core_compatible_price_feed_touches_only_price_fields() { .await .unwrap(); - let forged = locker - .with_svm_reader(|svm| svm.get_account(&target)) - .unwrap() - .expect("the feed should exist"); + let (forged, clock) = locker.with_svm_reader(|svm| { + ( + svm.get_account(&target) + .unwrap() + .expect("the feed should exist"), + svm.inner.get_sysvar::(), + ) + }); assert_eq!(forged.owner, live.owner); assert_eq!(forged.lamports, live.lamports); assert_eq!(forged.data.len(), live.data.len()); @@ -134,6 +141,12 @@ async fn core_compatible_price_feed_touches_only_price_fields() { "changed {diffs:?}" ); for (path, offset, width, value) in rows { + // Keep-alive republishes the price after the override plays. + let value = match path { + "price_message.publish_time" => clock.unix_timestamp, + "posted_slot" => clock.slot as i64, + _ => value, + }; assert_eq!( &forged.data[offset..offset + width], &value.to_le_bytes()[..width], @@ -141,3 +154,93 @@ async fn core_compatible_price_feed_touches_only_price_fields() { ); } } + +/// Keep-alive republishes a price account a scenario overrides every slot, as the Pyth publisher +/// does on mainnet, time travels included. Only the publication fields move with the Clock: the +/// price stays the scenario's. +#[tokio::test(flavor = "multi_thread")] +async fn price_feeds_stay_published_through_surfnet_svm() { + const PRICE: i64 = 2_000_000_000; + for (template_id, address, receiver) in [ + ("pyth-price-feed-v2", CORE_SOL_USD_FEED, PYTH_CORE_RECEIVER), + ( + "pyth-core-compatible-price-feed-v2", + CORE_COMPATIBLE_SOL_USD_FEED, + PYTH_CORE_COMPATIBLE_RECEIVER, + ), + ] { + let live = fetch(address).await; + assert_eq!(live.owner.to_string(), receiver); + // A Partial verification level shifts every offset below by one. + assert_eq!( + live.data[40], 1, + "{address} verification level should be Full" + ); + + let target = Pubkey::from_str_const(address); + let (svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); + let locker = SurfnetSvmLocker::new(svm); + locker.with_svm_writer(|svm| svm.set_account(&target, live.clone()).unwrap()); + let mut scenario = Scenario::new("Pyth SOL at $20".to_string(), "Price only".to_string()); + scenario.add_override( + OverrideInstance::new( + template_id.to_string(), + 0, + AccountAddress::Pubkey(address.to_string()), + ) + .with_values(HashMap::from([( + "price_message.price".to_string(), + serde_json::json!(PRICE), + )])), + ); + locker.register_scenario(scenario, None).unwrap(); + + let assert_published = |when: &str| { + let (data, clock) = locker.with_svm_reader(|svm| { + ( + svm.get_account(&target).unwrap().unwrap().data, + svm.inner.get_sysvar::(), + ) + }); + let word = |offset: usize| <[u8; 8]>::try_from(&data[offset..offset + 8]).unwrap(); + assert_eq!( + i64::from_le_bytes(word(93)), + clock.unix_timestamp, + "{template_id} {when}: publish_time" + ); + assert_eq!( + u64::from_le_bytes(word(125)), + clock.slot, + "{template_id} {when}: posted_slot" + ); + assert_eq!(i64::from_le_bytes(word(73)), PRICE, "{template_id} {when}"); + let diffs: Vec = (0..live.data.len()) + .filter(|&i| data[i] != live.data[i]) + .collect(); + assert!( + diffs.iter().all(|i| [73..81, 93..101, 125..133] + .iter() + .any(|written| written.contains(i))), + "{template_id} {when}: changed {diffs:?}" + ); + }; + + for slot in 1..=3 { + locker.confirm_current_block(&None).await.unwrap(); + assert_published(&format!("slot {slot}")); + } + let clock = locker.with_svm_reader(|svm| svm.inner.get_sysvar::()); + locker + .apply_time_travel( + Clock { + slot: clock.slot + 1_000, + unix_timestamp: clock.unix_timestamp + 3_600, + ..clock + }, + &None, + ) + .await + .unwrap(); + assert_published("after a time travel"); + } +} From 3ef1659abf5389478e340d2527b8c61c147a633e Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 14:07:27 +0200 Subject: [PATCH 08/24] feat(scenarios): let an override opt out of keep-alive --- crates/core/src/scenarios/README.md | 3 +- crates/core/src/surfnet/svm.rs | 1 + .../kit/generated/OverrideInstance.ts | 5 +++ crates/types/src/rpc_endpoints.json | 1 + crates/types/src/scenarios.rs | 34 +++++++++++++++++++ 5 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 970da4824..8ce00d1f8 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -121,7 +121,8 @@ time; other values are written as given. Keep-alive starts in the slot the importing override plays and rewrites its fields every slot, after that slot's overrides, until the network is reset. An override of one of those fields therefore -never takes effect. An account not yet in the surfnet is fetched from the remote first, unless it, +never takes effect. An override with `keepAlive: false` writes once and starts no keep-alive, so its +account ages as the clock moves on, for example to test a stale price. An account not yet in the surfnet is fetched from the remote first, unless it, or its owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops until an importing override plays again. diff --git a/crates/core/src/surfnet/svm.rs b/crates/core/src/surfnet/svm.rs index 168e8e00d..e7a3e0e45 100644 --- a/crates/core/src/surfnet/svm.rs +++ b/crates/core/src/surfnet/svm.rs @@ -3532,6 +3532,7 @@ impl SurfnetSvm { // if no scenario had touched it. let mut keep_alive_source = None; if scheduled + && override_instance.keep_alive && let Some(template) = template_registry().get(&override_instance.template_id) && !template.keep_alive.is_empty() { diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts index 0bf5926b1..06c6bfada 100644 --- a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts +++ b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts @@ -36,6 +36,11 @@ enabled: boolean, * Whether to fetch fresh account data just before transaction execution */ fetchBeforeUse?: boolean, +/** + * Whether keep-alive rewrites the account after this override, when its template imports + * keep-alive. Off, the override writes once and its fields age as the clock moves on. + */ +keepAlive?: boolean, /** * Account address to override - use pubkey for known addresses or pda for derived addresses */ diff --git a/crates/types/src/rpc_endpoints.json b/crates/types/src/rpc_endpoints.json index bc5b02991..0e954f57a 100644 --- a/crates/types/src/rpc_endpoints.json +++ b/crates/types/src/rpc_endpoints.json @@ -861,6 +861,7 @@ "label": "Option (An optional label for this override instance)", "enabled": "bool (Indicates whether this override instance is enabled)", "fetchBeforeUse": "bool (Indicates whether to fetch the latest on-chain account data before applying overrides)", + "keepAlive": "bool (Optional, defaults to true. If false, keep-alive does not keep the account fresh after this override, and its fields age as the clock moves on)", "account": "AccountAddress (The account this override targets, as {\"pubkey\": \"\"} or {\"pda\": {\"programId\": \"\", \"seeds\": [ ... ]}})" } } diff --git a/crates/types/src/scenarios.rs b/crates/types/src/scenarios.rs index 46a0c1088..bb98bbda7 100644 --- a/crates/types/src/scenarios.rs +++ b/crates/types/src/scenarios.rs @@ -592,6 +592,14 @@ pub struct OverrideInstance { #[serde(default)] #[cfg_attr(feature = "ts-bindings", ts(as = "Option", optional))] pub fetch_before_use: bool, + /// Whether keep-alive rewrites the account after this override, when its template imports + /// keep-alive. Off, the override writes once and its fields age as the clock moves on. + #[schemars( + description = "If false, the override writes once and keep-alive does not keep the account fresh afterwards. Defaults to true" + )] + #[serde(default = "default_keep_alive")] + #[cfg_attr(feature = "ts-bindings", ts(as = "Option", optional))] + pub keep_alive: bool, /// Account address to override - use pubkey for known addresses or pda for derived addresses #[schemars( description = "Account address: either {\"pubkey\": \"base58_address\"} or {\"pda\": {\"programId\": \"...\", \"seeds\": [...]}}" @@ -599,6 +607,10 @@ pub struct OverrideInstance { pub account: AccountAddress, } +fn default_keep_alive() -> bool { + true +} + impl OverrideInstance { pub fn new(template_id: String, scenario_relative_slot: Slot, account: AccountAddress) -> Self { Self { @@ -609,6 +621,7 @@ impl OverrideInstance { label: None, enabled: true, fetch_before_use: false, + keep_alive: true, account, } } @@ -2000,6 +2013,27 @@ mod tests { assert_eq!(values["fixed"], json!(3)); } + #[test] + fn an_override_keeps_its_account_alive_unless_it_opts_out() { + let instance = |extra: serde_json::Value| { + let mut value = json!({ + "id": "o", + "templateId": "t", + "values": {}, + "scenarioRelativeSlot": 0, + "enabled": true, + "account": { "pubkey": "11111111111111111111111111111111" }, + }); + value + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + serde_json::from_value::(value).unwrap() + }; + assert!(instance(json!({})).keep_alive); + assert!(!instance(json!({ "keepAlive": false })).keep_alive); + } + #[test] fn a_file_level_keep_alive_is_inherited_unless_a_template_sets_its_own() { let file: super::YamlOverrideTemplateCollection = serde_yaml::from_str( From e15c9a0b1b45d5ba9ee80e38e6608df9bb849bb3 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 14:12:57 +0200 Subject: [PATCH 09/24] ci: add Claude pull request reviews --- .github/workflows/claude-review.yml | 141 ++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 .github/workflows/claude-review.yml diff --git a/.github/workflows/claude-review.yml b/.github/workflows/claude-review.yml new file mode 100644 index 000000000..844c44d68 --- /dev/null +++ b/.github/workflows/claude-review.yml @@ -0,0 +1,141 @@ +name: Perform a code review when a pull request is created. +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + claude: + # Skip drafts, and skip fork PRs: on `pull_request` they don't get the + # ANTHROPIC_API_KEY secret, so the review would only fail. + if: >- + !github.event.pull_request.draft && + github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + structured_output: ${{ steps.run_claude.outputs.structured_output }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + # Explicitly check out the PR's merge commit. + ref: refs/pull/${{ github.event.pull_request.number }}/merge + persist-credentials: false + + - name: Pre-fetch base and head refs for the PR + env: + PR_BASE_REF: ${{ github.event.pull_request.base.ref }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + # Pass GitHub expressions through env and quote shell expansions. + git fetch --no-tags origin \ + "$PR_BASE_REF" \ + "+refs/pull/$PR_NUMBER/head" + + # If you want Claude to build and run code, install any dependencies that + # need to be downloaded before the "Run Claude" step, and add the commands + # it may run to --allowedTools below (e.g. "Bash(npm test:*)"). Any tool + # not listed there is denied. + + - name: Run Claude + id: run_claude + uses: anthropics/claude-code-action@86d88e619d8e6caf07b5c3944dd14f441c533718 # v1.0.243 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + # Use this job's read-only token instead of the Claude GitHub App, + # which needs `id-token: write` and would get write access. + github_token: ${{ github.token }} + prompt: | + This is PR #${{ github.event.pull_request.number }} for ${{ github.repository }}. + + Review ONLY the changes introduced by the PR, so consider: + git log --oneline ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} + git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} + + Suggest any improvements, potential bugs, or issues. + Be concise and specific in your feedback. + + Return your review in two parts: + - `summary`: a short Markdown overview of the PR and your overall assessment. + - `comments`: one entry per specific issue, anchored to the line it concerns. + `path` is relative to the repository root. `line` is the line number in + the PR head version of the file (${{ github.event.pull_request.head.sha }}), + and must be a line shown in the diff above. The working tree is the merge + commit, so its line numbers can differ; check them with + `git show ${{ github.event.pull_request.head.sha }}:`. + Put issues that don't belong to a single line in `summary` instead. + + Pull request title and body: + ---- + ${{ github.event.pull_request.title }} + ${{ github.event.pull_request.body }} + claude_args: | + --allowedTools "Read,Grep,Glob,Bash(git log:*),Bash(git diff:*),Bash(git show:*)" + --json-schema '{ + "type": "object", + "properties": { + "summary": { + "type": "string", + "description": "Overall review as Markdown, posted as the review body." + }, + "comments": { + "type": "array", + "description": "Inline comments, each anchored to one line of the PR diff.", + "items": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "File path relative to the repository root." }, + "line": { "type": "integer", "minimum": 1, "description": "Line number in the PR head version of the file. Must be within the diff." }, + "body": { "type": "string", "description": "The comment, as Markdown." } + }, + "required": ["path", "line", "body"] + } + } + }, + "required": ["summary", "comments"] + }' + + post_feedback: + runs-on: ubuntu-latest + needs: claude + if: needs.claude.outputs.structured_output != '' + permissions: + issues: write + pull-requests: write + steps: + - name: Report Claude feedback + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 + env: + CLAUDE_STRUCTURED_OUTPUT: ${{ needs.claude.outputs.structured_output }} + with: + github-token: ${{ github.token }} + script: | + const { summary = '', comments = [] } = JSON.parse(process.env.CLAUDE_STRUCTURED_OUTPUT); + const pr = context.payload.pull_request; + if (!summary.trim() && comments.length === 0) { + core.info('Claude returned an empty review; nothing to post.'); + return; + } + + try { + await github.rest.pulls.createReview({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pr.number, + commit_id: pr.head.sha, + event: 'COMMENT', + body: summary.trim() || 'See inline comments.', + comments: comments.map(({ path, line, body }) => ({ path, line, side: 'RIGHT', body })), + }); + } catch (error) { + // GitHub rejects the whole review if any comment points outside the + // diff. Fall back to a single PR comment so no feedback is lost. + core.warning(`Could not post inline review (${error.message}); posting a plain comment instead.`); + const details = comments.map(({ path, line, body }) => `**\`${path}:${line}\`**\n\n${body}`); + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pr.number, + body: [summary.trim(), ...details].filter(Boolean).join('\n\n---\n\n'), + }); + } From bafeba388a0cf2f7d9f3474f765e40a1aca5f27a Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 16:20:24 +0200 Subject: [PATCH 10/24] feat(scenarios): keep every local account of a kind alive, and stop or restart keep-alive per account --- crates/core/src/scenarios/README.md | 9 +- crates/core/src/scenarios/keep_alive.rs | 331 +++++++++++++++++- crates/core/src/scenarios/registry.rs | 36 +- crates/core/src/surfnet/svm.rs | 130 ++++--- .../kit/generated/OverrideInstance.ts | 4 +- crates/types/src/rpc_endpoints.json | 2 +- crates/types/src/scenarios.rs | 93 ++++- 7 files changed, 521 insertions(+), 84 deletions(-) diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 8ce00d1f8..3f20849ea 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -115,15 +115,18 @@ templates: | `{ type: input, value: oracle }` | the pubkey given in that `input` property (`value_type: pubkey`, never written) | | `{ type: pubkey, value:
}` | a fixed account | | `{ type: pda, program_id, seeds }` | a derived account; seeds resolve against the override's values | +| `{ type: owned, owner: , account: }` | every local account an owner owns whose data starts with that account's discriminator in the keep-alive template's IDL, including accounts loaded later; never fetched | `$slot`, `$slot±N` and `$unix_s`/`ms`/`us`/`ns` in `values` are filled from the slot and its Clock time; other values are written as given. Keep-alive starts in the slot the importing override plays and rewrites its fields every slot, after that slot's overrides, until the network is reset. An override of one of those fields therefore -never takes effect. An override with `keepAlive: false` writes once and starts no keep-alive, so its -account ages as the clock moves on, for example to test a stale price. An account not yet in the surfnet is fetched from the remote first, unless it, -or its owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops +never takes effect. An override with `keepAlive: false` stops keep-alive for the account it writes +from that slot on, so the account ages as the clock moves on, for example to test a stale price. A +later override with `keepAlive: true`, the default, on that account starts it again. An account not +yet in the surfnet is fetched from the remote first, unless it, or its owner with its owned accounts, +is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops until an importing override plays again. ### Override Templates diff --git a/crates/core/src/scenarios/keep_alive.rs b/crates/core/src/scenarios/keep_alive.rs index 9ca123dac..4dd9a7ae4 100644 --- a/crates/core/src/scenarios/keep_alive.rs +++ b/crates/core/src/scenarios/keep_alive.rs @@ -1,13 +1,18 @@ //! Keep-alive covers what a protocol's own off-chain actor rewrites every slot, such as a market //! maker republishing its quote. Nobody runs those actors against a surfnet, so once a scenario's //! override touches an account, the surfnet applies the keep-alive templates its template imports -//! every slot, as ordinary overrides, until the network is reset. +//! every slot, as ordinary overrides, until the network is reset. An override with `keep_alive` +//! off stops keep-alive for the account it writes, until an override with it on writes that account. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap, HashSet}; +use solana_account::Account; use solana_pubkey::Pubkey; +use surfpool_types::{KeepAliveAddress, KeepAliveImport}; -/// An account a scenario's override wrote through a template that imports keep-alive. +use super::TemplateRegistry; + +/// An account a scenario's override wrote. #[derive(Clone, Debug)] pub struct KeepAliveSource { pub template: String, @@ -15,6 +20,8 @@ pub struct KeepAliveSource { pub address: Pubkey, /// The override's values, which input and PDA addresses resolve against. pub values: HashMap, + /// The override's `keep_alive`: off, keep-alive stops for `address`. + pub keep_alive: bool, } /// Binds a template's keep-alive import to the account it rewrites every slot, resolved when an @@ -28,3 +35,321 @@ pub struct KeepAliveBinding { /// The address the import rewrites. pub address: Pubkey, } + +/// Binds a template's owned keep-alive import, which rewrites every local account of a kind, +/// resolved again each slot since the surfnet keeps loading accounts. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct KeepAliveKind { + /// The importing template's ID. + pub template: String, + /// The import's index in that template's `keep_alive` list. + pub import: usize, +} + +/// What keep-alive rewrites every slot. Kept in memory only, so a restart on a persistent database +/// stops keep-alive. +#[derive(Clone, Debug, Default)] +pub struct KeepAlive { + pub bindings: BTreeSet, + pub kinds: BTreeSet, + /// Accounts an override with `keep_alive` off wrote last. Keep-alive skips them. + pub excluded: HashSet, +} + +impl KeepAlive { + /// Applies the overrides that wrote `touched`, in order: one with `keep_alive` off stops + /// keep-alive for its account, one with it on starts it again and adds its template's imports. + pub fn enroll(&mut self, registry: &TemplateRegistry, touched: Vec) { + for source in touched { + if !source.keep_alive { + self.bindings + .retain(|binding| binding.address != source.address); + if self.excluded.insert(source.address) { + info!("Keep-alive stops rewriting {}", source.address); + } + continue; + } + self.excluded.remove(&source.address); + let Some(template) = registry.get(&source.template) else { + continue; + }; + for (index, import) in template.keep_alive.iter().enumerate() { + if let KeepAliveAddress::Owned { owners, account } = &import.address { + let kind = KeepAliveKind { + template: template.id.clone(), + import: index, + }; + if self.kinds.insert(kind) { + info!( + "Keep-alive '{}' rewrites every local '{}' of {:?} every slot", + import.template, account, owners + ); + } + continue; + } + let Some(address) = import.address(source.address, &source.values) else { + warn!( + "Keep-alive '{}' of override template '{}' has no address for {}", + import.template, template.id, source.address + ); + continue; + }; + if self.excluded.contains(&address) { + continue; + } + let binding = KeepAliveBinding { + template: template.id.clone(), + import: index, + address, + }; + if self.bindings.insert(binding) { + info!( + "Keep-alive '{}' rewrites {} every slot", + import.template, address + ); + } + } + } + } + + /// Each account to rewrite this slot with the import that rewrites it: every binding, then + /// every account `accounts_owned_by` returns for a kind's owners that holds the kind's account + /// type. Excluded accounts are skipped, and so is an account a keep-alive template already + /// rewrites. + pub fn targets<'r>( + &self, + registry: &'r TemplateRegistry, + accounts_owned_by: impl Fn(&Pubkey) -> Vec<(Pubkey, Account)>, + ) -> Vec<(&'r KeepAliveImport, Pubkey)> { + let import_of = |template: &str, index: usize| { + registry + .get(template) + .and_then(|template| template.keep_alive.get(index)) + }; + let mut seen = HashSet::new(); + let mut targets = Vec::new(); + for binding in &self.bindings { + if let Some(import) = import_of(&binding.template, binding.import) + && seen.insert((import.template.as_str(), binding.address)) + { + targets.push((import, binding.address)); + } + } + for kind in &self.kinds { + let Some(import) = import_of(&kind.template, kind.import) else { + continue; + }; + let KeepAliveAddress::Owned { owners, account } = &import.address else { + continue; + }; + let Some(discriminator) = registry + .get(&import.template) + .and_then(|template| template.account_discriminator(account)) + else { + continue; + }; + for owner in owners.iter().filter_map(|owner| owner.parse().ok()) { + for (address, owned) in accounts_owned_by(&owner) { + if owned.data.starts_with(discriminator) + && !self.excluded.contains(&address) + && seen.insert((import.template.as_str(), address)) + { + targets.push((import, address)); + } + } + } + } + targets + } +} + +#[cfg(test)] +pub(super) mod tests { + use super::*; + use crate::scenarios::registry::PYTH_V2_IDL_CONTENT; + + pub(crate) const OWNER: &str = "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ"; + + pub(crate) const OWNED_OVERRIDES: &str = r#" +protocol: Example +version: v1 +account_type: State +raw_layout: true +templates: + - id: example-vault + name: Vault + description: Example vault + keep_alive: + - template: example-price-fresh + address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: PriceUpdateV2 } + values: { posted_slot: $slot } + - template: example-price-fresh + address: { type: input, value: oracle } + values: { posted_slot: $slot } + address: { type: pubkey } + properties: + - { path: balance, offset: 0, encoding: u64, description: Balance } + - { path: oracle, type: input, value_type: pubkey, description: The vault's oracle } +"#; + + const PRICE_KEEP_ALIVE: &str = r#" +protocol: Example +version: v1 +account_type: PriceUpdateV2 +templates: + - id: example-price-fresh + name: Fresh price + description: What the publisher republishes + address: { type: pubkey } + properties: + - { path: posted_slot, label: Posted slot, description: Posted slot } +"#; + + pub(crate) fn owned_registry(overrides: &str) -> TemplateRegistry { + let mut registry = TemplateRegistry::default(); + registry.load_raw_layout_overrides(overrides, "example"); + registry.load_keep_alive( + Some(serde_json::from_str(PYTH_V2_IDL_CONTENT).unwrap()), + PRICE_KEEP_ALIVE, + "example", + ); + registry + } + + fn account(owner: Pubkey, data: &[u8]) -> Account { + Account { + lamports: 1, + data: data.to_vec(), + owner, + executable: false, + rent_epoch: 0, + } + } + + fn source( + template: &str, + address: Pubkey, + oracle: Pubkey, + keep_alive: bool, + ) -> KeepAliveSource { + KeepAliveSource { + template: template.to_string(), + address, + values: HashMap::from([("oracle".to_string(), serde_json::json!(oracle.to_string()))]), + keep_alive, + } + } + + struct LocalAccounts { + registry: TemplateRegistry, + accounts: Vec<(Pubkey, Account)>, + price: [u8; 8], + } + + impl LocalAccounts { + fn new() -> Self { + let registry = owned_registry(OWNED_OVERRIDES); + let price = registry + .get("example-price-fresh") + .and_then(|template| template.account_discriminator("PriceUpdateV2")) + .unwrap() + .try_into() + .unwrap(); + Self { + registry, + accounts: Vec::new(), + price, + } + } + + fn load(&mut self, owner: Pubkey, discriminator: [u8; 8]) -> Pubkey { + let address = Pubkey::new_unique(); + let mut data = discriminator.to_vec(); + data.extend([0; 8]); + self.accounts.push((address, account(owner, &data))); + address + } + + fn targets(&self, keep_alive: &KeepAlive) -> Vec { + keep_alive + .targets(&self.registry, |owner| { + self.accounts + .iter() + .filter(|(_, account)| account.owner == *owner) + .cloned() + .collect() + }) + .into_iter() + .map(|(import, address)| { + assert_eq!(import.template, "example-price-fresh"); + address + }) + .collect() + } + } + + #[test] + fn an_owned_kind_rewrites_every_local_account_of_its_owner_and_type() { + let owner = OWNER.parse().unwrap(); + let mut surfnet = LocalAccounts::new(); + let oracle = surfnet.load(owner, surfnet.price); + let other_price = surfnet.load(owner, surfnet.price); + surfnet.load(owner, [9; 8]); + surfnet.load(Pubkey::new_unique(), surfnet.price); + + let mut keep_alive = KeepAlive::default(); + let vault = Pubkey::new_unique(); + keep_alive.enroll( + &surfnet.registry, + vec![source("example-vault", vault, oracle, true)], + ); + assert_eq!( + surfnet.targets(&keep_alive), + [oracle, other_price], + "the oracle is bound and owned, and is written once" + ); + + let loaded_later = surfnet.load(owner, surfnet.price); + assert_eq!( + surfnet.targets(&keep_alive), + [oracle, other_price, loaded_later] + ); + } + + #[test] + fn an_override_without_keep_alive_stops_it_for_its_account_until_one_with_it_plays() { + let owner = OWNER.parse().unwrap(); + let mut surfnet = LocalAccounts::new(); + let oracle = surfnet.load(owner, surfnet.price); + let other_price = surfnet.load(owner, surfnet.price); + let vault = Pubkey::new_unique(); + let mut keep_alive = KeepAlive::default(); + keep_alive.enroll( + &surfnet.registry, + vec![source("example-vault", vault, oracle, true)], + ); + + keep_alive.enroll( + &surfnet.registry, + vec![source("pyth-price-feed-v2", oracle, oracle, false)], + ); + assert!(keep_alive.bindings.is_empty(), "its binding is dropped"); + assert_eq!(surfnet.targets(&keep_alive), [other_price]); + + keep_alive.enroll( + &surfnet.registry, + vec![source("example-vault", vault, oracle, true)], + ); + assert_eq!( + surfnet.targets(&keep_alive), + [other_price], + "another account's override does not restart it" + ); + + keep_alive.enroll( + &surfnet.registry, + vec![source("pyth-price-feed-v2", oracle, oracle, true)], + ); + assert_eq!(surfnet.targets(&keep_alive), [oracle, other_price]); + } +} diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index a80f6bb7f..890545d17 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -177,8 +177,9 @@ impl TemplateRegistry { } /// Fails on a keep-alive import the registry cannot apply: its template must be a loaded - /// keep-alive template that has every property it sets, and an input address must name a - /// pubkey input of the importing template. + /// keep-alive template that has every property it sets, an input address must name a pubkey + /// input of the importing template, and an owned address an account of the keep-alive + /// template's IDL. pub fn check_keep_alive_imports(&self) -> Result<(), String> { for template in self.templates.values() { for import in &template.keep_alive { @@ -208,6 +209,13 @@ impl TemplateRegistry { )); } } + if let KeepAliveAddress::Owned { account, .. } = &import.address + && keep_alive.account_discriminator(account).is_none() + { + return fail(format!( + "its IDL has no account '{account}' with a discriminator" + )); + } if let KeepAliveAddress::Input(name) = &import.address { let is_pubkey_input = template.properties.iter().any(|property| { &property.path == name @@ -1058,6 +1066,30 @@ templates: ); } + #[test] + fn an_owned_import_needs_its_account_in_the_keep_alive_idl() { + use crate::scenarios::keep_alive::tests::{OWNED_OVERRIDES, owned_registry}; + + owned_registry(OWNED_OVERRIDES) + .check_keep_alive_imports() + .unwrap(); + let error = + owned_registry(&OWNED_OVERRIDES.replace("account: PriceUpdateV2", "account: Nope")) + .check_keep_alive_imports() + .unwrap_err(); + assert!(error.contains("its IDL has no account 'Nope'"), "{error}"); + let error = keep_alive_registry(&KEEP_ALIVE_OVERRIDES.replace( + "address: { type: input, value: oracle }", + "address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: State }", + )) + .check_keep_alive_imports() + .unwrap_err(); + assert!( + error.contains("its IDL has no account 'State'"), + "a raw layout has no IDL: {error}" + ); + } + #[test] fn the_bundled_registry_resolves_every_keep_alive_import() { TemplateRegistry::new().check_keep_alive_imports().unwrap(); diff --git a/crates/core/src/surfnet/svm.rs b/crates/core/src/surfnet/svm.rs index e7a3e0e45..9abdc80b2 100644 --- a/crates/core/src/surfnet/svm.rs +++ b/crates/core/src/surfnet/svm.rs @@ -1,6 +1,6 @@ use std::{ cmp::max, - collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}, + collections::{BTreeMap, HashMap, HashSet, VecDeque}, ops::{ Bound::{Excluded, Unbounded}, RangeInclusive, @@ -105,7 +105,7 @@ use crate::{ rpc::utils::convert_transaction_metadata_from_canonical, scenarios::{ TemplateRegistry, account_data_values, - keep_alive::{KeepAliveBinding, KeepAliveSource}, + keep_alive::{KeepAlive, KeepAliveSource}, protocols::phoenix_eternal::v1::state_builder::{ prepare_phoenix_override, write_all_or_none, }, @@ -609,7 +609,7 @@ pub struct SurfnetSvm { pub scheduled_overrides: Box>>, /// The accounts keep-alive rewrites every slot, from the slot a scenario's override first /// touched them. Kept in memory only, so a restart on a persistent database stops keep-alive. - pub keep_alive_bindings: BTreeSet, + pub keep_alive: KeepAlive, /// Tracks accounts that should not be downloaded from the remote RPC. /// This includes accounts explicitly closed locally and accounts marked offline via cheatcodes. /// The key is the account pubkey as a string. If `include_owned_accounts` is true, @@ -893,7 +893,7 @@ impl SurfnetSvm { registered_idls: OverlayStorage::wrap(self.registered_idls.clone_box()), streamed_accounts: OverlayStorage::wrap(self.streamed_accounts.clone_box()), scheduled_overrides: OverlayStorage::wrap(self.scheduled_overrides.clone_box()), - keep_alive_bindings: self.keep_alive_bindings.clone(), + keep_alive: self.keep_alive.clone(), // Clone non-storage fields normally transactions_queued_for_confirmation: self.transactions_queued_for_confirmation.clone(), @@ -1403,7 +1403,7 @@ impl SurfnetSvm { streamed_accounts: streamed_accounts_db, recent_blockhashes: VecDeque::new(), scheduled_overrides: scheduled_overrides_db, - keep_alive_bindings: BTreeSet::new(), + keep_alive: KeepAlive::default(), offline_accounts: offline_accounts_db, genesis_slot: default_genesis_slot, genesis_updated_at: updated_at, @@ -2623,7 +2623,7 @@ impl SurfnetSvm { self.runbook_executions.clear(); self.streamed_accounts.clear()?; self.scheduled_overrides.clear()?; - self.keep_alive_bindings.clear(); + self.keep_alive = KeepAlive::default(); let current_time = chrono::Utc::now().timestamp_millis() as u64; self.updated_at = current_time; @@ -3404,7 +3404,7 @@ impl SurfnetSvm { /// 3. Optionally fetches fresh account data from remote if `fetch_before_use` is enabled /// 4. Applies the overrides to the account data /// 5. Updates the SVM state - /// 6. Applies keep-alive to every account in `keep_alive_bindings` + /// 6. Applies keep-alive to every account in `keep_alive` pub async fn materialize_overrides( &mut self, remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>, @@ -3414,7 +3414,7 @@ impl SurfnetSvm { .await } - /// Applies keep-alive to every account in `keep_alive_bindings`, with the placeholders filled from + /// Applies keep-alive to every account in `keep_alive`, with the placeholders filled from /// `slot` and its Clock time. pub async fn apply_keep_alive( &mut self, @@ -3432,7 +3432,7 @@ impl SurfnetSvm { } /// Materializes scheduled overrides for a specific slot, adds the accounts they touch to - /// `keep_alive_bindings`, then applies keep-alive to every account on it. + /// `keep_alive`, then applies keep-alive to every account on it. pub async fn materialize_overrides_for_slot( &mut self, remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>, @@ -3455,7 +3455,7 @@ impl SurfnetSvm { materialized } - /// Applies `overrides` in order and returns the scheduled ones whose template imports + /// Applies `overrides` in order and returns the scheduled ones that wrote their account, for /// keep-alive. `scheduled` overrides came out of this slot's schedule, which only registered /// scenarios fill: when one fails, the ones not reached yet go back into it. async fn apply_overrides( @@ -3528,20 +3528,14 @@ impl SurfnetSvm { } }; - // Joins keep-alive only once its write succeeds: a failed override leaves the account as - // if no scenario had touched it. - let mut keep_alive_source = None; - if scheduled - && override_instance.keep_alive - && let Some(template) = template_registry().get(&override_instance.template_id) - && !template.keep_alive.is_empty() - { - keep_alive_source = Some(KeepAliveSource { - template: template.id.clone(), - address: account_pubkey, - values: override_instance.values.clone(), - }); - } + // Joins or leaves keep-alive only once its write succeeds: a failed override leaves the + // account as if no scenario had touched it. + let mut keep_alive_source = scheduled.then(|| KeepAliveSource { + template: override_instance.template_id.clone(), + address: account_pubkey, + values: override_instance.values.clone(), + keep_alive: override_instance.keep_alive, + }); debug!( "Processing override {} for account {} (label: {:?})", @@ -3917,37 +3911,14 @@ impl SurfnetSvm { Ok(keep_alive_touched) } - /// Adds the accounts that `touched` makes keep-alive imports rewrite. + /// Starts or stops keep-alive for the accounts in `touched`. fn enroll_keep_alive(&mut self, touched: Vec) { - for source in touched { - let Some(template) = template_registry().get(&source.template) else { - continue; - }; - for (index, import) in template.keep_alive.iter().enumerate() { - let Some(address) = import.address(source.address, &source.values) else { - warn!( - "Keep-alive '{}' of override template '{}' has no address for {}", - import.template, template.id, source.address - ); - continue; - }; - let binding = KeepAliveBinding { - template: template.id.clone(), - import: index, - address, - }; - if self.keep_alive_bindings.insert(binding) { - info!( - "Keep-alive '{}' rewrites {} every slot", - import.template, address - ); - } - } - } + self.keep_alive.enroll(template_registry(), touched); } - /// The keep-alive overrides for every binding at `slot`. A missing account is fetched first when - /// `can_fetch` and not offline, otherwise skipped. + /// The keep-alive overrides for every account keep-alive rewrites at `slot`. A missing account + /// is fetched first when `can_fetch` and not offline, otherwise skipped. Owned kinds only reach + /// local accounts, so they never fetch. fn keep_alive_overrides(&self, slot: Slot, can_fetch: bool) -> Vec { // The time the open slot's Clock sysvar holds. The Clock advances by each slot's own // interval, so recomputing it from the slot would apply a changed slot interval to every @@ -3956,52 +3927,49 @@ impl SurfnetSvm { slot, unix_time_ms: self.updated_at, }; + let targets = self.keep_alive.targets(template_registry(), |owner| { + self.get_account_owned_by(owner).unwrap_or_else(|e| { + warn!("Keep-alive cannot read the accounts of {}: {}", owner, e); + Vec::new() + }) + }); let mut instances = Vec::new(); - for binding in &self.keep_alive_bindings { - let Some(import) = template_registry() - .get(&binding.template) - .and_then(|template| template.keep_alive.get(binding.import)) - else { - continue; - }; - let missing = match self.get_account(&binding.address) { + for (import, address) in targets { + let missing = match self.get_account(&address) { Ok(Some(_)) => false, Ok(None) if can_fetch && !self .offline_accounts - .contains_key(&binding.address.to_string()) + .contains_key(&address.to_string()) .unwrap_or(false) => { true } Ok(None) => { - debug!("Keep-alive skips {}: not in this surfnet", binding.address); + debug!("Keep-alive skips {}: not in this surfnet", address); continue; } Err(e) => { - warn!("Keep-alive cannot read {}: {}", binding.address, e); + warn!("Keep-alive cannot read {}: {}", address, e); continue; } }; let values = match import.values_at(&clock) { Ok(values) => values, Err(e) => { - warn!( - "Keep-alive '{}' skips {}: {}", - import.template, binding.address, e - ); + warn!("Keep-alive '{}' skips {}: {}", import.template, address, e); continue; } }; let mut instance = OverrideInstance::new( import.template.clone(), 0, - surfpool_types::AccountAddress::Pubkey(binding.address.to_string()), + surfpool_types::AccountAddress::Pubkey(address.to_string()), ) .with_values(values) .with_label(format!("keep-alive {}", import.template)); - instance.id = format!("keep-alive:{}:{}", import.template, binding.address); + instance.id = format!("keep-alive:{}:{}", import.template, address); instance.fetch_before_use = missing; instances.push(instance); } @@ -9735,4 +9703,28 @@ mod tests { .expect("the override must notify the account's subscribers"); assert_eq!(update.data.decode(), Some(account.data)); } + + #[tokio::test] + async fn a_written_override_without_keep_alive_excludes_its_account_until_one_with_it() { + const SLOT: u64 = 500; + let (mut svm, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default(); + let (account_pubkey, instance) = scheduled_override_fixture(&mut svm); + let mut play = async |keep_alive: bool, values: HashMap| { + let mut instance = instance.clone().with_values(values); + instance.keep_alive = keep_alive; + svm.scheduled_overrides.store(SLOT, vec![instance]).unwrap(); + svm.materialize_overrides_for_slot(&None, SLOT) + .await + .unwrap(); + svm.keep_alive.excluded.contains(&account_pubkey) + }; + + let failed = HashMap::from([("nope".to_string(), serde_json::json!(1))]); + assert!( + !play(false, failed).await, + "a failed write excludes nothing" + ); + assert!(play(false, instance.values.clone()).await); + assert!(!play(true, instance.values.clone()).await); + } } diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts index 06c6bfada..c52415578 100644 --- a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts +++ b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts @@ -37,8 +37,8 @@ enabled: boolean, */ fetchBeforeUse?: boolean, /** - * Whether keep-alive rewrites the account after this override, when its template imports - * keep-alive. Off, the override writes once and its fields age as the clock moves on. + * Whether keep-alive rewrites this account from this slot on. Off, keep-alive stops for the + * account, so its fields age as the clock moves on, until a later override turns it on again. */ keepAlive?: boolean, /** diff --git a/crates/types/src/rpc_endpoints.json b/crates/types/src/rpc_endpoints.json index 0e954f57a..6517dd7f0 100644 --- a/crates/types/src/rpc_endpoints.json +++ b/crates/types/src/rpc_endpoints.json @@ -861,7 +861,7 @@ "label": "Option (An optional label for this override instance)", "enabled": "bool (Indicates whether this override instance is enabled)", "fetchBeforeUse": "bool (Indicates whether to fetch the latest on-chain account data before applying overrides)", - "keepAlive": "bool (Optional, defaults to true. If false, keep-alive does not keep the account fresh after this override, and its fields age as the clock moves on)", + "keepAlive": "bool (Optional, defaults to true. If false, keep-alive stops rewriting this account from this slot on, and its fields age as the clock moves on. A later override with true starts it again)", "account": "AccountAddress (The account this override targets, as {\"pubkey\": \"\"} or {\"pda\": {\"programId\": \"\", \"seeds\": [ ... ]}})" } } diff --git a/crates/types/src/scenarios.rs b/crates/types/src/scenarios.rs index bb98bbda7..71aab50b7 100644 --- a/crates/types/src/scenarios.rs +++ b/crates/types/src/scenarios.rs @@ -592,10 +592,10 @@ pub struct OverrideInstance { #[serde(default)] #[cfg_attr(feature = "ts-bindings", ts(as = "Option", optional))] pub fetch_before_use: bool, - /// Whether keep-alive rewrites the account after this override, when its template imports - /// keep-alive. Off, the override writes once and its fields age as the clock moves on. + /// Whether keep-alive rewrites this account from this slot on. Off, keep-alive stops for the + /// account, so its fields age as the clock moves on, until a later override turns it on again. #[schemars( - description = "If false, the override writes once and keep-alive does not keep the account fresh afterwards. Defaults to true" + description = "If false, keep-alive stops rewriting this account from this slot on, so its fields age. A later override with true starts it again. Defaults to true" )] #[serde(default = "default_keep_alive")] #[cfg_attr(feature = "ts-bindings", ts(as = "Option", optional))] @@ -1576,6 +1576,20 @@ pub enum YamlKeepAliveAddress { program_id: String, seeds: Vec, }, + /// Every local account that `owner` owns and whose data starts with the discriminator of + /// `account` in the keep-alive template's IDL. + Owned { + owner: YamlOwners, + account: String, + }, +} + +/// One program ID or a list of them. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum YamlOwners { + One(String), + Many(Vec), } impl From for KeepAliveImport { @@ -1592,6 +1606,13 @@ impl From for KeepAliveImport { seeds: seeds.into_iter().map(Into::into).collect(), }) } + YamlKeepAliveAddress::Owned { owner, account } => KeepAliveAddress::Owned { + owners: match owner { + YamlOwners::One(owner) => vec![owner], + YamlOwners::Many(owners) => owners, + }, + account, + }, }; KeepAliveImport { template: yaml.template, @@ -1626,10 +1647,18 @@ pub enum KeepAliveAddress { Input(String), /// A fixed or derived address. PDA seeds resolve against the importing override's values. Account(AccountAddress), + /// Every account in the surfnet that one of `owners` owns and whose data starts with the + /// discriminator of `account` in the keep-alive template's IDL, including accounts loaded after + /// the override played. Only local accounts are written, never fetched. + Owned { + owners: Vec, + account: String, + }, } impl KeepAliveImport { - /// The address to write, given the address the importing override wrote and its values. + /// The address to write, given the address the importing override wrote and its values. `None` + /// for an owned import, which names no single account. pub fn address( &self, written: Pubkey, @@ -1642,6 +1671,7 @@ impl KeepAliveImport { .as_str() .and_then(|address| Pubkey::from_str(address).ok()), KeepAliveAddress::Account(address) => address.resolve(Some(values)), + KeepAliveAddress::Owned { .. } => None, } } @@ -1676,6 +1706,16 @@ impl KeepAliveImport { format!("keep-alive '{template}': invalid address '{address}': {e}") })?; } + if let KeepAliveAddress::Owned { owners, .. } = &self.address { + if owners.is_empty() { + return Err(format!("keep-alive '{template}' names no owner")); + } + for owner in owners { + Pubkey::from_str(owner).map_err(|e| { + format!("keep-alive '{template}': invalid owner '{owner}': {e}") + })?; + } + } let clock = KeepAliveClock { slot: 0, unix_time_ms: 0, @@ -1687,6 +1727,17 @@ impl KeepAliveImport { } impl OverrideTemplate { + /// The discriminator of `account` in this template's IDL, when it has one. + pub fn account_discriminator(&self, account: &str) -> Option<&[u8]> { + self.idl + .as_ref()? + .accounts + .iter() + .find(|idl_account| idl_account.name == account) + .map(|idl_account| idl_account.discriminator.as_slice()) + .filter(|discriminator| !discriminator.is_empty()) + } + /// The input properties keep-alive imports read addresses from. They are never written. pub fn keep_alive_inputs(&self) -> impl Iterator { self.keep_alive @@ -2101,6 +2152,40 @@ templates: "template: t\naddress: { type: pda, program_id: nope, seeds: [] }\nvalues: { slot: 1 }\n", "invalid address", ); + refused( + "template: t\naddress: { type: owned, owner: nope, account: A }\nvalues: { slot: 1 }\n", + "invalid owner 'nope'", + ); + refused( + "template: t\naddress: { type: owned, owner: [], account: A }\nvalues: { slot: 1 }\n", + "names no owner", + ); + } + + #[test] + fn an_owned_import_takes_one_owner_or_a_list() { + use solana_pubkey::Pubkey; + let (first, second) = (Pubkey::new_unique(), Pubkey::new_unique()); + let owned = |owner: String| { + keep_alive(&format!( + "template: t\naddress: {{ type: owned, owner: {owner}, account: Price }}\nvalues: {{ slot: $slot }}\n" + )) + }; + let expected = |owners: &[Pubkey]| super::KeepAliveAddress::Owned { + owners: owners.iter().map(Pubkey::to_string).collect(), + account: "Price".to_string(), + }; + let one = owned(format!("\"{first}\"")); + assert_eq!(one.address, expected(&[first])); + one.validate().unwrap(); + let many = owned(format!("[\"{first}\", \"{second}\"]")); + assert_eq!(many.address, expected(&[first, second])); + many.validate().unwrap(); + assert_eq!( + many.address(first, &HashMap::new()), + None, + "it names no single account" + ); } #[test] From ebea6b0b133a5a260189218ee4cb65121cd3154c Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 17:37:00 +0200 Subject: [PATCH 11/24] feat(scenarios): keep every loaded Pyth price of a receiver published with owned keep-alive --- .../pyth/core-compatible/v2/README.md | 12 +- .../pyth/core-compatible/v2/overrides.yaml | 17 ++- .../protocols/pyth/v2/overrides.yaml | 21 ++-- crates/core/src/scenarios/registry.rs | 16 ++- crates/core/src/tests/pyth/mod.rs | 108 ++++++++++++------ 5 files changed, 114 insertions(+), 60 deletions(-) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md index fb1111d2c..27e14795d 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md @@ -14,11 +14,13 @@ them. Take the price account from the consumer's own account that names it. # Keep-alive Nobody publishes Pyth prices on a surfnet, so both templates import a -[keep-alive](../../../../README.md#keep-alive): from the slot an override plays until the network -is reset, Surfpool writes the Clock's unix seconds to `price_message.publish_time` and the slot to -`posted_slot` every slot, time travels included. The price, confidence and EMA fields stay as the -scenario wrote them. A price account no override names is not republished and ages against the -Surfnet clock. +[keep-alive](../../../../README.md#keep-alive): from the slot an override of a template plays until +the network is reset, Surfpool writes the Clock's unix seconds to `price_message.publish_time` and +the slot to `posted_slot` every slot, time travels included. It does so for every price account of +that template's receiver the surfnet has loaded, including feeds no override names and, from the +next slot, feeds a transaction loads later, so a liquidation that reads the borrower's other feeds +finds them fresh. The price, confidence and EMA fields keep their values. To keep one feed stale on +purpose, override it with `keepAlive: false`; it then ages against the Surfnet clock. # IDL diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index b6a24e88b..b82bdf9e1 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -10,7 +10,7 @@ tags: keep_alive: - template: pyth-core-compatible-price-publication - address: { type: override } + address: { type: owned, owner: rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp, account: PriceUpdateV2 } values: { price_message.publish_time: $unix_s, posted_slot: $slot } templates: @@ -67,11 +67,16 @@ templates: of it, so a large drop that keeps the live conf can be refused. THE PRICE STAYS PUBLISHED BY ITSELF. From the slot this override plays until the network is - reset, Surfpool republishes this price account every slot, as the Pyth publisher does on - mainnet: publish_time becomes the Surfnet clock's unix seconds and posted_slot the slot, also - after a time travel. Price, conf and the EMA fields keep the values this override wrote. A - value set for publish_time or posted_slot never takes effect, so leave both unset. A price - account no override names is not republished and ages against the Surfnet clock. + reset, Surfpool republishes every price account of the Pyth Core Compatible receiver the + Surfnet has loaded every slot, as the Pyth publisher does on mainnet: publish_time becomes the + Surfnet clock's unix seconds and posted_slot the slot, also after a time travel. This includes + feeds no override names and, from the next slot, feeds a transaction loads later, so a + liquidation that reads the borrower's other feeds finds them fresh. Price, conf and the EMA + fields keep their values. A value set for publish_time or posted_slot never takes effect, so + leave both unset. + + STALE PRICE: to keep one feed stale on purpose, override it with keepAlive: false. It then + ages against the Surfnet clock. EXAMPLE - "SOL drops to $20" on an account with exponent -8, live price p and ema_price q: price_message.price: 2000000000 diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index a8ac0d6fc..20bd2255e 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -11,7 +11,7 @@ tags: keep_alive: - template: pyth-price-publication - address: { type: override } + address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: PriceUpdateV2 } values: { price_message.publish_time: $unix_s, posted_slot: $slot } constants: @@ -262,15 +262,18 @@ templates: - price_message.ema_price and price_message.ema_conf use the same scales as price and conf. THE PRICE STAYS PUBLISHED BY ITSELF. From the slot this override plays until the network is - reset, Surfpool republishes this price account every slot, as the Pyth publisher does on - mainnet: publish_time becomes the Surfnet clock's unix seconds and posted_slot the slot, also - after a time travel. Price, conf and the EMA fields keep the values this override wrote. A - value set for publish_time or posted_slot never takes effect, so leave both unset. + reset, Surfpool republishes every price account of the Pyth Core receiver the Surfnet has + loaded every slot, as the Pyth publisher does on mainnet: publish_time becomes the Surfnet + clock's unix seconds and posted_slot the slot, also after a time travel. This includes feeds + no override names and, from the next slot, feeds a transaction loads later, so a liquidation + that reads the borrower's other feeds finds them fresh. Price, conf and the EMA fields keep + their values. A value set for publish_time or posted_slot never takes effect, so leave both + unset. - STALE PRICE: a price account no override of this template names is not republished and ages - against the Surfnet clock. To test a consumer's staleness check, leave that feed without an - override and surfnet_timeTravel past the consumer's limit. Its absoluteTimestamp is in - MILLISECONDS, while publish_time and the Clock sysvar are in SECONDS. + STALE PRICE: to keep one feed stale on purpose, override it with keepAlive: false. It then + ages against the Surfnet clock. To test a consumer's staleness check, add that override and + surfnet_timeTravel past the consumer's limit. Its absoluteTimestamp is in MILLISECONDS, while + publish_time and the Clock sysvar are in SECONDS. address: type: pda program_id: pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index ec0ff7d3c..16bf0cb43 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -1734,11 +1734,16 @@ templates: [] #[test] fn pyth_price_feeds_keep_their_price_published() { let registry = TemplateRegistry::new(); - for (id, publication) in [ - ("pyth-price-feed-v2", "pyth-price-publication"), + for (id, publication, receiver) in [ + ( + "pyth-price-feed-v2", + "pyth-price-publication", + "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ", + ), ( "pyth-core-compatible-price-feed-v2", "pyth-core-compatible-price-publication", + "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp", ), ] { let template = registry.get(id).unwrap(); @@ -1748,8 +1753,11 @@ templates: [] assert_eq!(import.template, publication, "{id}"); assert_eq!( import.address, - surfpool_types::KeepAliveAddress::Override, - "{id}" + surfpool_types::KeepAliveAddress::Owned { + owners: vec![receiver.to_string()], + account: "PriceUpdateV2".to_string(), + }, + "{id} must keep every price account of its receiver published" ); let mut paths: Vec<&str> = import.values.keys().map(String::as_str).collect(); paths.sort(); diff --git a/crates/core/src/tests/pyth/mod.rs b/crates/core/src/tests/pyth/mod.rs index 6b2705cfb..fcd52a22c 100644 --- a/crates/core/src/tests/pyth/mod.rs +++ b/crates/core/src/tests/pyth/mod.rs @@ -155,9 +155,11 @@ async fn core_compatible_price_feed_touches_only_price_fields() { } } -/// Keep-alive republishes a price account a scenario overrides every slot, as the Pyth publisher -/// does on mainnet, time travels included. Only the publication fields move with the Clock: the -/// price stays the scenario's. +/// Once a scenario overrides one price account, keep-alive republishes every price account of its +/// receiver every slot, as the Pyth publisher does on mainnet, time travels included: the +/// overridden one, and one loaded after the override played. Only the publication fields move with +/// the Clock: each price stays as it was. An account overridden with keep-alive off is not +/// republished. #[tokio::test(flavor = "multi_thread")] async fn price_feeds_stay_published_through_surfnet_svm() { const PRICE: i64 = 2_000_000_000; @@ -178,11 +180,15 @@ async fn price_feeds_stay_published_through_surfnet_svm() { ); let target = Pubkey::from_str_const(address); + let stale = Pubkey::new_unique(); + let loaded_later = Pubkey::new_unique(); let (svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); let locker = SurfnetSvmLocker::new(svm); - locker.with_svm_writer(|svm| svm.set_account(&target, live.clone()).unwrap()); - let mut scenario = Scenario::new("Pyth SOL at $20".to_string(), "Price only".to_string()); - scenario.add_override( + locker.with_svm_writer(|svm| { + svm.set_account(&target, live.clone()).unwrap(); + svm.set_account(&stale, live.clone()).unwrap(); + }); + let price_override = |address: &Pubkey| { OverrideInstance::new( template_id.to_string(), 0, @@ -191,43 +197,73 @@ async fn price_feeds_stay_published_through_surfnet_svm() { .with_values(HashMap::from([( "price_message.price".to_string(), serde_json::json!(PRICE), - )])), - ); + )])) + }; + let mut scenario = Scenario::new("Pyth SOL at $20".to_string(), "Price only".to_string()); + scenario.add_override(price_override(&target)); + let mut stale_override = price_override(&stale); + stale_override.keep_alive = false; + scenario.add_override(stale_override); locker.register_scenario(scenario, None).unwrap(); - let assert_published = |when: &str| { - let (data, clock) = locker.with_svm_reader(|svm| { + let read = |address: &Pubkey| { + locker.with_svm_reader(|svm| { ( - svm.get_account(&target).unwrap().unwrap().data, + svm.get_account(address).unwrap().unwrap().data, svm.inner.get_sysvar::(), ) - }); - let word = |offset: usize| <[u8; 8]>::try_from(&data[offset..offset + 8]).unwrap(); - assert_eq!( - i64::from_le_bytes(word(93)), - clock.unix_timestamp, - "{template_id} {when}: publish_time" - ); - assert_eq!( - u64::from_le_bytes(word(125)), - clock.slot, - "{template_id} {when}: posted_slot" - ); - assert_eq!(i64::from_le_bytes(word(73)), PRICE, "{template_id} {when}"); - let diffs: Vec = (0..live.data.len()) - .filter(|&i| data[i] != live.data[i]) - .collect(); - assert!( - diffs.iter().all(|i| [73..81, 93..101, 125..133] - .iter() - .any(|written| written.contains(i))), - "{template_id} {when}: changed {diffs:?}" - ); + }) + }; + let word = + |data: &[u8], offset: usize| <[u8; 8]>::try_from(&data[offset..offset + 8]).unwrap(); + let assert_published = |when: &str, with_loaded_later: bool| { + let mut published = vec![(target, "overridden", PRICE)]; + if with_loaded_later { + published.push(( + loaded_later, + "loaded later", + i64::from_le_bytes(word(&live.data, 73)), + )); + } + for (address, name, price) in published { + let (data, clock) = read(&address); + let what = format!("{name} {when}"); + assert_eq!( + i64::from_le_bytes(word(&data, 93)), + clock.unix_timestamp, + "{template_id} {what}: publish_time" + ); + assert_eq!( + u64::from_le_bytes(word(&data, 125)), + clock.slot, + "{template_id} {what}: posted_slot" + ); + assert_eq!( + i64::from_le_bytes(word(&data, 73)), + price, + "{template_id} {what}" + ); + let diffs: Vec = (0..live.data.len()) + .filter(|&i| data[i] != live.data[i]) + .collect(); + assert!( + diffs.iter().all(|i| [73..81, 93..101, 125..133] + .iter() + .any(|written| written.contains(i))), + "{template_id} {what}: changed {diffs:?}" + ); + } + let mut unpublished = live.data.clone(); + unpublished[73..81].copy_from_slice(&PRICE.to_le_bytes()); + assert_eq!(read(&stale).0, unpublished, "{template_id} stale {when}"); }; - for slot in 1..=3 { + locker.confirm_current_block(&None).await.unwrap(); + assert_published("slot 1", false); + locker.with_svm_writer(|svm| svm.set_account(&loaded_later, live.clone()).unwrap()); + for slot in 2..=3 { locker.confirm_current_block(&None).await.unwrap(); - assert_published(&format!("slot {slot}")); + assert_published(&format!("slot {slot}"), true); } let clock = locker.with_svm_reader(|svm| svm.inner.get_sysvar::()); locker @@ -241,6 +277,6 @@ async fn price_feeds_stay_published_through_surfnet_svm() { ) .await .unwrap(); - assert_published("after a time travel"); + assert_published("after a time travel", true); } } From 660d37b4d94dee946ee6f0fcb7f8781aee1ed01e Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 07:47:35 +0200 Subject: [PATCH 12/24] fix(scenarios): restart every keep-alive binding of an account when keepAlive is on again --- crates/core/src/scenarios/README.md | 3 +- crates/core/src/scenarios/keep_alive.rs | 96 ++++++++++++++++++++++--- 2 files changed, 90 insertions(+), 9 deletions(-) diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 3f20849ea..4e7311a1c 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -124,7 +124,8 @@ Keep-alive starts in the slot the importing override plays and rewrites its fiel that slot's overrides, until the network is reset. An override of one of those fields therefore never takes effect. An override with `keepAlive: false` stops keep-alive for the account it writes from that slot on, so the account ages as the clock moves on, for example to test a stale price. A -later override with `keepAlive: true`, the default, on that account starts it again. An account not +later override with `keepAlive: true`, the default, on that account starts it again, with every import +that rewrites it, including imports bound by other templates' overrides. An account not yet in the surfnet is fetched from the remote first, unless it, or its owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops until an importing override plays again. diff --git a/crates/core/src/scenarios/keep_alive.rs b/crates/core/src/scenarios/keep_alive.rs index 4dd9a7ae4..9534dcefd 100644 --- a/crates/core/src/scenarios/keep_alive.rs +++ b/crates/core/src/scenarios/keep_alive.rs @@ -2,7 +2,8 @@ //! maker republishing its quote. Nobody runs those actors against a surfnet, so once a scenario's //! override touches an account, the surfnet applies the keep-alive templates its template imports //! every slot, as ordinary overrides, until the network is reset. An override with `keep_alive` -//! off stops keep-alive for the account it writes, until an override with it on writes that account. +//! off stops keep-alive for the account it writes, until an override with it on writes that account, +//! which restarts every import that rewrites it. use std::collections::{BTreeSet, HashMap, HashSet}; @@ -52,18 +53,18 @@ pub struct KeepAliveKind { pub struct KeepAlive { pub bindings: BTreeSet, pub kinds: BTreeSet, - /// Accounts an override with `keep_alive` off wrote last. Keep-alive skips them. + /// Accounts an override with `keep_alive` off wrote last. Keep-alive skips them but keeps + /// their bindings, so an override with it on restarts them all. pub excluded: HashSet, } impl KeepAlive { /// Applies the overrides that wrote `touched`, in order: one with `keep_alive` off stops /// keep-alive for its account, one with it on starts it again and adds its template's imports. + /// An import that rewrites a stopped account is bound too, and starts when the account does. pub fn enroll(&mut self, registry: &TemplateRegistry, touched: Vec) { for source in touched { if !source.keep_alive { - self.bindings - .retain(|binding| binding.address != source.address); if self.excluded.insert(source.address) { info!("Keep-alive stops rewriting {}", source.address); } @@ -94,9 +95,6 @@ impl KeepAlive { ); continue; }; - if self.excluded.contains(&address) { - continue; - } let binding = KeepAliveBinding { template: template.id.clone(), import: index, @@ -130,6 +128,7 @@ impl KeepAlive { let mut targets = Vec::new(); for binding in &self.bindings { if let Some(import) = import_of(&binding.template, binding.import) + && !self.excluded.contains(&binding.address) && seen.insert((import.template.as_str(), binding.address)) { targets.push((import, binding.address)); @@ -333,7 +332,7 @@ templates: &surfnet.registry, vec![source("pyth-price-feed-v2", oracle, oracle, false)], ); - assert!(keep_alive.bindings.is_empty(), "its binding is dropped"); + assert_eq!(keep_alive.bindings.len(), 1, "its binding is kept"); assert_eq!(surfnet.targets(&keep_alive), [other_price]); keep_alive.enroll( @@ -352,4 +351,85 @@ templates: ); assert_eq!(surfnet.targets(&keep_alive), [oracle, other_price]); } + + const INPUT_OVERRIDES: &str = r#" +protocol: Example +version: v1 +account_type: State +raw_layout: true +templates: + - id: example-vault + name: Vault + description: Example vault + keep_alive: + - template: example-price-fresh + address: { type: input, value: oracle } + values: { posted_slot: $slot } + address: { type: pubkey } + properties: + - { path: balance, offset: 0, encoding: u64, description: Balance } + - { path: oracle, type: input, value_type: pubkey, description: The vault's oracle } + - id: example-oracle + name: Oracle + description: Example oracle + address: { type: pubkey } + properties: + - { path: price, offset: 0, encoding: u64, description: Price } +"#; + + #[test] + fn keep_alive_on_again_restores_another_templates_binding() { + let surfnet = LocalAccounts { + registry: owned_registry(INPUT_OVERRIDES), + ..LocalAccounts::new() + }; + assert!( + surfnet + .registry + .get("example-oracle") + .unwrap() + .keep_alive + .is_empty(), + "re-enabling must not import anything itself" + ); + let oracle = Pubkey::new_unique(); + let mut keep_alive = KeepAlive::default(); + keep_alive.enroll( + &surfnet.registry, + vec![source("example-vault", Pubkey::new_unique(), oracle, true)], + ); + assert_eq!(surfnet.targets(&keep_alive), [oracle]); + + keep_alive.enroll( + &surfnet.registry, + vec![source("example-oracle", oracle, oracle, false)], + ); + assert!(surfnet.targets(&keep_alive).is_empty()); + + keep_alive.enroll( + &surfnet.registry, + vec![source("example-oracle", oracle, oracle, true)], + ); + assert_eq!(surfnet.targets(&keep_alive), [oracle]); + + let mut off_first = KeepAlive::default(); + off_first.enroll( + &surfnet.registry, + vec![ + source("example-oracle", oracle, oracle, false), + source("example-vault", Pubkey::new_unique(), oracle, true), + ], + ); + assert!(surfnet.targets(&off_first).is_empty()); + + off_first.enroll( + &surfnet.registry, + vec![source("example-oracle", oracle, oracle, true)], + ); + assert_eq!( + surfnet.targets(&off_first), + [oracle], + "a vault that played while the oracle was off still bound it" + ); + } } From 7c1dbf75756d88ea47f943b302d2dd13a21eb5ed Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 07:48:13 +0200 Subject: [PATCH 13/24] docs(scenarios): say in each price template that it keeps every loaded price fresh --- .../scenarios/protocols/pyth/core-compatible/v2/overrides.yaml | 2 +- crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index b82bdf9e1..7527becca 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -16,7 +16,7 @@ keep_alive: templates: - id: pyth-core-compatible-price-feed-v2 name: Override Pyth Core Compatible Price Account - description: Override a price account of the Pyth Core Compatible receiver, found by address + description: Override a price account of the Pyth Core Compatible receiver, found by address; keeps every loaded one published idl_account_name: PriceUpdateV2 properties: - path: price_message.price diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index 20bd2255e..f33db7384 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -199,7 +199,7 @@ constants: templates: - id: pyth-price-feed-v2 name: Override Price Feed - description: Override any Pyth price feed with custom price data + description: Override any Pyth price feed with custom price data; keeps every loaded Pyth Core price account published idl_account_name: PriceUpdateV2 properties: - path: feed_id From 8706557f8e92fd641e97cac842e1783e8fc86741 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 10:08:38 +0200 Subject: [PATCH 14/24] docs(scenarios): tell the Pyth Core template's reader which protocols read its receiver --- crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index f33db7384..2827c3be9 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -234,6 +234,12 @@ templates: CRITICAL: Always set fetchBeforeUse: true for Pyth price feeds! This fetches the current account data from mainnet before applying your price override. + WHICH RECEIVER: this template writes price accounts of the Pyth Core receiver + rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, which Save and Kamino read. Project 0 reads the + Pyth Core Compatible receiver instead: for a Project 0 price use + pyth-core-compatible-price-feed-v2 on the bank's config.oracle_keys.0. When a protocol's own + templates name the price account it reads, follow them. + HOW TO USE THIS TEMPLATE: 1. Select the correct price feed from the `feed_id` constant options (e.g., SOL/USD, BTC/USD) 2. Check the feed's `llm_context` field for its decimal precision (most use 8, some use 10) From 7cd2a682b3f36314b409f7c91769f4ec79160af6 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 11:00:07 +0200 Subject: [PATCH 15/24] docs(scenarios): explain how to keep one Pyth price stale while the others stay fresh --- .../pyth/core-compatible/v2/overrides.yaml | 11 +++++++++-- .../scenarios/protocols/pyth/v2/overrides.yaml | 16 ++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index 7527becca..d2c98accf 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -75,8 +75,15 @@ templates: fields keep their values. A value set for publish_time or posted_slot never takes effect, so leave both unset. - STALE PRICE: to keep one feed stale on purpose, override it with keepAlive: false. It then - ages against the Surfnet clock. + STALE PRICE: keep-alive starts only when an override with keepAlive: true writes a price + account, and an override with no values writes nothing. To keep one feed stale while the + others stay fresh, add two overrides of this template, both with fetchBeforeUse: true and + price_message.price set to the account's current price (getAccountInfo, encoding + "jsonParsed"), so no price changes: + - on the stale feed's price account, keepAlive: false. It then ages against the Surfnet + clock and turns stale once the consumer's age limit has passed; + - on any other price account the same consumer reads, keepAlive: true. This starts the + republishing of every loaded price account except the stale one. EXAMPLE - "SOL drops to $20" on an account with exponent -8, live price p and ema_price q: price_message.price: 2000000000 diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index 2827c3be9..1689eb4a8 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -276,10 +276,18 @@ templates: their values. A value set for publish_time or posted_slot never takes effect, so leave both unset. - STALE PRICE: to keep one feed stale on purpose, override it with keepAlive: false. It then - ages against the Surfnet clock. To test a consumer's staleness check, add that override and - surfnet_timeTravel past the consumer's limit. Its absoluteTimestamp is in MILLISECONDS, while - publish_time and the Clock sysvar are in SECONDS. + STALE PRICE: keep-alive starts only when an override with keepAlive: true writes a price + account, and an override with no values beyond feed_id writes nothing. To keep one feed + stale while the others stay fresh, add two overrides of this template, both with + fetchBeforeUse: true and price_message.price set to the feed's current price + (getAccountInfo, encoding "jsonParsed"), so no price changes: + - on the stale feed, keepAlive: false. It then ages against the Surfnet clock and turns + stale once the consumer's age limit has passed; + - on any other feed the same consumer reads, keepAlive: true. This starts the + republishing of every loaded price account except the stale one. + To make it stale at once, surfnet_timeTravel past the consumer's limit. Its + absoluteTimestamp is in MILLISECONDS, while publish_time and the Clock sysvar are in + SECONDS. address: type: pda program_id: pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT From 5fcded70bf50104ef3ea6ae7b8eb0618e1fde7b7 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 12:36:28 +0200 Subject: [PATCH 16/24] docs(scenarios): say that an override with keepAlive false starts no keep-alive --- crates/core/src/scenarios/README.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 4e7311a1c..97d131a9a 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -124,11 +124,14 @@ Keep-alive starts in the slot the importing override plays and rewrites its fiel that slot's overrides, until the network is reset. An override of one of those fields therefore never takes effect. An override with `keepAlive: false` stops keep-alive for the account it writes from that slot on, so the account ages as the clock moves on, for example to test a stale price. A -later override with `keepAlive: true`, the default, on that account starts it again, with every import -that rewrites it, including imports bound by other templates' overrides. An account not -yet in the surfnet is fetched from the remote first, unless it, or its owner with its owned accounts, -is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops -until an importing override plays again. +later override with `keepAlive: true`, the default, on that account starts it again, with every +import that rewrites it, including imports bound by other templates' overrides. An override with +`keepAlive: false` binds none of its template's imports, so on its own it starts no keep-alive, also +not for the other accounts those imports rewrite: add an override with `keepAlive: true` when they +must stay fresh. An override with no values writes nothing, so it neither starts nor stops +keep-alive. An account not yet in the surfnet is fetched from the remote first, unless it, or its +owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart +on a persistent database it stops until an importing override plays again. ### Override Templates Directly using the `surfnet_registerScenario` endpoint requires building out a map of account keys that are specific to the schema of the account that is being written to. From 8a2d644b6c977008c337be0f18b2ff23123b6501 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 12:36:29 +0200 Subject: [PATCH 17/24] docs(scenarios): a Pyth publish_time or posted_slot value holds only with keepAlive false --- .../protocols/pyth/core-compatible/v2/overrides.yaml | 8 ++++---- .../core/src/scenarios/protocols/pyth/v2/overrides.yaml | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index d2c98accf..b4d718de3 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -30,7 +30,7 @@ templates: description: Decimal exponent, normally -8 and -10 on some feeds. Rescales every price field - path: price_message.publish_time label: Publish Time - description: Unix seconds of this update, interpreted against the Surfnet clock + description: Unix seconds of this update, interpreted against the Surfnet clock. Keep-alive writes the Clock time every slot, so a value set here holds only with keepAlive false - path: price_message.prev_publish_time label: Previous Publish Time description: Unix seconds of the preceding update @@ -42,7 +42,7 @@ templates: description: Exponential moving average confidence, in the same scale as conf - path: posted_slot label: Posted Slot - description: Slot the update was posted at, for consumers that measure freshness in slots + description: Slot the update was posted at, for consumers that measure freshness in slots. Keep-alive writes the current slot every slot, so a value set here holds only with keepAlive false address: type: pubkey llm_context: | @@ -72,8 +72,8 @@ templates: Surfnet clock's unix seconds and posted_slot the slot, also after a time travel. This includes feeds no override names and, from the next slot, feeds a transaction loads later, so a liquidation that reads the borrower's other feeds finds them fresh. Price, conf and the EMA - fields keep their values. A value set for publish_time or posted_slot never takes effect, so - leave both unset. + fields keep their values. With keepAlive: true, a value set for publish_time or posted_slot + never takes effect, so leave both unset. STALE PRICE: keep-alive starts only when an override with keepAlive: true writes a price account, and an override with no values writes nothing. To keep one feed stale while the diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index 1689eb4a8..97d725dc8 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -217,7 +217,7 @@ templates: description: Decimal exponent, normally -8 and -10 on some feeds. Rescales every price field - path: price_message.publish_time label: Publish Time - description: Unix seconds of this update, interpreted against the Surfnet clock + description: Unix seconds of this update, interpreted against the Surfnet clock. Keep-alive writes the Clock time every slot, so a value set here holds only with keepAlive false - path: price_message.prev_publish_time label: Previous Publish Time description: Unix seconds of the preceding update @@ -229,7 +229,7 @@ templates: description: Exponential moving average confidence, in the same scale as conf - path: posted_slot label: Posted Slot - description: Slot the update was posted at, for consumers that measure freshness in slots + description: Slot the update was posted at, for consumers that measure freshness in slots. Keep-alive writes the current slot every slot, so a value set here holds only with keepAlive false llm_context: | CRITICAL: Always set fetchBeforeUse: true for Pyth price feeds! This fetches the current account data from mainnet before applying your price override. @@ -273,8 +273,8 @@ templates: clock's unix seconds and posted_slot the slot, also after a time travel. This includes feeds no override names and, from the next slot, feeds a transaction loads later, so a liquidation that reads the borrower's other feeds finds them fresh. Price, conf and the EMA fields keep - their values. A value set for publish_time or posted_slot never takes effect, so leave both - unset. + their values. With keepAlive: true, a value set for publish_time or posted_slot never takes + effect, so leave both unset. STALE PRICE: keep-alive starts only when an override with keepAlive: true writes a price account, and an override with no values beyond feed_id writes nothing. To keep one feed From 695043fce843d6d44fe37952159c027bb4986a71 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 20 Nov 2026 13:55:22 +0200 Subject: [PATCH 18/24] feat(scenarios): let an override pass its own keep-alive imports --- crates/core/src/scenarios/README.md | 45 +- crates/core/src/scenarios/keep_alive.rs | 429 ++---------------- crates/core/src/scenarios/registry.rs | 93 ++-- crates/core/src/surfnet/svm.rs | 295 +++++++++--- .../kit/generated/OverrideInstance.ts | 8 +- .../kit/generated/YamlKeepAliveAddress.ts | 9 + .../kit/generated/YamlKeepAliveImport.ts | 9 + .../surfpool-sdk/kit/generated/YamlPdaSeed.ts | 8 + .../surfpool-sdk/kit/generated/index.ts | 3 + crates/types/src/rpc_endpoints.json | 2 +- crates/types/src/scenarios.rs | 160 +++---- 11 files changed, 449 insertions(+), 612 deletions(-) create mode 100644 crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts create mode 100644 crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts create mode 100644 crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index 97d131a9a..a4d2095eb 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -115,23 +115,46 @@ templates: | `{ type: input, value: oracle }` | the pubkey given in that `input` property (`value_type: pubkey`, never written) | | `{ type: pubkey, value:
}` | a fixed account | | `{ type: pda, program_id, seeds }` | a derived account; seeds resolve against the override's values | -| `{ type: owned, owner: , account: }` | every local account an owner owns whose data starts with that account's discriminator in the keep-alive template's IDL, including accounts loaded later; never fetched | `$slot`, `$slot±N` and `$unix_s`/`ms`/`us`/`ns` in `values` are filled from the slot and its Clock time; other values are written as given. Keep-alive starts in the slot the importing override plays and rewrites its fields every slot, after that slot's overrides, until the network is reset. An override of one of those fields therefore -never takes effect. An override with `keepAlive: false` stops keep-alive for the account it writes -from that slot on, so the account ages as the clock moves on, for example to test a stale price. A -later override with `keepAlive: true`, the default, on that account starts it again, with every -import that rewrites it, including imports bound by other templates' overrides. An override with -`keepAlive: false` binds none of its template's imports, so on its own it starts no keep-alive, also -not for the other accounts those imports rewrite: add an override with `keepAlive: true` when they -must stay fresh. An override with no values writes nothing, so it neither starts nor stops -keep-alive. An account not yet in the surfnet is fetched from the remote first, unless it, or its -owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart -on a persistent database it stops until an importing override plays again. +never takes effect. An account not yet in the surfnet is fetched from the remote first, unless it, +or its owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops +until an importing override plays again. + +An override can give its own `keepAlive` list, in the shape of a `keep_alive` list, in place of its +template's. Without `keepAlive`, the template's list applies. With a list, `[]` included, keep-alive +first stops for everything that earlier overrides of the same account started, then the override's +own imports start. Keep-alive that overrides of other accounts started does not change. So `[]` +turns keep-alive off for the account's overrides, and a list repeats any template import it still +needs. A `pubkey` import keeps an account fresh that no override writes, such as another price feed +a transaction reads: + +```json +{ + "id": "vault-balance", + "templateId": "example-vault-balance", + "values": { "balance": 1000, "oracle": "" }, + "scenarioRelativeSlot": 0, + "enabled": true, + "account": { "pubkey": "" }, + "keepAlive": [ + { + "template": "example-oracle-fresh", + "address": { "type": "input", "value": "oracle" }, + "values": { "publication_slot": "$slot", "publication_time": "$unix_ms" } + }, + { + "template": "example-oracle-fresh", + "address": { "type": "pubkey", "value": "" }, + "values": { "publication_slot": "$slot", "publication_time": "$unix_ms" } + } + ] +} +``` ### Override Templates Directly using the `surfnet_registerScenario` endpoint requires building out a map of account keys that are specific to the schema of the account that is being written to. diff --git a/crates/core/src/scenarios/keep_alive.rs b/crates/core/src/scenarios/keep_alive.rs index 9534dcefd..dd5e3d097 100644 --- a/crates/core/src/scenarios/keep_alive.rs +++ b/crates/core/src/scenarios/keep_alive.rs @@ -1,19 +1,16 @@ //! Keep-alive covers what a protocol's own off-chain actor rewrites every slot, such as a market //! maker republishing its quote. Nobody runs those actors against a surfnet, so once a scenario's //! override touches an account, the surfnet applies the keep-alive templates its template imports -//! every slot, as ordinary overrides, until the network is reset. An override with `keep_alive` -//! off stops keep-alive for the account it writes, until an override with it on writes that account, -//! which restarts every import that rewrites it. +//! every slot, as ordinary overrides, until the network is reset. -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::HashMap; -use solana_account::Account; use solana_pubkey::Pubkey; -use surfpool_types::{KeepAliveAddress, KeepAliveImport}; +use surfpool_types::KeepAliveImport; use super::TemplateRegistry; -/// An account a scenario's override wrote. +/// An account a scenario's override wrote through a template that imports keep-alive. #[derive(Clone, Debug)] pub struct KeepAliveSource { pub template: String, @@ -21,8 +18,8 @@ pub struct KeepAliveSource { pub address: Pubkey, /// The override's values, which input and PDA addresses resolve against. pub values: HashMap, - /// The override's `keep_alive`: off, keep-alive stops for `address`. - pub keep_alive: bool, + /// The override's own keep-alive list, which replaces the template's. + pub imports: Option>, } /// Binds a template's keep-alive import to the account it rewrites every slot, resolved when an @@ -31,405 +28,37 @@ pub struct KeepAliveSource { pub struct KeepAliveBinding { /// The importing template's ID. pub template: String, - /// The import's index in that template's `keep_alive` list. + /// The import's index in that template's `keep_alive` list, or in the override's own list. pub import: usize, /// The address the import rewrites. pub address: Pubkey, + /// Whether the import is in the override's own list, kept by `source`. + pub own: bool, + /// The address the importing override wrote. + pub source: Pubkey, } -/// Binds a template's owned keep-alive import, which rewrites every local account of a kind, -/// resolved again each slot since the surfnet keeps loading accounts. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct KeepAliveKind { - /// The importing template's ID. - pub template: String, - /// The import's index in that template's `keep_alive` list. - pub import: usize, -} - -/// What keep-alive rewrites every slot. Kept in memory only, so a restart on a persistent database -/// stops keep-alive. -#[derive(Clone, Debug, Default)] -pub struct KeepAlive { - pub bindings: BTreeSet, - pub kinds: BTreeSet, - /// Accounts an override with `keep_alive` off wrote last. Keep-alive skips them but keeps - /// their bindings, so an override with it on restarts them all. - pub excluded: HashSet, -} - -impl KeepAlive { - /// Applies the overrides that wrote `touched`, in order: one with `keep_alive` off stops - /// keep-alive for its account, one with it on starts it again and adds its template's imports. - /// An import that rewrites a stopped account is bound too, and starts when the account does. - pub fn enroll(&mut self, registry: &TemplateRegistry, touched: Vec) { - for source in touched { - if !source.keep_alive { - if self.excluded.insert(source.address) { - info!("Keep-alive stops rewriting {}", source.address); - } - continue; - } - self.excluded.remove(&source.address); - let Some(template) = registry.get(&source.template) else { - continue; - }; - for (index, import) in template.keep_alive.iter().enumerate() { - if let KeepAliveAddress::Owned { owners, account } = &import.address { - let kind = KeepAliveKind { - template: template.id.clone(), - import: index, - }; - if self.kinds.insert(kind) { - info!( - "Keep-alive '{}' rewrites every local '{}' of {:?} every slot", - import.template, account, owners - ); - } - continue; - } - let Some(address) = import.address(source.address, &source.values) else { - warn!( - "Keep-alive '{}' of override template '{}' has no address for {}", - import.template, template.id, source.address - ); - continue; - }; - let binding = KeepAliveBinding { - template: template.id.clone(), - import: index, - address, - }; - if self.bindings.insert(binding) { - info!( - "Keep-alive '{}' rewrites {} every slot", - import.template, address - ); - } - } - } - } - - /// Each account to rewrite this slot with the import that rewrites it: every binding, then - /// every account `accounts_owned_by` returns for a kind's owners that holds the kind's account - /// type. Excluded accounts are skipped, and so is an account a keep-alive template already - /// rewrites. - pub fn targets<'r>( +impl KeepAliveBinding { + /// The import this binding applies. + pub fn find<'a>( &self, - registry: &'r TemplateRegistry, - accounts_owned_by: impl Fn(&Pubkey) -> Vec<(Pubkey, Account)>, - ) -> Vec<(&'r KeepAliveImport, Pubkey)> { - let import_of = |template: &str, index: usize| { - registry - .get(template) - .and_then(|template| template.keep_alive.get(index)) - }; - let mut seen = HashSet::new(); - let mut targets = Vec::new(); - for binding in &self.bindings { - if let Some(import) = import_of(&binding.template, binding.import) - && !self.excluded.contains(&binding.address) - && seen.insert((import.template.as_str(), binding.address)) - { - targets.push((import, binding.address)); - } - } - for kind in &self.kinds { - let Some(import) = import_of(&kind.template, kind.import) else { - continue; - }; - let KeepAliveAddress::Owned { owners, account } = &import.address else { - continue; - }; - let Some(discriminator) = registry - .get(&import.template) - .and_then(|template| template.account_discriminator(account)) - else { - continue; - }; - for owner in owners.iter().filter_map(|owner| owner.parse().ok()) { - for (address, owned) in accounts_owned_by(&owner) { - if owned.data.starts_with(discriminator) - && !self.excluded.contains(&address) - && seen.insert((import.template.as_str(), address)) - { - targets.push((import, address)); - } - } - } - } - targets - } -} - -#[cfg(test)] -pub(super) mod tests { - use super::*; - use crate::scenarios::registry::PYTH_V2_IDL_CONTENT; - - pub(crate) const OWNER: &str = "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ"; - - pub(crate) const OWNED_OVERRIDES: &str = r#" -protocol: Example -version: v1 -account_type: State -raw_layout: true -templates: - - id: example-vault - name: Vault - description: Example vault - keep_alive: - - template: example-price-fresh - address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: PriceUpdateV2 } - values: { posted_slot: $slot } - - template: example-price-fresh - address: { type: input, value: oracle } - values: { posted_slot: $slot } - address: { type: pubkey } - properties: - - { path: balance, offset: 0, encoding: u64, description: Balance } - - { path: oracle, type: input, value_type: pubkey, description: The vault's oracle } -"#; - - const PRICE_KEEP_ALIVE: &str = r#" -protocol: Example -version: v1 -account_type: PriceUpdateV2 -templates: - - id: example-price-fresh - name: Fresh price - description: What the publisher republishes - address: { type: pubkey } - properties: - - { path: posted_slot, label: Posted slot, description: Posted slot } -"#; - - pub(crate) fn owned_registry(overrides: &str) -> TemplateRegistry { - let mut registry = TemplateRegistry::default(); - registry.load_raw_layout_overrides(overrides, "example"); - registry.load_keep_alive( - Some(serde_json::from_str(PYTH_V2_IDL_CONTENT).unwrap()), - PRICE_KEEP_ALIVE, - "example", - ); - registry - } - - fn account(owner: Pubkey, data: &[u8]) -> Account { - Account { - lamports: 1, - data: data.to_vec(), - owner, - executable: false, - rent_epoch: 0, - } - } - - fn source( - template: &str, - address: Pubkey, - oracle: Pubkey, - keep_alive: bool, - ) -> KeepAliveSource { - KeepAliveSource { - template: template.to_string(), - address, - values: HashMap::from([("oracle".to_string(), serde_json::json!(oracle.to_string()))]), - keep_alive, - } - } - - struct LocalAccounts { - registry: TemplateRegistry, - accounts: Vec<(Pubkey, Account)>, - price: [u8; 8], - } - - impl LocalAccounts { - fn new() -> Self { - let registry = owned_registry(OWNED_OVERRIDES); - let price = registry - .get("example-price-fresh") - .and_then(|template| template.account_discriminator("PriceUpdateV2")) - .unwrap() - .try_into() - .unwrap(); - Self { - registry, - accounts: Vec::new(), - price, - } + registry: &'a TemplateRegistry, + own_imports: &'a HashMap>, + ) -> Option<&'a KeepAliveImport> { + if self.own { + own_imports.get(&self.source)?.get(self.import) + } else { + registry.get(&self.template)?.keep_alive.get(self.import) } - - fn load(&mut self, owner: Pubkey, discriminator: [u8; 8]) -> Pubkey { - let address = Pubkey::new_unique(); - let mut data = discriminator.to_vec(); - data.extend([0; 8]); - self.accounts.push((address, account(owner, &data))); - address - } - - fn targets(&self, keep_alive: &KeepAlive) -> Vec { - keep_alive - .targets(&self.registry, |owner| { - self.accounts - .iter() - .filter(|(_, account)| account.owner == *owner) - .cloned() - .collect() - }) - .into_iter() - .map(|(import, address)| { - assert_eq!(import.template, "example-price-fresh"); - address - }) - .collect() - } - } - - #[test] - fn an_owned_kind_rewrites_every_local_account_of_its_owner_and_type() { - let owner = OWNER.parse().unwrap(); - let mut surfnet = LocalAccounts::new(); - let oracle = surfnet.load(owner, surfnet.price); - let other_price = surfnet.load(owner, surfnet.price); - surfnet.load(owner, [9; 8]); - surfnet.load(Pubkey::new_unique(), surfnet.price); - - let mut keep_alive = KeepAlive::default(); - let vault = Pubkey::new_unique(); - keep_alive.enroll( - &surfnet.registry, - vec![source("example-vault", vault, oracle, true)], - ); - assert_eq!( - surfnet.targets(&keep_alive), - [oracle, other_price], - "the oracle is bound and owned, and is written once" - ); - - let loaded_later = surfnet.load(owner, surfnet.price); - assert_eq!( - surfnet.targets(&keep_alive), - [oracle, other_price, loaded_later] - ); - } - - #[test] - fn an_override_without_keep_alive_stops_it_for_its_account_until_one_with_it_plays() { - let owner = OWNER.parse().unwrap(); - let mut surfnet = LocalAccounts::new(); - let oracle = surfnet.load(owner, surfnet.price); - let other_price = surfnet.load(owner, surfnet.price); - let vault = Pubkey::new_unique(); - let mut keep_alive = KeepAlive::default(); - keep_alive.enroll( - &surfnet.registry, - vec![source("example-vault", vault, oracle, true)], - ); - - keep_alive.enroll( - &surfnet.registry, - vec![source("pyth-price-feed-v2", oracle, oracle, false)], - ); - assert_eq!(keep_alive.bindings.len(), 1, "its binding is kept"); - assert_eq!(surfnet.targets(&keep_alive), [other_price]); - - keep_alive.enroll( - &surfnet.registry, - vec![source("example-vault", vault, oracle, true)], - ); - assert_eq!( - surfnet.targets(&keep_alive), - [other_price], - "another account's override does not restart it" - ); - - keep_alive.enroll( - &surfnet.registry, - vec![source("pyth-price-feed-v2", oracle, oracle, true)], - ); - assert_eq!(surfnet.targets(&keep_alive), [oracle, other_price]); } - const INPUT_OVERRIDES: &str = r#" -protocol: Example -version: v1 -account_type: State -raw_layout: true -templates: - - id: example-vault - name: Vault - description: Example vault - keep_alive: - - template: example-price-fresh - address: { type: input, value: oracle } - values: { posted_slot: $slot } - address: { type: pubkey } - properties: - - { path: balance, offset: 0, encoding: u64, description: Balance } - - { path: oracle, type: input, value_type: pubkey, description: The vault's oracle } - - id: example-oracle - name: Oracle - description: Example oracle - address: { type: pubkey } - properties: - - { path: price, offset: 0, encoding: u64, description: Price } -"#; - - #[test] - fn keep_alive_on_again_restores_another_templates_binding() { - let surfnet = LocalAccounts { - registry: owned_registry(INPUT_OVERRIDES), - ..LocalAccounts::new() - }; - assert!( - surfnet - .registry - .get("example-oracle") - .unwrap() - .keep_alive - .is_empty(), - "re-enabling must not import anything itself" - ); - let oracle = Pubkey::new_unique(); - let mut keep_alive = KeepAlive::default(); - keep_alive.enroll( - &surfnet.registry, - vec![source("example-vault", Pubkey::new_unique(), oracle, true)], - ); - assert_eq!(surfnet.targets(&keep_alive), [oracle]); - - keep_alive.enroll( - &surfnet.registry, - vec![source("example-oracle", oracle, oracle, false)], - ); - assert!(surfnet.targets(&keep_alive).is_empty()); - - keep_alive.enroll( - &surfnet.registry, - vec![source("example-oracle", oracle, oracle, true)], - ); - assert_eq!(surfnet.targets(&keep_alive), [oracle]); - - let mut off_first = KeepAlive::default(); - off_first.enroll( - &surfnet.registry, - vec![ - source("example-oracle", oracle, oracle, false), - source("example-vault", Pubkey::new_unique(), oracle, true), - ], - ); - assert!(surfnet.targets(&off_first).is_empty()); - - off_first.enroll( - &surfnet.registry, - vec![source("example-oracle", oracle, oracle, true)], - ); - assert_eq!( - surfnet.targets(&off_first), - [oracle], - "a vault that played while the oracle was off still bound it" - ); + /// Whether this binds the same template import to the same address as `other`, for another + /// override's account. Such an import is applied once. + pub fn repeats(&self, other: &Self) -> bool { + !self.own + && !other.own + && self.template == other.template + && self.import == other.import + && self.address == other.address } } diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index 890545d17..bc248d4ac 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -93,12 +93,29 @@ pub(crate) fn account_data_values( instance: &OverrideInstance, template: Option<&OverrideTemplate>, ) -> (HashMap, usize, usize) { + // The override's own keep-alive list reads its addresses from the same values. Like a + // template's PDA seeds, a value that is a field is still written. + let own_imports = instance.keep_alive_imports().unwrap_or_default(); + let is_field = |path: &str| { + template.is_some_and(|template| { + template + .properties + .iter() + .any(|property| property.path == path && property.is_field()) + }) + }; let mut pda_refs = instance.account.get_pda_seed_references(); pda_refs.extend( template .into_iter() .flat_map(OverrideTemplate::keep_alive_pda_seeds), ); + for import in &own_imports { + if let KeepAliveAddress::Account(address) = &import.address { + let seeds = address.get_pda_seed_references().into_iter(); + pda_refs.extend(seeds.filter(|seed| !is_field(seed))); + } + } // Keep-alive inputs only name the account a keep-alive writes, so they count as selectors. let constant_refs: HashSet<&str> = template .into_iter() @@ -110,6 +127,14 @@ pub(crate) fn account_data_values( .map(|property| property.path.as_str()) .chain(template.keep_alive_inputs()) }) + .chain( + own_imports + .iter() + .filter_map(|import| match &import.address { + KeepAliveAddress::Input(name) if !is_field(name) => Some(name.as_str()), + _ => None, + }), + ) .collect(); let values = instance .values @@ -177,9 +202,8 @@ impl TemplateRegistry { } /// Fails on a keep-alive import the registry cannot apply: its template must be a loaded - /// keep-alive template that has every property it sets, an input address must name a pubkey - /// input of the importing template, and an owned address an account of the keep-alive - /// template's IDL. + /// keep-alive template that has every property it sets, and an input address must name a + /// pubkey input of the importing template. pub fn check_keep_alive_imports(&self) -> Result<(), String> { for template in self.templates.values() { for import in &template.keep_alive { @@ -209,13 +233,6 @@ impl TemplateRegistry { )); } } - if let KeepAliveAddress::Owned { account, .. } = &import.address - && keep_alive.account_discriminator(account).is_none() - { - return fail(format!( - "its IDL has no account '{account}' with a discriminator" - )); - } if let KeepAliveAddress::Input(name) = &import.address { let is_pubkey_input = template.properties.iter().any(|property| { &property.path == name @@ -471,7 +488,7 @@ impl TemplateRegistry { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use std::{ collections::{BTreeSet, HashMap}, str::FromStr, @@ -857,7 +874,7 @@ templates: assert!(error.contains("exceeds the 15 byte account"), "{error}"); } - const KEEP_ALIVE_OVERRIDES: &str = r#" + pub(crate) const KEEP_ALIVE_OVERRIDES: &str = r#" protocol: Example version: v1 account_type: State @@ -900,7 +917,7 @@ templates: - { path: ms, offset: 16, encoding: u64, description: Published time } "#; - fn keep_alive_registry(overrides: &str) -> TemplateRegistry { + pub(crate) fn keep_alive_registry(overrides: &str) -> TemplateRegistry { let mut registry = TemplateRegistry::default(); registry.load_raw_layout_overrides(overrides, "example"); registry.load_keep_alive(None, KEEP_ALIVE, "example"); @@ -989,6 +1006,32 @@ templates: assert_eq!(values.keys().collect::>(), ["balance"]); } + #[test] + fn what_an_overrides_own_keep_alive_reads_is_never_written_unless_a_field() { + let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); + let system = "11111111111111111111111111111111"; + let mut instance = OverrideInstance::new( + "example-price".to_string(), + 0, + surfpool_types::AccountAddress::Pubkey(system.to_string()), + ) + .with_values(HashMap::from([ + ("price".to_string(), serde_json::json!(1)), + ("feed".to_string(), serde_json::json!(system)), + ("seed".to_string(), serde_json::json!(system)), + ])); + instance.keep_alive = serde_json::from_value(serde_json::json!([ + { "template": "example-fresh", "address": { "type": "input", "value": "feed" }, "values": { "slot": "$slot" } }, + { "template": "example-fresh", "address": { "type": "pda", "program_id": system, "seeds": [ + { "type": "property_ref", "value": "seed" }, + { "type": "property_ref", "value": "price" }, + ] }, "values": { "slot": "$slot" } }, + ])) + .unwrap(); + let (values, _, _) = account_data_values(&instance, registry.get("example-price")); + assert_eq!(values.keys().collect::>(), ["price"]); + } + #[test] fn imports_the_registry_cannot_apply_are_refused() { let refused = |overrides: String, expected: &str| { @@ -1066,30 +1109,6 @@ templates: ); } - #[test] - fn an_owned_import_needs_its_account_in_the_keep_alive_idl() { - use crate::scenarios::keep_alive::tests::{OWNED_OVERRIDES, owned_registry}; - - owned_registry(OWNED_OVERRIDES) - .check_keep_alive_imports() - .unwrap(); - let error = - owned_registry(&OWNED_OVERRIDES.replace("account: PriceUpdateV2", "account: Nope")) - .check_keep_alive_imports() - .unwrap_err(); - assert!(error.contains("its IDL has no account 'Nope'"), "{error}"); - let error = keep_alive_registry(&KEEP_ALIVE_OVERRIDES.replace( - "address: { type: input, value: oracle }", - "address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: State }", - )) - .check_keep_alive_imports() - .unwrap_err(); - assert!( - error.contains("its IDL has no account 'State'"), - "a raw layout has no IDL: {error}" - ); - } - #[test] fn the_bundled_registry_resolves_every_keep_alive_import() { TemplateRegistry::new().check_keep_alive_imports().unwrap(); diff --git a/crates/core/src/surfnet/svm.rs b/crates/core/src/surfnet/svm.rs index c55447535..a5751af7e 100644 --- a/crates/core/src/surfnet/svm.rs +++ b/crates/core/src/surfnet/svm.rs @@ -1,6 +1,6 @@ use std::{ cmp::max, - collections::{BTreeMap, HashMap, HashSet, VecDeque}, + collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}, ops::{ Bound::{Excluded, Unbounded}, RangeInclusive, @@ -105,7 +105,7 @@ use crate::{ rpc::utils::convert_transaction_metadata_from_canonical, scenarios::{ TemplateRegistry, account_data_values, - keep_alive::{KeepAlive, KeepAliveSource}, + keep_alive::{KeepAliveBinding, KeepAliveSource}, protocols::phoenix_eternal::v1::state_builder::{ prepare_phoenix_override, write_all_or_none, }, @@ -609,7 +609,9 @@ pub struct SurfnetSvm { pub scheduled_overrides: Box>>, /// The accounts keep-alive rewrites every slot, from the slot a scenario's override first /// touched them. Kept in memory only, so a restart on a persistent database stops keep-alive. - pub keep_alive: KeepAlive, + pub keep_alive_bindings: BTreeSet, + /// The keep-alive lists overrides gave in place of their template's, by the account they wrote. + pub keep_alive_imports: HashMap>, /// Tracks accounts that should not be downloaded from the remote RPC. /// This includes accounts explicitly closed locally and accounts marked offline via cheatcodes. /// The key is the account pubkey as a string. If `include_owned_accounts` is true, @@ -893,7 +895,8 @@ impl SurfnetSvm { registered_idls: OverlayStorage::wrap(self.registered_idls.clone_box()), streamed_accounts: OverlayStorage::wrap(self.streamed_accounts.clone_box()), scheduled_overrides: OverlayStorage::wrap(self.scheduled_overrides.clone_box()), - keep_alive: self.keep_alive.clone(), + keep_alive_bindings: self.keep_alive_bindings.clone(), + keep_alive_imports: self.keep_alive_imports.clone(), // Clone non-storage fields normally transactions_queued_for_confirmation: self.transactions_queued_for_confirmation.clone(), @@ -1403,7 +1406,8 @@ impl SurfnetSvm { streamed_accounts: streamed_accounts_db, recent_blockhashes: VecDeque::new(), scheduled_overrides: scheduled_overrides_db, - keep_alive: KeepAlive::default(), + keep_alive_bindings: BTreeSet::new(), + keep_alive_imports: HashMap::new(), offline_accounts: offline_accounts_db, genesis_slot: default_genesis_slot, genesis_updated_at: updated_at, @@ -2623,7 +2627,8 @@ impl SurfnetSvm { self.runbook_executions.clear(); self.streamed_accounts.clear()?; self.scheduled_overrides.clear()?; - self.keep_alive = KeepAlive::default(); + self.keep_alive_bindings.clear(); + self.keep_alive_imports.clear(); let current_time = chrono::Utc::now().timestamp_millis() as u64; self.updated_at = current_time; @@ -3404,7 +3409,7 @@ impl SurfnetSvm { /// 3. Optionally fetches fresh account data from remote if `fetch_before_use` is enabled /// 4. Applies the overrides to the account data /// 5. Updates the SVM state - /// 6. Applies keep-alive to every account in `keep_alive` + /// 6. Applies keep-alive to every account in `keep_alive_bindings` pub async fn materialize_overrides( &mut self, remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>, @@ -3414,14 +3419,15 @@ impl SurfnetSvm { .await } - /// Applies keep-alive to every account in `keep_alive`, with the placeholders filled from + /// Applies keep-alive to every account in `keep_alive_bindings`, with the placeholders filled from /// `slot` and its Clock time. pub async fn apply_keep_alive( &mut self, remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>, slot: Slot, ) { - let keep_alive_overrides = self.keep_alive_overrides(slot, remote_ctx.is_some()); + let keep_alive_overrides = + self.keep_alive_overrides(template_registry(), slot, remote_ctx.is_some()); if let Err(e) = self .apply_overrides(remote_ctx, slot, keep_alive_overrides, false) .await @@ -3432,7 +3438,7 @@ impl SurfnetSvm { } /// Materializes scheduled overrides for a specific slot, adds the accounts they touch to - /// `keep_alive`, then applies keep-alive to every account on it. + /// `keep_alive_bindings`, then applies keep-alive to every account on it. pub async fn materialize_overrides_for_slot( &mut self, remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>, @@ -3443,7 +3449,7 @@ impl SurfnetSvm { let touched = self .apply_overrides(remote_ctx, target_slot, overrides, true) .await?; - self.enroll_keep_alive(touched); + self.enroll_keep_alive(template_registry(), touched); } Ok::<_, SurfpoolError>(()) } @@ -3455,7 +3461,7 @@ impl SurfnetSvm { materialized } - /// Applies `overrides` in order and returns the scheduled ones that wrote their account, for + /// Applies `overrides` in order and returns the scheduled ones whose template imports /// keep-alive. `scheduled` overrides came out of this slot's schedule, which only registered /// scenarios fill: when one fails, the ones not reached yet go back into it. async fn apply_overrides( @@ -3528,14 +3534,20 @@ impl SurfnetSvm { } }; - // Joins or leaves keep-alive only once its write succeeds: a failed override leaves the - // account as if no scenario had touched it. - let mut keep_alive_source = scheduled.then(|| KeepAliveSource { - template: override_instance.template_id.clone(), - address: account_pubkey, - values: override_instance.values.clone(), - keep_alive: override_instance.keep_alive, - }); + // Joins keep-alive only once its write succeeds: a failed override leaves the account as + // if no scenario had touched it. + let mut keep_alive_source = None; + if scheduled + && let Some(template) = template_registry().get(&override_instance.template_id) + && (!template.keep_alive.is_empty() || override_instance.keep_alive.is_some()) + { + keep_alive_source = Some(KeepAliveSource { + template: template.id.clone(), + address: account_pubkey, + values: override_instance.values.clone(), + imports: override_instance.keep_alive_imports(), + }); + } debug!( "Processing override {} for account {} (label: {:?})", @@ -3652,7 +3664,10 @@ impl SurfnetSvm { Err(e) => { restore_unprocessed(self, index); // The overrides before this one wrote their accounts, so they still join. - self.enroll_keep_alive(std::mem::take(&mut keep_alive_touched)); + self.enroll_keep_alive( + template_registry(), + std::mem::take(&mut keep_alive_touched), + ); return Err(e); } }; @@ -3802,7 +3817,10 @@ impl SurfnetSvm { ) { restore_unprocessed(self, index); // The overrides before this one wrote their accounts, so they still join. - self.enroll_keep_alive(std::mem::take(&mut keep_alive_touched)); + self.enroll_keep_alive( + template_registry(), + std::mem::take(&mut keep_alive_touched), + ); return Err(e); } keep_alive_touched.extend(keep_alive_source.take()); @@ -3911,15 +3929,68 @@ impl SurfnetSvm { Ok(keep_alive_touched) } - /// Starts or stops keep-alive for the accounts in `touched`. - fn enroll_keep_alive(&mut self, touched: Vec) { - self.keep_alive.enroll(template_registry(), touched); + /// Adds the accounts that `touched` makes keep-alive imports rewrite. An override's own list + /// replaces its template's, and first drops what earlier overrides of its account bound. + fn enroll_keep_alive(&mut self, registry: &TemplateRegistry, touched: Vec) { + for source in touched { + let Some(template) = registry.get(&source.template) else { + continue; + }; + let own = source.imports.is_some(); + let imports = match source.imports { + Some(imports) => { + self.keep_alive_bindings + .retain(|binding| binding.source != source.address); + self.keep_alive_imports.insert(source.address, imports); + &self.keep_alive_imports[&source.address] + } + None => &template.keep_alive, + }; + for (index, import) in imports.iter().enumerate() { + if own + && let Err(e) = registry + .keep_alive_template(&import.template) + .ok_or_else(|| "no keep-alive file defines it".to_string()) + .and_then(|_| import.validate()) + { + warn!( + "Keep-alive '{}' of the override of {} is skipped: {}", + import.template, source.address, e + ); + continue; + } + let Some(address) = import.address(source.address, &source.values) else { + warn!( + "Keep-alive '{}' of override template '{}' has no address for {}", + import.template, template.id, source.address + ); + continue; + }; + let binding = KeepAliveBinding { + template: template.id.clone(), + import: index, + address, + own, + source: source.address, + }; + if self.keep_alive_bindings.insert(binding) { + info!( + "Keep-alive '{}' rewrites {} every slot", + import.template, address + ); + } + } + } } - /// The keep-alive overrides for every account keep-alive rewrites at `slot`. A missing account - /// is fetched first when `can_fetch` and not offline, otherwise skipped. Owned kinds only reach - /// local accounts, so they never fetch. - fn keep_alive_overrides(&self, slot: Slot, can_fetch: bool) -> Vec { + /// The keep-alive overrides for every binding at `slot`. A missing account is fetched first when + /// `can_fetch` and not offline, otherwise skipped. + fn keep_alive_overrides( + &self, + registry: &TemplateRegistry, + slot: Slot, + can_fetch: bool, + ) -> Vec { // The time the open slot's Clock sysvar holds. The Clock advances by each slot's own // interval, so recomputing it from the slot would apply a changed slot interval to every // slot since the last time travel or restart. @@ -3927,49 +3998,56 @@ impl SurfnetSvm { slot, unix_time_ms: self.updated_at, }; - let targets = self.keep_alive.targets(template_registry(), |owner| { - self.get_account_owned_by(owner).unwrap_or_else(|e| { - warn!("Keep-alive cannot read the accounts of {}: {}", owner, e); - Vec::new() - }) - }); let mut instances = Vec::new(); - for (import, address) in targets { - let missing = match self.get_account(&address) { + let mut previous: Option<&KeepAliveBinding> = None; + for binding in &self.keep_alive_bindings { + if previous + .replace(binding) + .is_some_and(|previous| binding.repeats(previous)) + { + continue; + } + let Some(import) = binding.find(registry, &self.keep_alive_imports) else { + continue; + }; + let missing = match self.get_account(&binding.address) { Ok(Some(_)) => false, Ok(None) if can_fetch && !self .offline_accounts - .contains_key(&address.to_string()) + .contains_key(&binding.address.to_string()) .unwrap_or(false) => { true } Ok(None) => { - debug!("Keep-alive skips {}: not in this surfnet", address); + debug!("Keep-alive skips {}: not in this surfnet", binding.address); continue; } Err(e) => { - warn!("Keep-alive cannot read {}: {}", address, e); + warn!("Keep-alive cannot read {}: {}", binding.address, e); continue; } }; let values = match import.values_at(&clock) { Ok(values) => values, Err(e) => { - warn!("Keep-alive '{}' skips {}: {}", import.template, address, e); + warn!( + "Keep-alive '{}' skips {}: {}", + import.template, binding.address, e + ); continue; } }; let mut instance = OverrideInstance::new( import.template.clone(), 0, - surfpool_types::AccountAddress::Pubkey(address.to_string()), + surfpool_types::AccountAddress::Pubkey(binding.address.to_string()), ) .with_values(values) .with_label(format!("keep-alive {}", import.template)); - instance.id = format!("keep-alive:{}:{}", import.template, address); + instance.id = format!("keep-alive:{}:{}", import.template, binding.address); instance.fetch_before_use = missing; instances.push(instance); } @@ -5489,6 +5567,7 @@ mod tests { use super::*; use crate::{ + scenarios::registry::tests::{KEEP_ALIVE_OVERRIDES, keep_alive_registry}, storage::tests::TestType, surfnet::locker::SurfnetSvmLocker, tests::helpers::{UNHEALTHY_OFFSET, canned_rpc, scheduled_override_fixture}, @@ -9718,27 +9797,139 @@ mod tests { assert_eq!(update.data.decode(), Some(account.data)); } + fn own_keep_alive(imports: serde_json::Value) -> Option> { + let imports: Vec = + serde_json::from_value(imports).unwrap(); + Some(imports.into_iter().map(Into::into).collect()) + } + + fn keep_alive_target(svm: &mut SurfnetSvm) -> Pubkey { + let address = Pubkey::new_unique(); + let account = Account { + lamports: 1, + ..Account::default() + }; + svm.inner.set_account(address, account).unwrap(); + address + } + + /// The accounts keep-alive writes at `slot`, each stamped with that slot. + fn written_at(svm: &SurfnetSvm, registry: &TemplateRegistry, slot: Slot) -> Vec { + svm.keep_alive_overrides(registry, slot, false) + .into_iter() + .map(|instance| { + assert_eq!(instance.values["slot"], serde_json::json!(slot)); + match instance.account { + surfpool_types::AccountAddress::Pubkey(address) => address, + pda => panic!("keep-alive writes a pubkey, not {pda:?}"), + } + }) + .collect() + } + + /// Absent, an override binds its template's imports; its own list replaces what earlier + /// overrides of its account bound. A template import two overrides bind is applied once. + #[test] + fn an_overrides_own_keep_alive_list_replaces_its_templates() { + let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); + let (mut svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); + let (oracle, feed) = (keep_alive_target(&mut svm), keep_alive_target(&mut svm)); + let (vault, other_vault) = (Pubkey::new_unique(), Pubkey::new_unique()); + let source = |address, imports| KeepAliveSource { + template: "example-vault".to_string(), + address, + values: HashMap::from([("oracle".to_string(), serde_json::json!(oracle.to_string()))]), + imports, + }; + + svm.enroll_keep_alive( + ®istry, + vec![source(vault, None), source(other_vault, None)], + ); + assert_eq!(svm.keep_alive_bindings.len(), 2); + assert_eq!(written_at(&svm, ®istry, 1), [oracle.to_string()]); + + let own = own_keep_alive(serde_json::json!([ + { "template": "nowhere", "address": { "type": "override" }, "values": { "slot": "$slot" } }, + { "template": "example-fresh", "address": { "type": "input", "value": "missing" }, "values": { "slot": "$slot" } }, + { "template": "example-fresh", "address": { "type": "pubkey", "value": feed.to_string() }, "values": { "slot": "$slot" } }, + ])); + svm.enroll_keep_alive(®istry, vec![source(vault, own)]); + let bindings = svm + .keep_alive_bindings + .iter() + .map(|binding| (binding.source, binding.address, binding.own)) + .collect::>(); + assert_eq!( + bindings, + [(other_vault, oracle, false), (vault, feed, true)] + ); + assert_eq!( + written_at(&svm, ®istry, 1), + [oracle, feed].map(|address| address.to_string()), + "the other vault still keeps the oracle" + ); + } + + /// The case of the price feeds a transaction reads, which no scenario names. + #[test] + fn an_overrides_own_pubkey_imports_keep_other_accounts_fresh_every_slot() { + let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); + let (mut svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); + let feeds = [keep_alive_target(&mut svm), keep_alive_target(&mut svm)]; + let imports = feeds.map(|feed| { + serde_json::json!({ + "template": "example-fresh", + "address": { "type": "pubkey", "value": feed.to_string() }, + "values": { "slot": "$slot", "ms": "$unix_ms" }, + }) + }); + let source = KeepAliveSource { + template: "example-price".to_string(), + address: Pubkey::new_unique(), + values: HashMap::new(), + imports: own_keep_alive(serde_json::json!(imports)), + }; + svm.enroll_keep_alive(®istry, vec![source]); + for slot in [7, 8] { + let fresh = feeds.map(|feed| feed.to_string()); + assert_eq!(written_at(&svm, ®istry, slot), fresh); + } + } + #[tokio::test] - async fn a_written_override_without_keep_alive_excludes_its_account_until_one_with_it() { + async fn an_empty_keep_alive_list_stops_what_earlier_overrides_of_its_account_started() { const SLOT: u64 = 500; + let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); let (mut svm, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default(); let (account_pubkey, instance) = scheduled_override_fixture(&mut svm); - let mut play = async |keep_alive: bool, values: HashMap| { + let other = Pubkey::new_unique(); + let earlier = [account_pubkey, other].map(|address| KeepAliveSource { + template: "example-price".to_string(), + address, + values: HashMap::new(), + imports: None, + }); + svm.enroll_keep_alive(®istry, earlier.to_vec()); + let mut play = async |values: HashMap| { let mut instance = instance.clone().with_values(values); - instance.keep_alive = keep_alive; + instance.keep_alive = Some(Vec::new()); svm.scheduled_overrides.store(SLOT, vec![instance]).unwrap(); svm.materialize_overrides_for_slot(&None, SLOT) .await .unwrap(); - svm.keep_alive.excluded.contains(&account_pubkey) + svm.keep_alive_bindings + .iter() + .map(|binding| binding.source) + .collect::>() }; let failed = HashMap::from([("nope".to_string(), serde_json::json!(1))]); - assert!( - !play(false, failed).await, - "a failed write excludes nothing" + assert_eq!( + play(failed).await.len(), + 2, + "a failed write changes nothing" ); - assert!(play(false, instance.values.clone()).await); - assert!(!play(true, instance.values.clone()).await); + assert_eq!(play(instance.values.clone()).await, [other]); } } diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts index c52415578..ccc3bd379 100644 --- a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts +++ b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts @@ -2,6 +2,7 @@ // Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AccountAddress } from "./AccountAddress.js"; +import type { YamlKeepAliveImport } from "./YamlKeepAliveImport.js"; /** * A concrete instance of an override template with specific values @@ -37,10 +38,11 @@ enabled: boolean, */ fetchBeforeUse?: boolean, /** - * Whether keep-alive rewrites this account from this slot on. Off, keep-alive stops for the - * account, so its fields age as the clock moves on, until a later override turns it on again. + * Keep-alive imports in place of the template's, in the same shape as a template file's + * `keep_alive` list. Absent, the template's imports apply. Present, even empty, they first + * drop the keep-alive that earlier overrides of this account started. */ -keepAlive?: boolean, +keepAlive?: Array, /** * Account address to override - use pubkey for known addresses or pda for derived addresses */ diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts b/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts new file mode 100644 index 000000000..73c1062fe --- /dev/null +++ b/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts @@ -0,0 +1,9 @@ +// @generated by ts-rs from the Rust types in crates/types. +// Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { YamlPdaSeed } from "./YamlPdaSeed.js"; + +/** + * Where a keep-alive import writes, as YAML writes it. + */ +export type YamlKeepAliveAddress = { "type": "override" } | { "type": "input", value: string, } | { "type": "pubkey", value: string, } | { "type": "pda", program_id: string, seeds: Array, }; diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts b/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts new file mode 100644 index 000000000..5cbacacae --- /dev/null +++ b/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts @@ -0,0 +1,9 @@ +// @generated by ts-rs from the Rust types in crates/types. +// Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { YamlKeepAliveAddress } from "./YamlKeepAliveAddress.js"; + +/** + * A keep-alive import as YAML writes it. + */ +export type YamlKeepAliveImport = { template: string, address: YamlKeepAliveAddress, values: Record, }; diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts b/crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts new file mode 100644 index 000000000..848dc2029 --- /dev/null +++ b/crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts @@ -0,0 +1,8 @@ +// @generated by ts-rs from the Rust types in crates/types. +// Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * YAML representation of PDA seeds + */ +export type YamlPdaSeed = { "type": "string", value: string, } | { "type": "bytes", value: Array, } | { "type": "pubkey", value: string, } | { "type": "property_ref", value: string, } | { "type": "u16_be", value: number, } | { "type": "u16_be_ref", value: string, } | { "type": "u16_le", value: number, } | { "type": "bytes32_ref", value: string, } | { "type": "derived_pda", program_id: string, seeds: Array, }; diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/index.ts b/crates/sdk-node/surfpool-sdk/kit/generated/index.ts index e610e03d1..0a151a3f8 100644 --- a/crates/sdk-node/surfpool-sdk/kit/generated/index.ts +++ b/crates/sdk-node/surfpool-sdk/kit/generated/index.ts @@ -34,4 +34,7 @@ export type * from "./UiAccountEncoding.js"; export type * from "./UiAccountProfileState.js"; export type * from "./UiKeyedProfileResult.js"; export type * from "./UiProfileResult.js"; +export type * from "./YamlKeepAliveAddress.js"; +export type * from "./YamlKeepAliveImport.js"; +export type * from "./YamlPdaSeed.js"; export * from "./methods.js"; diff --git a/crates/types/src/rpc_endpoints.json b/crates/types/src/rpc_endpoints.json index 6517dd7f0..1384f3d2b 100644 --- a/crates/types/src/rpc_endpoints.json +++ b/crates/types/src/rpc_endpoints.json @@ -861,7 +861,7 @@ "label": "Option (An optional label for this override instance)", "enabled": "bool (Indicates whether this override instance is enabled)", "fetchBeforeUse": "bool (Indicates whether to fetch the latest on-chain account data before applying overrides)", - "keepAlive": "bool (Optional, defaults to true. If false, keep-alive stops rewriting this account from this slot on, and its fields age as the clock moves on. A later override with true starts it again)", + "keepAlive": "Option> (Optional keep-alive list in place of the template's keep_alive list, in the same shape: [{\"template\": \"\", \"address\": {\"type\": \"override\"} or {\"type\": \"input\", \"value\": \"\"} or {\"type\": \"pubkey\", \"value\": \"\"} or {\"type\": \"pda\", \"program_id\": \"\", \"seeds\": [ ... ]}, \"values\": {\"\": \"$slot\"}}]. Omitted, the template's list applies. Given, even as [], it first stops the keep-alive that earlier overrides of this account started, then starts its own imports)", "account": "AccountAddress (The account this override targets, as {\"pubkey\": \"\"} or {\"pda\": {\"programId\": \"\", \"seeds\": [ ... ]}})" } } diff --git a/crates/types/src/scenarios.rs b/crates/types/src/scenarios.rs index 71aab50b7..3e8d3c94a 100644 --- a/crates/types/src/scenarios.rs +++ b/crates/types/src/scenarios.rs @@ -592,14 +592,15 @@ pub struct OverrideInstance { #[serde(default)] #[cfg_attr(feature = "ts-bindings", ts(as = "Option", optional))] pub fetch_before_use: bool, - /// Whether keep-alive rewrites this account from this slot on. Off, keep-alive stops for the - /// account, so its fields age as the clock moves on, until a later override turns it on again. + /// Keep-alive imports in place of the template's, in the same shape as a template file's + /// `keep_alive` list. Absent, the template's imports apply. Present, even empty, they first + /// drop the keep-alive that earlier overrides of this account started. #[schemars( - description = "If false, keep-alive stops rewriting this account from this slot on, so its fields age. A later override with true starts it again. Defaults to true" + description = "Optional keep-alive list in place of the template's, rewritten every slot from this override on: [{\"template\": \"\", \"address\": {\"type\": \"override\"} or {\"type\": \"input\", \"value\": \"\"} or {\"type\": \"pubkey\", \"value\": \"\"} or {\"type\": \"pda\", \"program_id\": \"...\", \"seeds\": [...]}, \"values\": {\"\": \"$slot\"}}]. Omit it to use the template's list. Given, even as [], it first stops the keep-alive that earlier overrides of this account started." )] - #[serde(default = "default_keep_alive")] - #[cfg_attr(feature = "ts-bindings", ts(as = "Option", optional))] - pub keep_alive: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "ts-bindings", ts(optional))] + pub keep_alive: Option>, /// Account address to override - use pubkey for known addresses or pda for derived addresses #[schemars( description = "Account address: either {\"pubkey\": \"base58_address\"} or {\"pda\": {\"programId\": \"...\", \"seeds\": [...]}}" @@ -607,10 +608,6 @@ pub struct OverrideInstance { pub account: AccountAddress, } -fn default_keep_alive() -> bool { - true -} - impl OverrideInstance { pub fn new(template_id: String, scenario_relative_slot: Slot, account: AccountAddress) -> Self { Self { @@ -621,7 +618,7 @@ impl OverrideInstance { label: None, enabled: true, fetch_before_use: false, - keep_alive: true, + keep_alive: None, account, } } @@ -635,6 +632,12 @@ impl OverrideInstance { self.label = Some(label); self } + + /// The override's own keep-alive imports, when it gives them. + pub fn keep_alive_imports(&self) -> Option> { + let imports = self.keep_alive.clone()?; + Some(imports.into_iter().map(Into::into).collect()) + } } /// A scenario containing a timeline of overrides @@ -1552,16 +1555,19 @@ impl YamlOverrideTemplateCollection { // ======================================== /// A keep-alive import as YAML writes it. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] +#[cfg_attr(feature = "ts-bindings", derive(ts_rs::TS), ts(export))] pub struct YamlKeepAliveImport { pub template: String, pub address: YamlKeepAliveAddress, + #[cfg_attr(feature = "ts-bindings", ts(type = "Record"))] pub values: HashMap, } /// Where a keep-alive import writes, as YAML writes it. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(tag = "type", rename_all = "snake_case")] +#[cfg_attr(feature = "ts-bindings", derive(ts_rs::TS), ts(export))] pub enum YamlKeepAliveAddress { /// The account the importing override writes. Override, @@ -1576,20 +1582,6 @@ pub enum YamlKeepAliveAddress { program_id: String, seeds: Vec, }, - /// Every local account that `owner` owns and whose data starts with the discriminator of - /// `account` in the keep-alive template's IDL. - Owned { - owner: YamlOwners, - account: String, - }, -} - -/// One program ID or a list of them. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub enum YamlOwners { - One(String), - Many(Vec), } impl From for KeepAliveImport { @@ -1606,13 +1598,6 @@ impl From for KeepAliveImport { seeds: seeds.into_iter().map(Into::into).collect(), }) } - YamlKeepAliveAddress::Owned { owner, account } => KeepAliveAddress::Owned { - owners: match owner { - YamlOwners::One(owner) => vec![owner], - YamlOwners::Many(owners) => owners, - }, - account, - }, }; KeepAliveImport { template: yaml.template, @@ -1647,18 +1632,10 @@ pub enum KeepAliveAddress { Input(String), /// A fixed or derived address. PDA seeds resolve against the importing override's values. Account(AccountAddress), - /// Every account in the surfnet that one of `owners` owns and whose data starts with the - /// discriminator of `account` in the keep-alive template's IDL, including accounts loaded after - /// the override played. Only local accounts are written, never fetched. - Owned { - owners: Vec, - account: String, - }, } impl KeepAliveImport { - /// The address to write, given the address the importing override wrote and its values. `None` - /// for an owned import, which names no single account. + /// The address to write, given the address the importing override wrote and its values. pub fn address( &self, written: Pubkey, @@ -1671,7 +1648,6 @@ impl KeepAliveImport { .as_str() .and_then(|address| Pubkey::from_str(address).ok()), KeepAliveAddress::Account(address) => address.resolve(Some(values)), - KeepAliveAddress::Owned { .. } => None, } } @@ -1706,16 +1682,6 @@ impl KeepAliveImport { format!("keep-alive '{template}': invalid address '{address}': {e}") })?; } - if let KeepAliveAddress::Owned { owners, .. } = &self.address { - if owners.is_empty() { - return Err(format!("keep-alive '{template}' names no owner")); - } - for owner in owners { - Pubkey::from_str(owner).map_err(|e| { - format!("keep-alive '{template}': invalid owner '{owner}': {e}") - })?; - } - } let clock = KeepAliveClock { slot: 0, unix_time_ms: 0, @@ -1727,17 +1693,6 @@ impl KeepAliveImport { } impl OverrideTemplate { - /// The discriminator of `account` in this template's IDL, when it has one. - pub fn account_discriminator(&self, account: &str) -> Option<&[u8]> { - self.idl - .as_ref()? - .accounts - .iter() - .find(|idl_account| idl_account.name == account) - .map(|idl_account| idl_account.discriminator.as_slice()) - .filter(|discriminator| !discriminator.is_empty()) - } - /// The input properties keep-alive imports read addresses from. They are never written. pub fn keep_alive_inputs(&self) -> impl Iterator { self.keep_alive @@ -1899,8 +1854,9 @@ impl From for AccountAddress { } /// YAML representation of PDA seeds -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(tag = "type", rename_all = "snake_case")] +#[cfg_attr(feature = "ts-bindings", derive(ts_rs::TS), ts(export))] pub enum YamlPdaSeed { String { value: String, @@ -2065,8 +2021,8 @@ mod tests { } #[test] - fn an_override_keeps_its_account_alive_unless_it_opts_out() { - let instance = |extra: serde_json::Value| { + fn an_override_takes_the_yaml_keep_alive_shape_or_leaves_it_to_the_template() { + let instance = |keep_alive: Option| { let mut value = json!({ "id": "o", "templateId": "t", @@ -2075,14 +2031,36 @@ mod tests { "enabled": true, "account": { "pubkey": "11111111111111111111111111111111" }, }); - value - .as_object_mut() - .unwrap() - .extend(extra.as_object().unwrap().clone()); + if let Some(keep_alive) = keep_alive { + value["keepAlive"] = keep_alive; + } serde_json::from_value::(value).unwrap() }; - assert!(instance(json!({})).keep_alive); - assert!(!instance(json!({ "keepAlive": false })).keep_alive); + assert_eq!(instance(None).keep_alive_imports(), None); + assert_eq!(instance(Some(json!(null))).keep_alive_imports(), None); + assert_eq!( + instance(Some(json!([]))).keep_alive_imports(), + Some(Vec::new()) + ); + let program = "11111111111111111111111111111111"; + let own = instance(Some(json!([ + { "template": "t", "address": { "type": "pubkey", "value": program }, "values": { "slot": "$slot" } }, + { "template": "t", "address": { "type": "pda", "program_id": program, "seeds": [{ "type": "property_ref", "value": "feed" }] }, "values": { "ms": "$unix_ms" } }, + ]))); + assert_eq!( + own.keep_alive_imports(), + Some(vec![ + keep_alive(&format!( + "template: t\naddress: {{ type: pubkey, value: \"{program}\" }}\nvalues: {{ slot: $slot }}\n" + )), + keep_alive(&format!( + "template: t\naddress: {{ type: pda, program_id: \"{program}\", seeds: [{{ type: property_ref, value: feed }}] }}\nvalues: {{ ms: $unix_ms }}\n" + )), + ]) + ); + let serialized = |instance| serde_json::to_value(instance).unwrap(); + assert!(serialized(instance(None)).get("keepAlive").is_none()); + assert_eq!(serialized(own)["keepAlive"][1]["address"]["type"], "pda"); } #[test] @@ -2152,40 +2130,6 @@ templates: "template: t\naddress: { type: pda, program_id: nope, seeds: [] }\nvalues: { slot: 1 }\n", "invalid address", ); - refused( - "template: t\naddress: { type: owned, owner: nope, account: A }\nvalues: { slot: 1 }\n", - "invalid owner 'nope'", - ); - refused( - "template: t\naddress: { type: owned, owner: [], account: A }\nvalues: { slot: 1 }\n", - "names no owner", - ); - } - - #[test] - fn an_owned_import_takes_one_owner_or_a_list() { - use solana_pubkey::Pubkey; - let (first, second) = (Pubkey::new_unique(), Pubkey::new_unique()); - let owned = |owner: String| { - keep_alive(&format!( - "template: t\naddress: {{ type: owned, owner: {owner}, account: Price }}\nvalues: {{ slot: $slot }}\n" - )) - }; - let expected = |owners: &[Pubkey]| super::KeepAliveAddress::Owned { - owners: owners.iter().map(Pubkey::to_string).collect(), - account: "Price".to_string(), - }; - let one = owned(format!("\"{first}\"")); - assert_eq!(one.address, expected(&[first])); - one.validate().unwrap(); - let many = owned(format!("[\"{first}\", \"{second}\"]")); - assert_eq!(many.address, expected(&[first, second])); - many.validate().unwrap(); - assert_eq!( - many.address(first, &HashMap::new()), - None, - "it names no single account" - ); } #[test] From 57d4aff332b746026e54cab0bb0c6f67b8b39eca Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 20 Nov 2026 16:29:15 +0200 Subject: [PATCH 19/24] refactor(scenarios): keep upstream keep-alive and let an override turn it off with [] --- crates/core/src/scenarios/README.md | 36 +-- crates/core/src/scenarios/keep_alive.rs | 38 +-- crates/core/src/scenarios/registry.rs | 57 +---- crates/core/src/surfnet/svm.rs | 238 ++++-------------- .../kit/generated/OverrideInstance.ts | 8 +- .../kit/generated/YamlKeepAliveAddress.ts | 9 - .../kit/generated/YamlKeepAliveImport.ts | 9 - .../surfpool-sdk/kit/generated/YamlPdaSeed.ts | 8 - .../surfpool-sdk/kit/generated/index.ts | 3 - crates/types/src/rpc_endpoints.json | 2 +- crates/types/src/scenarios.rs | 97 +++---- 11 files changed, 105 insertions(+), 400 deletions(-) delete mode 100644 crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts delete mode 100644 crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts delete mode 100644 crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index a4d2095eb..d9705f356 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -125,36 +125,12 @@ never takes effect. An account not yet in the surfnet is fetched from the remote or its owner with its owned accounts, is marked offline. Keep-alive is kept in memory only: after a restart on a persistent database it stops until an importing override plays again. -An override can give its own `keepAlive` list, in the shape of a `keep_alive` list, in place of its -template's. Without `keepAlive`, the template's list applies. With a list, `[]` included, keep-alive -first stops for everything that earlier overrides of the same account started, then the override's -own imports start. Keep-alive that overrides of other accounts started does not change. So `[]` -turns keep-alive off for the account's overrides, and a list repeats any template import it still -needs. A `pubkey` import keeps an account fresh that no override writes, such as another price feed -a transaction reads: - -```json -{ - "id": "vault-balance", - "templateId": "example-vault-balance", - "values": { "balance": 1000, "oracle": "" }, - "scenarioRelativeSlot": 0, - "enabled": true, - "account": { "pubkey": "" }, - "keepAlive": [ - { - "template": "example-oracle-fresh", - "address": { "type": "input", "value": "oracle" }, - "values": { "publication_slot": "$slot", "publication_time": "$unix_ms" } - }, - { - "template": "example-oracle-fresh", - "address": { "type": "pubkey", "value": "" }, - "values": { "publication_slot": "$slot", "publication_time": "$unix_ms" } - } - ] -} -``` +An override can turn keep-alive off for the account it writes with `"keepAlive": []`, as `keep_alive: []` +does for a template. From that override's slot on, nothing rewrites the account, including keep-alive +that earlier overrides started, so its fields age as the clock moves on, for example to test a stale +price. The override must write a value for this to take effect. Without the field, the template's +keep-alive applies as usual. To keep fresh an account a transaction reads but no scenario names, give +it an override of its own. ### Override Templates Directly using the `surfnet_registerScenario` endpoint requires building out a map of account keys that are specific to the schema of the account that is being written to. diff --git a/crates/core/src/scenarios/keep_alive.rs b/crates/core/src/scenarios/keep_alive.rs index dd5e3d097..470def75b 100644 --- a/crates/core/src/scenarios/keep_alive.rs +++ b/crates/core/src/scenarios/keep_alive.rs @@ -6,9 +6,6 @@ use std::collections::HashMap; use solana_pubkey::Pubkey; -use surfpool_types::KeepAliveImport; - -use super::TemplateRegistry; /// An account a scenario's override wrote through a template that imports keep-alive. #[derive(Clone, Debug)] @@ -18,8 +15,8 @@ pub struct KeepAliveSource { pub address: Pubkey, /// The override's values, which input and PDA addresses resolve against. pub values: HashMap, - /// The override's own keep-alive list, which replaces the template's. - pub imports: Option>, + /// The override set `keepAlive: []`: keep-alive stops rewriting `address`. + pub off: bool, } /// Binds a template's keep-alive import to the account it rewrites every slot, resolved when an @@ -28,37 +25,8 @@ pub struct KeepAliveSource { pub struct KeepAliveBinding { /// The importing template's ID. pub template: String, - /// The import's index in that template's `keep_alive` list, or in the override's own list. + /// The import's index in that template's `keep_alive` list. pub import: usize, /// The address the import rewrites. pub address: Pubkey, - /// Whether the import is in the override's own list, kept by `source`. - pub own: bool, - /// The address the importing override wrote. - pub source: Pubkey, -} - -impl KeepAliveBinding { - /// The import this binding applies. - pub fn find<'a>( - &self, - registry: &'a TemplateRegistry, - own_imports: &'a HashMap>, - ) -> Option<&'a KeepAliveImport> { - if self.own { - own_imports.get(&self.source)?.get(self.import) - } else { - registry.get(&self.template)?.keep_alive.get(self.import) - } - } - - /// Whether this binds the same template import to the same address as `other`, for another - /// override's account. Such an import is applied once. - pub fn repeats(&self, other: &Self) -> bool { - !self.own - && !other.own - && self.template == other.template - && self.import == other.import - && self.address == other.address - } } diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index bc248d4ac..a80f6bb7f 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -93,29 +93,12 @@ pub(crate) fn account_data_values( instance: &OverrideInstance, template: Option<&OverrideTemplate>, ) -> (HashMap, usize, usize) { - // The override's own keep-alive list reads its addresses from the same values. Like a - // template's PDA seeds, a value that is a field is still written. - let own_imports = instance.keep_alive_imports().unwrap_or_default(); - let is_field = |path: &str| { - template.is_some_and(|template| { - template - .properties - .iter() - .any(|property| property.path == path && property.is_field()) - }) - }; let mut pda_refs = instance.account.get_pda_seed_references(); pda_refs.extend( template .into_iter() .flat_map(OverrideTemplate::keep_alive_pda_seeds), ); - for import in &own_imports { - if let KeepAliveAddress::Account(address) = &import.address { - let seeds = address.get_pda_seed_references().into_iter(); - pda_refs.extend(seeds.filter(|seed| !is_field(seed))); - } - } // Keep-alive inputs only name the account a keep-alive writes, so they count as selectors. let constant_refs: HashSet<&str> = template .into_iter() @@ -127,14 +110,6 @@ pub(crate) fn account_data_values( .map(|property| property.path.as_str()) .chain(template.keep_alive_inputs()) }) - .chain( - own_imports - .iter() - .filter_map(|import| match &import.address { - KeepAliveAddress::Input(name) if !is_field(name) => Some(name.as_str()), - _ => None, - }), - ) .collect(); let values = instance .values @@ -488,7 +463,7 @@ impl TemplateRegistry { } #[cfg(test)] -pub(crate) mod tests { +mod tests { use std::{ collections::{BTreeSet, HashMap}, str::FromStr, @@ -874,7 +849,7 @@ templates: assert!(error.contains("exceeds the 15 byte account"), "{error}"); } - pub(crate) const KEEP_ALIVE_OVERRIDES: &str = r#" + const KEEP_ALIVE_OVERRIDES: &str = r#" protocol: Example version: v1 account_type: State @@ -917,7 +892,7 @@ templates: - { path: ms, offset: 16, encoding: u64, description: Published time } "#; - pub(crate) fn keep_alive_registry(overrides: &str) -> TemplateRegistry { + fn keep_alive_registry(overrides: &str) -> TemplateRegistry { let mut registry = TemplateRegistry::default(); registry.load_raw_layout_overrides(overrides, "example"); registry.load_keep_alive(None, KEEP_ALIVE, "example"); @@ -1006,32 +981,6 @@ templates: assert_eq!(values.keys().collect::>(), ["balance"]); } - #[test] - fn what_an_overrides_own_keep_alive_reads_is_never_written_unless_a_field() { - let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); - let system = "11111111111111111111111111111111"; - let mut instance = OverrideInstance::new( - "example-price".to_string(), - 0, - surfpool_types::AccountAddress::Pubkey(system.to_string()), - ) - .with_values(HashMap::from([ - ("price".to_string(), serde_json::json!(1)), - ("feed".to_string(), serde_json::json!(system)), - ("seed".to_string(), serde_json::json!(system)), - ])); - instance.keep_alive = serde_json::from_value(serde_json::json!([ - { "template": "example-fresh", "address": { "type": "input", "value": "feed" }, "values": { "slot": "$slot" } }, - { "template": "example-fresh", "address": { "type": "pda", "program_id": system, "seeds": [ - { "type": "property_ref", "value": "seed" }, - { "type": "property_ref", "value": "price" }, - ] }, "values": { "slot": "$slot" } }, - ])) - .unwrap(); - let (values, _, _) = account_data_values(&instance, registry.get("example-price")); - assert_eq!(values.keys().collect::>(), ["price"]); - } - #[test] fn imports_the_registry_cannot_apply_are_refused() { let refused = |overrides: String, expected: &str| { diff --git a/crates/core/src/surfnet/svm.rs b/crates/core/src/surfnet/svm.rs index a5751af7e..9df65b65c 100644 --- a/crates/core/src/surfnet/svm.rs +++ b/crates/core/src/surfnet/svm.rs @@ -610,8 +610,6 @@ pub struct SurfnetSvm { /// The accounts keep-alive rewrites every slot, from the slot a scenario's override first /// touched them. Kept in memory only, so a restart on a persistent database stops keep-alive. pub keep_alive_bindings: BTreeSet, - /// The keep-alive lists overrides gave in place of their template's, by the account they wrote. - pub keep_alive_imports: HashMap>, /// Tracks accounts that should not be downloaded from the remote RPC. /// This includes accounts explicitly closed locally and accounts marked offline via cheatcodes. /// The key is the account pubkey as a string. If `include_owned_accounts` is true, @@ -896,7 +894,6 @@ impl SurfnetSvm { streamed_accounts: OverlayStorage::wrap(self.streamed_accounts.clone_box()), scheduled_overrides: OverlayStorage::wrap(self.scheduled_overrides.clone_box()), keep_alive_bindings: self.keep_alive_bindings.clone(), - keep_alive_imports: self.keep_alive_imports.clone(), // Clone non-storage fields normally transactions_queued_for_confirmation: self.transactions_queued_for_confirmation.clone(), @@ -1407,7 +1404,6 @@ impl SurfnetSvm { recent_blockhashes: VecDeque::new(), scheduled_overrides: scheduled_overrides_db, keep_alive_bindings: BTreeSet::new(), - keep_alive_imports: HashMap::new(), offline_accounts: offline_accounts_db, genesis_slot: default_genesis_slot, genesis_updated_at: updated_at, @@ -2628,7 +2624,6 @@ impl SurfnetSvm { self.streamed_accounts.clear()?; self.scheduled_overrides.clear()?; self.keep_alive_bindings.clear(); - self.keep_alive_imports.clear(); let current_time = chrono::Utc::now().timestamp_millis() as u64; self.updated_at = current_time; @@ -3426,8 +3421,7 @@ impl SurfnetSvm { remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>, slot: Slot, ) { - let keep_alive_overrides = - self.keep_alive_overrides(template_registry(), slot, remote_ctx.is_some()); + let keep_alive_overrides = self.keep_alive_overrides(slot, remote_ctx.is_some()); if let Err(e) = self .apply_overrides(remote_ctx, slot, keep_alive_overrides, false) .await @@ -3449,7 +3443,7 @@ impl SurfnetSvm { let touched = self .apply_overrides(remote_ctx, target_slot, overrides, true) .await?; - self.enroll_keep_alive(template_registry(), touched); + self.enroll_keep_alive(touched); } Ok::<_, SurfpoolError>(()) } @@ -3536,16 +3530,22 @@ impl SurfnetSvm { // Joins keep-alive only once its write succeeds: a failed override leaves the account as // if no scenario had touched it. + let keep_alive_off = override_instance + .keep_alive + .as_ref() + .is_some_and(Vec::is_empty); let mut keep_alive_source = None; if scheduled - && let Some(template) = template_registry().get(&override_instance.template_id) - && (!template.keep_alive.is_empty() || override_instance.keep_alive.is_some()) + && (keep_alive_off + || template_registry() + .get(&override_instance.template_id) + .is_some_and(|template| !template.keep_alive.is_empty())) { keep_alive_source = Some(KeepAliveSource { - template: template.id.clone(), + template: override_instance.template_id.clone(), address: account_pubkey, values: override_instance.values.clone(), - imports: override_instance.keep_alive_imports(), + off: keep_alive_off, }); } @@ -3664,10 +3664,7 @@ impl SurfnetSvm { Err(e) => { restore_unprocessed(self, index); // The overrides before this one wrote their accounts, so they still join. - self.enroll_keep_alive( - template_registry(), - std::mem::take(&mut keep_alive_touched), - ); + self.enroll_keep_alive(std::mem::take(&mut keep_alive_touched)); return Err(e); } }; @@ -3817,10 +3814,7 @@ impl SurfnetSvm { ) { restore_unprocessed(self, index); // The overrides before this one wrote their accounts, so they still join. - self.enroll_keep_alive( - template_registry(), - std::mem::take(&mut keep_alive_touched), - ); + self.enroll_keep_alive(std::mem::take(&mut keep_alive_touched)); return Err(e); } keep_alive_touched.extend(keep_alive_source.take()); @@ -3929,36 +3923,19 @@ impl SurfnetSvm { Ok(keep_alive_touched) } - /// Adds the accounts that `touched` makes keep-alive imports rewrite. An override's own list - /// replaces its template's, and first drops what earlier overrides of its account bound. - fn enroll_keep_alive(&mut self, registry: &TemplateRegistry, touched: Vec) { + /// Adds the accounts that `touched` makes keep-alive imports rewrite. + fn enroll_keep_alive(&mut self, touched: Vec) { for source in touched { - let Some(template) = registry.get(&source.template) else { + if source.off { + self.keep_alive_bindings + .retain(|binding| binding.address != source.address); + info!("Keep-alive stops rewriting {}", source.address); + continue; + } + let Some(template) = template_registry().get(&source.template) else { continue; }; - let own = source.imports.is_some(); - let imports = match source.imports { - Some(imports) => { - self.keep_alive_bindings - .retain(|binding| binding.source != source.address); - self.keep_alive_imports.insert(source.address, imports); - &self.keep_alive_imports[&source.address] - } - None => &template.keep_alive, - }; - for (index, import) in imports.iter().enumerate() { - if own - && let Err(e) = registry - .keep_alive_template(&import.template) - .ok_or_else(|| "no keep-alive file defines it".to_string()) - .and_then(|_| import.validate()) - { - warn!( - "Keep-alive '{}' of the override of {} is skipped: {}", - import.template, source.address, e - ); - continue; - } + for (index, import) in template.keep_alive.iter().enumerate() { let Some(address) = import.address(source.address, &source.values) else { warn!( "Keep-alive '{}' of override template '{}' has no address for {}", @@ -3970,8 +3947,6 @@ impl SurfnetSvm { template: template.id.clone(), import: index, address, - own, - source: source.address, }; if self.keep_alive_bindings.insert(binding) { info!( @@ -3985,12 +3960,7 @@ impl SurfnetSvm { /// The keep-alive overrides for every binding at `slot`. A missing account is fetched first when /// `can_fetch` and not offline, otherwise skipped. - fn keep_alive_overrides( - &self, - registry: &TemplateRegistry, - slot: Slot, - can_fetch: bool, - ) -> Vec { + fn keep_alive_overrides(&self, slot: Slot, can_fetch: bool) -> Vec { // The time the open slot's Clock sysvar holds. The Clock advances by each slot's own // interval, so recomputing it from the slot would apply a changed slot interval to every // slot since the last time travel or restart. @@ -3999,15 +3969,11 @@ impl SurfnetSvm { unix_time_ms: self.updated_at, }; let mut instances = Vec::new(); - let mut previous: Option<&KeepAliveBinding> = None; for binding in &self.keep_alive_bindings { - if previous - .replace(binding) - .is_some_and(|previous| binding.repeats(previous)) - { - continue; - } - let Some(import) = binding.find(registry, &self.keep_alive_imports) else { + let Some(import) = template_registry() + .get(&binding.template) + .and_then(|template| template.keep_alive.get(binding.import)) + else { continue; }; let missing = match self.get_account(&binding.address) { @@ -5567,7 +5533,6 @@ mod tests { use super::*; use crate::{ - scenarios::registry::tests::{KEEP_ALIVE_OVERRIDES, keep_alive_registry}, storage::tests::TestType, surfnet::locker::SurfnetSvmLocker, tests::helpers::{UNHEALTHY_OFFSET, canned_rpc, scheduled_override_fixture}, @@ -9797,139 +9762,44 @@ mod tests { assert_eq!(update.data.decode(), Some(account.data)); } - fn own_keep_alive(imports: serde_json::Value) -> Option> { - let imports: Vec = - serde_json::from_value(imports).unwrap(); - Some(imports.into_iter().map(Into::into).collect()) - } - - fn keep_alive_target(svm: &mut SurfnetSvm) -> Pubkey { - let address = Pubkey::new_unique(); - let account = Account { - lamports: 1, - ..Account::default() - }; - svm.inner.set_account(address, account).unwrap(); - address - } - - /// The accounts keep-alive writes at `slot`, each stamped with that slot. - fn written_at(svm: &SurfnetSvm, registry: &TemplateRegistry, slot: Slot) -> Vec { - svm.keep_alive_overrides(registry, slot, false) - .into_iter() - .map(|instance| { - assert_eq!(instance.values["slot"], serde_json::json!(slot)); - match instance.account { - surfpool_types::AccountAddress::Pubkey(address) => address, - pda => panic!("keep-alive writes a pubkey, not {pda:?}"), - } - }) - .collect() - } - - /// Absent, an override binds its template's imports; its own list replaces what earlier - /// overrides of its account bound. A template import two overrides bind is applied once. - #[test] - fn an_overrides_own_keep_alive_list_replaces_its_templates() { - let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); - let (mut svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); - let (oracle, feed) = (keep_alive_target(&mut svm), keep_alive_target(&mut svm)); - let (vault, other_vault) = (Pubkey::new_unique(), Pubkey::new_unique()); - let source = |address, imports| KeepAliveSource { - template: "example-vault".to_string(), - address, - values: HashMap::from([("oracle".to_string(), serde_json::json!(oracle.to_string()))]), - imports, - }; - - svm.enroll_keep_alive( - ®istry, - vec![source(vault, None), source(other_vault, None)], - ); - assert_eq!(svm.keep_alive_bindings.len(), 2); - assert_eq!(written_at(&svm, ®istry, 1), [oracle.to_string()]); - - let own = own_keep_alive(serde_json::json!([ - { "template": "nowhere", "address": { "type": "override" }, "values": { "slot": "$slot" } }, - { "template": "example-fresh", "address": { "type": "input", "value": "missing" }, "values": { "slot": "$slot" } }, - { "template": "example-fresh", "address": { "type": "pubkey", "value": feed.to_string() }, "values": { "slot": "$slot" } }, - ])); - svm.enroll_keep_alive(®istry, vec![source(vault, own)]); - let bindings = svm - .keep_alive_bindings - .iter() - .map(|binding| (binding.source, binding.address, binding.own)) - .collect::>(); - assert_eq!( - bindings, - [(other_vault, oracle, false), (vault, feed, true)] - ); - assert_eq!( - written_at(&svm, ®istry, 1), - [oracle, feed].map(|address| address.to_string()), - "the other vault still keeps the oracle" - ); - } - - /// The case of the price feeds a transaction reads, which no scenario names. - #[test] - fn an_overrides_own_pubkey_imports_keep_other_accounts_fresh_every_slot() { - let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); - let (mut svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); - let feeds = [keep_alive_target(&mut svm), keep_alive_target(&mut svm)]; - let imports = feeds.map(|feed| { - serde_json::json!({ - "template": "example-fresh", - "address": { "type": "pubkey", "value": feed.to_string() }, - "values": { "slot": "$slot", "ms": "$unix_ms" }, - }) - }); - let source = KeepAliveSource { - template: "example-price".to_string(), - address: Pubkey::new_unique(), - values: HashMap::new(), - imports: own_keep_alive(serde_json::json!(imports)), - }; - svm.enroll_keep_alive(®istry, vec![source]); - for slot in [7, 8] { - let fresh = feeds.map(|feed| feed.to_string()); - assert_eq!(written_at(&svm, ®istry, slot), fresh); - } - } - #[tokio::test] - async fn an_empty_keep_alive_list_stops_what_earlier_overrides_of_its_account_started() { - const SLOT: u64 = 500; - let registry = keep_alive_registry(KEEP_ALIVE_OVERRIDES); + async fn an_empty_keep_alive_list_stops_keep_alive_on_the_account_it_writes() { let (mut svm, _simnet_events_rx, _geyser_events_rx) = SurfnetSvm::default(); let (account_pubkey, instance) = scheduled_override_fixture(&mut svm); let other = Pubkey::new_unique(); - let earlier = [account_pubkey, other].map(|address| KeepAliveSource { - template: "example-price".to_string(), - address, - values: HashMap::new(), - imports: None, - }); - svm.enroll_keep_alive(®istry, earlier.to_vec()); - let mut play = async |values: HashMap| { + for address in [account_pubkey, other] { + svm.keep_alive_bindings.insert(KeepAliveBinding { + template: "an-earlier-override".to_string(), + import: 0, + address, + }); + } + let mut play = async |slot: u64, keep_alive: serde_json::Value, values| { let mut instance = instance.clone().with_values(values); - instance.keep_alive = Some(Vec::new()); - svm.scheduled_overrides.store(SLOT, vec![instance]).unwrap(); - svm.materialize_overrides_for_slot(&None, SLOT) + instance.keep_alive = serde_json::from_value(keep_alive).unwrap(); + svm.scheduled_overrides.store(slot, vec![instance]).unwrap(); + svm.materialize_overrides_for_slot(&None, slot) .await .unwrap(); svm.keep_alive_bindings .iter() - .map(|binding| binding.source) - .collect::>() + .map(|binding| binding.address) + .collect::>() }; + let mut both = vec![account_pubkey, other]; + both.sort(); let failed = HashMap::from([("nope".to_string(), serde_json::json!(1))]); + assert_eq!(play(500, serde_json::json!([]), failed).await, both); + assert_eq!( + play(501, serde_json::json!([{}]), instance.values.clone()).await, + both, + "a failed write and a non-empty list stop nothing" + ); assert_eq!( - play(failed).await.len(), - 2, - "a failed write changes nothing" + play(502, serde_json::json!([]), instance.values.clone()).await, + vec![other], + "only the written account stops" ); - assert_eq!(play(instance.values.clone()).await, [other]); } } diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts index ccc3bd379..d7d9cb87c 100644 --- a/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts +++ b/crates/sdk-node/surfpool-sdk/kit/generated/OverrideInstance.ts @@ -2,7 +2,6 @@ // Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AccountAddress } from "./AccountAddress.js"; -import type { YamlKeepAliveImport } from "./YamlKeepAliveImport.js"; /** * A concrete instance of an override template with specific values @@ -38,11 +37,10 @@ enabled: boolean, */ fetchBeforeUse?: boolean, /** - * Keep-alive imports in place of the template's, in the same shape as a template file's - * `keep_alive` list. Absent, the template's imports apply. Present, even empty, they first - * drop the keep-alive that earlier overrides of this account started. + * Keep-alive for the account this override writes. Absent, the template's keep-alive applies; + * `[]` turns it off. Only `[]` is supported. */ -keepAlive?: Array, +keepAlive?: Array, /** * Account address to override - use pubkey for known addresses or pda for derived addresses */ diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts b/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts deleted file mode 100644 index 73c1062fe..000000000 --- a/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveAddress.ts +++ /dev/null @@ -1,9 +0,0 @@ -// @generated by ts-rs from the Rust types in crates/types. -// Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { YamlPdaSeed } from "./YamlPdaSeed.js"; - -/** - * Where a keep-alive import writes, as YAML writes it. - */ -export type YamlKeepAliveAddress = { "type": "override" } | { "type": "input", value: string, } | { "type": "pubkey", value: string, } | { "type": "pda", program_id: string, seeds: Array, }; diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts b/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts deleted file mode 100644 index 5cbacacae..000000000 --- a/crates/sdk-node/surfpool-sdk/kit/generated/YamlKeepAliveImport.ts +++ /dev/null @@ -1,9 +0,0 @@ -// @generated by ts-rs from the Rust types in crates/types. -// Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { YamlKeepAliveAddress } from "./YamlKeepAliveAddress.js"; - -/** - * A keep-alive import as YAML writes it. - */ -export type YamlKeepAliveImport = { template: string, address: YamlKeepAliveAddress, values: Record, }; diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts b/crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts deleted file mode 100644 index 848dc2029..000000000 --- a/crates/sdk-node/surfpool-sdk/kit/generated/YamlPdaSeed.ts +++ /dev/null @@ -1,8 +0,0 @@ -// @generated by ts-rs from the Rust types in crates/types. -// Do not edit; run `npm run generate:kit-types` in crates/sdk-node instead. -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * YAML representation of PDA seeds - */ -export type YamlPdaSeed = { "type": "string", value: string, } | { "type": "bytes", value: Array, } | { "type": "pubkey", value: string, } | { "type": "property_ref", value: string, } | { "type": "u16_be", value: number, } | { "type": "u16_be_ref", value: string, } | { "type": "u16_le", value: number, } | { "type": "bytes32_ref", value: string, } | { "type": "derived_pda", program_id: string, seeds: Array, }; diff --git a/crates/sdk-node/surfpool-sdk/kit/generated/index.ts b/crates/sdk-node/surfpool-sdk/kit/generated/index.ts index 0a151a3f8..e610e03d1 100644 --- a/crates/sdk-node/surfpool-sdk/kit/generated/index.ts +++ b/crates/sdk-node/surfpool-sdk/kit/generated/index.ts @@ -34,7 +34,4 @@ export type * from "./UiAccountEncoding.js"; export type * from "./UiAccountProfileState.js"; export type * from "./UiKeyedProfileResult.js"; export type * from "./UiProfileResult.js"; -export type * from "./YamlKeepAliveAddress.js"; -export type * from "./YamlKeepAliveImport.js"; -export type * from "./YamlPdaSeed.js"; export * from "./methods.js"; diff --git a/crates/types/src/rpc_endpoints.json b/crates/types/src/rpc_endpoints.json index 1384f3d2b..58ea59acc 100644 --- a/crates/types/src/rpc_endpoints.json +++ b/crates/types/src/rpc_endpoints.json @@ -861,7 +861,7 @@ "label": "Option (An optional label for this override instance)", "enabled": "bool (Indicates whether this override instance is enabled)", "fetchBeforeUse": "bool (Indicates whether to fetch the latest on-chain account data before applying overrides)", - "keepAlive": "Option> (Optional keep-alive list in place of the template's keep_alive list, in the same shape: [{\"template\": \"\", \"address\": {\"type\": \"override\"} or {\"type\": \"input\", \"value\": \"\"} or {\"type\": \"pubkey\", \"value\": \"\"} or {\"type\": \"pda\", \"program_id\": \"\", \"seeds\": [ ... ]}, \"values\": {\"\": \"$slot\"}}]. Omitted, the template's list applies. Given, even as [], it first stops the keep-alive that earlier overrides of this account started, then starts its own imports)", + "keepAlive": "Option<[]> (Optional. Omit it to keep the template's keep-alive. [] turns keep-alive off for the account this override writes, from this slot on, including keep-alive that earlier overrides started. Only [] is supported)", "account": "AccountAddress (The account this override targets, as {\"pubkey\": \"\"} or {\"pda\": {\"programId\": \"\", \"seeds\": [ ... ]}})" } } diff --git a/crates/types/src/scenarios.rs b/crates/types/src/scenarios.rs index 3e8d3c94a..418c183e0 100644 --- a/crates/types/src/scenarios.rs +++ b/crates/types/src/scenarios.rs @@ -592,15 +592,14 @@ pub struct OverrideInstance { #[serde(default)] #[cfg_attr(feature = "ts-bindings", ts(as = "Option", optional))] pub fetch_before_use: bool, - /// Keep-alive imports in place of the template's, in the same shape as a template file's - /// `keep_alive` list. Absent, the template's imports apply. Present, even empty, they first - /// drop the keep-alive that earlier overrides of this account started. + /// Keep-alive for the account this override writes. Absent, the template's keep-alive applies; + /// `[]` turns it off. Only `[]` is supported. #[schemars( - description = "Optional keep-alive list in place of the template's, rewritten every slot from this override on: [{\"template\": \"\", \"address\": {\"type\": \"override\"} or {\"type\": \"input\", \"value\": \"\"} or {\"type\": \"pubkey\", \"value\": \"\"} or {\"type\": \"pda\", \"program_id\": \"...\", \"seeds\": [...]}, \"values\": {\"\": \"$slot\"}}]. Omit it to use the template's list. Given, even as [], it first stops the keep-alive that earlier overrides of this account started." + description = "Optional. Omit it to keep the template's keep-alive. [] turns keep-alive off for the account this override writes, from this slot on, including keep-alive that earlier overrides started. Only [] is supported" )] #[serde(default, skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "ts-bindings", ts(optional))] - pub keep_alive: Option>, + #[cfg_attr(feature = "ts-bindings", ts(type = "Array", optional))] + pub keep_alive: Option>, /// Account address to override - use pubkey for known addresses or pda for derived addresses #[schemars( description = "Account address: either {\"pubkey\": \"base58_address\"} or {\"pda\": {\"programId\": \"...\", \"seeds\": [...]}}" @@ -632,12 +631,6 @@ impl OverrideInstance { self.label = Some(label); self } - - /// The override's own keep-alive imports, when it gives them. - pub fn keep_alive_imports(&self) -> Option> { - let imports = self.keep_alive.clone()?; - Some(imports.into_iter().map(Into::into).collect()) - } } /// A scenario containing a timeline of overrides @@ -1555,19 +1548,16 @@ impl YamlOverrideTemplateCollection { // ======================================== /// A keep-alive import as YAML writes it. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] -#[cfg_attr(feature = "ts-bindings", derive(ts_rs::TS), ts(export))] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct YamlKeepAliveImport { pub template: String, pub address: YamlKeepAliveAddress, - #[cfg_attr(feature = "ts-bindings", ts(type = "Record"))] pub values: HashMap, } /// Where a keep-alive import writes, as YAML writes it. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] -#[cfg_attr(feature = "ts-bindings", derive(ts_rs::TS), ts(export))] pub enum YamlKeepAliveAddress { /// The account the importing override writes. Override, @@ -1854,9 +1844,8 @@ impl From for AccountAddress { } /// YAML representation of PDA seeds -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] -#[cfg_attr(feature = "ts-bindings", derive(ts_rs::TS), ts(export))] pub enum YamlPdaSeed { String { value: String, @@ -2020,49 +2009,6 @@ mod tests { assert_eq!(values["fixed"], json!(3)); } - #[test] - fn an_override_takes_the_yaml_keep_alive_shape_or_leaves_it_to_the_template() { - let instance = |keep_alive: Option| { - let mut value = json!({ - "id": "o", - "templateId": "t", - "values": {}, - "scenarioRelativeSlot": 0, - "enabled": true, - "account": { "pubkey": "11111111111111111111111111111111" }, - }); - if let Some(keep_alive) = keep_alive { - value["keepAlive"] = keep_alive; - } - serde_json::from_value::(value).unwrap() - }; - assert_eq!(instance(None).keep_alive_imports(), None); - assert_eq!(instance(Some(json!(null))).keep_alive_imports(), None); - assert_eq!( - instance(Some(json!([]))).keep_alive_imports(), - Some(Vec::new()) - ); - let program = "11111111111111111111111111111111"; - let own = instance(Some(json!([ - { "template": "t", "address": { "type": "pubkey", "value": program }, "values": { "slot": "$slot" } }, - { "template": "t", "address": { "type": "pda", "program_id": program, "seeds": [{ "type": "property_ref", "value": "feed" }] }, "values": { "ms": "$unix_ms" } }, - ]))); - assert_eq!( - own.keep_alive_imports(), - Some(vec![ - keep_alive(&format!( - "template: t\naddress: {{ type: pubkey, value: \"{program}\" }}\nvalues: {{ slot: $slot }}\n" - )), - keep_alive(&format!( - "template: t\naddress: {{ type: pda, program_id: \"{program}\", seeds: [{{ type: property_ref, value: feed }}] }}\nvalues: {{ ms: $unix_ms }}\n" - )), - ]) - ); - let serialized = |instance| serde_json::to_value(instance).unwrap(); - assert!(serialized(instance(None)).get("keepAlive").is_none()); - assert_eq!(serialized(own)["keepAlive"][1]["address"]["type"], "pda"); - } - #[test] fn a_file_level_keep_alive_is_inherited_unless_a_template_sets_its_own() { let file: super::YamlOverrideTemplateCollection = serde_yaml::from_str( @@ -2559,4 +2505,31 @@ templates: ); } } + + #[test] + fn keep_alive_is_absent_unless_given() { + let instance = |keep_alive: Option| { + let mut value = json!({ + "id": "o", "templateId": "t", "values": {}, "scenarioRelativeSlot": 0, + "enabled": true, "account": { "pubkey": "11111111111111111111111111111111" } + }); + if let Some(keep_alive) = keep_alive { + value["keepAlive"] = keep_alive; + } + serde_json::from_value::(value).unwrap() + }; + + let absent = instance(None); + assert_eq!(absent.keep_alive, None); + assert!( + serde_json::to_value(&absent) + .unwrap() + .get("keepAlive") + .is_none() + ); + + let off = instance(Some(json!([]))); + assert_eq!(off.keep_alive, Some(vec![])); + assert_eq!(serde_json::to_value(&off).unwrap()["keepAlive"], json!([])); + } } From 1e755e9fd0d57b49027d81653f9f71b05adaed4e Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 20 Nov 2026 16:36:27 +0200 Subject: [PATCH 20/24] docs(scenarios): one README for the Pyth receivers --- crates/core/src/scenarios/README.md | 2 +- .../src/scenarios/protocols/pyth/README.md | 228 ++++++++++++++++++ .../pyth/core-compatible/v2/README.md | 36 --- 3 files changed, 229 insertions(+), 37 deletions(-) create mode 100644 crates/core/src/scenarios/protocols/pyth/README.md delete mode 100644 crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md diff --git a/crates/core/src/scenarios/README.md b/crates/core/src/scenarios/README.md index b5989a839..04ff4e439 100644 --- a/crates/core/src/scenarios/README.md +++ b/crates/core/src/scenarios/README.md @@ -13,7 +13,7 @@ For Surfpool to understand how to serialize and deserialize account data, it nee Protocols that are natively supported by Surfpool will have their IDLs included by default. **Currently supported protocols:** -- **Pyth v2** - Price oracle with a price feed template for the Pyth Core receiver (`pyth-price-feed-v2`) and one for the Pyth Core Compatible receiver (`pyth-core-compatible-price-feed-v2`); both keep the price they write published +- **Pyth v2** - Price oracle with a price feed template for the Pyth Core receiver (`pyth-price-feed-v2`) and one for the Pyth Core Compatible receiver (`pyth-core-compatible-price-feed-v2`); both keep the price they write published. See [protocols/pyth/README.md](./protocols/pyth/README.md) - **Jupiter v6** - DEX aggregator with TokenLedger manipulation template - **Switchboard On-Demand** - On-demand oracle with QuoteAccount override template - **Kamino** – Lending (v1.23.0), Scope oracle, Farms, Swap/LIMO, Earn vaults and Liquidity, across six programs. See [protocols/kamino/README.md](./protocols/kamino/README.md) diff --git a/crates/core/src/scenarios/protocols/pyth/README.md b/crates/core/src/scenarios/protocols/pyth/README.md new file mode 100644 index 000000000..40e528162 --- /dev/null +++ b/crates/core/src/scenarios/protocols/pyth/README.md @@ -0,0 +1,228 @@ +# Pyth + +Pyth runs two price receivers on Solana, both deployments of the `pyth_solana_receiver` program, as +listed on [Pyth's Solana contract addresses](https://docs.pyth.network/price-feeds/contract-addresses/solana). +Surfpool bundles an IDL, an override template and a keep-alive for each: + +| Receiver | Program | Folder | Template | +|---|---|---|---| +| Pyth Core | `rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ` | `v2/` | `pyth-price-feed-v2` | +| Pyth Core Compatible | `rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` | `core-compatible/v2/` | `pyth-core-compatible-price-feed-v2` | + +They hold separate price accounts for the same feeds, and a consumer reads the accounts of one of +them. Take the price account from the consumer's own account that names it. + +For how scenarios work in general see the [scenarios README](../../README.md). + +# Template index + +**Pyth Core** · `rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ` · `v2/` + +| Template | Overrides | +|---|---| +| `pyth-price-feed-v2` | the price account of a feed picked from a list | + +**Pyth Core Compatible** · `rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` · `core-compatible/v2/` + +| Template | Overrides | +|---|---| +| `pyth-core-compatible-price-feed-v2` | a price account of this receiver, given by address | + +Both templates write the same fields of a `PriceUpdateV2` account: `price_message.price`, +`price_message.conf`, `price_message.exponent`, `price_message.publish_time`, +`price_message.prev_publish_time`, `price_message.ema_price`, `price_message.ema_conf` and +`posted_slot`. `pyth-price-feed-v2` also takes `feed_id`, which picks the account and is not +written. Both templates import a [keep-alive](#keep-alive). + +## Picking a price account + +Set `fetchBeforeUse: true` to pull the price account from upstream first. + +### Pyth Core + +Pick the feed in the template's **Price Feed** list, the `price_feed` constant in +`v2/overrides.yaml`. Its value is the feed id, and the template derives the price account from it: +a PDA of `pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT` with the seeds shard `0` as a little-endian +`u16` and the 32-byte feed id. For SOL/USD, feed id +`0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d`, that is +`7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE`, an account owned by the Pyth Core receiver. + +For a feed the list does not have, name the price account in the override's account as +`{"pubkey": ""}`. + +### Pyth Core Compatible + +This template has no feed list. It writes the account the override names: + +1. Take the price account from the consumer's account that names it. +2. Check that its owner is `rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp`. For an account owned by + the Pyth Core receiver, use `pyth-price-feed-v2`. +3. Put it in the override's account as `{"pubkey": ""}`. + +The SOL/USD price account of this receiver is `7AviUf9nL62mcxNbQGKm4nKDQnPjswo6c5MX4D57HmyE`. + +## Number formats + +Every price field is a scaled integer. The scale is the account's own `price_message.exponent`, +normally `-8` and `-10` on some feeds. + +| You'll see | It means | Example | +|---|---|---| +| `price_message.price` | the USD price x 10^-exponent | $145.00 at exponent `-8` → `14500000000` | +| `price_message.conf` | the uncertainty band around the price, in the same scale | $2 at exponent `-8` → `200000000` | +| `price_message.ema_price`, `price_message.ema_conf` | moving averages of price and conf, in the same scale | | +| `price_message.exponent` | the decimal exponent; it rescales every price field | `-8` | +| `price_message.publish_time`, `price_message.prev_publish_time` | Unix seconds | | +| `posted_slot` | the slot the update was posted at | | + +More examples at exponent `-8`: $97,000 BTC → `9700000000000`, $3,500 ETH → `350000000000`. At +exponent `-10` (BONK, PEPE and SHIB in the Pyth Core list): $0.00002 BONK → `200000`, $0.000012 +PEPE → `120000`. + +Leave `price_message.exponent` alone unless the scenario is about an exponent error. If you change it, +restate every scaled field to match. + +# Keep-alive + +Nobody publishes Pyth prices on a surfnet, so both templates import a +[keep-alive](../../README.md#keep-alive): from the slot an override of a template plays until +the network is reset, Surfpool writes the Clock's unix seconds to `price_message.publish_time` and +the slot to `posted_slot` every slot, time travels included. It does so for every price account of +that template's receiver the surfnet has loaded, including feeds no override names and, from the +next slot, feeds a transaction loads later, so a liquidation that reads the borrower's other feeds +finds them fresh. The price, confidence and EMA fields keep their values. To keep one feed stale on +purpose, override it with `keepAlive: false`; it then ages against the Surfnet clock. + +Each `overrides.yaml` imports, at its top level, the publication template of its folder's +`keep-alive.yaml`: + +| Template | Keep-alive template | Rewrites | +|---|---|---| +| `pyth-price-feed-v2` | `pyth-price-publication` | every loaded `PriceUpdateV2` account owned by `rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ` | +| `pyth-core-compatible-price-feed-v2` | `pyth-core-compatible-price-publication` | every loaded `PriceUpdateV2` account owned by `rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` | + +```yaml +keep_alive: + - template: pyth-price-publication + address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: PriceUpdateV2 } + values: { price_message.publish_time: $unix_s, posted_slot: $slot } +``` + +The keep-alive templates are never offered in Studio or MCP. Because keep-alive rewrites +`price_message.publish_time` and `posted_slot` every slot, a value an override sets for them holds +only with `keepAlive: false`. + +# Recipes + +## Drop a price + +"SOL drops to $20" on an account with exponent `-8`, live price `p` and live EMA price `q`: + +``` +price_message.price: 2000000000 +price_message.ema_price: 2000000000 +price_message.conf: +price_message.ema_conf: +``` + +Move `ema_price` with `price`: consumers use the EMA for some checks and the spot price for others. +Scale `conf` and `ema_conf` by the same factor as the price: consumers refuse a price whose +confidence is too wide a share of it, so a large drop that keeps the live `conf` can be refused. + +## Keep one feed stale + +Keep-alive starts only when an override with `keepAlive: true` writes a price account, and an +override with no values writes nothing. For `pyth-price-feed-v2`, `feed_id` does not count as a +value. To keep one feed stale while the others stay fresh, add two overrides of the receiver's +template, both with `fetchBeforeUse: true` and `price_message.price` set to the account's current +price, so no price changes: + +- on the stale feed's price account, `keepAlive: false`. It then ages against the Surfnet clock and + turns stale once the consumer's age limit has passed; +- on any other price account the same consumer reads, `keepAlive: true`. This starts the + republishing of every loaded price account except the stale one. + +To make it stale at once, `surfnet_timeTravel` past the consumer's limit. Its `absoluteTimestamp` +is in milliseconds, while `publish_time` and the Clock sysvar are in seconds. + +# Troubleshooting + +| Symptom | Fix | +|---|---| +| The consumer still reads the old price | The override wrote the other receiver's account. Check the price account's owner and use that receiver's template | +| A large price drop is refused | Scale `conf` and `ema_conf` with the price. See [Drop a price](#drop-a-price) | +| A `publish_time` or `posted_slot` value did not hold | Keep-alive rewrites both every slot. Set `keepAlive: false` on that override | +| Other feeds of the consumer turn stale | Keep-alive starts only when an override with `keepAlive: true` writes a price account. Give that override a value, such as the current price | +| A feed meant to be stale is still fresh after `surfnet_timeTravel` | `absoluteTimestamp` is in milliseconds, and `publish_time` is in seconds | +| Prices are off by a power of ten after an exponent change | `exponent` rescales every price field. Restate `price`, `conf`, `ema_price` and `ema_conf` to match | + +# Files + +| File | Holds | +|---|---| +| `v2/overrides.yaml` | the `pyth-price-feed-v2` template and its `price_feed` list | +| `v2/idl.json` | the Pyth Core IDL | +| `v2/keep-alive.yaml` | the `pyth-price-publication` keep-alive template | +| `v2/generate-price-feeds.js` | the script that regenerates the `price_feed` list | +| `core-compatible/v2/overrides.yaml` | the `pyth-core-compatible-price-feed-v2` template | +| `core-compatible/v2/idl.json` | the Pyth Core Compatible IDL | +| `core-compatible/v2/keep-alive.yaml` | the `pyth-core-compatible-price-publication` keep-alive template | + +[`registry.rs`](../../registry.rs) compiles these files in. `load_pyth_overrides` loads both +template collections under the protocol `Pyth`, each with the IDL beside it, and both keep-alive +files. + +## Regenerating the Pyth Core feed list + +`v2/generate-price-feeds.js` fetches the feeds from the Pyth Hermes API +(`https://hermes.pyth.network/v2/price_feeds`) and rewrites the `price_feed` options in +`v2/overrides.yaml`. From `v2/`: + +``` +node generate-price-feeds.js +``` + +It keeps the `Crypto` feeds quoted in USD whose base is in the script's `POPULAR_SYMBOLS`, plus +ETH/BTC, and puts SOL, BTC, ETH, USDC and USDT first. The "(N decimals)" in each option's +description is the feed's exponent without its sign, read from +`https://hermes.pyth.network/v2/updates/price/latest`, or 8 when Hermes returns none. The script +expects the `constants` block to end right before `templates:`. + +## Tests + +The Pyth integration tests in `crates/core/src/tests/pyth/` fetch real price accounts from mainnet, +so they need a network connection and are compiled only behind a feature: + +``` +cargo test -p surfpool-core --features integration-tests pyth +``` + +Set `SURFPOOL_TEST_RPC_URL` to use a private endpoint if the public one rate-limits. The unit tests +in `registry.rs` check the Pyth Core address derivation and both keep-alive imports without a +network. + +# IDL + +## Pyth Core + +`v2/idl.json` is an Anchor IDL with the address `rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ`. It +has no instructions and defines one account, `PriceUpdateV2`, with the types `PriceFeedMessage`, +`PriceUpdateV2` and `VerificationLevel`. Its `PriceUpdateV2` account has the same discriminator and +fields as the one in the Pyth Core Compatible IDL. + +| IDL | sha256 | +|---|---| +| Bundled `v2/idl.json` | `93b29b6f60d6c50c39de3d3f075b0d9acf948633edef7234e6b1e2f9b397aa02` | + +## Pyth Core Compatible + +`core-compatible/v2/idl.json` is the IDL the program publishes in its Anchor IDL account +`raeUSn8gguFWVFs4iw3YathYM3mdb95W5Bfiu3tqE7F` (`pyth_solana_receiver` 0.2.1, legacy format, sha256 +`9ec4718f66a71fc524ecdd533770ca5a8a3984f8e1fb603f01f5e31ff0ab0caa`), converted with +`anchor idl convert --program-id rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` (anchor-cli 0.31.1, +output sha256 `29ab79ef705a3429b3ced2b1222e1b5efdcd4b40fed547177d31c16ebd8473fc`). + +One change is made before the conversion: the account names `priceUpdateV2` and `twapUpdate` are +written `PriceUpdateV2` and `TwapUpdate`, as the program's Rust types are named. Anchor derives an +account's discriminator from its name, and only the capitalized names give the discriminator the +live price accounts carry. diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md deleted file mode 100644 index 27e14795d..000000000 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# Pyth Core Compatible - -Pyth runs two price receivers on Solana, both deployments of the `pyth_solana_receiver` program, as -listed on [Pyth's Solana contract addresses](https://docs.pyth.network/price-feeds/contract-addresses/solana): - -| Receiver | Program | Template | -|---|---|---| -| Pyth Core | `rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ` | `pyth-price-feed-v2` | -| Pyth Core Compatible | `rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` | `pyth-core-compatible-price-feed-v2` | - -They hold separate price accounts for the same feeds, and a consumer reads the accounts of one of -them. Take the price account from the consumer's own account that names it. - -# Keep-alive - -Nobody publishes Pyth prices on a surfnet, so both templates import a -[keep-alive](../../../../README.md#keep-alive): from the slot an override of a template plays until -the network is reset, Surfpool writes the Clock's unix seconds to `price_message.publish_time` and -the slot to `posted_slot` every slot, time travels included. It does so for every price account of -that template's receiver the surfnet has loaded, including feeds no override names and, from the -next slot, feeds a transaction loads later, so a liquidation that reads the borrower's other feeds -finds them fresh. The price, confidence and EMA fields keep their values. To keep one feed stale on -purpose, override it with `keepAlive: false`; it then ages against the Surfnet clock. - -# IDL - -`idl.json` is the IDL the program publishes in its Anchor IDL account -`raeUSn8gguFWVFs4iw3YathYM3mdb95W5Bfiu3tqE7F` (`pyth_solana_receiver` 0.2.1, legacy format, sha256 -`9ec4718f66a71fc524ecdd533770ca5a8a3984f8e1fb603f01f5e31ff0ab0caa`), converted with -`anchor idl convert --program-id rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` (anchor-cli 0.31.1, -output sha256 `29ab79ef705a3429b3ced2b1222e1b5efdcd4b40fed547177d31c16ebd8473fc`). - -One change is made before the conversion: the account names `priceUpdateV2` and `twapUpdate` are -written `PriceUpdateV2` and `TwapUpdate`, as the program's Rust types are named. Anchor derives an -account's discriminator from its name, and only the capitalized names give the discriminator the -live price accounts carry. From baf6c7359d30bbecf49f289761aa3af14ba437b7 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 20 Nov 2026 17:14:12 +0200 Subject: [PATCH 21/24] refactor(scenarios): keep each Pyth feed fresh through its own override --- .../src/scenarios/protocols/pyth/README.md | 49 +++++----- .../pyth/core-compatible/v2/overrides.yaml | 40 ++++---- .../protocols/pyth/v2/overrides.yaml | 41 ++++---- crates/core/src/scenarios/registry.rs | 16 +-- crates/core/src/tests/pyth/mod.rs | 98 +++++++++++-------- 5 files changed, 124 insertions(+), 120 deletions(-) diff --git a/crates/core/src/scenarios/protocols/pyth/README.md b/crates/core/src/scenarios/protocols/pyth/README.md index 40e528162..ca6c4bb61 100644 --- a/crates/core/src/scenarios/protocols/pyth/README.md +++ b/crates/core/src/scenarios/protocols/pyth/README.md @@ -85,32 +85,30 @@ restate every scaled field to match. # Keep-alive Nobody publishes Pyth prices on a surfnet, so both templates import a -[keep-alive](../../README.md#keep-alive): from the slot an override of a template plays until -the network is reset, Surfpool writes the Clock's unix seconds to `price_message.publish_time` and -the slot to `posted_slot` every slot, time travels included. It does so for every price account of -that template's receiver the surfnet has loaded, including feeds no override names and, from the -next slot, feeds a transaction loads later, so a liquidation that reads the borrower's other feeds -finds them fresh. The price, confidence and EMA fields keep their values. To keep one feed stale on -purpose, override it with `keepAlive: false`; it then ages against the Surfnet clock. +[keep-alive](../../README.md#keep-alive) for the price account an override writes: from the slot +the override plays until the network is reset, Surfpool writes the Clock's unix seconds to +`price_message.publish_time` and the slot to `posted_slot` every slot, time travels included. The +price, confidence and EMA fields keep their values. A price account no override writes is not +republished and ages against the Surfnet clock. Each `overrides.yaml` imports, at its top level, the publication template of its folder's `keep-alive.yaml`: -| Template | Keep-alive template | Rewrites | -|---|---|---| -| `pyth-price-feed-v2` | `pyth-price-publication` | every loaded `PriceUpdateV2` account owned by `rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ` | -| `pyth-core-compatible-price-feed-v2` | `pyth-core-compatible-price-publication` | every loaded `PriceUpdateV2` account owned by `rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp` | +| Template | Keep-alive template | +|---|---| +| `pyth-price-feed-v2` | `pyth-price-publication` | +| `pyth-core-compatible-price-feed-v2` | `pyth-core-compatible-price-publication` | ```yaml keep_alive: - template: pyth-price-publication - address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: PriceUpdateV2 } + address: { type: override } values: { price_message.publish_time: $unix_s, posted_slot: $slot } ``` The keep-alive templates are never offered in Studio or MCP. Because keep-alive rewrites `price_message.publish_time` and `posted_slot` every slot, a value an override sets for them holds -only with `keepAlive: false`. +only in an override with `"keepAlive": []`. # Recipes @@ -129,18 +127,19 @@ Move `ema_price` with `price`: consumers use the EMA for some checks and the spo Scale `conf` and `ema_conf` by the same factor as the price: consumers refuse a price whose confidence is too wide a share of it, so a large drop that keeps the live `conf` can be refused. -## Keep one feed stale +## Keep every feed a transaction reads fresh + +A transaction can read more feeds than the scenario moves: a liquidation reads every feed of the +borrower. Add one override of the receiver's template per such feed, in the same scenario and slot. +On a feed whose price must not move, set only `price_message.publish_time`. Any value works, +because keep-alive rewrites it in the same slot. For `pyth-price-feed-v2`, `feed_id` alone writes +nothing. -Keep-alive starts only when an override with `keepAlive: true` writes a price account, and an -override with no values writes nothing. For `pyth-price-feed-v2`, `feed_id` does not count as a -value. To keep one feed stale while the others stay fresh, add two overrides of the receiver's -template, both with `fetchBeforeUse: true` and `price_message.price` set to the account's current -price, so no price changes: +## Let a feed go stale -- on the stale feed's price account, `keepAlive: false`. It then ages against the Surfnet clock and - turns stale once the consumer's age limit has passed; -- on any other price account the same consumer reads, `keepAlive: true`. This starts the - republishing of every loaded price account except the stale one. +- A feed left without an override ages against the Surfnet clock from the start. +- To let a feed age later, give a later override of it `"keepAlive": []` and a value, such as its + current price. From that slot on nothing republishes it. To make it stale at once, `surfnet_timeTravel` past the consumer's limit. Its `absoluteTimestamp` is in milliseconds, while `publish_time` and the Clock sysvar are in seconds. @@ -151,8 +150,8 @@ is in milliseconds, while `publish_time` and the Clock sysvar are in seconds. |---|---| | The consumer still reads the old price | The override wrote the other receiver's account. Check the price account's owner and use that receiver's template | | A large price drop is refused | Scale `conf` and `ema_conf` with the price. See [Drop a price](#drop-a-price) | -| A `publish_time` or `posted_slot` value did not hold | Keep-alive rewrites both every slot. Set `keepAlive: false` on that override | -| Other feeds of the consumer turn stale | Keep-alive starts only when an override with `keepAlive: true` writes a price account. Give that override a value, such as the current price | +| A `publish_time` or `posted_slot` value did not hold | Keep-alive rewrites both every slot. A value holds only in an override with `"keepAlive": []` | +| Other feeds the transaction reads turn stale | Keep-alive republishes only the price accounts overrides write. See [Keep every feed a transaction reads fresh](#keep-every-feed-a-transaction-reads-fresh) | | A feed meant to be stale is still fresh after `surfnet_timeTravel` | `absoluteTimestamp` is in milliseconds, and `publish_time` is in seconds | | Prices are off by a power of ten after an exponent change | `exponent` rescales every price field. Restate `price`, `conf`, `ema_price` and `ema_conf` to match | diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index b4d718de3..9cb250a53 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -10,13 +10,13 @@ tags: keep_alive: - template: pyth-core-compatible-price-publication - address: { type: owned, owner: rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp, account: PriceUpdateV2 } + address: { type: override } values: { price_message.publish_time: $unix_s, posted_slot: $slot } templates: - id: pyth-core-compatible-price-feed-v2 name: Override Pyth Core Compatible Price Account - description: Override a price account of the Pyth Core Compatible receiver, found by address; keeps every loaded one published + description: Override a price account of the Pyth Core Compatible receiver, found by address; keeps that account published idl_account_name: PriceUpdateV2 properties: - path: price_message.price @@ -30,7 +30,7 @@ templates: description: Decimal exponent, normally -8 and -10 on some feeds. Rescales every price field - path: price_message.publish_time label: Publish Time - description: Unix seconds of this update, interpreted against the Surfnet clock. Keep-alive writes the Clock time every slot, so a value set here holds only with keepAlive false + description: 'Unix seconds of this update, interpreted against the Surfnet clock. Keep-alive writes the Clock time every slot, so a value set here holds only in an override with "keepAlive": []' - path: price_message.prev_publish_time label: Previous Publish Time description: Unix seconds of the preceding update @@ -42,7 +42,7 @@ templates: description: Exponential moving average confidence, in the same scale as conf - path: posted_slot label: Posted Slot - description: Slot the update was posted at, for consumers that measure freshness in slots. Keep-alive writes the current slot every slot, so a value set here holds only with keepAlive false + description: 'Slot the update was posted at, for consumers that measure freshness in slots. Keep-alive writes the current slot every slot, so a value set here holds only in an override with "keepAlive": []' address: type: pubkey llm_context: | @@ -66,24 +66,22 @@ templates: by the same factor as the price: consumers refuse a price whose confidence is too wide a share of it, so a large drop that keeps the live conf can be refused. - THE PRICE STAYS PUBLISHED BY ITSELF. From the slot this override plays until the network is - reset, Surfpool republishes every price account of the Pyth Core Compatible receiver the - Surfnet has loaded every slot, as the Pyth publisher does on mainnet: publish_time becomes the - Surfnet clock's unix seconds and posted_slot the slot, also after a time travel. This includes - feeds no override names and, from the next slot, feeds a transaction loads later, so a - liquidation that reads the borrower's other feeds finds them fresh. Price, conf and the EMA - fields keep their values. With keepAlive: true, a value set for publish_time or posted_slot - never takes effect, so leave both unset. + THE PRICE STAYS PUBLISHED. From the slot this override plays until the network is reset, + Surfpool republishes the price account it writes every slot, as the Pyth publisher does on + mainnet: publish_time becomes the Surfnet clock's unix seconds and posted_slot the slot, also + after a time travel. Price, conf and the EMA fields keep their values, and a value set for + publish_time or posted_slot does not hold. - STALE PRICE: keep-alive starts only when an override with keepAlive: true writes a price - account, and an override with no values writes nothing. To keep one feed stale while the - others stay fresh, add two overrides of this template, both with fetchBeforeUse: true and - price_message.price set to the account's current price (getAccountInfo, encoding - "jsonParsed"), so no price changes: - - on the stale feed's price account, keepAlive: false. It then ages against the Surfnet - clock and turns stale once the consumer's age limit has passed; - - on any other price account the same consumer reads, keepAlive: true. This starts the - republishing of every loaded price account except the stale one. + EVERY FEED A TRANSACTION READS: a price account no override writes is not republished and + ages against the Surfnet clock. A liquidation reads every feed of the borrower, so add one + override of this template per price account the transaction reads, in the same scenario and + slot. On an account whose price must not move, set only price_message.publish_time: any + value works, because keep-alive rewrites it in the same slot. + + STALE PRICE: a price account left without an override ages from the start. To let one age + later, give a later override of it "keepAlive": [] and a value, such as its current price. + From that slot on nothing republishes it, and a publish_time or posted_slot set in that + override holds. EXAMPLE - "SOL drops to $20" on an account with exponent -8, live price p and ema_price q: price_message.price: 2000000000 diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index 97d725dc8..35f8c6ad8 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -11,7 +11,7 @@ tags: keep_alive: - template: pyth-price-publication - address: { type: owned, owner: rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, account: PriceUpdateV2 } + address: { type: override } values: { price_message.publish_time: $unix_s, posted_slot: $slot } constants: @@ -199,7 +199,7 @@ constants: templates: - id: pyth-price-feed-v2 name: Override Price Feed - description: Override any Pyth price feed with custom price data; keeps every loaded Pyth Core price account published + description: Override any Pyth price feed with custom price data; keeps that feed published idl_account_name: PriceUpdateV2 properties: - path: feed_id @@ -217,7 +217,7 @@ templates: description: Decimal exponent, normally -8 and -10 on some feeds. Rescales every price field - path: price_message.publish_time label: Publish Time - description: Unix seconds of this update, interpreted against the Surfnet clock. Keep-alive writes the Clock time every slot, so a value set here holds only with keepAlive false + description: 'Unix seconds of this update, interpreted against the Surfnet clock. Keep-alive writes the Clock time every slot, so a value set here holds only in an override with "keepAlive": []' - path: price_message.prev_publish_time label: Previous Publish Time description: Unix seconds of the preceding update @@ -229,7 +229,7 @@ templates: description: Exponential moving average confidence, in the same scale as conf - path: posted_slot label: Posted Slot - description: Slot the update was posted at, for consumers that measure freshness in slots. Keep-alive writes the current slot every slot, so a value set here holds only with keepAlive false + description: 'Slot the update was posted at, for consumers that measure freshness in slots. Keep-alive writes the current slot every slot, so a value set here holds only in an override with "keepAlive": []' llm_context: | CRITICAL: Always set fetchBeforeUse: true for Pyth price feeds! This fetches the current account data from mainnet before applying your price override. @@ -267,25 +267,22 @@ templates: every scaled field to match. - price_message.ema_price and price_message.ema_conf use the same scales as price and conf. - THE PRICE STAYS PUBLISHED BY ITSELF. From the slot this override plays until the network is - reset, Surfpool republishes every price account of the Pyth Core receiver the Surfnet has - loaded every slot, as the Pyth publisher does on mainnet: publish_time becomes the Surfnet - clock's unix seconds and posted_slot the slot, also after a time travel. This includes feeds - no override names and, from the next slot, feeds a transaction loads later, so a liquidation - that reads the borrower's other feeds finds them fresh. Price, conf and the EMA fields keep - their values. With keepAlive: true, a value set for publish_time or posted_slot never takes - effect, so leave both unset. + THE PRICE STAYS PUBLISHED. From the slot this override plays until the network is reset, + Surfpool republishes the price account it writes every slot, as the Pyth publisher does on + mainnet: publish_time becomes the Surfnet clock's unix seconds and posted_slot the slot, also + after a time travel. Price, conf and the EMA fields keep their values, and a value set for + publish_time or posted_slot does not hold. - STALE PRICE: keep-alive starts only when an override with keepAlive: true writes a price - account, and an override with no values beyond feed_id writes nothing. To keep one feed - stale while the others stay fresh, add two overrides of this template, both with - fetchBeforeUse: true and price_message.price set to the feed's current price - (getAccountInfo, encoding "jsonParsed"), so no price changes: - - on the stale feed, keepAlive: false. It then ages against the Surfnet clock and turns - stale once the consumer's age limit has passed; - - on any other feed the same consumer reads, keepAlive: true. This starts the - republishing of every loaded price account except the stale one. - To make it stale at once, surfnet_timeTravel past the consumer's limit. Its + EVERY FEED A TRANSACTION READS: a price account no override writes is not republished and + ages against the Surfnet clock. A liquidation reads every feed of the borrower, so add one + override of this template per feed the transaction reads, in the same scenario and slot. On + a feed whose price must not move, set only price_message.publish_time: any value works, + because keep-alive rewrites it in the same slot. feed_id alone writes nothing. + + STALE PRICE: a feed left without an override ages from the start. To let a feed age later, + give a later override of it "keepAlive": [] and a value, such as its current price. From + that slot on nothing republishes it, and a publish_time or posted_slot set in that override + holds. To make it stale at once, surfnet_timeTravel past the consumer's limit. Its absoluteTimestamp is in MILLISECONDS, while publish_time and the Clock sysvar are in SECONDS. address: diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index 755085fda..e66548028 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -1702,16 +1702,11 @@ templates: [] #[test] fn pyth_price_feeds_keep_their_price_published() { let registry = TemplateRegistry::new(); - for (id, publication, receiver) in [ - ( - "pyth-price-feed-v2", - "pyth-price-publication", - "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ", - ), + for (id, publication) in [ + ("pyth-price-feed-v2", "pyth-price-publication"), ( "pyth-core-compatible-price-feed-v2", "pyth-core-compatible-price-publication", - "rec2HHDDnjLfj4kE7VyEtFA1HPGQLK33259532cRyHp", ), ] { let template = registry.get(id).unwrap(); @@ -1721,11 +1716,8 @@ templates: [] assert_eq!(import.template, publication, "{id}"); assert_eq!( import.address, - surfpool_types::KeepAliveAddress::Owned { - owners: vec![receiver.to_string()], - account: "PriceUpdateV2".to_string(), - }, - "{id} must keep every price account of its receiver published" + surfpool_types::KeepAliveAddress::Override, + "{id} must keep the price account it writes published" ); let mut paths: Vec<&str> = import.values.keys().map(String::as_str).collect(); paths.sort(); diff --git a/crates/core/src/tests/pyth/mod.rs b/crates/core/src/tests/pyth/mod.rs index fcd52a22c..a8e7ec42d 100644 --- a/crates/core/src/tests/pyth/mod.rs +++ b/crates/core/src/tests/pyth/mod.rs @@ -155,14 +155,16 @@ async fn core_compatible_price_feed_touches_only_price_fields() { } } -/// Once a scenario overrides one price account, keep-alive republishes every price account of its -/// receiver every slot, as the Pyth publisher does on mainnet, time travels included: the -/// overridden one, and one loaded after the override played. Only the publication fields move with -/// the Clock: each price stays as it was. An account overridden with keep-alive off is not -/// republished. +/// Keep-alive republishes each price account an override writes every slot, as the Pyth publisher +/// does on mainnet, time travels included: one whose price moved, and one whose override set only +/// `publish_time`. Only the publication fields move with the Clock: each price stays as the +/// scenario left it. A price account no override writes is never republished, and one whose later +/// override sets `keepAlive: []` is not republished from that slot on. #[tokio::test(flavor = "multi_thread")] -async fn price_feeds_stay_published_through_surfnet_svm() { +async fn each_override_keeps_the_price_account_it_writes_published() { const PRICE: i64 = 2_000_000_000; + const STOP_PRICE: i64 = 1_000_000_000; + const STOP_SLOT: u64 = 2; for (template_id, address, receiver) in [ ("pyth-price-feed-v2", CORE_SOL_USD_FEED, PYTH_CORE_RECEIVER), ( @@ -178,32 +180,43 @@ async fn price_feeds_stay_published_through_surfnet_svm() { live.data[40], 1, "{address} verification level should be Full" ); + let word = + |data: &[u8], offset: usize| <[u8; 8]>::try_from(&data[offset..offset + 8]).unwrap(); + let live_price = i64::from_le_bytes(word(&live.data, 73)); - let target = Pubkey::from_str_const(address); - let stale = Pubkey::new_unique(); - let loaded_later = Pubkey::new_unique(); + let moved = Pubkey::from_str_const(address); + let published = Pubkey::new_unique(); + let unnamed = Pubkey::new_unique(); + let stopped = Pubkey::new_unique(); let (svm, _events_rx, _geyser_rx) = SurfnetSvm::default(); let locker = SurfnetSvmLocker::new(svm); locker.with_svm_writer(|svm| { - svm.set_account(&target, live.clone()).unwrap(); - svm.set_account(&stale, live.clone()).unwrap(); + for address in [moved, published, unnamed, stopped] { + svm.set_account(&address, live.clone()).unwrap(); + } }); - let price_override = |address: &Pubkey| { + let override_of = |address: &Pubkey, slot: u64, path: &str, value: i64| { OverrideInstance::new( template_id.to_string(), - 0, + slot, AccountAddress::Pubkey(address.to_string()), ) .with_values(HashMap::from([( - "price_message.price".to_string(), - serde_json::json!(PRICE), + path.to_string(), + serde_json::json!(value), )])) }; - let mut scenario = Scenario::new("Pyth SOL at $20".to_string(), "Price only".to_string()); - scenario.add_override(price_override(&target)); - let mut stale_override = price_override(&stale); - stale_override.keep_alive = false; - scenario.add_override(stale_override); + let mut scenario = Scenario::new( + "Pyth SOL at $20".to_string(), + "One override per price account".to_string(), + ); + scenario.add_override(override_of(&moved, 0, "price_message.price", PRICE)); + // Any value: keep-alive rewrites it in the same slot. + scenario.add_override(override_of(&published, 0, "price_message.publish_time", 1)); + scenario.add_override(override_of(&stopped, 0, "price_message.price", PRICE)); + let mut stop = override_of(&stopped, STOP_SLOT, "price_message.price", STOP_PRICE); + stop.keep_alive = Some(vec![]); + scenario.add_override(stop); locker.register_scenario(scenario, None).unwrap(); let read = |address: &Pubkey| { @@ -214,18 +227,15 @@ async fn price_feeds_stay_published_through_surfnet_svm() { ) }) }; - let word = - |data: &[u8], offset: usize| <[u8; 8]>::try_from(&data[offset..offset + 8]).unwrap(); - let assert_published = |when: &str, with_loaded_later: bool| { - let mut published = vec![(target, "overridden", PRICE)]; - if with_loaded_later { - published.push(( - loaded_later, - "loaded later", - i64::from_le_bytes(word(&live.data, 73)), - )); + let assert_published = |when: &str, with_stopped: bool| { + let mut kept = vec![ + (moved, "moved", PRICE), + (published, "publish_time only", live_price), + ]; + if with_stopped { + kept.push((stopped, "stopped later", PRICE)); } - for (address, name, price) in published { + for (address, name, price) in kept { let (data, clock) = read(&address); let what = format!("{name} {when}"); assert_eq!( @@ -253,17 +263,20 @@ async fn price_feeds_stay_published_through_surfnet_svm() { "{template_id} {what}: changed {diffs:?}" ); } - let mut unpublished = live.data.clone(); - unpublished[73..81].copy_from_slice(&PRICE.to_le_bytes()); - assert_eq!(read(&stale).0, unpublished, "{template_id} stale {when}"); + assert_eq!(read(&unnamed).0, live.data, "{template_id} unnamed {when}"); }; - locker.confirm_current_block(&None).await.unwrap(); - assert_published("slot 1", false); - locker.with_svm_writer(|svm| svm.set_account(&loaded_later, live.clone()).unwrap()); - for slot in 2..=3 { + for slot in 0..STOP_SLOT { + locker.confirm_current_block(&None).await.unwrap(); + assert_published(&format!("relative slot {slot}"), true); + } + let mut aged = read(&stopped).0; + aged[73..81].copy_from_slice(&STOP_PRICE.to_le_bytes()); + for slot in STOP_SLOT..=STOP_SLOT + 1 { locker.confirm_current_block(&None).await.unwrap(); - assert_published(&format!("slot {slot}"), true); + let when = format!("relative slot {slot}"); + assert_published(&when, false); + assert_eq!(read(&stopped).0, aged, "{template_id} stopped {when}"); } let clock = locker.with_svm_reader(|svm| svm.inner.get_sysvar::()); locker @@ -277,6 +290,11 @@ async fn price_feeds_stay_published_through_surfnet_svm() { ) .await .unwrap(); - assert_published("after a time travel", true); + assert_published("after a time travel", false); + assert_eq!( + read(&stopped).0, + aged, + "{template_id} stopped after a time travel" + ); } } From 1f07b7b9500f51ca27eefbc39467f0f63308aaf5 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 20 Nov 2026 17:14:15 +0200 Subject: [PATCH 22/24] test(scenarios): move the Pyth tests to tests/protocols --- crates/core/src/scenarios/protocols/pyth/README.md | 6 +++--- crates/core/src/tests/mod.rs | 4 ++-- crates/core/src/tests/protocols/mod.rs | 11 +++++++++++ crates/core/src/tests/{ => protocols}/pyth/mod.rs | 2 +- 4 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 crates/core/src/tests/protocols/mod.rs rename crates/core/src/tests/{ => protocols}/pyth/mod.rs (99%) diff --git a/crates/core/src/scenarios/protocols/pyth/README.md b/crates/core/src/scenarios/protocols/pyth/README.md index ca6c4bb61..f7b55a714 100644 --- a/crates/core/src/scenarios/protocols/pyth/README.md +++ b/crates/core/src/scenarios/protocols/pyth/README.md @@ -189,11 +189,11 @@ expects the `constants` block to end right before `templates:`. ## Tests -The Pyth integration tests in `crates/core/src/tests/pyth/` fetch real price accounts from mainnet, -so they need a network connection and are compiled only behind a feature: +The Pyth integration tests in `crates/core/src/tests/protocols/pyth/` fetch real price accounts from +mainnet, so they need a network connection and are compiled only behind a feature: ``` -cargo test -p surfpool-core --features integration-tests pyth +cargo test -p surfpool-core --features integration-tests tests::protocols::pyth ``` Set `SURFPOOL_TEST_RPC_URL` to use a private endpoint if the public one rate-limits. The unit tests diff --git a/crates/core/src/tests/mod.rs b/crates/core/src/tests/mod.rs index bc35c2748..28233e7f3 100644 --- a/crates/core/src/tests/mod.rs +++ b/crates/core/src/tests/mod.rs @@ -6,7 +6,7 @@ pub mod kamino; pub mod phoenix; pub mod plugin; #[cfg(feature = "integration-tests")] -pub mod pump; +pub mod protocols; #[cfg(feature = "integration-tests")] -pub mod pyth; +pub mod pump; pub mod simnet_events; diff --git a/crates/core/src/tests/protocols/mod.rs b/crates/core/src/tests/protocols/mod.rs new file mode 100644 index 000000000..90666f341 --- /dev/null +++ b/crates/core/src/tests/protocols/mod.rs @@ -0,0 +1,11 @@ +//! Tests against live mainnet state, one module per integrated protocol. +//! +//! They need a network, so they are compiled only behind a feature. One filter runs them all: +//! +//! ```text +//! cargo test -p surfpool-core --features integration-tests tests::protocols:: +//! ``` +//! +//! A protocol's module is declared here and nowhere else; the filter above then covers it. + +pub mod pyth; diff --git a/crates/core/src/tests/pyth/mod.rs b/crates/core/src/tests/protocols/pyth/mod.rs similarity index 99% rename from crates/core/src/tests/pyth/mod.rs rename to crates/core/src/tests/protocols/pyth/mod.rs index a8e7ec42d..6d1914327 100644 --- a/crates/core/src/tests/pyth/mod.rs +++ b/crates/core/src/tests/protocols/pyth/mod.rs @@ -4,7 +4,7 @@ //! only behind a feature: //! //! ```text -//! cargo test -p surfpool-core --features integration-tests pyth +//! cargo test -p surfpool-core --features integration-tests tests::protocols::pyth //! ``` //! //! Set `SURFPOOL_TEST_RPC_URL` to use a private endpoint if the public one rate-limits. From a9edc7372d0ab6c85a8ce275fea876513d335b6c Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 4 Dec 2026 15:01:42 +0200 Subject: [PATCH 23/24] ci: remove the Claude pull request review --- .github/workflows/claude-review.yml | 141 ---------------------------- 1 file changed, 141 deletions(-) delete mode 100644 .github/workflows/claude-review.yml diff --git a/.github/workflows/claude-review.yml b/.github/workflows/claude-review.yml deleted file mode 100644 index 844c44d68..000000000 --- a/.github/workflows/claude-review.yml +++ /dev/null @@ -1,141 +0,0 @@ -name: Perform a code review when a pull request is created. -on: - pull_request: - types: [opened, synchronize, reopened, ready_for_review] - -jobs: - claude: - # Skip drafts, and skip fork PRs: on `pull_request` they don't get the - # ANTHROPIC_API_KEY secret, so the review would only fail. - if: >- - !github.event.pull_request.draft && - github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-latest - permissions: - contents: read - outputs: - structured_output: ${{ steps.run_claude.outputs.structured_output }} - steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - with: - # Explicitly check out the PR's merge commit. - ref: refs/pull/${{ github.event.pull_request.number }}/merge - persist-credentials: false - - - name: Pre-fetch base and head refs for the PR - env: - PR_BASE_REF: ${{ github.event.pull_request.base.ref }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - # Pass GitHub expressions through env and quote shell expansions. - git fetch --no-tags origin \ - "$PR_BASE_REF" \ - "+refs/pull/$PR_NUMBER/head" - - # If you want Claude to build and run code, install any dependencies that - # need to be downloaded before the "Run Claude" step, and add the commands - # it may run to --allowedTools below (e.g. "Bash(npm test:*)"). Any tool - # not listed there is denied. - - - name: Run Claude - id: run_claude - uses: anthropics/claude-code-action@86d88e619d8e6caf07b5c3944dd14f441c533718 # v1.0.243 - with: - anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} - # Use this job's read-only token instead of the Claude GitHub App, - # which needs `id-token: write` and would get write access. - github_token: ${{ github.token }} - prompt: | - This is PR #${{ github.event.pull_request.number }} for ${{ github.repository }}. - - Review ONLY the changes introduced by the PR, so consider: - git log --oneline ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} - git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} - - Suggest any improvements, potential bugs, or issues. - Be concise and specific in your feedback. - - Return your review in two parts: - - `summary`: a short Markdown overview of the PR and your overall assessment. - - `comments`: one entry per specific issue, anchored to the line it concerns. - `path` is relative to the repository root. `line` is the line number in - the PR head version of the file (${{ github.event.pull_request.head.sha }}), - and must be a line shown in the diff above. The working tree is the merge - commit, so its line numbers can differ; check them with - `git show ${{ github.event.pull_request.head.sha }}:`. - Put issues that don't belong to a single line in `summary` instead. - - Pull request title and body: - ---- - ${{ github.event.pull_request.title }} - ${{ github.event.pull_request.body }} - claude_args: | - --allowedTools "Read,Grep,Glob,Bash(git log:*),Bash(git diff:*),Bash(git show:*)" - --json-schema '{ - "type": "object", - "properties": { - "summary": { - "type": "string", - "description": "Overall review as Markdown, posted as the review body." - }, - "comments": { - "type": "array", - "description": "Inline comments, each anchored to one line of the PR diff.", - "items": { - "type": "object", - "properties": { - "path": { "type": "string", "description": "File path relative to the repository root." }, - "line": { "type": "integer", "minimum": 1, "description": "Line number in the PR head version of the file. Must be within the diff." }, - "body": { "type": "string", "description": "The comment, as Markdown." } - }, - "required": ["path", "line", "body"] - } - } - }, - "required": ["summary", "comments"] - }' - - post_feedback: - runs-on: ubuntu-latest - needs: claude - if: needs.claude.outputs.structured_output != '' - permissions: - issues: write - pull-requests: write - steps: - - name: Report Claude feedback - uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 - env: - CLAUDE_STRUCTURED_OUTPUT: ${{ needs.claude.outputs.structured_output }} - with: - github-token: ${{ github.token }} - script: | - const { summary = '', comments = [] } = JSON.parse(process.env.CLAUDE_STRUCTURED_OUTPUT); - const pr = context.payload.pull_request; - if (!summary.trim() && comments.length === 0) { - core.info('Claude returned an empty review; nothing to post.'); - return; - } - - try { - await github.rest.pulls.createReview({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: pr.number, - commit_id: pr.head.sha, - event: 'COMMENT', - body: summary.trim() || 'See inline comments.', - comments: comments.map(({ path, line, body }) => ({ path, line, side: 'RIGHT', body })), - }); - } catch (error) { - // GitHub rejects the whole review if any comment points outside the - // diff. Fall back to a single PR comment so no feedback is lost. - core.warning(`Could not post inline review (${error.message}); posting a plain comment instead.`); - const details = comments.map(({ path, line, body }) => `**\`${path}:${line}\`**\n\n${body}`); - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: pr.number, - body: [summary.trim(), ...details].filter(Boolean).join('\n\n---\n\n'), - }); - } From fe43d3bf1cd4f4923baad5118a2557876f134d6f Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Fri, 4 Dec 2026 15:05:31 +0200 Subject: [PATCH 24/24] fix(scenarios): tag the Pyth Core Compatible template clock-sensitive and drop the Project 0 field name --- .../pyth/core-compatible/v2/overrides.yaml | 3 ++- .../scenarios/protocols/pyth/v2/overrides.yaml | 4 ++-- crates/core/src/scenarios/registry.rs | 15 +++++++++------ 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml index 9cb250a53..0b3b99927 100644 --- a/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/core-compatible/v2/overrides.yaml @@ -7,6 +7,7 @@ tags: - oracle - price-feed - defi + - clock-sensitive keep_alive: - template: pyth-core-compatible-price-publication @@ -27,7 +28,7 @@ templates: description: Uncertainty band around the price, in the same scale as price - path: price_message.exponent label: Exponent - description: Decimal exponent, normally -8 and -10 on some feeds. Rescales every price field + description: Decimal exponent, usually -8 (-10 on some feeds). Rescales every price field - path: price_message.publish_time label: Publish Time description: 'Unix seconds of this update, interpreted against the Surfnet clock. Keep-alive writes the Clock time every slot, so a value set here holds only in an override with "keepAlive": []' diff --git a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml index 35f8c6ad8..49bf77223 100644 --- a/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml +++ b/crates/core/src/scenarios/protocols/pyth/v2/overrides.yaml @@ -237,8 +237,8 @@ templates: WHICH RECEIVER: this template writes price accounts of the Pyth Core receiver rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ, which Save and Kamino read. Project 0 reads the Pyth Core Compatible receiver instead: for a Project 0 price use - pyth-core-compatible-price-feed-v2 on the bank's config.oracle_keys.0. When a protocol's own - templates name the price account it reads, follow them. + pyth-core-compatible-price-feed-v2. When a protocol's own templates name the price account it + reads, follow them. HOW TO USE THIS TEMPLATE: 1. Select the correct price feed from the `feed_id` constant options (e.g., SOL/USD, BTC/USD) diff --git a/crates/core/src/scenarios/registry.rs b/crates/core/src/scenarios/registry.rs index 49afd6394..5ff8ec897 100644 --- a/crates/core/src/scenarios/registry.rs +++ b/crates/core/src/scenarios/registry.rs @@ -1738,12 +1738,15 @@ templates: [] !openbook.is_empty(), "the OpenBook v2 templates are registered" ); - for template in std::iter::once("pyth-price-feed-v2").chain( - phoenix - .iter() - .chain(openbook.iter()) - .map(|template| template.id.as_str()), - ) { + for template in ["pyth-price-feed-v2", "pyth-core-compatible-price-feed-v2"] + .into_iter() + .chain( + phoenix + .iter() + .chain(openbook.iter()) + .map(|template| template.id.as_str()), + ) + { assert!( tagged.contains(&template), "{template} must be clock-sensitive"