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