near-primitives-core 0.37.3

This crate provides the core set of primitives used by other nearcore crates including near-primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use crate::types::ProtocolVersion;

/// New Protocol features should go here. Features are guarded by their corresponding feature flag.
/// For example, if we have `ProtocolFeature::EVM` and a corresponding feature flag `evm`, it will look
/// like
///
/// #[cfg(feature = "protocol_feature_evm")]
/// EVM code
///
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
pub enum ProtocolFeature {
    #[deprecated]
    _DeprecatedImplicitAccountCreation,
    #[deprecated]
    _DeprecatedRectifyInflation,
    /// Add `AccessKey` nonce range by setting nonce to `(block_height - 1) * 1e6`, see
    /// <https://github.com/near/nearcore/issues/3779>.
    #[deprecated]
    _DeprecatedAccessKeyNonceRange,
    /// Don't process any receipts for shard when chunk is not present.
    /// Always use gas price computed in the previous block.
    #[deprecated]
    _DeprecatedFixApplyChunks,
    #[deprecated]
    _DeprecatedLowerStorageCost,
    #[deprecated]
    _DeprecatedDeleteActionRestriction,
    /// Add versions to `Account` data structure
    #[deprecated]
    _DeprecatedAccountVersions,
    #[deprecated]
    _DeprecatedTransactionSizeLimit,
    /// Fix a bug in `storage_usage` for account caused by #3824
    #[deprecated]
    _DeprecatedFixStorageUsage,
    /// Cap maximum gas price to 2,000,000,000 yoctoNEAR
    #[deprecated]
    _DeprecatedCapMaxGasPrice,
    #[deprecated]
    _DeprecatedCountRefundReceiptsInGasLimit,
    /// Add `ripemd60` and `ecrecover` host function
    #[deprecated]
    _DeprecatedMathExtension,
    /// Restore receipts that were previously stuck because of
    /// <https://github.com/near/nearcore/pull/4228>.
    #[deprecated]
    _DeprecatedRestoreReceiptsAfterFixApplyChunks,
    /// Minimum protocol version for NEP-92
    #[deprecated]
    _DeprecatedMinProtocolVersionNep92,
    /// Minimum protocol version for NEP-92 fix
    #[deprecated]
    _DeprecatedMinProtocolVersionNep92Fix,
    /// Creates a unique random seed to be provided to `VMContext` from a given `action_hash` and a given `random_seed`
    #[deprecated]
    _DeprecatedCorrectRandomValue,
    /// The protocol version that enables reward on mainnet
    #[deprecated]
    _DeprecatedEnableInflation,
    /// Fix upgrade to use the latest voted protocol version instead of the current epoch protocol
    /// version when there is no new change in protocol version
    #[deprecated]
    _DeprecatedUpgradabilityFix,
    /// Updates the way receipt ID, data ID and random seeds are constructed
    #[deprecated]
    _DeprecatedCreateHash,
    /// Fix the storage usage of the delete key action
    #[deprecated]
    _DeprecatedDeleteKeyStorageUsage,
    /// Upgrade for shard chunk header
    #[deprecated]
    _DeprecatedShardChunkHeaderUpgrade,
    /// Updates the way receipt ID is constructed to use current block hash instead of last block hash
    #[deprecated]
    _DeprecatedCreateReceiptIdSwitchToCurrentBlock,
    /// Pessimistic gas price estimation uses a fixed value of `minimum_new_receipt_gas` to stop being
    /// tied to the function call base cost
    #[deprecated]
    _DeprecatedFixedMinimumNewReceiptGas,
    /// This feature switch our WASM engine implementation from wasmer 0.* to
    /// wasmer 2.*, bringing better performance and reliability.
    ///
    /// The implementations should be sufficiently similar for this to not be a
    /// protocol upgrade, but we conservatively do a protocol upgrade to be on
    /// the safe side.
    ///
    /// Although wasmer2 is faster, we don't change fees with this protocol
    /// version -- we can safely do that in a separate step.
    #[deprecated]
    _DeprecatedWasmer2,
    #[deprecated]
    _DeprecatedSimpleNightshade,
    #[deprecated]
    _DeprecatedLowerDataReceiptAndEcrecoverBaseCost,
    /// Lowers the cost of wasm instruction due to switch to wasmer2.
    #[deprecated]
    _DeprecatedLowerRegularOpCost,
    /// Lowers the cost of wasm instruction due to switch to faster,
    /// compiler-intrinsics based gas counter.
    #[deprecated]
    _DeprecatedLowerRegularOpCost2,
    /// Limit number of wasm functions in one contract. See
    /// <https://github.com/near/nearcore/pull/4954> for more details.
    #[deprecated]
    _DeprecatedLimitContractFunctionsNumber,
    #[deprecated]
    _DeprecatedBlockHeaderV3,
    /// Changes how we select validators for epoch and how we select validators
    /// within epoch.  See <https://github.com/near/NEPs/pull/167> for general
    /// description, note that we would not introduce chunk-only validators with
    /// this feature
    #[deprecated]
    _DeprecatedAliasValidatorSelectionAlgorithm,
    /// Make block producers produce chunks for the same block they would later produce to avoid
    /// network delays
    #[deprecated]
    _DeprecatedSynchronizeBlockChunkProduction,
    /// Change the algorithm to count WASM stack usage to avoid under counting in
    /// some cases.
    #[deprecated]
    _DeprecatedCorrectStackLimit,
    /// Add `AccessKey` nonce range for implicit accounts, as in `AccessKeyNonceRange` feature.
    #[deprecated]
    _DeprecatedAccessKeyNonceForImplicitAccounts,
    /// Increase cost per deployed code byte to cover for the compilation steps
    /// that a deployment triggers. Only affects the action execution cost.
    #[deprecated]
    _DeprecatedIncreaseDeploymentCost,
    #[deprecated]
    _DeprecatedFunctionCallWeight,
    /// This feature enforces a global limit on the function local declarations in a WebAssembly
    /// contract. See <...> for more information.
    #[deprecated]
    _DeprecatedLimitContractLocals,
    /// Ensure caching all nodes in the chunk for which touching trie node cost was charged. Charge for each such node
    /// only once per chunk at the first access time.
    #[deprecated]
    _DeprecatedChunkNodesCache,
    /// Lower `max_length_storage_key` limit, which itself limits trie node sizes.
    #[deprecated]
    _DeprecatedLowerStorageKeyLimit,
    // alt_bn128_g1_multiexp, alt_bn128_g1_sum, alt_bn128_pairing_check host functions
    #[deprecated]
    _DeprecatedAltBn128,
    #[deprecated]
    _DeprecatedChunkOnlyProducers,
    /// Ensure the total stake of validators that are kicked out does not exceed a percentage of total stakes
    #[deprecated]
    _DeprecatedMaxKickoutStake,
    /// Validate account id for function call access keys.
    #[deprecated]
    _DeprecatedAccountIdInFunctionCallPermission,
    /// Zero Balance Account NEP 448: <https://github.com/near/NEPs/pull/448>
    #[deprecated]
    _DeprecatedZeroBalanceAccount,
    /// Execute a set of actions on behalf of another account.
    ///
    /// Meta Transaction NEP-366: <https://github.com/near/NEPs/blob/master/neps/nep-0366.md>
    #[deprecated]
    _DeprecatedDelegateAction,
    #[deprecated]
    _DeprecatedEd25519Verify,
    /// Decouple compute and gas costs of operations to safely limit the compute time it takes to
    /// process the chunk.
    ///
    /// Compute Costs NEP-455: <https://github.com/near/NEPs/blob/master/neps/nep-0455.md>
    #[deprecated]
    _DeprecatedComputeCosts,
    /// Decrease the cost of function call action. Only affects the execution cost.
    #[deprecated]
    _DeprecatedDecreaseFunctionCallBaseCost,
    /// Enable flat storage for reads, reducing number of DB accesses from `2 * key.len()` in
    /// the worst case to 2.
    ///
    /// Flat Storage NEP-399: <https://github.com/near/NEPs/blob/master/neps/nep-0399.md>
    #[deprecated]
    _DeprecatedFlatStorageReads,
    /// Enables preparation V2. Note that this setting is not supported in production settings
    /// without NearVmRuntime enabled alongside it, as the VM runner would be too slow.
    #[deprecated]
    _DeprecatedPreparationV2,
    /// Enables Near-Vm. Note that this setting is not at all supported without PreparationV2,
    /// as it hardcodes preparation v2 code into the generated assembly.
    #[deprecated]
    _DeprecatedNearVmRuntime,
    #[deprecated]
    _DeprecatedBlockHeaderV4,
    /// Resharding V2. A new implementation for resharding and a new shard
    /// layout for the production networks.
    #[deprecated]
    _DeprecatedSimpleNightshadeV2,
    /// Built on top of Resharding V2. Changes shard layout to V3 to split shard 2 into two parts.
    #[deprecated]
    _DeprecatedSimpleNightshadeV3,
    /// In case not all validator seats are occupied our algorithm provide incorrect minimal seat
    /// price - it reports as alpha * sum_stake instead of alpha * sum_stake / (1 - alpha), where
    /// alpha is min stake ratio
    #[deprecated]
    _DeprecatedFixStakingThreshold,
    /// In case not all validator seats are occupied, the minimum seat price of a chunk producer
    /// used to depend on the number of existing shards, which is no longer the case.
    #[deprecated]
    _DeprecatedFixChunkProducerStakingThreshold,
    /// Charge for contract loading before it happens.
    FixContractLoadingCost,
    /// Enables rejection of blocks with outdated protocol versions.
    #[deprecated]
    _DeprecatedRejectBlocksWithOutdatedProtocolVersions,
    // NEP: https://github.com/near/NEPs/pull/488
    #[deprecated]
    _DeprecatedBLS12381,
    #[deprecated]
    _DeprecatedRestrictTla,
    /// Increases the number of chunk producers.
    #[deprecated]
    _DeprecatedTestnetFewerBlockProducers,
    /// Enables stateless validation which is introduced in <https://github.com/near/NEPs/pull/509>
    /// LowerValidatorKickoutPercentForDebugging: lower block and chunk validator kickout percent from 90 to 50.
    /// SingleShardTracking: single shard tracking for stateless validation.
    /// StateWitnessSizeLimit: state witness size limits.
    /// PerReceiptHardStorageProofLimit: limit the size of storage proof generated by a single receipt.
    /// WitnessTransactionLimits: size limits for transactions included in a ChunkStateWitness.
    /// NoChunkOnlyProducers: no chunk-only producers in stateless validation.
    #[deprecated]
    _DeprecatedStatelessValidation,
    #[deprecated]
    _DeprecatedEthImplicitAccounts,
    /// Enables yield execution which is introduced in <https://github.com/near/NEPs/pull/519>
    #[deprecated]
    _DeprecatedYieldExecution,
    /// Bring minimum required validator stake effectively to ~10K NEAR as of 2024-08-15.
    /// Fixes increase to 100K NEAR in the previous protocol version.
    /// See #11953 for more details.
    #[deprecated]
    _DeprecatedFixMinStakeRatio,
    /// Increases main_storage_proof_size_soft_limit parameter from 3mb to 4mb
    #[deprecated]
    _DeprecatedIncreaseStorageProofSizeSoftLimit,

