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