Skip to main content

sui_protocol_config/
lib.rs

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