Skip to main content

sui_protocol_config/
lib.rs

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