    // Shuffle shard assignments for chunk producers at every epoch.
    ShuffleShardAssignments,
    /// Cross-shard congestion control according to <https://github.com/near/NEPs/pull/539>.
    #[deprecated]
    _DeprecatedCongestionControl,
    /// Remove account with long storage key.
    #[deprecated]
    _DeprecatedRemoveAccountWithLongStorageKey,
    /// Change the structure of ChunkEndorsement to have (shard_id, epoch_id, height_created)
    /// instead of chunk_hash
    #[deprecated]
    _DeprecatedChunkEndorsementV2,
    // Include a bitmap of endorsements from chunk validator in the block header
    // in order to calculate the rewards and kickouts for the chunk validators.
    // This feature introduces BlockHeaderV5.
    #[deprecated]
    _DeprecatedChunkEndorsementsInBlockHeader,
    /// Store receipts in State in the StateStoredReceipt format.
    #[deprecated]
    _DeprecatedStateStoredReceipt,
    /// Resharding V3 - Adding "game.hot.tg-0" boundary.
    #[deprecated]
    _DeprecatedSimpleNightshadeV4,
    /// Resharding V3 - Adding "earn.kaiching" boundary.
    #[deprecated]
    _DeprecatedSimpleNightshadeV5,
    /// Resharding V3 - Adding "650" boundary.
    #[deprecated]
    _DeprecatedSimpleNightshadeV6,
    /// Exclude contract code from the chunk state witness and distribute it to chunk validators separately.
    #[deprecated]
    _DeprecatedExcludeContractCodeFromStateWitness,
    /// A scheduler which limits bandwidth for sending receipts between shards.
    #[deprecated]
    _DeprecatedBandwidthScheduler,
    /// Indicates that the "sync_hash" used to identify the point in the chain to sync state to
    /// should no longer be the first block of the epoch, but a couple blocks after that in order
    /// to sync the current epoch's state. This is not strictly a protocol feature, but is included
    /// here to coordinate among nodes
    _DeprecatedCurrentEpochStateSync,
    /// Relaxed validation of transactions included in a chunk.
    ///
    /// Chunks no longer become entirely invalid in case invalid transactions are included in the
    /// chunk. Instead the transactions are discarded during their conversion to receipts.
    ///
    /// support for code that does not do relaxed chunk validation has now been removed.
    #[deprecated(
        note = "Was used for protocol versions without relaxed chunk validation which is not supported anymore."
    )]
    _DeprecatedRelaxedChunkValidation,
    /// This enables us to remove the expensive check_balance call from the
    /// runtime.
    ///
    /// Support for code that does check balances has now been removed.
    #[deprecated(
        note = "Was used for protocol versions where we checked balances which is not supported anymore."
    )]
    _DeprecatedRemoveCheckBalance,
    /// Exclude existing contract code in deploy-contract and delete-account actions from the chunk state witness.
    /// Instead of sending code in the witness, the code checks the code-size using the internal trie nodes.
    ExcludeExistingCodeFromWitnessForCodeLen,
    /// Use the block height instead of the block hash to calculate the receipt ID.
    #[deprecated]
    _DeprecatedBlockHeightForReceiptId,
    /// Enable optimistic block production.
    #[deprecated]
    _DeprecatedProduceOptimisticBlock,
    #[deprecated]
    _DeprecatedGlobalContracts,
    /// NEP: https://github.com/near/NEPs/pull/536
    ///
    /// Reduce the number of gas refund receipts by charging the current gas
    /// price rather than a pessimistic gas price. Also, introduce a new fee of
    /// 5% for gas refunds and charge the signer this fee for gas refund
    /// receipts.
    #[deprecated]
    _DeprecatedReducedGasRefunds,
    /// Move from ChunkStateWitness being a single struct to a versioned enum.
    #[deprecated]
    _DeprecatedVersionedStateWitness,
    /// Increase max_congestion_missed_chunks from 5 to 125.
    /// At 125 missing chunks shard will be fully congested.
    /// At 100 missing chunks shard will be 80% congested, and transactions
    /// targeting it will be rejected as per reject_tx_congestion_threshold
    /// config.
    ///
    /// It improves UX during long ranges of missing chunks, as transactions
    /// are much less likely to get rejected with ShardStuck error.
    #[deprecated]
    _DeprecatedIncreaseMaxCongestionMissedChunks,

    Wasmtime,
    #[deprecated]
    _DeprecatedSaturatingFloatToInt,
    #[deprecated]
    _DeprecatedChunkPartChecks,
    #[deprecated]
    _DeprecatedStatePartsCompression,
    /// NEP: https://github.com/near/NEPs/pull/616
    #[deprecated]
    _DeprecatedDeterministicAccountIds,
    InvalidTxGenerateOutcomes,
    DynamicResharding,
    GasKeys,
    /// Meta transactions with gas key support via `Action::DelegateV2`.
    DelegateV2,
    /// Fix access key allowance mutation in verify_and_charge_tx_ephemeral.
    /// Previously, the allowance was decremented in-place before later checks
    /// (storage stake, function call permission) that could return an error,
    /// violating the documented contract of no mutation on error.
    FixAccessKeyAllowanceCharging,
    /// Fix missing early return on DepositWithFunctionCall error path in
    /// validate_delegate_action_key. Previously the error could be
    /// overwritten by a subsequent receiver_id or method_name check.
    FixDelegateActionDepositWithFunctionCallError,
    Spice,
    ContinuousEpochSync,
    /// Fix `action_delete_account` not subtracting the global contract
    /// identifier storage usage. Previously only local contract code was
    /// subtracted, overstating storage usage for accounts with global
    /// contracts and making them marginally harder to delete.
    FixDeleteAccountGlobalContractStorageUsage,
    /// Skip transactions whose hash already appeared earlier in the same chunk.
    /// A transaction hash is also its outcome id, and outcomes are committed
    /// (via the chunk outcome root) keyed by that id. Including a transaction
    /// twice would otherwise commit two conflicting outcomes (a success and an
    /// InvalidNonce failure) under one id.
    UniqueChunkTransactions,
    /// Apply PromiseYield receipts immediately after emitting them. Allows to perform the resume
    /// sooner, without waiting for the PromiseYield receipt to pass through outgoing receipts.
    #[deprecated]
    _DeprecatedInstantPromiseYield,
    /// Improve functionality of Yield/Resume. Keep the current status of yielded receipt in the
    /// trie state. Allows to call yield and resume in two actions within the same transaction.
    /// Keeping the status in the state could allow to query it from contracts.
    #[deprecated]
    _DeprecatedYieldResumeImprovements,
    /// Includes tokens burnt as part of global contract deploys into corresponding
    /// execution outcome's `tokens_burnt`.
    IncludeDeployGlobalContractOutcomeBurntStorage,
    /// Nonce-based idempotency for global contract distribution receipts. Each
    /// distribution carries an auto-incremented nonce. Any distribution receipt
    /// with a nonce less than the one already stored will be dropped. This
    /// prevents race conditions in the case of multiple distribution attempts
    /// for the same contract.
    GlobalContractDistributionNonce,
    /// Use global contract for ETH implicit accounts instead of embedded WASM.
    EthImplicitGlobalContract,
    /// Process action receipts containing a single DeleteAccount action as
    /// instant receipts, executing them immediately after the receipt that
    /// produced them rather than sending them as outgoing receipts.
    #[deprecated]
    _DeprecatedInstantDeleteAccount,
    /// Opt-in strict nonce mode for transactions. When enabled, TransactionV1
    /// can carry `NonceMode::Strict` which requires `tx_nonce == ak_nonce + 1`
    /// (sequential ordering). Transactions with a nonce gap are held in the
    /// pool rather than discarded.
    StrictNonce,
    /// Pre-compute and persist chunk producer assignments in `DBCol::ChunkProducers`
    /// during header sync and block processing. Foundation for early chunk producer
    /// kickout without epoch manager recomputation.
    EarlyKickout,
    /// Extend the existing sticky chunk-producer-to-shard assignment to
    /// resharding boundaries. Previously stickiness was keyed by
    /// `ShardIndex`, which is unstable across a shard layout change; switch
    /// to keying by `ShardId`, and when a shard splits distribute the
    /// parent's chunk producers across its child shards using greedy
    /// stake-balanced bin-packing. Reduces unnecessary state sync after
    /// resharding.
    StickyReshardingValidatorAssignment,
    /// Add FIPS 204 ML-DSA-65 (post-quantum) as a third transaction signature
    /// scheme alongside ed25519 and secp256k1. Pre-feature blocks reject any
    /// transaction or `AddKey` action carrying an ML-DSA-65 key/signature, so
    /// post-feature there is no question of grandfathered keys.
    PostQuantumSignatures,
    /// Allow creating `DeterministicStateInitAction` from a delegated action by
    /// fixing the receiver id check.
    FixDelegatedDeterministicStateInit,
    /// Emit `ExecutionMetadata::V4` from chunk producers. V4 carries a
    /// per-action `Vec<AccountContract>`: one entry per action in the
    /// receipt, recording the contract attached to the receiver account
    /// immediately before that action ran. Captured unconditionally for
    /// every action kind (not just `FunctionCall`), so consumers can see
    /// what code an account had even on receipts that did not invoke a
    /// contract. `AccountContract::None` is emitted when the account has
    /// no contract deployed, when it did not yet exist (e.g. the
    /// `CreateAccount` slot that materialized it), or for unexecuted
    /// trailing slots padded after a mid-receipt failure. Order matches
    /// the receipt's `actions` vector. This is relevant when the receiver
    /// account and the contract source diverge — e.g. global contracts
    /// and `UseGlobalContract` flows. Wire format changes (new borsh
    /// discriminant), so the cutover must be coordinated across the
    /// network.
    ExecutionMetadataV4,
    /// New host functions `promise_yield_create_with_id` and `promise_yield_resume_with_yield_id`
    /// that allow contracts to provide a custom yield ID for yield/resume.
    YieldWithId,
    /// Increase account creation cost
    AccountCostIncrease,
    /// Recompute `block_ordinal` and `epoch_sync_data_hash` against local chain
    /// state when validating received block headers.
    ValidateBlockOrdinalAndEpochSyncDataHash,
    /// Authenticate `ContractCodeResponse` messages with a chunk-producer
    /// signature, matching the signed-message pattern already used by
    /// `ChunkContractAccesses` and `ContractCodeRequest`. Senders emit
    /// `ContractCodeResponseV2` (with a signed inner payload); receivers
    /// require a verifiable signature before processing the response.
    SignedContractCodeResponse,
    ClampOutgoingGasAdmission,
    EnforcePerReceiptStorageProofLimit,
}

