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