Skip to content

Commit 01d9447

Browse files
feat(sdk): seed devnets at protocol version 14 and persist the learned version (#4735)
Co-authored-by: Claude Fable 5.1 <[email protected]>
1 parent 6a66ab9 commit 01d9447

6 files changed

Lines changed: 258 additions & 14 deletions

File tree

‎packages/js-evo-sdk/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ Static helpers are also exported:
7777

7878
- `await EvoSDK.setLogLevel(filter)` — configure the underlying Wasm SDK's tracing globally.
7979
- `await EvoSDK.getLatestVersionNumber()` — return the latest Platform protocol version supported by the bundled Wasm SDK.
80+
- `sdk.version()` — the protocol version this SDK currently uses. Unpinned SDKs seed at a per-network floor (13 on mainnet, testnet and local; 14 on devnets) and ratchet upward from verified response metadata. On mainnet and testnet the Wasm SDK persists the learned version in `localStorage` under `dash-sdk.protocol-version.<network>` and seeds the next SDK with it, so the first proved request of a later page load already runs at the network's version. Passing `version` pins the SDK and disables both the ratchet and the persistence.
8081
- `await EvoSDK.maxRankedLimit()` — the hard ceiling on a [ranked / having-range](#ranked-queries) `limit`.
8182
- `await EvoSDK.rankedAverageScale()` — the fixed-point divisor for the `avg` axis of a ranked / having-range result.
8283
- `await EvoSDK.maxPrefixInBranches()` — the hard ceiling on the element count of a branching `in` [prefix pin](#ranked-queries).

‎packages/rs-sdk/src/sdk.rs‎

Lines changed: 127 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,30 @@ pub const DEFAULT_QUORUM_PUBLIC_KEYS_CACHE_SIZE: usize = 100;
5656
/// Per-network *default* seed used only when an unpinned SDK has no explicit
5757
/// initial version.
5858
///
59+
/// Mainnet, testnet and regtest seed at protocol version 13, the lowest version
60+
/// any of those networks still runs. Devnets seed at 14: they are cut from the
61+
/// current development line, and their contracts use index grammar that
62+
/// version 13 cannot deserialize, so a lower seed would fail the very first
63+
/// proved request instead of ratcheting (the ratchet only runs after a proof
64+
/// verifies).
65+
///
5966
/// Not a runtime clamp: [`SdkBuilder::with_initial_version`] can seed an unpinned
6067
/// SDK *below* this value (no construction-time floor), and auto-detect
6168
/// ([`Sdk::maybe_update_protocol_version`]) only ratchets the stored version
6269
/// *upward* via `fetch_max` when the network reports a newer one.
63-
const fn min_protocol_version(network: Network) -> u32 {
70+
pub const fn min_protocol_version(network: Network) -> u32 {
6471
match network {
65-
Network::Mainnet => dpp::version::v11::PROTOCOL_VERSION_11,
66-
Network::Testnet => dpp::version::v12::PROTOCOL_VERSION_12,
67-
Network::Devnet => dpp::version::v12::PROTOCOL_VERSION_12,
68-
Network::Regtest => dpp::version::v12::PROTOCOL_VERSION_12,
72+
Network::Mainnet => dpp::version::v13::PROTOCOL_VERSION_13,
73+
Network::Testnet => dpp::version::v13::PROTOCOL_VERSION_13,
74+
Network::Devnet => dpp::version::v14::PROTOCOL_VERSION_14,
75+
Network::Regtest => dpp::version::v13::PROTOCOL_VERSION_13,
6976
}
7077
}
7178

79+
/// Called with the new protocol version each time auto-detect ratchets it
80+
/// upward. See [`SdkBuilder::with_protocol_version_observer`].
81+
pub type ProtocolVersionObserver = Arc<dyn Fn(u32) + Send + Sync>;
82+
7283
/// Default signed-metadata freshness window for network SDKs.
7384
const DEFAULT_METADATA_TIME_TOLERANCE_MS: u64 = 31 * 60 * 1000;
7485

@@ -222,6 +233,10 @@ pub struct Sdk {
222233
/// [`SdkBuilder::with_version()`].
223234
version_pinned: bool,
224235

236+
/// Notified each time auto-detect ratchets the protocol version upward, so a
237+
/// host can persist the learned version and seed the next SDK with it.
238+
protocol_version_observer: Option<ProtocolVersionObserver>,
239+
225240
/// Last seen height; used to determine if the remote node is stale.
226241
///
227242
/// This is clone-able and can be shared between threads.
@@ -257,6 +272,7 @@ impl Clone for Sdk {
257272
cancel_token: self.cancel_token.clone(),
258273
protocol_version: Arc::clone(&self.protocol_version),
259274
version_pinned: self.version_pinned,
275+
protocol_version_observer: self.protocol_version_observer.clone(),
260276
metadata_last_seen_height: Arc::clone(&self.metadata_last_seen_height),
261277
metadata_height_tolerance: self.metadata_height_tolerance,
262278
metadata_time_tolerance_ms: self.metadata_time_tolerance_ms,
@@ -413,6 +429,9 @@ impl Sdk {
413429
to = received_version,
414430
"ratcheting protocol version upward"
415431
);
432+
if let Some(observer) = &self.protocol_version_observer {
433+
observer(received_version);
434+
}
416435
}
417436
}
418437

@@ -811,6 +830,9 @@ pub struct SdkBuilder {
811830
/// metadata is disabled.
812831
version_pinned: bool,
813832

833+
/// See [`SdkBuilder::with_protocol_version_observer`].
834+
protocol_version_observer: Option<ProtocolVersionObserver>,
835+
814836
/// Cache size for data contracts. Used by mock [GrpcContextProvider].
815837
#[cfg(feature = "mocks")]
816838
data_contract_cache_size: NonZeroUsize,
@@ -891,6 +913,7 @@ impl Default for SdkBuilder {
891913
// sets one.
892914
version: None,
893915
version_pinned: false,
916+
protocol_version_observer: None,
894917
#[cfg(not(target_arch = "wasm32"))]
895918
ca_certificate: None,
896919

@@ -1045,6 +1068,20 @@ impl SdkBuilder {
10451068
self
10461069
}
10471070

1071+
/// Observe upward protocol-version ratchets.
1072+
///
1073+
/// Auto-detect learns the network's protocol version from verified response
1074+
/// metadata and keeps it in the SDK instance only. A host that wants the next
1075+
/// instance to start where this one ended (so its first proved request already
1076+
/// uses the right version) persists the value from here and seeds it back with
1077+
/// [`SdkBuilder::with_initial_version`]. Called after the stored version has
1078+
/// moved, once per upward step, with the new version; never for equal, lower,
1079+
/// zero or unknown versions, and never on a pinned SDK.
1080+
pub fn with_protocol_version_observer(mut self, observer: ProtocolVersionObserver) -> Self {
1081+
self.protocol_version_observer = Some(observer);
1082+
self
1083+
}
1084+
10481085
/// Configure context provider to use.
10491086
///
10501087
/// Context provider is used to retrieve data contracts and quorum public keys from application state.
@@ -1209,6 +1246,7 @@ impl SdkBuilder {
12091246
// pinned is controlled separately by `version_pinned`.
12101247
protocol_version: Arc::new(atomic::AtomicU32::new(initial_version.protocol_version)),
12111248
version_pinned: self.version_pinned,
1249+
protocol_version_observer: self.protocol_version_observer.clone(),
12121250
metadata_last_seen_height: Arc::new(atomic::AtomicU64::new(
12131251
self.trusted_initial_height.unwrap_or(0),
12141252
)),
@@ -1278,6 +1316,7 @@ impl SdkBuilder {
12781316
nonce_cache: Default::default(),
12791317
protocol_version: Arc::new(atomic::AtomicU32::new(initial_version.protocol_version)),
12801318
version_pinned: self.version_pinned,
1319+
protocol_version_observer: self.protocol_version_observer.clone(),
12811320
context_provider: ArcSwapOption::new(Some(Arc::new(context_provider))),
12821321
cancel_token: self.cancel_token,
12831322
metadata_last_seen_height: Arc::new(atomic::AtomicU64::new(
@@ -1935,9 +1974,9 @@ mod test {
19351974
assert_eq!(sdk.protocol_version_number(), pinned.protocol_version);
19361975
assert!(sdk.version_pinned);
19371976

1938-
// Network reports version 12 (> pinned) — should be ignored because version is pinned
1977+
// Network reports version 14 (> pinned) — should be ignored because version is pinned
19391978
let metadata = ResponseMetadata {
1940-
protocol_version: dpp::version::v12::PROTOCOL_VERSION_12,
1979+
protocol_version: dpp::version::v14::PROTOCOL_VERSION_14,
19411980
height: 1,
19421981
..Default::default()
19431982
};
@@ -1988,7 +2027,7 @@ mod test {
19882027
assert_eq!(sdk.protocol_version_number(), floor);
19892028

19902029
// And a newer network version still ratchets upward.
1991-
let newer = dpp::version::v12::PROTOCOL_VERSION_12;
2030+
let newer = dpp::version::v14::PROTOCOL_VERSION_14;
19922031
assert!(newer > floor, "ratchet target must exceed the floor");
19932032
let metadata = ResponseMetadata {
19942033
protocol_version: newer,
@@ -2124,12 +2163,12 @@ mod test {
21242163
let floor = min_protocol_version(Network::Mainnet);
21252164
assert_eq!(sdk.protocol_version_number(), floor);
21262165

2127-
// Ratchet to a fixed known target (PV12), not `floor + N`: stays valid as the
2166+
// Ratchet to a fixed known target (PV14), not `floor + N`: stays valid as the
21282167
// floor advances, and `maybe_update_protocol_version` only accepts known versions.
2129-
let target = dpp::version::v12::PROTOCOL_VERSION_12;
2168+
let target = dpp::version::v14::PROTOCOL_VERSION_14;
21302169
assert!(
21312170
target > floor,
2132-
"ratchet test target must exceed the floor; bump it if the floor reaches v12"
2171+
"ratchet test target must exceed the floor; bump it if the floor reaches v14"
21332172
);
21342173
sdk.maybe_update_protocol_version(target);
21352174
assert_eq!(
@@ -2240,6 +2279,83 @@ mod test {
22402279
assert!(!sdk.version_pinned);
22412280
}
22422281

2282+
/// Devnets are cut from the current development line and their contracts use
2283+
/// index grammar older versions cannot deserialize, so the devnet floor is the
2284+
/// current version while the public networks keep the lowest version they run.
2285+
#[test]
2286+
fn test_per_network_floors() {
2287+
assert_eq!(
2288+
min_protocol_version(Network::Devnet),
2289+
dpp::version::v14::PROTOCOL_VERSION_14,
2290+
"devnet floor must be the current development version"
2291+
);
2292+
for network in [Network::Mainnet, Network::Testnet, Network::Regtest] {
2293+
assert_eq!(
2294+
min_protocol_version(network),
2295+
dpp::version::v13::PROTOCOL_VERSION_13,
2296+
"{network} floor must be the lowest version the network runs"
2297+
);
2298+
}
2299+
let sdk = SdkBuilder::new_mock()
2300+
.with_network(Network::Devnet)
2301+
.build()
2302+
.expect("mock Sdk should be created");
2303+
assert_eq!(
2304+
sdk.protocol_version_number(),
2305+
min_protocol_version(Network::Devnet)
2306+
);
2307+
assert!(!sdk.version_pinned);
2308+
}
2309+
2310+
/// The observer fires once per upward ratchet with the new version, and stays
2311+
/// silent for the inputs the ratchet rejects (equal, lower, zero, unknown).
2312+
#[test]
2313+
fn test_protocol_version_observer_fires_only_on_upward_ratchet() {
2314+
use dpp::version::PlatformVersion;
2315+
use std::sync::Mutex;
2316+
let seen: Arc<Mutex<Vec<u32>>> = Arc::new(Mutex::new(Vec::new()));
2317+
let observer = {
2318+
let seen = Arc::clone(&seen);
2319+
Arc::new(move |version: u32| {
2320+
seen.lock().expect("observer log lock").push(version);
2321+
})
2322+
};
2323+
let sdk = SdkBuilder::new_mock()
2324+
.with_protocol_version_observer(observer)
2325+
.build()
2326+
.expect("mock Sdk should be created");
2327+
let floor = min_protocol_version(Network::Mainnet);
2328+
let target = dpp::version::v14::PROTOCOL_VERSION_14;
2329+
assert!(target > floor, "ratchet target must exceed the floor");
2330+
2331+
sdk.maybe_update_protocol_version(floor);
2332+
sdk.maybe_update_protocol_version(floor - 1);
2333+
sdk.maybe_update_protocol_version(0);
2334+
sdk.maybe_update_protocol_version(dpp::version::LATEST_VERSION + 1);
2335+
assert!(
2336+
seen.lock().expect("observer log lock").is_empty(),
2337+
"rejected inputs must not notify the observer"
2338+
);
2339+
2340+
sdk.maybe_update_protocol_version(target);
2341+
sdk.maybe_update_protocol_version(target);
2342+
assert_eq!(
2343+
*seen.lock().expect("observer log lock"),
2344+
vec![target],
2345+
"one upward step must notify exactly once"
2346+
);
2347+
2348+
// Clones share the observer, and a pinned SDK never ratchets.
2349+
let clone = sdk.clone();
2350+
assert!(clone.protocol_version_observer.is_some());
2351+
let pinned = SdkBuilder::new_mock()
2352+
.with_version(PlatformVersion::get(floor).expect("floor PV exists"))
2353+
.with_protocol_version_observer(Arc::new(|_| panic!("pinned SDK must not ratchet")))
2354+
.build()
2355+
.expect("mock Sdk should be created");
2356+
pinned.maybe_update_protocol_version(target);
2357+
}
2358+
22432359
#[test_matrix([90,91,100,109,110], 100, 10, false; "valid time")]
22442360
#[test_matrix([0,89,111], 100, 10, true; "invalid time")]
22452361
#[test_matrix([0,100], [0,100], 100, false; "zero time")]

‎packages/rs-sdk/tests/fetch/document_query_v0_v1.rs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,11 @@ use std::sync::Arc;
2727
use super::common::{mock_data_contract, mock_document_type};
2828
use dapi_grpc::platform::v0::get_documents_request::Version as ReqVersion;
2929
use dapi_grpc::platform::v0::GetDocumentsRequest;
30+
use dash_sdk::sdk::min_protocol_version;
3031
use dash_sdk::{platform::documents::document_query::DocumentQuery, Error as SdkError, SdkBuilder};
32+
use dpp::dashcore::Network;
3133
use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters;
3234
use dpp::platform_value::Value;
33-
use dpp::version::v11::PROTOCOL_VERSION_11;
3435
use dpp::version::{PlatformVersion, INITIAL_PROTOCOL_VERSION};
3536
use drive::query::conditions::{WhereClause, WhereOperator};
3637
use drive::query::ordering::OrderClause;
@@ -298,8 +299,10 @@ fn sdk_builder_default_seeds_atomic_to_floor() {
298299
// Auto-detect default: the atomic seeds to the effective floor,
299300
// max(INITIAL_PROTOCOL_VERSION, mainnet network floor), which
300301
// `version()` returns until the first response ratchets it upward.
302+
// Read the floor from the SDK rather than repeating the number here, so
303+
// the test follows `min_protocol_version` when the networks move on.
301304
let sdk_default = SdkBuilder::new_mock().build().expect("mock sdk");
302-
let expected_floor = INITIAL_PROTOCOL_VERSION.max(PROTOCOL_VERSION_11);
305+
let expected_floor = INITIAL_PROTOCOL_VERSION.max(min_protocol_version(Network::Mainnet));
303306
assert_eq!(sdk_default.version().protocol_version, expected_floor);
304307
}
305308

‎packages/wasm-sdk/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub mod context_provider;
44
pub mod dpns;
55
pub mod error;
66
pub mod logging;
7+
mod protocol_version_store;
78
pub mod queries;
89
pub mod sdk;
910
pub mod serialization;
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
//! Persist the protocol version auto-detect learns, per network, so the next
2+
//! SDK instance seeds at it instead of at the per-network floor.
3+
//!
4+
//! rs-sdk keeps the detected version in the instance only: every page load
5+
//! starts at the floor and ratchets up once a proof verifies. A first request
6+
//! that only parses at the network's real version (a contract using newer
7+
//! index grammar, say) fails at the floor instead of ratcheting. Writing the
8+
//! learned version to `localStorage` under `dash-sdk.protocol-version.<network>`
9+
//! and seeding it back through `SdkBuilder::with_initial_version` removes that
10+
//! first-request gap for mainnet and testnet. Devnets are re-cut from the
11+
//! development line and already seed at the current version; regtest is local.
12+
//! Both are left alone.
13+
//!
14+
//! The seed keeps auto-detect on, so a network that has moved further still
15+
//! ratchets the SDK (and this store) upward. A version this build does not
16+
//! know is ignored, as is a value at or below the floor.
17+
18+
use dash_sdk::dpp::dashcore::Network;
19+
use dash_sdk::dpp::version::PlatformVersion;
20+
use dash_sdk::sdk::min_protocol_version;
21+
use js_sys::{Array, Function, Reflect};
22+
use wasm_bindgen::{JsCast, JsValue};
23+
24+
const KEY_PREFIX: &str = "dash-sdk.protocol-version.";
25+
26+
/// The storage key for a network, or `None` for networks that are not persisted.
27+
pub(crate) fn storage_key(network: Network) -> Option<String> {
28+
match network {
29+
Network::Mainnet => Some(format!("{KEY_PREFIX}mainnet")),
30+
Network::Testnet => Some(format!("{KEY_PREFIX}testnet")),
31+
Network::Devnet | Network::Regtest => None,
32+
}
33+
}
34+
35+
/// The persisted version for `network`, when one is stored, this build knows it,
36+
/// and it lies above the network's floor (a seed at or below the floor is a no-op).
37+
pub(crate) fn load(network: Network) -> Option<&'static PlatformVersion> {
38+
let key = storage_key(network)?;
39+
let storage = local_storage()?;
40+
let raw = call_method(&storage, "getItem", &[JsValue::from_str(&key)])?.as_string()?;
41+
let version = raw.trim().parse::<u32>().ok()?;
42+
if version <= min_protocol_version(network) {
43+
return None;
44+
}
45+
PlatformVersion::get(version).ok()
46+
}
47+
48+
/// Persist `version` for `network`. Silent when the network is not persisted or
49+
/// no `localStorage` is reachable (workers, Node, blocked site data).
50+
pub(crate) fn store(network: Network, version: u32) {
51+
let Some(key) = storage_key(network) else {
52+
return;
53+
};
54+
let Some(storage) = local_storage() else {
55+
return;
56+
};
57+
call_method(
58+
&storage,
59+
"setItem",
60+
&[
61+
JsValue::from_str(&key),
62+
JsValue::from_str(&version.to_string()),
63+
],
64+
);
65+
}
66+
67+
/// `globalThis.localStorage`, when the host has one. Reached through `Reflect`
68+
/// so a missing binding (a worker, Node) is a `None`, not a link error, and a
69+
/// throwing accessor (blocked site data) is swallowed.
70+
fn local_storage() -> Option<JsValue> {
71+
let storage = Reflect::get(&js_sys::global(), &JsValue::from_str("localStorage")).ok()?;
72+
if storage.is_undefined() || storage.is_null() {
73+
return None;
74+
}
75+
Some(storage)
76+
}
77+
78+
fn call_method(target: &JsValue, name: &str, args: &[JsValue]) -> Option<JsValue> {
79+
let method = Reflect::get(target, &JsValue::from_str(name))
80+
.ok()?
81+
.dyn_into::<Function>()
82+
.ok()?;
83+
let arguments = Array::new();
84+
for arg in args {
85+
arguments.push(arg);
86+
}
87+
Reflect::apply(&method, target, &arguments).ok()
88+
}

0 commit comments

Comments
 (0)