Skip to main content

sui_protocol_config/
lib.rs

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