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