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