impl ProtocolFeature {
    // The constructor must initialize all fields of the struct but some fields
    // are deprecated.  So unfortunately, we need this attribute here.  A better
    // fix is being discussed on
    // https://github.com/rust-lang/rust/issues/102777.
    #[allow(deprecated)]
    pub const fn protocol_version(self) -> ProtocolVersion {
        match self {
            // Stable features
            ProtocolFeature::_DeprecatedMinProtocolVersionNep92 => 31,
            ProtocolFeature::_DeprecatedMinProtocolVersionNep92Fix => 32,
            ProtocolFeature::_DeprecatedCorrectRandomValue => 33,
            ProtocolFeature::_DeprecatedImplicitAccountCreation => 35,
            ProtocolFeature::_DeprecatedEnableInflation => 36,
            ProtocolFeature::_DeprecatedUpgradabilityFix => 37,
            ProtocolFeature::_DeprecatedCreateHash => 38,
            ProtocolFeature::_DeprecatedDeleteKeyStorageUsage => 40,
            ProtocolFeature::_DeprecatedShardChunkHeaderUpgrade => 41,
            ProtocolFeature::_DeprecatedCreateReceiptIdSwitchToCurrentBlock
            | ProtocolFeature::_DeprecatedLowerStorageCost => 42,
            ProtocolFeature::_DeprecatedDeleteActionRestriction => 43,
            ProtocolFeature::_DeprecatedFixApplyChunks => 44,
            ProtocolFeature::_DeprecatedRectifyInflation
            | ProtocolFeature::_DeprecatedAccessKeyNonceRange => 45,
            ProtocolFeature::_DeprecatedAccountVersions
            | ProtocolFeature::_DeprecatedTransactionSizeLimit
            | ProtocolFeature::_DeprecatedFixStorageUsage
            | ProtocolFeature::_DeprecatedCapMaxGasPrice
            | ProtocolFeature::_DeprecatedCountRefundReceiptsInGasLimit
            | ProtocolFeature::_DeprecatedMathExtension => 46,
            ProtocolFeature::_DeprecatedRestoreReceiptsAfterFixApplyChunks => 47,
            ProtocolFeature::_DeprecatedWasmer2
            | ProtocolFeature::_DeprecatedLowerDataReceiptAndEcrecoverBaseCost
            | ProtocolFeature::_DeprecatedLowerRegularOpCost
            | ProtocolFeature::_DeprecatedSimpleNightshade => 48,
            ProtocolFeature::_DeprecatedLowerRegularOpCost2
            | ProtocolFeature::_DeprecatedLimitContractFunctionsNumber
            | ProtocolFeature::_DeprecatedBlockHeaderV3
            | ProtocolFeature::_DeprecatedAliasValidatorSelectionAlgorithm => 49,
            ProtocolFeature::_DeprecatedSynchronizeBlockChunkProduction
            | ProtocolFeature::_DeprecatedCorrectStackLimit => 50,
            ProtocolFeature::_DeprecatedAccessKeyNonceForImplicitAccounts => 51,
            ProtocolFeature::_DeprecatedIncreaseDeploymentCost
            | ProtocolFeature::_DeprecatedFunctionCallWeight
            | ProtocolFeature::_DeprecatedLimitContractLocals
            | ProtocolFeature::_DeprecatedChunkNodesCache
            | ProtocolFeature::_DeprecatedLowerStorageKeyLimit => 53,
            ProtocolFeature::_DeprecatedAltBn128 => 55,
            ProtocolFeature::_DeprecatedChunkOnlyProducers
            | ProtocolFeature::_DeprecatedMaxKickoutStake => 56,
            ProtocolFeature::_DeprecatedAccountIdInFunctionCallPermission => 57,
            ProtocolFeature::_DeprecatedEd25519Verify
            | ProtocolFeature::_DeprecatedZeroBalanceAccount
            | ProtocolFeature::_DeprecatedDelegateAction => 59,
            ProtocolFeature::_DeprecatedComputeCosts
            | ProtocolFeature::_DeprecatedFlatStorageReads => 61,
            ProtocolFeature::_DeprecatedPreparationV2
            | ProtocolFeature::_DeprecatedNearVmRuntime => 62,
            ProtocolFeature::_DeprecatedBlockHeaderV4 => 63,
            ProtocolFeature::_DeprecatedRestrictTla
            | ProtocolFeature::_DeprecatedTestnetFewerBlockProducers
            | ProtocolFeature::_DeprecatedSimpleNightshadeV2 => 64,
            ProtocolFeature::_DeprecatedSimpleNightshadeV3 => 65,
            ProtocolFeature::_DeprecatedDecreaseFunctionCallBaseCost
            | ProtocolFeature::_DeprecatedFixedMinimumNewReceiptGas => 66,
            ProtocolFeature::_DeprecatedYieldExecution => 67,
            ProtocolFeature::_DeprecatedCongestionControl
            | ProtocolFeature::_DeprecatedRemoveAccountWithLongStorageKey => 68,
            ProtocolFeature::_DeprecatedStatelessValidation => 69,
            ProtocolFeature::_DeprecatedBLS12381
            | ProtocolFeature::_DeprecatedEthImplicitAccounts => 70,
            ProtocolFeature::_DeprecatedFixMinStakeRatio => 71,
            ProtocolFeature::_DeprecatedIncreaseStorageProofSizeSoftLimit
            | ProtocolFeature::_DeprecatedChunkEndorsementV2
            | ProtocolFeature::_DeprecatedChunkEndorsementsInBlockHeader
            | ProtocolFeature::_DeprecatedStateStoredReceipt => 72,
            ProtocolFeature::_DeprecatedExcludeContractCodeFromStateWitness => 73,
            ProtocolFeature::_DeprecatedFixStakingThreshold
            | ProtocolFeature::_DeprecatedRejectBlocksWithOutdatedProtocolVersions
            | ProtocolFeature::_DeprecatedFixChunkProducerStakingThreshold
            | ProtocolFeature::_DeprecatedRelaxedChunkValidation
            | ProtocolFeature::_DeprecatedRemoveCheckBalance
            | ProtocolFeature::_DeprecatedBandwidthScheduler
            | ProtocolFeature::_DeprecatedCurrentEpochStateSync => 74,
            ProtocolFeature::_DeprecatedSimpleNightshadeV4 => 75,
            ProtocolFeature::_DeprecatedSimpleNightshadeV5 => 76,
            ProtocolFeature::_DeprecatedGlobalContracts
            | ProtocolFeature::_DeprecatedBlockHeightForReceiptId
            | ProtocolFeature::_DeprecatedProduceOptimisticBlock => 77,
            ProtocolFeature::_DeprecatedSimpleNightshadeV6
            | ProtocolFeature::_DeprecatedVersionedStateWitness
            | ProtocolFeature::_DeprecatedChunkPartChecks
            | ProtocolFeature::_DeprecatedSaturatingFloatToInt
            | ProtocolFeature::_DeprecatedReducedGasRefunds => 78,
            ProtocolFeature::_DeprecatedIncreaseMaxCongestionMissedChunks => 79,
            ProtocolFeature::_DeprecatedStatePartsCompression
            | ProtocolFeature::_DeprecatedDeterministicAccountIds => 82,
            ProtocolFeature::InvalidTxGenerateOutcomes
            | ProtocolFeature::ExcludeExistingCodeFromWitnessForCodeLen
            | ProtocolFeature::FixAccessKeyAllowanceCharging
            | ProtocolFeature::IncludeDeployGlobalContractOutcomeBurntStorage
            | ProtocolFeature::GlobalContractDistributionNonce
            | ProtocolFeature::_DeprecatedInstantPromiseYield
            | ProtocolFeature::_DeprecatedYieldResumeImprovements
            | ProtocolFeature::EthImplicitGlobalContract
            | ProtocolFeature::_DeprecatedInstantDeleteAccount => 83,
            ProtocolFeature::Wasmtime => 84,
            ProtocolFeature::FixDelegateActionDepositWithFunctionCallError
            | ProtocolFeature::FixDeleteAccountGlobalContractStorageUsage
            | ProtocolFeature::FixDelegatedDeterministicStateInit
            | ProtocolFeature::GasKeys
            | ProtocolFeature::ContinuousEpochSync
            | ProtocolFeature::DynamicResharding
            | ProtocolFeature::StickyReshardingValidatorAssignment
            | ProtocolFeature::StrictNonce
            | ProtocolFeature::PostQuantumSignatures
            | ProtocolFeature::UniqueChunkTransactions
            | ProtocolFeature::ValidateBlockOrdinalAndEpochSyncDataHash
            | ProtocolFeature::YieldWithId
            | ProtocolFeature::ExecutionMetadataV4
            | ProtocolFeature::SignedContractCodeResponse
            | ProtocolFeature::ClampOutgoingGasAdmission
            | ProtocolFeature::AccountCostIncrease
            | ProtocolFeature::DelegateV2 => 85,
            ProtocolFeature::EnforcePerReceiptStorageProofLimit => 86,

            // Nightly features:
            ProtocolFeature::FixContractLoadingCost => 129,
            // TODO(#11201): When stabilizing this feature in mainnet, also remove the temporary code
            // that always enables this for mocknet (see config_mocknet function).
            ProtocolFeature::ShuffleShardAssignments => 143,
            ProtocolFeature::EarlyKickout => 152,
            // Spice is setup to include nightly, but not be part of it for now so that features
            // that are released before spice can be tested properly.
            ProtocolFeature::Spice => 180,
            // Place features that are not yet in Nightly below this line.
        }
    }

