Skip to main content

sui_protocol_config/
lib.rs

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