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