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