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