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