Skip to main content

sui_protocol_config/
lib.rs

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