sui_protocol_config/
lib.rs

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