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 per-address FreezeList reads in a transaction's coin regulation check.
1815    /// Enforced during execution and at signing.
1816    max_freeze_list_address_reads: Option<u64>,
1817
1818    /// Maximum number of stored objects accessed by object runtime ObjectStore. Enforced by object runtime during execution
1819    object_runtime_max_num_store_entries: Option<u64>,
1820
1821    /// Maximum number of stored objects accessed by object runtime ObjectStore in system transaction. Enforced by object runtime during execution
1822    object_runtime_max_num_store_entries_system_tx: Option<u64>,
1823
1824    // === Execution gas costs ====
1825    /// Base cost for any Sui transaction
1826    base_tx_cost_fixed: Option<u64>,
1827
1828    /// Additional cost for a transaction that publishes a package
1829    /// i.e., the base cost of such a transaction is base_tx_cost_fixed + package_publish_cost_fixed
1830    package_publish_cost_fixed: Option<u64>,
1831
1832    /// Cost per byte of a Move call transaction
1833    /// i.e., the cost of such a transaction is base_cost + (base_tx_cost_per_byte * size)
1834    base_tx_cost_per_byte: Option<u64>,
1835
1836    /// Cost per byte for a transaction that publishes a package
1837    package_publish_cost_per_byte: Option<u64>,
1838
1839    /// MIST charged per publish or upgrade command.
1840    package_publish_charge_fixed: Option<u64>,
1841
1842    /// MIST charged per module of a publish or upgrade command.
1843    package_publish_charge_per_module: Option<u64>,
1844
1845    /// MIST charged per dependency of a publish or upgrade command.
1846    package_publish_charge_per_dependency: Option<u64>,
1847
1848    // Per-byte cost of reading an object during transaction execution
1849    obj_access_cost_read_per_byte: Option<u64>,
1850
1851    // Cost per KiB (1,024 bytes) of reading a non-system package input. When unset, packages are
1852    // charged `obj_access_cost_read_per_byte` like other input objects.
1853    obj_access_cost_read_per_package_kb: Option<u64>,
1854
1855    // Per-byte cost of writing an object during transaction execution
1856    obj_access_cost_mutate_per_byte: Option<u64>,
1857
1858    // Per-byte cost of deleting an object during transaction execution
1859    obj_access_cost_delete_per_byte: Option<u64>,
1860
1861    /// Per-byte cost charged for each input object to a transaction.
1862    /// Meant to approximate the cost of checking locks for each object
1863    // TODO: Option<I'm not sure that this cost makes sense. Checking locks is "free"
1864    // in the sense that an invalid tx that can never be committed/pay gas can
1865    // force validators to check an arbitrary number of locks. If those checks are
1866    // "free" for invalid transactions, why charge for them in valid transactions
1867    // TODO: Option<if we keep this, I think we probably want it to be a fixed cost rather
1868    // than a per-byte cost. checking an object lock should not require loading an
1869    // entire object, just consulting an ID -> tx digest map
1870    obj_access_cost_verify_per_byte: Option<u64>,
1871
1872    // Maximal nodes which are allowed when converting to a type layout.
1873    max_type_to_layout_nodes: Option<u64>,
1874
1875    // Maximal size in bytes that a PTB value can be
1876    max_ptb_value_size: Option<u64>,
1877
1878    // === Gas version. gas model ===
1879    /// Gas model version, what code we are using to charge gas
1880    gas_model_version: Option<u64>,
1881
1882    // === Storage gas costs ===
1883    /// 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
1884    obj_data_cost_refundable: Option<u64>,
1885
1886    // Per-byte cost of storing an object in the Sui transaction log (e.g., in CertifiedTransactionEffects)
1887    // This depends on the size of various fields including the effects
1888    // TODO: Option<I don't fully understand this^ and more details would be useful
1889    obj_metadata_cost_non_refundable: Option<u64>,
1890
1891    // === Tokenomics ===
1892
1893    // TODO: Option<this should be changed to u64.
1894    /// Sender of a txn that touches an object will get this percent of the storage rebate back.
1895    /// In basis point.
1896    storage_rebate_rate: Option<u64>,
1897
1898    /// 5% of the storage fund's share of rewards are reinvested into the storage fund.
1899    /// In basis point.
1900    storage_fund_reinvest_rate: Option<u64>,
1901
1902    /// The share of rewards that will be slashed and redistributed is 50%.
1903    /// In basis point.
1904    reward_slashing_rate: Option<u64>,
1905
1906    /// Unit gas price, Mist per internal gas unit.
1907    storage_gas_price: Option<u64>,
1908
1909    /// Per-object storage cost for accumulator objects, used during end-of-epoch accounting.
1910    accumulator_object_storage_cost: Option<u64>,
1911
1912    // === Core Protocol ===
1913    /// Max number of transactions per checkpoint.
1914    /// Note that this is a protocol constant and not a config as validators must have this set to
1915    /// the same value, otherwise they *will* fork.
1916    max_transactions_per_checkpoint: Option<u64>,
1917
1918    /// Max size of a checkpoint in bytes.
1919    /// Note that this is a protocol constant and not a config as validators must have this set to
1920    /// the same value, otherwise they *will* fork.
1921    max_checkpoint_size_bytes: Option<u64>,
1922
1923    /// A protocol upgrade always requires 2f+1 stake to agree. We support a buffer of additional
1924    /// stake (as a fraction of f, expressed in basis points) that is required before an upgrade
1925    /// can happen automatically. 10000bps would indicate that complete unanimity is required (all
1926    /// 3f+1 must vote), while 0bps would indicate that 2f+1 is sufficient.
1927    buffer_stake_for_protocol_upgrade_bps: Option<u64>,
1928
1929    // === Native Function Costs ===
1930
1931    // `address` module
1932    // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
1933    address_from_bytes_cost_base: Option<u64>,
1934    // Cost params for the Move native function `address::to_u256(address): u256`
1935    address_to_u256_cost_base: Option<u64>,
1936    // Cost params for the Move native function `address::from_u256(u256): address`
1937    address_from_u256_cost_base: Option<u64>,
1938
1939    // `config` module
1940    // Cost params for the Move native function `read_setting_impl<Name: copy + drop + store,
1941    // SettingValue: key + store, SettingDataValue: store, Value: copy + drop + store,
1942    // >(config: address, name: address, current_epoch: u64): Option<Value>`
1943    config_read_setting_impl_cost_base: Option<u64>,
1944    config_read_setting_impl_cost_per_byte: Option<u64>,
1945
1946    package_original_package_id_impl_cost_base: Option<u64>,
1947    package_original_package_id_impl_cost_per_byte: Option<u64>,
1948
1949    // `dynamic_field` module
1950    // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address`
1951    dynamic_field_hash_type_and_key_cost_base: Option<u64>,
1952    dynamic_field_hash_type_and_key_type_cost_per_byte: Option<u64>,
1953    dynamic_field_hash_type_and_key_value_cost_per_byte: Option<u64>,
1954    dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Option<u64>,
1955    // Cost params for the Move native function `add_child_object<Child: key>(parent: address, child: Child)`
1956    dynamic_field_add_child_object_cost_base: Option<u64>,
1957    dynamic_field_add_child_object_type_cost_per_byte: Option<u64>,
1958    dynamic_field_add_child_object_value_cost_per_byte: Option<u64>,
1959    dynamic_field_add_child_object_struct_tag_cost_per_byte: Option<u64>,
1960    // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut UID, id: address): &mut Child`
1961    dynamic_field_borrow_child_object_cost_base: Option<u64>,
1962    dynamic_field_borrow_child_object_child_ref_cost_per_byte: Option<u64>,
1963    dynamic_field_borrow_child_object_type_cost_per_byte: Option<u64>,
1964    // Cost params for the Move native function `remove_child_object<Child: key>(parent: address, id: address): Child`
1965    dynamic_field_remove_child_object_cost_base: Option<u64>,
1966    dynamic_field_remove_child_object_child_cost_per_byte: Option<u64>,
1967    dynamic_field_remove_child_object_type_cost_per_byte: Option<u64>,
1968    // Cost params for the Move native function `has_child_object(parent: address, id: address): bool`
1969    dynamic_field_has_child_object_cost_base: Option<u64>,
1970    // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent: address, id: address): bool`
1971    dynamic_field_has_child_object_with_ty_cost_base: Option<u64>,
1972    dynamic_field_has_child_object_with_ty_type_cost_per_byte: Option<u64>,
1973    dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Option<u64>,
1974
1975    // `scratch` module
1976    // Cost params for the Move native function `add_impl<V: drop>(key: address, value: V)`
1977    scratch_add_cost_base: Option<u64>,
1978    // Cost params for the Move native function `read_impl<V: copy + drop>(key: address): V`
1979    scratch_read_cost_base: Option<u64>,
1980    scratch_read_value_cost: Option<u64>,
1981    // Cost params for the Move native function `remove_impl<V: drop>(key: address): V`
1982    scratch_remove_cost_base: Option<u64>,
1983    // Cost params for the Move native function `exists_impl(key: address): bool`
1984    scratch_exists_cost_base: Option<u64>,
1985    // Cost params for the Move native function `exists_with_type_impl<V: drop>(key: address): bool`
1986    scratch_exists_with_type_cost_base: Option<u64>,
1987    scratch_exists_with_type_type_cost: Option<u64>,
1988    // Maximum number of entries in the per-transaction `sui::scratch` store.
1989    max_scratch_pad_size: Option<u64>,
1990
1991    // `event` module
1992    // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
1993    event_emit_cost_base: Option<u64>,
1994    event_emit_value_size_derivation_cost_per_byte: Option<u64>,
1995    event_emit_tag_size_derivation_cost_per_byte: Option<u64>,
1996    event_emit_output_cost_per_byte: Option<u64>,
1997    event_emit_auth_stream_cost: Option<u64>,
1998
1999    // `funds_accumulator` module
2000    // Base cost for reserving object funds for withdrawal.
2001    reserve_object_funds_for_withdrawal_cost_base: Option<u64>,
2002    // Cost of loading an object's settled balance on the first withdrawal for an owner and type.
2003    reserve_object_funds_for_withdrawal_cold_read_cost: Option<u64>,
2004
2005    //  `object` module
2006    // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
2007    object_borrow_uid_cost_base: Option<u64>,
2008    // Cost params for the Move native function `delete_impl(id: address)`
2009    object_delete_impl_cost_base: Option<u64>,
2010    // Cost params for the Move native function `record_new_uid(id: address)`
2011    object_record_new_uid_cost_base: Option<u64>,
2012    // Cost params for the Move native function
2013    // `record_new_uid_from_hash(parent: address, bytes: address)`
2014    object_record_new_uid_from_hash_cost_base: Option<u64>,
2015    // Cost params for the Move native function `is_shared_input_impl(id: address): bool`
2016    object_is_shared_input_cost_base: Option<u64>,
2017
2018    // Transfer
2019    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
2020    transfer_transfer_internal_cost_base: Option<u64>,
2021    // Cost params for the Move native function `party_transfer_impl<T: key>(obj: T, party_members: vector<address>)`
2022    transfer_party_transfer_internal_cost_base: Option<u64>,
2023    // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
2024    transfer_freeze_object_cost_base: Option<u64>,
2025    // Cost params for the Move native function `share_object<T: key>(obj: T)`
2026    transfer_share_object_cost_base: Option<u64>,
2027    // Cost params for the Move native function
2028    // `receive_object<T: key>(p: &mut UID, recv: Receiving<T>T)`
2029    transfer_receive_object_cost_base: Option<u64>,
2030    transfer_receive_object_cost_per_byte: Option<u64>,
2031    transfer_receive_object_type_cost_per_byte: Option<u64>,
2032
2033    // TxContext
2034    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
2035    tx_context_derive_id_cost_base: Option<u64>,
2036    tx_context_fresh_id_cost_base: Option<u64>,
2037    tx_context_sender_cost_base: Option<u64>,
2038    tx_context_epoch_cost_base: Option<u64>,
2039    tx_context_epoch_timestamp_ms_cost_base: Option<u64>,
2040    tx_context_sponsor_cost_base: Option<u64>,
2041    tx_context_rgp_cost_base: Option<u64>,
2042    tx_context_gas_price_cost_base: Option<u64>,
2043    tx_context_gas_budget_cost_base: Option<u64>,
2044    tx_context_ids_created_cost_base: Option<u64>,
2045    tx_context_replace_cost_base: Option<u64>,
2046
2047    // `clock` module
2048    // Cost params for the Move native function `native_borrow(): &Clock`
2049    clock_borrow_cost_base: Option<u64>,
2050
2051    // Types
2052    // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
2053    types_is_one_time_witness_cost_base: Option<u64>,
2054    types_is_one_time_witness_type_tag_cost_per_byte: Option<u64>,
2055    types_is_one_time_witness_type_cost_per_byte: Option<u64>,
2056
2057    // Validator
2058    // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
2059    validator_validate_metadata_cost_base: Option<u64>,
2060    validator_validate_metadata_data_cost_per_byte: Option<u64>,
2061
2062    // Crypto natives
2063    crypto_invalid_arguments_cost: Option<u64>,
2064    // bls12381::bls12381_min_sig_verify
2065    bls12381_bls12381_min_sig_verify_cost_base: Option<u64>,
2066    bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Option<u64>,
2067    bls12381_bls12381_min_sig_verify_msg_cost_per_block: Option<u64>,
2068
2069    // bls12381::bls12381_min_pk_verify
2070    bls12381_bls12381_min_pk_verify_cost_base: Option<u64>,
2071    bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Option<u64>,
2072    bls12381_bls12381_min_pk_verify_msg_cost_per_block: Option<u64>,
2073
2074    // ecdsa_k1::ecrecover
2075    ecdsa_k1_ecrecover_keccak256_cost_base: Option<u64>,
2076    ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
2077    ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
2078    ecdsa_k1_ecrecover_sha256_cost_base: Option<u64>,
2079    ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
2080    ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
2081
2082    // ecdsa_k1::decompress_pubkey
2083    ecdsa_k1_decompress_pubkey_cost_base: Option<u64>,
2084
2085    // ecdsa_k1::secp256k1_verify
2086    ecdsa_k1_secp256k1_verify_keccak256_cost_base: Option<u64>,
2087    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Option<u64>,
2088    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Option<u64>,
2089    ecdsa_k1_secp256k1_verify_sha256_cost_base: Option<u64>,
2090    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Option<u64>,
2091    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Option<u64>,
2092
2093    // ecdsa_r1::ecrecover
2094    ecdsa_r1_ecrecover_keccak256_cost_base: Option<u64>,
2095    ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
2096    ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
2097    ecdsa_r1_ecrecover_sha256_cost_base: Option<u64>,
2098    ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
2099    ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
2100
2101    // ecdsa_r1::secp256k1_verify
2102    ecdsa_r1_secp256r1_verify_keccak256_cost_base: Option<u64>,
2103    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Option<u64>,
2104    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Option<u64>,
2105    ecdsa_r1_secp256r1_verify_sha256_cost_base: Option<u64>,
2106    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Option<u64>,
2107    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Option<u64>,
2108
2109    // ecvrf::verify
2110    ecvrf_ecvrf_verify_cost_base: Option<u64>,
2111    ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Option<u64>,
2112    ecvrf_ecvrf_verify_alpha_string_cost_per_block: Option<u64>,
2113
2114    // ed25519
2115    ed25519_ed25519_verify_cost_base: Option<u64>,
2116    ed25519_ed25519_verify_msg_cost_per_byte: Option<u64>,
2117    ed25519_ed25519_verify_msg_cost_per_block: Option<u64>,
2118
2119    // groth16::prepare_verifying_key
2120    groth16_prepare_verifying_key_bls12381_cost_base: Option<u64>,
2121    groth16_prepare_verifying_key_bn254_cost_base: Option<u64>,
2122
2123    // groth16::verify_groth16_proof_internal
2124    groth16_verify_groth16_proof_internal_bls12381_cost_base: Option<u64>,
2125    groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Option<u64>,
2126    groth16_verify_groth16_proof_internal_bn254_cost_base: Option<u64>,
2127    groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Option<u64>,
2128    groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Option<u64>,
2129
2130    // hash::blake2b256
2131    hash_blake2b256_cost_base: Option<u64>,
2132    hash_blake2b256_data_cost_per_byte: Option<u64>,
2133    hash_blake2b256_data_cost_per_block: Option<u64>,
2134
2135    // hash::keccak256
2136    hash_keccak256_cost_base: Option<u64>,
2137    hash_keccak256_data_cost_per_byte: Option<u64>,
2138    hash_keccak256_data_cost_per_block: Option<u64>,
2139
2140    // poseidon::poseidon_bn254
2141    poseidon_bn254_cost_base: Option<u64>,
2142    poseidon_bn254_cost_per_block: Option<u64>,
2143
2144    // group_ops
2145    group_ops_bls12381_decode_scalar_cost: Option<u64>,
2146    group_ops_bls12381_decode_g1_cost: Option<u64>,
2147    group_ops_bls12381_decode_g2_cost: Option<u64>,
2148    group_ops_bls12381_decode_gt_cost: Option<u64>,
2149    group_ops_bls12381_scalar_add_cost: Option<u64>,
2150    group_ops_bls12381_g1_add_cost: Option<u64>,
2151    group_ops_bls12381_g2_add_cost: Option<u64>,
2152    group_ops_bls12381_gt_add_cost: Option<u64>,
2153    group_ops_bls12381_scalar_sub_cost: Option<u64>,
2154    group_ops_bls12381_g1_sub_cost: Option<u64>,
2155    group_ops_bls12381_g2_sub_cost: Option<u64>,
2156    group_ops_bls12381_gt_sub_cost: Option<u64>,
2157    group_ops_bls12381_scalar_mul_cost: Option<u64>,
2158    group_ops_bls12381_g1_mul_cost: Option<u64>,
2159    group_ops_bls12381_g2_mul_cost: Option<u64>,
2160    group_ops_bls12381_gt_mul_cost: Option<u64>,
2161    group_ops_bls12381_scalar_div_cost: Option<u64>,
2162    group_ops_bls12381_g1_div_cost: Option<u64>,
2163    group_ops_bls12381_g2_div_cost: Option<u64>,
2164    group_ops_bls12381_gt_div_cost: Option<u64>,
2165    group_ops_bls12381_g1_hash_to_base_cost: Option<u64>,
2166    group_ops_bls12381_g2_hash_to_base_cost: Option<u64>,
2167    group_ops_bls12381_g1_hash_to_cost_per_byte: Option<u64>,
2168    group_ops_bls12381_g2_hash_to_cost_per_byte: Option<u64>,
2169    group_ops_bls12381_g1_msm_base_cost: Option<u64>,
2170    group_ops_bls12381_g2_msm_base_cost: Option<u64>,
2171    group_ops_bls12381_g1_msm_base_cost_per_input: Option<u64>,
2172    group_ops_bls12381_g2_msm_base_cost_per_input: Option<u64>,
2173    group_ops_bls12381_msm_max_len: Option<u32>,
2174    group_ops_bls12381_pairing_cost: Option<u64>,
2175    group_ops_bls12381_g1_to_uncompressed_g1_cost: Option<u64>,
2176    group_ops_bls12381_uncompressed_g1_to_g1_cost: Option<u64>,
2177    group_ops_bls12381_uncompressed_g1_sum_base_cost: Option<u64>,
2178    group_ops_bls12381_uncompressed_g1_sum_cost_per_term: Option<u64>,
2179    group_ops_bls12381_uncompressed_g1_sum_max_terms: Option<u64>,
2180
2181    group_ops_ristretto_decode_scalar_cost: Option<u64>,
2182    group_ops_ristretto_decode_point_cost: Option<u64>,
2183    group_ops_ristretto_scalar_add_cost: Option<u64>,
2184    group_ops_ristretto_point_add_cost: Option<u64>,
2185    group_ops_ristretto_scalar_sub_cost: Option<u64>,
2186    group_ops_ristretto_point_sub_cost: Option<u64>,
2187    group_ops_ristretto_scalar_mul_cost: Option<u64>,
2188    group_ops_ristretto_point_mul_cost: Option<u64>,
2189    group_ops_ristretto_scalar_div_cost: Option<u64>,
2190    group_ops_ristretto_point_div_cost: Option<u64>,
2191
2192    verify_bulletproofs_ristretto255_base_cost: Option<u64>,
2193    verify_bulletproofs_ristretto255_cost_per_bit_and_commitment: Option<u64>,
2194    // Upper bound on batch size * range in bits for a bulletproofs range proof. Defaults to 512
2195    // when unset.
2196    max_bulletproofs_total_bits: Option<u64>,
2197
2198    // hmac::hmac_sha3_256
2199    hmac_hmac_sha3_256_cost_base: Option<u64>,
2200    hmac_hmac_sha3_256_input_cost_per_byte: Option<u64>,
2201    hmac_hmac_sha3_256_input_cost_per_block: Option<u64>,
2202
2203    // zklogin::check_zklogin_id
2204    check_zklogin_id_cost_base: Option<u64>,
2205    // zklogin::check_zklogin_issuer
2206    check_zklogin_issuer_cost_base: Option<u64>,
2207
2208    vdf_verify_vdf_cost: Option<u64>,
2209    vdf_hash_to_input_cost: Option<u64>,
2210
2211    // nitro_attestation::load_nitro_attestation
2212    nitro_attestation_parse_base_cost: Option<u64>,
2213    nitro_attestation_parse_cost_per_byte: Option<u64>,
2214    nitro_attestation_verify_base_cost: Option<u64>,
2215    nitro_attestation_verify_cost_per_cert: Option<u64>,
2216
2217    // Native layout cost multiplier in the layout cost formula.
2218    layout_node_cost: Option<u64>,
2219    // Layout size threshold above which the large-layout surcharge applies.
2220    layout_node_cost_large_layout_threshold: Option<u64>,
2221
2222    // Stdlib costs
2223    bcs_per_input_abstract_unit_cost: Option<u64>,
2224    bcs_per_byte_serialized_cost: Option<u64>,
2225    bcs_legacy_min_output_size_cost: Option<u64>,
2226    bcs_failure_cost: Option<u64>,
2227
2228    hash_sha2_256_base_cost: Option<u64>,
2229    hash_sha2_256_per_byte_cost: Option<u64>,
2230    hash_sha2_256_legacy_min_input_len_cost: Option<u64>,
2231    hash_sha3_256_base_cost: Option<u64>,
2232    hash_sha3_256_per_byte_cost: Option<u64>,
2233    hash_sha3_256_legacy_min_input_len_cost: Option<u64>,
2234    type_name_get_base_cost: Option<u64>,
2235    type_name_get_per_byte_cost: Option<u64>,
2236    type_name_id_base_cost: Option<u64>,
2237
2238    string_check_utf8_base_cost: Option<u64>,
2239    string_check_utf8_per_byte_cost: Option<u64>,
2240    string_is_char_boundary_base_cost: Option<u64>,
2241    string_sub_string_base_cost: Option<u64>,
2242    string_sub_string_per_byte_cost: Option<u64>,
2243    string_index_of_base_cost: Option<u64>,
2244    string_index_of_per_byte_pattern_cost: Option<u64>,
2245    string_index_of_per_byte_searched_cost: Option<u64>,
2246
2247    vector_empty_base_cost: Option<u64>,
2248    vector_length_base_cost: Option<u64>,
2249    vector_push_back_base_cost: Option<u64>,
2250    vector_push_back_legacy_per_abstract_memory_unit_cost: Option<u64>,
2251    vector_borrow_base_cost: Option<u64>,
2252    vector_pop_back_base_cost: Option<u64>,
2253    vector_destroy_empty_base_cost: Option<u64>,
2254    vector_swap_base_cost: Option<u64>,
2255    vector_reverse_base_cost: Option<u64>,
2256    vector_reverse_per_elem_cost: Option<u64>,
2257    vector_keep_range_base_cost: Option<u64>,
2258    vector_keep_range_per_dropped_elem_cost: Option<u64>,
2259    vector_keep_range_per_moved_elem_cost: Option<u64>,
2260    vector_copy_range_base_cost: Option<u64>,
2261    vector_copy_range_per_abstract_memory_unit_cost: Option<u64>,
2262    vector_replace_range_base_cost: Option<u64>,
2263    vector_replace_range_per_elem_cost: Option<u64>,
2264    debug_print_base_cost: Option<u64>,
2265    debug_print_stack_trace_base_cost: Option<u64>,
2266
2267    // ==== Ephemeral (consensus only) params deleted ====
2268    //
2269    // Const params for consensus scoring decision
2270    // The scaling factor property for the MED outlier detection
2271    // scoring_decision_mad_divisor: Option<f64>,
2272    // The cutoff value for the MED outlier detection
2273    // scoring_decision_cutoff_value: Option<f64>,
2274    /// === Execution Version ===
2275    // custom_setter: see `set_execution_version_for_testing`, which forbids downgrades.
2276    #[custom_setter]
2277    execution_version: Option<u64>,
2278
2279    // Dictates the threshold (percentage of stake) that is used to calculate the "bad" nodes to be
2280    // swapped when creating the consensus schedule. The values should be of the range [0 - 33]. Anything
2281    // above 33 (f) will not be allowed.
2282    consensus_bad_nodes_stake_threshold: Option<u64>,
2283
2284    max_jwk_votes_per_validator_per_epoch: Option<u64>,
2285    // The maximum age of a JWK in epochs before it is removed from the AuthenticatorState object.
2286    // Applied at the end of an epoch as a delta from the new epoch value, so setting this to 1
2287    // will cause the new epoch to start with JWKs from the previous epoch still valid.
2288    max_age_of_jwk_in_epochs: Option<u64>,
2289
2290    // === random beacon ===
2291    /// Maximum allowed precision loss when reducing voting weights for the random beacon
2292    /// protocol.
2293    random_beacon_reduction_allowed_delta: Option<u16>,
2294
2295    /// Minimum number of shares below which voting weights will not be reduced for the
2296    /// random beacon protocol.
2297    random_beacon_reduction_lower_bound: Option<u32>,
2298
2299    /// Consensus Round after which DKG should be aborted and randomness disabled for
2300    /// the epoch, if it hasn't already completed.
2301    random_beacon_dkg_timeout_round: Option<u32>,
2302
2303    /// Minimum interval between consecutive rounds of generated randomness.
2304    random_beacon_min_round_interval_ms: Option<u64>,
2305
2306    /// Version of the random beacon DKG protocol.
2307    /// 0 was deprecated (and currently not supported), 1 is the default version.
2308    random_beacon_dkg_version: Option<u64>,
2309
2310    /// The maximum serialised transaction size (in bytes) accepted by consensus. That should be bigger than the
2311    /// `max_tx_size_bytes` with some additional headroom.
2312    consensus_max_transaction_size_bytes: Option<u64>,
2313    /// The maximum size of transactions included in a consensus block.
2314    consensus_max_transactions_in_block_bytes: Option<u64>,
2315    /// The maximum number of transactions included in a consensus block.
2316    consensus_max_num_transactions_in_block: Option<u64>,
2317
2318    /// The maximum number of rounds where transaction voting is allowed.
2319    consensus_voting_rounds: Option<u32>,
2320
2321    /// DEPRECATED. Do not use.
2322    max_accumulated_txn_cost_per_object_in_narwhal_commit: Option<u64>,
2323
2324    /// The max number of consensus rounds a transaction can be deferred due to shared object congestion.
2325    /// Transactions will be cancelled after this many rounds.
2326    max_deferral_rounds_for_congestion_control: Option<u64>,
2327
2328    /// Time after the scheduled epoch end (`next_reconfiguration_timestamp_ms`) at which epoch
2329    /// close stops waiting for deferred transactions to drain: the epoch is closed even if
2330    /// deferred transactions remain unscheduled. They are abandoned and can be resubmitted in the
2331    /// next epoch. When unset, epoch close waits indefinitely.
2332    epoch_close_deadline_ms: Option<u64>,
2333
2334    /// DEPRECATED. Do not use.
2335    max_txn_cost_overage_per_object_in_commit: Option<u64>,
2336
2337    /// DEPRECATED. Do not use.
2338    allowed_txn_cost_overage_burst_per_object_in_commit: Option<u64>,
2339
2340    /// Minimum interval of commit timestamps between consecutive checkpoints.
2341    min_checkpoint_interval_ms: Option<u64>,
2342
2343    /// Version number to use for version_specific_data in `CheckpointSummary`.
2344    checkpoint_summary_version_specific_data: Option<u64>,
2345
2346    /// The max number of transactions that can be included in a single Soft Bundle.
2347    max_soft_bundle_size: Option<u64>,
2348
2349    /// Whether to try to form bridge committee
2350    // Note: this is not a feature flag because we want to distinguish between
2351    // `None` and `Some(false)`, as committee was already finalized on Testnet.
2352    bridge_should_try_to_finalize_committee: Option<bool>,
2353
2354    /// The max accumulated txn execution cost per object in a mysticeti. Transactions
2355    /// in a commit will be deferred once their touch shared objects hit this limit,
2356    /// unless the selected congestion control mode allows overage.
2357    /// This config plays the same role as `max_accumulated_txn_cost_per_object_in_narwhal_commit`
2358    /// but for mysticeti commits due to that mysticeti has higher commit rate.
2359    max_accumulated_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
2360
2361    /// As above, but separate per-commit budget for transactions that use randomness.
2362    /// If not configured, uses the setting for `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
2363    max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
2364
2365    /// Configures the garbage collection depth for consensus. When is unset or `0` then the garbage collection
2366    /// is disabled.
2367    consensus_gc_depth: Option<u32>,
2368
2369    /// DEPRECATED. Do not use.
2370    gas_budget_based_txn_cost_cap_factor: Option<u64>,
2371
2372    /// DEPRECATED. Do not use.
2373    gas_budget_based_txn_cost_absolute_cap_commit_count: Option<u64>,
2374
2375    /// SIP-45: K in the formula `amplification_factor = max(0, gas_price / reference_gas_price - K)`.
2376    /// This is the threshold for activating consensus amplification.
2377    sip_45_consensus_amplification_threshold: Option<u64>,
2378
2379    /// Number of recent commits the staggered-submission signal looks at. It compares
2380    /// excess copies of transactions without allowed proposers to unique user transactions.
2381    staggered_submission_signal_window_commits: Option<u64>,
2382    /// Excess copies per commit that the signal requires before it turns on. The signal
2383    /// compares the window's total with this value times
2384    /// `staggered_submission_signal_window_commits`, so a window that is not full yet
2385    /// must reach the same total.
2386    staggered_submission_signal_min_excess_copies_per_commit: Option<u64>,
2387    /// User transactions per consensus commit, duplicates included, that the signal
2388    /// requires. The signal compares the window's total with this value times
2389    /// `staggered_submission_signal_window_commits`, so a window that is not full yet
2390    /// must reach the same total. Below that total the signal does not escalate, and a
2391    /// commit counts towards the exit dwell.
2392    staggered_submission_signal_min_consensus_user_transactions_per_commit: Option<u64>,
2393    /// Number of consecutive commits before the signal drops to a lower band. Each of
2394    /// these commits must have a ratio below the band's exit ratio, or a window total
2395    /// below `staggered_submission_signal_min_consensus_user_transactions_per_commit` times
2396    /// `staggered_submission_signal_window_commits`. The two conditions can alternate.
2397    staggered_submission_signal_exit_dwell_commits: Option<u64>,
2398    /// Ratios to enter and exit each band, in basis points (bps) of the window's unique
2399    /// user transactions. Band 1 delays submissions up to 1.6s and band 2 up to 4.8s.
2400    staggered_submission_signal_band1_enter_ratio_bps: Option<u64>,
2401    staggered_submission_signal_band1_exit_ratio_bps: Option<u64>,
2402    staggered_submission_signal_band2_enter_ratio_bps: Option<u64>,
2403    staggered_submission_signal_band2_exit_ratio_bps: Option<u64>,
2404
2405    /// DEPRECATED: this was an ephemeral feature flag only used in per-epoch tables, which has now
2406    /// been deployed everywhere.
2407    use_object_per_epoch_marker_table_v2: Option<bool>,
2408
2409    /// The number of commits to consider when computing a deterministic commit rate.
2410    consensus_commit_rate_estimation_window_size: Option<u32>,
2411
2412    /// A list of effective AliasedAddress.
2413    /// For each pair, `aliased` is allowed to act as `original` for any of the transaction digests
2414    /// listed in `tx_digests`
2415    #[serde(skip_serializing_if = "Vec::is_empty")]
2416    aliased_addresses: Vec<AliasedAddress>,
2417
2418    /// The base charge for each command in a programmable transaction. This is a fixed cost to
2419    /// account for the overhead of processing each command.
2420    translation_per_command_base_charge: Option<u64>,
2421
2422    /// The base charge for each input in a programmable transaction regardless of if it is used or
2423    /// not, or a pure/object/funds withdrawal input.
2424    translation_per_input_base_charge: Option<u64>,
2425
2426    /// The base charge for each byte of pure input in a programmable transaction.
2427    translation_pure_input_per_byte_charge: Option<u64>,
2428
2429    /// The multiplier for the number of type nodes when charging for type loading.
2430    /// This is multiplied by the number of type nodes to get the total cost.
2431    /// This should be a small number to avoid excessive gas costs for loading types.
2432    translation_per_type_node_charge: Option<u64>,
2433
2434    /// The multiplier for the number of type references when charging for type checking and reference
2435    /// checking.
2436    translation_per_reference_node_charge: Option<u64>,
2437
2438    /// The multiplier for each linkage entry when charging for linkage tables that we have
2439    /// created.
2440    translation_per_linkage_entry_charge: Option<u64>,
2441
2442    /// The maximum number of updates per settlement transaction.
2443    max_updates_per_settlement_txn: Option<u32>,
2444
2445    /// Maximum computation units allowed for a gasless transaction.
2446    gasless_max_computation_units: Option<u64>,
2447
2448    /// Allowed token types for gasless transactions, with minimum transfer sizes per token.
2449    gasless_allowed_token_types: Option<Vec<(String, u64)>>,
2450
2451    /// Maximum number of unused Pure inputs allowed in a gasless transaction.
2452    /// Object and FundsWithdrawal inputs must always be used.
2453    /// When None, there is no limit (effectively unlimited).
2454    gasless_max_unused_inputs: Option<u64>,
2455
2456    /// Maximum size in bytes of each Pure input in a gasless transaction.
2457    /// When None, there is no limit (effectively unlimited).
2458    gasless_max_pure_input_bytes: Option<u64>,
2459
2460    /// Max tps for gasless transactions. Unlimited when unset, zero when set to zero.
2461    gasless_max_tps: Option<u64>,
2462
2463    #[serde(skip_serializing_if = "Option::is_none")]
2464    #[skip_accessor]
2465    include_special_package_amendments: Option<Arc<Amendments>>,
2466
2467    /// Maximum serialized size in bytes of a gasless transaction (SenderSignedData).
2468    /// Bounds the persistent storage impact of each admitted gasless transaction.
2469    gasless_max_tx_size_bytes: Option<u64>,
2470
2471    /// The multiplier for each live reference charging per-command. Only used when
2472    /// `allow_references_in_ptbs` is enabled.
2473    translation_per_live_reference_charge: Option<u64>,
2474
2475    /// The maximum number of live references while checking a command. Only used when
2476    /// `allow_references_in_ptbs` is enabled.
2477    max_ptb_live_references: Option<u64>,
2478
2479    /// The maximum number of references returned by a command. Only used when
2480    /// `allow_references_in_ptbs` is enabled.
2481    max_ptb_returned_references: Option<u64>,
2482
2483    /// The maximum number of references returned over the course of the transaction. Only used
2484    /// when `allow_references_in_ptbs` is enabled.
2485    max_ptb_total_returned_references: Option<u64>,
2486}
2487
2488/// An aliased address.
2489#[derive(Clone, Serialize, Deserialize, Debug)]
2490pub struct AliasedAddress {
2491    /// The original address.
2492    pub original: [u8; 32],
2493    /// An aliased address which is allowed to act as the original address.
2494    pub aliased: [u8; 32],
2495    /// A list of transaction digests for which the aliasing is allowed to be in effect.
2496    pub allowed_tx_digests: Vec<[u8; 32]>,
2497}
2498
2499// feature flags
2500impl ProtocolConfig {
2501    /// The chain this config was instantiated for (see the `chain` field).
2502    pub fn chain(&self) -> Chain {
2503        self.chain
2504    }
2505
2506    // Add checks for feature flag support here, e.g.:
2507    // pub fn check_new_protocol_feature_supported(&self) -> Result<(), Error> {
2508    //     if self.feature_flags.new_protocol_feature_supported {
2509    //         Ok(())
2510    //     } else {
2511    //         Err(Error(format!(
2512    //             "new_protocol_feature is not supported at {:?}",
2513    //             self.version
2514    //         )))
2515    //     }
2516    // }
2517
2518    pub fn check_package_upgrades_supported(&self) -> Result<(), Error> {
2519        if self.feature_flags.package_upgrades {
2520            Ok(())
2521        } else {
2522            Err(Error(format!(
2523                "package upgrades are not supported at {:?}",
2524                self.version
2525            )))
2526        }
2527    }
2528
2529    pub fn zklogin_supported_providers(&self) -> &BTreeSet<String> {
2530        &self.feature_flags.zklogin_supported_providers
2531    }
2532
2533    /// zkLogin circuit verify mode: 0 = v1 circuit only, 1 = v2 circuit with
2534    /// fallback to v1, 2 = v2 circuit only.
2535    pub fn zklogin_circuit_mode(&self) -> u64 {
2536        self.feature_flags.zklogin_circuit_mode
2537    }
2538
2539    pub fn consensus_transaction_ordering(&self) -> ConsensusTransactionOrdering {
2540        self.feature_flags.consensus_transaction_ordering
2541    }
2542
2543    pub fn enable_jwk_consensus_updates(&self) -> bool {
2544        let ret = self.feature_flags.enable_jwk_consensus_updates;
2545        if ret {
2546            // jwk updates required end-of-epoch transactions
2547            assert!(self.feature_flags.end_of_epoch_transaction_supported);
2548        }
2549        ret
2550    }
2551
2552    pub fn staggered_submission_signal(&self) -> bool {
2553        let ret = self.feature_flags.staggered_submission_signal;
2554        if ret {
2555            // The signal staggers transactions without allowed proposers. That
2556            // distinction only exists when allowed_proposers is enabled.
2557            assert!(self.feature_flags.allowed_proposers);
2558        }
2559        ret
2560    }
2561
2562    pub fn end_of_epoch_transaction_supported(&self) -> bool {
2563        let ret = self.feature_flags.end_of_epoch_transaction_supported;
2564        if !ret {
2565            // jwk updates required end-of-epoch transactions
2566            assert!(!self.feature_flags.enable_jwk_consensus_updates);
2567        }
2568        ret
2569    }
2570
2571    pub fn dkg_version(&self) -> u64 {
2572        // Version 0 was deprecated and removed, the default is 1 if not set.
2573        self.random_beacon_dkg_version.unwrap_or(1)
2574    }
2575
2576    pub fn bridge(&self) -> bool {
2577        let ret = self.feature_flags.bridge;
2578        if ret {
2579            // bridge required end-of-epoch transactions
2580            assert!(self.feature_flags.end_of_epoch_transaction_supported);
2581        }
2582        ret
2583    }
2584
2585    pub fn should_try_to_finalize_bridge_committee(&self) -> bool {
2586        if !self.bridge() {
2587            return false;
2588        }
2589        // In the older protocol version, always try to finalize the committee.
2590        self.bridge_should_try_to_finalize_committee.unwrap_or(true)
2591    }
2592
2593    pub fn zklogin_max_epoch_upper_bound_delta(&self) -> Option<u64> {
2594        self.feature_flags.zklogin_max_epoch_upper_bound_delta
2595    }
2596
2597    pub fn enable_allowances(&self) -> bool {
2598        self.feature_flags.enable_allowances && self.enable_accumulators()
2599    }
2600
2601    pub fn enable_coin_reservation_obj_refs(&self) -> bool {
2602        self.new_vm_enabled() && self.feature_flags.enable_coin_reservation_obj_refs
2603    }
2604
2605    pub fn enable_authenticated_event_streams(&self) -> bool {
2606        self.feature_flags.enable_authenticated_event_streams && self.enable_accumulators()
2607    }
2608
2609    pub fn per_object_congestion_control_mode(&self) -> PerObjectCongestionControlMode {
2610        self.feature_flags.per_object_congestion_control_mode
2611    }
2612
2613    pub fn consensus_choice(&self) -> ConsensusChoice {
2614        self.feature_flags.consensus_choice
2615    }
2616
2617    pub fn consensus_network(&self) -> ConsensusNetwork {
2618        self.feature_flags.consensus_network
2619    }
2620
2621    pub fn mysticeti_num_leaders_per_round(&self) -> Option<usize> {
2622        self.feature_flags.mysticeti_num_leaders_per_round
2623    }
2624
2625    pub fn max_transaction_size_bytes(&self) -> u64 {
2626        // Provide a default value if protocol config version is too low.
2627        self.consensus_max_transaction_size_bytes
2628            .unwrap_or(256 * 1024)
2629    }
2630
2631    pub fn max_transactions_in_block_bytes(&self) -> u64 {
2632        if cfg!(msim) {
2633            256 * 1024
2634        } else {
2635            self.consensus_max_transactions_in_block_bytes
2636                .unwrap_or(512 * 1024)
2637        }
2638    }
2639
2640    pub fn max_num_transactions_in_block(&self) -> u64 {
2641        if cfg!(msim) {
2642            8
2643        } else {
2644            self.consensus_max_num_transactions_in_block.unwrap_or(512)
2645        }
2646    }
2647
2648    pub fn gc_depth(&self) -> u32 {
2649        self.consensus_gc_depth.unwrap_or(0)
2650    }
2651
2652    pub fn consensus_linearize_subdag_v2(&self) -> bool {
2653        let res = self.feature_flags.consensus_linearize_subdag_v2;
2654        assert!(
2655            !res || self.gc_depth() > 0,
2656            "The consensus linearize sub dag V2 requires GC to be enabled"
2657        );
2658        res
2659    }
2660
2661    pub fn consensus_median_based_commit_timestamp(&self) -> bool {
2662        let res = self.feature_flags.consensus_median_based_commit_timestamp;
2663        assert!(
2664            !res || self.gc_depth() > 0,
2665            "The consensus median based commit timestamp requires GC to be enabled"
2666        );
2667        res
2668    }
2669
2670    pub fn get_consensus_commit_rate_estimation_window_size(&self) -> u32 {
2671        self.consensus_commit_rate_estimation_window_size
2672            .unwrap_or(0)
2673    }
2674
2675    pub fn consensus_num_requested_prior_commits_at_startup(&self) -> u32 {
2676        // Currently there is only one parameter driving this value. If there are multiple
2677        // things computed from prior consensus commits, this function must return the max
2678        // of all of them.
2679        let window_size = self.get_consensus_commit_rate_estimation_window_size();
2680        // Ensure we are not using past commits without recording a state digest in the prologue.
2681        assert!(window_size == 0 || self.record_additional_state_digest_in_prologue());
2682        window_size
2683    }
2684
2685    pub fn address_aliases(&self) -> bool {
2686        let address_aliases = self.feature_flags.address_aliases;
2687        assert!(
2688            !address_aliases || self.mysticeti_fastpath(),
2689            "Address aliases requires Mysticeti fastpath to be enabled"
2690        );
2691        if address_aliases {
2692            assert!(
2693                self.feature_flags.disable_preconsensus_locking,
2694                "Address aliases requires CertifiedTransaction to be disabled"
2695            );
2696        }
2697        address_aliases
2698    }
2699
2700    pub fn new_vm_enabled(&self) -> bool {
2701        self.execution_version.is_some_and(|v| v >= 4)
2702    }
2703
2704    pub fn gasless_allowed_token_types(&self) -> &[(String, u64)] {
2705        debug_assert!(self.gasless_allowed_token_types.is_some());
2706        self.gasless_allowed_token_types.as_deref().unwrap_or(&[])
2707    }
2708
2709    pub fn get_gasless_max_unused_inputs(&self) -> u64 {
2710        self.gasless_max_unused_inputs.unwrap_or(u64::MAX)
2711    }
2712
2713    pub fn get_gasless_max_pure_input_bytes(&self) -> u64 {
2714        self.gasless_max_pure_input_bytes.unwrap_or(u64::MAX)
2715    }
2716
2717    pub fn get_gasless_max_tx_size_bytes(&self) -> u64 {
2718        self.gasless_max_tx_size_bytes.unwrap_or(u64::MAX)
2719    }
2720
2721    pub fn include_special_package_amendments_as_option(&self) -> &Option<Arc<Amendments>> {
2722        &self.include_special_package_amendments
2723    }
2724}
2725
2726static POISON_VERSION_METHODS: AtomicBool = AtomicBool::new(false);
2727
2728// Instantiations for each protocol version.
2729impl ProtocolConfig {
2730    /// Get the value ProtocolConfig that are in effect during the given protocol version.
2731    pub fn get_for_version(version: ProtocolVersion, chain: Chain) -> Self {
2732        // ProtocolVersion can be deserialized so we need to check it here as well.
2733        assert!(
2734            version >= ProtocolVersion::MIN,
2735            "Network protocol version is {:?}, but the minimum supported version by the binary is {:?}. Please upgrade the binary.",
2736            version,
2737            ProtocolVersion::MIN.0,
2738        );
2739        assert!(
2740            version <= ProtocolVersion::MAX_ALLOWED,
2741            "Network protocol version is {:?}, but the maximum supported version by the binary is {:?}. Please upgrade the binary.",
2742            version,
2743            ProtocolVersion::MAX_ALLOWED.0,
2744        );
2745
2746        let mut ret = Self::get_for_version_impl(version, chain);
2747        ret.version = version;
2748        ret.chain = chain;
2749
2750        ret = Self::apply_config_override(version, ret);
2751
2752        if std::env::var("SUI_PROTOCOL_CONFIG_OVERRIDE_ENABLE").is_ok() {
2753            warn!(
2754                "overriding ProtocolConfig settings with custom settings; this may break non-local networks"
2755            );
2756            let overrides: ProtocolConfigOptional =
2757                serde_env::from_env_with_prefix("SUI_PROTOCOL_CONFIG_OVERRIDE")
2758                    .expect("failed to parse ProtocolConfig override env variables");
2759            overrides.apply_to(&mut ret);
2760        }
2761
2762        ret
2763    }
2764
2765    /// Get the value ProtocolConfig that are in effect during the given protocol version.
2766    /// Or none if the version is not supported.
2767    pub fn get_for_version_if_supported(version: ProtocolVersion, chain: Chain) -> Option<Self> {
2768        if version.0 >= ProtocolVersion::MIN.0 && version.0 <= ProtocolVersion::MAX_ALLOWED.0 {
2769            let mut ret = Self::get_for_version_impl(version, chain);
2770            ret.version = version;
2771            ret.chain = chain;
2772            ret = Self::apply_config_override(version, ret);
2773            Some(ret)
2774        } else {
2775            None
2776        }
2777    }
2778
2779    pub fn poison_get_for_min_version() {
2780        POISON_VERSION_METHODS.store(true, Ordering::Relaxed);
2781    }
2782
2783    fn load_poison_get_for_min_version() -> bool {
2784        POISON_VERSION_METHODS.load(Ordering::Relaxed)
2785    }
2786
2787    /// Convenience to get the constants at the current minimum supported version.
2788    /// Mainly used by client code that may not yet be protocol-version aware.
2789    pub fn get_for_min_version() -> Self {
2790        if Self::load_poison_get_for_min_version() {
2791            panic!("get_for_min_version called on validator");
2792        }
2793        ProtocolConfig::get_for_version(ProtocolVersion::MIN, Chain::Unknown)
2794    }
2795
2796    /// CAREFUL! - You probably want to use `get_for_version` instead.
2797    ///
2798    /// Convenience to get the constants at the current maximum supported version.
2799    /// Mainly used by genesis. Note well that this function uses the max version
2800    /// supported locally by the node, which is not necessarily the current version
2801    /// of the network. ALSO, this function disregards chain specific config (by
2802    /// using Chain::Unknown), thereby potentially returning a protocol config that
2803    /// is incorrect for some feature flags. Definitely safe for testing and for
2804    /// protocol version 11 and prior.
2805    #[allow(non_snake_case)]
2806    pub fn get_for_max_version_UNSAFE() -> Self {
2807        if Self::load_poison_get_for_min_version() {
2808            panic!("get_for_max_version_UNSAFE called on validator");
2809        }
2810        ProtocolConfig::get_for_version(ProtocolVersion::MAX, Chain::Unknown)
2811    }
2812
2813    fn get_for_version_impl(version: ProtocolVersion, chain: Chain) -> Self {
2814        #[cfg(msim)]
2815        {
2816            // populate the fake simulator version # with a different base tx cost.
2817            if version == ProtocolVersion::MAX_ALLOWED {
2818                let mut config = Self::get_for_version_impl(version - 1, Chain::Unknown);
2819                config.base_tx_cost_fixed = Some(config.base_tx_cost_fixed() + 1000);
2820                return config;
2821            }
2822        }
2823
2824        // IMPORTANT: Never modify the value of any constant for a pre-existing protocol version.
2825        // To change the values here you must create a new protocol version with the new values!
2826        let mut cfg = Self {
2827            // will be overwritten before being returned
2828            version,
2829            chain,
2830
2831            // All flags are disabled in V1
2832            feature_flags: Default::default(),
2833
2834            max_tx_size_bytes: Some(128 * 1024),
2835            // We need this number to be at least 100x less than `max_serialized_tx_effects_size_bytes`otherwise effects can be huge
2836            max_input_objects: Some(2048),
2837            max_serialized_tx_effects_size_bytes: Some(512 * 1024),
2838            max_serialized_tx_effects_size_bytes_system_tx: Some(512 * 1024 * 16),
2839            max_gas_payment_objects: Some(256),
2840            max_modules_in_publish: Some(128),
2841            max_package_dependencies: None,
2842            max_arguments: Some(512),
2843            max_type_arguments: Some(16),
2844            max_type_argument_depth: Some(16),
2845            max_pure_argument_size: Some(16 * 1024),
2846            max_programmable_tx_commands: Some(1024),
2847            move_binary_format_version: Some(6),
2848            min_move_binary_format_version: None,
2849            binary_module_handles: None,
2850            binary_struct_handles: None,
2851            binary_function_handles: None,
2852            binary_function_instantiations: None,
2853            binary_signatures: None,
2854            binary_constant_pool: None,
2855            binary_identifiers: None,
2856            binary_address_identifiers: None,
2857            binary_struct_defs: None,
2858            binary_struct_def_instantiations: None,
2859            binary_function_defs: None,
2860            binary_field_handles: None,
2861            binary_field_instantiations: None,
2862            binary_friend_decls: None,
2863            binary_enum_defs: None,
2864            binary_enum_def_instantiations: None,
2865            binary_variant_handles: None,
2866            binary_variant_instantiation_handles: None,
2867            binary_format_limits_profile: None,
2868            max_move_object_size: Some(250 * 1024),
2869            max_move_package_size: Some(100 * 1024),
2870            max_publish_or_upgrade_per_ptb: None,
2871            max_tx_gas: Some(10_000_000_000),
2872            max_gas_price: Some(100_000),
2873            max_gas_price_rgp_factor_for_aborted_transactions: None,
2874            max_gas_computation_bucket: Some(5_000_000),
2875            max_loop_depth: Some(5),
2876            max_generic_instantiation_length: Some(32),
2877            max_function_parameters: Some(128),
2878            max_basic_blocks: Some(1024),
2879            max_value_stack_size: Some(1024),
2880            max_type_nodes: Some(256),
2881            max_generic_instantiation_type_nodes_per_function: None,
2882            max_generic_instantiation_type_nodes_per_module: None,
2883            max_accumulator_type_nodes: None,
2884            max_push_size: Some(10000),
2885            max_struct_definitions: Some(200),
2886            max_function_definitions: Some(1000),
2887            max_fields_in_struct: Some(32),
2888            max_dependency_depth: Some(100),
2889            max_num_event_emit: Some(256),
2890            max_num_accumulator_events: None,
2891            max_num_new_move_object_ids: Some(2048),
2892            max_num_new_move_object_ids_system_tx: Some(2048 * 16),
2893            max_num_deleted_move_object_ids: Some(2048),
2894            max_num_deleted_move_object_ids_system_tx: Some(2048 * 16),
2895            max_num_transferred_move_object_ids: Some(2048),
2896            max_num_transferred_move_object_ids_system_tx: Some(2048 * 16),
2897            max_event_emit_size: Some(250 * 1024),
2898            max_move_vector_len: Some(256 * 1024),
2899            max_type_to_layout_nodes: None,
2900            max_ptb_value_size: None,
2901
2902            max_back_edges_per_function: Some(10_000),
2903            max_back_edges_per_module: Some(10_000),
2904            max_verifier_meter_ticks_per_function: Some(6_000_000),
2905            max_meter_ticks_per_module: Some(6_000_000),
2906            max_meter_ticks_per_package: None,
2907
2908            object_runtime_max_num_cached_objects: Some(1000),
2909            object_runtime_max_num_cached_objects_system_tx: Some(1000 * 16),
2910            object_runtime_max_loaded_child_value_size: None,
2911            max_freeze_list_address_reads: None,
2912            object_runtime_max_num_store_entries: Some(1000),
2913            object_runtime_max_num_store_entries_system_tx: Some(1000 * 16),
2914            base_tx_cost_fixed: Some(110_000),
2915            package_publish_cost_fixed: Some(1_000),
2916            base_tx_cost_per_byte: Some(0),
2917            package_publish_cost_per_byte: Some(80),
2918            package_publish_charge_fixed: None,
2919            package_publish_charge_per_module: None,
2920            package_publish_charge_per_dependency: None,
2921            obj_access_cost_read_per_byte: Some(15),
2922            obj_access_cost_read_per_package_kb: None,
2923            obj_access_cost_mutate_per_byte: Some(40),
2924            obj_access_cost_delete_per_byte: Some(40),
2925            obj_access_cost_verify_per_byte: Some(200),
2926            obj_data_cost_refundable: Some(100),
2927            obj_metadata_cost_non_refundable: Some(50),
2928            gas_model_version: Some(1),
2929            storage_rebate_rate: Some(9900),
2930            storage_fund_reinvest_rate: Some(500),
2931            reward_slashing_rate: Some(5000),
2932            storage_gas_price: Some(1),
2933            accumulator_object_storage_cost: None,
2934            max_transactions_per_checkpoint: Some(10_000),
2935            max_checkpoint_size_bytes: Some(30 * 1024 * 1024),
2936
2937            // For now, perform upgrades with a bare quorum of validators.
2938            // MUSTFIX: This number should be increased to at least 2000 (20%) for mainnet.
2939            buffer_stake_for_protocol_upgrade_bps: Some(0),
2940
2941            // === Native Function Costs ===
2942            // `address` module
2943            // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
2944            address_from_bytes_cost_base: Some(52),
2945            // Cost params for the Move native function `address::to_u256(address): u256`
2946            address_to_u256_cost_base: Some(52),
2947            // Cost params for the Move native function `address::from_u256(u256): address`
2948            address_from_u256_cost_base: Some(52),
2949
2950            // `config` module
2951            // Cost params for the Move native function `read_setting_impl``
2952            config_read_setting_impl_cost_base: None,
2953            config_read_setting_impl_cost_per_byte: None,
2954
2955            package_original_package_id_impl_cost_base: None,
2956            package_original_package_id_impl_cost_per_byte: None,
2957
2958            // `dynamic_field` module
2959            // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address`
2960            dynamic_field_hash_type_and_key_cost_base: Some(100),
2961            dynamic_field_hash_type_and_key_type_cost_per_byte: Some(2),
2962            dynamic_field_hash_type_and_key_value_cost_per_byte: Some(2),
2963            dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Some(2),
2964            // Cost params for the Move native function `add_child_object<Child: key>(parent: address, child: Child)`
2965            dynamic_field_add_child_object_cost_base: Some(100),
2966            dynamic_field_add_child_object_type_cost_per_byte: Some(10),
2967            dynamic_field_add_child_object_value_cost_per_byte: Some(10),
2968            dynamic_field_add_child_object_struct_tag_cost_per_byte: Some(10),
2969            // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut UID, id: address): &mut Child`
2970            dynamic_field_borrow_child_object_cost_base: Some(100),
2971            dynamic_field_borrow_child_object_child_ref_cost_per_byte: Some(10),
2972            dynamic_field_borrow_child_object_type_cost_per_byte: Some(10),
2973            // Cost params for the Move native function `remove_child_object<Child: key>(parent: address, id: address): Child`
2974            dynamic_field_remove_child_object_cost_base: Some(100),
2975            dynamic_field_remove_child_object_child_cost_per_byte: Some(2),
2976            dynamic_field_remove_child_object_type_cost_per_byte: Some(2),
2977            // Cost params for the Move native function `has_child_object(parent: address, id: address): bool`
2978            dynamic_field_has_child_object_cost_base: Some(100),
2979            // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent: address, id: address): bool`
2980            dynamic_field_has_child_object_with_ty_cost_base: Some(100),
2981            dynamic_field_has_child_object_with_ty_type_cost_per_byte: Some(2),
2982            dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Some(2),
2983
2984            // `scratch` module: introduced in protocol version 130
2985            scratch_add_cost_base: None,
2986            scratch_read_cost_base: None,
2987            scratch_read_value_cost: None,
2988            scratch_remove_cost_base: None,
2989            scratch_exists_cost_base: None,
2990            scratch_exists_with_type_cost_base: None,
2991            scratch_exists_with_type_type_cost: None,
2992            max_scratch_pad_size: None,
2993
2994            // `event` module
2995            // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
2996            event_emit_cost_base: Some(52),
2997            event_emit_value_size_derivation_cost_per_byte: Some(2),
2998            event_emit_tag_size_derivation_cost_per_byte: Some(5),
2999            event_emit_output_cost_per_byte: Some(10),
3000            event_emit_auth_stream_cost: None,
3001
3002            // `funds_accumulator` module: introduced in protocol version 137.
3003            reserve_object_funds_for_withdrawal_cost_base: None,
3004            reserve_object_funds_for_withdrawal_cold_read_cost: None,
3005
3006            //  `object` module
3007            // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
3008            object_borrow_uid_cost_base: Some(52),
3009            // Cost params for the Move native function `delete_impl(id: address)`
3010            object_delete_impl_cost_base: Some(52),
3011            // Cost params for the Move native function `record_new_uid(id: address)`
3012            object_record_new_uid_cost_base: Some(52),
3013            // Cost params for the Move native function
3014            // `record_new_uid_from_hash(parent: address, bytes: address)`. Introduced in v131.
3015            object_record_new_uid_from_hash_cost_base: None,
3016            // Cost params for the Move native function `is_shared_input_impl(id: address): bool`.
3017            // Introduced in v142.
3018            object_is_shared_input_cost_base: None,
3019
3020            // `transfer` module
3021            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
3022            transfer_transfer_internal_cost_base: Some(52),
3023            // Cost params for the Move native function `party_transfer_impl<T: key>(obj: T, party_members: vector<address>)`
3024            transfer_party_transfer_internal_cost_base: None,
3025            // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
3026            transfer_freeze_object_cost_base: Some(52),
3027            // Cost params for the Move native function `share_object<T: key>(obj: T)`
3028            transfer_share_object_cost_base: Some(52),
3029            transfer_receive_object_cost_base: None,
3030            transfer_receive_object_type_cost_per_byte: None,
3031            transfer_receive_object_cost_per_byte: None,
3032
3033            // `tx_context` module
3034            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
3035            tx_context_derive_id_cost_base: Some(52),
3036            tx_context_fresh_id_cost_base: None,
3037            tx_context_sender_cost_base: None,
3038            tx_context_epoch_cost_base: None,
3039            tx_context_epoch_timestamp_ms_cost_base: None,
3040            tx_context_sponsor_cost_base: None,
3041            tx_context_rgp_cost_base: None,
3042            tx_context_gas_price_cost_base: None,
3043            tx_context_gas_budget_cost_base: None,
3044            tx_context_ids_created_cost_base: None,
3045            tx_context_replace_cost_base: None,
3046
3047            // `clock` module
3048            clock_borrow_cost_base: None,
3049
3050            // `types` module
3051            // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
3052            types_is_one_time_witness_cost_base: Some(52),
3053            types_is_one_time_witness_type_tag_cost_per_byte: Some(2),
3054            types_is_one_time_witness_type_cost_per_byte: Some(2),
3055
3056            // `validator` module
3057            // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
3058            validator_validate_metadata_cost_base: Some(52),
3059            validator_validate_metadata_data_cost_per_byte: Some(2),
3060
3061            // Crypto
3062            crypto_invalid_arguments_cost: Some(100),
3063            // bls12381::bls12381_min_pk_verify
3064            bls12381_bls12381_min_sig_verify_cost_base: Some(52),
3065            bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Some(2),
3066            bls12381_bls12381_min_sig_verify_msg_cost_per_block: Some(2),
3067
3068            // bls12381::bls12381_min_pk_verify
3069            bls12381_bls12381_min_pk_verify_cost_base: Some(52),
3070            bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Some(2),
3071            bls12381_bls12381_min_pk_verify_msg_cost_per_block: Some(2),
3072
3073            // ecdsa_k1::ecrecover
3074            ecdsa_k1_ecrecover_keccak256_cost_base: Some(52),
3075            ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
3076            ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Some(2),
3077            ecdsa_k1_ecrecover_sha256_cost_base: Some(52),
3078            ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Some(2),
3079            ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Some(2),
3080
3081            // ecdsa_k1::decompress_pubkey
3082            ecdsa_k1_decompress_pubkey_cost_base: Some(52),
3083
3084            // ecdsa_k1::secp256k1_verify
3085            ecdsa_k1_secp256k1_verify_keccak256_cost_base: Some(52),
3086            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Some(2),
3087            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Some(2),
3088            ecdsa_k1_secp256k1_verify_sha256_cost_base: Some(52),
3089            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Some(2),
3090            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Some(2),
3091
3092            // ecdsa_r1::ecrecover
3093            ecdsa_r1_ecrecover_keccak256_cost_base: Some(52),
3094            ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
3095            ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Some(2),
3096            ecdsa_r1_ecrecover_sha256_cost_base: Some(52),
3097            ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Some(2),
3098            ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Some(2),
3099
3100            // ecdsa_r1::secp256k1_verify
3101            ecdsa_r1_secp256r1_verify_keccak256_cost_base: Some(52),
3102            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Some(2),
3103            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Some(2),
3104            ecdsa_r1_secp256r1_verify_sha256_cost_base: Some(52),
3105            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Some(2),
3106            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Some(2),
3107
3108            // ecvrf::verify
3109            ecvrf_ecvrf_verify_cost_base: Some(52),
3110            ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Some(2),
3111            ecvrf_ecvrf_verify_alpha_string_cost_per_block: Some(2),
3112
3113            // ed25519
3114            ed25519_ed25519_verify_cost_base: Some(52),
3115            ed25519_ed25519_verify_msg_cost_per_byte: Some(2),
3116            ed25519_ed25519_verify_msg_cost_per_block: Some(2),
3117
3118            // groth16::prepare_verifying_key
3119            groth16_prepare_verifying_key_bls12381_cost_base: Some(52),
3120            groth16_prepare_verifying_key_bn254_cost_base: Some(52),
3121
3122            // groth16::verify_groth16_proof_internal
3123            groth16_verify_groth16_proof_internal_bls12381_cost_base: Some(52),
3124            groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Some(2),
3125            groth16_verify_groth16_proof_internal_bn254_cost_base: Some(52),
3126            groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Some(2),
3127            groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Some(2),
3128
3129            // hash::blake2b256
3130            hash_blake2b256_cost_base: Some(52),
3131            hash_blake2b256_data_cost_per_byte: Some(2),
3132            hash_blake2b256_data_cost_per_block: Some(2),
3133
3134            // hash::keccak256
3135            hash_keccak256_cost_base: Some(52),
3136            hash_keccak256_data_cost_per_byte: Some(2),
3137            hash_keccak256_data_cost_per_block: Some(2),
3138
3139            poseidon_bn254_cost_base: None,
3140            poseidon_bn254_cost_per_block: None,
3141
3142            // hmac::hmac_sha3_256
3143            hmac_hmac_sha3_256_cost_base: Some(52),
3144            hmac_hmac_sha3_256_input_cost_per_byte: Some(2),
3145            hmac_hmac_sha3_256_input_cost_per_block: Some(2),
3146
3147            // group ops
3148            group_ops_bls12381_decode_scalar_cost: None,
3149            group_ops_bls12381_decode_g1_cost: None,
3150            group_ops_bls12381_decode_g2_cost: None,
3151            group_ops_bls12381_decode_gt_cost: None,
3152            group_ops_bls12381_scalar_add_cost: None,
3153            group_ops_bls12381_g1_add_cost: None,
3154            group_ops_bls12381_g2_add_cost: None,
3155            group_ops_bls12381_gt_add_cost: None,
3156            group_ops_bls12381_scalar_sub_cost: None,
3157            group_ops_bls12381_g1_sub_cost: None,
3158            group_ops_bls12381_g2_sub_cost: None,
3159            group_ops_bls12381_gt_sub_cost: None,
3160            group_ops_bls12381_scalar_mul_cost: None,
3161            group_ops_bls12381_g1_mul_cost: None,
3162            group_ops_bls12381_g2_mul_cost: None,
3163            group_ops_bls12381_gt_mul_cost: None,
3164            group_ops_bls12381_scalar_div_cost: None,
3165            group_ops_bls12381_g1_div_cost: None,
3166            group_ops_bls12381_g2_div_cost: None,
3167            group_ops_bls12381_gt_div_cost: None,
3168            group_ops_bls12381_g1_hash_to_base_cost: None,
3169            group_ops_bls12381_g2_hash_to_base_cost: None,
3170            group_ops_bls12381_g1_hash_to_cost_per_byte: None,
3171            group_ops_bls12381_g2_hash_to_cost_per_byte: None,
3172            group_ops_bls12381_g1_msm_base_cost: None,
3173            group_ops_bls12381_g2_msm_base_cost: None,
3174            group_ops_bls12381_g1_msm_base_cost_per_input: None,
3175            group_ops_bls12381_g2_msm_base_cost_per_input: None,
3176            group_ops_bls12381_msm_max_len: None,
3177            group_ops_bls12381_pairing_cost: None,
3178            group_ops_bls12381_g1_to_uncompressed_g1_cost: None,
3179            group_ops_bls12381_uncompressed_g1_to_g1_cost: None,
3180            group_ops_bls12381_uncompressed_g1_sum_base_cost: None,
3181            group_ops_bls12381_uncompressed_g1_sum_cost_per_term: None,
3182            group_ops_bls12381_uncompressed_g1_sum_max_terms: None,
3183
3184            group_ops_ristretto_decode_scalar_cost: None,
3185            group_ops_ristretto_decode_point_cost: None,
3186            group_ops_ristretto_scalar_add_cost: None,
3187            group_ops_ristretto_point_add_cost: None,
3188            group_ops_ristretto_scalar_sub_cost: None,
3189            group_ops_ristretto_point_sub_cost: None,
3190            group_ops_ristretto_scalar_mul_cost: None,
3191            group_ops_ristretto_point_mul_cost: None,
3192            group_ops_ristretto_scalar_div_cost: None,
3193            group_ops_ristretto_point_div_cost: None,
3194
3195            verify_bulletproofs_ristretto255_base_cost: None,
3196            verify_bulletproofs_ristretto255_cost_per_bit_and_commitment: None,
3197            max_bulletproofs_total_bits: None,
3198
3199            // zklogin::check_zklogin_id
3200            check_zklogin_id_cost_base: None,
3201            // zklogin::check_zklogin_issuer
3202            check_zklogin_issuer_cost_base: None,
3203
3204            vdf_verify_vdf_cost: None,
3205            vdf_hash_to_input_cost: None,
3206
3207            // nitro_attestation::verify_nitro_attestation
3208            nitro_attestation_parse_base_cost: None,
3209            nitro_attestation_parse_cost_per_byte: None,
3210            nitro_attestation_verify_base_cost: None,
3211            nitro_attestation_verify_cost_per_cert: None,
3212
3213            layout_node_cost: None,
3214            layout_node_cost_large_layout_threshold: None,
3215            bcs_per_input_abstract_unit_cost: None,
3216            bcs_per_byte_serialized_cost: None,
3217            bcs_legacy_min_output_size_cost: None,
3218            bcs_failure_cost: None,
3219            hash_sha2_256_base_cost: None,
3220            hash_sha2_256_per_byte_cost: None,
3221            hash_sha2_256_legacy_min_input_len_cost: None,
3222            hash_sha3_256_base_cost: None,
3223            hash_sha3_256_per_byte_cost: None,
3224            hash_sha3_256_legacy_min_input_len_cost: None,
3225            type_name_get_base_cost: None,
3226            type_name_get_per_byte_cost: None,
3227            type_name_id_base_cost: None,
3228            string_check_utf8_base_cost: None,
3229            string_check_utf8_per_byte_cost: None,
3230            string_is_char_boundary_base_cost: None,
3231            string_sub_string_base_cost: None,
3232            string_sub_string_per_byte_cost: None,
3233            string_index_of_base_cost: None,
3234            string_index_of_per_byte_pattern_cost: None,
3235            string_index_of_per_byte_searched_cost: None,
3236            vector_empty_base_cost: None,
3237            vector_length_base_cost: None,
3238            vector_push_back_base_cost: None,
3239            vector_push_back_legacy_per_abstract_memory_unit_cost: None,
3240            vector_borrow_base_cost: None,
3241            vector_pop_back_base_cost: None,
3242            vector_destroy_empty_base_cost: None,
3243            vector_swap_base_cost: None,
3244            vector_reverse_base_cost: None,
3245            vector_reverse_per_elem_cost: None,
3246            vector_keep_range_base_cost: None,
3247            vector_keep_range_per_dropped_elem_cost: None,
3248            vector_keep_range_per_moved_elem_cost: None,
3249            vector_copy_range_base_cost: None,
3250            vector_copy_range_per_abstract_memory_unit_cost: None,
3251            vector_replace_range_base_cost: None,
3252            vector_replace_range_per_elem_cost: None,
3253            debug_print_base_cost: None,
3254            debug_print_stack_trace_base_cost: None,
3255
3256            max_size_written_objects: None,
3257            max_size_written_objects_system_tx: None,
3258
3259            // ==== Ephemeral (consensus only) params deleted ====
3260            // Const params for consensus scoring decision
3261            // scoring_decision_mad_divisor: None,
3262            // scoring_decision_cutoff_value: None,
3263
3264            // Limits the length of a Move identifier
3265            max_move_identifier_len: None,
3266            max_move_value_depth: None,
3267            package_arena_size_in_bytes: None,
3268            max_move_enum_variants: None,
3269
3270            gas_rounding_step: None,
3271
3272            execution_version: None,
3273
3274            max_event_emit_size_total: None,
3275
3276            consensus_bad_nodes_stake_threshold: None,
3277
3278            max_jwk_votes_per_validator_per_epoch: None,
3279
3280            max_age_of_jwk_in_epochs: None,
3281
3282            random_beacon_reduction_allowed_delta: None,
3283
3284            random_beacon_reduction_lower_bound: None,
3285
3286            random_beacon_dkg_timeout_round: None,
3287
3288            random_beacon_min_round_interval_ms: None,
3289
3290            random_beacon_dkg_version: None,
3291
3292            consensus_max_transaction_size_bytes: None,
3293
3294            consensus_max_transactions_in_block_bytes: None,
3295
3296            consensus_max_num_transactions_in_block: None,
3297
3298            consensus_voting_rounds: None,
3299
3300            max_accumulated_txn_cost_per_object_in_narwhal_commit: None,
3301
3302            max_deferral_rounds_for_congestion_control: None,
3303
3304            epoch_close_deadline_ms: None,
3305
3306            max_txn_cost_overage_per_object_in_commit: None,
3307
3308            allowed_txn_cost_overage_burst_per_object_in_commit: None,
3309
3310            min_checkpoint_interval_ms: None,
3311
3312            checkpoint_summary_version_specific_data: None,
3313
3314            max_soft_bundle_size: None,
3315
3316            bridge_should_try_to_finalize_committee: None,
3317
3318            max_accumulated_txn_cost_per_object_in_mysticeti_commit: None,
3319
3320            max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit: None,
3321
3322            consensus_gc_depth: None,
3323
3324            gas_budget_based_txn_cost_cap_factor: None,
3325
3326            gas_budget_based_txn_cost_absolute_cap_commit_count: None,
3327
3328            sip_45_consensus_amplification_threshold: None,
3329            staggered_submission_signal_window_commits: None,
3330            staggered_submission_signal_min_excess_copies_per_commit: None,
3331            staggered_submission_signal_min_consensus_user_transactions_per_commit: None,
3332            staggered_submission_signal_exit_dwell_commits: None,
3333            staggered_submission_signal_band1_enter_ratio_bps: None,
3334            staggered_submission_signal_band1_exit_ratio_bps: None,
3335            staggered_submission_signal_band2_enter_ratio_bps: None,
3336            staggered_submission_signal_band2_exit_ratio_bps: None,
3337
3338            use_object_per_epoch_marker_table_v2: None,
3339
3340            consensus_commit_rate_estimation_window_size: None,
3341
3342            aliased_addresses: vec![],
3343
3344            translation_per_command_base_charge: None,
3345            translation_per_input_base_charge: None,
3346            translation_pure_input_per_byte_charge: None,
3347            translation_per_type_node_charge: None,
3348            translation_per_reference_node_charge: None,
3349            translation_per_linkage_entry_charge: None,
3350            translation_per_live_reference_charge: None,
3351            max_ptb_live_references: None,
3352            max_ptb_returned_references: None,
3353            max_ptb_total_returned_references: None,
3354
3355            max_updates_per_settlement_txn: None,
3356
3357            gasless_max_computation_units: None,
3358            gasless_allowed_token_types: None,
3359            gasless_max_unused_inputs: None,
3360            gasless_max_pure_input_bytes: None,
3361            gasless_max_tps: None,
3362            include_special_package_amendments: None,
3363            gasless_max_tx_size_bytes: None,
3364            // When adding a new constant, set it to None in the earliest version, like this:
3365            // new_constant: None,
3366        };
3367        for cur in 2..=version.0 {
3368            match cur {
3369                1 => unreachable!(),
3370                2 => {
3371                    cfg.feature_flags.advance_epoch_start_time_in_safe_mode = true;
3372                }
3373                3 => {
3374                    // changes for gas model
3375                    cfg.gas_model_version = Some(2);
3376                    // max gas budget is in MIST and an absolute value 50SUI
3377                    cfg.max_tx_gas = Some(50_000_000_000);
3378                    // min gas budget is in MIST and an absolute value 2000MIST or 0.000002SUI
3379                    cfg.base_tx_cost_fixed = Some(2_000);
3380                    // storage gas price multiplier
3381                    cfg.storage_gas_price = Some(76);
3382                    cfg.feature_flags.loaded_child_objects_fixed = true;
3383                    // max size of written objects during a TXn
3384                    // this is a sum of all objects written during a TXn
3385                    cfg.max_size_written_objects = Some(5 * 1000 * 1000);
3386                    // max size of written objects during a system TXn to allow for larger writes
3387                    // akin to `max_size_written_objects` but for system TXns
3388                    cfg.max_size_written_objects_system_tx = Some(50 * 1000 * 1000);
3389                    cfg.feature_flags.package_upgrades = true;
3390                }
3391                // This is the first protocol version currently possible.
3392                // Mainnet starts with version 4. Previous versions are pre mainnet and have
3393                // all been wiped out.
3394                // Every other chain is after version 4.
3395                4 => {
3396                    // Change reward slashing rate to 100%.
3397                    cfg.reward_slashing_rate = Some(10000);
3398                    // protect old and new lookup for object version
3399                    cfg.gas_model_version = Some(3);
3400                }
3401                5 => {
3402                    cfg.feature_flags.missing_type_is_compatibility_error = true;
3403                    cfg.gas_model_version = Some(4);
3404                    cfg.feature_flags.scoring_decision_with_validity_cutoff = true;
3405                    // ==== Ephemeral (consensus only) params deleted ====
3406                    // cfg.scoring_decision_mad_divisor = Some(2.3);
3407                    // cfg.scoring_decision_cutoff_value = Some(2.5);
3408                }
3409                6 => {
3410                    cfg.gas_model_version = Some(5);
3411                    cfg.buffer_stake_for_protocol_upgrade_bps = Some(5000);
3412                    cfg.feature_flags.consensus_order_end_of_epoch_last = true;
3413                }
3414                7 => {
3415                    cfg.feature_flags.disallow_adding_abilities_on_upgrade = true;
3416                    cfg.feature_flags
3417                        .disable_invariant_violation_check_in_swap_loc = true;
3418                    cfg.feature_flags.ban_entry_init = true;
3419                    cfg.feature_flags.package_digest_hash_module = true;
3420                }
3421                8 => {
3422                    cfg.feature_flags
3423                        .disallow_change_struct_type_params_on_upgrade = true;
3424                }
3425                9 => {
3426                    // Limits the length of a Move identifier
3427                    cfg.max_move_identifier_len = Some(128);
3428                    cfg.feature_flags.no_extraneous_module_bytes = true;
3429                    cfg.feature_flags
3430                        .advance_to_highest_supported_protocol_version = true;
3431                }
3432                10 => {
3433                    cfg.max_verifier_meter_ticks_per_function = Some(16_000_000);
3434                    cfg.max_meter_ticks_per_module = Some(16_000_000);
3435                }
3436                11 => {
3437                    cfg.max_move_value_depth = Some(128);
3438                }
3439                12 => {
3440                    cfg.feature_flags.narwhal_versioned_metadata = true;
3441                    if chain != Chain::Mainnet {
3442                        cfg.feature_flags.commit_root_state_digest = true;
3443                    }
3444
3445                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3446                        cfg.feature_flags.zklogin_auth = true;
3447                    }
3448                }
3449                13 => {}
3450                14 => {
3451                    cfg.gas_rounding_step = Some(1_000);
3452                    cfg.gas_model_version = Some(6);
3453                }
3454                15 => {
3455                    cfg.feature_flags.consensus_transaction_ordering =
3456                        ConsensusTransactionOrdering::ByGasPrice;
3457                }
3458                16 => {
3459                    cfg.feature_flags.simplified_unwrap_then_delete = true;
3460                }
3461                17 => {
3462                    cfg.feature_flags.upgraded_multisig_supported = true;
3463                }
3464                18 => {
3465                    cfg.execution_version = Some(1);
3466                    // Following flags are implied by this execution version.  Once support for earlier
3467                    // protocol versions is dropped, these flags can be removed:
3468                    // cfg.feature_flags.package_upgrades = true;
3469                    // cfg.feature_flags.disallow_adding_abilities_on_upgrade = true;
3470                    // cfg.feature_flags.disallow_change_struct_type_params_on_upgrade = true;
3471                    // cfg.feature_flags.loaded_child_objects_fixed = true;
3472                    // cfg.feature_flags.ban_entry_init = true;
3473                    // cfg.feature_flags.pack_digest_hash_modules = true;
3474                    cfg.feature_flags.txn_base_cost_as_multiplier = true;
3475                    // this is a multiplier of the gas price
3476                    cfg.base_tx_cost_fixed = Some(1_000);
3477                }
3478                19 => {
3479                    cfg.max_num_event_emit = Some(1024);
3480                    // We maintain the same total size limit for events, but increase the number of
3481                    // events that can be emitted.
3482                    cfg.max_event_emit_size_total = Some(
3483                        256 /* former event count limit */ * 250 * 1024, /* size limit per event */
3484                    );
3485                }
3486                20 => {
3487                    cfg.feature_flags.commit_root_state_digest = true;
3488
3489                    if chain != Chain::Mainnet {
3490                        cfg.feature_flags.narwhal_new_leader_election_schedule = true;
3491                        cfg.consensus_bad_nodes_stake_threshold = Some(20);
3492                    }
3493                }
3494
3495                21 => {
3496                    if chain != Chain::Mainnet {
3497                        cfg.feature_flags.zklogin_supported_providers = BTreeSet::from([
3498                            "Google".to_string(),
3499                            "Facebook".to_string(),
3500                            "Twitch".to_string(),
3501                        ]);
3502                    }
3503                }
3504                22 => {
3505                    cfg.feature_flags.loaded_child_object_format = true;
3506                }
3507                23 => {
3508                    cfg.feature_flags.loaded_child_object_format_type = true;
3509                    cfg.feature_flags.narwhal_new_leader_election_schedule = true;
3510                    // Taking a baby step approach, we consider only 20% by stake as bad nodes so we
3511                    // have a 80% by stake of nodes participating in the leader committee. That allow
3512                    // us for more redundancy in case we have validators under performing - since the
3513                    // responsibility is shared amongst more nodes. We can increase that once we do have
3514                    // higher confidence.
3515                    cfg.consensus_bad_nodes_stake_threshold = Some(20);
3516                }
3517                24 => {
3518                    cfg.feature_flags.simple_conservation_checks = true;
3519                    cfg.max_publish_or_upgrade_per_ptb = Some(5);
3520
3521                    cfg.feature_flags.end_of_epoch_transaction_supported = true;
3522
3523                    if chain != Chain::Mainnet {
3524                        cfg.feature_flags.enable_jwk_consensus_updates = true;
3525                        // Max of 10 votes per hour
3526                        cfg.max_jwk_votes_per_validator_per_epoch = Some(240);
3527                        cfg.max_age_of_jwk_in_epochs = Some(1);
3528                    }
3529                }
3530                25 => {
3531                    // Enable zkLogin for all providers in all networks.
3532                    cfg.feature_flags.zklogin_supported_providers = BTreeSet::from([
3533                        "Google".to_string(),
3534                        "Facebook".to_string(),
3535                        "Twitch".to_string(),
3536                    ]);
3537                    cfg.feature_flags.zklogin_auth = true;
3538
3539                    // Enable jwk consensus updates
3540                    cfg.feature_flags.enable_jwk_consensus_updates = true;
3541                    cfg.max_jwk_votes_per_validator_per_epoch = Some(240);
3542                    cfg.max_age_of_jwk_in_epochs = Some(1);
3543                }
3544                26 => {
3545                    cfg.gas_model_version = Some(7);
3546                    // Only enable receiving objects in devnet
3547                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3548                        cfg.transfer_receive_object_cost_base = Some(52);
3549                        cfg.feature_flags.receive_objects = true;
3550                    }
3551                }
3552                27 => {
3553                    cfg.gas_model_version = Some(8);
3554                }
3555                28 => {
3556                    // zklogin::check_zklogin_id
3557                    cfg.check_zklogin_id_cost_base = Some(200);
3558                    // zklogin::check_zklogin_issuer
3559                    cfg.check_zklogin_issuer_cost_base = Some(200);
3560
3561                    // Only enable effects v2 on devnet.
3562                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3563                        cfg.feature_flags.enable_effects_v2 = true;
3564                    }
3565                }
3566                29 => {
3567                    cfg.feature_flags.verify_legacy_zklogin_address = true;
3568                }
3569                30 => {
3570                    // Only enable nw certificate v2 on testnet.
3571                    if chain != Chain::Mainnet {
3572                        cfg.feature_flags.narwhal_certificate_v2 = true;
3573                    }
3574
3575                    cfg.random_beacon_reduction_allowed_delta = Some(800);
3576                    // Only enable effects v2 on devnet and testnet.
3577                    if chain != Chain::Mainnet {
3578                        cfg.feature_flags.enable_effects_v2 = true;
3579                    }
3580
3581                    // zklogin_supported_providers config is deprecated, zklogin
3582                    // signature verifier will use the fetched jwk map to determine
3583                    // whether the provider is supported based on node config.
3584                    cfg.feature_flags.zklogin_supported_providers = BTreeSet::default();
3585
3586                    cfg.feature_flags.recompute_has_public_transfer_in_execution = true;
3587                }
3588                31 => {
3589                    cfg.execution_version = Some(2);
3590                    // Only enable shared object deletion on devnet
3591                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3592                        cfg.feature_flags.shared_object_deletion = true;
3593                    }
3594                }
3595                32 => {
3596                    // enable zklogin in multisig in devnet and testnet
3597                    if chain != Chain::Mainnet {
3598                        cfg.feature_flags.accept_zklogin_in_multisig = true;
3599                    }
3600                    // enable receiving objects in devnet and testnet
3601                    if chain != Chain::Mainnet {
3602                        cfg.transfer_receive_object_cost_base = Some(52);
3603                        cfg.feature_flags.receive_objects = true;
3604                    }
3605                    // Only enable random beacon on devnet
3606                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3607                        cfg.feature_flags.random_beacon = true;
3608                        cfg.random_beacon_reduction_lower_bound = Some(1600);
3609                        cfg.random_beacon_dkg_timeout_round = Some(3000);
3610                        cfg.random_beacon_min_round_interval_ms = Some(150);
3611                    }
3612                    // Only enable consensus digest in consensus commit prologue in devnet.
3613                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3614                        cfg.feature_flags.include_consensus_digest_in_prologue = true;
3615                    }
3616
3617                    // enable nw cert v2 on mainnet
3618                    cfg.feature_flags.narwhal_certificate_v2 = true;
3619                }
3620                33 => {
3621                    cfg.feature_flags.hardened_otw_check = true;
3622                    cfg.feature_flags.allow_receiving_object_id = true;
3623
3624                    // Enable transfer-to-object in mainnet
3625                    cfg.transfer_receive_object_cost_base = Some(52);
3626                    cfg.feature_flags.receive_objects = true;
3627
3628                    // Enable shared object deletion in testnet and devnet
3629                    if chain != Chain::Mainnet {
3630                        cfg.feature_flags.shared_object_deletion = true;
3631                    }
3632
3633                    cfg.feature_flags.enable_effects_v2 = true;
3634                }
3635                34 => {}
3636                35 => {
3637                    // Add costs for poseidon::poseidon_bn254
3638                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3639                        cfg.feature_flags.enable_poseidon = true;
3640                        cfg.poseidon_bn254_cost_base = Some(260);
3641                        cfg.poseidon_bn254_cost_per_block = Some(10);
3642                    }
3643
3644                    cfg.feature_flags.enable_coin_deny_list = true;
3645                }
3646                36 => {
3647                    // Only enable group ops on devnet
3648                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3649                        cfg.feature_flags.enable_group_ops_native_functions = true;
3650                        cfg.feature_flags.enable_group_ops_native_function_msm = true;
3651                        // Next values are arbitrary in a similar way as the other crypto native functions.
3652                        cfg.group_ops_bls12381_decode_scalar_cost = Some(52);
3653                        cfg.group_ops_bls12381_decode_g1_cost = Some(52);
3654                        cfg.group_ops_bls12381_decode_g2_cost = Some(52);
3655                        cfg.group_ops_bls12381_decode_gt_cost = Some(52);
3656                        cfg.group_ops_bls12381_scalar_add_cost = Some(52);
3657                        cfg.group_ops_bls12381_g1_add_cost = Some(52);
3658                        cfg.group_ops_bls12381_g2_add_cost = Some(52);
3659                        cfg.group_ops_bls12381_gt_add_cost = Some(52);
3660                        cfg.group_ops_bls12381_scalar_sub_cost = Some(52);
3661                        cfg.group_ops_bls12381_g1_sub_cost = Some(52);
3662                        cfg.group_ops_bls12381_g2_sub_cost = Some(52);
3663                        cfg.group_ops_bls12381_gt_sub_cost = Some(52);
3664                        cfg.group_ops_bls12381_scalar_mul_cost = Some(52);
3665                        cfg.group_ops_bls12381_g1_mul_cost = Some(52);
3666                        cfg.group_ops_bls12381_g2_mul_cost = Some(52);
3667                        cfg.group_ops_bls12381_gt_mul_cost = Some(52);
3668                        cfg.group_ops_bls12381_scalar_div_cost = Some(52);
3669                        cfg.group_ops_bls12381_g1_div_cost = Some(52);
3670                        cfg.group_ops_bls12381_g2_div_cost = Some(52);
3671                        cfg.group_ops_bls12381_gt_div_cost = Some(52);
3672                        cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(52);
3673                        cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(52);
3674                        cfg.group_ops_bls12381_g1_hash_to_cost_per_byte = Some(2);
3675                        cfg.group_ops_bls12381_g2_hash_to_cost_per_byte = Some(2);
3676                        cfg.group_ops_bls12381_g1_msm_base_cost = Some(52);
3677                        cfg.group_ops_bls12381_g2_msm_base_cost = Some(52);
3678                        cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(52);
3679                        cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(52);
3680                        cfg.group_ops_bls12381_msm_max_len = Some(32);
3681                        cfg.group_ops_bls12381_pairing_cost = Some(52);
3682                    }
3683                    // Enable shared object deletion on all networks.
3684                    cfg.feature_flags.shared_object_deletion = true;
3685
3686                    cfg.consensus_max_transaction_size_bytes = Some(256 * 1024); // 256KB
3687                    cfg.consensus_max_transactions_in_block_bytes = Some(6 * 1_024 * 1024);
3688                    // 6 MB
3689                }
3690                37 => {
3691                    cfg.feature_flags.reject_mutable_random_on_entry_functions = true;
3692
3693                    // Enable consensus digest in consensus commit prologue in testnet and devnet.
3694                    if chain != Chain::Mainnet {
3695                        cfg.feature_flags.include_consensus_digest_in_prologue = true;
3696                    }
3697                }
3698                38 => {
3699                    cfg.binary_module_handles = Some(100);
3700                    cfg.binary_struct_handles = Some(300);
3701                    cfg.binary_function_handles = Some(1500);
3702                    cfg.binary_function_instantiations = Some(750);
3703                    cfg.binary_signatures = Some(1000);
3704                    // constants and identifiers are proportional to the binary size,
3705                    // and they vastly depend on the code, so we are leaving them
3706                    // reasonably high
3707                    cfg.binary_constant_pool = Some(4000);
3708                    cfg.binary_identifiers = Some(10000);
3709                    cfg.binary_address_identifiers = Some(100);
3710                    cfg.binary_struct_defs = Some(200);
3711                    cfg.binary_struct_def_instantiations = Some(100);
3712                    cfg.binary_function_defs = Some(1000);
3713                    cfg.binary_field_handles = Some(500);
3714                    cfg.binary_field_instantiations = Some(250);
3715                    cfg.binary_friend_decls = Some(100);
3716                    // reduce dependencies maximum
3717                    cfg.max_package_dependencies = Some(32);
3718                    cfg.max_modules_in_publish = Some(64);
3719                    // bump execution version
3720                    cfg.execution_version = Some(3);
3721                }
3722                39 => {
3723                    // It is important that we keep this protocol version blank due to an issue with random.move.
3724                }
3725                40 => {}
3726                41 => {
3727                    // Enable group ops and all networks (but not msm)
3728                    cfg.feature_flags.enable_group_ops_native_functions = true;
3729                    // Next values are arbitrary in a similar way as the other crypto native functions.
3730                    cfg.group_ops_bls12381_decode_scalar_cost = Some(52);
3731                    cfg.group_ops_bls12381_decode_g1_cost = Some(52);
3732                    cfg.group_ops_bls12381_decode_g2_cost = Some(52);
3733                    cfg.group_ops_bls12381_decode_gt_cost = Some(52);
3734                    cfg.group_ops_bls12381_scalar_add_cost = Some(52);
3735                    cfg.group_ops_bls12381_g1_add_cost = Some(52);
3736                    cfg.group_ops_bls12381_g2_add_cost = Some(52);
3737                    cfg.group_ops_bls12381_gt_add_cost = Some(52);
3738                    cfg.group_ops_bls12381_scalar_sub_cost = Some(52);
3739                    cfg.group_ops_bls12381_g1_sub_cost = Some(52);
3740                    cfg.group_ops_bls12381_g2_sub_cost = Some(52);
3741                    cfg.group_ops_bls12381_gt_sub_cost = Some(52);
3742                    cfg.group_ops_bls12381_scalar_mul_cost = Some(52);
3743                    cfg.group_ops_bls12381_g1_mul_cost = Some(52);
3744                    cfg.group_ops_bls12381_g2_mul_cost = Some(52);
3745                    cfg.group_ops_bls12381_gt_mul_cost = Some(52);
3746                    cfg.group_ops_bls12381_scalar_div_cost = Some(52);
3747                    cfg.group_ops_bls12381_g1_div_cost = Some(52);
3748                    cfg.group_ops_bls12381_g2_div_cost = Some(52);
3749                    cfg.group_ops_bls12381_gt_div_cost = Some(52);
3750                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(52);
3751                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(52);
3752                    cfg.group_ops_bls12381_g1_hash_to_cost_per_byte = Some(2);
3753                    cfg.group_ops_bls12381_g2_hash_to_cost_per_byte = Some(2);
3754                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(52);
3755                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(52);
3756                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(52);
3757                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(52);
3758                    cfg.group_ops_bls12381_msm_max_len = Some(32);
3759                    cfg.group_ops_bls12381_pairing_cost = Some(52);
3760                }
3761                42 => {}
3762                43 => {
3763                    cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = Some(30);
3764                    cfg.max_meter_ticks_per_package = Some(16_000_000);
3765                }
3766                44 => {
3767                    // Enable consensus digest in consensus commit prologue on all networks..
3768                    cfg.feature_flags.include_consensus_digest_in_prologue = true;
3769                    // Switch between Narwhal and Mysticeti per epoch in tests, devnet and testnet.
3770                    if chain != Chain::Mainnet {
3771                        cfg.feature_flags.consensus_choice = ConsensusChoice::SwapEachEpoch;
3772                    }
3773                }
3774                45 => {
3775                    // Use tonic networking for consensus, in tests and devnet.
3776                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3777                        cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
3778                    }
3779
3780                    if chain != Chain::Mainnet {
3781                        // Enable leader scoring & schedule change on testnet for mysticeti.
3782                        cfg.feature_flags.mysticeti_leader_scoring_and_schedule = true;
3783                    }
3784                    cfg.min_move_binary_format_version = Some(6);
3785                    cfg.feature_flags.accept_zklogin_in_multisig = true;
3786
3787                    // Also bumps framework snapshot to fix binop issue.
3788
3789                    // enable bridge in devnet
3790                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3791                        cfg.feature_flags.bridge = true;
3792                    }
3793                }
3794                46 => {
3795                    // enable bridge in devnet and testnet
3796                    if chain != Chain::Mainnet {
3797                        cfg.feature_flags.bridge = true;
3798                    }
3799
3800                    // Enable resharing at same initial version
3801                    cfg.feature_flags.reshare_at_same_initial_version = true;
3802                }
3803                47 => {}
3804                48 => {
3805                    // Use tonic networking for Mysticeti.
3806                    cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
3807
3808                    // Enable resolving abort code IDs to package ID instead of runtime module ID
3809                    cfg.feature_flags.resolve_abort_locations_to_package_id = true;
3810
3811                    // Enable random beacon on testnet.
3812                    if chain != Chain::Mainnet {
3813                        cfg.feature_flags.random_beacon = true;
3814                        cfg.random_beacon_reduction_lower_bound = Some(1600);
3815                        cfg.random_beacon_dkg_timeout_round = Some(3000);
3816                        cfg.random_beacon_min_round_interval_ms = Some(200);
3817                    }
3818
3819                    // Enable the committed sub dag digest inclusion on the commit output
3820                    cfg.feature_flags.mysticeti_use_committed_subdag_digest = true;
3821                }
3822                49 => {
3823                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3824                        cfg.move_binary_format_version = Some(7);
3825                    }
3826
3827                    // enable vdf in devnet
3828                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3829                        cfg.feature_flags.enable_vdf = true;
3830                        // Set to 30x and 2x the cost of a signature verification for now. This
3831                        // should be updated along with other native crypto functions.
3832                        cfg.vdf_verify_vdf_cost = Some(1500);
3833                        cfg.vdf_hash_to_input_cost = Some(100);
3834                    }
3835
3836                    // Only enable consensus commit prologue V3 in devnet.
3837                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3838                        cfg.feature_flags
3839                            .record_consensus_determined_version_assignments_in_prologue = true;
3840                    }
3841
3842                    // Run Mysticeti consensus in testnet.
3843                    if chain != Chain::Mainnet {
3844                        cfg.feature_flags.consensus_choice = ConsensusChoice::Mysticeti;
3845                    }
3846
3847                    // Run Move verification on framework upgrades in its own VM
3848                    cfg.feature_flags.fresh_vm_on_framework_upgrade = true;
3849                }
3850                50 => {
3851                    // Enable checkpoint batching in testnet.
3852                    if chain != Chain::Mainnet {
3853                        cfg.checkpoint_summary_version_specific_data = Some(1);
3854                        cfg.min_checkpoint_interval_ms = Some(200);
3855                    }
3856
3857                    // Only enable prepose consensus commit prologue in checkpoints in devnet.
3858                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3859                        cfg.feature_flags
3860                            .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3861                    }
3862
3863                    cfg.feature_flags.mysticeti_num_leaders_per_round = Some(1);
3864
3865                    // Set max transaction deferral to 10 consensus rounds.
3866                    cfg.max_deferral_rounds_for_congestion_control = Some(10);
3867                }
3868                51 => {
3869                    cfg.random_beacon_dkg_version = Some(1);
3870
3871                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3872                        cfg.feature_flags.enable_coin_deny_list_v2 = true;
3873                    }
3874                }
3875                52 => {
3876                    if chain != Chain::Mainnet {
3877                        cfg.feature_flags.soft_bundle = true;
3878                        cfg.max_soft_bundle_size = Some(5);
3879                    }
3880
3881                    cfg.config_read_setting_impl_cost_base = Some(100);
3882                    cfg.config_read_setting_impl_cost_per_byte = Some(40);
3883
3884                    // Turn on shared object congestion control in devnet.
3885                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3886                        cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3887                        cfg.feature_flags.per_object_congestion_control_mode =
3888                            PerObjectCongestionControlMode::TotalTxCount;
3889                    }
3890
3891                    // Enable Mysticeti on mainnet.
3892                    cfg.feature_flags.consensus_choice = ConsensusChoice::Mysticeti;
3893
3894                    // Enable leader scoring & schedule change on mainnet for mysticeti.
3895                    cfg.feature_flags.mysticeti_leader_scoring_and_schedule = true;
3896
3897                    // Enable checkpoint batching on mainnet.
3898                    cfg.checkpoint_summary_version_specific_data = Some(1);
3899                    cfg.min_checkpoint_interval_ms = Some(200);
3900
3901                    // Enable consensus commit prologue V3 in testnet.
3902                    if chain != Chain::Mainnet {
3903                        cfg.feature_flags
3904                            .record_consensus_determined_version_assignments_in_prologue = true;
3905                        cfg.feature_flags
3906                            .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3907                    }
3908                    // Turn on enums in testnet and devnet
3909                    if chain != Chain::Mainnet {
3910                        cfg.move_binary_format_version = Some(7);
3911                    }
3912
3913                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3914                        cfg.feature_flags.passkey_auth = true;
3915                    }
3916                    cfg.feature_flags.enable_coin_deny_list_v2 = true;
3917                }
3918                53 => {
3919                    // Do not allow bridge committee to finalize on mainnet.
3920                    cfg.bridge_should_try_to_finalize_committee = Some(chain != Chain::Mainnet);
3921
3922                    // Enable consensus commit prologue V3 on mainnet.
3923                    cfg.feature_flags
3924                        .record_consensus_determined_version_assignments_in_prologue = true;
3925                    cfg.feature_flags
3926                        .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3927
3928                    if chain == Chain::Unknown {
3929                        cfg.feature_flags.authority_capabilities_v2 = true;
3930                    }
3931
3932                    // Turns on shared object congestion control on testnet.
3933                    if chain != Chain::Mainnet {
3934                        cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3935                        cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(10);
3936                        cfg.feature_flags.per_object_congestion_control_mode =
3937                            PerObjectCongestionControlMode::TotalTxCount;
3938                    }
3939
3940                    // Adjust stdlib gas costs
3941                    cfg.bcs_per_byte_serialized_cost = Some(2);
3942                    cfg.bcs_legacy_min_output_size_cost = Some(1);
3943                    cfg.bcs_failure_cost = Some(52);
3944                    cfg.debug_print_base_cost = Some(52);
3945                    cfg.debug_print_stack_trace_base_cost = Some(52);
3946                    cfg.hash_sha2_256_base_cost = Some(52);
3947                    cfg.hash_sha2_256_per_byte_cost = Some(2);
3948                    cfg.hash_sha2_256_legacy_min_input_len_cost = Some(1);
3949                    cfg.hash_sha3_256_base_cost = Some(52);
3950                    cfg.hash_sha3_256_per_byte_cost = Some(2);
3951                    cfg.hash_sha3_256_legacy_min_input_len_cost = Some(1);
3952                    cfg.type_name_get_base_cost = Some(52);
3953                    cfg.type_name_get_per_byte_cost = Some(2);
3954                    cfg.string_check_utf8_base_cost = Some(52);
3955                    cfg.string_check_utf8_per_byte_cost = Some(2);
3956                    cfg.string_is_char_boundary_base_cost = Some(52);
3957                    cfg.string_sub_string_base_cost = Some(52);
3958                    cfg.string_sub_string_per_byte_cost = Some(2);
3959                    cfg.string_index_of_base_cost = Some(52);
3960                    cfg.string_index_of_per_byte_pattern_cost = Some(2);
3961                    cfg.string_index_of_per_byte_searched_cost = Some(2);
3962                    cfg.vector_empty_base_cost = Some(52);
3963                    cfg.vector_length_base_cost = Some(52);
3964                    cfg.vector_push_back_base_cost = Some(52);
3965                    cfg.vector_push_back_legacy_per_abstract_memory_unit_cost = Some(2);
3966                    cfg.vector_borrow_base_cost = Some(52);
3967                    cfg.vector_pop_back_base_cost = Some(52);
3968                    cfg.vector_destroy_empty_base_cost = Some(52);
3969                    cfg.vector_swap_base_cost = Some(52);
3970                }
3971                54 => {
3972                    // Enable random beacon on mainnet.
3973                    cfg.feature_flags.random_beacon = true;
3974                    cfg.random_beacon_reduction_lower_bound = Some(1000);
3975                    cfg.random_beacon_dkg_timeout_round = Some(3000);
3976                    cfg.random_beacon_min_round_interval_ms = Some(500);
3977
3978                    // Turns on shared object congestion control on mainnet.
3979                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3980                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(10);
3981                    cfg.feature_flags.per_object_congestion_control_mode =
3982                        PerObjectCongestionControlMode::TotalTxCount;
3983
3984                    // Enable soft bundle on mainnet.
3985                    cfg.feature_flags.soft_bundle = true;
3986                    cfg.max_soft_bundle_size = Some(5);
3987                }
3988                55 => {
3989                    // Turn on enums mainnet
3990                    cfg.move_binary_format_version = Some(7);
3991
3992                    // Assume 1KB per transaction and 500 transactions per block.
3993                    cfg.consensus_max_transactions_in_block_bytes = Some(512 * 1024);
3994                    // Assume 20_000 TPS * 5% max stake per validator / (minimum) 4 blocks per round = 250 transactions per block maximum
3995                    // Using a higher limit that is 512, to account for bursty traffic and system transactions.
3996                    cfg.consensus_max_num_transactions_in_block = Some(512);
3997
3998                    cfg.feature_flags.rethrow_serialization_type_layout_errors = true;
3999                }
4000                56 => {
4001                    if chain == Chain::Mainnet {
4002                        cfg.feature_flags.bridge = true;
4003                    }
4004                }
4005                57 => {
4006                    // Reduce minimum number of random beacon shares.
4007                    cfg.random_beacon_reduction_lower_bound = Some(800);
4008                }
4009                58 => {
4010                    if chain == Chain::Mainnet {
4011                        cfg.bridge_should_try_to_finalize_committee = Some(true);
4012                    }
4013
4014                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4015                        // Enable distributed vote scoring for devnet
4016                        cfg.feature_flags
4017                            .consensus_distributed_vote_scoring_strategy = true;
4018                    }
4019                }
4020                59 => {
4021                    // Enable round prober in consensus.
4022                    cfg.feature_flags.consensus_round_prober = true;
4023                }
4024                60 => {
4025                    cfg.max_type_to_layout_nodes = Some(512);
4026                    cfg.feature_flags.validate_identifier_inputs = true;
4027                }
4028                61 => {
4029                    if chain != Chain::Mainnet {
4030                        // Enable distributed vote scoring for testnet
4031                        cfg.feature_flags
4032                            .consensus_distributed_vote_scoring_strategy = true;
4033                    }
4034                    // Further reduce minimum number of random beacon shares.
4035                    cfg.random_beacon_reduction_lower_bound = Some(700);
4036
4037                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4038                        // Enable Mysticeti fastpath for devnet
4039                        cfg.feature_flags.mysticeti_fastpath = true;
4040                    }
4041                }
4042                62 => {
4043                    cfg.feature_flags.relocate_event_module = true;
4044                }
4045                63 => {
4046                    cfg.feature_flags.per_object_congestion_control_mode =
4047                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
4048                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
4049                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(18_500_000);
4050                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(240_000_000);
4051                }
4052                64 => {
4053                    cfg.feature_flags.per_object_congestion_control_mode =
4054                        PerObjectCongestionControlMode::TotalTxCount;
4055                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(40);
4056                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(3);
4057                }
4058                65 => {
4059                    // Enable distributed vote scoring for mainnet
4060                    cfg.feature_flags
4061                        .consensus_distributed_vote_scoring_strategy = true;
4062                }
4063                66 => {
4064                    if chain == Chain::Mainnet {
4065                        // Revert the distributed vote scoring for mainnet (for one protocol upgrade)
4066                        cfg.feature_flags
4067                            .consensus_distributed_vote_scoring_strategy = false;
4068                    }
4069                }
4070                67 => {
4071                    // Enable it once again.
4072                    cfg.feature_flags
4073                        .consensus_distributed_vote_scoring_strategy = true;
4074                }
4075                68 => {
4076                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(26);
4077                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(52);
4078                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(26);
4079                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(13);
4080                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(2000);
4081
4082                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4083                        cfg.feature_flags.uncompressed_g1_group_elements = true;
4084                    }
4085
4086                    cfg.feature_flags.per_object_congestion_control_mode =
4087                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
4088                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
4089                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(18_500_000);
4090                    cfg.max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit =
4091                        Some(3_700_000); // 20% of above
4092                    cfg.max_txn_cost_overage_per_object_in_commit = Some(u64::MAX);
4093                    cfg.gas_budget_based_txn_cost_absolute_cap_commit_count = Some(50);
4094
4095                    // Further reduce minimum number of random beacon shares.
4096                    cfg.random_beacon_reduction_lower_bound = Some(500);
4097
4098                    cfg.feature_flags.disallow_new_modules_in_deps_only_packages = true;
4099                }
4100                69 => {
4101                    // Sets number of rounds allowed for fastpath voting in consensus.
4102                    cfg.consensus_voting_rounds = Some(40);
4103
4104                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4105                        // Enable smart ancestor selection for devnet
4106                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
4107                    }
4108
4109                    if chain != Chain::Mainnet {
4110                        cfg.feature_flags.uncompressed_g1_group_elements = true;
4111                    }
4112                }
4113                70 => {
4114                    if chain != Chain::Mainnet {
4115                        // Enable smart ancestor selection for testnet
4116                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
4117                        // Enable probing for accepted rounds in round prober for testnet
4118                        cfg.feature_flags
4119                            .consensus_round_prober_probe_accepted_rounds = true;
4120                    }
4121
4122                    cfg.poseidon_bn254_cost_per_block = Some(388);
4123
4124                    cfg.gas_model_version = Some(9);
4125                    cfg.feature_flags.native_charging_v2 = true;
4126                    cfg.bls12381_bls12381_min_sig_verify_cost_base = Some(44064);
4127                    cfg.bls12381_bls12381_min_pk_verify_cost_base = Some(49282);
4128                    cfg.ecdsa_k1_secp256k1_verify_keccak256_cost_base = Some(1470);
4129                    cfg.ecdsa_k1_secp256k1_verify_sha256_cost_base = Some(1470);
4130                    cfg.ecdsa_r1_secp256r1_verify_sha256_cost_base = Some(4225);
4131                    cfg.ecdsa_r1_secp256r1_verify_keccak256_cost_base = Some(4225);
4132                    cfg.ecvrf_ecvrf_verify_cost_base = Some(4848);
4133                    cfg.ed25519_ed25519_verify_cost_base = Some(1802);
4134
4135                    // Manually changed to be "under cost"
4136                    cfg.ecdsa_r1_ecrecover_keccak256_cost_base = Some(1173);
4137                    cfg.ecdsa_r1_ecrecover_sha256_cost_base = Some(1173);
4138                    cfg.ecdsa_k1_ecrecover_keccak256_cost_base = Some(500);
4139                    cfg.ecdsa_k1_ecrecover_sha256_cost_base = Some(500);
4140
4141                    cfg.groth16_prepare_verifying_key_bls12381_cost_base = Some(53838);
4142                    cfg.groth16_prepare_verifying_key_bn254_cost_base = Some(82010);
4143                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_base = Some(72090);
4144                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input =
4145                        Some(8213);
4146                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_base = Some(115502);
4147                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_per_public_input =
4148                        Some(9484);
4149
4150                    cfg.hash_keccak256_cost_base = Some(10);
4151                    cfg.hash_blake2b256_cost_base = Some(10);
4152
4153                    // group ops
4154                    cfg.group_ops_bls12381_decode_scalar_cost = Some(7);
4155                    cfg.group_ops_bls12381_decode_g1_cost = Some(2848);
4156                    cfg.group_ops_bls12381_decode_g2_cost = Some(3770);
4157                    cfg.group_ops_bls12381_decode_gt_cost = Some(3068);
4158
4159                    cfg.group_ops_bls12381_scalar_add_cost = Some(10);
4160                    cfg.group_ops_bls12381_g1_add_cost = Some(1556);
4161                    cfg.group_ops_bls12381_g2_add_cost = Some(3048);
4162                    cfg.group_ops_bls12381_gt_add_cost = Some(188);
4163
4164                    cfg.group_ops_bls12381_scalar_sub_cost = Some(10);
4165                    cfg.group_ops_bls12381_g1_sub_cost = Some(1550);
4166                    cfg.group_ops_bls12381_g2_sub_cost = Some(3019);
4167                    cfg.group_ops_bls12381_gt_sub_cost = Some(497);
4168
4169                    cfg.group_ops_bls12381_scalar_mul_cost = Some(11);
4170                    cfg.group_ops_bls12381_g1_mul_cost = Some(4842);
4171                    cfg.group_ops_bls12381_g2_mul_cost = Some(9108);
4172                    cfg.group_ops_bls12381_gt_mul_cost = Some(27490);
4173
4174                    cfg.group_ops_bls12381_scalar_div_cost = Some(91);
4175                    cfg.group_ops_bls12381_g1_div_cost = Some(5091);
4176                    cfg.group_ops_bls12381_g2_div_cost = Some(9206);
4177                    cfg.group_ops_bls12381_gt_div_cost = Some(27804);
4178
4179                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(2962);
4180                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(8688);
4181
4182                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(62648);
4183                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(131192);
4184                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(1333);
4185                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(3216);
4186
4187                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(677);
4188                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(2099);
4189                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(77);
4190                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(26);
4191
4192                    cfg.group_ops_bls12381_pairing_cost = Some(26897);
4193                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(1200);
4194
4195                    cfg.validator_validate_metadata_cost_base = Some(20000);
4196                }
4197                71 => {
4198                    cfg.sip_45_consensus_amplification_threshold = Some(5);
4199
4200                    // Enable bursts for congestion control. (10x the per-commit budget)
4201                    cfg.allowed_txn_cost_overage_burst_per_object_in_commit = Some(185_000_000);
4202                }
4203                72 => {
4204                    cfg.feature_flags.convert_type_argument_error = true;
4205
4206                    // Invariant: max_gas_price * base_tx_cost_fixed <= max_tx_gas
4207                    // max gas budget is in MIST and an absolute value 50_000 SUI
4208                    cfg.max_tx_gas = Some(50_000_000_000_000);
4209                    // max gas price is in MIST and an absolute value 50 SUI
4210                    cfg.max_gas_price = Some(50_000_000_000);
4211
4212                    cfg.feature_flags.variant_nodes = true;
4213                }
4214                73 => {
4215                    // Enable new marker table version.
4216                    cfg.use_object_per_epoch_marker_table_v2 = Some(true);
4217
4218                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4219                        // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow blocks within a window of ~4 seconds
4220                        // to be included before be considered garbage collected.
4221                        cfg.consensus_gc_depth = Some(60);
4222                    }
4223
4224                    if chain != Chain::Mainnet {
4225                        // Enable zstd compression for consensus in testnet
4226                        cfg.feature_flags.consensus_zstd_compression = true;
4227                    }
4228
4229                    // Enable smart ancestor selection for mainnet
4230                    cfg.feature_flags.consensus_smart_ancestor_selection = true;
4231                    // Enable probing for accepted rounds in round prober for mainnet
4232                    cfg.feature_flags
4233                        .consensus_round_prober_probe_accepted_rounds = true;
4234
4235                    // Increase congestion control budget.
4236                    cfg.feature_flags.per_object_congestion_control_mode =
4237                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
4238                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
4239                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(37_000_000);
4240                    cfg.max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit =
4241                        Some(7_400_000); // 20% of above
4242                    cfg.max_txn_cost_overage_per_object_in_commit = Some(u64::MAX);
4243                    cfg.gas_budget_based_txn_cost_absolute_cap_commit_count = Some(50);
4244                    cfg.allowed_txn_cost_overage_burst_per_object_in_commit = Some(370_000_000);
4245                }
4246                74 => {
4247                    // Enable nitro attestation verify native move function for devnet
4248                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4249                        cfg.feature_flags.enable_nitro_attestation = true;
4250                    }
4251                    cfg.nitro_attestation_parse_base_cost = Some(53 * 50);
4252                    cfg.nitro_attestation_parse_cost_per_byte = Some(50);
4253                    cfg.nitro_attestation_verify_base_cost = Some(49632 * 50);
4254                    cfg.nitro_attestation_verify_cost_per_cert = Some(52369 * 50);
4255
4256                    // Enable zstd compression for consensus in mainnet
4257                    cfg.feature_flags.consensus_zstd_compression = true;
4258
4259                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4260                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4261                    }
4262                }
4263                75 => {
4264                    if chain != Chain::Mainnet {
4265                        cfg.feature_flags.passkey_auth = true;
4266                    }
4267                }
4268                76 => {
4269                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4270                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4271                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4272                    }
4273                    cfg.feature_flags.minimize_child_object_mutations = true;
4274
4275                    if chain != Chain::Mainnet {
4276                        cfg.feature_flags.accept_passkey_in_multisig = true;
4277                    }
4278                }
4279                77 => {
4280                    cfg.feature_flags.uncompressed_g1_group_elements = true;
4281
4282                    if chain != Chain::Mainnet {
4283                        cfg.consensus_gc_depth = Some(60);
4284                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4285                    }
4286                }
4287                78 => {
4288                    cfg.feature_flags.move_native_context = true;
4289                    cfg.tx_context_fresh_id_cost_base = Some(52);
4290                    cfg.tx_context_sender_cost_base = Some(30);
4291                    cfg.tx_context_epoch_cost_base = Some(30);
4292                    cfg.tx_context_epoch_timestamp_ms_cost_base = Some(30);
4293                    cfg.tx_context_sponsor_cost_base = Some(30);
4294                    cfg.tx_context_gas_price_cost_base = Some(30);
4295                    cfg.tx_context_gas_budget_cost_base = Some(30);
4296                    cfg.tx_context_ids_created_cost_base = Some(30);
4297                    cfg.tx_context_replace_cost_base = Some(30);
4298                    cfg.gas_model_version = Some(10);
4299
4300                    if chain != Chain::Mainnet {
4301                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4302                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4303
4304                        // Enable execution time estimate mode for congestion control on testnet.
4305                        cfg.feature_flags.per_object_congestion_control_mode =
4306                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4307                                ExecutionTimeEstimateParams {
4308                                    target_utilization: 30,
4309                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4310                                    randomness_scalar: 20,
4311                                    max_estimate_us: 1_500_000, // 1.5s
4312                                    stored_observations_num_included_checkpoints: 10,
4313                                    stored_observations_limit: u64::MAX,
4314                                    stake_weighted_median_threshold: 0,
4315                                    default_none_duration_for_new_keys: false,
4316                                    observations_chunk_size: None,
4317                                },
4318                            );
4319                    }
4320                }
4321                79 => {
4322                    if chain != Chain::Mainnet {
4323                        cfg.feature_flags.consensus_median_based_commit_timestamp = true;
4324
4325                        // Increase threshold for bad nodes that won't be considered
4326                        // leaders in consensus in testnet
4327                        cfg.consensus_bad_nodes_stake_threshold = Some(30);
4328
4329                        cfg.feature_flags.consensus_batched_block_sync = true;
4330
4331                        // Enable verify nitro attestation in testnet.
4332                        cfg.feature_flags.enable_nitro_attestation = true
4333                    }
4334                    cfg.feature_flags.normalize_ptb_arguments = true;
4335
4336                    cfg.consensus_gc_depth = Some(60);
4337                    cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4338                }
4339                80 => {
4340                    cfg.max_ptb_value_size = Some(1024 * 1024);
4341                }
4342                81 => {
4343                    cfg.feature_flags.consensus_median_based_commit_timestamp = true;
4344                    cfg.feature_flags.enforce_checkpoint_timestamp_monotonicity = true;
4345                    cfg.consensus_bad_nodes_stake_threshold = Some(30)
4346                }
4347                82 => {
4348                    cfg.feature_flags.max_ptb_value_size_v2 = true;
4349                }
4350                83 => {
4351                    if chain == Chain::Mainnet {
4352                        // The address that will sign the recovery transaction.
4353                        let aliased: [u8; 32] = Hex::decode(
4354                            "0x0b2da327ba6a4cacbe75dddd50e6e8bbf81d6496e92d66af9154c61c77f7332f",
4355                        )
4356                        .unwrap()
4357                        .try_into()
4358                        .unwrap();
4359
4360                        // Allow aliasing for the two addresses that contain stolen funds.
4361                        cfg.aliased_addresses.push(AliasedAddress {
4362                            original: Hex::decode("0xcd8962dad278d8b50fa0f9eb0186bfa4cbdecc6d59377214c88d0286a0ac9562").unwrap().try_into().unwrap(),
4363                            aliased,
4364                            allowed_tx_digests: vec![
4365                                Base58::decode("B2eGLFoMHgj93Ni8dAJBfqGzo8EWSTLBesZzhEpTPA4").unwrap().try_into().unwrap(),
4366                            ],
4367                        });
4368
4369                        cfg.aliased_addresses.push(AliasedAddress {
4370                            original: Hex::decode("0xe28b50cef1d633ea43d3296a3f6b67ff0312a5f1a99f0af753c85b8b5de8ff06").unwrap().try_into().unwrap(),
4371                            aliased,
4372                            allowed_tx_digests: vec![
4373                                Base58::decode("J4QqSAgp7VrQtQpMy5wDX4QGsCSEZu3U5KuDAkbESAge").unwrap().try_into().unwrap(),
4374                            ],
4375                        });
4376                    }
4377
4378                    // These features had to be deferred to v84 for mainnet in order to ship the recovery protocol
4379                    // upgrade as a patch to 1.48
4380                    if chain != Chain::Mainnet {
4381                        cfg.feature_flags.resolve_type_input_ids_to_defining_id = true;
4382                        cfg.transfer_party_transfer_internal_cost_base = Some(52);
4383
4384                        // Enable execution time estimate mode for congestion control on mainnet.
4385                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4386                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4387                        cfg.feature_flags.per_object_congestion_control_mode =
4388                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4389                                ExecutionTimeEstimateParams {
4390                                    target_utilization: 30,
4391                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4392                                    randomness_scalar: 20,
4393                                    max_estimate_us: 1_500_000, // 1.5s
4394                                    stored_observations_num_included_checkpoints: 10,
4395                                    stored_observations_limit: u64::MAX,
4396                                    stake_weighted_median_threshold: 0,
4397                                    default_none_duration_for_new_keys: false,
4398                                    observations_chunk_size: None,
4399                                },
4400                            );
4401
4402                        // Enable the new depth-first block sync logic.
4403                        cfg.feature_flags.consensus_batched_block_sync = true;
4404
4405                        // Enable nitro attestation upgraded parsing logic and enable the
4406                        // native function on mainnet.
4407                        cfg.feature_flags.enable_nitro_attestation_upgraded_parsing = true;
4408                        cfg.feature_flags.enable_nitro_attestation = true;
4409                    }
4410                }
4411                84 => {
4412                    if chain == Chain::Mainnet {
4413                        cfg.feature_flags.resolve_type_input_ids_to_defining_id = true;
4414                        cfg.transfer_party_transfer_internal_cost_base = Some(52);
4415
4416                        // Enable execution time estimate mode for congestion control on mainnet.
4417                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4418                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4419                        cfg.feature_flags.per_object_congestion_control_mode =
4420                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4421                                ExecutionTimeEstimateParams {
4422                                    target_utilization: 30,
4423                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4424                                    randomness_scalar: 20,
4425                                    max_estimate_us: 1_500_000, // 1.5s
4426                                    stored_observations_num_included_checkpoints: 10,
4427                                    stored_observations_limit: u64::MAX,
4428                                    stake_weighted_median_threshold: 0,
4429                                    default_none_duration_for_new_keys: false,
4430                                    observations_chunk_size: None,
4431                                },
4432                            );
4433
4434                        // Enable the new depth-first block sync logic.
4435                        cfg.feature_flags.consensus_batched_block_sync = true;
4436
4437                        // Enable nitro attestation upgraded parsing logic and enable the
4438                        // native function on mainnet.
4439                        cfg.feature_flags.enable_nitro_attestation_upgraded_parsing = true;
4440                        cfg.feature_flags.enable_nitro_attestation = true;
4441                    }
4442
4443                    // Limit the number of stored execution time observations at end of epoch.
4444                    cfg.feature_flags.per_object_congestion_control_mode =
4445                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4446                            ExecutionTimeEstimateParams {
4447                                target_utilization: 30,
4448                                allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4449                                randomness_scalar: 20,
4450                                max_estimate_us: 1_500_000, // 1.5s
4451                                stored_observations_num_included_checkpoints: 10,
4452                                stored_observations_limit: 20,
4453                                stake_weighted_median_threshold: 0,
4454                                default_none_duration_for_new_keys: false,
4455                                observations_chunk_size: None,
4456                            },
4457                        );
4458                    cfg.feature_flags.allow_unbounded_system_objects = true;
4459                }
4460                85 => {
4461                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4462                        cfg.feature_flags.enable_party_transfer = true;
4463                    }
4464
4465                    cfg.feature_flags
4466                        .record_consensus_determined_version_assignments_in_prologue_v2 = true;
4467                    cfg.feature_flags.disallow_self_identifier = true;
4468                    cfg.feature_flags.per_object_congestion_control_mode =
4469                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4470                            ExecutionTimeEstimateParams {
4471                                target_utilization: 50,
4472                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4473                                randomness_scalar: 20,
4474                                max_estimate_us: 1_500_000, // 1.5s
4475                                stored_observations_num_included_checkpoints: 10,
4476                                stored_observations_limit: 20,
4477                                stake_weighted_median_threshold: 0,
4478                                default_none_duration_for_new_keys: false,
4479                                observations_chunk_size: None,
4480                            },
4481                        );
4482                }
4483                86 => {
4484                    cfg.feature_flags.type_tags_in_object_runtime = true;
4485                    cfg.max_move_enum_variants = Some(move_core_types::VARIANT_COUNT_MAX);
4486
4487                    // Set a stake_weighted_median_threshold for congestion control.
4488                    cfg.feature_flags.per_object_congestion_control_mode =
4489                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4490                            ExecutionTimeEstimateParams {
4491                                target_utilization: 50,
4492                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4493                                randomness_scalar: 20,
4494                                max_estimate_us: 1_500_000, // 1.5s
4495                                stored_observations_num_included_checkpoints: 10,
4496                                stored_observations_limit: 20,
4497                                stake_weighted_median_threshold: 3334,
4498                                default_none_duration_for_new_keys: false,
4499                                observations_chunk_size: None,
4500                            },
4501                        );
4502                    // Enable party transfer for testnet.
4503                    if chain != Chain::Mainnet {
4504                        cfg.feature_flags.enable_party_transfer = true;
4505                    }
4506                }
4507                87 => {
4508                    if chain == Chain::Mainnet {
4509                        cfg.feature_flags.record_time_estimate_processed = true;
4510                    }
4511                    cfg.feature_flags.better_adapter_type_resolution_errors = true;
4512                }
4513                88 => {
4514                    cfg.feature_flags.record_time_estimate_processed = true;
4515                    cfg.tx_context_rgp_cost_base = Some(30);
4516                    cfg.feature_flags
4517                        .ignore_execution_time_observations_after_certs_closed = true;
4518
4519                    // Disable backwards compatible behavior in execution time estimator for
4520                    // new protocol version.
4521                    cfg.feature_flags.per_object_congestion_control_mode =
4522                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4523                            ExecutionTimeEstimateParams {
4524                                target_utilization: 50,
4525                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4526                                randomness_scalar: 20,
4527                                max_estimate_us: 1_500_000, // 1.5s
4528                                stored_observations_num_included_checkpoints: 10,
4529                                stored_observations_limit: 20,
4530                                stake_weighted_median_threshold: 3334,
4531                                default_none_duration_for_new_keys: true,
4532                                observations_chunk_size: None,
4533                            },
4534                        );
4535                }
4536                89 => {
4537                    cfg.feature_flags.dependency_linkage_error = true;
4538                    cfg.feature_flags.additional_multisig_checks = true;
4539                }
4540                90 => {
4541                    // 100x RGP
4542                    cfg.max_gas_price_rgp_factor_for_aborted_transactions = Some(100);
4543                    cfg.feature_flags.debug_fatal_on_move_invariant_violation = true;
4544                    cfg.feature_flags.additional_consensus_digest_indirect_state = true;
4545                    cfg.feature_flags.accept_passkey_in_multisig = true;
4546                    cfg.feature_flags.passkey_auth = true;
4547                    cfg.feature_flags.check_for_init_during_upgrade = true;
4548
4549                    // Enable Mysticeti fastpath handlers on testnet.
4550                    if chain != Chain::Mainnet {
4551                        cfg.feature_flags.mysticeti_fastpath = true;
4552                    }
4553                }
4554                91 => {
4555                    cfg.feature_flags.per_command_shared_object_transfer_rules = true;
4556                }
4557                92 => {
4558                    cfg.feature_flags.per_command_shared_object_transfer_rules = false;
4559                }
4560                93 => {
4561                    cfg.feature_flags
4562                        .consensus_checkpoint_signature_key_includes_digest = true;
4563                }
4564                94 => {
4565                    // Decrease stored observations limit 20->18 to stay within system object size limit.
4566                    cfg.feature_flags.per_object_congestion_control_mode =
4567                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4568                            ExecutionTimeEstimateParams {
4569                                target_utilization: 50,
4570                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4571                                randomness_scalar: 20,
4572                                max_estimate_us: 1_500_000, // 1.5s
4573                                stored_observations_num_included_checkpoints: 10,
4574                                stored_observations_limit: 18,
4575                                stake_weighted_median_threshold: 3334,
4576                                default_none_duration_for_new_keys: true,
4577                                observations_chunk_size: None,
4578                            },
4579                        );
4580
4581                    // Enable party transfer on mainnet.
4582                    cfg.feature_flags.enable_party_transfer = true;
4583                }
4584                95 => {
4585                    cfg.type_name_id_base_cost = Some(52);
4586
4587                    // Reduce the frequency of checkpoint splitting under high TPS.
4588                    cfg.max_transactions_per_checkpoint = Some(20_000);
4589                }
4590                96 => {
4591                    // Enable artifacts digest in devnet.
4592                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4593                        cfg.feature_flags
4594                            .include_checkpoint_artifacts_digest_in_summary = true;
4595                    }
4596                    cfg.feature_flags.correct_gas_payment_limit_check = true;
4597                    cfg.feature_flags.authority_capabilities_v2 = true;
4598                    cfg.feature_flags.use_mfp_txns_in_load_initial_object_debts = true;
4599                    cfg.feature_flags.cancel_for_failed_dkg_early = true;
4600                    cfg.feature_flags.enable_coin_registry = true;
4601
4602                    // Enable Mysticeti fastpath handlers on mainnet.
4603                    cfg.feature_flags.mysticeti_fastpath = true;
4604                }
4605                97 => {
4606                    cfg.feature_flags.additional_borrow_checks = true;
4607                }
4608                98 => {
4609                    cfg.event_emit_auth_stream_cost = Some(52);
4610                    cfg.feature_flags.better_loader_errors = true;
4611                    cfg.feature_flags.generate_df_type_layouts = true;
4612                }
4613                99 => {
4614                    cfg.feature_flags.use_new_commit_handler = true;
4615                }
4616                100 => {
4617                    cfg.feature_flags.private_generics_verifier_v2 = true;
4618                }
4619                101 => {
4620                    cfg.feature_flags.create_root_accumulator_object = true;
4621                    cfg.max_updates_per_settlement_txn = Some(100);
4622                    if chain != Chain::Mainnet {
4623                        cfg.feature_flags.enable_poseidon = true;
4624                    }
4625                }
4626                102 => {
4627                    // Enable execution time observation chunking and increase limit to 180.
4628                    // max_move_object_size is 250 KB, we've experientially determined that fits ~ 18 estimates
4629                    // so if we have 10 chunks, that's 2.5MB, < 8MB max_serialized_tx_effects_size_bytes_system_tx
4630                    cfg.feature_flags.per_object_congestion_control_mode =
4631                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4632                            ExecutionTimeEstimateParams {
4633                                target_utilization: 50,
4634                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4635                                randomness_scalar: 20,
4636                                max_estimate_us: 1_500_000, // 1.5s
4637                                stored_observations_num_included_checkpoints: 10,
4638                                stored_observations_limit: 180,
4639                                stake_weighted_median_threshold: 3334,
4640                                default_none_duration_for_new_keys: true,
4641                                observations_chunk_size: Some(18),
4642                            },
4643                        );
4644                    cfg.feature_flags.deprecate_global_storage_ops = true;
4645                }
4646                103 => {}
4647                104 => {
4648                    cfg.translation_per_command_base_charge = Some(1);
4649                    cfg.translation_per_input_base_charge = Some(1);
4650                    cfg.translation_pure_input_per_byte_charge = Some(1);
4651                    cfg.translation_per_type_node_charge = Some(1);
4652                    cfg.translation_per_reference_node_charge = Some(1);
4653                    cfg.translation_per_linkage_entry_charge = Some(10);
4654                    cfg.gas_model_version = Some(11);
4655                    cfg.feature_flags.abstract_size_in_object_runtime = true;
4656                    cfg.feature_flags.object_runtime_charge_cache_load_gas = true;
4657                    cfg.dynamic_field_hash_type_and_key_cost_base = Some(52);
4658                    cfg.dynamic_field_add_child_object_cost_base = Some(52);
4659                    cfg.dynamic_field_add_child_object_value_cost_per_byte = Some(1);
4660                    cfg.dynamic_field_borrow_child_object_cost_base = Some(52);
4661                    cfg.dynamic_field_borrow_child_object_child_ref_cost_per_byte = Some(1);
4662                    cfg.dynamic_field_remove_child_object_cost_base = Some(52);
4663                    cfg.dynamic_field_remove_child_object_child_cost_per_byte = Some(1);
4664                    cfg.dynamic_field_has_child_object_cost_base = Some(52);
4665                    cfg.dynamic_field_has_child_object_with_ty_cost_base = Some(52);
4666                    cfg.feature_flags.enable_ptb_execution_v2 = true;
4667
4668                    cfg.poseidon_bn254_cost_base = Some(260);
4669
4670                    cfg.feature_flags.consensus_skip_gced_accept_votes = true;
4671
4672                    if chain != Chain::Mainnet {
4673                        cfg.feature_flags
4674                            .enable_nitro_attestation_all_nonzero_pcrs_parsing = true;
4675                    }
4676
4677                    cfg.feature_flags
4678                        .include_cancelled_randomness_txns_in_prologue = true;
4679                }
4680                105 => {
4681                    cfg.feature_flags.enable_multi_epoch_transaction_expiration = true;
4682                    cfg.feature_flags.disable_preconsensus_locking = true;
4683
4684                    if chain != Chain::Mainnet {
4685                        cfg.feature_flags
4686                            .enable_nitro_attestation_always_include_required_pcrs_parsing = true;
4687                    }
4688                }
4689                106 => {
4690                    // est. 100 bytes per object * 76 (storage_gas_price)
4691                    cfg.accumulator_object_storage_cost = Some(7600);
4692
4693                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4694                        cfg.feature_flags.enable_accumulators = true;
4695                        cfg.feature_flags.enable_address_balance_gas_payments = true;
4696                        cfg.feature_flags.enable_authenticated_event_streams = true;
4697                        cfg.feature_flags.enable_object_funds_withdraw = true;
4698                    }
4699                }
4700                107 => {
4701                    cfg.feature_flags
4702                        .consensus_skip_gced_blocks_in_direct_finalization = true;
4703
4704                    // Trigger edge cases more often in integration tests.
4705                    if in_integration_test() {
4706                        cfg.consensus_gc_depth = Some(6);
4707                        cfg.consensus_max_num_transactions_in_block = Some(8);
4708                    }
4709                }
4710                108 => {
4711                    cfg.feature_flags.gas_rounding_halve_digits = true;
4712                    cfg.feature_flags.flexible_tx_context_positions = true;
4713                    cfg.feature_flags.disable_entry_point_signature_check = true;
4714
4715                    if chain != Chain::Mainnet {
4716                        cfg.feature_flags.address_aliases = true;
4717
4718                        cfg.feature_flags.enable_accumulators = true;
4719                        cfg.feature_flags.enable_address_balance_gas_payments = true;
4720                    }
4721
4722                    cfg.feature_flags.enable_poseidon = true;
4723                }
4724                109 => {
4725                    cfg.binary_variant_handles = Some(1024);
4726                    cfg.binary_variant_instantiation_handles = Some(1024);
4727                    cfg.feature_flags.restrict_hot_or_not_entry_functions = true;
4728                }
4729                110 => {
4730                    cfg.feature_flags
4731                        .enable_nitro_attestation_all_nonzero_pcrs_parsing = true;
4732                    cfg.feature_flags
4733                        .enable_nitro_attestation_always_include_required_pcrs_parsing = true;
4734                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4735                        cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4736                    }
4737                    cfg.feature_flags.validate_zklogin_public_identifier = true;
4738                    cfg.feature_flags.fix_checkpoint_signature_mapping = true;
4739                    cfg.feature_flags
4740                        .consensus_always_accept_system_transactions = true;
4741                    if chain != Chain::Mainnet {
4742                        cfg.feature_flags.enable_object_funds_withdraw = true;
4743                    }
4744                }
4745                111 => {
4746                    cfg.feature_flags.validator_metadata_verify_v2 = true;
4747                }
4748                112 => {
4749                    cfg.group_ops_ristretto_decode_scalar_cost = Some(7);
4750                    cfg.group_ops_ristretto_decode_point_cost = Some(200);
4751                    cfg.group_ops_ristretto_scalar_add_cost = Some(10);
4752                    cfg.group_ops_ristretto_point_add_cost = Some(500);
4753                    cfg.group_ops_ristretto_scalar_sub_cost = Some(10);
4754                    cfg.group_ops_ristretto_point_sub_cost = Some(500);
4755                    cfg.group_ops_ristretto_scalar_mul_cost = Some(11);
4756                    cfg.group_ops_ristretto_point_mul_cost = Some(1200);
4757                    cfg.group_ops_ristretto_scalar_div_cost = Some(151);
4758                    cfg.group_ops_ristretto_point_div_cost = Some(2500);
4759
4760                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4761                        cfg.feature_flags.enable_ristretto255_group_ops = true;
4762                    }
4763                }
4764                113 => {
4765                    cfg.feature_flags.address_balance_gas_check_rgp_at_signing = true;
4766                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4767                        cfg.feature_flags.defer_unpaid_amplification = true;
4768                    }
4769                }
4770                114 => {
4771                    cfg.feature_flags.randomize_checkpoint_tx_limit_in_tests = true;
4772                    cfg.feature_flags.address_balance_gas_reject_gas_coin_arg = true;
4773                    if chain != Chain::Mainnet {
4774                        cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4775                        cfg.feature_flags.enable_authenticated_event_streams = true;
4776                        cfg.feature_flags
4777                            .include_checkpoint_artifacts_digest_in_summary = true;
4778                    }
4779                }
4780                115 => {
4781                    cfg.feature_flags.normalize_depth_formula = true;
4782                }
4783                116 => {
4784                    cfg.feature_flags.gasless_transaction_drop_safety = true;
4785                    cfg.feature_flags.address_aliases = true;
4786                    cfg.feature_flags.relax_valid_during_for_owned_inputs = true;
4787                    // Disabled while debugging
4788                    cfg.feature_flags.defer_unpaid_amplification = false;
4789                    cfg.feature_flags.enable_display_registry = true;
4790                }
4791                117 => {}
4792                118 => {
4793                    cfg.feature_flags.use_coin_party_owner = true;
4794                }
4795                119 => {
4796                    // Enable new VM.
4797                    cfg.execution_version = Some(4);
4798                    cfg.feature_flags.address_balance_gas_reject_gas_coin_arg = false;
4799                    cfg.feature_flags.merge_randomness_into_checkpoint = true;
4800                    if chain != Chain::Mainnet {
4801                        cfg.feature_flags.enable_gasless = true;
4802                        cfg.gasless_max_computation_units = Some(50_000);
4803                        cfg.gasless_allowed_token_types = Some(vec![]);
4804                        cfg.feature_flags.enable_coin_reservation_obj_refs = true;
4805                        cfg.feature_flags
4806                            .convert_withdrawal_compatibility_ptb_arguments = true;
4807                    }
4808                    cfg.gasless_max_unused_inputs = Some(1);
4809                    cfg.gasless_max_pure_input_bytes = Some(32);
4810                    if chain == Chain::Testnet {
4811                        cfg.gasless_allowed_token_types = Some(vec![(TESTNET_USDC.to_string(), 0)]);
4812                    }
4813                    cfg.transfer_receive_object_cost_per_byte = Some(1);
4814                    cfg.transfer_receive_object_type_cost_per_byte = Some(2);
4815                }
4816                120 => {
4817                    cfg.feature_flags.disallow_jump_orphans = true;
4818                }
4819                121 => {
4820                    // Re-enable unpaid amplification deferral protection (testnet + devnet)
4821                    if chain != Chain::Mainnet {
4822                        cfg.feature_flags.defer_unpaid_amplification = true;
4823                        cfg.gasless_max_tps = Some(50);
4824                    }
4825                    cfg.feature_flags
4826                        .early_return_receive_object_mismatched_type = true;
4827                }
4828                122 => {
4829                    // Enable unpaid amplification deferral on mainnet
4830                    cfg.feature_flags.defer_unpaid_amplification = true;
4831                    // Enable bulletproofs range proofs on devnet
4832                    cfg.verify_bulletproofs_ristretto255_base_cost = Some(30000);
4833                    cfg.verify_bulletproofs_ristretto255_cost_per_bit_and_commitment = Some(6500);
4834                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4835                        cfg.feature_flags.enable_verify_bulletproofs_ristretto255 = true;
4836                    }
4837                    cfg.feature_flags.gasless_verify_remaining_balance = true;
4838                    cfg.include_special_package_amendments = match chain {
4839                        Chain::Mainnet => Some(MAINNET_LINKAGE_AMENDMENTS.clone()),
4840                        Chain::Testnet => Some(TESTNET_LINKAGE_AMENDMENTS.clone()),
4841                        Chain::Unknown => None,
4842                    };
4843                    cfg.gasless_max_tx_size_bytes = Some(16 * 1024);
4844                    cfg.gasless_max_tps = Some(300);
4845                    cfg.gasless_max_computation_units = Some(5_000);
4846                }
4847                123 => {
4848                    cfg.gas_model_version = Some(13);
4849                }
4850                124 => {
4851                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4852                        cfg.feature_flags.timestamp_based_epoch_close = true;
4853                    }
4854                    cfg.gas_model_version = Some(14);
4855                    cfg.feature_flags.limit_groth16_pvk_inputs = true;
4856
4857                    // Bring mainnet in line with testnet: enable address balances, the
4858                    // gasless "free tier", coin reservations, and the rest of the
4859                    // accumulator/withdraw stack. These are all already enabled on
4860                    // testnet and devnet, so setting them unconditionally is a no-op
4861                    // there.
4862                    cfg.feature_flags.enable_accumulators = true;
4863                    cfg.feature_flags.enable_address_balance_gas_payments = true;
4864                    cfg.feature_flags.enable_authenticated_event_streams = true;
4865                    cfg.feature_flags.enable_coin_reservation_obj_refs = true;
4866                    cfg.feature_flags.enable_object_funds_withdraw = true;
4867                    cfg.feature_flags
4868                        .convert_withdrawal_compatibility_ptb_arguments = true;
4869                    cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4870                    cfg.feature_flags
4871                        .include_checkpoint_artifacts_digest_in_summary = true;
4872                    cfg.feature_flags.enable_gasless = true;
4873
4874                    // Set the mainnet allow-list. Testnet already has its USDC entry
4875                    // from v119, so only set this on mainnet to avoid clobbering the
4876                    // testnet value. $0.01 minimum transfer per stable; all listed
4877                    // tokens have 6 decimals.
4878                    if chain == Chain::Mainnet {
4879                        cfg.gasless_allowed_token_types = Some(vec![
4880                            (MAINNET_USDC.to_string(), 10_000),
4881                            (MAINNET_USDSUI.to_string(), 10_000),
4882                            (MAINNET_SUI_USDE.to_string(), 10_000),
4883                            (MAINNET_USDY.to_string(), 10_000),
4884                            (MAINNET_FDUSD.to_string(), 10_000),
4885                            (MAINNET_AUSD.to_string(), 10_000),
4886                            (MAINNET_USDB.to_string(), 10_000),
4887                        ]);
4888                    }
4889                }
4890                125 => {
4891                    cfg.feature_flags.granular_post_execution_checks = true;
4892                    if chain != Chain::Mainnet {
4893                        cfg.feature_flags.timestamp_based_epoch_close = true;
4894                    }
4895                }
4896                126 => {
4897                    cfg.feature_flags.early_exit_on_iffw = true;
4898                }
4899                127 => {
4900                    cfg.feature_flags.always_advance_dkg_to_resolution = true;
4901
4902                    cfg.verify_bulletproofs_ristretto255_base_cost = Some(23866);
4903                    cfg.verify_bulletproofs_ristretto255_cost_per_bit_and_commitment = Some(1324);
4904                    cfg.group_ops_ristretto_decode_scalar_cost = Some(5);
4905                    cfg.group_ops_ristretto_decode_point_cost = Some(216);
4906                    cfg.group_ops_ristretto_scalar_add_cost = Some(2);
4907                    cfg.group_ops_ristretto_point_add_cost = Some(8);
4908                    cfg.group_ops_ristretto_scalar_sub_cost = Some(2);
4909                    cfg.group_ops_ristretto_point_sub_cost = Some(8);
4910                    cfg.group_ops_ristretto_scalar_mul_cost = Some(5);
4911                    cfg.group_ops_ristretto_point_mul_cost = Some(1763);
4912                    cfg.group_ops_ristretto_scalar_div_cost = Some(557);
4913                    cfg.group_ops_ristretto_point_div_cost = Some(2244);
4914
4915                    if chain != Chain::Mainnet {
4916                        cfg.feature_flags.enable_ristretto255_group_ops = true;
4917                        cfg.feature_flags.enable_verify_bulletproofs_ristretto255 = true;
4918                    }
4919
4920                    cfg.feature_flags.timestamp_based_epoch_close = true;
4921                }
4922                128 => {
4923                    cfg.max_generic_instantiation_type_nodes_per_function = Some(10_000);
4924                    cfg.max_generic_instantiation_type_nodes_per_module = Some(500_000);
4925                    cfg.binary_enum_defs = Some(200);
4926                    cfg.binary_enum_def_instantiations = Some(100);
4927                }
4928                129 => {
4929                    cfg.feature_flags.enable_unified_linkage = true;
4930                }
4931                130 => {
4932                    cfg.feature_flags.record_net_unsettled_object_withdraws = true;
4933                    cfg.feature_flags.enable_init_on_upgrade = true;
4934                    cfg.epoch_close_deadline_ms = Some(120_000);
4935                    cfg.scratch_add_cost_base = Some(13);
4936                    cfg.scratch_read_cost_base = Some(13);
4937                    cfg.scratch_read_value_cost = Some(1);
4938                    cfg.scratch_remove_cost_base = Some(13);
4939                    cfg.scratch_exists_cost_base = Some(13);
4940                    cfg.scratch_exists_with_type_cost_base = Some(13);
4941                    cfg.scratch_exists_with_type_type_cost = Some(1);
4942                    let max_commands = cfg.max_programmable_tx_commands() as u64;
4943                    cfg.max_scratch_pad_size = Some(16 * max_commands);
4944                    // Verify with the v2 then v1 for devnet.
4945                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4946                        cfg.feature_flags.zklogin_circuit_mode = 1;
4947                    }
4948                }
4949                131 => {
4950                    cfg.feature_flags.share_transaction_deny_config_in_consensus = true;
4951                    cfg.feature_flags.framework_tx_context_mut_restrictions = true;
4952                }
4953                132 => {
4954                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4955                        cfg.feature_flags.defer_owned_object_double_spend = true;
4956                        cfg.feature_flags.create_forwarding_address_registry = true;
4957                    }
4958                    cfg.object_record_new_uid_from_hash_cost_base = Some(1);
4959                    cfg.feature_flags
4960                        .enable_order_independent_upgrade_init_linkage = true;
4961                }
4962                133 => {
4963                    cfg.feature_flags
4964                        .include_function_signatures_in_instantiation_limits = true;
4965                    cfg.max_accumulator_type_nodes = Some(16);
4966                }
4967                134 => {
4968                    // v134 was released to testnet with this content before the 1.77
4969                    // branch backfilled its own v134 to disable defer_unpaid_amplification
4970                    // on mainnet. To keep (v134, Mainnet) identical across the 1.77 and
4971                    // 1.78 branches, the original v134 content is gated off mainnet here
4972                    // (it applies to mainnet in v135 instead), and mainnet's v134 carries
4973                    // only the deferral disable.
4974                    if chain != Chain::Mainnet {
4975                        cfg.package_original_package_id_impl_cost_base = Some(52);
4976                        let package_read_cost_per_byte = cfg.obj_access_cost_read_per_byte();
4977                        cfg.package_original_package_id_impl_cost_per_byte =
4978                            Some(package_read_cost_per_byte);
4979
4980                        cfg.consensus_max_transactions_in_block_bytes = Some(288 * 1024);
4981                        cfg.consensus_max_num_transactions_in_block = Some(128);
4982                    }
4983
4984                    if chain == Chain::Mainnet {
4985                        cfg.feature_flags.defer_unpaid_amplification = false;
4986                    }
4987                }
4988                135 => {
4989                    // Apply the original v134 content on mainnet (no-op re-assignment on
4990                    // chains that already applied it in v134).
4991                    cfg.package_original_package_id_impl_cost_base = Some(52);
4992                    let package_read_cost_per_byte = cfg.obj_access_cost_read_per_byte();
4993                    cfg.package_original_package_id_impl_cost_per_byte =
4994                        Some(package_read_cost_per_byte);
4995
4996                    cfg.consensus_max_transactions_in_block_bytes = Some(288 * 1024);
4997                    cfg.consensus_max_num_transactions_in_block = Some(128);
4998
4999                    cfg.feature_flags.defer_unpaid_amplification = false;
5000                }
5001                136 => {
5002                    cfg.feature_flags.ptb_tx_context_restrictions = true;
5003
5004                    cfg.translation_per_live_reference_charge = Some(1);
5005                    cfg.max_ptb_live_references = Some(64);
5006                    cfg.max_ptb_returned_references = Some(16);
5007                    cfg.max_ptb_total_returned_references = Some(256);
5008
5009                    if chain != Chain::Mainnet && chain != Chain::Testnet {
5010                        cfg.feature_flags.allowed_proposers = true;
5011                    }
5012                    cfg.feature_flags.harden_linkage_consistency = true;
5013
5014                    cfg.package_arena_size_in_bytes = Some(10_000_000);
5015                }
5016                137 => {
5017                    cfg.verify_bulletproofs_ristretto255_cost_per_bit_and_commitment = Some(621);
5018                    cfg.max_bulletproofs_total_bits = Some(1024);
5019
5020                    if chain != Chain::Mainnet {
5021                        cfg.feature_flags.enable_allowances = true;
5022                    }
5023                    cfg.feature_flags.fix_ptb_generated_reads = true;
5024                    cfg.feature_flags.charge_ld_const_abstract_size = true;
5025                    if chain != Chain::Mainnet && chain != Chain::Testnet {
5026                        cfg.feature_flags.check_object_funds_withdraw_in_execution = true;
5027                    }
5028                    cfg.reserve_object_funds_for_withdrawal_cost_base = Some(52);
5029                    // Equivalent to the fixed portion of a dynamic-field lookup (52 + 52) plus
5030                    // loading the 80-byte accumulator field contents at one gas unit per byte.
5031                    cfg.reserve_object_funds_for_withdrawal_cold_read_cost = Some(184);
5032
5033                    cfg.feature_flags.allowed_proposers = true;
5034
5035                    cfg.feature_flags.validate_ptb_argument_indices = true;
5036                    cfg.feature_flags.memory_safety_invariant_check_v2 = true;
5037                }
5038                138 => {
5039                    cfg.gas_model_version = Some(15);
5040                    cfg.feature_flags.enable_allowances = true;
5041                    if chain != Chain::Mainnet {
5042                        cfg.feature_flags.check_object_funds_withdraw_in_execution = true;
5043                        cfg.feature_flags.disable_effects_tx_dependencies = true;
5044                    }
5045                    cfg.feature_flags.merge_colliding_deferrals = true;
5046                    // Testnet already runs version 138, so it gets this change in version 139.
5047                    if chain == Chain::Mainnet {
5048                        cfg.storage_rebate_rate = Some(9999);
5049                    }
5050                }
5051                139 => {
5052                    if chain != Chain::Mainnet && chain != Chain::Testnet {
5053                        cfg.feature_flags.enable_forwarding_addresses = true;
5054                        cfg.feature_flags.mldsa65_auth = true;
5055                    }
5056                    cfg.storage_rebate_rate = Some(9999);
5057                    if chain != Chain::Mainnet {
5058                        cfg.feature_flags.allow_dkg_completion_after_timeout = true;
5059                    }
5060                    // Validators cache packages, so reading one costs far less than reading an object.
5061                    cfg.obj_access_cost_read_per_package_kb = Some(154);
5062                }
5063                140 => {
5064                    // Signal thresholds are set on every chain. They take effect only
5065                    // where `staggered_submission_signal` is enabled.
5066                    cfg.staggered_submission_signal_window_commits = Some(300);
5067                    cfg.staggered_submission_signal_min_excess_copies_per_commit = Some(2);
5068                    cfg.staggered_submission_signal_exit_dwell_commits = Some(6000);
5069                    cfg.staggered_submission_signal_band1_enter_ratio_bps = Some(1000);
5070                    cfg.staggered_submission_signal_band1_exit_ratio_bps = Some(500);
5071                    cfg.staggered_submission_signal_band2_enter_ratio_bps = Some(5000);
5072                    cfg.staggered_submission_signal_band2_exit_ratio_bps = Some(2500);
5073
5074                    cfg.vector_reverse_base_cost = Some(52);
5075                    cfg.vector_reverse_per_elem_cost = Some(8);
5076                    cfg.vector_keep_range_base_cost = Some(52);
5077                    cfg.vector_keep_range_per_dropped_elem_cost = Some(1);
5078                    cfg.vector_keep_range_per_moved_elem_cost = Some(8);
5079                    cfg.vector_copy_range_base_cost = Some(52);
5080                    cfg.vector_replace_range_base_cost = Some(52);
5081                    cfg.vector_replace_range_per_elem_cost = Some(8);
5082
5083                    if chain != Chain::Mainnet && chain != Chain::Testnet {
5084                        cfg.feature_flags.shuffle_consensus_commit_blocks = true;
5085                    }
5086
5087                    cfg.feature_flags.allow_references_in_ptbs = true;
5088                    cfg.feature_flags.disable_id_leak_verifier = true;
5089                    cfg.feature_flags.check_object_funds_withdraw_in_execution = true;
5090                    cfg.feature_flags.disable_effects_tx_dependencies = true;
5091                }
5092                141 => {
5093                    cfg.feature_flags.complete_effects_size_estimate = true;
5094                    cfg.max_num_accumulator_events = Some(1024);
5095                }
5096                142 => {
5097                    cfg.clock_borrow_cost_base = Some(52);
5098                    cfg.feature_flags.check_groth16_pvk_length = true;
5099                    cfg.object_is_shared_input_cost_base = Some(52);
5100                    cfg.feature_flags.secp256r1_ecrecover_checks_x_below_p = true;
5101                    cfg.binary_format_limits_profile = Some(BinaryFormatLimitsProfile::V1);
5102                    cfg.feature_flags.defer_owned_object_double_spend = true;
5103                }
5104                143 => {
5105                    cfg.execution_version = Some(5);
5106                    cfg.package_arena_size_in_bytes = Some(20_000_000);
5107                    cfg.feature_flags.simplify_nitro_header_validation = true;
5108                    cfg.feature_flags.enable_forwarding_addresses = false;
5109                    cfg.feature_flags.package_publish_charge = true;
5110                    cfg.package_publish_charge_fixed = Some(1_000_000_000);
5111                    cfg.package_publish_charge_per_module = Some(10_000_000);
5112                    cfg.package_publish_charge_per_dependency = Some(10_000_000);
5113                    if chain != Chain::Mainnet {
5114                        cfg.feature_flags.mldsa65_auth = true;
5115                    }
5116                    cfg.layout_node_cost = Some(16);
5117                    cfg.layout_node_cost_large_layout_threshold = Some(64);
5118                    cfg.bcs_per_input_abstract_unit_cost = Some(20);
5119                    cfg.vector_copy_range_per_abstract_memory_unit_cost = Some(1);
5120                }
5121                144 => {
5122                    if chain != Chain::Mainnet && chain != Chain::Testnet {
5123                        cfg.feature_flags.enable_timestamp_transaction_expiration = true;
5124                    }
5125                    cfg.object_runtime_max_loaded_child_value_size = Some(5_000_000);
5126
5127                    cfg.feature_flags.staggered_submission_signal = true;
5128                    // Staggering should turn on only at peak load. Mainnet commits about
5129                    // 15 times per second. There the window covers about 40 seconds and
5130                    // the floor is about 15,000 user transactions per second, duplicates
5131                    // included.
5132                    // Under load mainnet commits about 10 to 13 times per second. There
5133                    // the window covers 46 to 60 seconds and the floor is about 10,000
5134                    // to 13,000 user transactions per second.
5135                    // Mainnet traffic from 2026-11-04 to 2026-11-19 would have turned
5136                    // the signal on 32 times, with a median of once per day. With the
5137                    // same floor and the previous window of 300 commits, bursts of a
5138                    // few seconds would have turned it on 83 times.
5139                    cfg.staggered_submission_signal_window_commits = Some(600);
5140                    cfg.staggered_submission_signal_min_consensus_user_transactions_per_commit =
5141                        Some(1000);
5142                    if chain == Chain::Testnet {
5143                        // Testnet carries about one user transaction per commit and almost no
5144                        // duplicates, so it never meets the floor above. From 2026-11-04
5145                        // to 2026-11-19 no testnet window averaged more than 3 user transactions
5146                        // per commit. This floor lets a load test that submits
5147                        // duplicates turn the signal on.
5148                        cfg.staggered_submission_signal_min_consensus_user_transactions_per_commit = Some(5);
5149                    }
5150                }
5151                145 => {
5152                    cfg.feature_flags.secp256r1_strict_public_keys = true;
5153                    cfg.feature_flags.create_freeze_list = true;
5154                    cfg.feature_flags.enable_coin_regulation = true;
5155                    cfg.max_freeze_list_address_reads = Some(10_000);
5156                }
5157                // Use this template when making changes:
5158                //
5159                //     // modify an existing constant.
5160                //     move_binary_format_version: Some(7),
5161                //
5162                //     // Add a new constant (which is set to None in prior versions).
5163                //     new_constant: Some(new_value),
5164                //
5165                //     // Remove a constant (ensure that it is never accessed during this version).
5166                //     max_move_object_size: None,
5167                _ => panic!("unsupported version {:?}", version),
5168            }
5169        }
5170
5171        cfg
5172    }
5173
5174    pub fn apply_seeded_test_overrides(&mut self, seed: &[u8; 32]) {
5175        if !self.feature_flags.randomize_checkpoint_tx_limit_in_tests
5176            || !self.feature_flags.split_checkpoints_in_consensus_handler
5177        {
5178            return;
5179        }
5180
5181        if !mysten_common::in_test_configuration() {
5182            return;
5183        }
5184
5185        use rand::{Rng, SeedableRng, rngs::StdRng};
5186        let mut rng = StdRng::from_seed(*seed);
5187        let max_txns = rng.gen_range(10..=100u64);
5188        info!("seeded test override: max_transactions_per_checkpoint = {max_txns}");
5189        self.max_transactions_per_checkpoint = Some(max_txns);
5190    }
5191
5192    // Extract the bytecode verifier config from this protocol config.
5193    // If used during signing, `signing_limits` should be set.
5194    // The third limit configures`sanity_check_with_regex_reference_safety`,
5195    // which runs the new regex-based reference safety check to check that it is strictly more
5196    // permissive than the current implementation.
5197    pub fn verifier_config(&self, signing_limits: Option<(usize, usize, usize)>) -> VerifierConfig {
5198        let (
5199            max_back_edges_per_function,
5200            max_back_edges_per_module,
5201            sanity_check_with_regex_reference_safety,
5202        ) = if let Some((
5203            max_back_edges_per_function,
5204            max_back_edges_per_module,
5205            sanity_check_with_regex_reference_safety,
5206        )) = signing_limits
5207        {
5208            (
5209                Some(max_back_edges_per_function),
5210                Some(max_back_edges_per_module),
5211                Some(sanity_check_with_regex_reference_safety),
5212            )
5213        } else {
5214            (None, None, None)
5215        };
5216
5217        let additional_borrow_checks = if signing_limits.is_some() {
5218            // always turn on additional borrow checks during signing
5219            true
5220        } else {
5221            self.additional_borrow_checks()
5222        };
5223        let deprecate_global_storage_ops = if signing_limits.is_some() {
5224            // always turn on additional vector borrow checks during signing
5225            true
5226        } else {
5227            self.deprecate_global_storage_ops()
5228        };
5229
5230        VerifierConfig {
5231            max_loop_depth: Some(self.max_loop_depth() as usize),
5232            max_generic_instantiation_length: Some(self.max_generic_instantiation_length() as usize),
5233            max_function_parameters: Some(self.max_function_parameters() as usize),
5234            max_basic_blocks: Some(self.max_basic_blocks() as usize),
5235            max_value_stack_size: self.max_value_stack_size() as usize,
5236            max_type_nodes: Some(self.max_type_nodes() as usize),
5237            max_generic_instantiation_type_nodes_per_function: self
5238                .max_generic_instantiation_type_nodes_per_function_as_option()
5239                .map(|v| v as usize),
5240            max_generic_instantiation_type_nodes_per_module: self
5241                .max_generic_instantiation_type_nodes_per_module_as_option()
5242                .map(|v| v as usize),
5243            include_function_signatures_in_instantiation_limits: self
5244                .include_function_signatures_in_instantiation_limits(),
5245            max_push_size: Some(self.max_push_size() as usize),
5246            max_dependency_depth: Some(self.max_dependency_depth() as usize),
5247            max_fields_in_struct: Some(self.max_fields_in_struct() as usize),
5248            max_function_definitions: Some(self.max_function_definitions() as usize),
5249            max_data_definitions: Some(self.max_struct_definitions() as usize),
5250            max_constant_vector_len: Some(self.max_move_vector_len()),
5251            max_back_edges_per_function,
5252            max_back_edges_per_module,
5253            max_basic_blocks_in_script: None,
5254            max_identifier_len: self.max_move_identifier_len_as_option(), // Before protocol version 9, there was no limit
5255            disallow_self_identifier: self.feature_flags.disallow_self_identifier,
5256            allow_receiving_object_id: self.allow_receiving_object_id(),
5257            reject_mutable_random_on_entry_functions: self
5258                .reject_mutable_random_on_entry_functions(),
5259            bytecode_version: self.move_binary_format_version(),
5260            max_variants_in_enum: self.max_move_enum_variants_as_option(),
5261            additional_borrow_checks,
5262            better_loader_errors: self.better_loader_errors(),
5263            private_generics_verifier_v2: self.private_generics_verifier_v2(),
5264            sanity_check_with_regex_reference_safety: sanity_check_with_regex_reference_safety
5265                .map(|limit| limit as u128),
5266            deprecate_global_storage_ops,
5267            disable_entry_point_signature_check: self.disable_entry_point_signature_check(),
5268            disable_id_leak_verifier: self.disable_id_leak_verifier(),
5269            switch_to_regex_reference_safety: false,
5270            framework_tx_context_mut_restrictions: self.framework_tx_context_mut_restrictions(),
5271            disallow_jump_orphans: self.disallow_jump_orphans(),
5272        }
5273    }
5274
5275    pub fn binary_config(
5276        &self,
5277        override_deprecate_global_storage_ops_during_deserialization: Option<bool>,
5278    ) -> BinaryConfig {
5279        let deprecate_global_storage_ops =
5280            override_deprecate_global_storage_ops_during_deserialization
5281                .unwrap_or_else(|| self.deprecate_global_storage_ops());
5282        BinaryConfig::new(
5283            self.move_binary_format_version(),
5284            self.min_move_binary_format_version_as_option()
5285                .unwrap_or(VERSION_1),
5286            self.no_extraneous_module_bytes(),
5287            deprecate_global_storage_ops,
5288            TableConfig {
5289                module_handles: self.binary_module_handles_as_option().unwrap_or(u16::MAX),
5290                datatype_handles: self.binary_struct_handles_as_option().unwrap_or(u16::MAX),
5291                function_handles: self.binary_function_handles_as_option().unwrap_or(u16::MAX),
5292                function_instantiations: self
5293                    .binary_function_instantiations_as_option()
5294                    .unwrap_or(u16::MAX),
5295                signatures: self.binary_signatures_as_option().unwrap_or(u16::MAX),
5296                constant_pool: self.binary_constant_pool_as_option().unwrap_or(u16::MAX),
5297                identifiers: self.binary_identifiers_as_option().unwrap_or(u16::MAX),
5298                address_identifiers: self
5299                    .binary_address_identifiers_as_option()
5300                    .unwrap_or(u16::MAX),
5301                struct_defs: self.binary_struct_defs_as_option().unwrap_or(u16::MAX),
5302                struct_def_instantiations: self
5303                    .binary_struct_def_instantiations_as_option()
5304                    .unwrap_or(u16::MAX),
5305                function_defs: self.binary_function_defs_as_option().unwrap_or(u16::MAX),
5306                field_handles: self.binary_field_handles_as_option().unwrap_or(u16::MAX),
5307                field_instantiations: self
5308                    .binary_field_instantiations_as_option()
5309                    .unwrap_or(u16::MAX),
5310                friend_decls: self.binary_friend_decls_as_option().unwrap_or(u16::MAX),
5311                enum_defs: self.binary_enum_defs_as_option().unwrap_or(u16::MAX),
5312                enum_def_instantiations: self
5313                    .binary_enum_def_instantiations_as_option()
5314                    .unwrap_or(u16::MAX),
5315                variant_handles: self.binary_variant_handles_as_option().unwrap_or(u16::MAX),
5316                variant_instantiation_handles: self
5317                    .binary_variant_instantiation_handles_as_option()
5318                    .unwrap_or(u16::MAX),
5319            },
5320            self.binary_format_limits(),
5321        )
5322    }
5323
5324    pub fn binary_format_limits(
5325        &self,
5326    ) -> &'static move_binary_format::binary_config::BinaryFormatLimits {
5327        self.binary_format_limits_profile
5328            .unwrap_or(BinaryFormatLimitsProfile::LEGACY)
5329            .limits()
5330    }
5331
5332    /// Override one or more settings in the config, for testing.
5333    /// This must be called at the beginning of the test, before get_for_(min|max)_version is
5334    /// called, since those functions cache their return value.
5335    pub fn apply_overrides_for_testing(
5336        override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + Sync + 'static,
5337    ) -> OverrideGuard {
5338        let mut cur = CONFIG_OVERRIDE.lock().unwrap();
5339        assert!(cur.is_none(), "config override already present");
5340        *cur = Some(Box::new(override_fn));
5341        OverrideGuard
5342    }
5343
5344    /// Install a base override that applies before the override from `apply_overrides_for_testing`,
5345    /// so that one can replace values set here. Base overrides stack and apply in the order they
5346    /// were installed. Each is removed when its guard is dropped.
5347    #[cfg(feature = "testing")]
5348    pub fn apply_base_overrides_for_testing(
5349        override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + Sync + 'static,
5350    ) -> BaseOverrideGuard {
5351        info!("installing base ProtocolConfig override for testing");
5352        let override_fn: Arc<OverrideFn> = Arc::new(override_fn);
5353        BASE_CONFIG_OVERRIDES
5354            .lock()
5355            .unwrap()
5356            .push(override_fn.clone());
5357        BaseOverrideGuard { override_fn }
5358    }
5359
5360    fn apply_config_override(version: ProtocolVersion, mut ret: Self) -> Self {
5361        // Copy the list so that the lock is not held while the closures run.
5362        #[cfg(feature = "testing")]
5363        {
5364            let fns = BASE_CONFIG_OVERRIDES.lock().unwrap().clone();
5365            for override_fn in fns {
5366                ret = override_fn(version, ret);
5367            }
5368        }
5369        if let Some(override_fn) = CONFIG_OVERRIDE.lock().unwrap().as_ref() {
5370            warn!(
5371                "overriding ProtocolConfig settings with custom settings (you should not see this log outside of tests)"
5372            );
5373            ret = override_fn(version, ret);
5374        }
5375        ret
5376    }
5377}
5378
5379// Setters for tests.
5380// This is only needed for feature_flags. Please suffix each setter with `_for_testing`.
5381// Non-feature_flags should already have test setters defined through macros.
5382impl ProtocolConfig {
5383    // Hand-written (the field is marked #[custom_setter]) to forbid downgrades: an executor
5384    // older than the config's protocol version can't link the frameworks of later versions —
5385    // its natives tables are frozen. Upgrades are allowed for replay's executor override.
5386    pub fn set_execution_version_for_testing(&mut self, val: u64) {
5387        let current = self.execution_version.unwrap_or(0);
5388        assert!(
5389            val >= current,
5390            "cannot downgrade execution_version from {current} to {val}: running an old \
5391             executor against a newer protocol config/framework is unsupported. To test \
5392             frozen executor behavior, start from the last protocol version of that executor \
5393             instead, so genesis loads the matching framework snapshot (see \
5394             test_address_balance_gas_v3_accumulator_sign)."
5395        );
5396        self.execution_version = Some(val);
5397    }
5398
5399    // Not generated by the feature-flags derive because zklogin_circuit_mode is a u64
5400    // flag (the macro only generates setters for bool flags).
5401    pub fn set_zklogin_circuit_mode_for_testing(&mut self, val: u64) {
5402        self.feature_flags.zklogin_circuit_mode = val
5403    }
5404
5405    pub fn set_per_object_congestion_control_mode_for_testing(
5406        &mut self,
5407        val: PerObjectCongestionControlMode,
5408    ) {
5409        self.feature_flags.per_object_congestion_control_mode = val;
5410    }
5411
5412    pub fn set_consensus_choice_for_testing(&mut self, val: ConsensusChoice) {
5413        self.feature_flags.consensus_choice = val;
5414    }
5415
5416    pub fn set_consensus_network_for_testing(&mut self, val: ConsensusNetwork) {
5417        self.feature_flags.consensus_network = val;
5418    }
5419
5420    pub fn set_zklogin_max_epoch_upper_bound_delta_for_testing(&mut self, val: Option<u64>) {
5421        self.feature_flags.zklogin_max_epoch_upper_bound_delta = val
5422    }
5423
5424    pub fn set_mysticeti_num_leaders_per_round_for_testing(&mut self, val: Option<usize>) {
5425        self.feature_flags.mysticeti_num_leaders_per_round = val;
5426    }
5427
5428    pub fn disable_accumulators_for_testing(&mut self) {
5429        self.feature_flags.enable_accumulators = false;
5430        self.feature_flags.enable_address_balance_gas_payments = false;
5431    }
5432
5433    pub fn enable_coin_reservation_for_testing(&mut self) {
5434        self.feature_flags.enable_coin_reservation_obj_refs = true;
5435        self.feature_flags
5436            .convert_withdrawal_compatibility_ptb_arguments = true;
5437        // Ensure execution_version >= 4 so new_vm_enabled() returns true,
5438        // which is required for enable_coin_reservation_obj_refs() to return true.
5439        self.execution_version = Some(self.execution_version.map_or(4, |v| v.max(4)));
5440    }
5441
5442    pub fn disable_coin_reservation_for_testing(&mut self) {
5443        self.feature_flags.enable_coin_reservation_obj_refs = false;
5444        self.feature_flags
5445            .convert_withdrawal_compatibility_ptb_arguments = false;
5446    }
5447
5448    pub fn enable_address_balance_gas_payments_for_testing(&mut self) {
5449        self.feature_flags.enable_accumulators = true;
5450        self.feature_flags.allow_private_accumulator_entrypoints = true;
5451        self.feature_flags.enable_address_balance_gas_payments = true;
5452        self.feature_flags.address_balance_gas_check_rgp_at_signing = true;
5453        self.feature_flags.address_balance_gas_reject_gas_coin_arg = false;
5454        self.execution_version = Some(self.execution_version.map_or(4, |v| v.max(4)))
5455    }
5456
5457    pub fn enable_gasless_for_testing(&mut self) {
5458        self.enable_address_balance_gas_payments_for_testing();
5459        self.feature_flags.enable_gasless = true;
5460        self.feature_flags.gasless_verify_remaining_balance = true;
5461        self.gasless_max_computation_units = Some(5_000);
5462        self.gasless_allowed_token_types = Some(vec![]);
5463        self.gasless_max_tps = Some(1000);
5464        self.gasless_max_tx_size_bytes = Some(16 * 1024);
5465    }
5466
5467    pub fn disable_gasless_for_testing(&mut self) {
5468        self.feature_flags.enable_gasless = false;
5469        self.gasless_max_computation_units = None;
5470        self.gasless_allowed_token_types = None;
5471    }
5472
5473    pub fn enable_authenticated_event_streams_for_testing(&mut self) {
5474        self.feature_flags.enable_accumulators = true;
5475        self.feature_flags.enable_authenticated_event_streams = true;
5476        self.feature_flags
5477            .include_checkpoint_artifacts_digest_in_summary = true;
5478        self.feature_flags.split_checkpoints_in_consensus_handler = true;
5479    }
5480}
5481
5482type OverrideFn = dyn Fn(ProtocolVersion, ProtocolConfig) -> ProtocolConfig + Send + Sync;
5483
5484static CONFIG_OVERRIDE: Mutex<Option<Box<OverrideFn>>> = Mutex::new(None);
5485
5486#[must_use]
5487pub struct OverrideGuard;
5488
5489impl Drop for OverrideGuard {
5490    fn drop(&mut self) {
5491        info!("restoring override fn");
5492        *CONFIG_OVERRIDE.lock().unwrap() = None;
5493    }
5494}
5495
5496#[cfg(feature = "testing")]
5497static BASE_CONFIG_OVERRIDES: Mutex<Vec<Arc<OverrideFn>>> = Mutex::new(Vec::new());
5498
5499#[cfg(feature = "testing")]
5500#[must_use]
5501pub struct BaseOverrideGuard {
5502    override_fn: Arc<OverrideFn>,
5503}
5504
5505#[cfg(feature = "testing")]
5506impl Drop for BaseOverrideGuard {
5507    fn drop(&mut self) {
5508        BASE_CONFIG_OVERRIDES
5509            .lock()
5510            .unwrap()
5511            .retain(|f| !Arc::ptr_eq(f, &self.override_fn));
5512    }
5513}
5514
5515/// Defines which limit got crossed.
5516/// The value which crossed the limit and value of the limit crossed are embedded
5517#[derive(PartialEq, Eq)]
5518pub enum LimitThresholdCrossed {
5519    None,
5520    Soft(u128, u128),
5521    Hard(u128, u128),
5522}
5523
5524/// Convenience function for comparing limit ranges
5525/// V::MAX must be at >= U::MAX and T::MAX
5526pub fn check_limit_in_range<T: Into<V>, U: Into<V>, V: PartialOrd + Into<u128>>(
5527    x: T,
5528    soft_limit: U,
5529    hard_limit: V,
5530) -> LimitThresholdCrossed {
5531    let x: V = x.into();
5532    let soft_limit: V = soft_limit.into();
5533
5534    debug_assert!(soft_limit <= hard_limit);
5535
5536    // It is important to preserve this comparison order because if soft_limit == hard_limit
5537    // we want LimitThresholdCrossed::Hard
5538    if x >= hard_limit {
5539        LimitThresholdCrossed::Hard(x.into(), hard_limit.into())
5540    } else if x < soft_limit {
5541        LimitThresholdCrossed::None
5542    } else {
5543        LimitThresholdCrossed::Soft(x.into(), soft_limit.into())
5544    }
5545}
5546
5547#[macro_export]
5548macro_rules! assert_set {
5549    ($protocol_config:expr, $($flag:ident),+ $(,)?) => {{
5550        let protocol_config = $protocol_config;
5551        $(
5552            assert!(
5553                protocol_config.$flag(),
5554                "protocol config flag `{}` must be set",
5555                stringify!($flag),
5556            );
5557        )+
5558    }};
5559}
5560
5561#[macro_export]
5562macro_rules! check_limit {
5563    ($x:expr, $hard:expr) => {
5564        check_limit!($x, $hard, $hard)
5565    };
5566    ($x:expr, $soft:expr, $hard:expr) => {
5567        check_limit_in_range($x as u64, $soft, $hard)
5568    };
5569}
5570
5571/// Used to check which limits were crossed if the TX is metered (not system tx)
5572/// Args are: is_metered, value_to_check, metered_limit, unmetered_limit
5573/// metered_limit is always less than or equal to unmetered_hard_limit
5574#[macro_export]
5575macro_rules! check_limit_by_meter {
5576    ($is_metered:expr, $x:expr, $metered_limit:expr, $unmetered_hard_limit:expr, $metric:expr) => {{
5577        // If this is metered, we use the metered_limit limit as the upper bound
5578        let (h, metered_str) = if $is_metered {
5579            ($metered_limit, "metered")
5580        } else {
5581            // Unmetered gets more headroom
5582            ($unmetered_hard_limit, "unmetered")
5583        };
5584        use sui_protocol_config::check_limit_in_range;
5585        let result = check_limit_in_range($x as u64, $metered_limit, h);
5586        match result {
5587            LimitThresholdCrossed::None => {}
5588            LimitThresholdCrossed::Soft(_, _) => {
5589                $metric.with_label_values(&[metered_str, "soft"]).inc();
5590            }
5591            LimitThresholdCrossed::Hard(_, _) => {
5592                $metric.with_label_values(&[metered_str, "hard"]).inc();
5593            }
5594        };
5595        result
5596    }};
5597}
5598
5599// Amendments tables
5600
5601pub type Amendments = BTreeMap<AccountAddress, BTreeMap<AccountAddress, AccountAddress>>;
5602
5603static MAINNET_LINKAGE_AMENDMENTS: LazyLock<Arc<Amendments>> =
5604    LazyLock::new(|| parse_amendments(include_str!("mainnet_amendments.json")));
5605
5606static TESTNET_LINKAGE_AMENDMENTS: LazyLock<Arc<Amendments>> =
5607    LazyLock::new(|| parse_amendments(include_str!("testnet_amendments.json")));
5608
5609fn parse_amendments(json: &str) -> Arc<Amendments> {
5610    #[derive(serde::Deserialize)]
5611    struct AmendmentEntry {
5612        root: String,
5613        deps: Vec<DepEntry>,
5614    }
5615
5616    #[derive(serde::Deserialize)]
5617    struct DepEntry {
5618        original_id: String,
5619        version_id: String,
5620    }
5621
5622    let entries: Vec<AmendmentEntry> =
5623        serde_json::from_str(json).expect("Failed to parse amendments JSON");
5624    let mut amendments = BTreeMap::new();
5625    for entry in entries {
5626        let root_id = AccountAddress::from_hex_literal(&entry.root).unwrap();
5627        let mut dep_ids = BTreeMap::new();
5628        for dep in entry.deps {
5629            let orig_id = AccountAddress::from_hex_literal(&dep.original_id).unwrap();
5630            let upgraded_id = AccountAddress::from_hex_literal(&dep.version_id).unwrap();
5631            assert!(
5632                dep_ids.insert(orig_id, upgraded_id).is_none(),
5633                "Duplicate original ID in amendments table"
5634            );
5635        }
5636        assert!(
5637            amendments.insert(root_id, dep_ids).is_none(),
5638            "Duplicate root ID in amendments table"
5639        );
5640    }
5641    Arc::new(amendments)
5642}
5643
5644#[cfg(all(test, not(msim)))]
5645mod test {
5646    use insta::assert_yaml_snapshot;
5647
5648    use super::*;
5649
5650    #[test]
5651    fn snapshot_tests() {
5652        println!("\n============================================================================");
5653        println!("!                                                                          !");
5654        println!("! IMPORTANT: never update snapshots from this test. only add new versions! !");
5655        println!("!                                                                          !");
5656        println!("============================================================================\n");
5657        for chain_id in &[Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
5658            // make Chain::Unknown snapshots compatible with pre-chain-id snapshots so that we
5659            // don't break the release-time compatibility tests. Once Chain Id configs have been
5660            // released everywhere, we can remove this and only test Mainnet and Testnet
5661            let chain_str = match chain_id {
5662                Chain::Unknown => "".to_string(),
5663                _ => format!("{:?}_", chain_id),
5664            };
5665            for i in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
5666                let cur = ProtocolVersion::new(i);
5667                assert_yaml_snapshot!(
5668                    format!("{}version_{}", chain_str, cur.as_u64()),
5669                    ProtocolConfig::get_for_version(cur, *chain_id)
5670                );
5671            }
5672        }
5673    }
5674
5675    #[test]
5676    fn binary_format_limits_profile_matches_protocol_version() {
5677        let v141 = ProtocolConfig::get_for_version(ProtocolVersion::new(141), Chain::Unknown);
5678        assert_eq!(
5679            v141.binary_format_limits(),
5680            BinaryFormatLimitsProfile::LEGACY.limits()
5681        );
5682
5683        let v142 = ProtocolConfig::get_for_version(ProtocolVersion::new(142), Chain::Unknown);
5684        assert_eq!(
5685            v142.binary_format_limits(),
5686            BinaryFormatLimitsProfile::V1.limits()
5687        );
5688    }
5689
5690    #[test]
5691    fn test_getters() {
5692        let prot: ProtocolConfig =
5693            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5694        assert_eq!(
5695            prot.max_arguments(),
5696            prot.max_arguments_as_option().unwrap()
5697        );
5698    }
5699
5700    #[test]
5701    fn vector_bulk_native_gas_costs_start_at_version_140() {
5702        for chain in [Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
5703            let before = ProtocolConfig::get_for_version(ProtocolVersion::new(139), chain);
5704            assert_eq!(before.vector_reverse_base_cost_as_option(), None);
5705            assert_eq!(before.vector_reverse_per_elem_cost_as_option(), None);
5706            assert_eq!(before.vector_keep_range_base_cost_as_option(), None);
5707            assert_eq!(
5708                before.vector_keep_range_per_dropped_elem_cost_as_option(),
5709                None
5710            );
5711            assert_eq!(
5712                before.vector_keep_range_per_moved_elem_cost_as_option(),
5713                None
5714            );
5715            assert_eq!(before.vector_copy_range_base_cost_as_option(), None);
5716            assert_eq!(before.vector_replace_range_base_cost_as_option(), None);
5717            assert_eq!(before.vector_replace_range_per_elem_cost_as_option(), None);
5718
5719            let active = ProtocolConfig::get_for_version(ProtocolVersion::new(140), chain);
5720            assert_eq!(active.vector_reverse_base_cost_as_option(), Some(52));
5721            assert_eq!(active.vector_reverse_per_elem_cost_as_option(), Some(8));
5722            assert_eq!(active.vector_keep_range_base_cost_as_option(), Some(52));
5723            assert_eq!(
5724                active.vector_keep_range_per_dropped_elem_cost_as_option(),
5725                Some(1)
5726            );
5727            assert_eq!(
5728                active.vector_keep_range_per_moved_elem_cost_as_option(),
5729                Some(8)
5730            );
5731            assert_eq!(active.vector_copy_range_base_cost_as_option(), Some(52));
5732            assert_eq!(active.vector_replace_range_base_cost_as_option(), Some(52));
5733            assert_eq!(
5734                active.vector_replace_range_per_elem_cost_as_option(),
5735                Some(8)
5736            );
5737        }
5738    }
5739
5740    #[test]
5741    fn test_setters() {
5742        let mut prot: ProtocolConfig =
5743            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5744        prot.set_max_arguments_for_testing(123);
5745        assert_eq!(prot.max_arguments(), 123);
5746
5747        prot.set_max_arguments_from_str_for_testing("321".to_string());
5748        assert_eq!(prot.max_arguments(), 321);
5749
5750        prot.disable_max_arguments_for_testing();
5751        assert_eq!(prot.max_arguments_as_option(), None);
5752
5753        prot.set_attr_for_testing("max_arguments".to_string(), "456".to_string());
5754        assert_eq!(prot.max_arguments(), 456);
5755    }
5756
5757    #[test]
5758    fn test_execution_version_setter_allows_upgrade() {
5759        let mut prot = ProtocolConfig::get_for_max_version_UNSAFE();
5760        let current = prot.execution_version();
5761        prot.set_execution_version_for_testing(current);
5762        prot.set_execution_version_for_testing(current + 1);
5763        assert_eq!(prot.execution_version(), current + 1);
5764    }
5765
5766    #[test]
5767    #[should_panic(expected = "cannot downgrade execution_version")]
5768    fn test_execution_version_setter_panics_on_downgrade() {
5769        let mut prot = ProtocolConfig::get_for_max_version_UNSAFE();
5770        let current = prot.execution_version();
5771        prot.set_execution_version_for_testing(current - 1);
5772    }
5773
5774    #[test]
5775    fn test_feature_flag_setter_by_string() {
5776        let mut prot: ProtocolConfig =
5777            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5778        assert!(!prot.zklogin_auth());
5779        prot.set_feature_flag_for_testing("zklogin_auth".to_string(), true);
5780        assert!(prot.zklogin_auth());
5781        prot.set_feature_flag_for_testing("zklogin_auth".to_string(), false);
5782        assert!(!prot.zklogin_auth());
5783    }
5784
5785    #[test]
5786    #[should_panic(expected = "unknown feature flag")]
5787    fn test_feature_flag_setter_unknown_flag() {
5788        let mut prot: ProtocolConfig =
5789            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5790        prot.set_feature_flag_for_testing("some random string".to_string(), true);
5791    }
5792
5793    #[test]
5794    fn test_get_for_version_if_supported_applies_test_overrides() {
5795        let before =
5796            ProtocolConfig::get_for_version_if_supported(ProtocolVersion::new(1), Chain::Unknown)
5797                .unwrap();
5798
5799        assert!(!before.enable_coin_reservation_obj_refs());
5800
5801        let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut cfg| {
5802            cfg.enable_coin_reservation_for_testing();
5803            cfg
5804        });
5805
5806        let after =
5807            ProtocolConfig::get_for_version_if_supported(ProtocolVersion::new(1), Chain::Unknown)
5808                .unwrap();
5809
5810        assert!(after.enable_coin_reservation_obj_refs());
5811    }
5812
5813    #[test]
5814    #[should_panic(expected = "unsupported version")]
5815    fn max_version_test() {
5816        // When this does not panic, version higher than MAX_PROTOCOL_VERSION exists.
5817        // To fix, bump MAX_PROTOCOL_VERSION or disable this check for the version.
5818        let _ = ProtocolConfig::get_for_version_impl(
5819            ProtocolVersion::new(MAX_PROTOCOL_VERSION + 1),
5820            Chain::Unknown,
5821        );
5822    }
5823
5824    #[test]
5825    fn lookup_by_string_test() {
5826        let prot: ProtocolConfig =
5827            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5828        // Does not exist
5829        assert!(prot.lookup_attr("some random string".to_string()).is_none());
5830
5831        assert!(
5832            prot.lookup_attr("max_arguments".to_string())
5833                == Some(ProtocolConfigValue::u32(prot.max_arguments())),
5834        );
5835
5836        // We didnt have this in version 1
5837        assert!(
5838            prot.lookup_attr("max_move_identifier_len".to_string())
5839                .is_none()
5840        );
5841
5842        // But we did in version 9
5843        let prot: ProtocolConfig =
5844            ProtocolConfig::get_for_version(ProtocolVersion::new(9), Chain::Unknown);
5845        assert!(
5846            prot.lookup_attr("max_move_identifier_len".to_string())
5847                == Some(ProtocolConfigValue::u64(prot.max_move_identifier_len()))
5848        );
5849
5850        let prot: ProtocolConfig =
5851            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5852        // We didnt have this in version 1
5853        assert!(
5854            prot.attr_map()
5855                .get("max_move_identifier_len")
5856                .unwrap()
5857                .is_none()
5858        );
5859        // We had this in version 1
5860        assert!(
5861            prot.attr_map().get("max_arguments").unwrap()
5862                == &Some(ProtocolConfigValue::u32(prot.max_arguments()))
5863        );
5864
5865        // Check feature flags
5866        let prot: ProtocolConfig =
5867            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5868        // Does not exist
5869        assert!(
5870            prot.feature_flags
5871                .lookup_attr("some random string".to_owned())
5872                .is_none()
5873        );
5874        assert!(
5875            !prot
5876                .feature_flags
5877                .attr_map()
5878                .contains_key("some random string")
5879        );
5880
5881        // Was false in v1
5882        assert!(
5883            prot.feature_flags
5884                .lookup_attr("package_upgrades".to_owned())
5885                == Some(false)
5886        );
5887        assert!(
5888            prot.feature_flags
5889                .attr_map()
5890                .get("package_upgrades")
5891                .unwrap()
5892                == &false
5893        );
5894        let prot: ProtocolConfig =
5895            ProtocolConfig::get_for_version(ProtocolVersion::new(4), Chain::Unknown);
5896        // Was true from v3 and up
5897        assert!(
5898            prot.feature_flags
5899                .lookup_attr("package_upgrades".to_owned())
5900                == Some(true)
5901        );
5902        assert!(
5903            prot.feature_flags
5904                .attr_map()
5905                .get("package_upgrades")
5906                .unwrap()
5907                == &true
5908        );
5909    }
5910
5911    #[test]
5912    fn limit_range_fn_test() {
5913        let low = 100u32;
5914        let high = 10000u64;
5915
5916        assert!(check_limit!(1u8, low, high) == LimitThresholdCrossed::None);
5917        assert!(matches!(
5918            check_limit!(255u16, low, high),
5919            LimitThresholdCrossed::Soft(255u128, 100)
5920        ));
5921        // This wont compile because lossy
5922        //assert!(check_limit!(100000000u128, low, high) == LimitThresholdCrossed::None);
5923        // This wont compile because lossy
5924        //assert!(check_limit!(100000000usize, low, high) == LimitThresholdCrossed::None);
5925
5926        assert!(matches!(
5927            check_limit!(2550000u64, low, high),
5928            LimitThresholdCrossed::Hard(2550000, 10000)
5929        ));
5930
5931        assert!(matches!(
5932            check_limit!(2550000u64, high, high),
5933            LimitThresholdCrossed::Hard(2550000, 10000)
5934        ));
5935
5936        assert!(matches!(
5937            check_limit!(1u8, high),
5938            LimitThresholdCrossed::None
5939        ));
5940
5941        assert!(check_limit!(255u16, high) == LimitThresholdCrossed::None);
5942
5943        assert!(matches!(
5944            check_limit!(2550000u64, high),
5945            LimitThresholdCrossed::Hard(2550000, 10000)
5946        ));
5947    }
5948
5949    #[test]
5950    fn linkage_amendments_load() {
5951        let mainnet = LazyLock::force(&MAINNET_LINKAGE_AMENDMENTS);
5952        let testnet = LazyLock::force(&TESTNET_LINKAGE_AMENDMENTS);
5953        assert!(!mainnet.is_empty(), "mainnet amendments must not be empty");
5954        assert!(!testnet.is_empty(), "testnet amendments must not be empty");
5955    }
5956
5957    #[test]
5958    fn render_scalar_fields_use_precision_safe_encoding() {
5959        use mysten_common::rpc_format::Unmetered;
5960
5961        let config = ProtocolConfig::get_for_max_version_UNSAFE();
5962        let rendered = config
5963            .render::<serde_json::Value>(&mut Unmetered)
5964            .expect("render should succeed");
5965
5966        let max_args = rendered
5967            .get("max_arguments")
5968            .expect("max_arguments set at max version");
5969        assert!(
5970            max_args.is_number(),
5971            "u32 should render as number, got {max_args:?}",
5972        );
5973
5974        let max_tx_size = rendered
5975            .get("max_tx_size_bytes")
5976            .expect("max_tx_size_bytes set at max version");
5977        assert!(
5978            max_tx_size.is_string(),
5979            "u64 should render as string, got {max_tx_size:?}",
5980        );
5981    }
5982
5983    #[test]
5984    fn render_includes_non_scalar_gasless_allowlist_as_json() {
5985        use mysten_common::rpc_format::Unmetered;
5986        use serde_json::json;
5987
5988        let mut config = ProtocolConfig::get_for_max_version_UNSAFE();
5989        config.set_gasless_allowed_token_types_for_testing(vec![
5990            ("0xa::usdc::USDC".to_string(), 10_000),
5991            ("0xb::usdt::USDT".to_string(), 0),
5992        ]);
5993
5994        let rendered = config
5995            .render::<serde_json::Value>(&mut Unmetered)
5996            .expect("render should succeed under Unmetered budget");
5997        let allowlist = rendered
5998            .get("gasless_allowed_token_types")
5999            .expect("entry should be present after the testing setter");
6000
6001        // u64 values render as strings to preserve JS precision; the tuple becomes a 2-element
6002        // JSON array.
6003        assert_eq!(
6004            allowlist,
6005            &json!([["0xa::usdc::USDC", "10000"], ["0xb::usdt::USDT", "0"],]),
6006        );
6007    }
6008
6009    #[test]
6010    fn render_targets_prost_value_for_grpc() {
6011        use mysten_common::rpc_format::Unmetered;
6012        use prost_types::value::Kind;
6013
6014        let mut config = ProtocolConfig::get_for_max_version_UNSAFE();
6015        config.set_gasless_allowed_token_types_for_testing(vec![(
6016            "0xa::usdc::USDC".to_string(),
6017            10_000,
6018        )]);
6019
6020        let rendered = config
6021            .render::<prost_types::Value>(&mut Unmetered)
6022            .expect("render to prost Value should succeed");
6023        let allowlist = rendered
6024            .get("gasless_allowed_token_types")
6025            .expect("entry should be present after the testing setter");
6026
6027        // Outer ListValue with one inner ListValue carrying [coin_type_string, amount_string].
6028        let Some(Kind::ListValue(outer)) = &allowlist.kind else {
6029            panic!(
6030                "expected ListValue at the top level, got {:?}",
6031                allowlist.kind
6032            );
6033        };
6034        assert_eq!(outer.values.len(), 1, "one allowlisted entry");
6035        let Some(Kind::ListValue(entry)) = &outer.values[0].kind else {
6036            panic!("expected each entry to be a ListValue");
6037        };
6038        assert_eq!(entry.values.len(), 2, "entry has (coin_type, amount)");
6039
6040        let Some(Kind::StringValue(coin_type)) = &entry.values[0].kind else {
6041            panic!("expected coin_type as StringValue");
6042        };
6043        assert_eq!(coin_type, "0xa::usdc::USDC");
6044
6045        // u64 amount renders as a string, not a NumberValue — this is the precision-safe path.
6046        let Some(Kind::StringValue(amount)) = &entry.values[1].kind else {
6047            panic!(
6048                "expected minimum_transfer_amount as StringValue (precision-safe u64); got {:?}",
6049                entry.values[1].kind,
6050            );
6051        };
6052        assert_eq!(amount, "10000");
6053    }
6054
6055    #[test]
6056    fn render_emits_null_for_unset_protocol_versions() {
6057        use mysten_common::rpc_format::Unmetered;
6058
6059        let config = ProtocolConfig::get_for_version(1.into(), Chain::Unknown);
6060        let rendered = config
6061            .render::<serde_json::Value>(&mut Unmetered)
6062            .expect("render should succeed");
6063        // The gasless allowlist key is present in every version's keyset, but renders as JSON
6064        // `null` for versions that predate the feature. This keeps the keyset stable across
6065        // protocol versions so clients can distinguish "unknown key" from "present but unset".
6066        let entry = rendered
6067            .get("gasless_allowed_token_types")
6068            .expect("key should be present for every protocol version");
6069        assert!(
6070            entry.is_null(),
6071            "value should be null for pre-feature protocol version, got {entry:?}",
6072        );
6073    }
6074}