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