    pub const fn enabled(&self, protocol_version: ProtocolVersion) -> bool {
        protocol_version >= self.protocol_version()
    }
}

/// The protocol version of the genesis block on mainnet and testnet.
pub const PROD_GENESIS_PROTOCOL_VERSION: ProtocolVersion = 29;

/// Minimum supported protocol version for the current binary
pub const MIN_SUPPORTED_PROTOCOL_VERSION: ProtocolVersion = 83;

/// Returns the effective protocol version to use for processing a request.
///
/// Archival nodes can serve requests for blocks from protocol versions older than
/// `MIN_SUPPORTED_PROTOCOL_VERSION`. Some features from those old versions may no longer be
/// available in the current binary (e.g. the Wasmer0/Wasmer2 VM backends have been removed).
/// For read-only view calls that don't produce on-chain state, it is safe to clamp the protocol
/// version to `MIN_SUPPORTED_PROTOCOL_VERSION` so the request is processed with the config of
/// the oldest fully-supported version.
pub fn clamp_to_supported_protocol_version(
    current_protocol_version: ProtocolVersion,
) -> ProtocolVersion {
    current_protocol_version.max(MIN_SUPPORTED_PROTOCOL_VERSION)
}

/// Panics if `current_protocol_version` is below `MIN_SUPPORTED_PROTOCOL_VERSION`.
///
/// Use this at callee boundaries to enforce that the caller has already clamped the version
/// via [`clamp_to_supported_protocol_version`].
pub fn assert_supported_protocol_version(current_protocol_version: ProtocolVersion) {
    assert!(
        current_protocol_version >= MIN_SUPPORTED_PROTOCOL_VERSION,
        "protocol version {current_protocol_version} is below minimum supported {MIN_SUPPORTED_PROTOCOL_VERSION}"
    );
}

/// Current protocol version used on the mainnet with all stable features.
const STABLE_PROTOCOL_VERSION: ProtocolVersion = 86;

// On nightly, pick big enough version to support all features.
const NIGHTLY_PROTOCOL_VERSION: ProtocolVersion = 155;

// TODO(spice): Once spice is mature and close to release make it part of nightly - at the point in
// time cargo feature for spice should be removed as well.
// For spice we want to include all nightly features, but for now we don't want nightly to run with
// spice.
const SPICE_PROTOCOL_VERSION: ProtocolVersion = 200;

/// Largest protocol version supported by the current binary.
pub const PROTOCOL_VERSION: ProtocolVersion = if cfg!(feature = "protocol_feature_spice") {
    SPICE_PROTOCOL_VERSION
} else if cfg!(feature = "nightly") {
    NIGHTLY_PROTOCOL_VERSION
} else {
    STABLE_PROTOCOL_VERSION
};