Skip to main content

sui_protocol_config/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{BTreeMap, BTreeSet},
6    sync::{
7        Arc, LazyLock,
8        atomic::{AtomicBool, Ordering},
9    },
10};
11
12use std::sync::Mutex;
13
14use clap::*;
15use fastcrypto::encoding::{Base58, Encoding, Hex};
16use move_binary_format::{
17    binary_config::{BinaryConfig, TableConfig},
18    file_format_common::VERSION_1,
19};
20use move_core_types::account_address::AccountAddress;
21use move_vm_config::verifier::VerifierConfig;
22use mysten_common::in_integration_test;
23use serde::{Deserialize, Serialize};
24use serde_with::skip_serializing_none;
25use sui_protocol_config_macros::{
26    ProtocolConfigAccessors, ProtocolConfigFeatureFlagsGetters, ProtocolConfigOverride,
27};
28use tracing::{info, warn};
29
30pub mod reachability;
31
32// Re-exported so that `assert_reachable_gated!` expands without requiring callers to depend on
33// the antithesis sdk or mysten-common directly.
34#[doc(hidden)]
35pub use antithesis_sdk::linkme;
36#[doc(hidden)]
37pub use mysten_common::assert_reachable_simtest;
38
39/// The minimum and maximum protocol versions supported by this build.
40const MIN_PROTOCOL_VERSION: u64 = 1;
41const MAX_PROTOCOL_VERSION: u64 = 137;
42
43const TESTNET_USDC: &str =
44    "0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29::usdc::USDC";
45
46const MAINNET_USDC: &str =
47    "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
48const MAINNET_USDSUI: &str =
49    "0x44f838219cf67b058f3b37907b655f226153c18e33dfcd0da559a844fea9b1c1::usdsui::USDSUI";
50const MAINNET_SUI_USDE: &str =
51    "0x41d587e5336f1c86cad50d38a7136db99333bb9bda91cea4ba69115defeb1402::sui_usde::SUI_USDE";
52const MAINNET_USDY: &str =
53    "0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY";
54const MAINNET_FDUSD: &str =
55    "0xf16e6b723f242ec745dfd7634ad072c42d5c1d9ac9d62a39c381303eaa57693a::fdusd::FDUSD";
56const MAINNET_AUSD: &str =
57    "0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD";
58const MAINNET_USDB: &str =
59    "0xe14726c336e81b32328e92afc37345d159f5b550b09fa92bd43640cfdd0a0cfd::usdb::USDB";
60
61// Record history of protocol version allocations here:
62//
63// Version 1: Original version.
64// Version 2: Framework changes, including advancing epoch_start_time in safemode.
65// Version 3: gas model v2, including all sui conservation fixes. Fix for loaded child object
66//            changes, enable package upgrades, add limits on `max_size_written_objects`,
67//            `max_size_written_objects_system_tx`
68// Version 4: New reward slashing rate. Framework changes to skip stake susbidy when the epoch
69//            length is short.
70// Version 5: Package upgrade compatibility error fix. New gas cost table. New scoring decision
71//            mechanism that includes up to f scoring authorities.
72// Version 6: Change to how bytes are charged in the gas meter, increase buffer stake to 0.5f
73// Version 7: Disallow adding new abilities to types during package upgrades,
74//            disable_invariant_violation_check_in_swap_loc,
75//            disable init functions becoming entry,
76//            hash module bytes individually before computing package digest.
77// Version 8: Disallow changing abilities and type constraints for type parameters in structs
78//            during upgrades.
79// Version 9: Limit the length of Move idenfitiers to 128.
80//            Disallow extraneous module bytes,
81//            advance_to_highest_supported_protocol_version,
82// Version 10:increase bytecode verifier `max_verifier_meter_ticks_per_function` and
83//            `max_meter_ticks_per_module` limits each from 6_000_000 to 16_000_000. sui-system
84//            framework changes.
85// Version 11: Introduce `std::type_name::get_with_original_ids` to the system frameworks. Bound max depth of values within the VM.
86// Version 12: Changes to deepbook in framework to add API for querying marketplace.
87//             Change NW Batch to use versioned metadata field.
88//             Changes to sui-system package to add PTB-friendly unstake function, and minor cleanup.
89// Version 13: System package change deprecating `0xdee9::clob` and `0xdee9::custodian`, replaced by
90//             `0xdee9::clob_v2` and `0xdee9::custodian_v2`.
91// Version 14: Introduce a config variable to allow charging of computation to be either
92//             bucket base or rounding up. The presence of `gas_rounding_step` (or `None`)
93//             decides whether rounding is applied or not.
94// Version 15: Add reordering of user transactions by gas price after consensus.
95//             Add `sui::table_vec::drop` to the framework via a system package upgrade.
96// Version 16: Enabled simplified_unwrap_then_delete feature flag, which allows the execution engine
97//             to no longer consult the object store when generating unwrapped_then_deleted in the
98//             effects; this also allows us to stop including wrapped tombstones in accumulator.
99//             Add self-matching prevention for deepbook.
100// Version 17: Enable upgraded multisig support.
101// Version 18: Introduce execution layer versioning, preserve all existing behaviour in v0.
102//             Gas minimum charges moved to be a multiplier over the reference gas price. In this
103//             protocol version the multiplier is the same as the lowest bucket of computation
104//             such that the minimum transaction cost is the same as the minimum computation
105//             bucket.
106//             Add a feature flag to indicate the changes semantics of `base_tx_cost_fixed`.
107// Version 19: Changes to sui-system package to enable liquid staking.
108//             Add limit for total size of events.
109//             Increase limit for number of events emitted to 1024.
110// Version 20: Enables the flag `narwhal_new_leader_election_schedule` for the new narwhal leader
111//             schedule algorithm for enhanced fault tolerance and sets the bad node stake threshold
112//             value. Both values are set for all the environments except mainnet.
113// Version 21: ZKLogin known providers.
114// Version 22: Child object format change.
115// Version 23: Enabling the flag `narwhal_new_leader_election_schedule` for the new narwhal leader
116//             schedule algorithm for enhanced fault tolerance and sets the bad node stake threshold
117//             value for mainnet.
118// Version 24: Re-enable simple gas conservation checks.
119//             Package publish/upgrade number in a single transaction limited.
120//             JWK / authenticator state flags.
121// Version 25: Add sui::table_vec::swap and sui::table_vec::swap_remove to system packages.
122// Version 26: New gas model version.
123//             Add support for receiving objects off of other objects in devnet only.
124// Version 28: Add sui::zklogin::verify_zklogin_id and related functions to sui framework.
125//             Enable transaction effects v2 in devnet.
126// Version 29: Add verify_legacy_zklogin_address flag to sui framework, this add ability to verify
127//             transactions from a legacy zklogin address.
128// Version 30: Enable Narwhal CertificateV2
129//             Add support for random beacon.
130//             Enable transaction effects v2 in testnet.
131//             Deprecate supported oauth providers from protocol config and rely on node config
132//             instead.
133//             In execution, has_public_transfer is recomputed when loading the object.
134//             Add support for shared obj deletion and receiving objects off of other objects in devnet only.
135// Version 31: Add support for shared object deletion in devnet only.
136//             Add support for getting object ID referenced by receiving object in sui framework.
137//             Create new execution layer version, and preserve previous behavior in v1.
138//             Update semantics of `sui::transfer::receive` and add `sui::transfer::public_receive`.
139// Version 32: Add delete functions for VerifiedID and VerifiedIssuer.
140//             Add sui::token module to sui framework.
141//             Enable transfer to object in testnet.
142//             Enable Narwhal CertificateV2 on mainnet
143//             Make critbit tree and order getters public in deepbook.
144// Version 33: Add support for `receiving_object_id` function in framework
145//             Hardened OTW check.
146//             Enable transfer-to-object in mainnet.
147//             Enable shared object deletion in testnet.
148//             Enable effects v2 in mainnet.
149// Version 34: Framework changes for random beacon.
150// Version 35: Add poseidon hash function.
151//             Enable coin deny list.
152// Version 36: Enable group operations native functions in devnet.
153//             Enable shared object deletion in mainnet.
154//             Set the consensus accepted transaction size and the included transactions size in the proposed block.
155// Version 37: Reject entry functions with mutable Random.
156// Version 38: Introduce limits for binary tables size.
157// Version 39: Allow skipped epochs for randomness updates.
158//             Extra version to fix `test_upgrade_compatibility` simtest.
159// Version 40:
160// Version 41: Enable group operations native functions in testnet and mainnet (without msm).
161// Version 42: Migrate sui framework and related code to Move 2024
162// Version 43: Introduce the upper bound delta config for a zklogin signature's max epoch.
163//             Introduce an explicit parameter for the tick limit per package (previously this was
164//             represented by the parameter for the tick limit per module).
165// Version 44: Enable consensus fork detection on mainnet.
166//             Switch between Narwhal and Mysticeti consensus in tests, devnet and testnet.
167// Version 45: Use tonic networking for Mysticeti consensus.
168//             Set min Move binary format version to 6.
169//             Enable transactions to be signed with zkLogin inside multisig signature.
170//             Add native bridge.
171//             Enable native bridge in devnet
172//             Enable Leader Scoring & Schedule Change for Mysticeti consensus on testnet.
173// Version 46: Enable native bridge in testnet
174//             Enable resharing at the same initial shared version.
175// Version 47: Deepbook changes (framework update)
176// Version 48: Use tonic networking for Mysticeti.
177//             Resolve Move abort locations to the package id instead of the runtime module ID.
178//             Enable random beacon in testnet.
179//             Use new VM when verifying framework packages.
180// Version 49: Enable Move enums on devnet.
181//             Enable VDF in devnet
182//             Enable consensus commit prologue V3 in devnet.
183//             Run Mysticeti consensus by default.
184// Version 50: Add update_node_url to native bridge,
185//             New Move stdlib integer modules
186//             Enable checkpoint batching in testnet.
187//             Prepose consensus commit prologue in checkpoints.
188//             Set number of leaders per round for Mysticeti commits.
189// Version 51: Switch to DKG V1.
190//             Enable deny list v2 on devnet.
191// Version 52: Emit `CommitteeMemberUrlUpdateEvent` when updating bridge node url.
192//             std::config native functions.
193//             Modified sui-system package to enable withdrawal of stake before it becomes active.
194//             Enable soft bundle in devnet and testnet.
195//             Core macro visibility in sui core framework.
196//             Enable checkpoint batching in mainnet.
197//             Enable Mysticeti on mainnet.
198//             Enable Leader Scoring & Schedule Change for Mysticeti consensus on mainnet.
199//             Turn on count based shared object congestion control in devnet.
200//             Enable consensus commit prologue V3 in testnet.
201//             Enable enums on testnet.
202//             Add support for passkey in devnet.
203//             Enable deny list v2 on testnet and mainnet.
204// Version 53: Add feature flag to decide whether to attempt to finalize bridge committee
205//             Enable consensus commit prologue V3 on testnet.
206//             Turn on shared object congestion control in testnet.
207//             Update stdlib natives costs
208// Version 54: Enable random beacon on mainnet.
209//             Enable soft bundle on mainnet.
210// Version 55: Enable enums on mainnet.
211//             Rethrow serialization type layout errors instead of converting them.
212// Version 56: Enable bridge on mainnet.
213//             Note: do not use version 56 for any new features.
214// Version 57: Reduce minimum number of random beacon shares.
215// Version 58: Optimize boolean binops
216//             Finalize bridge committee on mainnet.
217//             Switch to distributed vote scoring in consensus in devnet
218// Version 59: Enable round prober in consensus.
219// Version 60: Validation of public inputs for Groth16 verification.
220//             Enable configuration of maximum number of type nodes in a type layout.
221// Version 61: Switch to distributed vote scoring in consensus in testnet
222//             Further reduce minimum number of random beacon shares.
223//             Add feature flag for Mysticeti fastpath.
224// Version 62: Makes the event's sending module package upgrade-aware.
225// Version 63: Enable gas based congestion control in consensus commit.
226// Version 64: Revert congestion control change.
227// Version 65: Enable distributed vote scoring in mainnet.
228// Version 66: Revert distributed vote scoring in mainnet.
229//             Framework fix for fungible staking book-keeping.
230// Version 67: Re-enable distributed vote scoring in mainnet.
231// Version 68: Add G1Uncompressed group to group ops.
232//             Update to Move stdlib.
233//             Enable gas based congestion control with overage.
234//             Further reduce minimum number of random beacon shares.
235//             Disallow adding new modules in `deps-only` packages.
236// Version 69: Sets number of rounds allowed for fastpath voting in consensus.
237//             Enable smart ancestor selection in devnet.
238//             Enable G1Uncompressed group in testnet.
239// Version 70: Enable smart ancestor selection in testnet.
240//             Enable probing for accepted rounds in round prober in testnet
241//             Add new gas model version to update charging of native functions.
242//             Add std::uq64_64 module to Move stdlib.
243//             Improve gas/wall time efficiency of some Move stdlib vector functions
244// Version 71: [SIP-45] Enable consensus amplification.
245// Version 72: Fix issue where `convert_type_argument_error` wasn't being used in all cases.
246//             Max gas budget moved to 50_000 SUI
247//             Max gas price moved to 50 SUI
248//             Variants as type nodes.
249// Version 73: Enable new marker table version.
250//             Enable consensus garbage collection and new commit rule for devnet.
251//             Enable zstd compression for consensus tonic network in testnet.
252//             Enable smart ancestor selection in mainnet.
253//             Enable probing for accepted rounds in round prober in mainnet
254// Version 74: Enable load_nitro_attestation move function in sui framework in devnet.
255//             Enable all gas costs for load_nitro_attestation.
256//             Enable zstd compression for consensus tonic network in mainnet.
257//             Enable the new commit rule for devnet.
258// Version 75: Enable passkey auth in testnet.
259// Version 76: Deprecate Deepbook V2 order placement and deposit.
260//             Removes unnecessary child object mutations
261//             Enable passkey auth in multisig for testnet.
262// Version 77: Enable uncompressed point group ops on mainnet.
263//             Enable consensus garbage collection for testnet
264//             Enable the new consensus commit rule for testnet.
265// Version 78: Make `TxContext` Move API native
266//             Enable execution time estimate mode for congestion control on testnet.
267// Version 79: Enable median based commit timestamp in consensus on testnet.
268//             Increase threshold for bad nodes that won't be considered leaders in consensus in testnet
269//             Enable load_nitro_attestation move function in sui framework in testnet.
270//             Enable consensus garbage collection for mainnet
271//             Enable the new consensus commit rule for mainnet.
272// Version 80: Bound size of values created in the adapter.
273// Version 81: Enable median based commit timestamp in consensus on mainnet.
274//             Enforce checkpoint timestamps are non-decreasing for testnet and mainnet.
275//             Increase threshold for bad nodes that won't be considered leaders in consensus in mainnet
276// Version 82: Relax bounding of size of values created in the adapter.
277// Version 83: Resolve `TypeInput` IDs to defining ID when converting to `TypeTag`s in the adapter.
278//             Enable execution time estimate mode for congestion control on mainnet.
279//             Enable nitro attestation upgraded parsing and mainnet.
280// Version 84: Limit number of stored execution time observations between epochs.
281// Version 85: Enable party transfer in devnet.
282// Version 86: Use type tags in the object runtime and adapter instead of `Type`s.
283//             Make variant count limit explicit in protocol config.
284//             Enable party transfer in testnet.
285// Version 87: Enable better type resolution errors in the adapter.
286// Version 88: Update `sui-system` package to use `calculate_rewards` function.
287//             Define the cost for the native Move function `rgp`.
288//             Ignore execution time observations after validator stops accepting certs.
289// Version 89: Add additional signature checks
290//             Add additional linkage checks
291// Version 90: Standard library improvements.
292//             Enable `debug_fatal` on Move invariant violations.
293//             Enable passkey and passkey inside multisig for mainnet.
294// Version 91: Minor changes in Sui Framework. Include CheckpointDigest in consensus dedup key for checkpoint signatures (V2).
295// Version 92: Disable checking shared object transfer restrictions per command = false
296// Version 93: Enable CheckpointDigest in consensus dedup key for checkpoint signatures.
297// Version 94: Decrease stored observations limit by 10% to stay within system object size limit.
298//             Enable party transfer on mainnet.
299// Version 95: Change type name id base cost to 52, increase max transactions per checkpoint to 20000.
300// Version 96: Enable authority capabilities v2.
301//             Fix bug where MFP transaction shared inputs' debts were not loaded
302//             Create Coin Registry object
303//             Enable checkpoint artifacts digest in devnet.
304// Version 97: Enable additional borrow checks
305// Version 98: Add authenticated event streams support via emit_authenticated function.
306//             Add better error messages to the loader.
307// Version 99: Enable new commit handler.
308// Version 100: Framework update
309// Version 101: Framework update
310//              Set max updates per settlement txn to 100.
311// Version 103: Framework update: internal Coin methods
312// Version 104: Framework update: CoinRegistry follow up for Coin methods
313//              Enable all non-zero PCRs parsing for nitro attestation native function in Devnet and Testnet.
314// Version 105: Framework update: address aliases
315//              Enable multi-epoch transaction expiration.
316//              Enable always include required PCRs (0-4 & 8) parsing even if they are zeros for
317//              nitro attestation native function in Devnet and Testnet.
318// Version 106: Framework update: accumulator storage fund calculations
319//              Enable address balances on devnet
320// Version 108: Enable new digit based gas rounding.
321//              Support TxContext in all parameter positions.
322//              Disable entry point signature check.
323//              Enable address aliases on testnet.
324//              Enable poseidon_bn254 on mainnet.
325// Version 109: Update where we set bounds for some binary tables to be a bit more idiomatic.
326// Version 110: Enable parsing on all nonzero custom pcrs in nitro attestation parsing native
327//              function on mainnet.
328//              split_checkpoints_in_consensus_handler in devnet
329//              Enable additional validation on zkLogin public identifier.
330// Version 111: Validator metadata
331// Version 112: Enable Ristretto255 in devnet.
332// Version 113: Validate gas price >= RGP at signing for address balance gas payments.
333// Version 114: Gate seeded test overrides for checkpoint tx limit behind feature flag.
334// Version 115: Gasless transaction drop safety.
335//              Enable address aliases on mainnet.
336//              Relax ValidDuring requirement for transactions with owned inputs.
337// Version 116: Enable Display Registry.
338//              Disable defer_unpaid_amplification (debugging).
339// Version 117: Update Sui System metadata handling.
340// Version 118: Adds `transfer_migration_cap` to display registry
341// Version 119: Enable the new VM.
342// Version 120: Disallow unused jump tables
343// Version 121: Re-enable defer_unpaid_amplification (devnet + testnet).
344// Version 122: Framework update: vector::empty is deprecated.
345//              Enable bulletproofs verification on devnet.
346//              Enable defer_unpaid_amplification on mainnet.
347// Version 123: Gas accounting refresh (gas_model v13).
348// Version 124: Add timestamp_based_epoch_close feature flag and enable in tests.
349//              Fix native call double-pop in gas meter stack height tracking (gas_model v14).
350//              Limit public inputs in groth16::prepare_verifying_key.
351//              Enable address balances, free tier (gasless), and coin reservations on mainnet.
352//              Enables enable_accumulators, enable_address_balance_gas_payments,
353//              enable_authenticated_event_streams, enable_coin_reservation_obj_refs,
354//              enable_object_funds_withdraw, convert_withdrawal_compatibility_ptb_arguments,
355//              split_checkpoints_in_consensus_handler, include_checkpoint_artifacts_digest_in_summary,
356//              and enable_gasless on mainnet to bring it in line with testnet.
357//              Configure mainnet gasless allowlist with stablecoin types and $0.01 minimum
358//              transfer per stable.
359// Version 125: Enable granular_post_execution_checks.
360//              Enable timestamp_based_epoch_close on testnet.
361// Version 126: Enable early_exit_on_iffw (gates the gas-underflow fix
362//              shipped to mainnet out-of-band in #26816).
363// Version 127: Enable always_advance_dkg_to_resolution.
364//              Update gas prices for range proofs and ristretto group operations.
365//              Enable Ristretto255 group operations and bulletproofs verification on testnet.
366//              Enable init functions for newly introduced modules during package upgrade.
367//              Enable timestamp_based_epoch_close on mainnet.
368// Version 128: Make some additional bounds to binary tables explicit.
369// Version 129: Add `insert_before` and `insert_after` to `sui::linked_table`
370//              Enable unified linkage in PTBs
371// Version 130: Record unsettled object-funds withdraws using per-account net amounts
372//              from transaction effects instead of running-max withdraw amounts.
373//              Add the `sui::scratch` per-transaction ephemeral store and its native costs.
374//              Enable zklogin v2 verify (with v1 fallback) for devnet only.
375//              Add an epoch close deadline failsafe for deferred transactions.
376// Version 131: Enable sharing transaction deny configs between validators via consensus.
377//              Enable tx_context_restrictions_verifier: reject system-package
378//              function signatures with `&mut TxContext` + any `&mut _` return
379//              that have no non-`TxContext` `&mut U` parameter.
380// Version 132: Enable defer_owned_object_double_spend on devnet.
381//              Add the `object::record_new_uid_from_hash` native and its cost, tracking the
382//              root version of hash-derived UIDs (`new_uid_from_hash`).
383//              Create the ForwardingAddressRegistry system object on devnet.
384//              Make upgrade-init linkage checks independent of PTB command order.
385// Version 133: Include function signatures in type-node limits.
386//              Bound type nodes in accumulators.
387// Version 134: Add `package::original_package_id` and its native costs.
388//              Reduce the consensus block transaction count and payload limits.
389//              (Both gated to non-mainnet chains.)
390//              Disable defer_unpaid_amplification on mainnet.
391// Version 135: Apply the v134 config changes on mainnet.
392//              Disable defer_unpaid_amplification everywhere.
393// Version 136: Enable ptb_tx_context_restrictions: `TxContext` may appear in a
394//              PTB Move call signature at most once mutably or any number of
395//              times immutably (never by value), and never in return position.
396//              Enable allowed_proposers on devnet.
397//              Add limits for references used by programmable transactions.
398//              Add additional linkage invariant hardening/invariant checks in PTBs.
399//              Add package_arena_size_in_bytes.
400// Version 137: Lower the per-bit cost of bulletproofs range proof verification, and raise the
401//              bound on batch size * range bits from 512 to 1024.
402//              Enable allowances.
403//              Enable fix_ptb_generated_reads.
404//              Charge `LdConst` for the abstract value size of the constant instead of its
405//              serialized byte length.
406//              Enable check_object_funds_withdraw_in_execution on devnet and charge for reads.
407//              Enable allowed_proposers on testnet and mainnet.
408//              Validate PTB indices at signing time.
409//              Enable memory_safety_invariant_check_v2.
410
411#[derive(Copy, Clone, Debug, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
412pub struct ProtocolVersion(u64);
413
414impl ProtocolVersion {
415    // The minimum and maximum protocol version supported by this binary. Counterintuitively, this constant may
416    // change over time as support for old protocol versions is removed from the source. This
417    // ensures that when a new network (such as a testnet) is created, its genesis committee will
418    // use a protocol version that is actually supported by the binary.
419    pub const MIN: Self = Self(MIN_PROTOCOL_VERSION);
420
421    pub const MAX: Self = Self(MAX_PROTOCOL_VERSION);
422
423    #[cfg(not(msim))]
424    pub const MAX_ALLOWED: Self = Self::MAX;
425
426    // We create one additional "fake" version in simulator builds so that we can test upgrades.
427    #[cfg(msim)]
428    pub const MAX_ALLOWED: Self = Self(MAX_PROTOCOL_VERSION + 1);
429
430    pub fn new(v: u64) -> Self {
431        Self(v)
432    }
433
434    pub const fn as_u64(&self) -> u64 {
435        self.0
436    }
437
438    // For serde deserialization - we don't define a Default impl because there isn't a single
439    // universally appropriate default value.
440    pub fn max() -> Self {
441        Self::MAX
442    }
443
444    pub fn prev(self) -> Self {
445        Self(self.0.checked_sub(1).unwrap())
446    }
447}
448
449impl From<u64> for ProtocolVersion {
450    fn from(v: u64) -> Self {
451        Self::new(v)
452    }
453}
454
455impl std::ops::Sub<u64> for ProtocolVersion {
456    type Output = Self;
457    fn sub(self, rhs: u64) -> Self::Output {
458        Self::new(self.0 - rhs)
459    }
460}
461
462impl std::ops::Add<u64> for ProtocolVersion {
463    type Output = Self;
464    fn add(self, rhs: u64) -> Self::Output {
465        Self::new(self.0 + rhs)
466    }
467}
468
469#[derive(
470    Clone, Serialize, Deserialize, Debug, Default, PartialEq, Copy, PartialOrd, Ord, Eq, ValueEnum,
471)]
472pub enum Chain {
473    Mainnet,
474    Testnet,
475    #[default]
476    Unknown,
477}
478
479impl Chain {
480    pub fn as_str(self) -> &'static str {
481        match self {
482            Chain::Mainnet => "mainnet",
483            Chain::Testnet => "testnet",
484            Chain::Unknown => "unknown",
485        }
486    }
487}
488
489pub struct Error(pub String);
490
491// TODO: There are quite a few non boolean values in the feature flags. We should move them out.
492/// Records on/off feature flags that may vary at each protocol version.
493#[derive(Default, Clone, Serialize, Deserialize, Debug, ProtocolConfigFeatureFlagsGetters)]
494struct FeatureFlags {
495    // Add feature flags here, e.g.:
496    // new_protocol_feature: bool,
497    #[serde(skip_serializing_if = "is_false")]
498    package_upgrades: bool,
499    // If true, validators will commit to the root state digest
500    // in end of epoch checkpoint proposals
501    #[serde(skip_serializing_if = "is_false")]
502    commit_root_state_digest: bool,
503    // Pass epoch start time to advance_epoch safe mode function.
504    #[serde(skip_serializing_if = "is_false")]
505    advance_epoch_start_time_in_safe_mode: bool,
506    // If true, apply the fix to correctly capturing loaded child object versions in execution's
507    // object runtime.
508    #[serde(skip_serializing_if = "is_false")]
509    loaded_child_objects_fixed: bool,
510    // If true, treat missing types in the upgraded modules when creating an upgraded package as a
511    // compatibility error.
512    #[serde(skip_serializing_if = "is_false")]
513    missing_type_is_compatibility_error: bool,
514    // If true, then the scoring decision mechanism will not get disabled when we do have more than
515    // f low scoring authorities, but it will simply flag as low scoring only up to f authorities.
516    #[serde(skip_serializing_if = "is_false")]
517    scoring_decision_with_validity_cutoff: bool,
518
519    // DEPRECATED: this was an ephemeral feature flag only used by consensus handler, which has now
520    // been deployed everywhere.
521    #[serde(skip_serializing_if = "is_false")]
522    consensus_order_end_of_epoch_last: bool,
523
524    // If true, validators emit slim (ancestor-compressed) blocks on the consensus block
525    // subscription stream, framed in a block envelope. Gates the wire framing on both
526    // ends of the stream.
527    #[serde(skip_serializing_if = "is_false")]
528    consensus_slim_block_propagation: bool,
529
530    // Disallow adding abilities to types during package upgrades.
531    #[serde(skip_serializing_if = "is_false")]
532    disallow_adding_abilities_on_upgrade: bool,
533    // Disables unnecessary invariant check in the Move VM when swapping the value out of a local
534    #[serde(skip_serializing_if = "is_false")]
535    disable_invariant_violation_check_in_swap_loc: bool,
536    // advance to highest supported protocol version at epoch change, instead of the next consecutive
537    // protocol version.
538    #[serde(skip_serializing_if = "is_false")]
539    advance_to_highest_supported_protocol_version: bool,
540    // If true, disallow entry modifiers on entry functions
541    #[serde(skip_serializing_if = "is_false")]
542    ban_entry_init: bool,
543    // If true, hash module bytes individually when calculating package digests for upgrades
544    #[serde(skip_serializing_if = "is_false")]
545    package_digest_hash_module: bool,
546    // If true, disallow changing struct type parameters during package upgrades
547    #[serde(skip_serializing_if = "is_false")]
548    disallow_change_struct_type_params_on_upgrade: bool,
549    // If true, checks no extra bytes in a compiled module
550    #[serde(skip_serializing_if = "is_false")]
551    no_extraneous_module_bytes: bool,
552    // If true, then use the versioned metadata format in narwhal entities.
553    #[serde(skip_serializing_if = "is_false")]
554    narwhal_versioned_metadata: bool,
555
556    // Enable zklogin auth
557    #[serde(skip_serializing_if = "is_false")]
558    zklogin_auth: bool,
559    // zkLogin circuit verify mode: 0 = accept v1 circuit proofs only, 1 = try the v2
560    // circuit first and fall back to v1 (migration phase), 2 = accept v2 circuit proofs only.
561    #[serde(skip_serializing_if = "is_zero")]
562    zklogin_circuit_mode: u64,
563    // How we order transactions coming out of consensus before sending to execution.
564    #[serde(skip_serializing_if = "ConsensusTransactionOrdering::is_none")]
565    consensus_transaction_ordering: ConsensusTransactionOrdering,
566
567    // Previously, the unwrapped_then_deleted field in TransactionEffects makes a distinction between
568    // whether an object has existed in the store previously (i.e. whether there is a tombstone).
569    // Such dependency makes effects generation inefficient, and requires us to include wrapped
570    // tombstone in state root hash.
571    // To prepare for effects V2, with this flag set to true, we simplify the definition of
572    // unwrapped_then_deleted to always include unwrapped then deleted objects,
573    // regardless of their previous state in the store.
574    #[serde(skip_serializing_if = "is_false")]
575    simplified_unwrap_then_delete: bool,
576    // Enable upgraded multisig support
577    #[serde(skip_serializing_if = "is_false")]
578    upgraded_multisig_supported: bool,
579    // If true minimum txn charge is a multiplier of the gas price
580    #[serde(skip_serializing_if = "is_false")]
581    txn_base_cost_as_multiplier: bool,
582
583    // If true, the ability to delete shared objects is in effect
584    #[serde(skip_serializing_if = "is_false")]
585    shared_object_deletion: bool,
586
587    // If true, then the new algorithm for the leader election schedule will be used
588    #[serde(skip_serializing_if = "is_false")]
589    narwhal_new_leader_election_schedule: bool,
590
591    // A list of supported OIDC providers that can be used for zklogin.
592    #[serde(skip_serializing_if = "is_empty")]
593    zklogin_supported_providers: BTreeSet<String>,
594
595    // If true, use the new child object format
596    #[serde(skip_serializing_if = "is_false")]
597    loaded_child_object_format: bool,
598
599    #[serde(skip_serializing_if = "is_false")]
600    #[skip_protocol_config_accessor]
601    enable_jwk_consensus_updates: bool,
602
603    #[serde(skip_serializing_if = "is_false")]
604    #[skip_protocol_config_accessor]
605    end_of_epoch_transaction_supported: bool,
606
607    // Perform simple conservation checks keeping into account out of gas scenarios
608    // while charging for storage.
609    #[serde(skip_serializing_if = "is_false")]
610    simple_conservation_checks: bool,
611
612    // If true, use the new child object format type logging
613    #[serde(skip_serializing_if = "is_false")]
614    loaded_child_object_format_type: bool,
615
616    // Enable receiving sent objects
617    #[serde(skip_serializing_if = "is_false")]
618    receive_objects: bool,
619
620    // If true, include CheckpointDigest in consensus dedup key for checkpoint signatures (V2).
621    #[serde(skip_serializing_if = "is_false")]
622    consensus_checkpoint_signature_key_includes_digest: bool,
623
624    // Enable random beacon protocol
625    #[serde(skip_serializing_if = "is_false")]
626    random_beacon: bool,
627
628    // Enable bridge protocol
629    #[serde(skip_serializing_if = "is_false")]
630    #[skip_protocol_config_accessor]
631    bridge: bool,
632
633    #[serde(skip_serializing_if = "is_false")]
634    enable_effects_v2: bool,
635
636    // If true, then use CertificateV2 in narwhal.
637    #[serde(skip_serializing_if = "is_false")]
638    narwhal_certificate_v2: bool,
639
640    // If true, allow verify with legacy zklogin address
641    #[serde(skip_serializing_if = "is_false")]
642    verify_legacy_zklogin_address: bool,
643
644    // Enable throughput aware consensus submission
645    #[serde(skip_serializing_if = "is_false")]
646    throughput_aware_consensus_submission: bool,
647
648    // If true, recompute has_public_transfer from the type instead of what is stored in the object
649    #[serde(skip_serializing_if = "is_false")]
650    recompute_has_public_transfer_in_execution: bool,
651
652    // If true, multisig containing zkLogin sig is accepted.
653    #[serde(skip_serializing_if = "is_false")]
654    accept_zklogin_in_multisig: bool,
655
656    // If true, multisig containing passkey sig is accepted.
657    #[serde(skip_serializing_if = "is_false")]
658    accept_passkey_in_multisig: bool,
659
660    // If true, additional zkLogin public identifier structure is validated.
661    #[serde(skip_serializing_if = "is_false")]
662    validate_zklogin_public_identifier: bool,
663
664    // If true, consensus prologue transaction also includes the consensus output digest.
665    // It can be used to detect consensus output folk.
666    #[serde(skip_serializing_if = "is_false")]
667    include_consensus_digest_in_prologue: bool,
668
669    // If true, use the hardened OTW check
670    #[serde(skip_serializing_if = "is_false")]
671    hardened_otw_check: bool,
672
673    // If true allow calling receiving_object_id function
674    #[serde(skip_serializing_if = "is_false")]
675    allow_receiving_object_id: bool,
676
677    // Enable the poseidon hash function
678    #[serde(skip_serializing_if = "is_false")]
679    enable_poseidon: bool,
680
681    // If true, enable the coin deny list.
682    #[serde(skip_serializing_if = "is_false")]
683    enable_coin_deny_list: bool,
684
685    // Enable native functions for group operations.
686    #[serde(skip_serializing_if = "is_false")]
687    enable_group_ops_native_functions: bool,
688
689    // Enable native function for msm.
690    #[serde(skip_serializing_if = "is_false")]
691    enable_group_ops_native_function_msm: bool,
692
693    // Enable group operations for Ristretto255
694    #[serde(skip_serializing_if = "is_false")]
695    enable_ristretto255_group_ops: bool,
696
697    // Enable native functions for group operations.
698    #[serde(skip_serializing_if = "is_false")]
699    enable_verify_bulletproofs_ristretto255: bool,
700
701    // Enable nitro attestation.
702    #[serde(skip_serializing_if = "is_false")]
703    enable_nitro_attestation: bool,
704
705    // Enable upgraded parsing of nitro attestation that interprets pcrs as a map.
706    #[serde(skip_serializing_if = "is_false")]
707    enable_nitro_attestation_upgraded_parsing: bool,
708
709    // Enable upgraded parsing of nitro attestation containing all nonzero PCRs.
710    #[serde(skip_serializing_if = "is_false")]
711    enable_nitro_attestation_all_nonzero_pcrs_parsing: bool,
712
713    // Enable upgraded parsing of nitro attestation to always include required PCRs, even when all zeros.
714    #[serde(skip_serializing_if = "is_false")]
715    enable_nitro_attestation_always_include_required_pcrs_parsing: bool,
716
717    // Reject functions with mutable Random.
718    #[serde(skip_serializing_if = "is_false")]
719    reject_mutable_random_on_entry_functions: bool,
720
721    // Controls the behavior of per object congestion control in consensus handler.
722    #[serde(skip_serializing_if = "PerObjectCongestionControlMode::is_none")]
723    per_object_congestion_control_mode: PerObjectCongestionControlMode,
724
725    // The consensus protocol to be used for the epoch.
726    #[serde(skip_serializing_if = "ConsensusChoice::is_narwhal")]
727    consensus_choice: ConsensusChoice,
728
729    // Consensus network to use.
730    #[serde(skip_serializing_if = "ConsensusNetwork::is_anemo")]
731    consensus_network: ConsensusNetwork,
732
733    // If true, use the correct (<=) comparison for max_gas_payment_objects instead of (<)
734    #[serde(skip_serializing_if = "is_false")]
735    correct_gas_payment_limit_check: bool,
736
737    // Set the upper bound allowed for max_epoch in zklogin signature.
738    #[serde(skip_serializing_if = "Option::is_none")]
739    zklogin_max_epoch_upper_bound_delta: Option<u64>,
740
741    // Controls leader scoring & schedule change in Mysticeti consensus.
742    #[serde(skip_serializing_if = "is_false")]
743    mysticeti_leader_scoring_and_schedule: bool,
744
745    // Enable resharing of shared objects using the same initial shared version
746    #[serde(skip_serializing_if = "is_false")]
747    reshare_at_same_initial_version: bool,
748
749    // Resolve Move abort locations to the package id instead of the runtime module ID.
750    #[serde(skip_serializing_if = "is_false")]
751    resolve_abort_locations_to_package_id: bool,
752
753    // Enables the use of the Mysticeti committed sub dag digest to the `ConsensusCommitInfo` in checkpoints.
754    // When disabled the default digest is used instead. It's important to have this guarded behind
755    // a flag as it will lead to checkpoint forks.
756    #[serde(skip_serializing_if = "is_false")]
757    mysticeti_use_committed_subdag_digest: bool,
758
759    // Enable VDF
760    #[serde(skip_serializing_if = "is_false")]
761    enable_vdf: bool,
762
763    // Controls whether consensus handler should record consensus determined shared object version
764    // assignments in consensus commit prologue transaction.
765    // The purpose of doing this is to enable replaying transaction without transaction effects.
766    #[serde(skip_serializing_if = "is_false")]
767    record_consensus_determined_version_assignments_in_prologue: bool,
768    // V2 also records initial shared versions for consensus objects.
769    // Deprecated: must always be set to `true`.
770    #[serde(skip_serializing_if = "is_false")]
771    record_consensus_determined_version_assignments_in_prologue_v2: bool,
772
773    // Run verification of framework upgrades using a new/fresh VM.
774    #[serde(skip_serializing_if = "is_false")]
775    fresh_vm_on_framework_upgrade: bool,
776
777    // When set to true, the consensus commit prologue transaction will be placed first
778    // in a consensus commit in checkpoints.
779    // If a checkpoint contains multiple consensus commit, say [cm1][cm2]. The each commit's
780    // consensus commit prologue will be the first transaction in each segment:
781    //     [ccp1, rest cm1][ccp2, rest cm2]
782    // The reason to prepose the prologue transaction is to provide information for transaction
783    // cancellation.
784    #[serde(skip_serializing_if = "is_false")]
785    prepend_prologue_tx_in_consensus_commit_in_checkpoints: bool,
786
787    // Set number of leaders per round for Mysticeti commits.
788    #[serde(skip_serializing_if = "Option::is_none")]
789    mysticeti_num_leaders_per_round: Option<usize>,
790
791    // Enable Soft Bundle (SIP-19).
792    #[serde(skip_serializing_if = "is_false")]
793    soft_bundle: bool,
794
795    // If true, enable the coin deny list V2.
796    #[serde(skip_serializing_if = "is_false")]
797    enable_coin_deny_list_v2: bool,
798
799    // Enable passkey auth (SIP-9)
800    #[serde(skip_serializing_if = "is_false")]
801    passkey_auth: bool,
802
803    // Use AuthorityCapabilitiesV2
804    #[serde(skip_serializing_if = "is_false")]
805    authority_capabilities_v2: bool,
806
807    // Rethrow type layout errors during serialization instead of trying to convert them.
808    #[serde(skip_serializing_if = "is_false")]
809    rethrow_serialization_type_layout_errors: bool,
810
811    // Use distributed vote leader scoring strategy in consensus.
812    #[serde(skip_serializing_if = "is_false")]
813    consensus_distributed_vote_scoring_strategy: bool,
814
815    // Probe rounds received by peers from every authority.
816    #[serde(skip_serializing_if = "is_false")]
817    consensus_round_prober: bool,
818
819    // Validate identifier inputs separately
820    #[serde(skip_serializing_if = "is_false")]
821    validate_identifier_inputs: bool,
822
823    // Disallow self identifier
824    #[serde(skip_serializing_if = "is_false")]
825    disallow_self_identifier: bool,
826
827    // Enables Mysticeti fastpath.
828    #[serde(skip_serializing_if = "is_false")]
829    mysticeti_fastpath: bool,
830
831    // If true, disable pre-consensus locking for owned objects.
832    // All transactions go through consensus, and owned object conflict detection
833    // happens post-consensus via lock acquisition.
834    #[serde(skip_serializing_if = "is_false")]
835    disable_preconsensus_locking: bool,
836
837    // Makes the event's sending module version-aware.
838    #[serde(skip_serializing_if = "is_false")]
839    relocate_event_module: bool,
840
841    // Enable uncompressed group elements in BLS123-81 G1
842    #[serde(skip_serializing_if = "is_false")]
843    uncompressed_g1_group_elements: bool,
844
845    #[serde(skip_serializing_if = "is_false")]
846    disallow_new_modules_in_deps_only_packages: bool,
847
848    // Use smart ancestor selection in consensus.
849    #[serde(skip_serializing_if = "is_false")]
850    consensus_smart_ancestor_selection: bool,
851
852    // Probe accepted rounds in round prober.
853    #[serde(skip_serializing_if = "is_false")]
854    consensus_round_prober_probe_accepted_rounds: bool,
855
856    // Enable v2 native charging for natives.
857    #[serde(skip_serializing_if = "is_false")]
858    native_charging_v2: bool,
859
860    // Enables the new logic for collecting the subdag in the consensus linearizer. The new logic does not stop the recursion at the highest
861    // committed round for each authority, but allows to commit uncommitted blocks up to gc round (excluded) for that authority.
862    #[serde(skip_serializing_if = "is_false")]
863    #[skip_protocol_config_accessor]
864    consensus_linearize_subdag_v2: bool,
865
866    // Properly convert certain type argument errors in the execution layer.
867    #[serde(skip_serializing_if = "is_false")]
868    convert_type_argument_error: bool,
869
870    // Variants count as nodes
871    #[serde(skip_serializing_if = "is_false")]
872    variant_nodes: bool,
873
874    // If true, enable zstd compression for consensus tonic network.
875    #[serde(skip_serializing_if = "is_false")]
876    consensus_zstd_compression: bool,
877
878    // If true, enables the optimizations for child object mutations, removing unnecessary mutations
879    #[serde(skip_serializing_if = "is_false")]
880    minimize_child_object_mutations: bool,
881
882    // If true, record the additional state digest in the consensus commit prologue.
883    // Deprecated: must always be set to `true`.
884    #[serde(skip_serializing_if = "is_false")]
885    record_additional_state_digest_in_prologue: bool,
886
887    // If true, enable `TxContext` Move API to go native.
888    #[serde(skip_serializing_if = "is_false")]
889    move_native_context: bool,
890
891    // If true, then it (1) will not enforce monotonicity checks for a block's ancestors and (2) calculates the commit's timestamp based on the
892    // weighted by stake median timestamp of the leader's ancestors.
893    #[serde(skip_serializing_if = "is_false")]
894    #[skip_protocol_config_accessor]
895    consensus_median_based_commit_timestamp: bool,
896
897    // If true, enables the normalization of PTB arguments but does not yet enable splatting
898    // `Result`s of length not equal to 1
899    #[serde(skip_serializing_if = "is_false")]
900    normalize_ptb_arguments: bool,
901
902    // If true, enabled batched block sync in consensus.
903    #[serde(skip_serializing_if = "is_false")]
904    consensus_batched_block_sync: bool,
905
906    // If true, enforces checkpoint timestamps are non-decreasing.
907    #[serde(skip_serializing_if = "is_false")]
908    enforce_checkpoint_timestamp_monotonicity: bool,
909
910    // If true, enables better errors and bounds for max ptb values
911    #[serde(skip_serializing_if = "is_false")]
912    max_ptb_value_size_v2: bool,
913
914    // If true, resolves all type input ids to be defining ID based in the adapter
915    #[serde(skip_serializing_if = "is_false")]
916    resolve_type_input_ids_to_defining_id: bool,
917
918    // Enable native function for party transfer
919    #[serde(skip_serializing_if = "is_false")]
920    enable_party_transfer: bool,
921
922    // Allow objects created or mutated in system transactions to exceed the max object size limit.
923    #[serde(skip_serializing_if = "is_false")]
924    allow_unbounded_system_objects: bool,
925
926    // Signifies the cut-over of using type tags instead of `Type`s in the object runtime.
927    #[serde(skip_serializing_if = "is_false")]
928    type_tags_in_object_runtime: bool,
929
930    // Enable accumulators
931    #[serde(skip_serializing_if = "is_false")]
932    enable_accumulators: bool,
933
934    // Enable coin reservation
935    #[serde(skip_serializing_if = "is_false")]
936    #[skip_protocol_config_accessor]
937    enable_coin_reservation_obj_refs: bool,
938
939    // If true, create the root accumulator object in the change epoch transaction.
940    // This must be enabled and shipped before `enable_accumulators` is set to true.
941    #[serde(skip_serializing_if = "is_false")]
942    create_root_accumulator_object: bool,
943
944    // Enable authenticated event streams
945    #[serde(skip_serializing_if = "is_false")]
946    #[skip_protocol_config_accessor]
947    enable_authenticated_event_streams: bool,
948
949    // Enable address balance gas payments
950    #[serde(skip_serializing_if = "is_false")]
951    enable_address_balance_gas_payments: bool,
952
953    // Validate gas price >= RGP at signing for address balance gas payments
954    #[serde(skip_serializing_if = "is_false")]
955    address_balance_gas_check_rgp_at_signing: bool,
956
957    #[serde(skip_serializing_if = "is_false")]
958    address_balance_gas_reject_gas_coin_arg: bool,
959
960    // Enable multi-epoch transaction expiration (max 1 epoch difference)
961    #[serde(skip_serializing_if = "is_false")]
962    enable_multi_epoch_transaction_expiration: bool,
963
964    // Relax ValidDuring expiration requirement for transactions with owned inputs
965    #[serde(skip_serializing_if = "is_false")]
966    relax_valid_during_for_owned_inputs: bool,
967
968    // Enable statically type checked ptb execution
969    #[serde(skip_serializing_if = "is_false")]
970    enable_ptb_execution_v2: bool,
971
972    // Provide better type resolution errors in the adapter.
973    #[serde(skip_serializing_if = "is_false")]
974    better_adapter_type_resolution_errors: bool,
975
976    // If true, record the time estimate processed in the consensus commit prologue.
977    #[serde(skip_serializing_if = "is_false")]
978    record_time_estimate_processed: bool,
979
980    // If true enable additional linkage checks.
981    #[serde(skip_serializing_if = "is_false")]
982    dependency_linkage_error: bool,
983
984    // If true enable additional multisig checks.
985    #[serde(skip_serializing_if = "is_false")]
986    additional_multisig_checks: bool,
987
988    // If true, ignore execution time observations after certs are closed.
989    #[serde(skip_serializing_if = "is_false")]
990    ignore_execution_time_observations_after_certs_closed: bool,
991
992    // If true use `debug_fatal` to report invariant violations.
993    // `debug_fatal` panics in debug builds and breaks tests/behavior based on older
994    // protocol versions (see make_vec_non_existent_type_v71.move)
995    #[serde(skip_serializing_if = "is_false")]
996    debug_fatal_on_move_invariant_violation: bool,
997
998    // DO NOT ENABLE THIS FOR PRODUCTION NETWORKS. used for testing only.
999    // Allow private accumulator entrypoints
1000    #[serde(skip_serializing_if = "is_false")]
1001    allow_private_accumulator_entrypoints: bool,
1002
1003    // If true, include indirect state in the additional consensus digest.
1004    // Deprecated: must always be set to `true`.
1005    #[serde(skip_serializing_if = "is_false")]
1006    additional_consensus_digest_indirect_state: bool,
1007
1008    // Check for `init` for new modules to a package on upgrade.
1009    #[serde(skip_serializing_if = "is_false")]
1010    check_for_init_during_upgrade: bool,
1011
1012    // If true, run `init` for newly introduced modules during package upgrade.
1013    #[serde(skip_serializing_if = "is_false")]
1014    enable_init_on_upgrade: bool,
1015
1016    // If true, analyze upgrade-init linkage after all other PTB linkage constraints.
1017    #[serde(skip_serializing_if = "is_false")]
1018    enable_order_independent_upgrade_init_linkage: bool,
1019
1020    // If true, adds additional hardening and checks to upgrade-init linkage entries, and adds
1021    // additional linkage invariant checks around linkage.
1022    #[serde(skip_serializing_if = "is_false")]
1023    harden_linkage_consistency: bool,
1024
1025    // Check shared object transfer restrictions per command.
1026    #[serde(skip_serializing_if = "is_false")]
1027    per_command_shared_object_transfer_rules: bool,
1028
1029    // Validate PTB input and result indices before signing.
1030    #[serde(skip_serializing_if = "is_false")]
1031    validate_ptb_argument_indices: bool,
1032
1033    // Enable including checkpoint artifacts digest in the summary.
1034    #[serde(skip_serializing_if = "is_false")]
1035    include_checkpoint_artifacts_digest_in_summary: bool,
1036
1037    // If true, use MFP txns in load initial object debts.
1038    #[serde(skip_serializing_if = "is_false")]
1039    use_mfp_txns_in_load_initial_object_debts: bool,
1040
1041    // If true, cancel randomness-using txns when DKG has failed *before* doing other congestion checks.
1042    #[serde(skip_serializing_if = "is_false")]
1043    cancel_for_failed_dkg_early: bool,
1044
1045    // If true, keep advancing the DKG state machine while DKG is pending.
1046    #[serde(skip_serializing_if = "is_false")]
1047    always_advance_dkg_to_resolution: bool,
1048
1049    // Enable coin registry protocol
1050    #[serde(skip_serializing_if = "is_false")]
1051    enable_coin_registry: bool,
1052
1053    // Use abstract size in the object runtime instead the legacy value size.
1054    #[serde(skip_serializing_if = "is_false")]
1055    abstract_size_in_object_runtime: bool,
1056
1057    // If true charge for loads into the cache (i.e., fetches from storage) in the object runtime.
1058    #[serde(skip_serializing_if = "is_false")]
1059    object_runtime_charge_cache_load_gas: bool,
1060
1061    // If true, perform additional borrow checks
1062    #[serde(skip_serializing_if = "is_false")]
1063    additional_borrow_checks: bool,
1064
1065    // If true, use the new commit handler.
1066    #[serde(skip_serializing_if = "is_false")]
1067    use_new_commit_handler: bool,
1068
1069    // If true return a better error message when we encounter a loader error.
1070    #[serde(skip_serializing_if = "is_false")]
1071    better_loader_errors: bool,
1072
1073    // If true generate layouts for dynamic fields
1074    #[serde(skip_serializing_if = "is_false")]
1075    generate_df_type_layouts: bool,
1076
1077    // If true, allow Move functions called in PTBs to return references
1078    #[serde(skip_serializing_if = "is_false")]
1079    allow_references_in_ptbs: bool,
1080
1081    // If true, the tx_context_restrictions_verifier pass runs at Move module
1082    // publish time and rejects system-package signatures with `&mut TxContext`
1083    // + any `&mut _` return that have no non-`TxContext` `&mut U` parameter.
1084    // User packages are exempt: they can express the same shape through
1085    // generic instantiation, so PTB arity and auto-injection checks are the
1086    // safety mechanism there.
1087    #[serde(skip_serializing_if = "is_false")]
1088    framework_tx_context_mut_restrictions: bool,
1089
1090    // Count function and local signatures towards type-node budgets.
1091    #[serde(skip_serializing_if = "is_false")]
1092    include_function_signatures_in_instantiation_limits: bool,
1093
1094    // If true, the static PTB verifier restricts `TxContext` in Move call
1095    // signatures: it may appear at most once as `&mut TxContext`, or any
1096    // number of times as `&TxContext`, never by value, and never in return
1097    // position (it can never become a PTB result).
1098    #[serde(skip_serializing_if = "is_false")]
1099    ptb_tx_context_restrictions: bool,
1100
1101    // Enable display registry protocol
1102    #[serde(skip_serializing_if = "is_false")]
1103    enable_display_registry: bool,
1104
1105    // If true, enable private generics verifier v2
1106    #[serde(skip_serializing_if = "is_false")]
1107    private_generics_verifier_v2: bool,
1108
1109    // If true, deprecate global storage ops during Move module deserialization
1110    #[serde(skip_serializing_if = "is_false")]
1111    deprecate_global_storage_ops_during_deserialization: bool,
1112
1113    // If true, enable non-exclusive writes for user transactions.
1114    // DO NOT ENABLE outside of the transaction test runner.
1115    #[serde(skip_serializing_if = "is_false")]
1116    enable_non_exclusive_writes: bool,
1117
1118    // If true, deprecate global storage ops everywhere.
1119    #[serde(skip_serializing_if = "is_false")]
1120    deprecate_global_storage_ops: bool,
1121
1122    // If true, normalize depth formula to not be empty for zero depth.
1123    #[serde(skip_serializing_if = "is_false")]
1124    normalize_depth_formula: bool,
1125
1126    // If true, `LdConst` charges for the abstract value size of the constant instead of its
1127    // serialized byte length.
1128    #[serde(skip_serializing_if = "is_false")]
1129    charge_ld_const_abstract_size: bool,
1130
1131    // If true, skip GC'ed accept votes in CommitFinalizer.
1132    #[serde(skip_serializing_if = "is_false")]
1133    consensus_skip_gced_accept_votes: bool,
1134
1135    // If true, include cancelled randomness txns in the consensus commit prologue.
1136    // Deprecated: must always be set to `true`.
1137    #[serde(skip_serializing_if = "is_false")]
1138    include_cancelled_randomness_txns_in_prologue: bool,
1139
1140    // Enables address aliases.
1141    #[serde(skip_serializing_if = "is_false")]
1142    #[skip_protocol_config_accessor]
1143    address_aliases: bool,
1144
1145    // If true, create the forwarding address registry object in the change epoch transaction.
1146    #[serde(skip_serializing_if = "is_false")]
1147    create_forwarding_address_registry: bool,
1148
1149    // Corrects signature-to-signer mapping in CheckpointContentsV2.
1150    // Deprecated: must always be set to `true`.
1151    #[serde(skip_serializing_if = "is_false")]
1152    fix_checkpoint_signature_mapping: bool,
1153
1154    // If true, enable object funds withdraw.
1155    #[serde(skip_serializing_if = "is_false")]
1156    enable_object_funds_withdraw: bool,
1157
1158    // If true, unsettled object-funds withdraws are recorded using per-account net
1159    // amounts from transaction effects, instead of running-max withdraw amounts.
1160    #[serde(skip_serializing_if = "is_false")]
1161    record_net_unsettled_object_withdraws: bool,
1162
1163    // If true, skip GC'ed blocks in direct finalization.
1164    #[serde(skip_serializing_if = "is_false")]
1165    consensus_skip_gced_blocks_in_direct_finalization: bool,
1166
1167    // If true, uses a new rounding mechanism for gas calculations, replacing the step-based one
1168    #[serde(skip_serializing_if = "is_false")]
1169    gas_rounding_halve_digits: bool,
1170
1171    // If true, enable tx contexts in all argument positions
1172    #[serde(skip_serializing_if = "is_false")]
1173    flexible_tx_context_positions: bool,
1174
1175    // If true, disable entry point signature check.
1176    #[serde(skip_serializing_if = "is_false")]
1177    disable_entry_point_signature_check: bool,
1178
1179    // If true, convert withdrawal compatibility PTB arguments to coins at the start of the PTB.
1180    #[serde(skip_serializing_if = "is_false")]
1181    convert_withdrawal_compatibility_ptb_arguments: bool,
1182
1183    // If true, additional restrictions for hot or not entry functions are enforced.
1184    #[serde(skip_serializing_if = "is_false")]
1185    restrict_hot_or_not_entry_functions: bool,
1186
1187    // If true, split checkpoints in consensus handler.
1188    #[serde(skip_serializing_if = "is_false")]
1189    split_checkpoints_in_consensus_handler: bool,
1190
1191    // If true, always accept committed system transactions.
1192    #[serde(skip_serializing_if = "is_false")]
1193    consensus_always_accept_system_transactions: bool,
1194
1195    // If true perform consistent verification of metadata
1196    #[serde(skip_serializing_if = "is_false")]
1197    validator_metadata_verify_v2: bool,
1198
1199    // If true, defer transactions with unpaid consensus amplification
1200    // (where duplicate count exceeds gas_price / RGP + 1)
1201    #[serde(skip_serializing_if = "is_false")]
1202    defer_unpaid_amplification: bool,
1203
1204    // If true, defer transactions that won an owned object lock when other transactions
1205    // in the same commit attempted to lock the same object (double-spend attempt).
1206    #[serde(skip_serializing_if = "is_false")]
1207    defer_owned_object_double_spend: bool,
1208
1209    // If true, `TransactionExpiration::Validity` is accepted, allowing a transaction to
1210    // restrict which validators may propose it in consensus.
1211    #[serde(skip_serializing_if = "is_false")]
1212    allowed_proposers: bool,
1213
1214    #[serde(skip_serializing_if = "is_false")]
1215    randomize_checkpoint_tx_limit_in_tests: bool,
1216
1217    // If true, mark the gas coin as uninitialized in drop safety when there is no gas coin.
1218    #[serde(skip_serializing_if = "is_false")]
1219    gasless_transaction_drop_safety: bool,
1220
1221    // When split-checkpoints enabled, merge randomness and non-randomness schedulables together.
1222    // Deprecated: must always be set to `true`.
1223    #[serde(skip_serializing_if = "is_false")]
1224    merge_randomness_into_checkpoint: bool,
1225
1226    // If true, use coin party owner information.
1227    #[serde(skip_serializing_if = "is_false")]
1228    use_coin_party_owner: bool,
1229
1230    #[serde(skip_serializing_if = "is_false")]
1231    enable_gasless: bool,
1232
1233    #[serde(skip_serializing_if = "is_false")]
1234    gasless_verify_remaining_balance: bool,
1235
1236    #[serde(skip_serializing_if = "is_false")]
1237    disallow_jump_orphans: bool,
1238
1239    // If true, return early on type mismatch in receive_object.
1240    #[serde(skip_serializing_if = "is_false")]
1241    early_return_receive_object_mismatched_type: bool,
1242
1243    // If true, use consensus commit timestamps to determine epoch close instead of EndOfPublish voting.
1244    // Each validator transitions from AcceptAllCerts to RejectAllCerts when the consensus commit
1245    // timestamp exceeds the reconfiguration timestamp. EndOfPublish quorum still works as a
1246    // fallback for manual epoch close.
1247    #[serde(skip_serializing_if = "is_false")]
1248    timestamp_based_epoch_close: bool,
1249
1250    // If true, groth16::prepare_verifying_key checks that the verifying key has no more than
1251    // MAX_PUBLIC_INPUTS public inputs.
1252    #[serde(skip_serializing_if = "is_false")]
1253    limit_groth16_pvk_inputs: bool,
1254
1255    // If true, the funds-accumulator address-balance change invariant
1256    // (`TemporaryStore::check_address_balance_changes`) is enforced as a consensus check —
1257    // violations abort the tx via the conservation-recovery flow. When false, the check still
1258    // runs but a violation panics so unexpected violations surface during rollout.
1259    #[serde(skip_serializing_if = "is_false")]
1260    enforce_address_balance_change_invariant: bool,
1261
1262    // If true, validators may broadcast `UpdateTransactionDenyConfig` consensus messages.
1263    #[serde(skip_serializing_if = "is_false")]
1264    share_transaction_deny_config_in_consensus: bool,
1265
1266    // Enables more granular post-execution checks.
1267    #[serde(skip_serializing_if = "is_false")]
1268    granular_post_execution_checks: bool,
1269
1270    // If true, exit early for IFWW transactions.
1271    #[serde(skip_serializing_if = "is_false")]
1272    early_exit_on_iffw: bool,
1273
1274    // If true enable unified linkage
1275    #[serde(skip_serializing_if = "is_false")]
1276    enable_unified_linkage: bool,
1277
1278    // Enable allowance-sourced funds withdrawals (`WithdrawFrom::SenderAllowance`).
1279    // Requires `enable_accumulators`.
1280    #[serde(skip_serializing_if = "is_false")]
1281    #[skip_protocol_config_accessor]
1282    enable_allowances: bool,
1283
1284    // Fixes last-use scoping and live-reference metering for generated `Read` PTB arguments.
1285    #[serde(skip_serializing_if = "is_false")]
1286    fix_ptb_generated_reads: bool,
1287
1288    #[serde(skip_serializing_if = "is_false")]
1289    check_object_funds_withdraw_in_execution: bool,
1290    // If true, use the bitset implementation for PTB memory safety invariant check.
1291    #[serde(skip_serializing_if = "is_false")]
1292    memory_safety_invariant_check_v2: bool,
1293}
1294
1295fn is_false(b: &bool) -> bool {
1296    !b
1297}
1298
1299fn is_empty(b: &BTreeSet<String>) -> bool {
1300    b.is_empty()
1301}
1302
1303fn is_zero(val: &u64) -> bool {
1304    *val == 0
1305}
1306
1307/// Ordering mechanism for transactions in one Narwhal consensus output.
1308#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1309pub enum ConsensusTransactionOrdering {
1310    /// No ordering. Transactions are processed in the order they appear in the consensus output.
1311    #[default]
1312    None,
1313    /// Order transactions by gas price, highest first.
1314    ByGasPrice,
1315}
1316
1317impl ConsensusTransactionOrdering {
1318    pub fn is_none(&self) -> bool {
1319        matches!(self, ConsensusTransactionOrdering::None)
1320    }
1321}
1322
1323#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1324pub struct ExecutionTimeEstimateParams {
1325    // Targeted per-object utilization as an integer percentage (1-100).
1326    pub target_utilization: u64,
1327    // Schedule up to this much extra work (in microseconds) per object,
1328    // but don't allow more than a single transaction to exceed this
1329    // burst limit.
1330    pub allowed_txn_cost_overage_burst_limit_us: u64,
1331
1332    // For separate budget for randomness-using tx, the above limits are
1333    // used with this integer-percentage scaling factor (1-100).
1334    pub randomness_scalar: u64,
1335
1336    // Absolute maximum allowed transaction duration estimate (in microseconds).
1337    pub max_estimate_us: u64,
1338
1339    // Number of the final checkpoints in an epoch whose observations should be
1340    // stored for use in the next epoch.
1341    pub stored_observations_num_included_checkpoints: u64,
1342
1343    // Absolute limit on the number of saved observations at end of epoch.
1344    pub stored_observations_limit: u64,
1345
1346    // Requires observations from at least this amount of stake in order to use
1347    // observation-based execution time estimates instead of the default.
1348    #[serde(skip_serializing_if = "is_zero")]
1349    pub stake_weighted_median_threshold: u64,
1350
1351    // For backwards compatibility with old behavior we use a zero default duration when adding
1352    // new execution time observation keys and a zero generation when loading stored observations.
1353    // This can be removed once set to "true" on mainnet.
1354    #[serde(skip_serializing_if = "is_false")]
1355    pub default_none_duration_for_new_keys: bool,
1356
1357    // Number of observations per chunk. When None, chunking is disabled.
1358    #[serde(skip_serializing_if = "Option::is_none")]
1359    pub observations_chunk_size: Option<u64>,
1360}
1361
1362// The config for per object congestion control in consensus handler.
1363#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1364pub enum PerObjectCongestionControlMode {
1365    #[default]
1366    None, // Deprecated.
1367    TotalGasBudget,                                     // Deprecated.
1368    TotalTxCount,                                       // Deprecated.
1369    TotalGasBudgetWithCap,                              // Deprecated.
1370    ExecutionTimeEstimate(ExecutionTimeEstimateParams), // Use execution time estimate as execution cost.
1371}
1372
1373impl PerObjectCongestionControlMode {
1374    pub fn is_none(&self) -> bool {
1375        matches!(self, PerObjectCongestionControlMode::None)
1376    }
1377}
1378
1379// Configuration options for consensus algorithm.
1380#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1381pub enum ConsensusChoice {
1382    #[default]
1383    Narwhal,
1384    SwapEachEpoch,
1385    Mysticeti,
1386}
1387
1388impl ConsensusChoice {
1389    pub fn is_narwhal(&self) -> bool {
1390        matches!(self, ConsensusChoice::Narwhal)
1391    }
1392}
1393
1394// Configuration options for consensus network.
1395#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1396pub enum ConsensusNetwork {
1397    #[default]
1398    Anemo,
1399    Tonic,
1400}
1401
1402impl ConsensusNetwork {
1403    pub fn is_anemo(&self) -> bool {
1404        matches!(self, ConsensusNetwork::Anemo)
1405    }
1406}
1407
1408/// Constants that change the behavior of the protocol.
1409///
1410/// The value of each constant here must be fixed for a given protocol version. To change the value
1411/// of a constant, advance the protocol version, and add support for it in `get_for_version` under
1412/// the new version number.
1413/// (below).
1414///
1415/// To add a new field to this struct, use the following procedure:
1416/// - Advance the protocol version.
1417/// - Add the field as a private `Option<T>` to the struct.
1418/// - Initialize the field to `None` in prior protocol versions.
1419/// - Initialize the field to `Some(val)` for your new protocol version.
1420/// - Add a public getter that simply unwraps the field.
1421/// - Two public getters of the form `field(&self) -> field_type`
1422///     and `field_as_option(&self) -> Option<field_type>` will be automatically generated for you.
1423/// Example for a field: `new_constant: Option<u64>`
1424/// ```rust,ignore
1425///      pub fn new_constant(&self) -> u64 {
1426///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
1427///     }
1428///      pub fn new_constant_as_option(&self) -> Option<u64> {
1429///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
1430///     }
1431/// ```
1432/// With `pub fn new_constant(&self) -> u64`, if the constant is accessed in a protocol version
1433/// in which it is not defined, the validator will crash. (Crashing is necessary because
1434/// this type of error would almost always result in forking if not prevented here).
1435/// If you don't want the validator to crash, you can use the
1436/// `pub fn new_constant_as_option(&self) -> Option<u64>` getter, which will
1437/// return `None` if the field is not defined at that version.
1438/// - If you want a customized getter, you can add a method in the impl.
1439#[skip_serializing_none]
1440#[derive(Clone, Serialize, Debug, ProtocolConfigAccessors, ProtocolConfigOverride)]
1441pub struct ProtocolConfig {
1442    pub version: ProtocolVersion,
1443
1444    /// The chain this config was instantiated for. Unlike the other fields, this is not a
1445    /// versioned protocol constant: it identifies the network rather than describing protocol
1446    /// behavior, so it is intentionally excluded from serialization (and from the config
1447    /// snapshots) and is populated directly from the chain passed to `get_for_version`.
1448    #[serde(skip)]
1449    chain: Chain,
1450
1451    feature_flags: FeatureFlags,
1452
1453    // ==== Transaction input limits ====
1454    /// Maximum serialized size of a transaction (in bytes).
1455    max_tx_size_bytes: Option<u64>,
1456
1457    /// Maximum number of input objects to a transaction. Enforced by the transaction input checker
1458    max_input_objects: Option<u64>,
1459
1460    /// Max size of objects a transaction can write to disk after completion. Enforce by the Sui adapter.
1461    /// This is the sum of the serialized size of all objects written to disk.
1462    /// The max size of individual objects on the other hand is `max_move_object_size`.
1463    max_size_written_objects: Option<u64>,
1464    /// Max size of objects a system transaction can write to disk after completion. Enforce by the Sui adapter.
1465    /// Similar to `max_size_written_objects` but for system transactions.
1466    max_size_written_objects_system_tx: Option<u64>,
1467
1468    /// Maximum size of serialized transaction effects.
1469    max_serialized_tx_effects_size_bytes: Option<u64>,
1470
1471    /// Maximum size of serialized transaction effects for system transactions.
1472    max_serialized_tx_effects_size_bytes_system_tx: Option<u64>,
1473
1474    /// Maximum number of gas payment objects for a transaction.
1475    max_gas_payment_objects: Option<u32>,
1476
1477    /// Maximum number of modules in a Publish transaction.
1478    max_modules_in_publish: Option<u32>,
1479
1480    /// Maximum number of transitive dependencies in a package when publishing.
1481    max_package_dependencies: Option<u32>,
1482
1483    /// Maximum number of arguments in a move call or a ProgrammableTransaction's
1484    /// TransferObjects command.
1485    max_arguments: Option<u32>,
1486
1487    /// Maximum number of total type arguments, computed recursively.
1488    max_type_arguments: Option<u32>,
1489
1490    /// Maximum depth of an individual type argument.
1491    max_type_argument_depth: Option<u32>,
1492
1493    /// Maximum size of a Pure CallArg.
1494    max_pure_argument_size: Option<u32>,
1495
1496    /// Maximum number of Commands in a ProgrammableTransaction.
1497    max_programmable_tx_commands: Option<u32>,
1498
1499    // ==== Move VM, Move bytecode verifier, and execution limits ===
1500    /// Maximum Move bytecode version the VM understands. All older versions are accepted.
1501    move_binary_format_version: Option<u32>,
1502    min_move_binary_format_version: Option<u32>,
1503
1504    /// Configuration controlling binary tables size.
1505    binary_module_handles: Option<u16>,
1506    binary_struct_handles: Option<u16>,
1507    binary_function_handles: Option<u16>,
1508    binary_function_instantiations: Option<u16>,
1509    binary_signatures: Option<u16>,
1510    binary_constant_pool: Option<u16>,
1511    binary_identifiers: Option<u16>,
1512    binary_address_identifiers: Option<u16>,
1513    binary_struct_defs: Option<u16>,
1514    binary_struct_def_instantiations: Option<u16>,
1515    binary_function_defs: Option<u16>,
1516    binary_field_handles: Option<u16>,
1517    binary_field_instantiations: Option<u16>,
1518    binary_friend_decls: Option<u16>,
1519    binary_enum_defs: Option<u16>,
1520    binary_enum_def_instantiations: Option<u16>,
1521    binary_variant_handles: Option<u16>,
1522    binary_variant_instantiation_handles: Option<u16>,
1523
1524    /// Maximum size of the `contents` part of an object, in bytes. Enforced by the Sui adapter when effects are produced.
1525    max_move_object_size: Option<u64>,
1526
1527    // TODO: Option<increase to 500 KB. currently, publishing a package > 500 KB exceeds the max computation gas cost
1528    /// Maximum size of a Move package object, in bytes. Enforced by the Sui adapter at the end of a publish transaction.
1529    max_move_package_size: Option<u64>,
1530
1531    /// Max number of publish or upgrade commands allowed in a programmable transaction block.
1532    max_publish_or_upgrade_per_ptb: Option<u64>,
1533
1534    /// Maximum gas budget in MIST that a transaction can use.
1535    max_tx_gas: Option<u64>,
1536
1537    /// Maximum amount of the proposed gas price in MIST (defined in the transaction).
1538    max_gas_price: Option<u64>,
1539
1540    /// For aborted txns, we cap the gas price at a factor of RGP. This lowers risk of setting higher priority gas price
1541    /// if there's a chance the txn will abort.
1542    max_gas_price_rgp_factor_for_aborted_transactions: Option<u64>,
1543
1544    /// The max computation bucket for gas. This is the max that can be charged for computation.
1545    max_gas_computation_bucket: Option<u64>,
1546
1547    // Define the value used to round up computation gas charges
1548    gas_rounding_step: Option<u64>,
1549
1550    /// Maximum number of nested loops. Enforced by the Move bytecode verifier.
1551    max_loop_depth: Option<u64>,
1552
1553    /// Maximum number of type arguments that can be bound to generic type parameters. Enforced by the Move bytecode verifier.
1554    max_generic_instantiation_length: Option<u64>,
1555
1556    /// Maximum number of parameters that a Move function can have. Enforced by the Move bytecode verifier.
1557    max_function_parameters: Option<u64>,
1558
1559    /// Maximum number of basic blocks that a Move function can have. Enforced by the Move bytecode verifier.
1560    max_basic_blocks: Option<u64>,
1561
1562    /// Maximum stack size value. Enforced by the Move bytecode verifier.
1563    max_value_stack_size: Option<u64>,
1564
1565    /// Maximum number of "type nodes", a metric for how big a SignatureToken will be when expanded into a fully qualified type. Enforced by the Move bytecode verifier.
1566    max_type_nodes: Option<u64>,
1567
1568    /// Maximum number of "type nodes" that can be instantiated in a single function.
1569    max_generic_instantiation_type_nodes_per_function: Option<u64>,
1570
1571    /// Maximum number of "type nodes" that can be instantiated in a module.
1572    max_generic_instantiation_type_nodes_per_module: Option<u64>,
1573
1574    /// Maximum number of "type nodes" allowed in an accumulator.
1575    max_accumulator_type_nodes: Option<u64>,
1576
1577    /// Maximum number of push instructions in one function. Enforced by the Move bytecode verifier.
1578    max_push_size: Option<u64>,
1579
1580    /// Maximum number of struct definitions in a module. Enforced by the Move bytecode verifier.
1581    max_struct_definitions: Option<u64>,
1582
1583    /// Maximum number of function definitions in a module. Enforced by the Move bytecode verifier.
1584    max_function_definitions: Option<u64>,
1585
1586    /// Maximum number of fields allowed in a struct definition. Enforced by the Move bytecode verifier.
1587    max_fields_in_struct: Option<u64>,
1588
1589    /// Maximum dependency depth. Enforced by the Move linker when loading dependent modules.
1590    max_dependency_depth: Option<u64>,
1591
1592    /// Maximum number of Move events that a single transaction can emit. Enforced by the VM during execution.
1593    max_num_event_emit: Option<u64>,
1594
1595    /// Maximum number of new IDs that a single transaction can create. Enforced by the VM during execution.
1596    max_num_new_move_object_ids: Option<u64>,
1597
1598    /// Maximum number of new IDs that a single system transaction can create. Enforced by the VM during execution.
1599    max_num_new_move_object_ids_system_tx: Option<u64>,
1600
1601    /// Maximum number of IDs that a single transaction can delete. Enforced by the VM during execution.
1602    max_num_deleted_move_object_ids: Option<u64>,
1603
1604    /// Maximum number of IDs that a single system transaction can delete. Enforced by the VM during execution.
1605    max_num_deleted_move_object_ids_system_tx: Option<u64>,
1606
1607    /// Maximum number of IDs that a single transaction can transfer. Enforced by the VM during execution.
1608    max_num_transferred_move_object_ids: Option<u64>,
1609
1610    /// Maximum number of IDs that a single system transaction can transfer. Enforced by the VM during execution.
1611    max_num_transferred_move_object_ids_system_tx: Option<u64>,
1612
1613    /// Maximum size of a Move user event. Enforced by the VM during execution.
1614    max_event_emit_size: Option<u64>,
1615
1616    /// Maximum size of a Move user event. Enforced by the VM during execution.
1617    max_event_emit_size_total: Option<u64>,
1618
1619    /// Maximum length of a vector in Move. Enforced by the VM during execution, and for constants, by the verifier.
1620    max_move_vector_len: Option<u64>,
1621
1622    /// Maximum length of an `Identifier` in Move. Enforced by the bytecode verifier at signing.
1623    max_move_identifier_len: Option<u64>,
1624
1625    /// Maximum depth of a Move value within the VM.
1626    max_move_value_depth: Option<u64>,
1627
1628    /// Maximum number of bytes a single package's arena may allocate when the package is loaded
1629    /// into the VM. If unset, the VM uses its built-in default.
1630    package_arena_size_in_bytes: Option<u64>,
1631
1632    /// Maximum number of variants in an enum. Enforced by the bytecode verifier at signing.
1633    max_move_enum_variants: Option<u64>,
1634
1635    /// Maximum number of back edges in Move function. Enforced by the bytecode verifier at signing.
1636    max_back_edges_per_function: Option<u64>,
1637
1638    /// Maximum number of back edges in Move module. Enforced by the bytecode verifier at signing.
1639    max_back_edges_per_module: Option<u64>,
1640
1641    /// Maximum number of meter `ticks` spent verifying a Move function. Enforced by the bytecode verifier at signing.
1642    max_verifier_meter_ticks_per_function: Option<u64>,
1643
1644    /// Maximum number of meter `ticks` spent verifying a Move module. Enforced by the bytecode verifier at signing.
1645    max_meter_ticks_per_module: Option<u64>,
1646
1647    /// Maximum number of meter `ticks` spent verifying a Move package. Enforced by the bytecode verifier at signing.
1648    max_meter_ticks_per_package: Option<u64>,
1649
1650    // === Object runtime internal operation limits ====
1651    // These affect dynamic fields
1652    /// Maximum number of cached objects in the object runtime ObjectStore. Enforced by object runtime during execution
1653    object_runtime_max_num_cached_objects: Option<u64>,
1654
1655    /// Maximum number of cached objects in the object runtime ObjectStore in system transaction. Enforced by object runtime during execution
1656    object_runtime_max_num_cached_objects_system_tx: Option<u64>,
1657
1658    /// Maximum number of stored objects accessed by object runtime ObjectStore. Enforced by object runtime during execution
1659    object_runtime_max_num_store_entries: Option<u64>,
1660
1661    /// Maximum number of stored objects accessed by object runtime ObjectStore in system transaction. Enforced by object runtime during execution
1662    object_runtime_max_num_store_entries_system_tx: Option<u64>,
1663
1664    // === Execution gas costs ====
1665    /// Base cost for any Sui transaction
1666    base_tx_cost_fixed: Option<u64>,
1667
1668    /// Additional cost for a transaction that publishes a package
1669    /// i.e., the base cost of such a transaction is base_tx_cost_fixed + package_publish_cost_fixed
1670    package_publish_cost_fixed: Option<u64>,
1671
1672    /// Cost per byte of a Move call transaction
1673    /// i.e., the cost of such a transaction is base_cost + (base_tx_cost_per_byte * size)
1674    base_tx_cost_per_byte: Option<u64>,
1675
1676    /// Cost per byte for a transaction that publishes a package
1677    package_publish_cost_per_byte: Option<u64>,
1678
1679    // Per-byte cost of reading an object during transaction execution
1680    obj_access_cost_read_per_byte: Option<u64>,
1681
1682    // Per-byte cost of writing an object during transaction execution
1683    obj_access_cost_mutate_per_byte: Option<u64>,
1684
1685    // Per-byte cost of deleting an object during transaction execution
1686    obj_access_cost_delete_per_byte: Option<u64>,
1687
1688    /// Per-byte cost charged for each input object to a transaction.
1689    /// Meant to approximate the cost of checking locks for each object
1690    // TODO: Option<I'm not sure that this cost makes sense. Checking locks is "free"
1691    // in the sense that an invalid tx that can never be committed/pay gas can
1692    // force validators to check an arbitrary number of locks. If those checks are
1693    // "free" for invalid transactions, why charge for them in valid transactions
1694    // TODO: Option<if we keep this, I think we probably want it to be a fixed cost rather
1695    // than a per-byte cost. checking an object lock should not require loading an
1696    // entire object, just consulting an ID -> tx digest map
1697    obj_access_cost_verify_per_byte: Option<u64>,
1698
1699    // Maximal nodes which are allowed when converting to a type layout.
1700    max_type_to_layout_nodes: Option<u64>,
1701
1702    // Maximal size in bytes that a PTB value can be
1703    max_ptb_value_size: Option<u64>,
1704
1705    // === Gas version. gas model ===
1706    /// Gas model version, what code we are using to charge gas
1707    gas_model_version: Option<u64>,
1708
1709    // === Storage gas costs ===
1710    /// Per-byte cost of storing an object in the Sui global object store. Some of this cost may be refundable if the object is later freed
1711    obj_data_cost_refundable: Option<u64>,
1712
1713    // Per-byte cost of storing an object in the Sui transaction log (e.g., in CertifiedTransactionEffects)
1714    // This depends on the size of various fields including the effects
1715    // TODO: Option<I don't fully understand this^ and more details would be useful
1716    obj_metadata_cost_non_refundable: Option<u64>,
1717
1718    // === Tokenomics ===
1719
1720    // TODO: Option<this should be changed to u64.
1721    /// Sender of a txn that touches an object will get this percent of the storage rebate back.
1722    /// In basis point.
1723    storage_rebate_rate: Option<u64>,
1724
1725    /// 5% of the storage fund's share of rewards are reinvested into the storage fund.
1726    /// In basis point.
1727    storage_fund_reinvest_rate: Option<u64>,
1728
1729    /// The share of rewards that will be slashed and redistributed is 50%.
1730    /// In basis point.
1731    reward_slashing_rate: Option<u64>,
1732
1733    /// Unit gas price, Mist per internal gas unit.
1734    storage_gas_price: Option<u64>,
1735
1736    /// Per-object storage cost for accumulator objects, used during end-of-epoch accounting.
1737    accumulator_object_storage_cost: Option<u64>,
1738
1739    // === Core Protocol ===
1740    /// Max number of transactions per checkpoint.
1741    /// Note that this is a protocol constant and not a config as validators must have this set to
1742    /// the same value, otherwise they *will* fork.
1743    max_transactions_per_checkpoint: Option<u64>,
1744
1745    /// Max size of a checkpoint in bytes.
1746    /// Note that this is a protocol constant and not a config as validators must have this set to
1747    /// the same value, otherwise they *will* fork.
1748    max_checkpoint_size_bytes: Option<u64>,
1749
1750    /// A protocol upgrade always requires 2f+1 stake to agree. We support a buffer of additional
1751    /// stake (as a fraction of f, expressed in basis points) that is required before an upgrade
1752    /// can happen automatically. 10000bps would indicate that complete unanimity is required (all
1753    /// 3f+1 must vote), while 0bps would indicate that 2f+1 is sufficient.
1754    buffer_stake_for_protocol_upgrade_bps: Option<u64>,
1755
1756    // === Native Function Costs ===
1757
1758    // `address` module
1759    // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
1760    address_from_bytes_cost_base: Option<u64>,
1761    // Cost params for the Move native function `address::to_u256(address): u256`
1762    address_to_u256_cost_base: Option<u64>,
1763    // Cost params for the Move native function `address::from_u256(u256): address`
1764    address_from_u256_cost_base: Option<u64>,
1765
1766    // `config` module
1767    // Cost params for the Move native function `read_setting_impl<Name: copy + drop + store,
1768    // SettingValue: key + store, SettingDataValue: store, Value: copy + drop + store,
1769    // >(config: address, name: address, current_epoch: u64): Option<Value>`
1770    config_read_setting_impl_cost_base: Option<u64>,
1771    config_read_setting_impl_cost_per_byte: Option<u64>,
1772
1773    package_original_package_id_impl_cost_base: Option<u64>,
1774    package_original_package_id_impl_cost_per_byte: Option<u64>,
1775
1776    // `dynamic_field` module
1777    // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address`
1778    dynamic_field_hash_type_and_key_cost_base: Option<u64>,
1779    dynamic_field_hash_type_and_key_type_cost_per_byte: Option<u64>,
1780    dynamic_field_hash_type_and_key_value_cost_per_byte: Option<u64>,
1781    dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Option<u64>,
1782    // Cost params for the Move native function `add_child_object<Child: key>(parent: address, child: Child)`
1783    dynamic_field_add_child_object_cost_base: Option<u64>,
1784    dynamic_field_add_child_object_type_cost_per_byte: Option<u64>,
1785    dynamic_field_add_child_object_value_cost_per_byte: Option<u64>,
1786    dynamic_field_add_child_object_struct_tag_cost_per_byte: Option<u64>,
1787    // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut UID, id: address): &mut Child`
1788    dynamic_field_borrow_child_object_cost_base: Option<u64>,
1789    dynamic_field_borrow_child_object_child_ref_cost_per_byte: Option<u64>,
1790    dynamic_field_borrow_child_object_type_cost_per_byte: Option<u64>,
1791    // Cost params for the Move native function `remove_child_object<Child: key>(parent: address, id: address): Child`
1792    dynamic_field_remove_child_object_cost_base: Option<u64>,
1793    dynamic_field_remove_child_object_child_cost_per_byte: Option<u64>,
1794    dynamic_field_remove_child_object_type_cost_per_byte: Option<u64>,
1795    // Cost params for the Move native function `has_child_object(parent: address, id: address): bool`
1796    dynamic_field_has_child_object_cost_base: Option<u64>,
1797    // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent: address, id: address): bool`
1798    dynamic_field_has_child_object_with_ty_cost_base: Option<u64>,
1799    dynamic_field_has_child_object_with_ty_type_cost_per_byte: Option<u64>,
1800    dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Option<u64>,
1801
1802    // `scratch` module
1803    // Cost params for the Move native function `add_impl<V: drop>(key: address, value: V)`
1804    scratch_add_cost_base: Option<u64>,
1805    // Cost params for the Move native function `read_impl<V: copy + drop>(key: address): V`
1806    scratch_read_cost_base: Option<u64>,
1807    scratch_read_value_cost: Option<u64>,
1808    // Cost params for the Move native function `remove_impl<V: drop>(key: address): V`
1809    scratch_remove_cost_base: Option<u64>,
1810    // Cost params for the Move native function `exists_impl(key: address): bool`
1811    scratch_exists_cost_base: Option<u64>,
1812    // Cost params for the Move native function `exists_with_type_impl<V: drop>(key: address): bool`
1813    scratch_exists_with_type_cost_base: Option<u64>,
1814    scratch_exists_with_type_type_cost: Option<u64>,
1815    // Maximum number of entries in the per-transaction `sui::scratch` store.
1816    max_scratch_pad_size: Option<u64>,
1817
1818    // `event` module
1819    // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
1820    event_emit_cost_base: Option<u64>,
1821    event_emit_value_size_derivation_cost_per_byte: Option<u64>,
1822    event_emit_tag_size_derivation_cost_per_byte: Option<u64>,
1823    event_emit_output_cost_per_byte: Option<u64>,
1824    event_emit_auth_stream_cost: Option<u64>,
1825
1826    // `funds_accumulator` module
1827    // Base cost for reserving object funds for withdrawal.
1828    reserve_object_funds_for_withdrawal_cost_base: Option<u64>,
1829    // Cost of loading an object's settled balance on the first withdrawal for an owner and type.
1830    reserve_object_funds_for_withdrawal_cold_read_cost: Option<u64>,
1831
1832    //  `object` module
1833    // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
1834    object_borrow_uid_cost_base: Option<u64>,
1835    // Cost params for the Move native function `delete_impl(id: address)`
1836    object_delete_impl_cost_base: Option<u64>,
1837    // Cost params for the Move native function `record_new_uid(id: address)`
1838    object_record_new_uid_cost_base: Option<u64>,
1839    // Cost params for the Move native function
1840    // `record_new_uid_from_hash(parent: address, bytes: address)`
1841    object_record_new_uid_from_hash_cost_base: Option<u64>,
1842
1843    // Transfer
1844    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1845    transfer_transfer_internal_cost_base: Option<u64>,
1846    // Cost params for the Move native function `party_transfer_impl<T: key>(obj: T, party_members: vector<address>)`
1847    transfer_party_transfer_internal_cost_base: Option<u64>,
1848    // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
1849    transfer_freeze_object_cost_base: Option<u64>,
1850    // Cost params for the Move native function `share_object<T: key>(obj: T)`
1851    transfer_share_object_cost_base: Option<u64>,
1852    // Cost params for the Move native function
1853    // `receive_object<T: key>(p: &mut UID, recv: Receiving<T>T)`
1854    transfer_receive_object_cost_base: Option<u64>,
1855    transfer_receive_object_cost_per_byte: Option<u64>,
1856    transfer_receive_object_type_cost_per_byte: Option<u64>,
1857
1858    // TxContext
1859    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1860    tx_context_derive_id_cost_base: Option<u64>,
1861    tx_context_fresh_id_cost_base: Option<u64>,
1862    tx_context_sender_cost_base: Option<u64>,
1863    tx_context_epoch_cost_base: Option<u64>,
1864    tx_context_epoch_timestamp_ms_cost_base: Option<u64>,
1865    tx_context_sponsor_cost_base: Option<u64>,
1866    tx_context_rgp_cost_base: Option<u64>,
1867    tx_context_gas_price_cost_base: Option<u64>,
1868    tx_context_gas_budget_cost_base: Option<u64>,
1869    tx_context_ids_created_cost_base: Option<u64>,
1870    tx_context_replace_cost_base: Option<u64>,
1871
1872    // Types
1873    // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
1874    types_is_one_time_witness_cost_base: Option<u64>,
1875    types_is_one_time_witness_type_tag_cost_per_byte: Option<u64>,
1876    types_is_one_time_witness_type_cost_per_byte: Option<u64>,
1877
1878    // Validator
1879    // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
1880    validator_validate_metadata_cost_base: Option<u64>,
1881    validator_validate_metadata_data_cost_per_byte: Option<u64>,
1882
1883    // Crypto natives
1884    crypto_invalid_arguments_cost: Option<u64>,
1885    // bls12381::bls12381_min_sig_verify
1886    bls12381_bls12381_min_sig_verify_cost_base: Option<u64>,
1887    bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Option<u64>,
1888    bls12381_bls12381_min_sig_verify_msg_cost_per_block: Option<u64>,
1889
1890    // bls12381::bls12381_min_pk_verify
1891    bls12381_bls12381_min_pk_verify_cost_base: Option<u64>,
1892    bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Option<u64>,
1893    bls12381_bls12381_min_pk_verify_msg_cost_per_block: Option<u64>,
1894
1895    // ecdsa_k1::ecrecover
1896    ecdsa_k1_ecrecover_keccak256_cost_base: Option<u64>,
1897    ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1898    ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1899    ecdsa_k1_ecrecover_sha256_cost_base: Option<u64>,
1900    ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1901    ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1902
1903    // ecdsa_k1::decompress_pubkey
1904    ecdsa_k1_decompress_pubkey_cost_base: Option<u64>,
1905
1906    // ecdsa_k1::secp256k1_verify
1907    ecdsa_k1_secp256k1_verify_keccak256_cost_base: Option<u64>,
1908    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1909    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Option<u64>,
1910    ecdsa_k1_secp256k1_verify_sha256_cost_base: Option<u64>,
1911    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Option<u64>,
1912    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Option<u64>,
1913
1914    // ecdsa_r1::ecrecover
1915    ecdsa_r1_ecrecover_keccak256_cost_base: Option<u64>,
1916    ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1917    ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1918    ecdsa_r1_ecrecover_sha256_cost_base: Option<u64>,
1919    ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1920    ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1921
1922    // ecdsa_r1::secp256k1_verify
1923    ecdsa_r1_secp256r1_verify_keccak256_cost_base: Option<u64>,
1924    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1925    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Option<u64>,
1926    ecdsa_r1_secp256r1_verify_sha256_cost_base: Option<u64>,
1927    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Option<u64>,
1928    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Option<u64>,
1929
1930    // ecvrf::verify
1931    ecvrf_ecvrf_verify_cost_base: Option<u64>,
1932    ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Option<u64>,
1933    ecvrf_ecvrf_verify_alpha_string_cost_per_block: Option<u64>,
1934
1935    // ed25519
1936    ed25519_ed25519_verify_cost_base: Option<u64>,
1937    ed25519_ed25519_verify_msg_cost_per_byte: Option<u64>,
1938    ed25519_ed25519_verify_msg_cost_per_block: Option<u64>,
1939
1940    // groth16::prepare_verifying_key
1941    groth16_prepare_verifying_key_bls12381_cost_base: Option<u64>,
1942    groth16_prepare_verifying_key_bn254_cost_base: Option<u64>,
1943
1944    // groth16::verify_groth16_proof_internal
1945    groth16_verify_groth16_proof_internal_bls12381_cost_base: Option<u64>,
1946    groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Option<u64>,
1947    groth16_verify_groth16_proof_internal_bn254_cost_base: Option<u64>,
1948    groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Option<u64>,
1949    groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Option<u64>,
1950
1951    // hash::blake2b256
1952    hash_blake2b256_cost_base: Option<u64>,
1953    hash_blake2b256_data_cost_per_byte: Option<u64>,
1954    hash_blake2b256_data_cost_per_block: Option<u64>,
1955
1956    // hash::keccak256
1957    hash_keccak256_cost_base: Option<u64>,
1958    hash_keccak256_data_cost_per_byte: Option<u64>,
1959    hash_keccak256_data_cost_per_block: Option<u64>,
1960
1961    // poseidon::poseidon_bn254
1962    poseidon_bn254_cost_base: Option<u64>,
1963    poseidon_bn254_cost_per_block: Option<u64>,
1964
1965    // group_ops
1966    group_ops_bls12381_decode_scalar_cost: Option<u64>,
1967    group_ops_bls12381_decode_g1_cost: Option<u64>,
1968    group_ops_bls12381_decode_g2_cost: Option<u64>,
1969    group_ops_bls12381_decode_gt_cost: Option<u64>,
1970    group_ops_bls12381_scalar_add_cost: Option<u64>,
1971    group_ops_bls12381_g1_add_cost: Option<u64>,
1972    group_ops_bls12381_g2_add_cost: Option<u64>,
1973    group_ops_bls12381_gt_add_cost: Option<u64>,
1974    group_ops_bls12381_scalar_sub_cost: Option<u64>,
1975    group_ops_bls12381_g1_sub_cost: Option<u64>,
1976    group_ops_bls12381_g2_sub_cost: Option<u64>,
1977    group_ops_bls12381_gt_sub_cost: Option<u64>,
1978    group_ops_bls12381_scalar_mul_cost: Option<u64>,
1979    group_ops_bls12381_g1_mul_cost: Option<u64>,
1980    group_ops_bls12381_g2_mul_cost: Option<u64>,
1981    group_ops_bls12381_gt_mul_cost: Option<u64>,
1982    group_ops_bls12381_scalar_div_cost: Option<u64>,
1983    group_ops_bls12381_g1_div_cost: Option<u64>,
1984    group_ops_bls12381_g2_div_cost: Option<u64>,
1985    group_ops_bls12381_gt_div_cost: Option<u64>,
1986    group_ops_bls12381_g1_hash_to_base_cost: Option<u64>,
1987    group_ops_bls12381_g2_hash_to_base_cost: Option<u64>,
1988    group_ops_bls12381_g1_hash_to_cost_per_byte: Option<u64>,
1989    group_ops_bls12381_g2_hash_to_cost_per_byte: Option<u64>,
1990    group_ops_bls12381_g1_msm_base_cost: Option<u64>,
1991    group_ops_bls12381_g2_msm_base_cost: Option<u64>,
1992    group_ops_bls12381_g1_msm_base_cost_per_input: Option<u64>,
1993    group_ops_bls12381_g2_msm_base_cost_per_input: Option<u64>,
1994    group_ops_bls12381_msm_max_len: Option<u32>,
1995    group_ops_bls12381_pairing_cost: Option<u64>,
1996    group_ops_bls12381_g1_to_uncompressed_g1_cost: Option<u64>,
1997    group_ops_bls12381_uncompressed_g1_to_g1_cost: Option<u64>,
1998    group_ops_bls12381_uncompressed_g1_sum_base_cost: Option<u64>,
1999    group_ops_bls12381_uncompressed_g1_sum_cost_per_term: Option<u64>,
2000    group_ops_bls12381_uncompressed_g1_sum_max_terms: Option<u64>,
2001
2002    group_ops_ristretto_decode_scalar_cost: Option<u64>,
2003    group_ops_ristretto_decode_point_cost: Option<u64>,
2004    group_ops_ristretto_scalar_add_cost: Option<u64>,
2005    group_ops_ristretto_point_add_cost: Option<u64>,
2006    group_ops_ristretto_scalar_sub_cost: Option<u64>,
2007    group_ops_ristretto_point_sub_cost: Option<u64>,
2008    group_ops_ristretto_scalar_mul_cost: Option<u64>,
2009    group_ops_ristretto_point_mul_cost: Option<u64>,
2010    group_ops_ristretto_scalar_div_cost: Option<u64>,
2011    group_ops_ristretto_point_div_cost: Option<u64>,
2012
2013    verify_bulletproofs_ristretto255_base_cost: Option<u64>,
2014    verify_bulletproofs_ristretto255_cost_per_bit_and_commitment: Option<u64>,
2015    // Upper bound on batch size * range in bits for a bulletproofs range proof. Defaults to 512
2016    // when unset.
2017    max_bulletproofs_total_bits: Option<u64>,
2018
2019    // hmac::hmac_sha3_256
2020    hmac_hmac_sha3_256_cost_base: Option<u64>,
2021    hmac_hmac_sha3_256_input_cost_per_byte: Option<u64>,
2022    hmac_hmac_sha3_256_input_cost_per_block: Option<u64>,
2023
2024    // zklogin::check_zklogin_id
2025    check_zklogin_id_cost_base: Option<u64>,
2026    // zklogin::check_zklogin_issuer
2027    check_zklogin_issuer_cost_base: Option<u64>,
2028
2029    vdf_verify_vdf_cost: Option<u64>,
2030    vdf_hash_to_input_cost: Option<u64>,
2031
2032    // nitro_attestation::load_nitro_attestation
2033    nitro_attestation_parse_base_cost: Option<u64>,
2034    nitro_attestation_parse_cost_per_byte: Option<u64>,
2035    nitro_attestation_verify_base_cost: Option<u64>,
2036    nitro_attestation_verify_cost_per_cert: Option<u64>,
2037
2038    // Stdlib costs
2039    bcs_per_byte_serialized_cost: Option<u64>,
2040    bcs_legacy_min_output_size_cost: Option<u64>,
2041    bcs_failure_cost: Option<u64>,
2042
2043    hash_sha2_256_base_cost: Option<u64>,
2044    hash_sha2_256_per_byte_cost: Option<u64>,
2045    hash_sha2_256_legacy_min_input_len_cost: Option<u64>,
2046    hash_sha3_256_base_cost: Option<u64>,
2047    hash_sha3_256_per_byte_cost: Option<u64>,
2048    hash_sha3_256_legacy_min_input_len_cost: Option<u64>,
2049    type_name_get_base_cost: Option<u64>,
2050    type_name_get_per_byte_cost: Option<u64>,
2051    type_name_id_base_cost: Option<u64>,
2052
2053    string_check_utf8_base_cost: Option<u64>,
2054    string_check_utf8_per_byte_cost: Option<u64>,
2055    string_is_char_boundary_base_cost: Option<u64>,
2056    string_sub_string_base_cost: Option<u64>,
2057    string_sub_string_per_byte_cost: Option<u64>,
2058    string_index_of_base_cost: Option<u64>,
2059    string_index_of_per_byte_pattern_cost: Option<u64>,
2060    string_index_of_per_byte_searched_cost: Option<u64>,
2061
2062    vector_empty_base_cost: Option<u64>,
2063    vector_length_base_cost: Option<u64>,
2064    vector_push_back_base_cost: Option<u64>,
2065    vector_push_back_legacy_per_abstract_memory_unit_cost: Option<u64>,
2066    vector_borrow_base_cost: Option<u64>,
2067    vector_pop_back_base_cost: Option<u64>,
2068    vector_destroy_empty_base_cost: Option<u64>,
2069    vector_swap_base_cost: Option<u64>,
2070    debug_print_base_cost: Option<u64>,
2071    debug_print_stack_trace_base_cost: Option<u64>,
2072
2073    // ==== Ephemeral (consensus only) params deleted ====
2074    //
2075    // Const params for consensus scoring decision
2076    // The scaling factor property for the MED outlier detection
2077    // scoring_decision_mad_divisor: Option<f64>,
2078    // The cutoff value for the MED outlier detection
2079    // scoring_decision_cutoff_value: Option<f64>,
2080    /// === Execution Version ===
2081    // custom_setter: see `set_execution_version_for_testing`, which forbids downgrades.
2082    #[custom_setter]
2083    execution_version: Option<u64>,
2084
2085    // Dictates the threshold (percentage of stake) that is used to calculate the "bad" nodes to be
2086    // swapped when creating the consensus schedule. The values should be of the range [0 - 33]. Anything
2087    // above 33 (f) will not be allowed.
2088    consensus_bad_nodes_stake_threshold: Option<u64>,
2089
2090    max_jwk_votes_per_validator_per_epoch: Option<u64>,
2091    // The maximum age of a JWK in epochs before it is removed from the AuthenticatorState object.
2092    // Applied at the end of an epoch as a delta from the new epoch value, so setting this to 1
2093    // will cause the new epoch to start with JWKs from the previous epoch still valid.
2094    max_age_of_jwk_in_epochs: Option<u64>,
2095
2096    // === random beacon ===
2097    /// Maximum allowed precision loss when reducing voting weights for the random beacon
2098    /// protocol.
2099    random_beacon_reduction_allowed_delta: Option<u16>,
2100
2101    /// Minimum number of shares below which voting weights will not be reduced for the
2102    /// random beacon protocol.
2103    random_beacon_reduction_lower_bound: Option<u32>,
2104
2105    /// Consensus Round after which DKG should be aborted and randomness disabled for
2106    /// the epoch, if it hasn't already completed.
2107    random_beacon_dkg_timeout_round: Option<u32>,
2108
2109    /// Minimum interval between consecutive rounds of generated randomness.
2110    random_beacon_min_round_interval_ms: Option<u64>,
2111
2112    /// Version of the random beacon DKG protocol.
2113    /// 0 was deprecated (and currently not supported), 1 is the default version.
2114    random_beacon_dkg_version: Option<u64>,
2115
2116    /// The maximum serialised transaction size (in bytes) accepted by consensus. That should be bigger than the
2117    /// `max_tx_size_bytes` with some additional headroom.
2118    consensus_max_transaction_size_bytes: Option<u64>,
2119    /// The maximum size of transactions included in a consensus block.
2120    consensus_max_transactions_in_block_bytes: Option<u64>,
2121    /// The maximum number of transactions included in a consensus block.
2122    consensus_max_num_transactions_in_block: Option<u64>,
2123
2124    /// The maximum number of rounds where transaction voting is allowed.
2125    consensus_voting_rounds: Option<u32>,
2126
2127    /// DEPRECATED. Do not use.
2128    max_accumulated_txn_cost_per_object_in_narwhal_commit: Option<u64>,
2129
2130    /// The max number of consensus rounds a transaction can be deferred due to shared object congestion.
2131    /// Transactions will be cancelled after this many rounds.
2132    max_deferral_rounds_for_congestion_control: Option<u64>,
2133
2134    /// Time after the scheduled epoch end (`next_reconfiguration_timestamp_ms`) at which epoch
2135    /// close stops waiting for deferred transactions to drain: the epoch is closed even if
2136    /// deferred transactions remain unscheduled. They are abandoned and can be resubmitted in the
2137    /// next epoch. When unset, epoch close waits indefinitely.
2138    epoch_close_deadline_ms: Option<u64>,
2139
2140    /// DEPRECATED. Do not use.
2141    max_txn_cost_overage_per_object_in_commit: Option<u64>,
2142
2143    /// DEPRECATED. Do not use.
2144    allowed_txn_cost_overage_burst_per_object_in_commit: Option<u64>,
2145
2146    /// Minimum interval of commit timestamps between consecutive checkpoints.
2147    min_checkpoint_interval_ms: Option<u64>,
2148
2149    /// Version number to use for version_specific_data in `CheckpointSummary`.
2150    checkpoint_summary_version_specific_data: Option<u64>,
2151
2152    /// The max number of transactions that can be included in a single Soft Bundle.
2153    max_soft_bundle_size: Option<u64>,
2154
2155    /// Whether to try to form bridge committee
2156    // Note: this is not a feature flag because we want to distinguish between
2157    // `None` and `Some(false)`, as committee was already finalized on Testnet.
2158    bridge_should_try_to_finalize_committee: Option<bool>,
2159
2160    /// The max accumulated txn execution cost per object in a mysticeti. Transactions
2161    /// in a commit will be deferred once their touch shared objects hit this limit,
2162    /// unless the selected congestion control mode allows overage.
2163    /// This config plays the same role as `max_accumulated_txn_cost_per_object_in_narwhal_commit`
2164    /// but for mysticeti commits due to that mysticeti has higher commit rate.
2165    max_accumulated_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
2166
2167    /// As above, but separate per-commit budget for transactions that use randomness.
2168    /// If not configured, uses the setting for `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
2169    max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
2170
2171    /// Configures the garbage collection depth for consensus. When is unset or `0` then the garbage collection
2172    /// is disabled.
2173    consensus_gc_depth: Option<u32>,
2174
2175    /// DEPRECATED. Do not use.
2176    gas_budget_based_txn_cost_cap_factor: Option<u64>,
2177
2178    /// DEPRECATED. Do not use.
2179    gas_budget_based_txn_cost_absolute_cap_commit_count: Option<u64>,
2180
2181    /// SIP-45: K in the formula `amplification_factor = max(0, gas_price / reference_gas_price - K)`.
2182    /// This is the threshold for activating consensus amplification.
2183    sip_45_consensus_amplification_threshold: Option<u64>,
2184
2185    /// DEPRECATED: this was an ephemeral feature flag only used in per-epoch tables, which has now
2186    /// been deployed everywhere.
2187    use_object_per_epoch_marker_table_v2: Option<bool>,
2188
2189    /// The number of commits to consider when computing a deterministic commit rate.
2190    consensus_commit_rate_estimation_window_size: Option<u32>,
2191
2192    /// A list of effective AliasedAddress.
2193    /// For each pair, `aliased` is allowed to act as `original` for any of the transaction digests
2194    /// listed in `tx_digests`
2195    #[serde(skip_serializing_if = "Vec::is_empty")]
2196    aliased_addresses: Vec<AliasedAddress>,
2197
2198    /// The base charge for each command in a programmable transaction. This is a fixed cost to
2199    /// account for the overhead of processing each command.
2200    translation_per_command_base_charge: Option<u64>,
2201
2202    /// The base charge for each input in a programmable transaction regardless of if it is used or
2203    /// not, or a pure/object/funds withdrawal input.
2204    translation_per_input_base_charge: Option<u64>,
2205
2206    /// The base charge for each byte of pure input in a programmable transaction.
2207    translation_pure_input_per_byte_charge: Option<u64>,
2208
2209    /// The multiplier for the number of type nodes when charging for type loading.
2210    /// This is multiplied by the number of type nodes to get the total cost.
2211    /// This should be a small number to avoid excessive gas costs for loading types.
2212    translation_per_type_node_charge: Option<u64>,
2213
2214    /// The multiplier for the number of type references when charging for type checking and reference
2215    /// checking.
2216    translation_per_reference_node_charge: Option<u64>,
2217
2218    /// The multiplier for each linkage entry when charging for linkage tables that we have
2219    /// created.
2220    translation_per_linkage_entry_charge: Option<u64>,
2221
2222    /// The maximum number of updates per settlement transaction.
2223    max_updates_per_settlement_txn: Option<u32>,
2224
2225    /// Maximum computation units allowed for a gasless transaction.
2226    gasless_max_computation_units: Option<u64>,
2227
2228    /// Allowed token types for gasless transactions, with minimum transfer sizes per token.
2229    gasless_allowed_token_types: Option<Vec<(String, u64)>>,
2230
2231    /// Maximum number of unused Pure inputs allowed in a gasless transaction.
2232    /// Object and FundsWithdrawal inputs must always be used.
2233    /// When None, there is no limit (effectively unlimited).
2234    gasless_max_unused_inputs: Option<u64>,
2235
2236    /// Maximum size in bytes of each Pure input in a gasless transaction.
2237    /// When None, there is no limit (effectively unlimited).
2238    gasless_max_pure_input_bytes: Option<u64>,
2239
2240    /// Max tps for gasless transactions. Unlimited when unset, zero when set to zero.
2241    gasless_max_tps: Option<u64>,
2242
2243    #[serde(skip_serializing_if = "Option::is_none")]
2244    #[skip_accessor]
2245    include_special_package_amendments: Option<Arc<Amendments>>,
2246
2247    /// Maximum serialized size in bytes of a gasless transaction (SenderSignedData).
2248    /// Bounds the persistent storage impact of each admitted gasless transaction.
2249    gasless_max_tx_size_bytes: Option<u64>,
2250
2251    /// The multiplier for each live reference charging per-command. Only used when
2252    /// `allow_references_in_ptbs` is enabled.
2253    translation_per_live_reference_charge: Option<u64>,
2254
2255    /// The maximum number of live references while checking a command. Only used when
2256    /// `allow_references_in_ptbs` is enabled.
2257    max_ptb_live_references: Option<u64>,
2258
2259    /// The maximum number of references returned by a command. Only used when
2260    /// `allow_references_in_ptbs` is enabled.
2261    max_ptb_returned_references: Option<u64>,
2262
2263    /// The maximum number of references returned over the course of the transaction. Only used
2264    /// when `allow_references_in_ptbs` is enabled.
2265    max_ptb_total_returned_references: Option<u64>,
2266}
2267
2268/// An aliased address.
2269#[derive(Clone, Serialize, Deserialize, Debug)]
2270pub struct AliasedAddress {
2271    /// The original address.
2272    pub original: [u8; 32],
2273    /// An aliased address which is allowed to act as the original address.
2274    pub aliased: [u8; 32],
2275    /// A list of transaction digests for which the aliasing is allowed to be in effect.
2276    pub allowed_tx_digests: Vec<[u8; 32]>,
2277}
2278
2279// feature flags
2280impl ProtocolConfig {
2281    /// The chain this config was instantiated for (see the `chain` field).
2282    pub fn chain(&self) -> Chain {
2283        self.chain
2284    }
2285
2286    // Add checks for feature flag support here, e.g.:
2287    // pub fn check_new_protocol_feature_supported(&self) -> Result<(), Error> {
2288    //     if self.feature_flags.new_protocol_feature_supported {
2289    //         Ok(())
2290    //     } else {
2291    //         Err(Error(format!(
2292    //             "new_protocol_feature is not supported at {:?}",
2293    //             self.version
2294    //         )))
2295    //     }
2296    // }
2297
2298    pub fn check_package_upgrades_supported(&self) -> Result<(), Error> {
2299        if self.feature_flags.package_upgrades {
2300            Ok(())
2301        } else {
2302            Err(Error(format!(
2303                "package upgrades are not supported at {:?}",
2304                self.version
2305            )))
2306        }
2307    }
2308
2309    pub fn zklogin_supported_providers(&self) -> &BTreeSet<String> {
2310        &self.feature_flags.zklogin_supported_providers
2311    }
2312
2313    /// zkLogin circuit verify mode: 0 = v1 circuit only, 1 = v2 circuit with
2314    /// fallback to v1, 2 = v2 circuit only.
2315    pub fn zklogin_circuit_mode(&self) -> u64 {
2316        self.feature_flags.zklogin_circuit_mode
2317    }
2318
2319    pub fn consensus_transaction_ordering(&self) -> ConsensusTransactionOrdering {
2320        self.feature_flags.consensus_transaction_ordering
2321    }
2322
2323    pub fn enable_jwk_consensus_updates(&self) -> bool {
2324        let ret = self.feature_flags.enable_jwk_consensus_updates;
2325        if ret {
2326            // jwk updates required end-of-epoch transactions
2327            assert!(self.feature_flags.end_of_epoch_transaction_supported);
2328        }
2329        ret
2330    }
2331
2332    pub fn end_of_epoch_transaction_supported(&self) -> bool {
2333        let ret = self.feature_flags.end_of_epoch_transaction_supported;
2334        if !ret {
2335            // jwk updates required end-of-epoch transactions
2336            assert!(!self.feature_flags.enable_jwk_consensus_updates);
2337        }
2338        ret
2339    }
2340
2341    pub fn dkg_version(&self) -> u64 {
2342        // Version 0 was deprecated and removed, the default is 1 if not set.
2343        self.random_beacon_dkg_version.unwrap_or(1)
2344    }
2345
2346    pub fn bridge(&self) -> bool {
2347        let ret = self.feature_flags.bridge;
2348        if ret {
2349            // bridge required end-of-epoch transactions
2350            assert!(self.feature_flags.end_of_epoch_transaction_supported);
2351        }
2352        ret
2353    }
2354
2355    pub fn should_try_to_finalize_bridge_committee(&self) -> bool {
2356        if !self.bridge() {
2357            return false;
2358        }
2359        // In the older protocol version, always try to finalize the committee.
2360        self.bridge_should_try_to_finalize_committee.unwrap_or(true)
2361    }
2362
2363    pub fn zklogin_max_epoch_upper_bound_delta(&self) -> Option<u64> {
2364        self.feature_flags.zklogin_max_epoch_upper_bound_delta
2365    }
2366
2367    pub fn enable_allowances(&self) -> bool {
2368        self.feature_flags.enable_allowances && self.enable_accumulators()
2369    }
2370
2371    pub fn enable_coin_reservation_obj_refs(&self) -> bool {
2372        self.new_vm_enabled() && self.feature_flags.enable_coin_reservation_obj_refs
2373    }
2374
2375    pub fn enable_authenticated_event_streams(&self) -> bool {
2376        self.feature_flags.enable_authenticated_event_streams && self.enable_accumulators()
2377    }
2378
2379    pub fn per_object_congestion_control_mode(&self) -> PerObjectCongestionControlMode {
2380        self.feature_flags.per_object_congestion_control_mode
2381    }
2382
2383    pub fn consensus_choice(&self) -> ConsensusChoice {
2384        self.feature_flags.consensus_choice
2385    }
2386
2387    pub fn consensus_network(&self) -> ConsensusNetwork {
2388        self.feature_flags.consensus_network
2389    }
2390
2391    pub fn mysticeti_num_leaders_per_round(&self) -> Option<usize> {
2392        self.feature_flags.mysticeti_num_leaders_per_round
2393    }
2394
2395    pub fn max_transaction_size_bytes(&self) -> u64 {
2396        // Provide a default value if protocol config version is too low.
2397        self.consensus_max_transaction_size_bytes
2398            .unwrap_or(256 * 1024)
2399    }
2400
2401    pub fn max_transactions_in_block_bytes(&self) -> u64 {
2402        if cfg!(msim) {
2403            256 * 1024
2404        } else {
2405            self.consensus_max_transactions_in_block_bytes
2406                .unwrap_or(512 * 1024)
2407        }
2408    }
2409
2410    pub fn max_num_transactions_in_block(&self) -> u64 {
2411        if cfg!(msim) {
2412            8
2413        } else {
2414            self.consensus_max_num_transactions_in_block.unwrap_or(512)
2415        }
2416    }
2417
2418    pub fn gc_depth(&self) -> u32 {
2419        self.consensus_gc_depth.unwrap_or(0)
2420    }
2421
2422    pub fn consensus_linearize_subdag_v2(&self) -> bool {
2423        let res = self.feature_flags.consensus_linearize_subdag_v2;
2424        assert!(
2425            !res || self.gc_depth() > 0,
2426            "The consensus linearize sub dag V2 requires GC to be enabled"
2427        );
2428        res
2429    }
2430
2431    pub fn consensus_median_based_commit_timestamp(&self) -> bool {
2432        let res = self.feature_flags.consensus_median_based_commit_timestamp;
2433        assert!(
2434            !res || self.gc_depth() > 0,
2435            "The consensus median based commit timestamp requires GC to be enabled"
2436        );
2437        res
2438    }
2439
2440    pub fn get_consensus_commit_rate_estimation_window_size(&self) -> u32 {
2441        self.consensus_commit_rate_estimation_window_size
2442            .unwrap_or(0)
2443    }
2444
2445    pub fn consensus_num_requested_prior_commits_at_startup(&self) -> u32 {
2446        // Currently there is only one parameter driving this value. If there are multiple
2447        // things computed from prior consensus commits, this function must return the max
2448        // of all of them.
2449        let window_size = self.get_consensus_commit_rate_estimation_window_size();
2450        // Ensure we are not using past commits without recording a state digest in the prologue.
2451        assert!(window_size == 0 || self.record_additional_state_digest_in_prologue());
2452        window_size
2453    }
2454
2455    pub fn address_aliases(&self) -> bool {
2456        let address_aliases = self.feature_flags.address_aliases;
2457        assert!(
2458            !address_aliases || self.mysticeti_fastpath(),
2459            "Address aliases requires Mysticeti fastpath to be enabled"
2460        );
2461        if address_aliases {
2462            assert!(
2463                self.feature_flags.disable_preconsensus_locking,
2464                "Address aliases requires CertifiedTransaction to be disabled"
2465            );
2466        }
2467        address_aliases
2468    }
2469
2470    pub fn new_vm_enabled(&self) -> bool {
2471        self.execution_version.is_some_and(|v| v >= 4)
2472    }
2473
2474    pub fn gasless_allowed_token_types(&self) -> &[(String, u64)] {
2475        debug_assert!(self.gasless_allowed_token_types.is_some());
2476        self.gasless_allowed_token_types.as_deref().unwrap_or(&[])
2477    }
2478
2479    pub fn get_gasless_max_unused_inputs(&self) -> u64 {
2480        self.gasless_max_unused_inputs.unwrap_or(u64::MAX)
2481    }
2482
2483    pub fn get_gasless_max_pure_input_bytes(&self) -> u64 {
2484        self.gasless_max_pure_input_bytes.unwrap_or(u64::MAX)
2485    }
2486
2487    pub fn get_gasless_max_tx_size_bytes(&self) -> u64 {
2488        self.gasless_max_tx_size_bytes.unwrap_or(u64::MAX)
2489    }
2490
2491    pub fn include_special_package_amendments_as_option(&self) -> &Option<Arc<Amendments>> {
2492        &self.include_special_package_amendments
2493    }
2494}
2495
2496static POISON_VERSION_METHODS: AtomicBool = AtomicBool::new(false);
2497
2498// Instantiations for each protocol version.
2499impl ProtocolConfig {
2500    /// Get the value ProtocolConfig that are in effect during the given protocol version.
2501    pub fn get_for_version(version: ProtocolVersion, chain: Chain) -> Self {
2502        // ProtocolVersion can be deserialized so we need to check it here as well.
2503        assert!(
2504            version >= ProtocolVersion::MIN,
2505            "Network protocol version is {:?}, but the minimum supported version by the binary is {:?}. Please upgrade the binary.",
2506            version,
2507            ProtocolVersion::MIN.0,
2508        );
2509        assert!(
2510            version <= ProtocolVersion::MAX_ALLOWED,
2511            "Network protocol version is {:?}, but the maximum supported version by the binary is {:?}. Please upgrade the binary.",
2512            version,
2513            ProtocolVersion::MAX_ALLOWED.0,
2514        );
2515
2516        let mut ret = Self::get_for_version_impl(version, chain);
2517        ret.version = version;
2518        ret.chain = chain;
2519
2520        ret = Self::apply_config_override(version, ret);
2521
2522        if std::env::var("SUI_PROTOCOL_CONFIG_OVERRIDE_ENABLE").is_ok() {
2523            warn!(
2524                "overriding ProtocolConfig settings with custom settings; this may break non-local networks"
2525            );
2526            let overrides: ProtocolConfigOptional =
2527                serde_env::from_env_with_prefix("SUI_PROTOCOL_CONFIG_OVERRIDE")
2528                    .expect("failed to parse ProtocolConfig override env variables");
2529            overrides.apply_to(&mut ret);
2530        }
2531
2532        ret
2533    }
2534
2535    /// Get the value ProtocolConfig that are in effect during the given protocol version.
2536    /// Or none if the version is not supported.
2537    pub fn get_for_version_if_supported(version: ProtocolVersion, chain: Chain) -> Option<Self> {
2538        if version.0 >= ProtocolVersion::MIN.0 && version.0 <= ProtocolVersion::MAX_ALLOWED.0 {
2539            let mut ret = Self::get_for_version_impl(version, chain);
2540            ret.version = version;
2541            ret.chain = chain;
2542            ret = Self::apply_config_override(version, ret);
2543            Some(ret)
2544        } else {
2545            None
2546        }
2547    }
2548
2549    pub fn poison_get_for_min_version() {
2550        POISON_VERSION_METHODS.store(true, Ordering::Relaxed);
2551    }
2552
2553    fn load_poison_get_for_min_version() -> bool {
2554        POISON_VERSION_METHODS.load(Ordering::Relaxed)
2555    }
2556
2557    /// Convenience to get the constants at the current minimum supported version.
2558    /// Mainly used by client code that may not yet be protocol-version aware.
2559    pub fn get_for_min_version() -> Self {
2560        if Self::load_poison_get_for_min_version() {
2561            panic!("get_for_min_version called on validator");
2562        }
2563        ProtocolConfig::get_for_version(ProtocolVersion::MIN, Chain::Unknown)
2564    }
2565
2566    /// CAREFUL! - You probably want to use `get_for_version` instead.
2567    ///
2568    /// Convenience to get the constants at the current maximum supported version.
2569    /// Mainly used by genesis. Note well that this function uses the max version
2570    /// supported locally by the node, which is not necessarily the current version
2571    /// of the network. ALSO, this function disregards chain specific config (by
2572    /// using Chain::Unknown), thereby potentially returning a protocol config that
2573    /// is incorrect for some feature flags. Definitely safe for testing and for
2574    /// protocol version 11 and prior.
2575    #[allow(non_snake_case)]
2576    pub fn get_for_max_version_UNSAFE() -> Self {
2577        if Self::load_poison_get_for_min_version() {
2578            panic!("get_for_max_version_UNSAFE called on validator");
2579        }
2580        ProtocolConfig::get_for_version(ProtocolVersion::MAX, Chain::Unknown)
2581    }
2582
2583    fn get_for_version_impl(version: ProtocolVersion, chain: Chain) -> Self {
2584        #[cfg(msim)]
2585        {
2586            // populate the fake simulator version # with a different base tx cost.
2587            if version == ProtocolVersion::MAX_ALLOWED {
2588                let mut config = Self::get_for_version_impl(version - 1, Chain::Unknown);
2589                config.base_tx_cost_fixed = Some(config.base_tx_cost_fixed() + 1000);
2590                return config;
2591            }
2592        }
2593
2594        // IMPORTANT: Never modify the value of any constant for a pre-existing protocol version.
2595        // To change the values here you must create a new protocol version with the new values!
2596        let mut cfg = Self {
2597            // will be overwritten before being returned
2598            version,
2599            chain,
2600
2601            // All flags are disabled in V1
2602            feature_flags: Default::default(),
2603
2604            max_tx_size_bytes: Some(128 * 1024),
2605            // We need this number to be at least 100x less than `max_serialized_tx_effects_size_bytes`otherwise effects can be huge
2606            max_input_objects: Some(2048),
2607            max_serialized_tx_effects_size_bytes: Some(512 * 1024),
2608            max_serialized_tx_effects_size_bytes_system_tx: Some(512 * 1024 * 16),
2609            max_gas_payment_objects: Some(256),
2610            max_modules_in_publish: Some(128),
2611            max_package_dependencies: None,
2612            max_arguments: Some(512),
2613            max_type_arguments: Some(16),
2614            max_type_argument_depth: Some(16),
2615            max_pure_argument_size: Some(16 * 1024),
2616            max_programmable_tx_commands: Some(1024),
2617            move_binary_format_version: Some(6),
2618            min_move_binary_format_version: None,
2619            binary_module_handles: None,
2620            binary_struct_handles: None,
2621            binary_function_handles: None,
2622            binary_function_instantiations: None,
2623            binary_signatures: None,
2624            binary_constant_pool: None,
2625            binary_identifiers: None,
2626            binary_address_identifiers: None,
2627            binary_struct_defs: None,
2628            binary_struct_def_instantiations: None,
2629            binary_function_defs: None,
2630            binary_field_handles: None,
2631            binary_field_instantiations: None,
2632            binary_friend_decls: None,
2633            binary_enum_defs: None,
2634            binary_enum_def_instantiations: None,
2635            binary_variant_handles: None,
2636            binary_variant_instantiation_handles: None,
2637            max_move_object_size: Some(250 * 1024),
2638            max_move_package_size: Some(100 * 1024),
2639            max_publish_or_upgrade_per_ptb: None,
2640            max_tx_gas: Some(10_000_000_000),
2641            max_gas_price: Some(100_000),
2642            max_gas_price_rgp_factor_for_aborted_transactions: None,
2643            max_gas_computation_bucket: Some(5_000_000),
2644            max_loop_depth: Some(5),
2645            max_generic_instantiation_length: Some(32),
2646            max_function_parameters: Some(128),
2647            max_basic_blocks: Some(1024),
2648            max_value_stack_size: Some(1024),
2649            max_type_nodes: Some(256),
2650            max_generic_instantiation_type_nodes_per_function: None,
2651            max_generic_instantiation_type_nodes_per_module: None,
2652            max_accumulator_type_nodes: None,
2653            max_push_size: Some(10000),
2654            max_struct_definitions: Some(200),
2655            max_function_definitions: Some(1000),
2656            max_fields_in_struct: Some(32),
2657            max_dependency_depth: Some(100),
2658            max_num_event_emit: Some(256),
2659            max_num_new_move_object_ids: Some(2048),
2660            max_num_new_move_object_ids_system_tx: Some(2048 * 16),
2661            max_num_deleted_move_object_ids: Some(2048),
2662            max_num_deleted_move_object_ids_system_tx: Some(2048 * 16),
2663            max_num_transferred_move_object_ids: Some(2048),
2664            max_num_transferred_move_object_ids_system_tx: Some(2048 * 16),
2665            max_event_emit_size: Some(250 * 1024),
2666            max_move_vector_len: Some(256 * 1024),
2667            max_type_to_layout_nodes: None,
2668            max_ptb_value_size: None,
2669
2670            max_back_edges_per_function: Some(10_000),
2671            max_back_edges_per_module: Some(10_000),
2672            max_verifier_meter_ticks_per_function: Some(6_000_000),
2673            max_meter_ticks_per_module: Some(6_000_000),
2674            max_meter_ticks_per_package: None,
2675
2676            object_runtime_max_num_cached_objects: Some(1000),
2677            object_runtime_max_num_cached_objects_system_tx: Some(1000 * 16),
2678            object_runtime_max_num_store_entries: Some(1000),
2679            object_runtime_max_num_store_entries_system_tx: Some(1000 * 16),
2680            base_tx_cost_fixed: Some(110_000),
2681            package_publish_cost_fixed: Some(1_000),
2682            base_tx_cost_per_byte: Some(0),
2683            package_publish_cost_per_byte: Some(80),
2684            obj_access_cost_read_per_byte: Some(15),
2685            obj_access_cost_mutate_per_byte: Some(40),
2686            obj_access_cost_delete_per_byte: Some(40),
2687            obj_access_cost_verify_per_byte: Some(200),
2688            obj_data_cost_refundable: Some(100),
2689            obj_metadata_cost_non_refundable: Some(50),
2690            gas_model_version: Some(1),
2691            storage_rebate_rate: Some(9900),
2692            storage_fund_reinvest_rate: Some(500),
2693            reward_slashing_rate: Some(5000),
2694            storage_gas_price: Some(1),
2695            accumulator_object_storage_cost: None,
2696            max_transactions_per_checkpoint: Some(10_000),
2697            max_checkpoint_size_bytes: Some(30 * 1024 * 1024),
2698
2699            // For now, perform upgrades with a bare quorum of validators.
2700            // MUSTFIX: This number should be increased to at least 2000 (20%) for mainnet.
2701            buffer_stake_for_protocol_upgrade_bps: Some(0),
2702
2703            // === Native Function Costs ===
2704            // `address` module
2705            // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
2706            address_from_bytes_cost_base: Some(52),
2707            // Cost params for the Move native function `address::to_u256(address): u256`
2708            address_to_u256_cost_base: Some(52),
2709            // Cost params for the Move native function `address::from_u256(u256): address`
2710            address_from_u256_cost_base: Some(52),
2711
2712            // `config` module
2713            // Cost params for the Move native function `read_setting_impl``
2714            config_read_setting_impl_cost_base: None,
2715            config_read_setting_impl_cost_per_byte: None,
2716
2717            package_original_package_id_impl_cost_base: None,
2718            package_original_package_id_impl_cost_per_byte: None,
2719
2720            // `dynamic_field` module
2721            // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address`
2722            dynamic_field_hash_type_and_key_cost_base: Some(100),
2723            dynamic_field_hash_type_and_key_type_cost_per_byte: Some(2),
2724            dynamic_field_hash_type_and_key_value_cost_per_byte: Some(2),
2725            dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Some(2),
2726            // Cost params for the Move native function `add_child_object<Child: key>(parent: address, child: Child)`
2727            dynamic_field_add_child_object_cost_base: Some(100),
2728            dynamic_field_add_child_object_type_cost_per_byte: Some(10),
2729            dynamic_field_add_child_object_value_cost_per_byte: Some(10),
2730            dynamic_field_add_child_object_struct_tag_cost_per_byte: Some(10),
2731            // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut UID, id: address): &mut Child`
2732            dynamic_field_borrow_child_object_cost_base: Some(100),
2733            dynamic_field_borrow_child_object_child_ref_cost_per_byte: Some(10),
2734            dynamic_field_borrow_child_object_type_cost_per_byte: Some(10),
2735            // Cost params for the Move native function `remove_child_object<Child: key>(parent: address, id: address): Child`
2736            dynamic_field_remove_child_object_cost_base: Some(100),
2737            dynamic_field_remove_child_object_child_cost_per_byte: Some(2),
2738            dynamic_field_remove_child_object_type_cost_per_byte: Some(2),
2739            // Cost params for the Move native function `has_child_object(parent: address, id: address): bool`
2740            dynamic_field_has_child_object_cost_base: Some(100),
2741            // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent: address, id: address): bool`
2742            dynamic_field_has_child_object_with_ty_cost_base: Some(100),
2743            dynamic_field_has_child_object_with_ty_type_cost_per_byte: Some(2),
2744            dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Some(2),
2745
2746            // `scratch` module: introduced in protocol version 130
2747            scratch_add_cost_base: None,
2748            scratch_read_cost_base: None,
2749            scratch_read_value_cost: None,
2750            scratch_remove_cost_base: None,
2751            scratch_exists_cost_base: None,
2752            scratch_exists_with_type_cost_base: None,
2753            scratch_exists_with_type_type_cost: None,
2754            max_scratch_pad_size: None,
2755
2756            // `event` module
2757            // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
2758            event_emit_cost_base: Some(52),
2759            event_emit_value_size_derivation_cost_per_byte: Some(2),
2760            event_emit_tag_size_derivation_cost_per_byte: Some(5),
2761            event_emit_output_cost_per_byte: Some(10),
2762            event_emit_auth_stream_cost: None,
2763
2764            // `funds_accumulator` module: introduced in protocol version 137.
2765            reserve_object_funds_for_withdrawal_cost_base: None,
2766            reserve_object_funds_for_withdrawal_cold_read_cost: None,
2767
2768            //  `object` module
2769            // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
2770            object_borrow_uid_cost_base: Some(52),
2771            // Cost params for the Move native function `delete_impl(id: address)`
2772            object_delete_impl_cost_base: Some(52),
2773            // Cost params for the Move native function `record_new_uid(id: address)`
2774            object_record_new_uid_cost_base: Some(52),
2775            // Cost params for the Move native function
2776            // `record_new_uid_from_hash(parent: address, bytes: address)`. Introduced in v131.
2777            object_record_new_uid_from_hash_cost_base: None,
2778
2779            // `transfer` module
2780            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
2781            transfer_transfer_internal_cost_base: Some(52),
2782            // Cost params for the Move native function `party_transfer_impl<T: key>(obj: T, party_members: vector<address>)`
2783            transfer_party_transfer_internal_cost_base: None,
2784            // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
2785            transfer_freeze_object_cost_base: Some(52),
2786            // Cost params for the Move native function `share_object<T: key>(obj: T)`
2787            transfer_share_object_cost_base: Some(52),
2788            transfer_receive_object_cost_base: None,
2789            transfer_receive_object_type_cost_per_byte: None,
2790            transfer_receive_object_cost_per_byte: None,
2791
2792            // `tx_context` module
2793            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
2794            tx_context_derive_id_cost_base: Some(52),
2795            tx_context_fresh_id_cost_base: None,
2796            tx_context_sender_cost_base: None,
2797            tx_context_epoch_cost_base: None,
2798            tx_context_epoch_timestamp_ms_cost_base: None,
2799            tx_context_sponsor_cost_base: None,
2800            tx_context_rgp_cost_base: None,
2801            tx_context_gas_price_cost_base: None,
2802            tx_context_gas_budget_cost_base: None,
2803            tx_context_ids_created_cost_base: None,
2804            tx_context_replace_cost_base: None,
2805
2806            // `types` module
2807            // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
2808            types_is_one_time_witness_cost_base: Some(52),
2809            types_is_one_time_witness_type_tag_cost_per_byte: Some(2),
2810            types_is_one_time_witness_type_cost_per_byte: Some(2),
2811
2812            // `validator` module
2813            // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
2814            validator_validate_metadata_cost_base: Some(52),
2815            validator_validate_metadata_data_cost_per_byte: Some(2),
2816
2817            // Crypto
2818            crypto_invalid_arguments_cost: Some(100),
2819            // bls12381::bls12381_min_pk_verify
2820            bls12381_bls12381_min_sig_verify_cost_base: Some(52),
2821            bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Some(2),
2822            bls12381_bls12381_min_sig_verify_msg_cost_per_block: Some(2),
2823
2824            // bls12381::bls12381_min_pk_verify
2825            bls12381_bls12381_min_pk_verify_cost_base: Some(52),
2826            bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Some(2),
2827            bls12381_bls12381_min_pk_verify_msg_cost_per_block: Some(2),
2828
2829            // ecdsa_k1::ecrecover
2830            ecdsa_k1_ecrecover_keccak256_cost_base: Some(52),
2831            ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
2832            ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Some(2),
2833            ecdsa_k1_ecrecover_sha256_cost_base: Some(52),
2834            ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Some(2),
2835            ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Some(2),
2836
2837            // ecdsa_k1::decompress_pubkey
2838            ecdsa_k1_decompress_pubkey_cost_base: Some(52),
2839
2840            // ecdsa_k1::secp256k1_verify
2841            ecdsa_k1_secp256k1_verify_keccak256_cost_base: Some(52),
2842            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Some(2),
2843            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Some(2),
2844            ecdsa_k1_secp256k1_verify_sha256_cost_base: Some(52),
2845            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Some(2),
2846            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Some(2),
2847
2848            // ecdsa_r1::ecrecover
2849            ecdsa_r1_ecrecover_keccak256_cost_base: Some(52),
2850            ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
2851            ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Some(2),
2852            ecdsa_r1_ecrecover_sha256_cost_base: Some(52),
2853            ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Some(2),
2854            ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Some(2),
2855
2856            // ecdsa_r1::secp256k1_verify
2857            ecdsa_r1_secp256r1_verify_keccak256_cost_base: Some(52),
2858            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Some(2),
2859            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Some(2),
2860            ecdsa_r1_secp256r1_verify_sha256_cost_base: Some(52),
2861            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Some(2),
2862            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Some(2),
2863
2864            // ecvrf::verify
2865            ecvrf_ecvrf_verify_cost_base: Some(52),
2866            ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Some(2),
2867            ecvrf_ecvrf_verify_alpha_string_cost_per_block: Some(2),
2868
2869            // ed25519
2870            ed25519_ed25519_verify_cost_base: Some(52),
2871            ed25519_ed25519_verify_msg_cost_per_byte: Some(2),
2872            ed25519_ed25519_verify_msg_cost_per_block: Some(2),
2873
2874            // groth16::prepare_verifying_key
2875            groth16_prepare_verifying_key_bls12381_cost_base: Some(52),
2876            groth16_prepare_verifying_key_bn254_cost_base: Some(52),
2877
2878            // groth16::verify_groth16_proof_internal
2879            groth16_verify_groth16_proof_internal_bls12381_cost_base: Some(52),
2880            groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Some(2),
2881            groth16_verify_groth16_proof_internal_bn254_cost_base: Some(52),
2882            groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Some(2),
2883            groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Some(2),
2884
2885            // hash::blake2b256
2886            hash_blake2b256_cost_base: Some(52),
2887            hash_blake2b256_data_cost_per_byte: Some(2),
2888            hash_blake2b256_data_cost_per_block: Some(2),
2889
2890            // hash::keccak256
2891            hash_keccak256_cost_base: Some(52),
2892            hash_keccak256_data_cost_per_byte: Some(2),
2893            hash_keccak256_data_cost_per_block: Some(2),
2894
2895            poseidon_bn254_cost_base: None,
2896            poseidon_bn254_cost_per_block: None,
2897
2898            // hmac::hmac_sha3_256
2899            hmac_hmac_sha3_256_cost_base: Some(52),
2900            hmac_hmac_sha3_256_input_cost_per_byte: Some(2),
2901            hmac_hmac_sha3_256_input_cost_per_block: Some(2),
2902
2903            // group ops
2904            group_ops_bls12381_decode_scalar_cost: None,
2905            group_ops_bls12381_decode_g1_cost: None,
2906            group_ops_bls12381_decode_g2_cost: None,
2907            group_ops_bls12381_decode_gt_cost: None,
2908            group_ops_bls12381_scalar_add_cost: None,
2909            group_ops_bls12381_g1_add_cost: None,
2910            group_ops_bls12381_g2_add_cost: None,
2911            group_ops_bls12381_gt_add_cost: None,
2912            group_ops_bls12381_scalar_sub_cost: None,
2913            group_ops_bls12381_g1_sub_cost: None,
2914            group_ops_bls12381_g2_sub_cost: None,
2915            group_ops_bls12381_gt_sub_cost: None,
2916            group_ops_bls12381_scalar_mul_cost: None,
2917            group_ops_bls12381_g1_mul_cost: None,
2918            group_ops_bls12381_g2_mul_cost: None,
2919            group_ops_bls12381_gt_mul_cost: None,
2920            group_ops_bls12381_scalar_div_cost: None,
2921            group_ops_bls12381_g1_div_cost: None,
2922            group_ops_bls12381_g2_div_cost: None,
2923            group_ops_bls12381_gt_div_cost: None,
2924            group_ops_bls12381_g1_hash_to_base_cost: None,
2925            group_ops_bls12381_g2_hash_to_base_cost: None,
2926            group_ops_bls12381_g1_hash_to_cost_per_byte: None,
2927            group_ops_bls12381_g2_hash_to_cost_per_byte: None,
2928            group_ops_bls12381_g1_msm_base_cost: None,
2929            group_ops_bls12381_g2_msm_base_cost: None,
2930            group_ops_bls12381_g1_msm_base_cost_per_input: None,
2931            group_ops_bls12381_g2_msm_base_cost_per_input: None,
2932            group_ops_bls12381_msm_max_len: None,
2933            group_ops_bls12381_pairing_cost: None,
2934            group_ops_bls12381_g1_to_uncompressed_g1_cost: None,
2935            group_ops_bls12381_uncompressed_g1_to_g1_cost: None,
2936            group_ops_bls12381_uncompressed_g1_sum_base_cost: None,
2937            group_ops_bls12381_uncompressed_g1_sum_cost_per_term: None,
2938            group_ops_bls12381_uncompressed_g1_sum_max_terms: None,
2939
2940            group_ops_ristretto_decode_scalar_cost: None,
2941            group_ops_ristretto_decode_point_cost: None,
2942            group_ops_ristretto_scalar_add_cost: None,
2943            group_ops_ristretto_point_add_cost: None,
2944            group_ops_ristretto_scalar_sub_cost: None,
2945            group_ops_ristretto_point_sub_cost: None,
2946            group_ops_ristretto_scalar_mul_cost: None,
2947            group_ops_ristretto_point_mul_cost: None,
2948            group_ops_ristretto_scalar_div_cost: None,
2949            group_ops_ristretto_point_div_cost: None,
2950
2951            verify_bulletproofs_ristretto255_base_cost: None,
2952            verify_bulletproofs_ristretto255_cost_per_bit_and_commitment: None,
2953            max_bulletproofs_total_bits: None,
2954
2955            // zklogin::check_zklogin_id
2956            check_zklogin_id_cost_base: None,
2957            // zklogin::check_zklogin_issuer
2958            check_zklogin_issuer_cost_base: None,
2959
2960            vdf_verify_vdf_cost: None,
2961            vdf_hash_to_input_cost: None,
2962
2963            // nitro_attestation::verify_nitro_attestation
2964            nitro_attestation_parse_base_cost: None,
2965            nitro_attestation_parse_cost_per_byte: None,
2966            nitro_attestation_verify_base_cost: None,
2967            nitro_attestation_verify_cost_per_cert: None,
2968
2969            bcs_per_byte_serialized_cost: None,
2970            bcs_legacy_min_output_size_cost: None,
2971            bcs_failure_cost: None,
2972            hash_sha2_256_base_cost: None,
2973            hash_sha2_256_per_byte_cost: None,
2974            hash_sha2_256_legacy_min_input_len_cost: None,
2975            hash_sha3_256_base_cost: None,
2976            hash_sha3_256_per_byte_cost: None,
2977            hash_sha3_256_legacy_min_input_len_cost: None,
2978            type_name_get_base_cost: None,
2979            type_name_get_per_byte_cost: None,
2980            type_name_id_base_cost: None,
2981            string_check_utf8_base_cost: None,
2982            string_check_utf8_per_byte_cost: None,
2983            string_is_char_boundary_base_cost: None,
2984            string_sub_string_base_cost: None,
2985            string_sub_string_per_byte_cost: None,
2986            string_index_of_base_cost: None,
2987            string_index_of_per_byte_pattern_cost: None,
2988            string_index_of_per_byte_searched_cost: None,
2989            vector_empty_base_cost: None,
2990            vector_length_base_cost: None,
2991            vector_push_back_base_cost: None,
2992            vector_push_back_legacy_per_abstract_memory_unit_cost: None,
2993            vector_borrow_base_cost: None,
2994            vector_pop_back_base_cost: None,
2995            vector_destroy_empty_base_cost: None,
2996            vector_swap_base_cost: None,
2997            debug_print_base_cost: None,
2998            debug_print_stack_trace_base_cost: None,
2999
3000            max_size_written_objects: None,
3001            max_size_written_objects_system_tx: None,
3002
3003            // ==== Ephemeral (consensus only) params deleted ====
3004            // Const params for consensus scoring decision
3005            // scoring_decision_mad_divisor: None,
3006            // scoring_decision_cutoff_value: None,
3007
3008            // Limits the length of a Move identifier
3009            max_move_identifier_len: None,
3010            max_move_value_depth: None,
3011            package_arena_size_in_bytes: None,
3012            max_move_enum_variants: None,
3013
3014            gas_rounding_step: None,
3015
3016            execution_version: None,
3017
3018            max_event_emit_size_total: None,
3019
3020            consensus_bad_nodes_stake_threshold: None,
3021
3022            max_jwk_votes_per_validator_per_epoch: None,
3023
3024            max_age_of_jwk_in_epochs: None,
3025
3026            random_beacon_reduction_allowed_delta: None,
3027
3028            random_beacon_reduction_lower_bound: None,
3029
3030            random_beacon_dkg_timeout_round: None,
3031
3032            random_beacon_min_round_interval_ms: None,
3033
3034            random_beacon_dkg_version: None,
3035
3036            consensus_max_transaction_size_bytes: None,
3037
3038            consensus_max_transactions_in_block_bytes: None,
3039
3040            consensus_max_num_transactions_in_block: None,
3041
3042            consensus_voting_rounds: None,
3043
3044            max_accumulated_txn_cost_per_object_in_narwhal_commit: None,
3045
3046            max_deferral_rounds_for_congestion_control: None,
3047
3048            epoch_close_deadline_ms: None,
3049
3050            max_txn_cost_overage_per_object_in_commit: None,
3051
3052            allowed_txn_cost_overage_burst_per_object_in_commit: None,
3053
3054            min_checkpoint_interval_ms: None,
3055
3056            checkpoint_summary_version_specific_data: None,
3057
3058            max_soft_bundle_size: None,
3059
3060            bridge_should_try_to_finalize_committee: None,
3061
3062            max_accumulated_txn_cost_per_object_in_mysticeti_commit: None,
3063
3064            max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit: None,
3065
3066            consensus_gc_depth: None,
3067
3068            gas_budget_based_txn_cost_cap_factor: None,
3069
3070            gas_budget_based_txn_cost_absolute_cap_commit_count: None,
3071
3072            sip_45_consensus_amplification_threshold: None,
3073
3074            use_object_per_epoch_marker_table_v2: None,
3075
3076            consensus_commit_rate_estimation_window_size: None,
3077
3078            aliased_addresses: vec![],
3079
3080            translation_per_command_base_charge: None,
3081            translation_per_input_base_charge: None,
3082            translation_pure_input_per_byte_charge: None,
3083            translation_per_type_node_charge: None,
3084            translation_per_reference_node_charge: None,
3085            translation_per_linkage_entry_charge: None,
3086            translation_per_live_reference_charge: None,
3087            max_ptb_live_references: None,
3088            max_ptb_returned_references: None,
3089            max_ptb_total_returned_references: None,
3090
3091            max_updates_per_settlement_txn: None,
3092
3093            gasless_max_computation_units: None,
3094            gasless_allowed_token_types: None,
3095            gasless_max_unused_inputs: None,
3096            gasless_max_pure_input_bytes: None,
3097            gasless_max_tps: None,
3098            include_special_package_amendments: None,
3099            gasless_max_tx_size_bytes: None,
3100            // When adding a new constant, set it to None in the earliest version, like this:
3101            // new_constant: None,
3102        };
3103        for cur in 2..=version.0 {
3104            match cur {
3105                1 => unreachable!(),
3106                2 => {
3107                    cfg.feature_flags.advance_epoch_start_time_in_safe_mode = true;
3108                }
3109                3 => {
3110                    // changes for gas model
3111                    cfg.gas_model_version = Some(2);
3112                    // max gas budget is in MIST and an absolute value 50SUI
3113                    cfg.max_tx_gas = Some(50_000_000_000);
3114                    // min gas budget is in MIST and an absolute value 2000MIST or 0.000002SUI
3115                    cfg.base_tx_cost_fixed = Some(2_000);
3116                    // storage gas price multiplier
3117                    cfg.storage_gas_price = Some(76);
3118                    cfg.feature_flags.loaded_child_objects_fixed = true;
3119                    // max size of written objects during a TXn
3120                    // this is a sum of all objects written during a TXn
3121                    cfg.max_size_written_objects = Some(5 * 1000 * 1000);
3122                    // max size of written objects during a system TXn to allow for larger writes
3123                    // akin to `max_size_written_objects` but for system TXns
3124                    cfg.max_size_written_objects_system_tx = Some(50 * 1000 * 1000);
3125                    cfg.feature_flags.package_upgrades = true;
3126                }
3127                // This is the first protocol version currently possible.
3128                // Mainnet starts with version 4. Previous versions are pre mainnet and have
3129                // all been wiped out.
3130                // Every other chain is after version 4.
3131                4 => {
3132                    // Change reward slashing rate to 100%.
3133                    cfg.reward_slashing_rate = Some(10000);
3134                    // protect old and new lookup for object version
3135                    cfg.gas_model_version = Some(3);
3136                }
3137                5 => {
3138                    cfg.feature_flags.missing_type_is_compatibility_error = true;
3139                    cfg.gas_model_version = Some(4);
3140                    cfg.feature_flags.scoring_decision_with_validity_cutoff = true;
3141                    // ==== Ephemeral (consensus only) params deleted ====
3142                    // cfg.scoring_decision_mad_divisor = Some(2.3);
3143                    // cfg.scoring_decision_cutoff_value = Some(2.5);
3144                }
3145                6 => {
3146                    cfg.gas_model_version = Some(5);
3147                    cfg.buffer_stake_for_protocol_upgrade_bps = Some(5000);
3148                    cfg.feature_flags.consensus_order_end_of_epoch_last = true;
3149                }
3150                7 => {
3151                    cfg.feature_flags.disallow_adding_abilities_on_upgrade = true;
3152                    cfg.feature_flags
3153                        .disable_invariant_violation_check_in_swap_loc = true;
3154                    cfg.feature_flags.ban_entry_init = true;
3155                    cfg.feature_flags.package_digest_hash_module = true;
3156                }
3157                8 => {
3158                    cfg.feature_flags
3159                        .disallow_change_struct_type_params_on_upgrade = true;
3160                }
3161                9 => {
3162                    // Limits the length of a Move identifier
3163                    cfg.max_move_identifier_len = Some(128);
3164                    cfg.feature_flags.no_extraneous_module_bytes = true;
3165                    cfg.feature_flags
3166                        .advance_to_highest_supported_protocol_version = true;
3167                }
3168                10 => {
3169                    cfg.max_verifier_meter_ticks_per_function = Some(16_000_000);
3170                    cfg.max_meter_ticks_per_module = Some(16_000_000);
3171                }
3172                11 => {
3173                    cfg.max_move_value_depth = Some(128);
3174                }
3175                12 => {
3176                    cfg.feature_flags.narwhal_versioned_metadata = true;
3177                    if chain != Chain::Mainnet {
3178                        cfg.feature_flags.commit_root_state_digest = true;
3179                    }
3180
3181                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3182                        cfg.feature_flags.zklogin_auth = true;
3183                    }
3184                }
3185                13 => {}
3186                14 => {
3187                    cfg.gas_rounding_step = Some(1_000);
3188                    cfg.gas_model_version = Some(6);
3189                }
3190                15 => {
3191                    cfg.feature_flags.consensus_transaction_ordering =
3192                        ConsensusTransactionOrdering::ByGasPrice;
3193                }
3194                16 => {
3195                    cfg.feature_flags.simplified_unwrap_then_delete = true;
3196                }
3197                17 => {
3198                    cfg.feature_flags.upgraded_multisig_supported = true;
3199                }
3200                18 => {
3201                    cfg.execution_version = Some(1);
3202                    // Following flags are implied by this execution version.  Once support for earlier
3203                    // protocol versions is dropped, these flags can be removed:
3204                    // cfg.feature_flags.package_upgrades = true;
3205                    // cfg.feature_flags.disallow_adding_abilities_on_upgrade = true;
3206                    // cfg.feature_flags.disallow_change_struct_type_params_on_upgrade = true;
3207                    // cfg.feature_flags.loaded_child_objects_fixed = true;
3208                    // cfg.feature_flags.ban_entry_init = true;
3209                    // cfg.feature_flags.pack_digest_hash_modules = true;
3210                    cfg.feature_flags.txn_base_cost_as_multiplier = true;
3211                    // this is a multiplier of the gas price
3212                    cfg.base_tx_cost_fixed = Some(1_000);
3213                }
3214                19 => {
3215                    cfg.max_num_event_emit = Some(1024);
3216                    // We maintain the same total size limit for events, but increase the number of
3217                    // events that can be emitted.
3218                    cfg.max_event_emit_size_total = Some(
3219                        256 /* former event count limit */ * 250 * 1024, /* size limit per event */
3220                    );
3221                }
3222                20 => {
3223                    cfg.feature_flags.commit_root_state_digest = true;
3224
3225                    if chain != Chain::Mainnet {
3226                        cfg.feature_flags.narwhal_new_leader_election_schedule = true;
3227                        cfg.consensus_bad_nodes_stake_threshold = Some(20);
3228                    }
3229                }
3230
3231                21 => {
3232                    if chain != Chain::Mainnet {
3233                        cfg.feature_flags.zklogin_supported_providers = BTreeSet::from([
3234                            "Google".to_string(),
3235                            "Facebook".to_string(),
3236                            "Twitch".to_string(),
3237                        ]);
3238                    }
3239                }
3240                22 => {
3241                    cfg.feature_flags.loaded_child_object_format = true;
3242                }
3243                23 => {
3244                    cfg.feature_flags.loaded_child_object_format_type = true;
3245                    cfg.feature_flags.narwhal_new_leader_election_schedule = true;
3246                    // Taking a baby step approach, we consider only 20% by stake as bad nodes so we
3247                    // have a 80% by stake of nodes participating in the leader committee. That allow
3248                    // us for more redundancy in case we have validators under performing - since the
3249                    // responsibility is shared amongst more nodes. We can increase that once we do have
3250                    // higher confidence.
3251                    cfg.consensus_bad_nodes_stake_threshold = Some(20);
3252                }
3253                24 => {
3254                    cfg.feature_flags.simple_conservation_checks = true;
3255                    cfg.max_publish_or_upgrade_per_ptb = Some(5);
3256
3257                    cfg.feature_flags.end_of_epoch_transaction_supported = true;
3258
3259                    if chain != Chain::Mainnet {
3260                        cfg.feature_flags.enable_jwk_consensus_updates = true;
3261                        // Max of 10 votes per hour
3262                        cfg.max_jwk_votes_per_validator_per_epoch = Some(240);
3263                        cfg.max_age_of_jwk_in_epochs = Some(1);
3264                    }
3265                }
3266                25 => {
3267                    // Enable zkLogin for all providers in all networks.
3268                    cfg.feature_flags.zklogin_supported_providers = BTreeSet::from([
3269                        "Google".to_string(),
3270                        "Facebook".to_string(),
3271                        "Twitch".to_string(),
3272                    ]);
3273                    cfg.feature_flags.zklogin_auth = true;
3274
3275                    // Enable jwk consensus updates
3276                    cfg.feature_flags.enable_jwk_consensus_updates = true;
3277                    cfg.max_jwk_votes_per_validator_per_epoch = Some(240);
3278                    cfg.max_age_of_jwk_in_epochs = Some(1);
3279                }
3280                26 => {
3281                    cfg.gas_model_version = Some(7);
3282                    // Only enable receiving objects in devnet
3283                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3284                        cfg.transfer_receive_object_cost_base = Some(52);
3285                        cfg.feature_flags.receive_objects = true;
3286                    }
3287                }
3288                27 => {
3289                    cfg.gas_model_version = Some(8);
3290                }
3291                28 => {
3292                    // zklogin::check_zklogin_id
3293                    cfg.check_zklogin_id_cost_base = Some(200);
3294                    // zklogin::check_zklogin_issuer
3295                    cfg.check_zklogin_issuer_cost_base = Some(200);
3296
3297                    // Only enable effects v2 on devnet.
3298                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3299                        cfg.feature_flags.enable_effects_v2 = true;
3300                    }
3301                }
3302                29 => {
3303                    cfg.feature_flags.verify_legacy_zklogin_address = true;
3304                }
3305                30 => {
3306                    // Only enable nw certificate v2 on testnet.
3307                    if chain != Chain::Mainnet {
3308                        cfg.feature_flags.narwhal_certificate_v2 = true;
3309                    }
3310
3311                    cfg.random_beacon_reduction_allowed_delta = Some(800);
3312                    // Only enable effects v2 on devnet and testnet.
3313                    if chain != Chain::Mainnet {
3314                        cfg.feature_flags.enable_effects_v2 = true;
3315                    }
3316
3317                    // zklogin_supported_providers config is deprecated, zklogin
3318                    // signature verifier will use the fetched jwk map to determine
3319                    // whether the provider is supported based on node config.
3320                    cfg.feature_flags.zklogin_supported_providers = BTreeSet::default();
3321
3322                    cfg.feature_flags.recompute_has_public_transfer_in_execution = true;
3323                }
3324                31 => {
3325                    cfg.execution_version = Some(2);
3326                    // Only enable shared object deletion on devnet
3327                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3328                        cfg.feature_flags.shared_object_deletion = true;
3329                    }
3330                }
3331                32 => {
3332                    // enable zklogin in multisig in devnet and testnet
3333                    if chain != Chain::Mainnet {
3334                        cfg.feature_flags.accept_zklogin_in_multisig = true;
3335                    }
3336                    // enable receiving objects in devnet and testnet
3337                    if chain != Chain::Mainnet {
3338                        cfg.transfer_receive_object_cost_base = Some(52);
3339                        cfg.feature_flags.receive_objects = true;
3340                    }
3341                    // Only enable random beacon on devnet
3342                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3343                        cfg.feature_flags.random_beacon = true;
3344                        cfg.random_beacon_reduction_lower_bound = Some(1600);
3345                        cfg.random_beacon_dkg_timeout_round = Some(3000);
3346                        cfg.random_beacon_min_round_interval_ms = Some(150);
3347                    }
3348                    // Only enable consensus digest in consensus commit prologue in devnet.
3349                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3350                        cfg.feature_flags.include_consensus_digest_in_prologue = true;
3351                    }
3352
3353                    // enable nw cert v2 on mainnet
3354                    cfg.feature_flags.narwhal_certificate_v2 = true;
3355                }
3356                33 => {
3357                    cfg.feature_flags.hardened_otw_check = true;
3358                    cfg.feature_flags.allow_receiving_object_id = true;
3359
3360                    // Enable transfer-to-object in mainnet
3361                    cfg.transfer_receive_object_cost_base = Some(52);
3362                    cfg.feature_flags.receive_objects = true;
3363
3364                    // Enable shared object deletion in testnet and devnet
3365                    if chain != Chain::Mainnet {
3366                        cfg.feature_flags.shared_object_deletion = true;
3367                    }
3368
3369                    cfg.feature_flags.enable_effects_v2 = true;
3370                }
3371                34 => {}
3372                35 => {
3373                    // Add costs for poseidon::poseidon_bn254
3374                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3375                        cfg.feature_flags.enable_poseidon = true;
3376                        cfg.poseidon_bn254_cost_base = Some(260);
3377                        cfg.poseidon_bn254_cost_per_block = Some(10);
3378                    }
3379
3380                    cfg.feature_flags.enable_coin_deny_list = true;
3381                }
3382                36 => {
3383                    // Only enable group ops on devnet
3384                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3385                        cfg.feature_flags.enable_group_ops_native_functions = true;
3386                        cfg.feature_flags.enable_group_ops_native_function_msm = true;
3387                        // Next values are arbitrary in a similar way as the other crypto native functions.
3388                        cfg.group_ops_bls12381_decode_scalar_cost = Some(52);
3389                        cfg.group_ops_bls12381_decode_g1_cost = Some(52);
3390                        cfg.group_ops_bls12381_decode_g2_cost = Some(52);
3391                        cfg.group_ops_bls12381_decode_gt_cost = Some(52);
3392                        cfg.group_ops_bls12381_scalar_add_cost = Some(52);
3393                        cfg.group_ops_bls12381_g1_add_cost = Some(52);
3394                        cfg.group_ops_bls12381_g2_add_cost = Some(52);
3395                        cfg.group_ops_bls12381_gt_add_cost = Some(52);
3396                        cfg.group_ops_bls12381_scalar_sub_cost = Some(52);
3397                        cfg.group_ops_bls12381_g1_sub_cost = Some(52);
3398                        cfg.group_ops_bls12381_g2_sub_cost = Some(52);
3399                        cfg.group_ops_bls12381_gt_sub_cost = Some(52);
3400                        cfg.group_ops_bls12381_scalar_mul_cost = Some(52);
3401                        cfg.group_ops_bls12381_g1_mul_cost = Some(52);
3402                        cfg.group_ops_bls12381_g2_mul_cost = Some(52);
3403                        cfg.group_ops_bls12381_gt_mul_cost = Some(52);
3404                        cfg.group_ops_bls12381_scalar_div_cost = Some(52);
3405                        cfg.group_ops_bls12381_g1_div_cost = Some(52);
3406                        cfg.group_ops_bls12381_g2_div_cost = Some(52);
3407                        cfg.group_ops_bls12381_gt_div_cost = Some(52);
3408                        cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(52);
3409                        cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(52);
3410                        cfg.group_ops_bls12381_g1_hash_to_cost_per_byte = Some(2);
3411                        cfg.group_ops_bls12381_g2_hash_to_cost_per_byte = Some(2);
3412                        cfg.group_ops_bls12381_g1_msm_base_cost = Some(52);
3413                        cfg.group_ops_bls12381_g2_msm_base_cost = Some(52);
3414                        cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(52);
3415                        cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(52);
3416                        cfg.group_ops_bls12381_msm_max_len = Some(32);
3417                        cfg.group_ops_bls12381_pairing_cost = Some(52);
3418                    }
3419                    // Enable shared object deletion on all networks.
3420                    cfg.feature_flags.shared_object_deletion = true;
3421
3422                    cfg.consensus_max_transaction_size_bytes = Some(256 * 1024); // 256KB
3423                    cfg.consensus_max_transactions_in_block_bytes = Some(6 * 1_024 * 1024);
3424                    // 6 MB
3425                }
3426                37 => {
3427                    cfg.feature_flags.reject_mutable_random_on_entry_functions = true;
3428
3429                    // Enable consensus digest in consensus commit prologue in testnet and devnet.
3430                    if chain != Chain::Mainnet {
3431                        cfg.feature_flags.include_consensus_digest_in_prologue = true;
3432                    }
3433                }
3434                38 => {
3435                    cfg.binary_module_handles = Some(100);
3436                    cfg.binary_struct_handles = Some(300);
3437                    cfg.binary_function_handles = Some(1500);
3438                    cfg.binary_function_instantiations = Some(750);
3439                    cfg.binary_signatures = Some(1000);
3440                    // constants and identifiers are proportional to the binary size,
3441                    // and they vastly depend on the code, so we are leaving them
3442                    // reasonably high
3443                    cfg.binary_constant_pool = Some(4000);
3444                    cfg.binary_identifiers = Some(10000);
3445                    cfg.binary_address_identifiers = Some(100);
3446                    cfg.binary_struct_defs = Some(200);
3447                    cfg.binary_struct_def_instantiations = Some(100);
3448                    cfg.binary_function_defs = Some(1000);
3449                    cfg.binary_field_handles = Some(500);
3450                    cfg.binary_field_instantiations = Some(250);
3451                    cfg.binary_friend_decls = Some(100);
3452                    // reduce dependencies maximum
3453                    cfg.max_package_dependencies = Some(32);
3454                    cfg.max_modules_in_publish = Some(64);
3455                    // bump execution version
3456                    cfg.execution_version = Some(3);
3457                }
3458                39 => {
3459                    // It is important that we keep this protocol version blank due to an issue with random.move.
3460                }
3461                40 => {}
3462                41 => {
3463                    // Enable group ops and all networks (but not msm)
3464                    cfg.feature_flags.enable_group_ops_native_functions = true;
3465                    // Next values are arbitrary in a similar way as the other crypto native functions.
3466                    cfg.group_ops_bls12381_decode_scalar_cost = Some(52);
3467                    cfg.group_ops_bls12381_decode_g1_cost = Some(52);
3468                    cfg.group_ops_bls12381_decode_g2_cost = Some(52);
3469                    cfg.group_ops_bls12381_decode_gt_cost = Some(52);
3470                    cfg.group_ops_bls12381_scalar_add_cost = Some(52);
3471                    cfg.group_ops_bls12381_g1_add_cost = Some(52);
3472                    cfg.group_ops_bls12381_g2_add_cost = Some(52);
3473                    cfg.group_ops_bls12381_gt_add_cost = Some(52);
3474                    cfg.group_ops_bls12381_scalar_sub_cost = Some(52);
3475                    cfg.group_ops_bls12381_g1_sub_cost = Some(52);
3476                    cfg.group_ops_bls12381_g2_sub_cost = Some(52);
3477                    cfg.group_ops_bls12381_gt_sub_cost = Some(52);
3478                    cfg.group_ops_bls12381_scalar_mul_cost = Some(52);
3479                    cfg.group_ops_bls12381_g1_mul_cost = Some(52);
3480                    cfg.group_ops_bls12381_g2_mul_cost = Some(52);
3481                    cfg.group_ops_bls12381_gt_mul_cost = Some(52);
3482                    cfg.group_ops_bls12381_scalar_div_cost = Some(52);
3483                    cfg.group_ops_bls12381_g1_div_cost = Some(52);
3484                    cfg.group_ops_bls12381_g2_div_cost = Some(52);
3485                    cfg.group_ops_bls12381_gt_div_cost = Some(52);
3486                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(52);
3487                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(52);
3488                    cfg.group_ops_bls12381_g1_hash_to_cost_per_byte = Some(2);
3489                    cfg.group_ops_bls12381_g2_hash_to_cost_per_byte = Some(2);
3490                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(52);
3491                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(52);
3492                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(52);
3493                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(52);
3494                    cfg.group_ops_bls12381_msm_max_len = Some(32);
3495                    cfg.group_ops_bls12381_pairing_cost = Some(52);
3496                }
3497                42 => {}
3498                43 => {
3499                    cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = Some(30);
3500                    cfg.max_meter_ticks_per_package = Some(16_000_000);
3501                }
3502                44 => {
3503                    // Enable consensus digest in consensus commit prologue on all networks..
3504                    cfg.feature_flags.include_consensus_digest_in_prologue = true;
3505                    // Switch between Narwhal and Mysticeti per epoch in tests, devnet and testnet.
3506                    if chain != Chain::Mainnet {
3507                        cfg.feature_flags.consensus_choice = ConsensusChoice::SwapEachEpoch;
3508                    }
3509                }
3510                45 => {
3511                    // Use tonic networking for consensus, in tests and devnet.
3512                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3513                        cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
3514                    }
3515
3516                    if chain != Chain::Mainnet {
3517                        // Enable leader scoring & schedule change on testnet for mysticeti.
3518                        cfg.feature_flags.mysticeti_leader_scoring_and_schedule = true;
3519                    }
3520                    cfg.min_move_binary_format_version = Some(6);
3521                    cfg.feature_flags.accept_zklogin_in_multisig = true;
3522
3523                    // Also bumps framework snapshot to fix binop issue.
3524
3525                    // enable bridge in devnet
3526                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3527                        cfg.feature_flags.bridge = true;
3528                    }
3529                }
3530                46 => {
3531                    // enable bridge in devnet and testnet
3532                    if chain != Chain::Mainnet {
3533                        cfg.feature_flags.bridge = true;
3534                    }
3535
3536                    // Enable resharing at same initial version
3537                    cfg.feature_flags.reshare_at_same_initial_version = true;
3538                }
3539                47 => {}
3540                48 => {
3541                    // Use tonic networking for Mysticeti.
3542                    cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
3543
3544                    // Enable resolving abort code IDs to package ID instead of runtime module ID
3545                    cfg.feature_flags.resolve_abort_locations_to_package_id = true;
3546
3547                    // Enable random beacon on testnet.
3548                    if chain != Chain::Mainnet {
3549                        cfg.feature_flags.random_beacon = true;
3550                        cfg.random_beacon_reduction_lower_bound = Some(1600);
3551                        cfg.random_beacon_dkg_timeout_round = Some(3000);
3552                        cfg.random_beacon_min_round_interval_ms = Some(200);
3553                    }
3554
3555                    // Enable the committed sub dag digest inclusion on the commit output
3556                    cfg.feature_flags.mysticeti_use_committed_subdag_digest = true;
3557                }
3558                49 => {
3559                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3560                        cfg.move_binary_format_version = Some(7);
3561                    }
3562
3563                    // enable vdf in devnet
3564                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3565                        cfg.feature_flags.enable_vdf = true;
3566                        // Set to 30x and 2x the cost of a signature verification for now. This
3567                        // should be updated along with other native crypto functions.
3568                        cfg.vdf_verify_vdf_cost = Some(1500);
3569                        cfg.vdf_hash_to_input_cost = Some(100);
3570                    }
3571
3572                    // Only enable consensus commit prologue V3 in devnet.
3573                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3574                        cfg.feature_flags
3575                            .record_consensus_determined_version_assignments_in_prologue = true;
3576                    }
3577
3578                    // Run Mysticeti consensus in testnet.
3579                    if chain != Chain::Mainnet {
3580                        cfg.feature_flags.consensus_choice = ConsensusChoice::Mysticeti;
3581                    }
3582
3583                    // Run Move verification on framework upgrades in its own VM
3584                    cfg.feature_flags.fresh_vm_on_framework_upgrade = true;
3585                }
3586                50 => {
3587                    // Enable checkpoint batching in testnet.
3588                    if chain != Chain::Mainnet {
3589                        cfg.checkpoint_summary_version_specific_data = Some(1);
3590                        cfg.min_checkpoint_interval_ms = Some(200);
3591                    }
3592
3593                    // Only enable prepose consensus commit prologue in checkpoints in devnet.
3594                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3595                        cfg.feature_flags
3596                            .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3597                    }
3598
3599                    cfg.feature_flags.mysticeti_num_leaders_per_round = Some(1);
3600
3601                    // Set max transaction deferral to 10 consensus rounds.
3602                    cfg.max_deferral_rounds_for_congestion_control = Some(10);
3603                }
3604                51 => {
3605                    cfg.random_beacon_dkg_version = Some(1);
3606
3607                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3608                        cfg.feature_flags.enable_coin_deny_list_v2 = true;
3609                    }
3610                }
3611                52 => {
3612                    if chain != Chain::Mainnet {
3613                        cfg.feature_flags.soft_bundle = true;
3614                        cfg.max_soft_bundle_size = Some(5);
3615                    }
3616
3617                    cfg.config_read_setting_impl_cost_base = Some(100);
3618                    cfg.config_read_setting_impl_cost_per_byte = Some(40);
3619
3620                    // Turn on shared object congestion control in devnet.
3621                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3622                        cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3623                        cfg.feature_flags.per_object_congestion_control_mode =
3624                            PerObjectCongestionControlMode::TotalTxCount;
3625                    }
3626
3627                    // Enable Mysticeti on mainnet.
3628                    cfg.feature_flags.consensus_choice = ConsensusChoice::Mysticeti;
3629
3630                    // Enable leader scoring & schedule change on mainnet for mysticeti.
3631                    cfg.feature_flags.mysticeti_leader_scoring_and_schedule = true;
3632
3633                    // Enable checkpoint batching on mainnet.
3634                    cfg.checkpoint_summary_version_specific_data = Some(1);
3635                    cfg.min_checkpoint_interval_ms = Some(200);
3636
3637                    // Enable consensus commit prologue V3 in testnet.
3638                    if chain != Chain::Mainnet {
3639                        cfg.feature_flags
3640                            .record_consensus_determined_version_assignments_in_prologue = true;
3641                        cfg.feature_flags
3642                            .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3643                    }
3644                    // Turn on enums in testnet and devnet
3645                    if chain != Chain::Mainnet {
3646                        cfg.move_binary_format_version = Some(7);
3647                    }
3648
3649                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3650                        cfg.feature_flags.passkey_auth = true;
3651                    }
3652                    cfg.feature_flags.enable_coin_deny_list_v2 = true;
3653                }
3654                53 => {
3655                    // Do not allow bridge committee to finalize on mainnet.
3656                    cfg.bridge_should_try_to_finalize_committee = Some(chain != Chain::Mainnet);
3657
3658                    // Enable consensus commit prologue V3 on mainnet.
3659                    cfg.feature_flags
3660                        .record_consensus_determined_version_assignments_in_prologue = true;
3661                    cfg.feature_flags
3662                        .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3663
3664                    if chain == Chain::Unknown {
3665                        cfg.feature_flags.authority_capabilities_v2 = true;
3666                    }
3667
3668                    // Turns on shared object congestion control on testnet.
3669                    if chain != Chain::Mainnet {
3670                        cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3671                        cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(10);
3672                        cfg.feature_flags.per_object_congestion_control_mode =
3673                            PerObjectCongestionControlMode::TotalTxCount;
3674                    }
3675
3676                    // Adjust stdlib gas costs
3677                    cfg.bcs_per_byte_serialized_cost = Some(2);
3678                    cfg.bcs_legacy_min_output_size_cost = Some(1);
3679                    cfg.bcs_failure_cost = Some(52);
3680                    cfg.debug_print_base_cost = Some(52);
3681                    cfg.debug_print_stack_trace_base_cost = Some(52);
3682                    cfg.hash_sha2_256_base_cost = Some(52);
3683                    cfg.hash_sha2_256_per_byte_cost = Some(2);
3684                    cfg.hash_sha2_256_legacy_min_input_len_cost = Some(1);
3685                    cfg.hash_sha3_256_base_cost = Some(52);
3686                    cfg.hash_sha3_256_per_byte_cost = Some(2);
3687                    cfg.hash_sha3_256_legacy_min_input_len_cost = Some(1);
3688                    cfg.type_name_get_base_cost = Some(52);
3689                    cfg.type_name_get_per_byte_cost = Some(2);
3690                    cfg.string_check_utf8_base_cost = Some(52);
3691                    cfg.string_check_utf8_per_byte_cost = Some(2);
3692                    cfg.string_is_char_boundary_base_cost = Some(52);
3693                    cfg.string_sub_string_base_cost = Some(52);
3694                    cfg.string_sub_string_per_byte_cost = Some(2);
3695                    cfg.string_index_of_base_cost = Some(52);
3696                    cfg.string_index_of_per_byte_pattern_cost = Some(2);
3697                    cfg.string_index_of_per_byte_searched_cost = Some(2);
3698                    cfg.vector_empty_base_cost = Some(52);
3699                    cfg.vector_length_base_cost = Some(52);
3700                    cfg.vector_push_back_base_cost = Some(52);
3701                    cfg.vector_push_back_legacy_per_abstract_memory_unit_cost = Some(2);
3702                    cfg.vector_borrow_base_cost = Some(52);
3703                    cfg.vector_pop_back_base_cost = Some(52);
3704                    cfg.vector_destroy_empty_base_cost = Some(52);
3705                    cfg.vector_swap_base_cost = Some(52);
3706                }
3707                54 => {
3708                    // Enable random beacon on mainnet.
3709                    cfg.feature_flags.random_beacon = true;
3710                    cfg.random_beacon_reduction_lower_bound = Some(1000);
3711                    cfg.random_beacon_dkg_timeout_round = Some(3000);
3712                    cfg.random_beacon_min_round_interval_ms = Some(500);
3713
3714                    // Turns on shared object congestion control on mainnet.
3715                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3716                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(10);
3717                    cfg.feature_flags.per_object_congestion_control_mode =
3718                        PerObjectCongestionControlMode::TotalTxCount;
3719
3720                    // Enable soft bundle on mainnet.
3721                    cfg.feature_flags.soft_bundle = true;
3722                    cfg.max_soft_bundle_size = Some(5);
3723                }
3724                55 => {
3725                    // Turn on enums mainnet
3726                    cfg.move_binary_format_version = Some(7);
3727
3728                    // Assume 1KB per transaction and 500 transactions per block.
3729                    cfg.consensus_max_transactions_in_block_bytes = Some(512 * 1024);
3730                    // Assume 20_000 TPS * 5% max stake per validator / (minimum) 4 blocks per round = 250 transactions per block maximum
3731                    // Using a higher limit that is 512, to account for bursty traffic and system transactions.
3732                    cfg.consensus_max_num_transactions_in_block = Some(512);
3733
3734                    cfg.feature_flags.rethrow_serialization_type_layout_errors = true;
3735                }
3736                56 => {
3737                    if chain == Chain::Mainnet {
3738                        cfg.feature_flags.bridge = true;
3739                    }
3740                }
3741                57 => {
3742                    // Reduce minimum number of random beacon shares.
3743                    cfg.random_beacon_reduction_lower_bound = Some(800);
3744                }
3745                58 => {
3746                    if chain == Chain::Mainnet {
3747                        cfg.bridge_should_try_to_finalize_committee = Some(true);
3748                    }
3749
3750                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3751                        // Enable distributed vote scoring for devnet
3752                        cfg.feature_flags
3753                            .consensus_distributed_vote_scoring_strategy = true;
3754                    }
3755                }
3756                59 => {
3757                    // Enable round prober in consensus.
3758                    cfg.feature_flags.consensus_round_prober = true;
3759                }
3760                60 => {
3761                    cfg.max_type_to_layout_nodes = Some(512);
3762                    cfg.feature_flags.validate_identifier_inputs = true;
3763                }
3764                61 => {
3765                    if chain != Chain::Mainnet {
3766                        // Enable distributed vote scoring for testnet
3767                        cfg.feature_flags
3768                            .consensus_distributed_vote_scoring_strategy = true;
3769                    }
3770                    // Further reduce minimum number of random beacon shares.
3771                    cfg.random_beacon_reduction_lower_bound = Some(700);
3772
3773                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3774                        // Enable Mysticeti fastpath for devnet
3775                        cfg.feature_flags.mysticeti_fastpath = true;
3776                    }
3777                }
3778                62 => {
3779                    cfg.feature_flags.relocate_event_module = true;
3780                }
3781                63 => {
3782                    cfg.feature_flags.per_object_congestion_control_mode =
3783                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
3784                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
3785                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(18_500_000);
3786                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(240_000_000);
3787                }
3788                64 => {
3789                    cfg.feature_flags.per_object_congestion_control_mode =
3790                        PerObjectCongestionControlMode::TotalTxCount;
3791                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(40);
3792                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(3);
3793                }
3794                65 => {
3795                    // Enable distributed vote scoring for mainnet
3796                    cfg.feature_flags
3797                        .consensus_distributed_vote_scoring_strategy = true;
3798                }
3799                66 => {
3800                    if chain == Chain::Mainnet {
3801                        // Revert the distributed vote scoring for mainnet (for one protocol upgrade)
3802                        cfg.feature_flags
3803                            .consensus_distributed_vote_scoring_strategy = false;
3804                    }
3805                }
3806                67 => {
3807                    // Enable it once again.
3808                    cfg.feature_flags
3809                        .consensus_distributed_vote_scoring_strategy = true;
3810                }
3811                68 => {
3812                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(26);
3813                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(52);
3814                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(26);
3815                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(13);
3816                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(2000);
3817
3818                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3819                        cfg.feature_flags.uncompressed_g1_group_elements = true;
3820                    }
3821
3822                    cfg.feature_flags.per_object_congestion_control_mode =
3823                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
3824                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
3825                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(18_500_000);
3826                    cfg.max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit =
3827                        Some(3_700_000); // 20% of above
3828                    cfg.max_txn_cost_overage_per_object_in_commit = Some(u64::MAX);
3829                    cfg.gas_budget_based_txn_cost_absolute_cap_commit_count = Some(50);
3830
3831                    // Further reduce minimum number of random beacon shares.
3832                    cfg.random_beacon_reduction_lower_bound = Some(500);
3833
3834                    cfg.feature_flags.disallow_new_modules_in_deps_only_packages = true;
3835                }
3836                69 => {
3837                    // Sets number of rounds allowed for fastpath voting in consensus.
3838                    cfg.consensus_voting_rounds = Some(40);
3839
3840                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3841                        // Enable smart ancestor selection for devnet
3842                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
3843                    }
3844
3845                    if chain != Chain::Mainnet {
3846                        cfg.feature_flags.uncompressed_g1_group_elements = true;
3847                    }
3848                }
3849                70 => {
3850                    if chain != Chain::Mainnet {
3851                        // Enable smart ancestor selection for testnet
3852                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
3853                        // Enable probing for accepted rounds in round prober for testnet
3854                        cfg.feature_flags
3855                            .consensus_round_prober_probe_accepted_rounds = true;
3856                    }
3857
3858                    cfg.poseidon_bn254_cost_per_block = Some(388);
3859
3860                    cfg.gas_model_version = Some(9);
3861                    cfg.feature_flags.native_charging_v2 = true;
3862                    cfg.bls12381_bls12381_min_sig_verify_cost_base = Some(44064);
3863                    cfg.bls12381_bls12381_min_pk_verify_cost_base = Some(49282);
3864                    cfg.ecdsa_k1_secp256k1_verify_keccak256_cost_base = Some(1470);
3865                    cfg.ecdsa_k1_secp256k1_verify_sha256_cost_base = Some(1470);
3866                    cfg.ecdsa_r1_secp256r1_verify_sha256_cost_base = Some(4225);
3867                    cfg.ecdsa_r1_secp256r1_verify_keccak256_cost_base = Some(4225);
3868                    cfg.ecvrf_ecvrf_verify_cost_base = Some(4848);
3869                    cfg.ed25519_ed25519_verify_cost_base = Some(1802);
3870
3871                    // Manually changed to be "under cost"
3872                    cfg.ecdsa_r1_ecrecover_keccak256_cost_base = Some(1173);
3873                    cfg.ecdsa_r1_ecrecover_sha256_cost_base = Some(1173);
3874                    cfg.ecdsa_k1_ecrecover_keccak256_cost_base = Some(500);
3875                    cfg.ecdsa_k1_ecrecover_sha256_cost_base = Some(500);
3876
3877                    cfg.groth16_prepare_verifying_key_bls12381_cost_base = Some(53838);
3878                    cfg.groth16_prepare_verifying_key_bn254_cost_base = Some(82010);
3879                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_base = Some(72090);
3880                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input =
3881                        Some(8213);
3882                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_base = Some(115502);
3883                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_per_public_input =
3884                        Some(9484);
3885
3886                    cfg.hash_keccak256_cost_base = Some(10);
3887                    cfg.hash_blake2b256_cost_base = Some(10);
3888
3889                    // group ops
3890                    cfg.group_ops_bls12381_decode_scalar_cost = Some(7);
3891                    cfg.group_ops_bls12381_decode_g1_cost = Some(2848);
3892                    cfg.group_ops_bls12381_decode_g2_cost = Some(3770);
3893                    cfg.group_ops_bls12381_decode_gt_cost = Some(3068);
3894
3895                    cfg.group_ops_bls12381_scalar_add_cost = Some(10);
3896                    cfg.group_ops_bls12381_g1_add_cost = Some(1556);
3897                    cfg.group_ops_bls12381_g2_add_cost = Some(3048);
3898                    cfg.group_ops_bls12381_gt_add_cost = Some(188);
3899
3900                    cfg.group_ops_bls12381_scalar_sub_cost = Some(10);
3901                    cfg.group_ops_bls12381_g1_sub_cost = Some(1550);
3902                    cfg.group_ops_bls12381_g2_sub_cost = Some(3019);
3903                    cfg.group_ops_bls12381_gt_sub_cost = Some(497);
3904
3905                    cfg.group_ops_bls12381_scalar_mul_cost = Some(11);
3906                    cfg.group_ops_bls12381_g1_mul_cost = Some(4842);
3907                    cfg.group_ops_bls12381_g2_mul_cost = Some(9108);
3908                    cfg.group_ops_bls12381_gt_mul_cost = Some(27490);
3909
3910                    cfg.group_ops_bls12381_scalar_div_cost = Some(91);
3911                    cfg.group_ops_bls12381_g1_div_cost = Some(5091);
3912                    cfg.group_ops_bls12381_g2_div_cost = Some(9206);
3913                    cfg.group_ops_bls12381_gt_div_cost = Some(27804);
3914
3915                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(2962);
3916                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(8688);
3917
3918                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(62648);
3919                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(131192);
3920                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(1333);
3921                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(3216);
3922
3923                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(677);
3924                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(2099);
3925                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(77);
3926                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(26);
3927
3928                    cfg.group_ops_bls12381_pairing_cost = Some(26897);
3929                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(1200);
3930
3931                    cfg.validator_validate_metadata_cost_base = Some(20000);
3932                }
3933                71 => {
3934                    cfg.sip_45_consensus_amplification_threshold = Some(5);
3935
3936                    // Enable bursts for congestion control. (10x the per-commit budget)
3937                    cfg.allowed_txn_cost_overage_burst_per_object_in_commit = Some(185_000_000);
3938                }
3939                72 => {
3940                    cfg.feature_flags.convert_type_argument_error = true;
3941
3942                    // Invariant: max_gas_price * base_tx_cost_fixed <= max_tx_gas
3943                    // max gas budget is in MIST and an absolute value 50_000 SUI
3944                    cfg.max_tx_gas = Some(50_000_000_000_000);
3945                    // max gas price is in MIST and an absolute value 50 SUI
3946                    cfg.max_gas_price = Some(50_000_000_000);
3947
3948                    cfg.feature_flags.variant_nodes = true;
3949                }
3950                73 => {
3951                    // Enable new marker table version.
3952                    cfg.use_object_per_epoch_marker_table_v2 = Some(true);
3953
3954                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3955                        // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow blocks within a window of ~4 seconds
3956                        // to be included before be considered garbage collected.
3957                        cfg.consensus_gc_depth = Some(60);
3958                    }
3959
3960                    if chain != Chain::Mainnet {
3961                        // Enable zstd compression for consensus in testnet
3962                        cfg.feature_flags.consensus_zstd_compression = true;
3963                    }
3964
3965                    // Enable smart ancestor selection for mainnet
3966                    cfg.feature_flags.consensus_smart_ancestor_selection = true;
3967                    // Enable probing for accepted rounds in round prober for mainnet
3968                    cfg.feature_flags
3969                        .consensus_round_prober_probe_accepted_rounds = true;
3970
3971                    // Increase congestion control budget.
3972                    cfg.feature_flags.per_object_congestion_control_mode =
3973                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
3974                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
3975                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(37_000_000);
3976                    cfg.max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit =
3977                        Some(7_400_000); // 20% of above
3978                    cfg.max_txn_cost_overage_per_object_in_commit = Some(u64::MAX);
3979                    cfg.gas_budget_based_txn_cost_absolute_cap_commit_count = Some(50);
3980                    cfg.allowed_txn_cost_overage_burst_per_object_in_commit = Some(370_000_000);
3981                }
3982                74 => {
3983                    // Enable nitro attestation verify native move function for devnet
3984                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3985                        cfg.feature_flags.enable_nitro_attestation = true;
3986                    }
3987                    cfg.nitro_attestation_parse_base_cost = Some(53 * 50);
3988                    cfg.nitro_attestation_parse_cost_per_byte = Some(50);
3989                    cfg.nitro_attestation_verify_base_cost = Some(49632 * 50);
3990                    cfg.nitro_attestation_verify_cost_per_cert = Some(52369 * 50);
3991
3992                    // Enable zstd compression for consensus in mainnet
3993                    cfg.feature_flags.consensus_zstd_compression = true;
3994
3995                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3996                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
3997                    }
3998                }
3999                75 => {
4000                    if chain != Chain::Mainnet {
4001                        cfg.feature_flags.passkey_auth = true;
4002                    }
4003                }
4004                76 => {
4005                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4006                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4007                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4008                    }
4009                    cfg.feature_flags.minimize_child_object_mutations = true;
4010
4011                    if chain != Chain::Mainnet {
4012                        cfg.feature_flags.accept_passkey_in_multisig = true;
4013                    }
4014                }
4015                77 => {
4016                    cfg.feature_flags.uncompressed_g1_group_elements = true;
4017
4018                    if chain != Chain::Mainnet {
4019                        cfg.consensus_gc_depth = Some(60);
4020                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4021                    }
4022                }
4023                78 => {
4024                    cfg.feature_flags.move_native_context = true;
4025                    cfg.tx_context_fresh_id_cost_base = Some(52);
4026                    cfg.tx_context_sender_cost_base = Some(30);
4027                    cfg.tx_context_epoch_cost_base = Some(30);
4028                    cfg.tx_context_epoch_timestamp_ms_cost_base = Some(30);
4029                    cfg.tx_context_sponsor_cost_base = Some(30);
4030                    cfg.tx_context_gas_price_cost_base = Some(30);
4031                    cfg.tx_context_gas_budget_cost_base = Some(30);
4032                    cfg.tx_context_ids_created_cost_base = Some(30);
4033                    cfg.tx_context_replace_cost_base = Some(30);
4034                    cfg.gas_model_version = Some(10);
4035
4036                    if chain != Chain::Mainnet {
4037                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4038                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4039
4040                        // Enable execution time estimate mode for congestion control on testnet.
4041                        cfg.feature_flags.per_object_congestion_control_mode =
4042                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4043                                ExecutionTimeEstimateParams {
4044                                    target_utilization: 30,
4045                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4046                                    randomness_scalar: 20,
4047                                    max_estimate_us: 1_500_000, // 1.5s
4048                                    stored_observations_num_included_checkpoints: 10,
4049                                    stored_observations_limit: u64::MAX,
4050                                    stake_weighted_median_threshold: 0,
4051                                    default_none_duration_for_new_keys: false,
4052                                    observations_chunk_size: None,
4053                                },
4054                            );
4055                    }
4056                }
4057                79 => {
4058                    if chain != Chain::Mainnet {
4059                        cfg.feature_flags.consensus_median_based_commit_timestamp = true;
4060
4061                        // Increase threshold for bad nodes that won't be considered
4062                        // leaders in consensus in testnet
4063                        cfg.consensus_bad_nodes_stake_threshold = Some(30);
4064
4065                        cfg.feature_flags.consensus_batched_block_sync = true;
4066
4067                        // Enable verify nitro attestation in testnet.
4068                        cfg.feature_flags.enable_nitro_attestation = true
4069                    }
4070                    cfg.feature_flags.normalize_ptb_arguments = true;
4071
4072                    cfg.consensus_gc_depth = Some(60);
4073                    cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4074                }
4075                80 => {
4076                    cfg.max_ptb_value_size = Some(1024 * 1024);
4077                }
4078                81 => {
4079                    cfg.feature_flags.consensus_median_based_commit_timestamp = true;
4080                    cfg.feature_flags.enforce_checkpoint_timestamp_monotonicity = true;
4081                    cfg.consensus_bad_nodes_stake_threshold = Some(30)
4082                }
4083                82 => {
4084                    cfg.feature_flags.max_ptb_value_size_v2 = true;
4085                }
4086                83 => {
4087                    if chain == Chain::Mainnet {
4088                        // The address that will sign the recovery transaction.
4089                        let aliased: [u8; 32] = Hex::decode(
4090                            "0x0b2da327ba6a4cacbe75dddd50e6e8bbf81d6496e92d66af9154c61c77f7332f",
4091                        )
4092                        .unwrap()
4093                        .try_into()
4094                        .unwrap();
4095
4096                        // Allow aliasing for the two addresses that contain stolen funds.
4097                        cfg.aliased_addresses.push(AliasedAddress {
4098                            original: Hex::decode("0xcd8962dad278d8b50fa0f9eb0186bfa4cbdecc6d59377214c88d0286a0ac9562").unwrap().try_into().unwrap(),
4099                            aliased,
4100                            allowed_tx_digests: vec![
4101                                Base58::decode("B2eGLFoMHgj93Ni8dAJBfqGzo8EWSTLBesZzhEpTPA4").unwrap().try_into().unwrap(),
4102                            ],
4103                        });
4104
4105                        cfg.aliased_addresses.push(AliasedAddress {
4106                            original: Hex::decode("0xe28b50cef1d633ea43d3296a3f6b67ff0312a5f1a99f0af753c85b8b5de8ff06").unwrap().try_into().unwrap(),
4107                            aliased,
4108                            allowed_tx_digests: vec![
4109                                Base58::decode("J4QqSAgp7VrQtQpMy5wDX4QGsCSEZu3U5KuDAkbESAge").unwrap().try_into().unwrap(),
4110                            ],
4111                        });
4112                    }
4113
4114                    // These features had to be deferred to v84 for mainnet in order to ship the recovery protocol
4115                    // upgrade as a patch to 1.48
4116                    if chain != Chain::Mainnet {
4117                        cfg.feature_flags.resolve_type_input_ids_to_defining_id = true;
4118                        cfg.transfer_party_transfer_internal_cost_base = Some(52);
4119
4120                        // Enable execution time estimate mode for congestion control on mainnet.
4121                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4122                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4123                        cfg.feature_flags.per_object_congestion_control_mode =
4124                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4125                                ExecutionTimeEstimateParams {
4126                                    target_utilization: 30,
4127                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4128                                    randomness_scalar: 20,
4129                                    max_estimate_us: 1_500_000, // 1.5s
4130                                    stored_observations_num_included_checkpoints: 10,
4131                                    stored_observations_limit: u64::MAX,
4132                                    stake_weighted_median_threshold: 0,
4133                                    default_none_duration_for_new_keys: false,
4134                                    observations_chunk_size: None,
4135                                },
4136                            );
4137
4138                        // Enable the new depth-first block sync logic.
4139                        cfg.feature_flags.consensus_batched_block_sync = true;
4140
4141                        // Enable nitro attestation upgraded parsing logic and enable the
4142                        // native function on mainnet.
4143                        cfg.feature_flags.enable_nitro_attestation_upgraded_parsing = true;
4144                        cfg.feature_flags.enable_nitro_attestation = true;
4145                    }
4146                }
4147                84 => {
4148                    if chain == Chain::Mainnet {
4149                        cfg.feature_flags.resolve_type_input_ids_to_defining_id = true;
4150                        cfg.transfer_party_transfer_internal_cost_base = Some(52);
4151
4152                        // Enable execution time estimate mode for congestion control on mainnet.
4153                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4154                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4155                        cfg.feature_flags.per_object_congestion_control_mode =
4156                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4157                                ExecutionTimeEstimateParams {
4158                                    target_utilization: 30,
4159                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4160                                    randomness_scalar: 20,
4161                                    max_estimate_us: 1_500_000, // 1.5s
4162                                    stored_observations_num_included_checkpoints: 10,
4163                                    stored_observations_limit: u64::MAX,
4164                                    stake_weighted_median_threshold: 0,
4165                                    default_none_duration_for_new_keys: false,
4166                                    observations_chunk_size: None,
4167                                },
4168                            );
4169
4170                        // Enable the new depth-first block sync logic.
4171                        cfg.feature_flags.consensus_batched_block_sync = true;
4172
4173                        // Enable nitro attestation upgraded parsing logic and enable the
4174                        // native function on mainnet.
4175                        cfg.feature_flags.enable_nitro_attestation_upgraded_parsing = true;
4176                        cfg.feature_flags.enable_nitro_attestation = true;
4177                    }
4178
4179                    // Limit the number of stored execution time observations at end of epoch.
4180                    cfg.feature_flags.per_object_congestion_control_mode =
4181                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4182                            ExecutionTimeEstimateParams {
4183                                target_utilization: 30,
4184                                allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4185                                randomness_scalar: 20,
4186                                max_estimate_us: 1_500_000, // 1.5s
4187                                stored_observations_num_included_checkpoints: 10,
4188                                stored_observations_limit: 20,
4189                                stake_weighted_median_threshold: 0,
4190                                default_none_duration_for_new_keys: false,
4191                                observations_chunk_size: None,
4192                            },
4193                        );
4194                    cfg.feature_flags.allow_unbounded_system_objects = true;
4195                }
4196                85 => {
4197                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4198                        cfg.feature_flags.enable_party_transfer = true;
4199                    }
4200
4201                    cfg.feature_flags
4202                        .record_consensus_determined_version_assignments_in_prologue_v2 = true;
4203                    cfg.feature_flags.disallow_self_identifier = true;
4204                    cfg.feature_flags.per_object_congestion_control_mode =
4205                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4206                            ExecutionTimeEstimateParams {
4207                                target_utilization: 50,
4208                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4209                                randomness_scalar: 20,
4210                                max_estimate_us: 1_500_000, // 1.5s
4211                                stored_observations_num_included_checkpoints: 10,
4212                                stored_observations_limit: 20,
4213                                stake_weighted_median_threshold: 0,
4214                                default_none_duration_for_new_keys: false,
4215                                observations_chunk_size: None,
4216                            },
4217                        );
4218                }
4219                86 => {
4220                    cfg.feature_flags.type_tags_in_object_runtime = true;
4221                    cfg.max_move_enum_variants = Some(move_core_types::VARIANT_COUNT_MAX);
4222
4223                    // Set a stake_weighted_median_threshold for congestion control.
4224                    cfg.feature_flags.per_object_congestion_control_mode =
4225                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4226                            ExecutionTimeEstimateParams {
4227                                target_utilization: 50,
4228                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4229                                randomness_scalar: 20,
4230                                max_estimate_us: 1_500_000, // 1.5s
4231                                stored_observations_num_included_checkpoints: 10,
4232                                stored_observations_limit: 20,
4233                                stake_weighted_median_threshold: 3334,
4234                                default_none_duration_for_new_keys: false,
4235                                observations_chunk_size: None,
4236                            },
4237                        );
4238                    // Enable party transfer for testnet.
4239                    if chain != Chain::Mainnet {
4240                        cfg.feature_flags.enable_party_transfer = true;
4241                    }
4242                }
4243                87 => {
4244                    if chain == Chain::Mainnet {
4245                        cfg.feature_flags.record_time_estimate_processed = true;
4246                    }
4247                    cfg.feature_flags.better_adapter_type_resolution_errors = true;
4248                }
4249                88 => {
4250                    cfg.feature_flags.record_time_estimate_processed = true;
4251                    cfg.tx_context_rgp_cost_base = Some(30);
4252                    cfg.feature_flags
4253                        .ignore_execution_time_observations_after_certs_closed = true;
4254
4255                    // Disable backwards compatible behavior in execution time estimator for
4256                    // new protocol version.
4257                    cfg.feature_flags.per_object_congestion_control_mode =
4258                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4259                            ExecutionTimeEstimateParams {
4260                                target_utilization: 50,
4261                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4262                                randomness_scalar: 20,
4263                                max_estimate_us: 1_500_000, // 1.5s
4264                                stored_observations_num_included_checkpoints: 10,
4265                                stored_observations_limit: 20,
4266                                stake_weighted_median_threshold: 3334,
4267                                default_none_duration_for_new_keys: true,
4268                                observations_chunk_size: None,
4269                            },
4270                        );
4271                }
4272                89 => {
4273                    cfg.feature_flags.dependency_linkage_error = true;
4274                    cfg.feature_flags.additional_multisig_checks = true;
4275                }
4276                90 => {
4277                    // 100x RGP
4278                    cfg.max_gas_price_rgp_factor_for_aborted_transactions = Some(100);
4279                    cfg.feature_flags.debug_fatal_on_move_invariant_violation = true;
4280                    cfg.feature_flags.additional_consensus_digest_indirect_state = true;
4281                    cfg.feature_flags.accept_passkey_in_multisig = true;
4282                    cfg.feature_flags.passkey_auth = true;
4283                    cfg.feature_flags.check_for_init_during_upgrade = true;
4284
4285                    // Enable Mysticeti fastpath handlers on testnet.
4286                    if chain != Chain::Mainnet {
4287                        cfg.feature_flags.mysticeti_fastpath = true;
4288                    }
4289                }
4290                91 => {
4291                    cfg.feature_flags.per_command_shared_object_transfer_rules = true;
4292                }
4293                92 => {
4294                    cfg.feature_flags.per_command_shared_object_transfer_rules = false;
4295                }
4296                93 => {
4297                    cfg.feature_flags
4298                        .consensus_checkpoint_signature_key_includes_digest = true;
4299                }
4300                94 => {
4301                    // Decrease stored observations limit 20->18 to stay within system object size limit.
4302                    cfg.feature_flags.per_object_congestion_control_mode =
4303                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4304                            ExecutionTimeEstimateParams {
4305                                target_utilization: 50,
4306                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4307                                randomness_scalar: 20,
4308                                max_estimate_us: 1_500_000, // 1.5s
4309                                stored_observations_num_included_checkpoints: 10,
4310                                stored_observations_limit: 18,
4311                                stake_weighted_median_threshold: 3334,
4312                                default_none_duration_for_new_keys: true,
4313                                observations_chunk_size: None,
4314                            },
4315                        );
4316
4317                    // Enable party transfer on mainnet.
4318                    cfg.feature_flags.enable_party_transfer = true;
4319                }
4320                95 => {
4321                    cfg.type_name_id_base_cost = Some(52);
4322
4323                    // Reduce the frequency of checkpoint splitting under high TPS.
4324                    cfg.max_transactions_per_checkpoint = Some(20_000);
4325                }
4326                96 => {
4327                    // Enable artifacts digest in devnet.
4328                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4329                        cfg.feature_flags
4330                            .include_checkpoint_artifacts_digest_in_summary = true;
4331                    }
4332                    cfg.feature_flags.correct_gas_payment_limit_check = true;
4333                    cfg.feature_flags.authority_capabilities_v2 = true;
4334                    cfg.feature_flags.use_mfp_txns_in_load_initial_object_debts = true;
4335                    cfg.feature_flags.cancel_for_failed_dkg_early = true;
4336                    cfg.feature_flags.enable_coin_registry = true;
4337
4338                    // Enable Mysticeti fastpath handlers on mainnet.
4339                    cfg.feature_flags.mysticeti_fastpath = true;
4340                }
4341                97 => {
4342                    cfg.feature_flags.additional_borrow_checks = true;
4343                }
4344                98 => {
4345                    cfg.event_emit_auth_stream_cost = Some(52);
4346                    cfg.feature_flags.better_loader_errors = true;
4347                    cfg.feature_flags.generate_df_type_layouts = true;
4348                }
4349                99 => {
4350                    cfg.feature_flags.use_new_commit_handler = true;
4351                }
4352                100 => {
4353                    cfg.feature_flags.private_generics_verifier_v2 = true;
4354                }
4355                101 => {
4356                    cfg.feature_flags.create_root_accumulator_object = true;
4357                    cfg.max_updates_per_settlement_txn = Some(100);
4358                    if chain != Chain::Mainnet {
4359                        cfg.feature_flags.enable_poseidon = true;
4360                    }
4361                }
4362                102 => {
4363                    // Enable execution time observation chunking and increase limit to 180.
4364                    // max_move_object_size is 250 KB, we've experientially determined that fits ~ 18 estimates
4365                    // so if we have 10 chunks, that's 2.5MB, < 8MB max_serialized_tx_effects_size_bytes_system_tx
4366                    cfg.feature_flags.per_object_congestion_control_mode =
4367                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4368                            ExecutionTimeEstimateParams {
4369                                target_utilization: 50,
4370                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4371                                randomness_scalar: 20,
4372                                max_estimate_us: 1_500_000, // 1.5s
4373                                stored_observations_num_included_checkpoints: 10,
4374                                stored_observations_limit: 180,
4375                                stake_weighted_median_threshold: 3334,
4376                                default_none_duration_for_new_keys: true,
4377                                observations_chunk_size: Some(18),
4378                            },
4379                        );
4380                    cfg.feature_flags.deprecate_global_storage_ops = true;
4381                }
4382                103 => {}
4383                104 => {
4384                    cfg.translation_per_command_base_charge = Some(1);
4385                    cfg.translation_per_input_base_charge = Some(1);
4386                    cfg.translation_pure_input_per_byte_charge = Some(1);
4387                    cfg.translation_per_type_node_charge = Some(1);
4388                    cfg.translation_per_reference_node_charge = Some(1);
4389                    cfg.translation_per_linkage_entry_charge = Some(10);
4390                    cfg.gas_model_version = Some(11);
4391                    cfg.feature_flags.abstract_size_in_object_runtime = true;
4392                    cfg.feature_flags.object_runtime_charge_cache_load_gas = true;
4393                    cfg.dynamic_field_hash_type_and_key_cost_base = Some(52);
4394                    cfg.dynamic_field_add_child_object_cost_base = Some(52);
4395                    cfg.dynamic_field_add_child_object_value_cost_per_byte = Some(1);
4396                    cfg.dynamic_field_borrow_child_object_cost_base = Some(52);
4397                    cfg.dynamic_field_borrow_child_object_child_ref_cost_per_byte = Some(1);
4398                    cfg.dynamic_field_remove_child_object_cost_base = Some(52);
4399                    cfg.dynamic_field_remove_child_object_child_cost_per_byte = Some(1);
4400                    cfg.dynamic_field_has_child_object_cost_base = Some(52);
4401                    cfg.dynamic_field_has_child_object_with_ty_cost_base = Some(52);
4402                    cfg.feature_flags.enable_ptb_execution_v2 = true;
4403
4404                    cfg.poseidon_bn254_cost_base = Some(260);
4405
4406                    cfg.feature_flags.consensus_skip_gced_accept_votes = true;
4407
4408                    if chain != Chain::Mainnet {
4409                        cfg.feature_flags
4410                            .enable_nitro_attestation_all_nonzero_pcrs_parsing = true;
4411                    }
4412
4413                    cfg.feature_flags
4414                        .include_cancelled_randomness_txns_in_prologue = true;
4415                }
4416                105 => {
4417                    cfg.feature_flags.enable_multi_epoch_transaction_expiration = true;
4418                    cfg.feature_flags.disable_preconsensus_locking = true;
4419
4420                    if chain != Chain::Mainnet {
4421                        cfg.feature_flags
4422                            .enable_nitro_attestation_always_include_required_pcrs_parsing = true;
4423                    }
4424                }
4425                106 => {
4426                    // est. 100 bytes per object * 76 (storage_gas_price)
4427                    cfg.accumulator_object_storage_cost = Some(7600);
4428
4429                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4430                        cfg.feature_flags.enable_accumulators = true;
4431                        cfg.feature_flags.enable_address_balance_gas_payments = true;
4432                        cfg.feature_flags.enable_authenticated_event_streams = true;
4433                        cfg.feature_flags.enable_object_funds_withdraw = true;
4434                    }
4435                }
4436                107 => {
4437                    cfg.feature_flags
4438                        .consensus_skip_gced_blocks_in_direct_finalization = true;
4439
4440                    // Trigger edge cases more often in integration tests.
4441                    if in_integration_test() {
4442                        cfg.consensus_gc_depth = Some(6);
4443                        cfg.consensus_max_num_transactions_in_block = Some(8);
4444                    }
4445                }
4446                108 => {
4447                    cfg.feature_flags.gas_rounding_halve_digits = true;
4448                    cfg.feature_flags.flexible_tx_context_positions = true;
4449                    cfg.feature_flags.disable_entry_point_signature_check = true;
4450
4451                    if chain != Chain::Mainnet {
4452                        cfg.feature_flags.address_aliases = true;
4453
4454                        cfg.feature_flags.enable_accumulators = true;
4455                        cfg.feature_flags.enable_address_balance_gas_payments = true;
4456                    }
4457
4458                    cfg.feature_flags.enable_poseidon = true;
4459                }
4460                109 => {
4461                    cfg.binary_variant_handles = Some(1024);
4462                    cfg.binary_variant_instantiation_handles = Some(1024);
4463                    cfg.feature_flags.restrict_hot_or_not_entry_functions = true;
4464                }
4465                110 => {
4466                    cfg.feature_flags
4467                        .enable_nitro_attestation_all_nonzero_pcrs_parsing = true;
4468                    cfg.feature_flags
4469                        .enable_nitro_attestation_always_include_required_pcrs_parsing = true;
4470                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4471                        cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4472                    }
4473                    cfg.feature_flags.validate_zklogin_public_identifier = true;
4474                    cfg.feature_flags.fix_checkpoint_signature_mapping = true;
4475                    cfg.feature_flags
4476                        .consensus_always_accept_system_transactions = true;
4477                    if chain != Chain::Mainnet {
4478                        cfg.feature_flags.enable_object_funds_withdraw = true;
4479                    }
4480                }
4481                111 => {
4482                    cfg.feature_flags.validator_metadata_verify_v2 = true;
4483                }
4484                112 => {
4485                    cfg.group_ops_ristretto_decode_scalar_cost = Some(7);
4486                    cfg.group_ops_ristretto_decode_point_cost = Some(200);
4487                    cfg.group_ops_ristretto_scalar_add_cost = Some(10);
4488                    cfg.group_ops_ristretto_point_add_cost = Some(500);
4489                    cfg.group_ops_ristretto_scalar_sub_cost = Some(10);
4490                    cfg.group_ops_ristretto_point_sub_cost = Some(500);
4491                    cfg.group_ops_ristretto_scalar_mul_cost = Some(11);
4492                    cfg.group_ops_ristretto_point_mul_cost = Some(1200);
4493                    cfg.group_ops_ristretto_scalar_div_cost = Some(151);
4494                    cfg.group_ops_ristretto_point_div_cost = Some(2500);
4495
4496                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4497                        cfg.feature_flags.enable_ristretto255_group_ops = true;
4498                    }
4499                }
4500                113 => {
4501                    cfg.feature_flags.address_balance_gas_check_rgp_at_signing = true;
4502                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4503                        cfg.feature_flags.defer_unpaid_amplification = true;
4504                    }
4505                }
4506                114 => {
4507                    cfg.feature_flags.randomize_checkpoint_tx_limit_in_tests = true;
4508                    cfg.feature_flags.address_balance_gas_reject_gas_coin_arg = true;
4509                    if chain != Chain::Mainnet {
4510                        cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4511                        cfg.feature_flags.enable_authenticated_event_streams = true;
4512                        cfg.feature_flags
4513                            .include_checkpoint_artifacts_digest_in_summary = true;
4514                    }
4515                }
4516                115 => {
4517                    cfg.feature_flags.normalize_depth_formula = true;
4518                }
4519                116 => {
4520                    cfg.feature_flags.gasless_transaction_drop_safety = true;
4521                    cfg.feature_flags.address_aliases = true;
4522                    cfg.feature_flags.relax_valid_during_for_owned_inputs = true;
4523                    // Disabled while debugging
4524                    cfg.feature_flags.defer_unpaid_amplification = false;
4525                    cfg.feature_flags.enable_display_registry = true;
4526                }
4527                117 => {}
4528                118 => {
4529                    cfg.feature_flags.use_coin_party_owner = true;
4530                }
4531                119 => {
4532                    // Enable new VM.
4533                    cfg.execution_version = Some(4);
4534                    cfg.feature_flags.address_balance_gas_reject_gas_coin_arg = false;
4535                    cfg.feature_flags.merge_randomness_into_checkpoint = true;
4536                    if chain != Chain::Mainnet {
4537                        cfg.feature_flags.enable_gasless = true;
4538                        cfg.gasless_max_computation_units = Some(50_000);
4539                        cfg.gasless_allowed_token_types = Some(vec![]);
4540                        cfg.feature_flags.enable_coin_reservation_obj_refs = true;
4541                        cfg.feature_flags
4542                            .convert_withdrawal_compatibility_ptb_arguments = true;
4543                    }
4544                    cfg.gasless_max_unused_inputs = Some(1);
4545                    cfg.gasless_max_pure_input_bytes = Some(32);
4546                    if chain == Chain::Testnet {
4547                        cfg.gasless_allowed_token_types = Some(vec![(TESTNET_USDC.to_string(), 0)]);
4548                    }
4549                    cfg.transfer_receive_object_cost_per_byte = Some(1);
4550                    cfg.transfer_receive_object_type_cost_per_byte = Some(2);
4551                }
4552                120 => {
4553                    cfg.feature_flags.disallow_jump_orphans = true;
4554                }
4555                121 => {
4556                    // Re-enable unpaid amplification deferral protection (testnet + devnet)
4557                    if chain != Chain::Mainnet {
4558                        cfg.feature_flags.defer_unpaid_amplification = true;
4559                        cfg.gasless_max_tps = Some(50);
4560                    }
4561                    cfg.feature_flags
4562                        .early_return_receive_object_mismatched_type = true;
4563                }
4564                122 => {
4565                    // Enable unpaid amplification deferral on mainnet
4566                    cfg.feature_flags.defer_unpaid_amplification = true;
4567                    // Enable bulletproofs range proofs on devnet
4568                    cfg.verify_bulletproofs_ristretto255_base_cost = Some(30000);
4569                    cfg.verify_bulletproofs_ristretto255_cost_per_bit_and_commitment = Some(6500);
4570                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4571                        cfg.feature_flags.enable_verify_bulletproofs_ristretto255 = true;
4572                    }
4573                    cfg.feature_flags.gasless_verify_remaining_balance = true;
4574                    cfg.include_special_package_amendments = match chain {
4575                        Chain::Mainnet => Some(MAINNET_LINKAGE_AMENDMENTS.clone()),
4576                        Chain::Testnet => Some(TESTNET_LINKAGE_AMENDMENTS.clone()),
4577                        Chain::Unknown => None,
4578                    };
4579                    cfg.gasless_max_tx_size_bytes = Some(16 * 1024);
4580                    cfg.gasless_max_tps = Some(300);
4581                    cfg.gasless_max_computation_units = Some(5_000);
4582                }
4583                123 => {
4584                    cfg.gas_model_version = Some(13);
4585                }
4586                124 => {
4587                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4588                        cfg.feature_flags.timestamp_based_epoch_close = true;
4589                    }
4590                    cfg.gas_model_version = Some(14);
4591                    cfg.feature_flags.limit_groth16_pvk_inputs = true;
4592
4593                    // Bring mainnet in line with testnet: enable address balances, the
4594                    // gasless "free tier", coin reservations, and the rest of the
4595                    // accumulator/withdraw stack. These are all already enabled on
4596                    // testnet and devnet, so setting them unconditionally is a no-op
4597                    // there.
4598                    cfg.feature_flags.enable_accumulators = true;
4599                    cfg.feature_flags.enable_address_balance_gas_payments = true;
4600                    cfg.feature_flags.enable_authenticated_event_streams = true;
4601                    cfg.feature_flags.enable_coin_reservation_obj_refs = true;
4602                    cfg.feature_flags.enable_object_funds_withdraw = true;
4603                    cfg.feature_flags
4604                        .convert_withdrawal_compatibility_ptb_arguments = true;
4605                    cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4606                    cfg.feature_flags
4607                        .include_checkpoint_artifacts_digest_in_summary = true;
4608                    cfg.feature_flags.enable_gasless = true;
4609
4610                    // Set the mainnet allow-list. Testnet already has its USDC entry
4611                    // from v119, so only set this on mainnet to avoid clobbering the
4612                    // testnet value. $0.01 minimum transfer per stable; all listed
4613                    // tokens have 6 decimals.
4614                    if chain == Chain::Mainnet {
4615                        cfg.gasless_allowed_token_types = Some(vec![
4616                            (MAINNET_USDC.to_string(), 10_000),
4617                            (MAINNET_USDSUI.to_string(), 10_000),
4618                            (MAINNET_SUI_USDE.to_string(), 10_000),
4619                            (MAINNET_USDY.to_string(), 10_000),
4620                            (MAINNET_FDUSD.to_string(), 10_000),
4621                            (MAINNET_AUSD.to_string(), 10_000),
4622                            (MAINNET_USDB.to_string(), 10_000),
4623                        ]);
4624                    }
4625                }
4626                125 => {
4627                    cfg.feature_flags.granular_post_execution_checks = true;
4628                    if chain != Chain::Mainnet {
4629                        cfg.feature_flags.timestamp_based_epoch_close = true;
4630                    }
4631                }
4632                126 => {
4633                    cfg.feature_flags.early_exit_on_iffw = true;
4634                }
4635                127 => {
4636                    cfg.feature_flags.always_advance_dkg_to_resolution = true;
4637
4638                    cfg.verify_bulletproofs_ristretto255_base_cost = Some(23866);
4639                    cfg.verify_bulletproofs_ristretto255_cost_per_bit_and_commitment = Some(1324);
4640                    cfg.group_ops_ristretto_decode_scalar_cost = Some(5);
4641                    cfg.group_ops_ristretto_decode_point_cost = Some(216);
4642                    cfg.group_ops_ristretto_scalar_add_cost = Some(2);
4643                    cfg.group_ops_ristretto_point_add_cost = Some(8);
4644                    cfg.group_ops_ristretto_scalar_sub_cost = Some(2);
4645                    cfg.group_ops_ristretto_point_sub_cost = Some(8);
4646                    cfg.group_ops_ristretto_scalar_mul_cost = Some(5);
4647                    cfg.group_ops_ristretto_point_mul_cost = Some(1763);
4648                    cfg.group_ops_ristretto_scalar_div_cost = Some(557);
4649                    cfg.group_ops_ristretto_point_div_cost = Some(2244);
4650
4651                    if chain != Chain::Mainnet {
4652                        cfg.feature_flags.enable_ristretto255_group_ops = true;
4653                        cfg.feature_flags.enable_verify_bulletproofs_ristretto255 = true;
4654                    }
4655
4656                    cfg.feature_flags.timestamp_based_epoch_close = true;
4657                }
4658                128 => {
4659                    cfg.max_generic_instantiation_type_nodes_per_function = Some(10_000);
4660                    cfg.max_generic_instantiation_type_nodes_per_module = Some(500_000);
4661                    cfg.binary_enum_defs = Some(200);
4662                    cfg.binary_enum_def_instantiations = Some(100);
4663                }
4664                129 => {
4665                    cfg.feature_flags.enable_unified_linkage = true;
4666                }
4667                130 => {
4668                    cfg.feature_flags.record_net_unsettled_object_withdraws = true;
4669                    cfg.feature_flags.enable_init_on_upgrade = true;
4670                    cfg.epoch_close_deadline_ms = Some(120_000);
4671                    cfg.scratch_add_cost_base = Some(13);
4672                    cfg.scratch_read_cost_base = Some(13);
4673                    cfg.scratch_read_value_cost = Some(1);
4674                    cfg.scratch_remove_cost_base = Some(13);
4675                    cfg.scratch_exists_cost_base = Some(13);
4676                    cfg.scratch_exists_with_type_cost_base = Some(13);
4677                    cfg.scratch_exists_with_type_type_cost = Some(1);
4678                    let max_commands = cfg.max_programmable_tx_commands() as u64;
4679                    cfg.max_scratch_pad_size = Some(16 * max_commands);
4680                    // Verify with the v2 then v1 for devnet.
4681                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4682                        cfg.feature_flags.zklogin_circuit_mode = 1;
4683                    }
4684                }
4685                131 => {
4686                    cfg.feature_flags.share_transaction_deny_config_in_consensus = true;
4687                    cfg.feature_flags.framework_tx_context_mut_restrictions = true;
4688                }
4689                132 => {
4690                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4691                        cfg.feature_flags.defer_owned_object_double_spend = true;
4692                        cfg.feature_flags.create_forwarding_address_registry = true;
4693                    }
4694                    cfg.object_record_new_uid_from_hash_cost_base = Some(1);
4695                    cfg.feature_flags
4696                        .enable_order_independent_upgrade_init_linkage = true;
4697                }
4698                133 => {
4699                    cfg.feature_flags
4700                        .include_function_signatures_in_instantiation_limits = true;
4701                    cfg.max_accumulator_type_nodes = Some(16);
4702                }
4703                134 => {
4704                    // v134 was released to testnet with this content before the 1.77
4705                    // branch backfilled its own v134 to disable defer_unpaid_amplification
4706                    // on mainnet. To keep (v134, Mainnet) identical across the 1.77 and
4707                    // 1.78 branches, the original v134 content is gated off mainnet here
4708                    // (it applies to mainnet in v135 instead), and mainnet's v134 carries
4709                    // only the deferral disable.
4710                    if chain != Chain::Mainnet {
4711                        cfg.package_original_package_id_impl_cost_base = Some(52);
4712                        let package_read_cost_per_byte = cfg.obj_access_cost_read_per_byte();
4713                        cfg.package_original_package_id_impl_cost_per_byte =
4714                            Some(package_read_cost_per_byte);
4715
4716                        cfg.consensus_max_transactions_in_block_bytes = Some(288 * 1024);
4717                        cfg.consensus_max_num_transactions_in_block = Some(128);
4718                    }
4719
4720                    if chain == Chain::Mainnet {
4721                        cfg.feature_flags.defer_unpaid_amplification = false;
4722                    }
4723                }
4724                135 => {
4725                    // Apply the original v134 content on mainnet (no-op re-assignment on
4726                    // chains that already applied it in v134).
4727                    cfg.package_original_package_id_impl_cost_base = Some(52);
4728                    let package_read_cost_per_byte = cfg.obj_access_cost_read_per_byte();
4729                    cfg.package_original_package_id_impl_cost_per_byte =
4730                        Some(package_read_cost_per_byte);
4731
4732                    cfg.consensus_max_transactions_in_block_bytes = Some(288 * 1024);
4733                    cfg.consensus_max_num_transactions_in_block = Some(128);
4734
4735                    cfg.feature_flags.defer_unpaid_amplification = false;
4736                }
4737                136 => {
4738                    cfg.feature_flags.ptb_tx_context_restrictions = true;
4739
4740                    cfg.translation_per_live_reference_charge = Some(1);
4741                    cfg.max_ptb_live_references = Some(64);
4742                    cfg.max_ptb_returned_references = Some(16);
4743                    cfg.max_ptb_total_returned_references = Some(256);
4744
4745                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4746                        cfg.feature_flags.allowed_proposers = true;
4747                    }
4748                    cfg.feature_flags.harden_linkage_consistency = true;
4749
4750                    cfg.package_arena_size_in_bytes = Some(10_000_000);
4751                }
4752                137 => {
4753                    cfg.verify_bulletproofs_ristretto255_cost_per_bit_and_commitment = Some(621);
4754                    cfg.max_bulletproofs_total_bits = Some(1024);
4755
4756                    cfg.feature_flags.enable_allowances = true;
4757                    cfg.feature_flags.fix_ptb_generated_reads = true;
4758                    cfg.feature_flags.charge_ld_const_abstract_size = true;
4759                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4760                        cfg.feature_flags.check_object_funds_withdraw_in_execution = true;
4761                    }
4762                    cfg.reserve_object_funds_for_withdrawal_cost_base = Some(52);
4763                    // Equivalent to the fixed portion of a dynamic-field lookup (52 + 52) plus
4764                    // loading the 80-byte accumulator field contents at one gas unit per byte.
4765                    cfg.reserve_object_funds_for_withdrawal_cold_read_cost = Some(184);
4766
4767                    cfg.feature_flags.allowed_proposers = true;
4768
4769                    cfg.feature_flags.validate_ptb_argument_indices = true;
4770                    cfg.feature_flags.memory_safety_invariant_check_v2 = true;
4771                }
4772                // Use this template when making changes:
4773                //
4774                //     // modify an existing constant.
4775                //     move_binary_format_version: Some(7),
4776                //
4777                //     // Add a new constant (which is set to None in prior versions).
4778                //     new_constant: Some(new_value),
4779                //
4780                //     // Remove a constant (ensure that it is never accessed during this version).
4781                //     max_move_object_size: None,
4782                _ => panic!("unsupported version {:?}", version),
4783            }
4784        }
4785
4786        cfg
4787    }
4788
4789    pub fn apply_seeded_test_overrides(&mut self, seed: &[u8; 32]) {
4790        if !self.feature_flags.randomize_checkpoint_tx_limit_in_tests
4791            || !self.feature_flags.split_checkpoints_in_consensus_handler
4792        {
4793            return;
4794        }
4795
4796        if !mysten_common::in_test_configuration() {
4797            return;
4798        }
4799
4800        use rand::{Rng, SeedableRng, rngs::StdRng};
4801        let mut rng = StdRng::from_seed(*seed);
4802        let max_txns = rng.gen_range(10..=100u64);
4803        info!("seeded test override: max_transactions_per_checkpoint = {max_txns}");
4804        self.max_transactions_per_checkpoint = Some(max_txns);
4805    }
4806
4807    // Extract the bytecode verifier config from this protocol config.
4808    // If used during signing, `signing_limits` should be set.
4809    // The third limit configures`sanity_check_with_regex_reference_safety`,
4810    // which runs the new regex-based reference safety check to check that it is strictly more
4811    // permissive than the current implementation.
4812    pub fn verifier_config(&self, signing_limits: Option<(usize, usize, usize)>) -> VerifierConfig {
4813        let (
4814            max_back_edges_per_function,
4815            max_back_edges_per_module,
4816            sanity_check_with_regex_reference_safety,
4817        ) = if let Some((
4818            max_back_edges_per_function,
4819            max_back_edges_per_module,
4820            sanity_check_with_regex_reference_safety,
4821        )) = signing_limits
4822        {
4823            (
4824                Some(max_back_edges_per_function),
4825                Some(max_back_edges_per_module),
4826                Some(sanity_check_with_regex_reference_safety),
4827            )
4828        } else {
4829            (None, None, None)
4830        };
4831
4832        let additional_borrow_checks = if signing_limits.is_some() {
4833            // always turn on additional borrow checks during signing
4834            true
4835        } else {
4836            self.additional_borrow_checks()
4837        };
4838        let deprecate_global_storage_ops = if signing_limits.is_some() {
4839            // always turn on additional vector borrow checks during signing
4840            true
4841        } else {
4842            self.deprecate_global_storage_ops()
4843        };
4844
4845        VerifierConfig {
4846            max_loop_depth: Some(self.max_loop_depth() as usize),
4847            max_generic_instantiation_length: Some(self.max_generic_instantiation_length() as usize),
4848            max_function_parameters: Some(self.max_function_parameters() as usize),
4849            max_basic_blocks: Some(self.max_basic_blocks() as usize),
4850            max_value_stack_size: self.max_value_stack_size() as usize,
4851            max_type_nodes: Some(self.max_type_nodes() as usize),
4852            max_generic_instantiation_type_nodes_per_function: self
4853                .max_generic_instantiation_type_nodes_per_function_as_option()
4854                .map(|v| v as usize),
4855            max_generic_instantiation_type_nodes_per_module: self
4856                .max_generic_instantiation_type_nodes_per_module_as_option()
4857                .map(|v| v as usize),
4858            include_function_signatures_in_instantiation_limits: self
4859                .include_function_signatures_in_instantiation_limits(),
4860            max_push_size: Some(self.max_push_size() as usize),
4861            max_dependency_depth: Some(self.max_dependency_depth() as usize),
4862            max_fields_in_struct: Some(self.max_fields_in_struct() as usize),
4863            max_function_definitions: Some(self.max_function_definitions() as usize),
4864            max_data_definitions: Some(self.max_struct_definitions() as usize),
4865            max_constant_vector_len: Some(self.max_move_vector_len()),
4866            max_back_edges_per_function,
4867            max_back_edges_per_module,
4868            max_basic_blocks_in_script: None,
4869            max_identifier_len: self.max_move_identifier_len_as_option(), // Before protocol version 9, there was no limit
4870            disallow_self_identifier: self.feature_flags.disallow_self_identifier,
4871            allow_receiving_object_id: self.allow_receiving_object_id(),
4872            reject_mutable_random_on_entry_functions: self
4873                .reject_mutable_random_on_entry_functions(),
4874            bytecode_version: self.move_binary_format_version(),
4875            max_variants_in_enum: self.max_move_enum_variants_as_option(),
4876            additional_borrow_checks,
4877            better_loader_errors: self.better_loader_errors(),
4878            private_generics_verifier_v2: self.private_generics_verifier_v2(),
4879            sanity_check_with_regex_reference_safety: sanity_check_with_regex_reference_safety
4880                .map(|limit| limit as u128),
4881            deprecate_global_storage_ops,
4882            disable_entry_point_signature_check: self.disable_entry_point_signature_check(),
4883            switch_to_regex_reference_safety: false,
4884            framework_tx_context_mut_restrictions: self.framework_tx_context_mut_restrictions(),
4885            disallow_jump_orphans: self.disallow_jump_orphans(),
4886        }
4887    }
4888
4889    pub fn binary_config(
4890        &self,
4891        override_deprecate_global_storage_ops_during_deserialization: Option<bool>,
4892    ) -> BinaryConfig {
4893        let deprecate_global_storage_ops =
4894            override_deprecate_global_storage_ops_during_deserialization
4895                .unwrap_or_else(|| self.deprecate_global_storage_ops());
4896        BinaryConfig::new(
4897            self.move_binary_format_version(),
4898            self.min_move_binary_format_version_as_option()
4899                .unwrap_or(VERSION_1),
4900            self.no_extraneous_module_bytes(),
4901            deprecate_global_storage_ops,
4902            TableConfig {
4903                module_handles: self.binary_module_handles_as_option().unwrap_or(u16::MAX),
4904                datatype_handles: self.binary_struct_handles_as_option().unwrap_or(u16::MAX),
4905                function_handles: self.binary_function_handles_as_option().unwrap_or(u16::MAX),
4906                function_instantiations: self
4907                    .binary_function_instantiations_as_option()
4908                    .unwrap_or(u16::MAX),
4909                signatures: self.binary_signatures_as_option().unwrap_or(u16::MAX),
4910                constant_pool: self.binary_constant_pool_as_option().unwrap_or(u16::MAX),
4911                identifiers: self.binary_identifiers_as_option().unwrap_or(u16::MAX),
4912                address_identifiers: self
4913                    .binary_address_identifiers_as_option()
4914                    .unwrap_or(u16::MAX),
4915                struct_defs: self.binary_struct_defs_as_option().unwrap_or(u16::MAX),
4916                struct_def_instantiations: self
4917                    .binary_struct_def_instantiations_as_option()
4918                    .unwrap_or(u16::MAX),
4919                function_defs: self.binary_function_defs_as_option().unwrap_or(u16::MAX),
4920                field_handles: self.binary_field_handles_as_option().unwrap_or(u16::MAX),
4921                field_instantiations: self
4922                    .binary_field_instantiations_as_option()
4923                    .unwrap_or(u16::MAX),
4924                friend_decls: self.binary_friend_decls_as_option().unwrap_or(u16::MAX),
4925                enum_defs: self.binary_enum_defs_as_option().unwrap_or(u16::MAX),
4926                enum_def_instantiations: self
4927                    .binary_enum_def_instantiations_as_option()
4928                    .unwrap_or(u16::MAX),
4929                variant_handles: self.binary_variant_handles_as_option().unwrap_or(u16::MAX),
4930                variant_instantiation_handles: self
4931                    .binary_variant_instantiation_handles_as_option()
4932                    .unwrap_or(u16::MAX),
4933            },
4934        )
4935    }
4936
4937    /// Override one or more settings in the config, for testing.
4938    /// This must be called at the beginning of the test, before get_for_(min|max)_version is
4939    /// called, since those functions cache their return value.
4940    pub fn apply_overrides_for_testing(
4941        override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + Sync + 'static,
4942    ) -> OverrideGuard {
4943        let mut cur = CONFIG_OVERRIDE.lock().unwrap();
4944        assert!(cur.is_none(), "config override already present");
4945        *cur = Some(Box::new(override_fn));
4946        OverrideGuard
4947    }
4948
4949    fn apply_config_override(version: ProtocolVersion, mut ret: Self) -> Self {
4950        if let Some(override_fn) = CONFIG_OVERRIDE.lock().unwrap().as_ref() {
4951            warn!(
4952                "overriding ProtocolConfig settings with custom settings (you should not see this log outside of tests)"
4953            );
4954            ret = override_fn(version, ret);
4955        }
4956        ret
4957    }
4958}
4959
4960// Setters for tests.
4961// This is only needed for feature_flags. Please suffix each setter with `_for_testing`.
4962// Non-feature_flags should already have test setters defined through macros.
4963impl ProtocolConfig {
4964    // Hand-written (the field is marked #[custom_setter]) to forbid downgrades: an executor
4965    // older than the config's protocol version can't link the frameworks of later versions —
4966    // its natives tables are frozen. Upgrades are allowed for replay's executor override.
4967    pub fn set_execution_version_for_testing(&mut self, val: u64) {
4968        let current = self.execution_version.unwrap_or(0);
4969        assert!(
4970            val >= current,
4971            "cannot downgrade execution_version from {current} to {val}: running an old \
4972             executor against a newer protocol config/framework is unsupported. To test \
4973             frozen executor behavior, start from the last protocol version of that executor \
4974             instead, so genesis loads the matching framework snapshot (see \
4975             test_address_balance_gas_v3_accumulator_sign)."
4976        );
4977        self.execution_version = Some(val);
4978    }
4979
4980    // Not generated by the feature-flags derive because zklogin_circuit_mode is a u64
4981    // flag (the macro only generates setters for bool flags).
4982    pub fn set_zklogin_circuit_mode_for_testing(&mut self, val: u64) {
4983        self.feature_flags.zklogin_circuit_mode = val
4984    }
4985
4986    pub fn set_per_object_congestion_control_mode_for_testing(
4987        &mut self,
4988        val: PerObjectCongestionControlMode,
4989    ) {
4990        self.feature_flags.per_object_congestion_control_mode = val;
4991    }
4992
4993    pub fn set_consensus_choice_for_testing(&mut self, val: ConsensusChoice) {
4994        self.feature_flags.consensus_choice = val;
4995    }
4996
4997    pub fn set_consensus_network_for_testing(&mut self, val: ConsensusNetwork) {
4998        self.feature_flags.consensus_network = val;
4999    }
5000
5001    pub fn set_zklogin_max_epoch_upper_bound_delta_for_testing(&mut self, val: Option<u64>) {
5002        self.feature_flags.zklogin_max_epoch_upper_bound_delta = val
5003    }
5004
5005    pub fn set_mysticeti_num_leaders_per_round_for_testing(&mut self, val: Option<usize>) {
5006        self.feature_flags.mysticeti_num_leaders_per_round = val;
5007    }
5008
5009    pub fn disable_accumulators_for_testing(&mut self) {
5010        self.feature_flags.enable_accumulators = false;
5011        self.feature_flags.enable_address_balance_gas_payments = false;
5012    }
5013
5014    pub fn enable_coin_reservation_for_testing(&mut self) {
5015        self.feature_flags.enable_coin_reservation_obj_refs = true;
5016        self.feature_flags
5017            .convert_withdrawal_compatibility_ptb_arguments = true;
5018        // Ensure execution_version >= 4 so new_vm_enabled() returns true,
5019        // which is required for enable_coin_reservation_obj_refs() to return true.
5020        self.execution_version = Some(self.execution_version.map_or(4, |v| v.max(4)));
5021    }
5022
5023    pub fn disable_coin_reservation_for_testing(&mut self) {
5024        self.feature_flags.enable_coin_reservation_obj_refs = false;
5025        self.feature_flags
5026            .convert_withdrawal_compatibility_ptb_arguments = false;
5027    }
5028
5029    pub fn enable_address_balance_gas_payments_for_testing(&mut self) {
5030        self.feature_flags.enable_accumulators = true;
5031        self.feature_flags.allow_private_accumulator_entrypoints = true;
5032        self.feature_flags.enable_address_balance_gas_payments = true;
5033        self.feature_flags.address_balance_gas_check_rgp_at_signing = true;
5034        self.feature_flags.address_balance_gas_reject_gas_coin_arg = false;
5035        self.execution_version = Some(self.execution_version.map_or(4, |v| v.max(4)))
5036    }
5037
5038    pub fn enable_gasless_for_testing(&mut self) {
5039        self.enable_address_balance_gas_payments_for_testing();
5040        self.feature_flags.enable_gasless = true;
5041        self.feature_flags.gasless_verify_remaining_balance = true;
5042        self.gasless_max_computation_units = Some(5_000);
5043        self.gasless_allowed_token_types = Some(vec![]);
5044        self.gasless_max_tps = Some(1000);
5045        self.gasless_max_tx_size_bytes = Some(16 * 1024);
5046    }
5047
5048    pub fn disable_gasless_for_testing(&mut self) {
5049        self.feature_flags.enable_gasless = false;
5050        self.gasless_max_computation_units = None;
5051        self.gasless_allowed_token_types = None;
5052    }
5053
5054    pub fn enable_authenticated_event_streams_for_testing(&mut self) {
5055        self.feature_flags.enable_accumulators = true;
5056        self.feature_flags.enable_authenticated_event_streams = true;
5057        self.feature_flags
5058            .include_checkpoint_artifacts_digest_in_summary = true;
5059        self.feature_flags.split_checkpoints_in_consensus_handler = true;
5060    }
5061}
5062
5063type OverrideFn = dyn Fn(ProtocolVersion, ProtocolConfig) -> ProtocolConfig + Send + Sync;
5064
5065static CONFIG_OVERRIDE: Mutex<Option<Box<OverrideFn>>> = Mutex::new(None);
5066
5067#[must_use]
5068pub struct OverrideGuard;
5069
5070impl Drop for OverrideGuard {
5071    fn drop(&mut self) {
5072        info!("restoring override fn");
5073        *CONFIG_OVERRIDE.lock().unwrap() = None;
5074    }
5075}
5076
5077/// Defines which limit got crossed.
5078/// The value which crossed the limit and value of the limit crossed are embedded
5079#[derive(PartialEq, Eq)]
5080pub enum LimitThresholdCrossed {
5081    None,
5082    Soft(u128, u128),
5083    Hard(u128, u128),
5084}
5085
5086/// Convenience function for comparing limit ranges
5087/// V::MAX must be at >= U::MAX and T::MAX
5088pub fn check_limit_in_range<T: Into<V>, U: Into<V>, V: PartialOrd + Into<u128>>(
5089    x: T,
5090    soft_limit: U,
5091    hard_limit: V,
5092) -> LimitThresholdCrossed {
5093    let x: V = x.into();
5094    let soft_limit: V = soft_limit.into();
5095
5096    debug_assert!(soft_limit <= hard_limit);
5097
5098    // It is important to preserve this comparison order because if soft_limit == hard_limit
5099    // we want LimitThresholdCrossed::Hard
5100    if x >= hard_limit {
5101        LimitThresholdCrossed::Hard(x.into(), hard_limit.into())
5102    } else if x < soft_limit {
5103        LimitThresholdCrossed::None
5104    } else {
5105        LimitThresholdCrossed::Soft(x.into(), soft_limit.into())
5106    }
5107}
5108
5109#[macro_export]
5110macro_rules! check_limit {
5111    ($x:expr, $hard:expr) => {
5112        check_limit!($x, $hard, $hard)
5113    };
5114    ($x:expr, $soft:expr, $hard:expr) => {
5115        check_limit_in_range($x as u64, $soft, $hard)
5116    };
5117}
5118
5119/// Used to check which limits were crossed if the TX is metered (not system tx)
5120/// Args are: is_metered, value_to_check, metered_limit, unmetered_limit
5121/// metered_limit is always less than or equal to unmetered_hard_limit
5122#[macro_export]
5123macro_rules! check_limit_by_meter {
5124    ($is_metered:expr, $x:expr, $metered_limit:expr, $unmetered_hard_limit:expr, $metric:expr) => {{
5125        // If this is metered, we use the metered_limit limit as the upper bound
5126        let (h, metered_str) = if $is_metered {
5127            ($metered_limit, "metered")
5128        } else {
5129            // Unmetered gets more headroom
5130            ($unmetered_hard_limit, "unmetered")
5131        };
5132        use sui_protocol_config::check_limit_in_range;
5133        let result = check_limit_in_range($x as u64, $metered_limit, h);
5134        match result {
5135            LimitThresholdCrossed::None => {}
5136            LimitThresholdCrossed::Soft(_, _) => {
5137                $metric.with_label_values(&[metered_str, "soft"]).inc();
5138            }
5139            LimitThresholdCrossed::Hard(_, _) => {
5140                $metric.with_label_values(&[metered_str, "hard"]).inc();
5141            }
5142        };
5143        result
5144    }};
5145}
5146
5147// Amendments tables
5148
5149pub type Amendments = BTreeMap<AccountAddress, BTreeMap<AccountAddress, AccountAddress>>;
5150
5151static MAINNET_LINKAGE_AMENDMENTS: LazyLock<Arc<Amendments>> =
5152    LazyLock::new(|| parse_amendments(include_str!("mainnet_amendments.json")));
5153
5154static TESTNET_LINKAGE_AMENDMENTS: LazyLock<Arc<Amendments>> =
5155    LazyLock::new(|| parse_amendments(include_str!("testnet_amendments.json")));
5156
5157fn parse_amendments(json: &str) -> Arc<Amendments> {
5158    #[derive(serde::Deserialize)]
5159    struct AmendmentEntry {
5160        root: String,
5161        deps: Vec<DepEntry>,
5162    }
5163
5164    #[derive(serde::Deserialize)]
5165    struct DepEntry {
5166        original_id: String,
5167        version_id: String,
5168    }
5169
5170    let entries: Vec<AmendmentEntry> =
5171        serde_json::from_str(json).expect("Failed to parse amendments JSON");
5172    let mut amendments = BTreeMap::new();
5173    for entry in entries {
5174        let root_id = AccountAddress::from_hex_literal(&entry.root).unwrap();
5175        let mut dep_ids = BTreeMap::new();
5176        for dep in entry.deps {
5177            let orig_id = AccountAddress::from_hex_literal(&dep.original_id).unwrap();
5178            let upgraded_id = AccountAddress::from_hex_literal(&dep.version_id).unwrap();
5179            assert!(
5180                dep_ids.insert(orig_id, upgraded_id).is_none(),
5181                "Duplicate original ID in amendments table"
5182            );
5183        }
5184        assert!(
5185            amendments.insert(root_id, dep_ids).is_none(),
5186            "Duplicate root ID in amendments table"
5187        );
5188    }
5189    Arc::new(amendments)
5190}
5191
5192#[cfg(all(test, not(msim)))]
5193mod test {
5194    use insta::assert_yaml_snapshot;
5195
5196    use super::*;
5197
5198    #[test]
5199    fn snapshot_tests() {
5200        println!("\n============================================================================");
5201        println!("!                                                                          !");
5202        println!("! IMPORTANT: never update snapshots from this test. only add new versions! !");
5203        println!("!                                                                          !");
5204        println!("============================================================================\n");
5205        for chain_id in &[Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
5206            // make Chain::Unknown snapshots compatible with pre-chain-id snapshots so that we
5207            // don't break the release-time compatibility tests. Once Chain Id configs have been
5208            // released everywhere, we can remove this and only test Mainnet and Testnet
5209            let chain_str = match chain_id {
5210                Chain::Unknown => "".to_string(),
5211                _ => format!("{:?}_", chain_id),
5212            };
5213            for i in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
5214                let cur = ProtocolVersion::new(i);
5215                assert_yaml_snapshot!(
5216                    format!("{}version_{}", chain_str, cur.as_u64()),
5217                    ProtocolConfig::get_for_version(cur, *chain_id)
5218                );
5219            }
5220        }
5221    }
5222
5223    #[test]
5224    fn test_getters() {
5225        let prot: ProtocolConfig =
5226            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5227        assert_eq!(
5228            prot.max_arguments(),
5229            prot.max_arguments_as_option().unwrap()
5230        );
5231    }
5232
5233    #[test]
5234    fn test_setters() {
5235        let mut prot: ProtocolConfig =
5236            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5237        prot.set_max_arguments_for_testing(123);
5238        assert_eq!(prot.max_arguments(), 123);
5239
5240        prot.set_max_arguments_from_str_for_testing("321".to_string());
5241        assert_eq!(prot.max_arguments(), 321);
5242
5243        prot.disable_max_arguments_for_testing();
5244        assert_eq!(prot.max_arguments_as_option(), None);
5245
5246        prot.set_attr_for_testing("max_arguments".to_string(), "456".to_string());
5247        assert_eq!(prot.max_arguments(), 456);
5248    }
5249
5250    #[test]
5251    fn test_execution_version_setter_allows_upgrade() {
5252        let mut prot = ProtocolConfig::get_for_max_version_UNSAFE();
5253        let current = prot.execution_version();
5254        prot.set_execution_version_for_testing(current);
5255        prot.set_execution_version_for_testing(current + 1);
5256        assert_eq!(prot.execution_version(), current + 1);
5257    }
5258
5259    #[test]
5260    #[should_panic(expected = "cannot downgrade execution_version")]
5261    fn test_execution_version_setter_panics_on_downgrade() {
5262        let mut prot = ProtocolConfig::get_for_max_version_UNSAFE();
5263        let current = prot.execution_version();
5264        prot.set_execution_version_for_testing(current - 1);
5265    }
5266
5267    #[test]
5268    fn test_feature_flag_setter_by_string() {
5269        let mut prot: ProtocolConfig =
5270            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5271        assert!(!prot.zklogin_auth());
5272        prot.set_feature_flag_for_testing("zklogin_auth".to_string(), true);
5273        assert!(prot.zklogin_auth());
5274        prot.set_feature_flag_for_testing("zklogin_auth".to_string(), false);
5275        assert!(!prot.zklogin_auth());
5276    }
5277
5278    #[test]
5279    #[should_panic(expected = "unknown feature flag")]
5280    fn test_feature_flag_setter_unknown_flag() {
5281        let mut prot: ProtocolConfig =
5282            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5283        prot.set_feature_flag_for_testing("some random string".to_string(), true);
5284    }
5285
5286    #[test]
5287    fn test_get_for_version_if_supported_applies_test_overrides() {
5288        let before =
5289            ProtocolConfig::get_for_version_if_supported(ProtocolVersion::new(1), Chain::Unknown)
5290                .unwrap();
5291
5292        assert!(!before.enable_coin_reservation_obj_refs());
5293
5294        let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut cfg| {
5295            cfg.enable_coin_reservation_for_testing();
5296            cfg
5297        });
5298
5299        let after =
5300            ProtocolConfig::get_for_version_if_supported(ProtocolVersion::new(1), Chain::Unknown)
5301                .unwrap();
5302
5303        assert!(after.enable_coin_reservation_obj_refs());
5304    }
5305
5306    #[test]
5307    #[should_panic(expected = "unsupported version")]
5308    fn max_version_test() {
5309        // When this does not panic, version higher than MAX_PROTOCOL_VERSION exists.
5310        // To fix, bump MAX_PROTOCOL_VERSION or disable this check for the version.
5311        let _ = ProtocolConfig::get_for_version_impl(
5312            ProtocolVersion::new(MAX_PROTOCOL_VERSION + 1),
5313            Chain::Unknown,
5314        );
5315    }
5316
5317    #[test]
5318    fn lookup_by_string_test() {
5319        let prot: ProtocolConfig =
5320            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5321        // Does not exist
5322        assert!(prot.lookup_attr("some random string".to_string()).is_none());
5323
5324        assert!(
5325            prot.lookup_attr("max_arguments".to_string())
5326                == Some(ProtocolConfigValue::u32(prot.max_arguments())),
5327        );
5328
5329        // We didnt have this in version 1
5330        assert!(
5331            prot.lookup_attr("max_move_identifier_len".to_string())
5332                .is_none()
5333        );
5334
5335        // But we did in version 9
5336        let prot: ProtocolConfig =
5337            ProtocolConfig::get_for_version(ProtocolVersion::new(9), Chain::Unknown);
5338        assert!(
5339            prot.lookup_attr("max_move_identifier_len".to_string())
5340                == Some(ProtocolConfigValue::u64(prot.max_move_identifier_len()))
5341        );
5342
5343        let prot: ProtocolConfig =
5344            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5345        // We didnt have this in version 1
5346        assert!(
5347            prot.attr_map()
5348                .get("max_move_identifier_len")
5349                .unwrap()
5350                .is_none()
5351        );
5352        // We had this in version 1
5353        assert!(
5354            prot.attr_map().get("max_arguments").unwrap()
5355                == &Some(ProtocolConfigValue::u32(prot.max_arguments()))
5356        );
5357
5358        // Check feature flags
5359        let prot: ProtocolConfig =
5360            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5361        // Does not exist
5362        assert!(
5363            prot.feature_flags
5364                .lookup_attr("some random string".to_owned())
5365                .is_none()
5366        );
5367        assert!(
5368            !prot
5369                .feature_flags
5370                .attr_map()
5371                .contains_key("some random string")
5372        );
5373
5374        // Was false in v1
5375        assert!(
5376            prot.feature_flags
5377                .lookup_attr("package_upgrades".to_owned())
5378                == Some(false)
5379        );
5380        assert!(
5381            prot.feature_flags
5382                .attr_map()
5383                .get("package_upgrades")
5384                .unwrap()
5385                == &false
5386        );
5387        let prot: ProtocolConfig =
5388            ProtocolConfig::get_for_version(ProtocolVersion::new(4), Chain::Unknown);
5389        // Was true from v3 and up
5390        assert!(
5391            prot.feature_flags
5392                .lookup_attr("package_upgrades".to_owned())
5393                == Some(true)
5394        );
5395        assert!(
5396            prot.feature_flags
5397                .attr_map()
5398                .get("package_upgrades")
5399                .unwrap()
5400                == &true
5401        );
5402    }
5403
5404    #[test]
5405    fn limit_range_fn_test() {
5406        let low = 100u32;
5407        let high = 10000u64;
5408
5409        assert!(check_limit!(1u8, low, high) == LimitThresholdCrossed::None);
5410        assert!(matches!(
5411            check_limit!(255u16, low, high),
5412            LimitThresholdCrossed::Soft(255u128, 100)
5413        ));
5414        // This wont compile because lossy
5415        //assert!(check_limit!(100000000u128, low, high) == LimitThresholdCrossed::None);
5416        // This wont compile because lossy
5417        //assert!(check_limit!(100000000usize, low, high) == LimitThresholdCrossed::None);
5418
5419        assert!(matches!(
5420            check_limit!(2550000u64, low, high),
5421            LimitThresholdCrossed::Hard(2550000, 10000)
5422        ));
5423
5424        assert!(matches!(
5425            check_limit!(2550000u64, high, high),
5426            LimitThresholdCrossed::Hard(2550000, 10000)
5427        ));
5428
5429        assert!(matches!(
5430            check_limit!(1u8, high),
5431            LimitThresholdCrossed::None
5432        ));
5433
5434        assert!(check_limit!(255u16, high) == LimitThresholdCrossed::None);
5435
5436        assert!(matches!(
5437            check_limit!(2550000u64, high),
5438            LimitThresholdCrossed::Hard(2550000, 10000)
5439        ));
5440    }
5441
5442    #[test]
5443    fn linkage_amendments_load() {
5444        let mainnet = LazyLock::force(&MAINNET_LINKAGE_AMENDMENTS);
5445        let testnet = LazyLock::force(&TESTNET_LINKAGE_AMENDMENTS);
5446        assert!(!mainnet.is_empty(), "mainnet amendments must not be empty");
5447        assert!(!testnet.is_empty(), "testnet amendments must not be empty");
5448    }
5449
5450    #[test]
5451    fn render_scalar_fields_use_precision_safe_encoding() {
5452        use mysten_common::rpc_format::Unmetered;
5453
5454        let config = ProtocolConfig::get_for_max_version_UNSAFE();
5455        let rendered = config
5456            .render::<serde_json::Value>(&mut Unmetered)
5457            .expect("render should succeed");
5458
5459        let max_args = rendered
5460            .get("max_arguments")
5461            .expect("max_arguments set at max version");
5462        assert!(
5463            max_args.is_number(),
5464            "u32 should render as number, got {max_args:?}",
5465        );
5466
5467        let max_tx_size = rendered
5468            .get("max_tx_size_bytes")
5469            .expect("max_tx_size_bytes set at max version");
5470        assert!(
5471            max_tx_size.is_string(),
5472            "u64 should render as string, got {max_tx_size:?}",
5473        );
5474    }
5475
5476    #[test]
5477    fn render_includes_non_scalar_gasless_allowlist_as_json() {
5478        use mysten_common::rpc_format::Unmetered;
5479        use serde_json::json;
5480
5481        let mut config = ProtocolConfig::get_for_max_version_UNSAFE();
5482        config.set_gasless_allowed_token_types_for_testing(vec![
5483            ("0xa::usdc::USDC".to_string(), 10_000),
5484            ("0xb::usdt::USDT".to_string(), 0),
5485        ]);
5486
5487        let rendered = config
5488            .render::<serde_json::Value>(&mut Unmetered)
5489            .expect("render should succeed under Unmetered budget");
5490        let allowlist = rendered
5491            .get("gasless_allowed_token_types")
5492            .expect("entry should be present after the testing setter");
5493
5494        // u64 values render as strings to preserve JS precision; the tuple becomes a 2-element
5495        // JSON array.
5496        assert_eq!(
5497            allowlist,
5498            &json!([["0xa::usdc::USDC", "10000"], ["0xb::usdt::USDT", "0"],]),
5499        );
5500    }
5501
5502    #[test]
5503    fn render_targets_prost_value_for_grpc() {
5504        use mysten_common::rpc_format::Unmetered;
5505        use prost_types::value::Kind;
5506
5507        let mut config = ProtocolConfig::get_for_max_version_UNSAFE();
5508        config.set_gasless_allowed_token_types_for_testing(vec![(
5509            "0xa::usdc::USDC".to_string(),
5510            10_000,
5511        )]);
5512
5513        let rendered = config
5514            .render::<prost_types::Value>(&mut Unmetered)
5515            .expect("render to prost Value should succeed");
5516        let allowlist = rendered
5517            .get("gasless_allowed_token_types")
5518            .expect("entry should be present after the testing setter");
5519
5520        // Outer ListValue with one inner ListValue carrying [coin_type_string, amount_string].
5521        let Some(Kind::ListValue(outer)) = &allowlist.kind else {
5522            panic!(
5523                "expected ListValue at the top level, got {:?}",
5524                allowlist.kind
5525            );
5526        };
5527        assert_eq!(outer.values.len(), 1, "one allowlisted entry");
5528        let Some(Kind::ListValue(entry)) = &outer.values[0].kind else {
5529            panic!("expected each entry to be a ListValue");
5530        };
5531        assert_eq!(entry.values.len(), 2, "entry has (coin_type, amount)");
5532
5533        let Some(Kind::StringValue(coin_type)) = &entry.values[0].kind else {
5534            panic!("expected coin_type as StringValue");
5535        };
5536        assert_eq!(coin_type, "0xa::usdc::USDC");
5537
5538        // u64 amount renders as a string, not a NumberValue — this is the precision-safe path.
5539        let Some(Kind::StringValue(amount)) = &entry.values[1].kind else {
5540            panic!(
5541                "expected minimum_transfer_amount as StringValue (precision-safe u64); got {:?}",
5542                entry.values[1].kind,
5543            );
5544        };
5545        assert_eq!(amount, "10000");
5546    }
5547
5548    #[test]
5549    fn render_emits_null_for_unset_protocol_versions() {
5550        use mysten_common::rpc_format::Unmetered;
5551
5552        let config = ProtocolConfig::get_for_version(1.into(), Chain::Unknown);
5553        let rendered = config
5554            .render::<serde_json::Value>(&mut Unmetered)
5555            .expect("render should succeed");
5556        // The gasless allowlist key is present in every version's keyset, but renders as JSON
5557        // `null` for versions that predate the feature. This keeps the keyset stable across
5558        // protocol versions so clients can distinguish "unknown key" from "present but unset".
5559        let entry = rendered
5560            .get("gasless_allowed_token_types")
5561            .expect("key should be present for every protocol version");
5562        assert!(
5563            entry.is_null(),
5564            "value should be null for pre-feature protocol version, got {entry:?}",
5565        );
5566    }
5567}