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