Skip to main content

sui_protocol_config/
lib.rs

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