Skip to main content

sui_protocol_config/
lib.rs

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