Skip to main content

sui_protocol_config/
lib.rs

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