Skip to main content

sui_protocol_config/
lib.rs

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