From a853d8682e996f43d80a4aed6d46f2ee7da8a7ad Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Thu, 13 Feb 2025 20:33:37 +0100 Subject: [PATCH 01/12] add cors for localnet --- .../sources/configs/config_buffer.move | 1 + .../sources/configs/evm_config.move | 44 +++++++++++++++++++ .../sources/configs/evm_config.spec.move | 22 ++++++++++ types/src/on_chain_config/evm_config.rs | 34 ++++++++++++++ types/src/on_chain_config/mod.rs | 1 + 5 files changed, 102 insertions(+) create mode 100644 aptos-move/framework/supra-framework/sources/configs/evm_config.move create mode 100644 aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move create mode 100644 types/src/on_chain_config/evm_config.rs diff --git a/aptos-move/framework/supra-framework/sources/configs/config_buffer.move b/aptos-move/framework/supra-framework/sources/configs/config_buffer.move index dfd161e2a991b..3fd9ac4429c36 100644 --- a/aptos-move/framework/supra-framework/sources/configs/config_buffer.move +++ b/aptos-move/framework/supra-framework/sources/configs/config_buffer.move @@ -18,6 +18,7 @@ module supra_framework::config_buffer { use aptos_std::type_info; use supra_framework::system_addresses; + friend supra_framework::evm_config; friend supra_framework::consensus_config; friend supra_framework::execution_config; friend supra_framework::supra_config; diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.move new file mode 100644 index 0000000000000..13a55246ef430 --- /dev/null +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.move @@ -0,0 +1,44 @@ +module supra_framework::evm_config { + use std::error; + use std::vector; + use supra_framework::config_buffer; + + use supra_framework::system_addresses; + + friend supra_framework::genesis; + friend supra_framework::reconfiguration_with_dkg; + + struct EvmConfig has drop, key, store { + config: vector, + } + + /// The provided on chain config bytes are empty or invalid + const EINVALID_CONFIG: u64 = 1; + + /// This can be called by on-chain governance to update on-chain consensus configs for the next epoch. + /// Example usage: + /// ``` + /// supra_framework::evm_config::set_for_next_epoch(&framework_signer, some_config_bytes); + /// supra_framework::supra_governance::reconfigure(&framework_signer); + /// ``` + public fun set_for_next_epoch(account: &signer, config: vector) { + system_addresses::assert_supra_framework(account); + assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG)); + std::config_buffer::upsert(EvmConfig {config}); + } + /// Only used in reconfigurations to apply the pending `EvmConfig` in buffer, if there is any. + /// If supra_framework has a EvmConfig, then update the new config to supra_framework. + /// Otherwise, move the new config to supra_framework. + public(friend) fun on_new_epoch(framework: &signer) acquires EvmConfig { + system_addresses::assert_supra_framework(framework); + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@supra_framework)) { + *borrow_global_mut(@supra_framework) = new_config; + } else { + move_to(framework, new_config); + }; + } + } + +} diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move new file mode 100644 index 0000000000000..e4070993ea326 --- /dev/null +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move @@ -0,0 +1,22 @@ +spec supra_framework::evm_config { + + spec module { + use supra_framework::chain_status; + pragma verify = true; + pragma aborts_if_is_strict; + /// The Evm config does not exist on chain from genesis. + /// So we do not require below condition. + // chain_status::is_operating() ==> exists(@supra_framework); + } + + spec set_for_next_epoch(account: &signer, config: vector) { + include config_buffer::SetForNextEpochAbortsIf; + } + + spec on_new_epoch(framework: &signer) { + requires @supra_framework == std::signer::address_of(framework); + include config_buffer::OnNewEpochRequirement; + aborts_if false; + } + +} diff --git a/types/src/on_chain_config/evm_config.rs b/types/src/on_chain_config/evm_config.rs new file mode 100644 index 0000000000000..92d6da84a0dcb --- /dev/null +++ b/types/src/on_chain_config/evm_config.rs @@ -0,0 +1,34 @@ +// Copyright (c) Aptos Foundation +// SPDX-License-Identifier: Apache-2.0 + +use serde::{Deserialize, Serialize}; +use anyhow::{Result, anyhow}; +use super::OnChainConfig; + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] +pub enum OnChainEvmConfig { + V1(EvmConfigV1), +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] +pub struct EvmConfigV1 { + chain_id: u64, +} + +impl OnChainConfig for OnChainEvmConfig { + const MODULE_IDENTIFIER: &'static str = "evm_config"; + const TYPE_IDENTIFIER: &'static str = "EvmConfig"; + + /// The Move resource is + /// ```ignore + /// struct EvmConfig has copy, drop, store { + /// config: vector, + /// } + /// ``` + /// so we need two rounds of bcs deserilization to turn it back to OnChainEvmConfig + fn deserialize_into_config(bytes: &[u8]) -> Result { + let raw_bytes: Vec = bcs::from_bytes(bytes)?; + bcs::from_bytes(&raw_bytes) + .map_err(|e| anyhow!("[on-chain config] Failed to deserialize into config: {}", e)) + } +} diff --git a/types/src/on_chain_config/mod.rs b/types/src/on_chain_config/mod.rs index 32692e9aec19a..b9c30aa63db97 100644 --- a/types/src/on_chain_config/mod.rs +++ b/types/src/on_chain_config/mod.rs @@ -26,6 +26,7 @@ mod aptos_version; mod chain_id; mod commit_history; mod consensus_config; +mod evm_config; mod execution_config; mod gas_schedule; mod jwk_consensus_config; From ba61f084667fd316f6c38d5f0fcd085662235099 Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Thu, 13 Feb 2025 20:46:29 +0100 Subject: [PATCH 02/12] add docs and default --- .../framework/aptos-token-objects/doc/collection.md | 4 ++-- aptos-move/framework/aptos-token-objects/doc/token.md | 6 +++--- types/src/on_chain_config/evm_config.rs | 9 +++++++++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/aptos-move/framework/aptos-token-objects/doc/collection.md b/aptos-move/framework/aptos-token-objects/doc/collection.md index 3cb95eb99eef3..e6098031719f9 100644 --- a/aptos-move/framework/aptos-token-objects/doc/collection.md +++ b/aptos-move/framework/aptos-token-objects/doc/collection.md @@ -793,7 +793,7 @@ The collection does not have a max supply Creates a fixed-sized collection, or a collection that supports a fixed amount of tokens. This is useful to create a guaranteed, limited supply on-chain digital asset. For example, a collection 1111 vicious vipers. Note, creating restrictions such as upward limits results -in data structures that prevent Supra from parallelizing mints of this collection type. +in data structures that prevent Aptos from parallelizing mints of this collection type. Beyond that, it adds supply tracking with events. @@ -892,7 +892,7 @@ the supply of tokens. ## Function `create_untracked_collection` Creates an untracked collection, or a collection that supports an arbitrary amount of -tokens. This is useful for mass airdrops that fully leverage Supra parallelization. +tokens. This is useful for mass airdrops that fully leverage Aptos parallelization. TODO: Hide this until we bring back meaningful way to enforce burns diff --git a/aptos-move/framework/aptos-token-objects/doc/token.md b/aptos-move/framework/aptos-token-objects/doc/token.md index 4f405dbc13d3c..6c3c30342af11 100644 --- a/aptos-move/framework/aptos-token-objects/doc/token.md +++ b/aptos-move/framework/aptos-token-objects/doc/token.md @@ -3,7 +3,7 @@ # Module `0x4::token` -This defines an object-based Token. The key differentiating features from the Supra standard +This defines an object-based Token. The key differentiating features from the Aptos standard token are: * Decoupled token ownership from token data. * Explicit data model for token metadata via adjacent resources @@ -113,7 +113,7 @@ Represents the common fields to all tokens. Was populated until concurrent_token_v2_enabled feature flag was enabled. The name of the token, which should be unique within the collection; the length of name - should be smaller than 128, characters, eg: "Supra Animal #1234" + should be smaller than 128, characters, eg: "Aptos Animal #1234"
uri: string::String @@ -163,7 +163,7 @@ Started being populated once aggregator_v2_api_enabled was enabled.
The name of the token, which should be unique within the collection; the length of name - should be smaller than 128, characters, eg: "Supra Animal #1234" + should be smaller than 128, characters, eg: "Aptos Animal #1234"
diff --git a/types/src/on_chain_config/evm_config.rs b/types/src/on_chain_config/evm_config.rs index 92d6da84a0dcb..9def1ef6af202 100644 --- a/types/src/on_chain_config/evm_config.rs +++ b/types/src/on_chain_config/evm_config.rs @@ -15,6 +15,15 @@ pub struct EvmConfigV1 { chain_id: u64, } +impl Default for OnChainEvmConfig { + fn default() -> Self { + // Chose a chain_id that is not used by Ethereum compatible chains + OnChainEvmConfig::V1(EvmConfigV1 { chain_id: 0x1a2b3c4d_1a2b3c4d }) + } +} + +/// This onchain config does not exist from genesis, until it is added by the governance proposal. +/// If the config is not found, Evm should not be enabled. impl OnChainConfig for OnChainEvmConfig { const MODULE_IDENTIFIER: &'static str = "evm_config"; const TYPE_IDENTIFIER: &'static str = "EvmConfig"; From fb1ab0246ee1b470c1b8cf39c44dc62793f47bde Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Thu, 13 Feb 2025 21:46:37 +0100 Subject: [PATCH 03/12] docs --- .../aptos-token-objects/doc/collection.md | 4 +- .../aptos-token-objects/doc/token.md | 6 +- .../supra-framework/doc/evm_config.md | 178 ++++++++++++++++++ 3 files changed, 183 insertions(+), 5 deletions(-) create mode 100644 aptos-move/framework/supra-framework/doc/evm_config.md diff --git a/aptos-move/framework/aptos-token-objects/doc/collection.md b/aptos-move/framework/aptos-token-objects/doc/collection.md index e6098031719f9..3cb95eb99eef3 100644 --- a/aptos-move/framework/aptos-token-objects/doc/collection.md +++ b/aptos-move/framework/aptos-token-objects/doc/collection.md @@ -793,7 +793,7 @@ The collection does not have a max supply Creates a fixed-sized collection, or a collection that supports a fixed amount of tokens. This is useful to create a guaranteed, limited supply on-chain digital asset. For example, a collection 1111 vicious vipers. Note, creating restrictions such as upward limits results -in data structures that prevent Aptos from parallelizing mints of this collection type. +in data structures that prevent Supra from parallelizing mints of this collection type. Beyond that, it adds supply tracking with events. @@ -892,7 +892,7 @@ the supply of tokens. ## Function `create_untracked_collection` Creates an untracked collection, or a collection that supports an arbitrary amount of -tokens. This is useful for mass airdrops that fully leverage Aptos parallelization. +tokens. This is useful for mass airdrops that fully leverage Supra parallelization. TODO: Hide this until we bring back meaningful way to enforce burns diff --git a/aptos-move/framework/aptos-token-objects/doc/token.md b/aptos-move/framework/aptos-token-objects/doc/token.md index 6c3c30342af11..4f405dbc13d3c 100644 --- a/aptos-move/framework/aptos-token-objects/doc/token.md +++ b/aptos-move/framework/aptos-token-objects/doc/token.md @@ -3,7 +3,7 @@ # Module `0x4::token` -This defines an object-based Token. The key differentiating features from the Aptos standard +This defines an object-based Token. The key differentiating features from the Supra standard token are: * Decoupled token ownership from token data. * Explicit data model for token metadata via adjacent resources @@ -113,7 +113,7 @@ Represents the common fields to all tokens. Was populated until concurrent_token_v2_enabled feature flag was enabled. The name of the token, which should be unique within the collection; the length of name - should be smaller than 128, characters, eg: "Aptos Animal #1234" + should be smaller than 128, characters, eg: "Supra Animal #1234"
uri: string::String @@ -163,7 +163,7 @@ Started being populated once aggregator_v2_api_enabled was enabled.
The name of the token, which should be unique within the collection; the length of name - should be smaller than 128, characters, eg: "Aptos Animal #1234" + should be smaller than 128, characters, eg: "Supra Animal #1234"
diff --git a/aptos-move/framework/supra-framework/doc/evm_config.md b/aptos-move/framework/supra-framework/doc/evm_config.md new file mode 100644 index 0000000000000..d0251fbd79c5b --- /dev/null +++ b/aptos-move/framework/supra-framework/doc/evm_config.md @@ -0,0 +1,178 @@ + + + +# Module `0x1::evm_config` + + + +- [Resource `EvmConfig`](#0x1_evm_config_EvmConfig) +- [Constants](#@Constants_0) +- [Function `set_for_next_epoch`](#0x1_evm_config_set_for_next_epoch) +- [Function `on_new_epoch`](#0x1_evm_config_on_new_epoch) +- [Specification](#@Specification_1) + - [Function `set_for_next_epoch`](#@Specification_1_set_for_next_epoch) + - [Function `on_new_epoch`](#@Specification_1_on_new_epoch) + + +
use 0x1::config_buffer;
+use 0x1::error;
+use 0x1::system_addresses;
+
+ + + + + +## Resource `EvmConfig` + + + +
struct EvmConfig has drop, store, key
+
+ + + +
+Fields + + +
+
+config: vector<u8> +
+
+ +
+
+ + +
+ + + +## Constants + + + + +The provided on chain config bytes are empty or invalid + + +
const EINVALID_CONFIG: u64 = 1;
+
+ + + + + +## Function `set_for_next_epoch` + +This can be called by on-chain governance to update on-chain consensus configs for the next epoch. +Example usage: +``` +supra_framework::evm_config::set_for_next_epoch(&framework_signer, some_config_bytes); +supra_framework::supra_governance::reconfigure(&framework_signer); +``` + + +
public fun set_for_next_epoch(account: &signer, config: vector<u8>)
+
+ + + +
+Implementation + + +
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
+    system_addresses::assert_supra_framework(account);
+    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    std::config_buffer::upsert<EvmConfig>(EvmConfig {config});
+}
+
+ + + +
+ + + +## Function `on_new_epoch` + +Only used in reconfigurations to apply the pending EvmConfig in buffer, if there is any. +If supra_framework has a EvmConfig, then update the new config to supra_framework. +Otherwise, move the new config to supra_framework. + + +
public(friend) fun on_new_epoch(framework: &signer)
+
+ + + +
+Implementation + + +
public(friend) fun on_new_epoch(framework: &signer) acquires EvmConfig {
+    system_addresses::assert_supra_framework(framework);
+    if (config_buffer::does_exist<EvmConfig>()) {
+        let new_config = config_buffer::extract<EvmConfig>();
+        if (exists<EvmConfig>(@supra_framework)) {
+            *borrow_global_mut<EvmConfig>(@supra_framework) = new_config;
+        } else {
+            move_to(framework, new_config);
+        };
+    }
+}
+
+ + + +
+ + + +## Specification + + + +
pragma verify = true;
+pragma aborts_if_is_strict;
+
+ + + + + +### Function `set_for_next_epoch` + + +
public fun set_for_next_epoch(account: &signer, config: vector<u8>)
+
+ + + + +
include config_buffer::SetForNextEpochAbortsIf;
+
+ + + + + +### Function `on_new_epoch` + + +
public(friend) fun on_new_epoch(framework: &signer)
+
+ + + + +
requires @supra_framework == std::signer::address_of(framework);
+include config_buffer::OnNewEpochRequirement<EvmConfig>;
+aborts_if false;
+
+ + +[move-book]: https://aptos.dev/move/book/SUMMARY From 02a40b60c6dfc04dc9e206e8e12a65fd6877d6e4 Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Thu, 13 Feb 2025 21:48:23 +0100 Subject: [PATCH 04/12] docs --- .../framework/supra-framework/sources/configs/evm_config.move | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.move index 13a55246ef430..f3a122d101118 100644 --- a/aptos-move/framework/supra-framework/sources/configs/evm_config.move +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.move @@ -15,7 +15,7 @@ module supra_framework::evm_config { /// The provided on chain config bytes are empty or invalid const EINVALID_CONFIG: u64 = 1; - /// This can be called by on-chain governance to update on-chain consensus configs for the next epoch. + /// This can be called by on-chain governance to update on-chain evm configs for the next epoch. /// Example usage: /// ``` /// supra_framework::evm_config::set_for_next_epoch(&framework_signer, some_config_bytes); From fa19a9cccff3ed3685a139761ee3cee4c0ed60e5 Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Fri, 14 Feb 2025 14:16:12 +0100 Subject: [PATCH 05/12] integration with smr --- .../supra-framework/sources/configs/evm_config.move | 6 ++++++ .../sources/configs/evm_config.spec.move | 4 ---- .../framework/supra-framework/sources/genesis.move | 7 +++++++ aptos-move/vm-genesis/src/lib.rs | 12 ++++++++++++ crates/aptos-genesis/src/lib.rs | 4 ++-- crates/aptos/src/test/mod.rs | 2 +- testsuite/smoke-test/src/lib.rs | 2 +- types/src/on_chain_config/evm_config.rs | 12 ++++++++---- types/src/on_chain_config/mod.rs | 1 + 9 files changed, 38 insertions(+), 12 deletions(-) diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.move index f3a122d101118..a14869e5f57c8 100644 --- a/aptos-move/framework/supra-framework/sources/configs/evm_config.move +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.move @@ -15,6 +15,12 @@ module supra_framework::evm_config { /// The provided on chain config bytes are empty or invalid const EINVALID_CONFIG: u64 = 1; + public(friend) fun initialize(supra_framework: &signer, config: vector) { + system_addresses::assert_supra_framework(supra_framework); + assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG)); + move_to(supra_framework, EvmConfig { config }); + } + /// This can be called by on-chain governance to update on-chain evm configs for the next epoch. /// Example usage: /// ``` diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move index e4070993ea326..6270c95ddb3c5 100644 --- a/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move @@ -1,12 +1,8 @@ spec supra_framework::evm_config { spec module { - use supra_framework::chain_status; pragma verify = true; pragma aborts_if_is_strict; - /// The Evm config does not exist on chain from genesis. - /// So we do not require below condition. - // chain_status::is_operating() ==> exists(@supra_framework); } spec set_for_next_epoch(account: &signer, config: vector) { diff --git a/aptos-move/framework/supra-framework/sources/genesis.move b/aptos-move/framework/supra-framework/sources/genesis.move index 0b42c26955e93..fdc65bb97fa0f 100644 --- a/aptos-move/framework/supra-framework/sources/genesis.move +++ b/aptos-move/framework/supra-framework/sources/genesis.move @@ -21,6 +21,7 @@ module supra_framework::genesis { use supra_framework::consensus_config; use supra_framework::execution_config; use supra_framework::supra_config; + use supra_framework::evm_config; use supra_framework::create_signer::create_signer; use supra_framework::gas_schedule; use supra_framework::reconfiguration; @@ -135,6 +136,7 @@ module supra_framework::genesis { rewards_rate_denominator: u64, voting_power_increase_limit: u64, genesis_timestamp_in_microseconds: u64, + evm_config: vector, ) { // Initialize the aptos framework account. This is the account where system resources and modules will be // deployed to. This will be entirely managed by on-chain governance and no entities have the key or privileges @@ -189,6 +191,7 @@ module supra_framework::genesis { block::initialize(&supra_framework_account, epoch_interval_microsecs); state_storage::initialize(&supra_framework_account); timestamp::set_time_has_started(&supra_framework_account, genesis_timestamp_in_microseconds); + evm_config::initialize(&supra_framework_account, evm_config); } /// Genesis step 2: Initialize Supra coin. @@ -641,6 +644,7 @@ module supra_framework::genesis { consensus_config: vector, execution_config: vector, supra_config: vector, + evm_config: vector, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, @@ -677,6 +681,8 @@ module supra_framework::genesis { rewards_rate_denominator, voting_power_increase_limit, 0, + evm_config, + ); features::change_feature_flags_for_verification(supra_framework, vector[1, 2, 11], vector[]); initialize_supra_coin(supra_framework); @@ -714,6 +720,7 @@ module supra_framework::genesis { 1, 30, 0, + x"15", ) } diff --git a/aptos-move/vm-genesis/src/lib.rs b/aptos-move/vm-genesis/src/lib.rs index 962731c8d878b..8f1f227a159b6 100644 --- a/aptos-move/vm-genesis/src/lib.rs +++ b/aptos-move/vm-genesis/src/lib.rs @@ -34,6 +34,7 @@ use aptos_types::{ randomness_api_v0_config::{AllowCustomMaxGasFlag, RequiredGasDeposit}, FeatureFlag, Features, GasScheduleV2, OnChainConsensusConfig, OnChainExecutionConfig, OnChainJWKConsensusConfig, OnChainRandomnessConfig, RandomnessConfigMoveStruct, + OnChainEvmConfig, APTOS_MAX_KNOWN_VERSION, }, transaction::{authenticator::AuthenticationKey, ChangeSet, Transaction, WriteSetPayload}, @@ -154,6 +155,7 @@ pub fn encode_supra_mainnet_genesis_transaction( let consensus_config = OnChainConsensusConfig::default_for_genesis(); let execution_config = OnChainExecutionConfig::default_for_genesis(); let gas_schedule = default_gas_schedule(); + let evm_config = OnChainEvmConfig::default_for_mainnet(); initialize( &mut session, chain_id, @@ -162,6 +164,7 @@ pub fn encode_supra_mainnet_genesis_transaction( &execution_config, &gas_schedule, supra_config_bytes, + &evm_config, ); initialize_features( &mut session, @@ -245,6 +248,7 @@ pub fn encode_genesis_transaction_for_testnet( execution_config: &OnChainExecutionConfig, gas_schedule: &GasScheduleV2, supra_config_bytes: Vec, + evm_config: &OnChainEvmConfig, ) -> Transaction { Transaction::GenesisTransaction(WriteSetPayload::Direct( encode_genesis_change_set_for_testnet( @@ -264,6 +268,7 @@ pub fn encode_genesis_transaction_for_testnet( execution_config, gas_schedule, supra_config_bytes, + evm_config, ), )) } @@ -285,6 +290,7 @@ pub fn encode_genesis_change_set_for_testnet( execution_config: &OnChainExecutionConfig, gas_schedule: &GasScheduleV2, supra_config_bytes: Vec, + evm_config: &OnChainEvmConfig, ) -> ChangeSet { validate_genesis_config(genesis_config); @@ -307,6 +313,7 @@ pub fn encode_genesis_change_set_for_testnet( execution_config, gas_schedule, supra_config_bytes, + evm_config, ); initialize_features( &mut session, @@ -481,6 +488,7 @@ fn initialize( execution_config: &OnChainExecutionConfig, gas_schedule: &GasScheduleV2, supra_config_bytes: Vec, + evm_config: &OnChainEvmConfig, ) { let gas_schedule_blob = bcs::to_bytes(gas_schedule).expect("Failure serializing genesis gas schedule"); @@ -491,6 +499,7 @@ fn initialize( let execution_config_bytes = bcs::to_bytes(execution_config).expect("Failure serializing genesis consensus config"); + let evm_config_bytes = bcs::to_bytes(evm_config).expect("Failure serializing genesis evm config"); // Calculate the per-epoch rewards rate, represented as 2 separate ints (numerator and // denominator). let rewards_rate_denominator = 1_000_000_000; @@ -524,6 +533,7 @@ fn initialize( MoveValue::U64(rewards_rate_denominator), MoveValue::U64(genesis_config.voting_power_increase_limit), MoveValue::U64(genesis_config.genesis_timestamp_in_microseconds), + MoveValue::vector_u8(evm_config_bytes), ]), ); } @@ -1201,6 +1211,7 @@ pub fn generate_test_genesis( &OnChainExecutionConfig::default_for_genesis(), &default_gas_schedule(), b"test".to_vec(), + &OnChainEvmConfig::default_for_test(), ); (genesis, test_validators) } @@ -1231,6 +1242,7 @@ pub fn generate_mainnet_genesis( &OnChainExecutionConfig::default_for_genesis(), &default_gas_schedule(), b"test".to_vec(), + &OnChainEvmConfig::default_for_test(), ); (genesis, test_validators) } diff --git a/crates/aptos-genesis/src/lib.rs b/crates/aptos-genesis/src/lib.rs index 6f05814302cf5..a204189749536 100644 --- a/crates/aptos-genesis/src/lib.rs +++ b/crates/aptos-genesis/src/lib.rs @@ -25,8 +25,7 @@ use aptos_types::{ account_address::AccountAddress, chain_id::ChainId, on_chain_config::{ - Features, GasScheduleV2, OnChainConsensusConfig, OnChainExecutionConfig, - OnChainJWKConsensusConfig, OnChainRandomnessConfig, + Features, GasScheduleV2, OnChainConsensusConfig, OnChainEvmConfig, OnChainExecutionConfig, OnChainJWKConsensusConfig, OnChainRandomnessConfig }, transaction::Transaction, waypoint::Waypoint, @@ -169,6 +168,7 @@ impl GenesisInfo { &self.execution_config, &self.gas_schedule, b"test".to_vec(), + &OnChainEvmConfig::default_for_test(), ) } diff --git a/crates/aptos/src/test/mod.rs b/crates/aptos/src/test/mod.rs index 8d89e25c8eaa2..6d7d2ef1ddf77 100644 --- a/crates/aptos/src/test/mod.rs +++ b/crates/aptos/src/test/mod.rs @@ -1182,7 +1182,7 @@ impl CliTestFramework { is_multi_step: bool, ) -> CliTypedResult { SubmitProposal { - pool_address_args: PoolAddressArgs { pool_address }, + // pool_address_args: PoolAddressArgs { pool_address }, args: SubmitProposalArgs { #[cfg(feature = "no-upload-proposal")] metadata_path: None, diff --git a/testsuite/smoke-test/src/lib.rs b/testsuite/smoke-test/src/lib.rs index fe96bb83e7ea3..84b0a815b8403 100644 --- a/testsuite/smoke-test/src/lib.rs +++ b/testsuite/smoke-test/src/lib.rs @@ -37,7 +37,7 @@ mod randomness; #[cfg(test)] mod rest_api; #[cfg(test)] -mod rosetta; +// mod rosetta; #[cfg(test)] mod state_sync; #[cfg(test)] diff --git a/types/src/on_chain_config/evm_config.rs b/types/src/on_chain_config/evm_config.rs index 9def1ef6af202..2fe51f0277921 100644 --- a/types/src/on_chain_config/evm_config.rs +++ b/types/src/on_chain_config/evm_config.rs @@ -15,13 +15,17 @@ pub struct EvmConfigV1 { chain_id: u64, } -impl Default for OnChainEvmConfig { - fn default() -> Self { - // Chose a chain_id that is not used by Ethereum compatible chains - OnChainEvmConfig::V1(EvmConfigV1 { chain_id: 0x1a2b3c4d_1a2b3c4d }) +impl OnChainEvmConfig { + pub fn default_for_test() -> Self { + Self::V1(EvmConfigV1 { chain_id: 0x12_3456_7890 }) + } + + pub fn default_for_mainnet() -> Self { + Self::V1(EvmConfigV1 { chain_id: 0xffff_aaaa_eeee }) } } + /// This onchain config does not exist from genesis, until it is added by the governance proposal. /// If the config is not found, Evm should not be enabled. impl OnChainConfig for OnChainEvmConfig { diff --git a/types/src/on_chain_config/mod.rs b/types/src/on_chain_config/mod.rs index b9c30aa63db97..310f5cc7a8fcf 100644 --- a/types/src/on_chain_config/mod.rs +++ b/types/src/on_chain_config/mod.rs @@ -64,6 +64,7 @@ pub use self::{ timestamp::CurrentTimeMicroseconds, transaction_fee::TransactionFeeBurnCap, validator_set::{ConsensusScheme, ValidatorSet}, + evm_config::OnChainEvmConfig, }; /// To register an on-chain config in Rust: From 7fe91c44ebce5572e12241fe5fe3ae2c70991ffa Mon Sep 17 00:00:00 2001 From: Simon <141160134+so-schen@users.noreply.github.com> Date: Mon, 17 Feb 2025 14:44:12 +0100 Subject: [PATCH 06/12] fix move docs (#181) * fix move docs * fix docs * addressing comments * addressing comments * generate .md --- .../framework/aptos-stdlib/doc/bls12381.md | 36 ++ .../aptos-stdlib/doc/fixed_point64.md | 31 + .../sources/cryptography/bls12381.move | 12 +- .../sources/cryptography/ed25519.move | 8 +- .../sources/cryptography/multi_ed25519.move | 12 +- .../sources/collection.move | 4 +- .../aptos-token-objects/sources/token.move | 6 +- .../framework/aptos-token/sources/token.move | 8 +- .../src/aptos_framework_sdk_builder.rs | 82 +++ .../move-stdlib/doc/fixed_point32.md | 31 + .../move-stdlib/sources/configs/features.move | 4 +- .../framework/supra-framework/doc/block.md | 72 ++- .../framework/supra-framework/doc/code.md | 2 +- .../framework/supra-framework/doc/coin.md | 14 +- .../supra-framework/doc/committee_map.md | 12 +- .../supra-framework/doc/consensus_config.md | 8 +- .../supra-framework/doc/evm_config.md | 34 +- .../supra-framework/doc/execution_config.md | 4 +- .../supra-framework/doc/gas_schedule.md | 16 +- .../framework/supra-framework/doc/genesis.md | 104 ++- .../doc/governance_proposal.md | 10 +- .../supra-framework/doc/multisig_account.md | 20 +- .../supra-framework/doc/multisig_voting.md | 2 +- .../framework/supra-framework/doc/overview.md | 1 + .../doc/pbo_delegation_pool.md | 67 +- .../supra-framework/doc/reconfiguration.md | 10 +- .../framework/supra-framework/doc/stake.md | 15 +- .../supra-framework/doc/staking_config.md | 22 +- .../supra-framework/doc/staking_contract.md | 8 +- .../supra-framework/doc/storage_gas.md | 6 +- .../supra-framework/doc/supra_coin.md | 4 +- .../supra-framework/doc/supra_config.md | 4 +- .../supra-framework/doc/supra_governance.md | 4 +- .../supra-framework/doc/system_addresses.md | 10 +- .../supra-framework/doc/timestamp.md | 2 +- .../supra-framework/doc/transaction_fee.md | 4 +- .../doc/transaction_validation.md | 2 +- .../framework/supra-framework/doc/version.md | 2 +- .../framework/supra-framework/doc/vesting.md | 10 +- .../doc/vesting_without_staking.md | 594 +++++++++++++----- .../framework/supra-framework/doc/voting.md | 4 +- .../supra-framework/sources/account.move | 2 +- .../aggregator/aggregator_factory.spec.move | 2 +- .../supra-framework/sources/block.move | 2 +- .../supra-framework/sources/block.spec.move | 2 +- .../sources/chain_id.spec.move | 2 +- .../supra-framework/sources/coin.spec.move | 2 +- .../configs/consensus_config.spec.move | 2 +- .../sources/configs/evm_config.move | 8 +- .../sources/configs/evm_config.spec.move | 1 - .../sources/configs/gas_schedule.spec.move | 16 +- .../sources/configs/staking_config.move | 6 +- .../sources/configs/version.spec.move | 2 +- .../supra-framework/sources/genesis.move | 9 +- .../supra-framework/sources/genesis.spec.move | 6 +- .../sources/governance_proposal.move | 8 +- .../sources/governance_proposal.spec.move | 2 +- .../sources/reconfiguration.spec.move | 10 +- .../sources/storage_gas.spec.move | 4 +- .../supra-framework/sources/supra_coin.move | 4 +- .../sources/supra_governance.move | 4 +- .../sources/system_addresses.spec.move | 8 +- .../supra-framework/sources/timestamp.move | 2 +- .../sources/transaction_fee.spec.move | 2 +- .../supra-framework/sources/voting.move | 2 +- crates/aptos/src/test/mod.rs | 1 - testsuite/smoke-test/src/lib.rs | 2 +- types/src/on_chain_config/evm_config.rs | 2 +- 68 files changed, 995 insertions(+), 419 deletions(-) diff --git a/aptos-move/framework/aptos-stdlib/doc/bls12381.md b/aptos-move/framework/aptos-stdlib/doc/bls12381.md index 5f3f76d2527b1..c28a8fb58bd26 100644 --- a/aptos-move/framework/aptos-stdlib/doc/bls12381.md +++ b/aptos-move/framework/aptos-stdlib/doc/bls12381.md @@ -22,6 +22,7 @@ as per the [IETF BLS draft standard](https://datatracker.ietf.org/doc/html/draft - [Function `proof_of_possession_from_bytes`](#0x1_bls12381_proof_of_possession_from_bytes) - [Function `proof_of_possession_to_bytes`](#0x1_bls12381_proof_of_possession_to_bytes) - [Function `public_key_from_bytes_with_pop`](#0x1_bls12381_public_key_from_bytes_with_pop) +- [Function `public_key_from_bytes_with_pop_externally_verified`](#0x1_bls12381_public_key_from_bytes_with_pop_externally_verified) - [Function `public_key_with_pop_to_normal`](#0x1_bls12381_public_key_with_pop_to_normal) - [Function `public_key_with_pop_to_bytes`](#0x1_bls12381_public_key_with_pop_to_bytes) - [Function `signature_from_bytes`](#0x1_bls12381_signature_from_bytes) @@ -478,6 +479,41 @@ Creates a PoP'd public key from a normal public key and a corresponding proof-of + + + + +## Function `public_key_from_bytes_with_pop_externally_verified` + +CRYPTOGRAPHY WARNING: Using this function to create PublicKeyWithPoP' without first externally verifying the pop can +result in rogue-key attacks. +Creates a PoP'd public key from a normal public key assuming the pop is verified externally +This function in contrast to public_key_from_bytes_with_pop' does not require pop and assumes that +the pop is already verified and we donot wish to verify it again or pop is unavailable due to some reason. + + +
public fun public_key_from_bytes_with_pop_externally_verified(pk_bytes: vector<u8>): option::Option<bls12381::PublicKeyWithPoP>
+
+ + + +
+Implementation + + +
public fun public_key_from_bytes_with_pop_externally_verified(pk_bytes: vector<u8>): Option<PublicKeyWithPoP> {
+    if (validate_pubkey_internal(pk_bytes)) {
+        option::some(PublicKeyWithPoP {
+            bytes: pk_bytes
+        })
+    } else {
+        option::none<PublicKeyWithPoP>()
+    }
+}
+
+ + +
diff --git a/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md b/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md index 22571462f6c30..642601dc34a1b 100644 --- a/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md +++ b/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md @@ -12,6 +12,7 @@ a 64-bit fractional part. - [Function `sub`](#0x1_fixed_point64_sub) - [Function `add`](#0x1_fixed_point64_add) - [Function `multiply_u128`](#0x1_fixed_point64_multiply_u128) +- [Function `multiply_u128_return_fixpoint64`](#0x1_fixed_point64_multiply_u128_return_fixpoint64) - [Function `divide_u128`](#0x1_fixed_point64_divide_u128) - [Function `create_from_rational`](#0x1_fixed_point64_create_from_rational) - [Function `create_from_raw_value`](#0x1_fixed_point64_create_from_raw_value) @@ -255,6 +256,36 @@ overflows. + + + + +## Function `multiply_u128_return_fixpoint64` + + + +
public fun multiply_u128_return_fixpoint64(val: u128, multiplier: fixed_point64::FixedPoint64): fixed_point64::FixedPoint64
+
+ + + +
+Implementation + + +
public fun multiply_u128_return_fixpoint64(val: u128, multiplier: FixedPoint64): FixedPoint64 {
+    // The product of two 128 bit values has 256 bits, so perform the
+    // multiplication with u256 types and keep the full 256 bit product
+    // to avoid losing accuracy.
+    let unscaled_product = (val as u256) * (multiplier.value as u256);
+    // Check whether the value is too large.
+    assert!(unscaled_product <= MAX_U128, EMULTIPLICATION);
+    create_from_raw_value((unscaled_product as u128))
+}
+
+ + +
diff --git a/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move b/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move index de7d05ad8b18b..86f74d4fe7e43 100644 --- a/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move +++ b/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move @@ -480,7 +480,7 @@ module aptos_std::bls12381 { // /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. - /// The message signed is "Hello Aptos!" and the associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. + /// The message signed is "Hello Supra!" and the associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. const RANDOM_SIGNATURE: vector = x"a01a65854f987d3434149b7f08f70730e30b241984e8712bc2aca885d632aafced4c3f661209debb6b1c8601326623cc16ca2f6c9edc53b7b88b7435fb6b05ddece418d2c34dc6aca2f5a11a79e67774582c14084a01dcb7820e4cb4bad0ea8d"; /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. @@ -740,7 +740,7 @@ module aptos_std::bls12381 { // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: // $ cargo test -- bls12381_sample_aggregate_pk_and_aggsig --nocapture --ignored - // The signed messages are "Hello, Aptos !", where \in {1, ..., 5} + // The signed messages are "Hello, Supra !", where \in {1, ..., 5} let msgs = vector[ x"48656c6c6f2c204170746f73203121", x"48656c6c6f2c204170746f73203221", @@ -847,7 +847,7 @@ module aptos_std::bls12381 { // ============================================================================================================= // SK: 077c8a56f26259215a4a245373ab6ddf328ac6e00e5ea38d8700efa361bdc58d - let message = b"Hello Aptos!"; + let message = b"Hello Supra!"; // First, test signatures that verify let ok = verify_normal_signature( @@ -879,9 +879,9 @@ module aptos_std::bls12381 { x"82ed7bb5528303a2e306775040a7309e0bd597b70d9949d8c6198a01a7be0b00079320ebfeaf7bbd5bfe86809940d252", ]; let messages = vector[ - b"Hello Aptos!", - b"Hello Aptos!", - b"Bello Aptos!", + b"Hello Supra!", + b"Hello Supra!", + b"Bello Supra!", ]; let i = 0; diff --git a/aptos-move/framework/aptos-stdlib/sources/cryptography/ed25519.move b/aptos-move/framework/aptos-stdlib/sources/cryptography/ed25519.move index 0f8d9c8122970..6e5dfec654bc5 100644 --- a/aptos-move/framework/aptos-stdlib/sources/cryptography/ed25519.move +++ b/aptos-move/framework/aptos-stdlib/sources/cryptography/ed25519.move @@ -21,7 +21,7 @@ module aptos_std::ed25519 { // Constants // - /// The identifier of the Ed25519 signature scheme, which is used when deriving Aptos authentication keys by hashing + /// The identifier of the Ed25519 signature scheme, which is used when deriving Supra authentication keys by hashing /// it together with an Ed25519 public key. const SIGNATURE_SCHEME_ID: u8 = 0; @@ -156,17 +156,17 @@ module aptos_std::ed25519 { } } - /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + /// Derives the Supra-specific authentication key of the given Ed25519 public key. public fun unvalidated_public_key_to_authentication_key(pk: &UnvalidatedPublicKey): vector { public_key_bytes_to_authentication_key(pk.bytes) } - /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + /// Derives the Supra-specific authentication key of the given Ed25519 public key. public fun validated_public_key_to_authentication_key(pk: &ValidatedPublicKey): vector { public_key_bytes_to_authentication_key(pk.bytes) } - /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + /// Derives the Supra-specific authentication key of the given Ed25519 public key. fun public_key_bytes_to_authentication_key(pk_bytes: vector): vector { std::vector::push_back(&mut pk_bytes, SIGNATURE_SCHEME_ID); std::hash::sha3_256(pk_bytes) diff --git a/aptos-move/framework/aptos-stdlib/sources/cryptography/multi_ed25519.move b/aptos-move/framework/aptos-stdlib/sources/cryptography/multi_ed25519.move index f1f97bc635720..01f30558e9fe3 100644 --- a/aptos-move/framework/aptos-stdlib/sources/cryptography/multi_ed25519.move +++ b/aptos-move/framework/aptos-stdlib/sources/cryptography/multi_ed25519.move @@ -29,7 +29,7 @@ module aptos_std::multi_ed25519 { // Constants // - /// The identifier of the MultiEd25519 signature scheme, which is used when deriving Aptos authentication keys by hashing + /// The identifier of the MultiEd25519 signature scheme, which is used when deriving Supra authentication keys by hashing /// it together with an MultiEd25519 public key. const SIGNATURE_SCHEME_ID: u8 = 1; @@ -232,7 +232,7 @@ module aptos_std::multi_ed25519 { signature_verify_strict_internal(multisignature.bytes, public_key.bytes, bcs::to_bytes(&encoded)) } - /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + /// Derives the Supra-specific authentication key of the given Ed25519 public key. public fun unvalidated_public_key_to_authentication_key(pk: &UnvalidatedPublicKey): vector { public_key_bytes_to_authentication_key(pk.bytes) } @@ -255,7 +255,7 @@ module aptos_std::multi_ed25519 { check_and_get_threshold(pk.bytes) } - /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + /// Derives the Supra-specific authentication key of the given Ed25519 public key. public fun validated_public_key_to_authentication_key(pk: &ValidatedPublicKey): vector { public_key_bytes_to_authentication_key(pk.bytes) } @@ -298,7 +298,7 @@ module aptos_std::multi_ed25519 { } } - /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + /// Derives the Supra-specific authentication key of the given Ed25519 public key. fun public_key_bytes_to_authentication_key(pk_bytes: vector): vector { vector::push_back(&mut pk_bytes, SIGNATURE_SCHEME_ID); std::hash::sha3_256(pk_bytes) @@ -440,7 +440,7 @@ module aptos_std::multi_ed25519 { assert!(option::extract(&mut unvalidated_public_key_threshold(&upk)) == threshold, 4); assert!(unvalidated_public_key_num_sub_pks(&upk) == group_size, 5); - let msg1 = b"Hello Aptos!"; + let msg1 = b"Hello Supra!"; let sig1 = sign_arbitrary_bytes(&sk, msg1); assert!(signature_verify_strict(&sig1, &upk, msg1), 6); @@ -466,7 +466,7 @@ module aptos_std::multi_ed25519 { assert!(option::extract(&mut unvalidated_public_key_threshold(&upk)) == 4, 4); assert!(unvalidated_public_key_num_sub_pks(&upk) == 5, 5); - let msg1 = b"Hello Aptos!"; + let msg1 = b"Hello Supra!"; let sig1 = sign_arbitrary_bytes(&sk, msg1); maul_first_signature(&mut sig1); assert!(!signature_verify_strict(&sig1, &upk, msg1), 6); diff --git a/aptos-move/framework/aptos-token-objects/sources/collection.move b/aptos-move/framework/aptos-token-objects/sources/collection.move index 7fd1eac1b559a..7bc46214228d0 100644 --- a/aptos-move/framework/aptos-token-objects/sources/collection.move +++ b/aptos-move/framework/aptos-token-objects/sources/collection.move @@ -180,7 +180,7 @@ module aptos_token_objects::collection { /// Creates a fixed-sized collection, or a collection that supports a fixed amount of tokens. /// This is useful to create a guaranteed, limited supply on-chain digital asset. For example, /// a collection 1111 vicious vipers. Note, creating restrictions such as upward limits results - /// in data structures that prevent Aptos from parallelizing mints of this collection type. + /// in data structures that prevent Supra from parallelizing mints of this collection type. /// Beyond that, it adds supply tracking with events. public fun create_fixed_collection( creator: &signer, @@ -239,7 +239,7 @@ module aptos_token_objects::collection { } /// Creates an untracked collection, or a collection that supports an arbitrary amount of - /// tokens. This is useful for mass airdrops that fully leverage Aptos parallelization. + /// tokens. This is useful for mass airdrops that fully leverage Supra parallelization. /// TODO: Hide this until we bring back meaningful way to enforce burns fun create_untracked_collection( creator: &signer, diff --git a/aptos-move/framework/aptos-token-objects/sources/token.move b/aptos-move/framework/aptos-token-objects/sources/token.move index 06bd1d44066e4..d14e82ac1fd14 100644 --- a/aptos-move/framework/aptos-token-objects/sources/token.move +++ b/aptos-move/framework/aptos-token-objects/sources/token.move @@ -1,4 +1,4 @@ -/// This defines an object-based Token. The key differentiating features from the Aptos standard +/// This defines an object-based Token. The key differentiating features from the Supra standard /// token are: /// * Decoupled token ownership from token data. /// * Explicit data model for token metadata via adjacent resources @@ -56,7 +56,7 @@ module aptos_token_objects::token { /// Was populated until concurrent_token_v2_enabled feature flag was enabled. /// /// The name of the token, which should be unique within the collection; the length of name - /// should be smaller than 128, characters, eg: "Aptos Animal #1234" + /// should be smaller than 128, characters, eg: "Supra Animal #1234" name: String, // DEPRECATED /// The Uniform Resource Identifier (uri) pointing to the JSON file stored in off-chain @@ -73,7 +73,7 @@ module aptos_token_objects::token { /// Unique identifier within the collection, optional, 0 means unassigned index: AggregatorSnapshot, /// The name of the token, which should be unique within the collection; the length of name - /// should be smaller than 128, characters, eg: "Aptos Animal #1234" + /// should be smaller than 128, characters, eg: "Supra Animal #1234" name: DerivedStringSnapshot, } diff --git a/aptos-move/framework/aptos-token/sources/token.move b/aptos-move/framework/aptos-token/sources/token.move index c7b329fb58bd7..059882e969431 100644 --- a/aptos-move/framework/aptos-token/sources/token.move +++ b/aptos-move/framework/aptos-token/sources/token.move @@ -177,7 +177,7 @@ module aptos_token::token { struct TokenDataId has copy, drop, store { /// The address of the creator, eg: 0xcafe creator: address, - /// The name of collection; this is unique under the same account, eg: "Aptos Animal Collection" + /// The name of collection; this is unique under the same account, eg: "Supra Animal Collection" collection: String, /// The name of the token; this is the same as the name field of TokenData name: String, @@ -195,7 +195,7 @@ module aptos_token::token { uri: String, /// The denominator and numerator for calculating the royalty fee; it also contains payee account address for depositing the Royalty royalty: Royalty, - /// The name of the token, which should be unique within the collection; the length of name should be smaller than 128, characters, eg: "Aptos Animal #1234" + /// The name of the token, which should be unique within the collection; the length of name should be smaller than 128, characters, eg: "Supra Animal #1234" name: String, /// Describes this Token description: String, @@ -260,7 +260,7 @@ module aptos_token::token { /// Represent the collection metadata struct CollectionData has store { - /// A description for the token collection Eg: "Aptos Toad Overload" + /// A description for the token collection Eg: "Supra Toad Overload" description: String, /// The collection name, which should be unique among all collections by the creator; the name should also be smaller than 128 characters, eg: "Animal Collection" name: String, @@ -269,7 +269,7 @@ module aptos_token::token { /// The number of different TokenData entries in this collection supply: u64, /// If maximal is a non-zero value, the number of created TokenData entries should be smaller or equal to this maximum - /// If maximal is 0, Aptos doesn't track the supply of this collection, and there is no limit + /// If maximal is 0, Supra doesn't track the supply of this collection, and there is no limit maximum: u64, /// control which collectionData field is mutable mutability_config: CollectionMutabilityConfig, diff --git a/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs b/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs index a75cf4008e055..a2d053ca281bd 100644 --- a/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs +++ b/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs @@ -602,6 +602,20 @@ pub enum EntryFunctionCall { new_commission_percentage: u64, }, + /// Pre-condition: `cumulative_unlocked_fraction` should be zero, which would indicate that even + /// though there are principle stake holders, none of those have yet called `unlock` on the pool + /// thus it is ``safe'' to change the schedule + /// This is a temporary measure to allow Supra Foundation to change the schedule for those pools + /// there were initialized with ``dummy/default'' schedule. This method must be disabled + /// before external validators are allowed to join the validator set. + PboDelegationPoolUpdateUnlockingSchedule { + pool_address: AccountAddress, + unlock_numerators: Vec, + unlock_denominator: u64, + unlock_start_time: u64, + unlock_duration: u64, + }, + /// Withdraw `amount` of owned inactive stake from the delegation pool at `pool_address`. PboDelegationPoolWithdraw { pool_address: AccountAddress, @@ -1538,6 +1552,19 @@ impl EntryFunctionCall { PboDelegationPoolUpdateCommissionPercentage { new_commission_percentage, } => pbo_delegation_pool_update_commission_percentage(new_commission_percentage), + PboDelegationPoolUpdateUnlockingSchedule { + pool_address, + unlock_numerators, + unlock_denominator, + unlock_start_time, + unlock_duration, + } => pbo_delegation_pool_update_unlocking_schedule( + pool_address, + unlock_numerators, + unlock_denominator, + unlock_start_time, + unlock_duration, + ), PboDelegationPoolWithdraw { pool_address, amount, @@ -3466,6 +3493,39 @@ pub fn pbo_delegation_pool_update_commission_percentage( )) } +/// Pre-condition: `cumulative_unlocked_fraction` should be zero, which would indicate that even +/// though there are principle stake holders, none of those have yet called `unlock` on the pool +/// thus it is ``safe'' to change the schedule +/// This is a temporary measure to allow Supra Foundation to change the schedule for those pools +/// there were initialized with ``dummy/default'' schedule. This method must be disabled +/// before external validators are allowed to join the validator set. +pub fn pbo_delegation_pool_update_unlocking_schedule( + pool_address: AccountAddress, + unlock_numerators: Vec, + unlock_denominator: u64, + unlock_start_time: u64, + unlock_duration: u64, +) -> TransactionPayload { + TransactionPayload::EntryFunction(EntryFunction::new( + ModuleId::new( + AccountAddress::new([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, + ]), + ident_str!("pbo_delegation_pool").to_owned(), + ), + ident_str!("update_unlocking_schedule").to_owned(), + vec![], + vec![ + bcs::to_bytes(&pool_address).unwrap(), + bcs::to_bytes(&unlock_numerators).unwrap(), + bcs::to_bytes(&unlock_denominator).unwrap(), + bcs::to_bytes(&unlock_start_time).unwrap(), + bcs::to_bytes(&unlock_duration).unwrap(), + ], + )) +} + /// Withdraw `amount` of owned inactive stake from the delegation pool at `pool_address`. pub fn pbo_delegation_pool_withdraw( pool_address: AccountAddress, @@ -6078,6 +6138,24 @@ mod decoder { } } + pub fn pbo_delegation_pool_update_unlocking_schedule( + payload: &TransactionPayload, + ) -> Option { + if let TransactionPayload::EntryFunction(script) = payload { + Some( + EntryFunctionCall::PboDelegationPoolUpdateUnlockingSchedule { + pool_address: bcs::from_bytes(script.args().get(0)?).ok()?, + unlock_numerators: bcs::from_bytes(script.args().get(1)?).ok()?, + unlock_denominator: bcs::from_bytes(script.args().get(2)?).ok()?, + unlock_start_time: bcs::from_bytes(script.args().get(3)?).ok()?, + unlock_duration: bcs::from_bytes(script.args().get(4)?).ok()?, + }, + ) + } else { + None + } + } + pub fn pbo_delegation_pool_withdraw(payload: &TransactionPayload) -> Option { if let TransactionPayload::EntryFunction(script) = payload { Some(EntryFunctionCall::PboDelegationPoolWithdraw { @@ -7362,6 +7440,10 @@ static SCRIPT_FUNCTION_DECODER_MAP: once_cell::sync::Lazy + + + +## Function `multiply_u64_return_fixpoint32` + + + +
public fun multiply_u64_return_fixpoint32(val: u64, multiplier: fixed_point32::FixedPoint32): fixed_point32::FixedPoint32
+
+ + + +
+Implementation + + +
public fun multiply_u64_return_fixpoint32(val: u64, multiplier: FixedPoint32): FixedPoint32 {
+    // The product of two 64 bit values has 128 bits, so perform the
+    // multiplication with u128 types and keep the full 128 bit product
+    // to avoid losing accuracy.
+    let unscaled_product = (val as u128) * (multiplier.value as u128);
+    // Check whether the value is too large.
+    assert!(unscaled_product <= MAX_U64, EMULTIPLICATION);
+    create_from_raw_value((unscaled_product as u64))
+}
+
+ + +
diff --git a/aptos-move/framework/move-stdlib/sources/configs/features.move b/aptos-move/framework/move-stdlib/sources/configs/features.move index 8fbe0984859ae..d3800e3dabf88 100644 --- a/aptos-move/framework/move-stdlib/sources/configs/features.move +++ b/aptos-move/framework/move-stdlib/sources/configs/features.move @@ -1,5 +1,5 @@ -/// Defines feature flags for Aptos. Those are used in Aptos specific implementations of features in -/// the Move stdlib, the Aptos stdlib, and the Aptos framework. +/// Defines feature flags for Supra. Those are used in Supra specific implementations of features in +/// the Move stdlib, the Supra stdlib, and the Supra framework. /// /// ============================================================================================ /// Feature Flag Definitions diff --git a/aptos-move/framework/supra-framework/doc/block.md b/aptos-move/framework/supra-framework/doc/block.md index cd6b2ab647d8b..29402816443c2 100644 --- a/aptos-move/framework/supra-framework/doc/block.md +++ b/aptos-move/framework/supra-framework/doc/block.md @@ -427,7 +427,7 @@ This can only be called during Genesis.
public(friend) fun initialize(supra_framework: &signer, epoch_interval_microsecs: u64) {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(epoch_interval_microsecs > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
+    assert!(epoch_interval_microsecs != 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
 
     move_to<CommitHistory>(supra_framework, CommitHistory {
         max_capacity: 2000,
@@ -468,7 +468,7 @@ Initialize the commit history resource if it's not in genesis.
 
 
 
public fun initialize_commit_history(fx: &signer, max_capacity: u32) {
-    assert!(max_capacity > 0, error::invalid_argument(EZERO_MAX_CAPACITY));
+    assert!(max_capacity != 0, error::invalid_argument(EZERO_MAX_CAPACITY));
     move_to<CommitHistory>(fx, CommitHistory {
         max_capacity,
         next_idx: 0,
@@ -486,7 +486,7 @@ Initialize the commit history resource if it's not in genesis.
 ## Function `update_epoch_interval_microsecs`
 
 Update the epoch interval.
-Can only be called as part of the Supra governance proposal process established by the AptosGovernance module.
+Can only be called as part of the Supra governance proposal process established by the SupraGovernance module.
 
 
 
public fun update_epoch_interval_microsecs(supra_framework: &signer, new_epoch_interval: u64)
@@ -503,7 +503,7 @@ Can only be called as part of the Supra governance proposal process established
     new_epoch_interval: u64,
 ) acquires BlockResource {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(new_epoch_interval > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
+    assert!(new_epoch_interval != 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
 
     let block_resource = borrow_global_mut<BlockResource>(@supra_framework);
     let old_epoch_interval = block_resource.epoch_interval;
@@ -1088,6 +1088,70 @@ The number of new events created does not exceed MAX_U64.
 
 
 
+
+
+
+
+
schema BlockRequirement {
+    vm: signer;
+    hash: address;
+    epoch: u64;
+    round: u64;
+    proposer: address;
+    failed_proposer_indices: vector<u64>;
+    previous_block_votes_bitvec: vector<u8>;
+    timestamp: u64;
+    requires chain_status::is_operating();
+    requires system_addresses::is_vm(vm);
+    // This enforces high-level requirement 4:
+    requires proposer == @vm_reserved || stake::spec_is_current_epoch_validator(proposer);
+    requires (proposer == @vm_reserved) ==> (timestamp::spec_now_microseconds() == timestamp);
+    requires (proposer != @vm_reserved) ==> (timestamp::spec_now_microseconds() < timestamp);
+    requires exists<stake::ValidatorFees>(@supra_framework);
+    requires exists<CoinInfo<SupraCoin>>(@supra_framework);
+    include transaction_fee::RequiresCollectedFeesPerValueLeqBlockAptosSupply;
+    include staking_config::StakingRewardsConfigRequirement;
+}
+
+ + + + + + + +
schema Initialize {
+    supra_framework: signer;
+    epoch_interval_microsecs: u64;
+    let addr = signer::address_of(supra_framework);
+    // This enforces high-level requirement 2:
+    aborts_if addr != @supra_framework;
+    aborts_if epoch_interval_microsecs == 0;
+    aborts_if exists<BlockResource>(addr);
+    aborts_if exists<CommitHistory>(addr);
+    ensures exists<BlockResource>(addr);
+    ensures exists<CommitHistory>(addr);
+    ensures global<BlockResource>(addr).height == 0;
+}
+
+ + + + + + + +
schema NewEventHandle {
+    supra_framework: signer;
+    let addr = signer::address_of(supra_framework);
+    let account = global<account::Account>(addr);
+    aborts_if !exists<account::Account>(addr);
+    aborts_if account.guid_creation_num + 2 > MAX_U64;
+}
+
+ + + ### Function `update_epoch_interval_microsecs` diff --git a/aptos-move/framework/supra-framework/doc/code.md b/aptos-move/framework/supra-framework/doc/code.md index 36721ea20c942..22f315eb80d27 100644 --- a/aptos-move/framework/supra-framework/doc/code.md +++ b/aptos-move/framework/supra-framework/doc/code.md @@ -646,7 +646,7 @@ package. event::emit(PublishPackage { code_address: addr, - is_upgrade: upgrade_number > 0 + is_upgrade: upgrade_number != 0 }); // Request publish diff --git a/aptos-move/framework/supra-framework/doc/coin.md b/aptos-move/framework/supra-framework/doc/coin.md index 86bc5fadbc5ad..a3ef151ae9436 100644 --- a/aptos-move/framework/supra-framework/doc/coin.md +++ b/aptos-move/framework/supra-framework/doc/coin.md @@ -2224,13 +2224,13 @@ Collects a specified amount of coin form an account into aggregatable coin. account_addr, amount ); - let coin = if (coin_amount_to_collect > 0) { + let coin = if (coin_amount_to_collect != 0) { let coin_store = borrow_global_mut<CoinStore<CoinType>>(account_addr); extract(&mut coin_store.coin, coin_amount_to_collect) } else { zero() }; - if (fa_amount_to_collect > 0) { + if (fa_amount_to_collect != 0) { let store_addr = primary_fungible_store::primary_store_address( account_addr, option::destroy_some(paired_metadata<CoinType>()) @@ -2837,12 +2837,12 @@ Note: This bypasses CoinStore::frozen -- coins within a frozen CoinStore can be account_addr, amount ); - if (coin_amount_to_burn > 0) { + if (coin_amount_to_burn != 0) { let coin_store = borrow_global_mut<CoinStore<CoinType>>(account_addr); let coin_to_burn = extract(&mut coin_store.coin, coin_amount_to_burn); burn(coin_to_burn, burn_cap); }; - if (fa_amount_to_burn > 0) { + if (fa_amount_to_burn != 0) { fungible_asset::burn_from( borrow_paired_burn_ref(burn_cap), primary_fungible_store::primary_store(account_addr, option::destroy_some(paired_metadata<CoinType>())), @@ -3581,7 +3581,7 @@ Withdraw specified amount of coin CoinType from the si account_addr, amount ); - let withdrawn_coin = if (coin_amount_to_withdraw > 0) { + let withdrawn_coin = if (coin_amount_to_withdraw != 0) { let coin_store = borrow_global_mut<CoinStore<CoinType>>(account_addr); assert!( !coin_store.frozen, @@ -3602,7 +3602,7 @@ Withdraw specified amount of coin CoinType from the si } else { zero() }; - if (fa_amount_to_withdraw > 0) { + if (fa_amount_to_withdraw != 0) { let fa = primary_fungible_store::withdraw( account, option::destroy_some(paired_metadata<CoinType>()), @@ -4150,7 +4150,7 @@ Can only be updated by @supra_framework. -
include system_addresses::AbortsIfNotAptosFramework { account: supra_framework };
+
include system_addresses::AbortsIfNotSupraFramework { account: supra_framework };
 include aggregator_factory::CreateAggregatorInternalAbortsIf;
 
diff --git a/aptos-move/framework/supra-framework/doc/committee_map.md b/aptos-move/framework/supra-framework/doc/committee_map.md index ff00adc120f84..9146990f8d213 100644 --- a/aptos-move/framework/supra-framework/doc/committee_map.md +++ b/aptos-move/framework/supra-framework/doc/committee_map.md @@ -970,7 +970,7 @@ Get the committee's node vector and committee type let committee = simple_map::borrow(&committee_store.committee_map, &id); let (addrs, nodes) = simple_map::to_vec_pair(committee.map); let node_data_vec = vector::empty<NodeData>(); - while (vector::length(&addrs) > 0) { + while (vector::length(&addrs) != 0) { let addr = vector::pop_back(&mut addrs); let node_info = vector::pop_back(&mut nodes); let node_data = NodeData { @@ -1289,7 +1289,7 @@ This function is used to add a new committee to the store let committee_store = borrow_global_mut<CommitteeInfoStore>(com_store_addr); let node_infos = vector::empty<NodeInfo>(); let node_addresses_for_iteration = node_addresses; - while (vector::length(&node_addresses_for_iteration) > 0) { + while (vector::length(&node_addresses_for_iteration) != 0) { let ip_public_address = vector::pop_back(&mut ip_public_address); let node_public_key = vector::pop_back(&mut node_public_key); let network_public_key = vector::pop_back(&mut network_public_key); @@ -1402,7 +1402,7 @@ Add the committee in bulk ids_len == vector::length(&rpc_por_bulkt), error::invalid_argument(INVALID_COMMITTEE_NUMBERS) ); - while (vector::length(&ids) > 0) { + while (vector::length(&ids) != 0) { let id = vector::pop_back(&mut ids); let node_addresses = vector::pop_back(&mut node_addresses_bulk); let ip_public_address = vector::pop_back(&mut ip_public_address_bulk); @@ -1465,7 +1465,7 @@ Remove the committee from the store let (id, committee_info) = simple_map::remove(&mut committee_store.committee_map, &id); // Also remove the node_to_committee_map let (addrs, _) = simple_map::to_vec_pair(committee_info.map); - while (vector::length(&addrs) > 0) { + while (vector::length(&addrs) != 0) { let addr = vector::pop_back(&mut addrs); assert!( simple_map::contains_key(&committee_store.node_to_committee_map, &addr), @@ -1508,7 +1508,7 @@ Remove the committee in bulk com_store_addr: address, ids: vector<u64> ) acquires CommitteeInfoStore, SupraCommitteeEventHandler { - while (vector::length(&ids) > 0) { + while (vector::length(&ids) != 0) { let id = vector::pop_back(&mut ids); remove_committee(owner_signer, com_store_addr, id); } @@ -1644,7 +1644,7 @@ Upsert nodes to the committee vector::length(&ids) == vector::length(&rpc_port), error::invalid_argument(INVALID_COMMITTEE_NUMBERS) ); - while (vector::length(&ids) > 0) { + while (vector::length(&ids) != 0) { let id = vector::pop_back(&mut ids); let node_address = vector::pop_back(&mut node_addresses); let ip_public_address = vector::pop_back(&mut ip_public_address); diff --git a/aptos-move/framework/supra-framework/doc/consensus_config.md b/aptos-move/framework/supra-framework/doc/consensus_config.md index a335ee955de29..b4374a973d71b 100644 --- a/aptos-move/framework/supra-framework/doc/consensus_config.md +++ b/aptos-move/framework/supra-framework/doc/consensus_config.md @@ -95,7 +95,7 @@ Publishes the ConsensusConfig config.
public(friend) fun initialize(supra_framework: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
     move_to(supra_framework, ConsensusConfig { config });
 }
 
@@ -127,7 +127,7 @@ TODO: update all the tests that reference this function, then disable this funct
public fun set(account: &signer, config: vector<u8>) acquires ConsensusConfig {
     system_addresses::assert_supra_framework(account);
     chain_status::assert_genesis();
-    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
 
     let config_ref = &mut borrow_global_mut<ConsensusConfig>(@supra_framework).config;
     *config_ref = config;
@@ -164,7 +164,7 @@ supra_framework::supra_governance::reconfigure(&framework_signer);
 
 
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(account);
-    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
     std::config_buffer::upsert<ConsensusConfig>(ConsensusConfig {config});
 }
 
@@ -279,7 +279,7 @@ Only used in reconfigurations to apply the pending set. diff --git a/aptos-move/framework/supra-framework/doc/evm_config.md b/aptos-move/framework/supra-framework/doc/evm_config.md index d0251fbd79c5b..6a60a5adffc31 100644 --- a/aptos-move/framework/supra-framework/doc/evm_config.md +++ b/aptos-move/framework/supra-framework/doc/evm_config.md @@ -7,6 +7,7 @@ - [Resource `EvmConfig`](#0x1_evm_config_EvmConfig) - [Constants](#@Constants_0) +- [Function `initialize`](#0x1_evm_config_initialize) - [Function `set_for_next_epoch`](#0x1_evm_config_set_for_next_epoch) - [Function `on_new_epoch`](#0x1_evm_config_on_new_epoch) - [Specification](#@Specification_1) @@ -17,6 +18,7 @@
use 0x1::config_buffer;
 use 0x1::error;
 use 0x1::system_addresses;
+use 0x1::vector;
 
@@ -25,6 +27,7 @@ ## Resource `EvmConfig` +The struct stores the on-chain EVM configuration.
struct EvmConfig has drop, store, key
@@ -63,11 +66,38 @@ The provided on chain config bytes are empty or invalid
 
 
 
+
+
+## Function `initialize`
+
+Publishes the EvmConfig config.
+
+
+
public(friend) fun initialize(supra_framework: &signer, config: vector<u8>)
+
+ + + +
+Implementation + + +
public(friend) fun initialize(supra_framework: &signer, config: vector<u8>) {
+    system_addresses::assert_supra_framework(supra_framework);
+    assert!(!vector::is_empty(&config), error::invalid_argument(EINVALID_CONFIG));
+    move_to(supra_framework, EvmConfig { config });
+}
+
+ + + +
+ ## Function `set_for_next_epoch` -This can be called by on-chain governance to update on-chain consensus configs for the next epoch. +This can be called by on-chain governance to update on-chain evm configs for the next epoch. Example usage: ``` supra_framework::evm_config::set_for_next_epoch(&framework_signer, some_config_bytes); @@ -86,7 +116,7 @@ supra_framework::supra_governance::reconfigure(&framework_signer);
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(account);
-    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(!vector::is_empty(&config), error::invalid_argument(EINVALID_CONFIG));
     std::config_buffer::upsert<EvmConfig>(EvmConfig {config});
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/execution_config.md b/aptos-move/framework/supra-framework/doc/execution_config.md index 25625078d0474..019027dceed44 100644 --- a/aptos-move/framework/supra-framework/doc/execution_config.md +++ b/aptos-move/framework/supra-framework/doc/execution_config.md @@ -93,7 +93,7 @@ TODO: update all the tests that reference this function, then disable this funct system_addresses::assert_supra_framework(account); chain_status::assert_genesis(); - assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG)); if (exists<ExecutionConfig>(@supra_framework)) { let config_ref = &mut borrow_global_mut<ExecutionConfig>(@supra_framework).config; @@ -133,7 +133,7 @@ supra_framework::aptos_governance::reconfigure(&framework_signer);
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(account);
-    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
     config_buffer::upsert(ExecutionConfig { config });
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/gas_schedule.md b/aptos-move/framework/supra-framework/doc/gas_schedule.md index 60bb13b62341b..8af2b941e8668 100644 --- a/aptos-move/framework/supra-framework/doc/gas_schedule.md +++ b/aptos-move/framework/supra-framework/doc/gas_schedule.md @@ -455,7 +455,7 @@ Only used in reconfigurations to apply the pending set_gas_schedule. @@ -504,7 +504,7 @@ Only used in reconfigurations to apply the pending signer::address_of(supra_framework); // This enforces high-level requirement 1: -include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; +include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; // This enforces high-level requirement 3: aborts_if len(gas_schedule_blob) == 0; aborts_if exists<GasScheduleV2>(addr); @@ -531,7 +531,7 @@ Only used in reconfigurations to apply the pending transaction_fee::RequiresCollectedFeesPerValueLeqBlockAptosSupply; include staking_config::StakingRewardsConfigRequirement; // This enforces high-level requirement 2: -include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; +include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; // This enforces high-level requirement 3: aborts_if len(gas_schedule_blob) == 0; let new_gas_schedule = util::spec_from_bytes<GasScheduleV2>(gas_schedule_blob); @@ -555,7 +555,7 @@ Only used in reconfigurations to apply the pending system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; +
include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework };
 include config_buffer::SetForNextEpochAbortsIf {
     account: supra_framework,
     config: gas_schedule_blob
@@ -578,7 +578,7 @@ Only used in reconfigurations to apply the pending system_addresses::AbortsIfNotAptosFramework{ account: supra_framework };
+
include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework };
 include config_buffer::SetForNextEpochAbortsIf {
     account: supra_framework,
     config: new_gas_schedule_blob
@@ -623,7 +623,7 @@ Only used in reconfigurations to apply the pending stake::ValidatorFees>(@supra_framework);
 requires exists<CoinInfo<SupraCoin>>(@supra_framework);
-include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework };
+include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework };
 include transaction_fee::RequiresCollectedFeesPerValueLeqBlockAptosSupply;
 include staking_config::StakingRewardsConfigRequirement;
 aborts_if !exists<StorageGasConfig>(@supra_framework);
@@ -633,7 +633,7 @@ Only used in reconfigurations to apply the pending system_addresses::AbortsIfNotAptosFramework{ account: supra_framework };
+
include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework };
 aborts_if !exists<storage_gas::StorageGasConfig>(@supra_framework);
 
@@ -650,7 +650,7 @@ Only used in reconfigurations to apply the pending system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; +
include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework };
 aborts_if !exists<storage_gas::StorageGasConfig>(@supra_framework);
 
diff --git a/aptos-move/framework/supra-framework/doc/genesis.md b/aptos-move/framework/supra-framework/doc/genesis.md index 8823b5d9a6d32..2b89f6a3e56f8 100644 --- a/aptos-move/framework/supra-framework/doc/genesis.md +++ b/aptos-move/framework/supra-framework/doc/genesis.md @@ -56,6 +56,7 @@ use 0x1::consensus_config; use 0x1::create_signer; use 0x1::error; +use 0x1::evm_config; use 0x1::execution_config; use 0x1::features; use 0x1::fixed_point32; @@ -548,10 +549,10 @@ ## Function `initialize` -Genesis step 1: Initialize aptos framework account and core modules on chain. +Genesis step 1: Initialize supra framework account and core modules on chain. -
fun initialize(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, genesis_timestamp_in_microseconds: u64)
+
fun initialize(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, genesis_timestamp_in_microseconds: u64, evm_config: vector<u8>)
 
@@ -576,12 +577,13 @@ Genesis step 1: Initialize aptos framework account and core modules on chain. rewards_rate_denominator: u64, voting_power_increase_limit: u64, genesis_timestamp_in_microseconds: u64, + evm_config: vector<u8>, ) { - // Initialize the aptos framework account. This is the account where system resources and modules will be + // Initialize the supra framework account. This is the account where system resources and modules will be // deployed to. This will be entirely managed by on-chain governance and no entities have the key or privileges // to use this account. let (supra_framework_account, supra_framework_signer_cap) = account::create_framework_reserved_account(@supra_framework); - // Initialize account configs on aptos framework account. + // Initialize account configs on supra framework account. account::initialize(&supra_framework_account); transaction_validation::initialize( @@ -595,7 +597,7 @@ Genesis step 1: Initialize aptos framework account and core modules on chain. // Give the decentralized on-chain governance control over the core framework account. supra_governance::store_signer_cap(&supra_framework_account, @supra_framework, supra_framework_signer_cap); - // put reserved framework reserved accounts under aptos governance + // put reserved framework reserved accounts under supra governance let framework_reserved_addresses = vector<address>[@0x2, @0x3, @0x4, @0x5, @0x6, @0x7, @0x8, @0x9, @0xa]; while (!vector::is_empty(&framework_reserved_addresses)) { let address = vector::pop_back<address>(&mut framework_reserved_addresses); @@ -630,6 +632,7 @@ Genesis step 1: Initialize aptos framework account and core modules on chain. block::initialize(&supra_framework_account, epoch_interval_microsecs); state_storage::initialize(&supra_framework_account); timestamp::set_time_has_started(&supra_framework_account, genesis_timestamp_in_microseconds); + evm_config::initialize(&supra_framework_account, evm_config); }
@@ -797,17 +800,23 @@ If it exists, it just returns the signer. Implementation -
fun create_multiple_multisig_accounts_with_schema(supra_framework: &signer,
-owner: address, additional_owners: vector<address>,num_signatures_required:u64,metadata_keys:vector<String>,metadata_values:vector<vector<u8>>,
-timeout_duration:u64, balance:u64, num_of_accounts: u32): vector<address> {
-
+
fun create_multiple_multisig_accounts_with_schema(
+    supra_framework: &signer,
+    owner: address,
+    additional_owners: vector<address>,
+    num_signatures_required:u64,
+    metadata_keys:vector<String>,
+    metadata_values:vector<vector<u8>>,
+    timeout_duration:u64,
+    balance:u64,
+    num_of_accounts: u32
+): vector<address> {
     let counter = 0;
     let result = vector::empty();
     while (counter < num_of_accounts) {
         let account_addr = create_multisig_account_with_balance(supra_framework, owner, additional_owners,
                             num_signatures_required,metadata_keys,metadata_values,timeout_duration,balance);
         vector::push_back(&mut result,account_addr);
-        account::increment_sequence_number(owner);
         counter = counter + 1;
     };
     result
@@ -833,20 +842,25 @@ timeout_duration:u64, balance:u64, num_of_accounts: u32): create_multisig_account_with_balance(supra_framework: &signer, owner: address, additional_owners: vector<address>,
-                            num_signatures_required:u64, metadata_keys: vector<String>,
-                            metadata_values: vector<vector<u8>>, timeout_duration: u64, balance:u64 ) : address {
-
-
+
fun create_multisig_account_with_balance(
+    supra_framework: &signer,
+    owner: address,
+    additional_owners: vector<address>,
+    num_signatures_required:u64,
+    metadata_keys: vector<String>,
+    metadata_values: vector<vector<u8>>,
+    timeout_duration: u64,
+    balance:u64,
+): address {
     assert!(account::exists_at(owner),error::invalid_argument(EACCOUNT_DOES_NOT_EXIST));
     assert!(vector::all(&additional_owners,|ao_addr|{account::exists_at(*ao_addr)}),error::invalid_argument(EACCOUNT_DOES_NOT_EXIST));
     let addr = multisig_account::get_next_multisig_account_address(owner);
     let owner_signer = create_signer(owner);
     multisig_account::create_with_owners(&owner_signer,additional_owners,num_signatures_required,metadata_keys,metadata_values,timeout_duration);
     supra_coin::mint(supra_framework,addr,balance);
+    account::increment_sequence_number(owner);
     addr
-
-    }
+}
 
@@ -1115,7 +1129,7 @@ encoded in a single BCS byte array. delegation_percentage: u64, ) { let unique_accounts: vector<address> = vector::empty(); - assert!(delegation_percentage > 0 && delegation_percentage <= 100, error::invalid_argument(EPERCENTAGE_INVALID)); + assert!(delegation_percentage != 0 && delegation_percentage <= 100, error::invalid_argument(EPERCENTAGE_INVALID)); vector::for_each_ref(&pbo_delegator_configs, |pbo_delegator_config| { let pbo_delegator_config: &PboDelegatorConfiguration = pbo_delegator_config; assert!(!vector::contains(&unique_accounts,&pbo_delegator_config.delegator_config.owner_address), @@ -1149,7 +1163,7 @@ encoded in a single BCS byte array. pbo_delegator_config: &PboDelegatorConfiguration, delegation_percentage: u64, ) { - assert!(delegation_percentage>0 && delegation_percentage<=100,error::invalid_argument(EPERCENTAGE_INVALID)); + assert!(delegation_percentage != 0 && delegation_percentage<=100,error::invalid_argument(EPERCENTAGE_INVALID)); let unique_accounts:vector<address> = vector::empty(); vector::for_each_ref(&pbo_delegator_config.delegator_config.delegator_addresses, |delegator_address| { let delegator_address: &address = delegator_address; @@ -1258,9 +1272,9 @@ encoded in a single BCS byte array. let pool_config: &VestingPoolsMap = pool_config; let schedule = vector::empty(); let schedule_length = vector::length(&pool_config.vesting_numerators); - assert!(schedule_length > 0, error::invalid_argument(EVESTING_SCHEDULE_IS_ZERO)); - assert!(pool_config.vesting_denominator > 0, error::invalid_argument(EDENOMINATOR_IS_ZERO)); - assert!(pool_config.vpool_locking_percentage > 0 && pool_config.vpool_locking_percentage <=100 , + assert!(schedule_length != 0, error::invalid_argument(EVESTING_SCHEDULE_IS_ZERO)); + assert!(pool_config.vesting_denominator != 0, error::invalid_argument(EDENOMINATOR_IS_ZERO)); + assert!(pool_config.vpool_locking_percentage != 0 && pool_config.vpool_locking_percentage <=100 , error::invalid_argument(EPERCENTAGE_INVALID)); //check the sum of numerator are <= denominator. let sum = vector::fold(pool_config.vesting_numerators,0,|acc, x| acc + x); @@ -1276,7 +1290,7 @@ encoded in a single BCS byte array. let j=0; while (j < schedule_length) { let numerator = *vector::borrow(&pool_config.vesting_numerators,j); - assert!(numerator > 0, error::invalid_argument(ENUMERATOR_IS_ZERO)); + assert!(numerator != 0, error::invalid_argument(ENUMERATOR_IS_ZERO)); let event = fixed_point32::create_from_rational(numerator,pool_config.vesting_denominator); vector::push_back(&mut schedule,event); j = j + 1; @@ -1290,7 +1304,7 @@ encoded in a single BCS byte array. let buy_ins = simple_map::create(); let num_shareholders = vector::length(&pool_config.shareholders); - assert!(num_shareholders > 0, error::invalid_argument(ENO_SHAREHOLDERS)); + assert!(num_shareholders != 0, error::invalid_argument(ENO_SHAREHOLDERS)); let j = 0; while (j < num_shareholders) { let shareholder = *vector::borrow(&pool_config.shareholders,j); @@ -1392,7 +1406,7 @@ The last step of genesis.
#[verify_only]
-fun initialize_for_verification(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, supra_framework: &signer, voting_duration_secs: u64, supra_min_voting_threshold: u64, voters: vector<address>, accounts: vector<genesis::AccountMap>, employee_vesting_start: u64, employee_vesting_period_duration: u64, employees: vector<genesis::EmployeeAccountMap>, validators: vector<genesis::ValidatorConfigurationWithCommission>)
+fun initialize_for_verification(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, evm_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, supra_framework: &signer, voting_duration_secs: u64, supra_min_voting_threshold: u64, voters: vector<address>, accounts: vector<genesis::AccountMap>, employee_vesting_start: u64, employee_vesting_period_duration: u64, employees: vector<genesis::EmployeeAccountMap>, validators: vector<genesis::ValidatorConfigurationWithCommission>)
 
@@ -1408,6 +1422,7 @@ The last step of genesis. consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, + evm_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, @@ -1444,6 +1459,8 @@ The last step of genesis. rewards_rate_denominator, voting_power_increase_limit, 0, + evm_config, + ); features::change_feature_flags_for_verification(supra_framework, vector[1, 2, 11], vector[]); initialize_supra_coin(supra_framework); @@ -1492,7 +1509,7 @@ The last step of genesis. 2 -Addresses ranging from 0x0 - 0xa should be reserved for the framework and part of aptos governance. +Addresses ranging from 0x0 - 0xa should be reserved for the framework and part of supra governance. Critical The function genesis::initialize calls account::create_framework_reserved_account for addresses 0x0, 0x2, 0x3, 0x4, ..., 0xa which creates an account and authentication_key for them. This should be formally verified by ensuring that at the beginning of the genesis::initialize function no Account resource exists for the reserved addresses, and at the end of the function, an Account resource exists. Formally verified via initialize. @@ -1541,7 +1558,7 @@ The last step of genesis. ### Function `initialize` -
fun initialize(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, genesis_timestamp_in_microseconds: u64)
+
fun initialize(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, genesis_timestamp_in_microseconds: u64, evm_config: vector<u8>)
 
@@ -1735,37 +1752,6 @@ The last step of genesis. - - - - -
schema InitalizeRequires {
-    execution_config: vector<u8>;
-    requires !exists<account::Account>(@supra_framework);
-    requires chain_status::is_operating();
-    requires len(execution_config) > 0;
-    requires exists<staking_config::StakingRewardsConfig>(@supra_framework);
-    requires exists<stake::ValidatorFees>(@supra_framework);
-    requires exists<coin::CoinInfo<SupraCoin>>(@supra_framework);
-    include CompareTimeRequires;
-    include transaction_fee::RequiresCollectedFeesPerValueLeqBlockAptosSupply;
-}
-
- - - - - - - -
schema CompareTimeRequires {
-    let staking_rewards_config = global<staking_config::StakingRewardsConfig>(@supra_framework);
-    requires staking_rewards_config.last_rewards_rate_period_start_in_secs <= timestamp::spec_now_seconds();
-}
-
- - - ### Function `set_genesis_end` @@ -1795,7 +1781,7 @@ The last step of genesis.
#[verify_only]
-fun initialize_for_verification(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, supra_framework: &signer, voting_duration_secs: u64, supra_min_voting_threshold: u64, voters: vector<address>, accounts: vector<genesis::AccountMap>, employee_vesting_start: u64, employee_vesting_period_duration: u64, employees: vector<genesis::EmployeeAccountMap>, validators: vector<genesis::ValidatorConfigurationWithCommission>)
+fun initialize_for_verification(gas_schedule: vector<u8>, chain_id: u8, initial_version: u64, consensus_config: vector<u8>, execution_config: vector<u8>, supra_config: vector<u8>, evm_config: vector<u8>, epoch_interval_microsecs: u64, minimum_stake: u64, maximum_stake: u64, recurring_lockup_duration_secs: u64, allow_validator_set_change: bool, rewards_rate: u64, rewards_rate_denominator: u64, voting_power_increase_limit: u64, supra_framework: &signer, voting_duration_secs: u64, supra_min_voting_threshold: u64, voters: vector<address>, accounts: vector<genesis::AccountMap>, employee_vesting_start: u64, employee_vesting_period_duration: u64, employees: vector<genesis::EmployeeAccountMap>, validators: vector<genesis::ValidatorConfigurationWithCommission>)
 
diff --git a/aptos-move/framework/supra-framework/doc/governance_proposal.md b/aptos-move/framework/supra-framework/doc/governance_proposal.md index 58f51df70ca84..3b6267e9858bb 100644 --- a/aptos-move/framework/supra-framework/doc/governance_proposal.md +++ b/aptos-move/framework/supra-framework/doc/governance_proposal.md @@ -3,9 +3,9 @@ # Module `0x1::governance_proposal` -Define the GovernanceProposal that will be used as part of on-chain governance by AptosGovernance. +Define the GovernanceProposal that will be used as part of on-chain governance by SupraGovernance. -This is separate from the AptosGovernance module to avoid circular dependency between AptosGovernance and Stake. +This is separate from the SupraGovernance module to avoid circular dependency between SupraGovernance and Stake. - [Struct `GovernanceProposal`](#0x1_governance_proposal_GovernanceProposal) @@ -53,7 +53,7 @@ This is separate from the AptosGovernance module to avoid circular dependency be ## Function `create_proposal` -Create and return a GovernanceProposal resource. Can only be called by AptosGovernance +Create and return a GovernanceProposal resource. Can only be called by SupraGovernance
public(friend) fun create_proposal(): governance_proposal::GovernanceProposal
@@ -78,7 +78,7 @@ Create and return a GovernanceProposal resource. Can only be called by AptosGove
 
 ## Function `create_empty_proposal`
 
-Useful for AptosGovernance to create an empty proposal as proof.
+Useful for SupraGovernance to create an empty proposal as proof.
 
 
 
public(friend) fun create_empty_proposal(): governance_proposal::GovernanceProposal
@@ -135,7 +135,7 @@ Useful for AptosGovernance to create an empty proposal as proof.
 
 
 2
-The governance proposal module should only be accessible to the aptos governance.
+The governance proposal module should only be accessible to the supra governance.
 Medium
 Both create_proposal and create_empty_proposal functions are only available to the friend module supra_framework::supra_governance.
 Enforced via friend module relationship.
diff --git a/aptos-move/framework/supra-framework/doc/multisig_account.md b/aptos-move/framework/supra-framework/doc/multisig_account.md
index 5c0091e90f434..5a7fabf9ea7e3 100644
--- a/aptos-move/framework/supra-framework/doc/multisig_account.md
+++ b/aptos-move/framework/supra-framework/doc/multisig_account.md
@@ -1693,7 +1693,7 @@ Return the transaction with the given transaction id.
 ): MultisigTransaction acquires MultisigAccount {
     let multisig_account_resource = borrow_global<MultisigAccount>(multisig_account);
     assert!(
-        sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number,
+        sequence_number != 0 && sequence_number < multisig_account_resource.next_sequence_number,
         error::invalid_argument(EINVALID_SEQUENCE_NUMBER),
     );
     *table::borrow(&multisig_account_resource.transactions, sequence_number)
@@ -2033,7 +2033,7 @@ Return a bool tuple indicating whether an owner has voted and if so, whether the
     multisig_account: address, sequence_number: u64, owner: address): (bool, bool) acquires MultisigAccount {
     let multisig_account_resource = borrow_global_mut<MultisigAccount>(multisig_account);
     assert!(
-        sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number,
+        sequence_number != 0 && sequence_number < multisig_account_resource.next_sequence_number,
         error::invalid_argument(EINVALID_SEQUENCE_NUMBER),
     );
     let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number);
@@ -2387,7 +2387,7 @@ be an owner after the vanity multisig address has been secured.
 ) acquires MultisigAccount {
     assert!(features::multisig_accounts_enabled(), error::unavailable(EMULTISIG_ACCOUNTS_NOT_ENABLED_YET));
     assert!(
-        num_signatures_required > 0 && num_signatures_required <= vector::length(&owners),
+        num_signatures_required != 0 && num_signatures_required <= vector::length(&owners),
         error::invalid_argument(EINVALID_SIGNATURES_REQUIRED),
     );
 
@@ -2882,7 +2882,7 @@ Create a multisig transaction, which will have one approval initially (from the
     multisig_account: address,
     payload: vector<u8>,
 ) acquires MultisigAccount {
-    assert!(vector::length(&payload) > 0, error::invalid_argument(EPAYLOAD_CANNOT_BE_EMPTY));
+    assert!(vector::length(&payload) != 0, error::invalid_argument(EPAYLOAD_CANNOT_BE_EMPTY));
 
     assert_multisig_account_exists(multisig_account);
     assert_is_owner(owner, multisig_account);
@@ -3502,7 +3502,7 @@ This function is private so no other code can call this beside the VM itself as
 ) {
     if (features::multisig_v2_enhancement_feature_enabled()) {
         assert!(
-            available_transaction_queue_capacity(multisig_account) > 0,
+            available_transaction_queue_capacity(multisig_account) != 0,
             error::invalid_state(EMAX_PENDING_TRANSACTIONS_EXCEEDED)
         );
     };
@@ -3832,7 +3832,7 @@ This function is private so no other code can call this beside the VM itself as
 
inline fun assert_valid_sequence_number(multisig_account: address, sequence_number: u64) acquires MultisigAccount {
     let multisig_account_resource = borrow_global<MultisigAccount>(multisig_account);
     assert!(
-        sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number,
+        sequence_number != 0 && sequence_number < multisig_account_resource.next_sequence_number,
         error::invalid_argument(EINVALID_SEQUENCE_NUMBER),
     );
 }
@@ -3903,7 +3903,7 @@ Add new owners, remove owners to remove, update signatures required.
         )
     });
     // If new owners provided, try to add them and emit an event.
-    if (vector::length(&new_owners) > 0) {
+    if (vector::length(&new_owners) != 0) {
         vector::append(&mut multisig_account_ref_mut.owners, new_owners);
         validate_owners(
             &multisig_account_ref_mut.owners,
@@ -3918,7 +3918,7 @@ Add new owners, remove owners to remove, update signatures required.
         );
     };
     // If owners to remove provided, try to remove them.
-    if (vector::length(&owners_to_remove) > 0) {
+    if (vector::length(&owners_to_remove) != 0) {
         let owners_ref_mut = &mut multisig_account_ref_mut.owners;
         let owners_removed = vector[];
         vector::for_each_ref(&owners_to_remove, |owner_to_remove_ref| {
@@ -3932,7 +3932,7 @@ Add new owners, remove owners to remove, update signatures required.
             }
         });
         // Only emit event if owner(s) actually removed.
-        if (vector::length(&owners_removed) > 0) {
+        if (vector::length(&owners_removed) != 0) {
             if (std::features::module_event_migration_enabled()) {
                 emit(
                     RemoveOwners { multisig_account: multisig_address, owners_removed }
@@ -3949,7 +3949,7 @@ Add new owners, remove owners to remove, update signatures required.
         let new_num_signatures_required =
             option::extract(&mut optional_new_num_signatures_required);
         assert!(
-            new_num_signatures_required > 0,
+            new_num_signatures_required != 0,
             error::invalid_argument(EINVALID_SIGNATURES_REQUIRED)
         );
         let old_num_signatures_required =
diff --git a/aptos-move/framework/supra-framework/doc/multisig_voting.md b/aptos-move/framework/supra-framework/doc/multisig_voting.md
index 5cbc4038e75a6..26a2d464452e8 100644
--- a/aptos-move/framework/supra-framework/doc/multisig_voting.md
+++ b/aptos-move/framework/supra-framework/doc/multisig_voting.md
@@ -943,7 +943,7 @@ resolve this proposal.
 ): u64 acquires VotingForum {
 
     // Make sure the execution script's hash is not empty.
-    assert!(vector::length(&execution_hash) > 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH));
+    assert!(vector::length(&execution_hash) != 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH));
 
     assert!(min_vote_threshold > 1, error::invalid_argument(ETHRESHOLD_MUST_BE_GREATER_THAN_ONE));
 
diff --git a/aptos-move/framework/supra-framework/doc/overview.md b/aptos-move/framework/supra-framework/doc/overview.md
index 79f5b45427cf3..73400c445e290 100644
--- a/aptos-move/framework/supra-framework/doc/overview.md
+++ b/aptos-move/framework/supra-framework/doc/overview.md
@@ -28,6 +28,7 @@ This is the reference documentation of the Supra framework.
 -  [`0x1::dispatchable_fungible_asset`](dispatchable_fungible_asset.md#0x1_dispatchable_fungible_asset)
 -  [`0x1::dkg`](dkg.md#0x1_dkg)
 -  [`0x1::event`](event.md#0x1_event)
+-  [`0x1::evm_config`](evm_config.md#0x1_evm_config)
 -  [`0x1::execution_config`](execution_config.md#0x1_execution_config)
 -  [`0x1::function_info`](function_info.md#0x1_function_info)
 -  [`0x1::fungible_asset`](fungible_asset.md#0x1_fungible_asset)
diff --git a/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md b/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md
index f46534674a0f6..2c81bf8676847 100644
--- a/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md
+++ b/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md
@@ -131,6 +131,7 @@ transferred to A
 -  [Struct `UnlockStakeEvent`](#0x1_pbo_delegation_pool_UnlockStakeEvent)
 -  [Struct `WithdrawStakeEvent`](#0x1_pbo_delegation_pool_WithdrawStakeEvent)
 -  [Struct `DistributeCommissionEvent`](#0x1_pbo_delegation_pool_DistributeCommissionEvent)
+-  [Struct `UnlockScheduleUpdated`](#0x1_pbo_delegation_pool_UnlockScheduleUpdated)
 -  [Struct `DistributeCommission`](#0x1_pbo_delegation_pool_DistributeCommission)
 -  [Struct `DelegatorReplacemendEvent`](#0x1_pbo_delegation_pool_DelegatorReplacemendEvent)
 -  [Struct `VoteEvent`](#0x1_pbo_delegation_pool_VoteEvent)
@@ -907,6 +908,58 @@ This struct should be stored in the delegation pool resource account.
 
 
 
+
+
+
+
+## Struct `UnlockScheduleUpdated`
+
+
+
+
#[event]
+struct UnlockScheduleUpdated has drop, store
+
+ + + +
+Fields + + +
+
+pool_address: address +
+
+ +
+
+unlock_numerators: vector<u64> +
+
+ +
+
+unlock_denominator: u64 +
+
+ +
+
+unlock_start_time: u64 +
+
+ +
+
+unlock_duration: u64 +
+
+ +
+
+ +
@@ -1578,6 +1631,15 @@ Commission percentage change is too late in this lockup period, and should be do + + + + +
const EUNLOCKING_ALREADY_STARTED: u64 = 41;
+
+ + + Vector length is not the same. @@ -2369,7 +2431,7 @@ Ownership over setting the operator/voter is granted to owner who h // initialize the principle stake table let principle_stake_table = table::new<address, u64>(); // initialize the principle stake table - while (vector::length(&delegator_address) > 0) { + while (vector::length(&delegator_address) != 0) { let delegator = vector::pop_back(&mut delegator_address); let stake = vector::pop_back(&mut principle_stake); table::add(&mut principle_stake_table, delegator, stake); @@ -2413,7 +2475,7 @@ Ownership over setting the operator/voter is granted to owner who h move_to(owner, DelegationPoolOwnership { pool_address }); // Add stake to each delegator - while (vector::length(&delegator_address_copy) > 0) { + while (vector::length(&delegator_address_copy) != 0) { let delegator = vector::pop_back(&mut delegator_address_copy); let stake = vector::pop_back(&mut principle_stake_copy); add_stake_initialization(delegator, pool_address, stake); @@ -3711,7 +3773,6 @@ accurate as time passes last_unlocked_period = last_unlocked_period + 1; }; - unlock_schedule.cumulative_unlocked_fraction = cfraction; unlock_schedule.last_unlock_period = unlock_periods_passed; let unlockable_amount = cached_unlockable_balance(delegator_addr, pool_address); diff --git a/aptos-move/framework/supra-framework/doc/reconfiguration.md b/aptos-move/framework/supra-framework/doc/reconfiguration.md index 68d2cc9e1833e..136ac752db801 100644 --- a/aptos-move/framework/supra-framework/doc/reconfiguration.md +++ b/aptos-move/framework/supra-framework/doc/reconfiguration.md @@ -611,10 +611,10 @@ reconfiguration event. Make sure the signer address is @supra_framework. - + -
schema AbortsIfNotAptosFramework {
+
schema AbortsIfNotSupraFramework {
     supra_framework: &signer;
     let addr = signer::address_of(supra_framework);
     aborts_if !system_addresses::is_supra_framework_address(addr);
@@ -637,7 +637,7 @@ Already exists in framework account.
 Guid_creation_num should be 2 according to logic.
 
 
-
include AbortsIfNotAptosFramework;
+
include AbortsIfNotSupraFramework;
 let addr = signer::address_of(supra_framework);
 let post config = global<Configuration>(@supra_framework);
 requires exists<Account>(addr);
@@ -670,7 +670,7 @@ Guid_creation_num should be 2 according to logic.
 
 
 
-
include AbortsIfNotAptosFramework;
+
include AbortsIfNotSupraFramework;
 aborts_if exists<DisableReconfiguration>(@supra_framework);
 ensures exists<DisableReconfiguration>(@supra_framework);
 
@@ -689,7 +689,7 @@ Guid_creation_num should be 2 according to logic. Make sure the caller is admin and check the resource DisableReconfiguration. -
include AbortsIfNotAptosFramework;
+
include AbortsIfNotSupraFramework;
 aborts_if !exists<DisableReconfiguration>(@supra_framework);
 ensures !exists<DisableReconfiguration>(@supra_framework);
 
diff --git a/aptos-move/framework/supra-framework/doc/stake.md b/aptos-move/framework/supra-framework/doc/stake.md index 6f8c32f667cc2..113f9e9e709dc 100644 --- a/aptos-move/framework/supra-framework/doc/stake.md +++ b/aptos-move/framework/supra-framework/doc/stake.md @@ -2462,7 +2462,7 @@ to set later. validator_index: 0, }); - if (initial_stake_amount > 0) { + if (initial_stake_amount != 0) { add_stake(owner, initial_stake_amount); }; @@ -3576,7 +3576,7 @@ Can only be called by the operator of the validator/staking pool. assert!(option::is_some(&maybe_active_index), error::invalid_state(ENOT_VALIDATOR)); let validator_info = vector::swap_remove( &mut validator_set.active_validators, option::extract(&mut maybe_active_index)); - assert!(vector::length(&validator_set.active_validators) > 0, error::invalid_state(ELAST_VALIDATOR)); + assert!(vector::length(&validator_set.active_validators) != 0, error::invalid_state(ELAST_VALIDATOR)); vector::push_back(&mut validator_set.pending_inactive, validator_info); if (std::features::module_event_migration_enabled()) { @@ -3928,7 +3928,7 @@ Return the ValidatorConsensusInfo of each current validator, sorted let cur_pending_active = coin::value(&stake_pool.pending_active); let cur_pending_inactive = coin::value(&stake_pool.pending_inactive); - let cur_reward = if (candidate_in_current_validator_set && cur_active > 0) { + let cur_reward = if (candidate_in_current_validator_set && cur_active != 0) { spec { assert candidate.config.validator_index < len(validator_perf.validators); }; @@ -4269,7 +4269,7 @@ Calculate the rewards amount. // We do multiplication in u128 before division to avoid the overflow and minimize the rounding error. let rewards_numerator = (stake_amount as u128) * (rewards_rate as u128) * (num_successful_proposals as u128); let rewards_denominator = (rewards_rate_denominator as u128) * (num_total_proposals as u128); - if (rewards_denominator > 0) { + if (rewards_denominator != 0) { ((rewards_numerator / rewards_denominator) as u64) } else { 0 @@ -4305,7 +4305,7 @@ Mint rewards corresponding to current epoch's acquires SupraCoinCapabilities { let stake_amount = coin::value(stake); - let rewards_amount = if (stake_amount > 0) { + let rewards_amount = if (stake_amount != 0) { calculate_rewards_amount( stake_amount, num_successful_proposals, @@ -4316,7 +4316,7 @@ Mint rewards corresponding to current epoch's else { 0 }; - if (rewards_amount > 0) { + if (rewards_amount != 0) { let mint_cap = &borrow_global<SupraCoinCapabilities>(@supra_framework).mint_cap; let rewards = coin::mint(rewards_amount, mint_cap); coin::merge(stake, rewards); @@ -4474,7 +4474,7 @@ Returns validator's next epoch voting power, including pending_active, active, a validator_set.total_joining_power = validator_set.total_joining_power + (increase_amount as u128); // Only validator voting power increase if the current validator set's voting power > 0. - if (validator_set.total_voting_power > 0) { + if (validator_set.total_voting_power != 0) { assert!( validator_set.total_joining_power <= validator_set.total_voting_power * voting_power_increase_limit / 100, error::invalid_argument(EVOTING_POWER_INCREASE_EXCEEDS_LIMIT), @@ -5491,7 +5491,6 @@ Returns validator's next epoch voting power, including pending_active, active, a
pragma verify = false;
-pragma disable_invariants_in_body;
 include ResourceRequirement;
 include GetReconfigStartTimeRequirement;
 include staking_config::StakingRewardsConfigRequirement;
diff --git a/aptos-move/framework/supra-framework/doc/staking_config.md b/aptos-move/framework/supra-framework/doc/staking_config.md
index 6f94a9cde6397..c431a45175c0b 100644
--- a/aptos-move/framework/supra-framework/doc/staking_config.md
+++ b/aptos-move/framework/supra-framework/doc/staking_config.md
@@ -362,15 +362,15 @@ Only called during genesis.
     validate_required_stake(minimum_stake, maximum_stake);
 
     assert!(
-        recurring_lockup_duration_secs > 0,
+        recurring_lockup_duration_secs != 0,
         error::invalid_argument(EZERO_LOCKUP_DURATION)
     );
     assert!(
-        rewards_rate_denominator > 0,
+        rewards_rate_denominator != 0,
         error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR)
     );
     assert!(
-        voting_power_increase_limit > 0 && voting_power_increase_limit <= 50,
+        voting_power_increase_limit != 0 && voting_power_increase_limit <= 50,
         error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT)
     );
 
@@ -789,7 +789,7 @@ Can only be called as part of the Supra governance proposal process established
 ## Function `update_recurring_lockup_duration_secs`
 
 Update the recurring lockup duration.
-Can only be called as part of the Supra governance proposal process established by the AptosGovernance module.
+Can only be called as part of the Supra governance proposal process established by the SupraGovernance module.
 
 
 
public fun update_recurring_lockup_duration_secs(supra_framework: &signer, new_recurring_lockup_duration_secs: u64)
@@ -805,7 +805,7 @@ Can only be called as part of the Supra governance proposal process established
     supra_framework: &signer, new_recurring_lockup_duration_secs: u64
 ) acquires StakingConfig {
     assert!(
-        new_recurring_lockup_duration_secs > 0,
+        new_recurring_lockup_duration_secs != 0,
         error::invalid_argument(EZERO_LOCKUP_DURATION)
     );
     system_addresses::assert_supra_framework(supra_framework);
@@ -825,7 +825,7 @@ Can only be called as part of the Supra governance proposal process established
 
 DEPRECATING
 Update the rewards rate.
-Can only be called as part of the Supra governance proposal process established by the AptosGovernance module.
+Can only be called as part of the Supra governance proposal process established by the SupraGovernance module.
 
 
 
public fun update_rewards_rate(supra_framework: &signer, new_rewards_rate: u64, new_rewards_rate_denominator: u64)
@@ -848,7 +848,7 @@ Can only be called as part of the Supra governance proposal process established
     );
     system_addresses::assert_supra_framework(supra_framework);
     assert!(
-        new_rewards_rate_denominator > 0,
+        new_rewards_rate_denominator != 0,
         error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR)
     );
     // `rewards_rate` which is the numerator is limited to be `<= MAX_REWARDS_RATE` in order to avoid the arithmetic
@@ -960,7 +960,7 @@ Can only be called as part of the Supra governance proposal process established
 ## Function `update_voting_power_increase_limit`
 
 Update the joining limit %.
-Can only be called as part of the Supra governance proposal process established by the AptosGovernance module.
+Can only be called as part of the Supra governance proposal process established by the SupraGovernance module.
 
 
 
public fun update_voting_power_increase_limit(supra_framework: &signer, new_voting_power_increase_limit: u64)
@@ -977,7 +977,7 @@ Can only be called as part of the Supra governance proposal process established
 ) acquires StakingConfig {
     system_addresses::assert_supra_framework(supra_framework);
     assert!(
-        new_voting_power_increase_limit > 0
+        new_voting_power_increase_limit != 0
             && new_voting_power_increase_limit <= 50,
         error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT)
     );
@@ -1008,7 +1008,7 @@ Can only be called as part of the Supra governance proposal process established
 
 
fun validate_required_stake(minimum_stake: u64, maximum_stake: u64) {
     assert!(
-        minimum_stake <= maximum_stake && maximum_stake > 0,
+        minimum_stake <= maximum_stake && maximum_stake != 0,
         error::invalid_argument(EINVALID_STAKE_RANGE)
     );
 }
@@ -1056,7 +1056,7 @@ Can only be called as part of the Supra governance proposal process established
     // This field, rewards_rate_period_in_secs must be greater than 0.
     // TODO: rewards_rate_period_in_secs should be longer than the epoch duration but reading epoch duration causes a circular dependency.
     assert!(
-        rewards_rate_period_in_secs > 0,
+        rewards_rate_period_in_secs != 0,
         error::invalid_argument(EINVALID_REWARDS_RATE_PERIOD)
     );
 }
diff --git a/aptos-move/framework/supra-framework/doc/staking_contract.md b/aptos-move/framework/supra-framework/doc/staking_contract.md
index fdf925a255408..3b91343b7af5b 100644
--- a/aptos-move/framework/supra-framework/doc/staking_contract.md
+++ b/aptos-move/framework/supra-framework/doc/staking_contract.md
@@ -1686,7 +1686,7 @@ Staker can call this function to create a simple staking contract with a specifi
     contract_creation_seed: vector<u8>,
 ): address acquires Store {
     assert!(
-        commission_percentage >= 0 && commission_percentage <= 100,
+        commission_percentage <= 100,
         error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE),
     );
     // The amount should be at least the min_stake_required, so the stake pool will be eligible to join the
@@ -1889,7 +1889,7 @@ TODO: fix the typo in function name. commision -> commission
     new_commission_percentage: u64
 ) acquires Store, BeneficiaryForOperator, StakingGroupUpdateCommissionEvent {
     assert!(
-        new_commission_percentage >= 0 && new_commission_percentage <= 100,
+        new_commission_percentage <= 100,
         error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE),
     );
 
@@ -2358,7 +2358,7 @@ Distribute all unlocked (inactive) funds according to distribution shares.
         distribution_pool, distribution_amount, operator, staking_contract.commission_percentage);
 
     // Buy all recipients out of the distribution pool.
-    while (pool_u64::shareholders_count(distribution_pool) > 0) {
+    while (pool_u64::shareholders_count(distribution_pool) != 0) {
         let recipients = pool_u64::shareholders(distribution_pool);
         let recipient = *vector::borrow(&mut recipients, 0);
         let current_shares = pool_u64::shares(distribution_pool, recipient);
@@ -2379,7 +2379,7 @@ Distribute all unlocked (inactive) funds according to distribution shares.
     };
 
     // In case there's any dust left, send them all to the staker.
-    if (coin::value(&coins) > 0) {
+    if (coin::value(&coins) != 0) {
         supra_account::deposit_coins(staker, coins);
         pool_u64::update_total_coins(distribution_pool, 0);
     } else {
diff --git a/aptos-move/framework/supra-framework/doc/storage_gas.md b/aptos-move/framework/supra-framework/doc/storage_gas.md
index aa6052370584f..20b96b608320f 100644
--- a/aptos-move/framework/supra-framework/doc/storage_gas.md
+++ b/aptos-move/framework/supra-framework/doc/storage_gas.md
@@ -774,7 +774,7 @@ Which means that the price above min_gas is approximately
 
 
 
public fun new_usage_gas_config(target_usage: u64, read_curve: GasCurve, create_curve: GasCurve, write_curve: GasCurve): UsageGasConfig {
-    assert!(target_usage > 0, error::invalid_argument(EZERO_TARGET_USAGE));
+    assert!(target_usage != 0, error::invalid_argument(EZERO_TARGET_USAGE));
     assert!(target_usage <= MAX_U64 / BASIS_POINT_DENOMINATION, error::invalid_argument(ETARGET_USAGE_TOO_BIG));
     UsageGasConfig {
         target_usage,
@@ -1524,7 +1524,7 @@ A non decreasing curve must ensure that next is greater than cur.
 Signer address must be @supra_framework and StorageGasConfig exists.
 
 
-
include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework };
+
include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework };
 aborts_if !exists<StorageGasConfig>(@supra_framework);
 
@@ -1544,7 +1544,7 @@ Address @supra_framework does not exist StorageGasConfig and StorageGas before t and exists after the function is executed. -
include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework };
+
include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework };
 pragma verify_duration_estimate = 120;
 aborts_if exists<StorageGasConfig>(@supra_framework);
 aborts_if exists<StorageGas>(@supra_framework);
diff --git a/aptos-move/framework/supra-framework/doc/supra_coin.md b/aptos-move/framework/supra-framework/doc/supra_coin.md
index 48c30a21d9057..6cf900bccc623 100644
--- a/aptos-move/framework/supra-framework/doc/supra_coin.md
+++ b/aptos-move/framework/supra-framework/doc/supra_coin.md
@@ -265,7 +265,7 @@ Can only called during genesis to initialize the Supra coin.
 
 ## Function `destroy_mint_cap`
 
-Only called during genesis to destroy the aptos framework account's mint capability once all initial validators
+Only called during genesis to destroy the supra framework account's mint capability once all initial validators
 and accounts have been initialized during genesis.
 
 
@@ -293,7 +293,7 @@ and accounts have been initialized during genesis.
 
 ## Function `configure_accounts_for_test`
 
-Can only be called during genesis for tests to grant mint capability to aptos framework and core resources
+Can only be called during genesis for tests to grant mint capability to supra framework and core resources
 accounts.
 Expects account and SUPRA store to be registered before calling.
 
diff --git a/aptos-move/framework/supra-framework/doc/supra_config.md b/aptos-move/framework/supra-framework/doc/supra_config.md
index ec43b19a3078d..bb3c8507dc91b 100644
--- a/aptos-move/framework/supra-framework/doc/supra_config.md
+++ b/aptos-move/framework/supra-framework/doc/supra_config.md
@@ -87,7 +87,7 @@ Publishes the SupraConfig config.
 
 
public(friend) fun initialize(supra_framework: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
     move_to(supra_framework, SupraConfig { config });
 }
 
@@ -119,7 +119,7 @@ supra_framework::supra_governance::reconfigure(&framework_signer);
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(account);
-    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
     std::config_buffer::upsert<SupraConfig>(SupraConfig {config});
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/supra_governance.md b/aptos-move/framework/supra-framework/doc/supra_governance.md index 07e10eaa829bb..5bc61628b5b50 100644 --- a/aptos-move/framework/supra-framework/doc/supra_governance.md +++ b/aptos-move/framework/supra-framework/doc/supra_governance.md @@ -9,7 +9,7 @@ current epoch's voting power of the proposer or voter's backing stake pool. In a the stake pool's lockup needs to be at least as long as the proposal's duration. It provides the following flow: -1. Proposers can create a proposal by calling AptosGovernance::create_proposal. The proposer's backing stake pool +1. Proposers can create a proposal by calling SupraGovernance::create_proposal. The proposer's backing stake pool needs to have the minimum proposer stake required. Off-chain components can subscribe to CreateProposalEvent to track proposal creation and proposal ids. 2. Voters can vote on a proposal. Their voting power is derived from the backing stake pool. A stake pool can vote @@ -685,7 +685,7 @@ This function is private because it's called directly from the vm. ## Function `update_supra_governance_config` Update the governance configurations. This can only be called as part of resolving a proposal in this same -AptosGovernance. +SupraGovernance.
public fun update_supra_governance_config(supra_framework: &signer, voting_duration_secs: u64, min_voting_threshold: u64, voters: vector<address>)
diff --git a/aptos-move/framework/supra-framework/doc/system_addresses.md b/aptos-move/framework/supra-framework/doc/system_addresses.md
index ce4576e7f332a..65991a98064c6 100644
--- a/aptos-move/framework/supra-framework/doc/system_addresses.md
+++ b/aptos-move/framework/supra-framework/doc/system_addresses.md
@@ -419,7 +419,7 @@ Return true if addr is either the VM address or an Supra Framework
 Asserting that a provided address corresponds to the Supra Framework Resources address should always yield a true result when matched.
 High
 The assert_supra_framework function ensures that the provided signer belongs to the @supra_framework account.
-Formally verified via AbortsIfNotAptosFramework.
+Formally verified via AbortsIfNotSupraFramework.
 
 
 
@@ -510,7 +510,7 @@ Return true if addr is either the VM address or an Supra Framework
 
 
 
pragma opaque;
-include AbortsIfNotAptosFramework;
+include AbortsIfNotSupraFramework;
 
@@ -546,13 +546,13 @@ Return true if addr is either the VM address or an Supra Framework
-Specifies that a function aborts if the account does not have the aptos framework address. +Specifies that a function aborts if the account does not have the supra framework address. - + -
schema AbortsIfNotAptosFramework {
+
schema AbortsIfNotSupraFramework {
     account: signer;
     // This enforces high-level requirement 2:
     aborts_if signer::address_of(account) != @supra_framework with error::PERMISSION_DENIED;
diff --git a/aptos-move/framework/supra-framework/doc/timestamp.md b/aptos-move/framework/supra-framework/doc/timestamp.md
index f59e06479fba6..9192dfa09192f 100644
--- a/aptos-move/framework/supra-framework/doc/timestamp.md
+++ b/aptos-move/framework/supra-framework/doc/timestamp.md
@@ -94,7 +94,7 @@ Conversion factor between seconds and microseconds
 
 ## Function `set_time_has_started`
 
-Marks that time has started. This can only be called from genesis and with the aptos framework account.
+Marks that time has started. This can only be called from genesis and with the supra framework account.
 
 
 
public(friend) fun set_time_has_started(supra_framework: &signer, start_time_in_microseconds: u64)
diff --git a/aptos-move/framework/supra-framework/doc/transaction_fee.md b/aptos-move/framework/supra-framework/doc/transaction_fee.md
index 900307b1c77e8..e442a3a58695b 100644
--- a/aptos-move/framework/supra-framework/doc/transaction_fee.md
+++ b/aptos-move/framework/supra-framework/doc/transaction_fee.md
@@ -460,7 +460,7 @@ Burns a specified fraction of the coin.
         assume burn_percentage * collected_amount <= MAX_U64;
     };
     let amount_to_burn = (burn_percentage as u64) * collected_amount / 100;
-    if (amount_to_burn > 0) {
+    if (amount_to_burn != 0) {
         let coin_to_burn = coin::extract(coin, amount_to_burn);
         coin::burn(
             coin_to_burn,
@@ -917,7 +917,7 @@ Only called during genesis.
 // This enforces high-level requirement 3:
 aborts_if !system_addresses::is_supra_framework_address(aptos_addr);
 aborts_if exists<ValidatorFees>(aptos_addr);
-include system_addresses::AbortsIfNotAptosFramework { account: supra_framework };
+include system_addresses::AbortsIfNotSupraFramework { account: supra_framework };
 include aggregator_factory::CreateAggregatorInternalAbortsIf;
 aborts_if exists<CollectedFeesPerBlock>(aptos_addr);
 ensures exists<ValidatorFees>(aptos_addr);
diff --git a/aptos-move/framework/supra-framework/doc/transaction_validation.md b/aptos-move/framework/supra-framework/doc/transaction_validation.md
index 5aa36bc15fedf..28cfa55c3429b 100644
--- a/aptos-move/framework/supra-framework/doc/transaction_validation.md
+++ b/aptos-move/framework/supra-framework/doc/transaction_validation.md
@@ -300,7 +300,7 @@ Only called during genesis to initialize system resources for this module.
         transaction_sender == gas_payer
             || account::exists_at(transaction_sender)
             || !features::sponsored_automatic_account_creation_enabled()
-            || txn_sequence_number > 0
+            || txn_sequence_number != 0
     ) {
         assert!(account::exists_at(transaction_sender), error::invalid_argument(PROLOGUE_EACCOUNT_DOES_NOT_EXIST));
         assert!(
diff --git a/aptos-move/framework/supra-framework/doc/version.md b/aptos-move/framework/supra-framework/doc/version.md
index 6506a76800e6d..ebc4746b38a84 100644
--- a/aptos-move/framework/supra-framework/doc/version.md
+++ b/aptos-move/framework/supra-framework/doc/version.md
@@ -294,7 +294,7 @@ to update the version.
 1
 During genesis, the Version resource should be initialized with the initial version and stored along with its capability under the supra framework account.
 Medium
-The initialize function ensures that the signer is the aptos framework account and stores the Version and SetVersionCapability resources in it.
+The initialize function ensures that the signer is the supra framework account and stores the Version and SetVersionCapability resources in it.
 Formally verified via initialize.
 
 
diff --git a/aptos-move/framework/supra-framework/doc/vesting.md b/aptos-move/framework/supra-framework/doc/vesting.md
index d472cbb7abc6e..41af9e584b85a 100644
--- a/aptos-move/framework/supra-framework/doc/vesting.md
+++ b/aptos-move/framework/supra-framework/doc/vesting.md
@@ -2114,8 +2114,8 @@ Create a vesting schedule with the given schedule of distributions, a vesting st
     start_timestamp_secs: u64,
     period_duration: u64,
 ): VestingSchedule {
-    assert!(vector::length(&schedule) > 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
-    assert!(period_duration > 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD));
+    assert!(vector::length(&schedule) != 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
+    assert!(period_duration != 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD));
     assert!(
         start_timestamp_secs >= timestamp::now_seconds(),
         error::invalid_argument(EVESTING_START_TOO_SOON),
@@ -2167,7 +2167,7 @@ Create a vesting contract with a given configurations.
         error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS),
     );
     assert_account_is_registered_for_supra(withdrawal_address);
-    assert!(vector::length(shareholders) > 0, error::invalid_argument(ENO_SHAREHOLDERS));
+    assert!(vector::length(shareholders) != 0, error::invalid_argument(ENO_SHAREHOLDERS));
     assert!(
         simple_map::length(&buy_ins) == vector::length(shareholders),
         error::invalid_argument(ESHARES_LENGTH_MISMATCH),
@@ -2189,7 +2189,7 @@ Create a vesting contract with a given configurations.
         );
         grant_amount = grant_amount + buy_in_amount;
     });
-    assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT));
+    assert!(grant_amount != 0, error::invalid_argument(EZERO_GRANT));
 
     // If this is the first time this admin account has created a vesting contract, initialize the admin store.
     let admin_address = signer::address_of(admin);
@@ -2482,7 +2482,7 @@ Distribute any withdrawable stake from the stake pool.
     });
 
     // Send any remaining "dust" (leftover due to rounding error) to the withdrawal address.
-    if (coin::value(&coins) > 0) {
+    if (coin::value(&coins) != 0) {
         supra_account::deposit_coins(vesting_contract.withdrawal_address, coins);
     } else {
         coin::destroy_zero(coins);
diff --git a/aptos-move/framework/supra-framework/doc/vesting_without_staking.md b/aptos-move/framework/supra-framework/doc/vesting_without_staking.md
index 8b6ddf1f8ef2e..f9d0d9d7f450d 100644
--- a/aptos-move/framework/supra-framework/doc/vesting_without_staking.md
+++ b/aptos-move/framework/supra-framework/doc/vesting_without_staking.md
@@ -21,6 +21,9 @@ Vesting without staking contract
 -  [Constants](#@Constants_0)
 -  [Function `vesting_start_secs`](#0x1_vesting_without_staking_vesting_start_secs)
 -  [Function `period_duration_secs`](#0x1_vesting_without_staking_period_duration_secs)
+-  [Function `get_withdrawal_addr`](#0x1_vesting_without_staking_get_withdrawal_addr)
+-  [Function `get_contract_admin`](#0x1_vesting_without_staking_get_contract_admin)
+-  [Function `get_vesting_record`](#0x1_vesting_without_staking_get_vesting_record)
 -  [Function `remaining_grant`](#0x1_vesting_without_staking_remaining_grant)
 -  [Function `beneficiary`](#0x1_vesting_without_staking_beneficiary)
 -  [Function `vesting_contracts`](#0x1_vesting_without_staking_vesting_contracts)
@@ -735,6 +738,8 @@ Admin can only withdraw from an inactive (paused or terminated) vesting contract
 
 
 
+Deprecated.
+
 Vesting cannot start before or at the current block timestamp. Has to be in the future.
 
 
@@ -861,6 +866,93 @@ This errors out if the vesting contract with the provided address doesn't exist.
 
 
 
+
+
+
+
+## Function `get_withdrawal_addr`
+
+
+
+
#[view]
+public fun get_withdrawal_addr(vesting_contract_addr: address): address
+
+ + + +
+Implementation + + +
public fun get_withdrawal_addr(vesting_contract_addr: address): address acquires VestingContract {
+    borrow_global<VestingContract>(vesting_contract_addr).withdrawal_address
+}
+
+ + + +
+ + + +## Function `get_contract_admin` + + + +
#[view]
+public fun get_contract_admin(vesting_contract_addr: address): address
+
+ + + +
+Implementation + + +
public fun get_contract_admin(vesting_contract_addr: address): address acquires VestingContract {
+    borrow_global<VestingContract>(vesting_contract_addr).admin
+}
+
+ + + +
+ + + +## Function `get_vesting_record` + + + +
#[view]
+public fun get_vesting_record(vesting_contract_address: address, shareholder_address: address): (u64, u64, u64)
+
+ + + +
+Implementation + + +
public fun get_vesting_record(
+    vesting_contract_address: address, shareholder_address: address
+): (u64, u64, u64) acquires VestingContract {
+    assert_vesting_contract_exists(vesting_contract_address);
+    let vesting_record =
+        simple_map::borrow(
+            &borrow_global<VestingContract>(vesting_contract_address).shareholders,
+            &shareholder_address
+        );
+    (
+        vesting_record.init_amount,
+        vesting_record.left_amount,
+        vesting_record.last_vested_period
+    )
+}
+
+ + +
@@ -880,11 +972,14 @@ Return the remaining grant of shareholder Implementation -
public fun remaining_grant(vesting_contract_address: address, shareholder_address: address)
-    : u64 acquires VestingContract {
+
public fun remaining_grant(
+    vesting_contract_address: address, shareholder_address: address
+): u64 acquires VestingContract {
     assert_vesting_contract_exists(vesting_contract_address);
-    simple_map::borrow(&borrow_global<VestingContract>(vesting_contract_address).shareholders,
-        &shareholder_address).left_amount
+    simple_map::borrow(
+        &borrow_global<VestingContract>(vesting_contract_address).shareholders,
+        &shareholder_address
+    ).left_amount
 }
 
@@ -912,10 +1007,13 @@ This errors out if the vesting contract with the provided address doesn't exist. Implementation -
public fun beneficiary(vesting_contract_address: address, shareholder: address): address acquires VestingContract {
+
public fun beneficiary(
+    vesting_contract_address: address, shareholder: address
+): address acquires VestingContract {
     assert_vesting_contract_exists(vesting_contract_address);
-    get_beneficiary(borrow_global<VestingContract>(vesting_contract_address),
-        shareholder)
+    get_beneficiary(
+        borrow_global<VestingContract>(vesting_contract_address), shareholder
+    )
 }
 
@@ -978,7 +1076,9 @@ This errors out if the vesting contract with the provided address doesn't exist. Implementation -
public fun vesting_schedule(vesting_contract_address: address): VestingSchedule acquires VestingContract {
+
public fun vesting_schedule(
+    vesting_contract_address: address
+): VestingSchedule acquires VestingContract {
     assert_vesting_contract_exists(vesting_contract_address);
     borrow_global<VestingContract>(vesting_contract_address).vesting_schedule
 }
@@ -1005,7 +1105,9 @@ Return the list of all shareholders in the vesting contract.
 Implementation
 
 
-
public fun shareholders(vesting_contract_address: address): vector<address> acquires VestingContract {
+
public fun shareholders(
+    vesting_contract_address: address
+): vector<address> acquires VestingContract {
     assert_active_vesting_contract(vesting_contract_address);
 
     let vesting_contract = borrow_global<VestingContract>(vesting_contract_address);
@@ -1039,8 +1141,9 @@ This returns 0x0 if no shareholder is found for the given beneficiary / the addr
 Implementation
 
 
-
public fun shareholder(vesting_contract_address: address, shareholder_or_beneficiary: address)
-    : address acquires VestingContract {
+
public fun shareholder(
+    vesting_contract_address: address, shareholder_or_beneficiary: address
+): address acquires VestingContract {
     assert_active_vesting_contract(vesting_contract_address);
 
     let shareholders = &shareholders(vesting_contract_address);
@@ -1050,7 +1153,9 @@ This returns 0x0 if no shareholder is found for the given beneficiary / the addr
     let vesting_contract = borrow_global<VestingContract>(vesting_contract_address);
     let result = @0x0;
     let (sh_vec, ben_vec) = simple_map::to_vec_pair(vesting_contract.beneficiaries);
-    let (found, found_index) = vector::index_of(&ben_vec, &shareholder_or_beneficiary);
+    let (found, found_index) = vector::index_of(
+        &ben_vec, &shareholder_or_beneficiary
+    );
     if (found) {
         result = *vector::borrow(&sh_vec, found_index);
     };
@@ -1079,27 +1184,31 @@ Create a vesting schedule with the given schedule of distributions, a vesting st
 
 
 
public fun create_vesting_schedule(
-    schedule: vector<FixedPoint32>, start_timestamp_secs: u64, period_duration: u64,
+    schedule: vector<FixedPoint32>,
+    start_timestamp_secs: u64,
+    period_duration: u64
 ): VestingSchedule {
     let schedule_len = vector::length(&schedule);
-    assert!(schedule_len > 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
+    assert!(schedule_len != 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
     // If the first vesting fraction is zero, we can replace it with nonzero by increasing start time
-    assert!(fixed_point32::get_raw_value(*vector::borrow(&schedule, 0)) != 0,
-        error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
+    assert!(
+        fixed_point32::get_raw_value(*vector::borrow(&schedule, 0)) != 0,
+        error::invalid_argument(EEMPTY_VESTING_SCHEDULE)
+    );
     // last vesting fraction must be non zero to ensure that no amount remains unvested forever.
-    assert!(fixed_point32::get_raw_value(*vector::borrow(&schedule, schedule_len - 1))
-        != 0,
-        error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
-
-    assert!(period_duration > 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD));
-    assert!(start_timestamp_secs >= timestamp::now_seconds(),
-        error::invalid_argument(EVESTING_START_TOO_SOON),);
-
+    assert!(
+        fixed_point32::get_raw_value(*vector::borrow(&schedule, schedule_len - 1))
+            != 0,
+        error::invalid_argument(EEMPTY_VESTING_SCHEDULE)
+    );
+    assert!(
+        period_duration != 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD)
+    );
     VestingSchedule {
         schedule,
         start_timestamp_secs,
         period_duration,
-        last_vested_period: 0,
+        last_vested_period: 0
     }
 }
 
@@ -1114,7 +1223,7 @@ Create a vesting schedule with the given schedule of distributions, a vesting st -
public entry fun create_vesting_contract_with_amounts(admin: &signer, shareholders: vector<address>, amounts: vector<u64>, schedule_numerator: vector<u64>, schedule_denominator: u64, start_timestamp_secs: u64, period_duration: u64, withdrawal_address: address, contract_creation_seed: vector<u8>)
+
public entry fun create_vesting_contract_with_amounts(admin: &signer, shareholders: vector<address>, shares: vector<u64>, vesting_numerators: vector<u64>, vesting_denominator: u64, start_timestamp_secs: u64, period_duration: u64, withdrawal_address: address, contract_creation_seed: vector<u8>)
 
@@ -1123,91 +1232,115 @@ Create a vesting schedule with the given schedule of distributions, a vesting st Implementation -
public entry fun create_vesting_contract_with_amounts (
+
public entry fun create_vesting_contract_with_amounts(
     admin: &signer,
     shareholders: vector<address>,
-    amounts: vector<u64>,
-    schedule_numerator: vector<u64>,
-    schedule_denominator: u64,
+    shares: vector<u64>,
+    vesting_numerators: vector<u64>,
+    vesting_denominator: u64,
     start_timestamp_secs: u64,
     period_duration: u64,
     withdrawal_address: address,
-    contract_creation_seed: vector<u8>,
+    contract_creation_seed: vector<u8>
 ) acquires AdminStore {
-    assert!(!system_addresses::is_reserved_address(withdrawal_address),
-        error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS),);
-    assert_account_is_registered_for_apt(withdrawal_address);
-    assert!(vector::length(&shareholders) > 0,
-        error::invalid_argument(ENO_SHAREHOLDERS));
     assert!(
-        vector::length(&shareholders) == vector::length(&amounts),
-        error::invalid_argument(ESHARES_LENGTH_MISMATCH),
+        !system_addresses::is_reserved_address(withdrawal_address),
+        error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS)
+    );
+    assert_account_is_registered_for_supra(withdrawal_address);
+    assert!(
+        vector::length(&shareholders) != 0,
+        error::invalid_argument(ENO_SHAREHOLDERS)
+    );
+    assert!(
+        vector::length(&shareholders) == vector::length(&shares),
+        error::invalid_argument(ESHARES_LENGTH_MISMATCH)
     );
 
     // If this is the first time this admin account has created a vesting contract, initialize the admin store.
     let admin_address = signer::address_of(admin);
     if (!exists<AdminStore>(admin_address)) {
-        move_to(admin,
+        move_to(
+            admin,
             AdminStore {
                 vesting_contracts: vector::empty<address>(),
                 nonce: 0,
-                create_events: new_event_handle<CreateVestingContractEvent>(admin),
-            });
+                create_events: new_event_handle<CreateVestingContractEvent>(admin)
+            }
+        );
     };
 
     // Initialize the vesting contract in a new resource account. This allows the same admin to create multiple
     // pools.
-    let (contract_signer, contract_signer_cap) = create_vesting_contract_account(admin,
-        contract_creation_seed);
+    let (contract_signer, contract_signer_cap) =
+        create_vesting_contract_account(admin, contract_creation_seed);
     let contract_signer_address = signer::address_of(&contract_signer);
-    let schedule = vector::map_ref(&schedule_numerator, |numerator| {
-        let event = fixed_point32::create_from_rational(*numerator, schedule_denominator);
-        event
-    });
+    let schedule = vector::map_ref(
+        &vesting_numerators,
+        |numerator| {
+            let event =
+                fixed_point32::create_from_rational(*numerator, vesting_denominator);
+            event
+        }
+    );
 
-    let vesting_schedule = create_vesting_schedule(schedule, start_timestamp_secs, period_duration);
+    let vesting_schedule =
+        create_vesting_schedule(schedule, start_timestamp_secs, period_duration);
     let shareholders_map = simple_map::create<address, VestingRecord>();
     let grant_amount = 0;
-    vector::for_each_reverse(amounts, |amount| {
-        let shareholder = vector::pop_back(&mut shareholders);
-        simple_map::add(&mut shareholders_map,
-            shareholder,
-            VestingRecord {
-                init_amount: amount,
-                left_amount: amount,
-                last_vested_period: vesting_schedule.last_vested_period,
-            }
-        );
-        grant_amount = grant_amount + amount;
-    });
-    assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT));
+    vector::for_each_reverse(
+        shares,
+        |amount| {
+            let shareholder = vector::pop_back(&mut shareholders);
+            simple_map::add(
+                &mut shareholders_map,
+                shareholder,
+                VestingRecord {
+                    init_amount: amount,
+                    left_amount: amount,
+                    last_vested_period: vesting_schedule.last_vested_period
+                }
+            );
+            grant_amount = grant_amount + amount;
+        }
+    );
+    assert!(grant_amount != 0, error::invalid_argument(EZERO_GRANT));
     coin::transfer<SupraCoin>(admin, contract_signer_address, grant_amount);
 
     let admin_store = borrow_global_mut<AdminStore>(admin_address);
     vector::push_back(&mut admin_store.vesting_contracts, contract_signer_address);
-    emit_event(&mut admin_store.create_events,
+    emit_event(
+        &mut admin_store.create_events,
         CreateVestingContractEvent {
             withdrawal_address,
             grant_amount,
-            vesting_contract_address: contract_signer_address,
-        },
+            vesting_contract_address: contract_signer_address
+        }
     );
 
-    move_to(&contract_signer,
+    move_to(
+        &contract_signer,
         VestingContract {
             state: VESTING_POOL_ACTIVE,
             admin: admin_address,
-            shareholders:shareholders_map,
+            shareholders: shareholders_map,
             beneficiaries: simple_map::create<address, address>(),
             vesting_schedule,
             withdrawal_address,
             signer_cap: contract_signer_cap,
-            set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>(&contract_signer),
+            set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>(
+                &contract_signer
+            ),
             vest_events: new_event_handle<VestEvent>(&contract_signer),
             terminate_events: new_event_handle<TerminateEvent>(&contract_signer),
-            admin_withdraw_events: new_event_handle<AdminWithdrawEvent>(&contract_signer),
-            shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>(&contract_signer),
-        });
+            admin_withdraw_events: new_event_handle<AdminWithdrawEvent>(
+                &contract_signer
+            ),
+            shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>(
+                &contract_signer
+            )
+        }
+    );
 }
 
@@ -1236,65 +1369,74 @@ Create a vesting contract with a given configurations. buy_ins: SimpleMap<address, Coin<SupraCoin>>, vesting_schedule: VestingSchedule, withdrawal_address: address, - contract_creation_seed: vector<u8>, + contract_creation_seed: vector<u8> ): address acquires AdminStore { - assert!(!system_addresses::is_reserved_address(withdrawal_address), - error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS),); + assert!( + !system_addresses::is_reserved_address(withdrawal_address), + error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS) + ); assert_account_is_registered_for_supra(withdrawal_address); let shareholders_address = &simple_map::keys(&buy_ins); - assert!(vector::length(shareholders_address) > 0, - error::invalid_argument(ENO_SHAREHOLDERS)); + assert!( + vector::length(shareholders_address) != 0, + error::invalid_argument(ENO_SHAREHOLDERS) + ); let shareholders = simple_map::create<address, VestingRecord>(); let grant = coin::zero<SupraCoin>(); let grant_amount = 0; let (shareholders_address, buy_ins) = simple_map::to_vec_pair(buy_ins); - while (vector::length(&shareholders_address) > 0) { + while (vector::length(&shareholders_address) != 0) { let shareholder = vector::pop_back(&mut shareholders_address); let buy_in = vector::pop_back(&mut buy_ins); let init = coin::value(&buy_in); coin::merge(&mut grant, buy_in); - simple_map::add(&mut shareholders, + simple_map::add( + &mut shareholders, shareholder, VestingRecord { init_amount: init, left_amount: init, - last_vested_period: vesting_schedule.last_vested_period, + last_vested_period: vesting_schedule.last_vested_period } ); grant_amount = grant_amount + init; }; - assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT)); + assert!(grant_amount != 0, error::invalid_argument(EZERO_GRANT)); // If this is the first time this admin account has created a vesting contract, initialize the admin store. let admin_address = signer::address_of(admin); if (!exists<AdminStore>(admin_address)) { - move_to(admin, + move_to( + admin, AdminStore { vesting_contracts: vector::empty<address>(), nonce: 0, - create_events: new_event_handle<CreateVestingContractEvent>(admin), - }); + create_events: new_event_handle<CreateVestingContractEvent>(admin) + } + ); }; // Initialize the vesting contract in a new resource account. This allows the same admin to create multiple // pools. - let (contract_signer, contract_signer_cap) = create_vesting_contract_account(admin, - contract_creation_seed); + let (contract_signer, contract_signer_cap) = + create_vesting_contract_account(admin, contract_creation_seed); let contract_signer_address = signer::address_of(&contract_signer); coin::deposit(contract_signer_address, grant); let admin_store = borrow_global_mut<AdminStore>(admin_address); vector::push_back(&mut admin_store.vesting_contracts, contract_signer_address); - emit_event(&mut admin_store.create_events, + emit_event( + &mut admin_store.create_events, CreateVestingContractEvent { withdrawal_address, grant_amount, - vesting_contract_address: contract_signer_address, - }, + vesting_contract_address: contract_signer_address + } ); - move_to(&contract_signer, + move_to( + &contract_signer, VestingContract { state: VESTING_POOL_ACTIVE, admin: admin_address, @@ -1303,12 +1445,19 @@ Create a vesting contract with a given configurations. vesting_schedule, withdrawal_address, signer_cap: contract_signer_cap, - set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>(&contract_signer), + set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>( + &contract_signer + ), vest_events: new_event_handle<VestEvent>(&contract_signer), terminate_events: new_event_handle<TerminateEvent>(&contract_signer), - admin_withdraw_events: new_event_handle<AdminWithdrawEvent>(&contract_signer), - shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>(&contract_signer), - }); + admin_withdraw_events: new_event_handle<AdminWithdrawEvent>( + &contract_signer + ), + shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>( + &contract_signer + ) + } + ); vector::destroy_empty(buy_ins); contract_signer_address @@ -1339,10 +1488,11 @@ Unlock any vested portion of the grant. assert_active_vesting_contract(contract_address); let vesting_contract = borrow_global_mut<VestingContract>(contract_address); // Short-circuit if vesting hasn't started yet. - if (vesting_contract.vesting_schedule.start_timestamp_secs > timestamp::now_seconds()) { return }; + if (vesting_contract.vesting_schedule.start_timestamp_secs + > timestamp::now_seconds()) { return }; let shareholders = simple_map::keys(&vesting_contract.shareholders); - while (vector::length(&shareholders) > 0) { + while (vector::length(&shareholders) != 0) { let shareholder = vector::pop_back(&mut shareholders); vest_individual(contract_address, shareholder); }; @@ -1372,16 +1522,22 @@ Unlock any vested portion of the grant. Implementation -
public entry fun vest_individual(contract_address: address, shareholder_address: address) acquires VestingContract {
+
public entry fun vest_individual(
+    contract_address: address, shareholder_address: address
+) acquires VestingContract {
     //check if contract exist, active and shareholder is a member of the contract
     assert_shareholder_exists(contract_address, shareholder_address);
 
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     let beneficiary = get_beneficiary(vesting_contract, shareholder_address);
     // Short-circuit if vesting hasn't started yet.
-    if (vesting_contract.vesting_schedule.start_timestamp_secs > timestamp::now_seconds()) { return };
+    if (vesting_contract.vesting_schedule.start_timestamp_secs
+        > timestamp::now_seconds()) { return };
 
-    let vesting_record = simple_map::borrow_mut(&mut vesting_contract.shareholders, &shareholder_address);
+    let vesting_record =
+        simple_map::borrow_mut(
+            &mut vesting_contract.shareholders, &shareholder_address
+        );
     let signer_cap = &vesting_contract.signer_cap;
 
     // Check if the next vested period has already passed. If not, short-circuit since there's nothing to vest.
@@ -1389,29 +1545,58 @@ Unlock any vested portion of the grant.
     let schedule = &vesting_schedule.schedule;
     let last_vested_period = vesting_record.last_vested_period;
     let next_period_to_vest = last_vested_period + 1;
-    let last_completed_period = (timestamp::now_seconds() - vesting_schedule.start_timestamp_secs)
-        / vesting_schedule.period_duration;
+    let last_completed_period =
+        (timestamp::now_seconds() - vesting_schedule.start_timestamp_secs)
+            / vesting_schedule.period_duration;
 
     // Index is 0-based while period is 1-based so we need to subtract 1.
-    while (last_completed_period >= next_period_to_vest && vesting_record.left_amount > 0) {
+
+    while (last_completed_period >= next_period_to_vest && vesting_record.left_amount != 0 && next_period_to_vest <= vector::length(schedule)) {
         let schedule_index = next_period_to_vest - 1;
-        let vesting_fraction = if (schedule_index < vector::length(schedule)) {
-            *vector::borrow(schedule, schedule_index)
+        let vesting_fraction = *vector::borrow(schedule, schedule_index);
+        vest_transfer(vesting_record, signer_cap, beneficiary, vesting_fraction);
+        emit_event(&mut vesting_contract.vest_events,
+            VestEvent {
+                admin: vesting_contract.admin,
+                shareholder_address,
+                vesting_contract_address: contract_address,
+                period_vested: next_period_to_vest
+            }
+        );
+        next_period_to_vest = next_period_to_vest + 1;
+    };
+
+    if(last_completed_period >= next_period_to_vest && vesting_record.left_amount != 0) {
+        let final_fraction = *vector::borrow(schedule, vector::length(schedule) - 1);
+        let final_fraction_amount = fixed_point32::multiply_u64(vesting_record.init_amount, final_fraction);
+        // Determine how many periods is needed based on the left_amount
+        let added_fraction = fixed_point32::multiply_u64_return_fixpoint32(last_completed_period - next_period_to_vest + 1, final_fraction);
+        // If the added_fraction is greater than or equal to the left_amount, then we can vest all the left_amount
+        let periods_need =
+            if (fixed_point32::multiply_u64(vesting_record.init_amount, added_fraction) >= vesting_record.left_amount){
+            let result =  vesting_record.left_amount / final_fraction_amount;
+                // check if `left_amount` is perfectly divisible by `final_fraction_amount`
+                  if (vesting_record.left_amount == final_fraction_amount*result) {
+                   result
+                } else {
+                   result + 1
+                }
         } else {
-            // Last vesting schedule fraction will repeat until the grant runs out.
-            *vector::borrow(schedule, vector::length(schedule) - 1)
+            last_completed_period - next_period_to_vest + 1
         };
-        vest_transfer(vesting_record, signer_cap, beneficiary, vesting_fraction);
 
+        let total_fraction = fixed_point32::multiply_u64_return_fixpoint32(periods_need, final_fraction);
+        // We don't need to check vesting_record.left_amount > 0 because vest_transfer will handle that.
+        vest_transfer(vesting_record, signer_cap, beneficiary, total_fraction);
+        next_period_to_vest = next_period_to_vest + periods_need;
         emit_event(&mut vesting_contract.vest_events,
             VestEvent {
                 admin: vesting_contract.admin,
-                shareholder_address: shareholder_address,
+                shareholder_address,
                 vesting_contract_address: contract_address,
                 period_vested: next_period_to_vest,
             },
         );
-        next_period_to_vest = next_period_to_vest + 1;
     };
 
     //update last_vested_period for the shareholder
@@ -1447,8 +1632,13 @@ Unlock any vested portion of the grant.
     let vesting_signer = account::create_signer_with_capability(signer_cap);
 
     //amount to be transfer is minimum of what is left and vesting fraction due of init_amount
-    let amount = min(vesting_record.left_amount,
-        fixed_point32::multiply_u64(vesting_record.init_amount, vesting_fraction));
+    let amount =
+        min(
+            vesting_record.left_amount,
+            fixed_point32::multiply_u64(
+                vesting_record.init_amount, vesting_fraction
+            )
+        );
     //update left_amount for the shareholder
     vesting_record.left_amount = vesting_record.left_amount - amount;
     coin::transfer<SupraCoin>(&vesting_signer, beneficiary, amount);
@@ -1483,38 +1673,43 @@ Example usage: If admin find shareholder suspicious, admin can remove it.
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
     let vesting_signer = get_vesting_account_signer_internal(vesting_contract);
-    let shareholder_amount = simple_map::borrow(&vesting_contract.shareholders, &shareholder_address)
-        .left_amount;
-    coin::transfer<SupraCoin>(&vesting_signer, vesting_contract.withdrawal_address,
-        shareholder_amount);
-    emit_event(&mut vesting_contract.admin_withdraw_events,
+    let shareholder_amount =
+        simple_map::borrow(&vesting_contract.shareholders, &shareholder_address).left_amount;
+    coin::transfer<SupraCoin>(
+        &vesting_signer, vesting_contract.withdrawal_address, shareholder_amount
+    );
+    emit_event(
+        &mut vesting_contract.admin_withdraw_events,
         AdminWithdrawEvent {
             admin: vesting_contract.admin,
             vesting_contract_address: contract_address,
-            amount: shareholder_amount,
-        },
+            amount: shareholder_amount
+        }
     );
 
     // remove `shareholder_address`` from `vesting_contract.shareholders`
     let shareholders = &mut vesting_contract.shareholders;
-    let (_, shareholders_vesting) = simple_map::remove(shareholders, &shareholder_address);
+    let (_, shareholders_vesting) =
+        simple_map::remove(shareholders, &shareholder_address);
 
     // remove `shareholder_address` from `vesting_contract.beneficiaries`
     let beneficiary = option::none();
     let shareholder_beneficiaries = &mut vesting_contract.beneficiaries;
     // Not all shareholders have their beneficiaries, so before removing them, we need to check if the beneficiary exists
     if (simple_map::contains_key(shareholder_beneficiaries, &shareholder_address)) {
-        let (_, shareholder_baneficiary) = simple_map::remove(shareholder_beneficiaries, &shareholder_address);
+        let (_, shareholder_baneficiary) =
+            simple_map::remove(shareholder_beneficiaries, &shareholder_address);
         beneficiary = option::some(shareholder_baneficiary);
     };
 
     // Emit ShareHolderRemovedEvent
-    emit_event(&mut vesting_contract.shareholder_removed_events,
+    emit_event(
+        &mut vesting_contract.shareholder_removed_events,
         ShareHolderRemovedEvent {
             shareholder: shareholder_address,
             beneficiary,
-            amount: shareholders_vesting.left_amount,
-        },
+            amount: shareholders_vesting.left_amount
+        }
     );
 }
 
@@ -1539,7 +1734,9 @@ Terminate the vesting contract and send all funds back to the withdrawal address Implementation -
public entry fun terminate_vesting_contract(admin: &signer, contract_address: address) acquires VestingContract {
+
public entry fun terminate_vesting_contract(
+    admin: &signer, contract_address: address
+) acquires VestingContract {
     assert_active_vesting_contract(contract_address);
 
     vest(contract_address);
@@ -1549,12 +1746,16 @@ Terminate the vesting contract and send all funds back to the withdrawal address
 
     // Distribute remaining coins to withdrawal address of vesting contract.
     let shareholders_address = simple_map::keys(&vesting_contract.shareholders);
-    vector::for_each_ref(&shareholders_address,
+    vector::for_each_ref(
+        &shareholders_address,
         |shareholder| {
-            let shareholder_amount = simple_map::borrow_mut(&mut vesting_contract.shareholders,
-                shareholder);
+            let shareholder_amount =
+                simple_map::borrow_mut(
+                    &mut vesting_contract.shareholders, shareholder
+                );
             shareholder_amount.left_amount = 0;
-        });
+        }
+    );
     set_terminate_vesting_contract(contract_address);
 }
 
@@ -1580,24 +1781,30 @@ has already been terminated. Implementation -
public entry fun admin_withdraw(admin: &signer, contract_address: address) acquires VestingContract {
+
public entry fun admin_withdraw(
+    admin: &signer, contract_address: address
+) acquires VestingContract {
     let vesting_contract = borrow_global<VestingContract>(contract_address);
-    assert!(vesting_contract.state == VESTING_POOL_TERMINATED,
-        error::invalid_state(EVESTING_CONTRACT_STILL_ACTIVE));
+    assert!(
+        vesting_contract.state == VESTING_POOL_TERMINATED,
+        error::invalid_state(EVESTING_CONTRACT_STILL_ACTIVE)
+    );
 
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
     let total_balance = coin::balance<SupraCoin>(contract_address);
     let vesting_signer = get_vesting_account_signer_internal(vesting_contract);
-    coin::transfer<SupraCoin>(&vesting_signer, vesting_contract.withdrawal_address,
-        total_balance);
+    coin::transfer<SupraCoin>(
+        &vesting_signer, vesting_contract.withdrawal_address, total_balance
+    );
 
-    emit_event(&mut vesting_contract.admin_withdraw_events,
+    emit_event(
+        &mut vesting_contract.admin_withdraw_events,
         AdminWithdrawEvent {
             admin: vesting_contract.admin,
             vesting_contract_address: contract_address,
-            amount: total_balance,
-        },
+            amount: total_balance
+        }
     );
 }
 
@@ -1625,7 +1832,7 @@ has already been terminated. admin: &signer, contract_address: address, shareholder: address, - new_beneficiary: address, + new_beneficiary: address ) acquires VestingContract { // Verify that the beneficiary account is set up to receive SUPRA. This is a requirement so distribute() wouldn't // fail and block all other accounts from receiving SUPRA if one beneficiary is not registered. @@ -1638,14 +1845,15 @@ has already been terminated. let beneficiaries = &mut vesting_contract.beneficiaries; simple_map::upsert(beneficiaries, shareholder, new_beneficiary); - emit_event(&mut vesting_contract.set_beneficiary_events, + emit_event( + &mut vesting_contract.set_beneficiary_events, SetBeneficiaryEvent { admin: vesting_contract.admin, vesting_contract_address: contract_address, shareholder, old_beneficiary, - new_beneficiary, - }, + new_beneficiary + } ); }
@@ -1672,13 +1880,20 @@ account.
public entry fun reset_beneficiary(
-    account: &signer, contract_address: address, shareholder: address,
+    account: &signer,
+    contract_address: address,
+    shareholder: address
 ) acquires VestingAccountManagement, VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     let addr = signer::address_of(account);
-    assert!(addr == vesting_contract.admin || addr == get_role_holder(contract_address,
-            utf8(ROLE_BENEFICIARY_RESETTER)),
-        error::permission_denied(EPERMISSION_DENIED),);
+    assert!(
+        addr == vesting_contract.admin
+            || addr
+                == get_role_holder(
+                    contract_address, utf8(ROLE_BENEFICIARY_RESETTER)
+                ),
+        error::permission_denied(EPERMISSION_DENIED)
+    );
 
     let beneficiaries = &mut vesting_contract.beneficiaries;
     if (simple_map::contains_key(beneficiaries, &shareholder)) {
@@ -1710,17 +1925,22 @@ account.
     admin: &signer,
     contract_address: address,
     role: String,
-    role_holder: address,
+    role_holder: address
 ) acquires VestingAccountManagement, VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
 
     if (!exists<VestingAccountManagement>(contract_address)) {
         let contract_signer = &get_vesting_account_signer_internal(vesting_contract);
-        move_to(contract_signer,
-            VestingAccountManagement { roles: simple_map::create<String, address>(), })
+        move_to(
+            contract_signer,
+            VestingAccountManagement {
+                roles: simple_map::create<String, address>()
+            }
+        )
     };
-    let roles = &mut borrow_global_mut<VestingAccountManagement>(contract_address).roles;
+    let roles =
+        &mut borrow_global_mut<VestingAccountManagement>(contract_address).roles;
     simple_map::upsert(roles, role, role_holder);
 }
 
@@ -1745,10 +1965,16 @@ account.
public entry fun set_beneficiary_resetter(
-    admin: &signer, contract_address: address, beneficiary_resetter: address,
+    admin: &signer,
+    contract_address: address,
+    beneficiary_resetter: address
 ) acquires VestingAccountManagement, VestingContract {
-    set_management_role(admin, contract_address, utf8(ROLE_BENEFICIARY_RESETTER),
-        beneficiary_resetter);
+    set_management_role(
+        admin,
+        contract_address,
+        utf8(ROLE_BENEFICIARY_RESETTER),
+        beneficiary_resetter
+    );
 }
 
@@ -1771,11 +1997,17 @@ account. Implementation -
public fun get_role_holder(contract_address: address, role: String): address acquires VestingAccountManagement {
-    assert!(exists<VestingAccountManagement>(contract_address),
-        error::not_found(EVESTING_ACCOUNT_HAS_NO_ROLES));
+
public fun get_role_holder(
+    contract_address: address, role: String
+): address acquires VestingAccountManagement {
+    assert!(
+        exists<VestingAccountManagement>(contract_address),
+        error::not_found(EVESTING_ACCOUNT_HAS_NO_ROLES)
+    );
     let roles = &borrow_global<VestingAccountManagement>(contract_address).roles;
-    assert!(simple_map::contains_key(roles, &role), error::not_found(EROLE_NOT_FOUND));
+    assert!(
+        simple_map::contains_key(roles, &role), error::not_found(EROLE_NOT_FOUND)
+    );
     *simple_map::borrow(roles, &role)
 }
 
@@ -1800,7 +2032,9 @@ For emergency use in case the admin needs emergency control of vesting contract Implementation -
public fun get_vesting_account_signer(admin: &signer, contract_address: address): signer acquires VestingContract {
+
public fun get_vesting_account_signer(
+    admin: &signer, contract_address: address
+): signer acquires VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
     get_vesting_account_signer_internal(vesting_contract)
@@ -1826,7 +2060,9 @@ For emergency use in case the admin needs emergency control of vesting contract
 Implementation
 
 
-
fun get_vesting_account_signer_internal(vesting_contract: &VestingContract): signer {
+
fun get_vesting_account_signer_internal(
+    vesting_contract: &VestingContract
+): signer {
     account::create_signer_with_capability(&vesting_contract.signer_cap)
 }
 
@@ -1852,8 +2088,9 @@ This address should be deterministic for the same admin and vesting contract cre Implementation -
fun create_vesting_contract_account(admin: &signer, contract_creation_seed: vector<u8>,)
-    : (signer, SignerCapability) acquires AdminStore {
+
fun create_vesting_contract_account(
+    admin: &signer, contract_creation_seed: vector<u8>
+): (signer, SignerCapability) acquires AdminStore {
     let admin_store = borrow_global_mut<AdminStore>(signer::address_of(admin));
     let seed = bcs::to_bytes(&signer::address_of(admin));
     vector::append(&mut seed, bcs::to_bytes(&admin_store.nonce));
@@ -1892,8 +2129,10 @@ This address should be deterministic for the same admin and vesting contract cre
 
 
 
fun verify_admin(admin: &signer, vesting_contract: &VestingContract) {
-    assert!(signer::address_of(admin) == vesting_contract.admin,
-        error::unauthenticated(ENOT_ADMIN));
+    assert!(
+        signer::address_of(admin) == vesting_contract.admin,
+        error::unauthenticated(ENOT_ADMIN)
+    );
 }
 
@@ -1917,8 +2156,10 @@ This address should be deterministic for the same admin and vesting contract cre
fun assert_vesting_contract_exists(contract_address: address) {
-    assert!(exists<VestingContract>(contract_address),
-        error::not_found(EVESTING_CONTRACT_NOT_FOUND));
+    assert!(
+        exists<VestingContract>(contract_address),
+        error::not_found(EVESTING_CONTRACT_NOT_FOUND)
+    );
 }
 
@@ -1941,11 +2182,17 @@ This address should be deterministic for the same admin and vesting contract cre Implementation -
fun assert_shareholder_exists(contract_address: address, shareholder_address: address) acquires VestingContract {
+
fun assert_shareholder_exists(
+    contract_address: address, shareholder_address: address
+) acquires VestingContract {
     assert_active_vesting_contract(contract_address);
-    assert!(simple_map::contains_key(&borrow_global<VestingContract>(contract_address)
-                .shareholders, &shareholder_address),
-        error::not_found(ESHAREHOLDER_NOT_EXIST));
+    assert!(
+        simple_map::contains_key(
+            &borrow_global<VestingContract>(contract_address).shareholders,
+            &shareholder_address
+        ),
+        error::not_found(ESHAREHOLDER_NOT_EXIST)
+    );
 }
 
@@ -1971,8 +2218,10 @@ This address should be deterministic for the same admin and vesting contract cre
fun assert_active_vesting_contract(contract_address: address) acquires VestingContract {
     assert_vesting_contract_exists(contract_address);
     let vesting_contract = borrow_global<VestingContract>(contract_address);
-    assert!(vesting_contract.state == VESTING_POOL_ACTIVE,
-        error::invalid_state(EVESTING_CONTRACT_NOT_ACTIVE));
+    assert!(
+        vesting_contract.state == VESTING_POOL_ACTIVE,
+        error::invalid_state(EVESTING_CONTRACT_NOT_ACTIVE)
+    );
 }
 
@@ -1998,7 +2247,9 @@ This address should be deterministic for the same admin and vesting contract cre
fun get_beneficiary(contract: &VestingContract, shareholder: address): address {
     if (simple_map::contains_key(&contract.beneficiaries, &shareholder)) {
         *simple_map::borrow(&contract.beneficiaries, &shareholder)
-    } else { shareholder }
+    } else {
+        shareholder
+    }
 }
 
@@ -2024,11 +2275,12 @@ This address should be deterministic for the same admin and vesting contract cre
fun set_terminate_vesting_contract(contract_address: address) acquires VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     vesting_contract.state = VESTING_POOL_TERMINATED;
-    emit_event(&mut vesting_contract.terminate_events,
+    emit_event(
+        &mut vesting_contract.terminate_events,
         TerminateEvent {
             admin: vesting_contract.admin,
-            vesting_contract_address: contract_address,
-        },
+            vesting_contract_address: contract_address
+        }
     );
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/voting.md b/aptos-move/framework/supra-framework/doc/voting.md index 42f3c6e07091d..d00efdf78d45d 100644 --- a/aptos-move/framework/supra-framework/doc/voting.md +++ b/aptos-move/framework/supra-framework/doc/voting.md @@ -11,7 +11,7 @@ On-chain governance of the Supra network also uses Voting. The voting flow: 1. The Voting module can be deployed at a known address (e.g. 0x1 for Supra on-chain governance) -2. The governance module, e.g. AptosGovernance, can be deployed later and define a GovernanceProposal resource type +2. The governance module, e.g. SupraGovernance, can be deployed later and define a GovernanceProposal resource type that can also contain other information such as Capability resource for authorization. 3. The governance module's owner can then register the ProposalType with Voting. This also hosts the proposal list (forum) on the calling account. @@ -935,7 +935,7 @@ resolve this proposal. ); }; // Make sure the execution script's hash is not empty. - assert!(vector::length(&execution_hash) > 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); + assert!(vector::length(&execution_hash) != 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); let voting_forum = borrow_global_mut<VotingForum<ProposalType>>(voting_forum_address); let proposal_id = voting_forum.next_proposal_id; diff --git a/aptos-move/framework/supra-framework/sources/account.move b/aptos-move/framework/supra-framework/sources/account.move index 5e7894a54a4fd..52d4bdb94d9ae 100644 --- a/aptos-move/framework/supra-framework/sources/account.move +++ b/aptos-move/framework/supra-framework/sources/account.move @@ -174,7 +174,7 @@ module supra_framework::account { const MAX_GUID_CREATION_NUM: u64 = 0x4000000000000; #[test_only] - /// Create signer for testing, independently of an Aptos-style `Account`. + /// Create signer for testing, independently of an Supra-style `Account`. public fun create_signer_for_test(addr: address): signer { create_signer(addr) } /// Only called during genesis to initialize system resources for this module. diff --git a/aptos-move/framework/supra-framework/sources/aggregator/aggregator_factory.spec.move b/aptos-move/framework/supra-framework/sources/aggregator/aggregator_factory.spec.move index a2fa94ca4fcac..083ab1c77b81d 100644 --- a/aptos-move/framework/supra-framework/sources/aggregator/aggregator_factory.spec.move +++ b/aptos-move/framework/supra-framework/sources/aggregator/aggregator_factory.spec.move @@ -14,7 +14,7 @@ spec supra_framework::aggregator_factory { /// Requirement: To create a new aggregator instance, the aggregator factory must already be initialized and exist /// under the Supra account. /// Criticality: High - /// Implementation: The create_aggregator_internal function asserts that AggregatorFactory exists for the Aptos + /// Implementation: The create_aggregator_internal function asserts that AggregatorFactory exists for the Supra /// account. /// Enforcement: Formally verified via [high-level-req-2](CreateAggregatorInternalAbortsIf). /// diff --git a/aptos-move/framework/supra-framework/sources/block.move b/aptos-move/framework/supra-framework/sources/block.move index 1f079012a5d96..5fb2e7718049a 100644 --- a/aptos-move/framework/supra-framework/sources/block.move +++ b/aptos-move/framework/supra-framework/sources/block.move @@ -122,7 +122,7 @@ module supra_framework::block { } /// Update the epoch interval. - /// Can only be called as part of the Supra governance proposal process established by the AptosGovernance module. + /// Can only be called as part of the Supra governance proposal process established by the SupraGovernance module. public fun update_epoch_interval_microsecs( supra_framework: &signer, new_epoch_interval: u64, diff --git a/aptos-move/framework/supra-framework/sources/block.spec.move b/aptos-move/framework/supra-framework/sources/block.spec.move index e7dc0715a33a2..253862bfc1353 100644 --- a/aptos-move/framework/supra-framework/sources/block.spec.move +++ b/aptos-move/framework/supra-framework/sources/block.spec.move @@ -2,7 +2,7 @@ spec supra_framework::block { /// /// No.: 1 /// Requirement: During the module's initialization, it guarantees that the BlockResource resource moves under the - /// Aptos framework account with initial values. + /// Supra framework account with initial values. /// Criticality: High /// Implementation: The initialize function is responsible for setting up the initial state of the module, ensuring /// that the following conditions are met (1) the BlockResource resource is created, indicating its existence within diff --git a/aptos-move/framework/supra-framework/sources/chain_id.spec.move b/aptos-move/framework/supra-framework/sources/chain_id.spec.move index cc48c565c4aa8..45e30e9cc2b18 100644 --- a/aptos-move/framework/supra-framework/sources/chain_id.spec.move +++ b/aptos-move/framework/supra-framework/sources/chain_id.spec.move @@ -9,7 +9,7 @@ spec supra_framework::chain_id { /// Enforcement: Formally verified via [high-level-req-1](initialize). /// /// No.: 2 - /// Requirement: The chain id can only be fetched if the chain id resource exists under the Aptos + /// Requirement: The chain id can only be fetched if the chain id resource exists under the Supra /// framework account. /// Criticality: Low /// Implementation: The chain_id::get function fetches the chain id by borrowing the ChainId diff --git a/aptos-move/framework/supra-framework/sources/coin.spec.move b/aptos-move/framework/supra-framework/sources/coin.spec.move index c3f007e496167..64513db9c7870 100644 --- a/aptos-move/framework/supra-framework/sources/coin.spec.move +++ b/aptos-move/framework/supra-framework/sources/coin.spec.move @@ -580,7 +580,7 @@ spec supra_framework::coin { } spec initialize_aggregatable_coin(supra_framework: &signer): AggregatableCoin { - include system_addresses::AbortsIfNotAptosFramework { account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework { account: supra_framework }; include aggregator_factory::CreateAggregatorInternalAbortsIf; } diff --git a/aptos-move/framework/supra-framework/sources/configs/consensus_config.spec.move b/aptos-move/framework/supra-framework/sources/configs/consensus_config.spec.move index 92b77ab44b094..61614cb738f16 100644 --- a/aptos-move/framework/supra-framework/sources/configs/consensus_config.spec.move +++ b/aptos-move/framework/supra-framework/sources/configs/consensus_config.spec.move @@ -8,7 +8,7 @@ spec supra_framework::consensus_config { /// Enforcement: Formally verified via [high-level-req-1](initialize). /// /// No.: 2 - /// Requirement: Only aptos framework account is allowed to update the consensus configuration. + /// Requirement: Only supra framework account is allowed to update the consensus configuration. /// Criticality: Medium /// Implementation: The consensus_config::set function ensures that the signer is supra_framework. /// Enforcement: Formally verified via [high-level-req-2](set). diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.move index a14869e5f57c8..edd2710770f08 100644 --- a/aptos-move/framework/supra-framework/sources/configs/evm_config.move +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.move @@ -8,6 +8,9 @@ module supra_framework::evm_config { friend supra_framework::genesis; friend supra_framework::reconfiguration_with_dkg; + + /// The struct stores the on-chain EVM configuration. + // Note: Serialized bytes of `OnChainEvmConfig` in rust layer. struct EvmConfig has drop, key, store { config: vector, } @@ -15,9 +18,10 @@ module supra_framework::evm_config { /// The provided on chain config bytes are empty or invalid const EINVALID_CONFIG: u64 = 1; + /// Publishes the EvmConfig config. public(friend) fun initialize(supra_framework: &signer, config: vector) { system_addresses::assert_supra_framework(supra_framework); - assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG)); + assert!(!vector::is_empty(&config), error::invalid_argument(EINVALID_CONFIG)); move_to(supra_framework, EvmConfig { config }); } @@ -29,7 +33,7 @@ module supra_framework::evm_config { /// ``` public fun set_for_next_epoch(account: &signer, config: vector) { system_addresses::assert_supra_framework(account); - assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG)); + assert!(!vector::is_empty(&config), error::invalid_argument(EINVALID_CONFIG)); std::config_buffer::upsert(EvmConfig {config}); } /// Only used in reconfigurations to apply the pending `EvmConfig` in buffer, if there is any. diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move index 6270c95ddb3c5..da20ca5a094cf 100644 --- a/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.spec.move @@ -1,5 +1,4 @@ spec supra_framework::evm_config { - spec module { pragma verify = true; pragma aborts_if_is_strict; diff --git a/aptos-move/framework/supra-framework/sources/configs/gas_schedule.spec.move b/aptos-move/framework/supra-framework/sources/configs/gas_schedule.spec.move index ef7adb907defe..c74bde2889c0f 100644 --- a/aptos-move/framework/supra-framework/sources/configs/gas_schedule.spec.move +++ b/aptos-move/framework/supra-framework/sources/configs/gas_schedule.spec.move @@ -11,7 +11,7 @@ spec supra_framework::gas_schedule { /// Requirement: Only the Supra framework account should be allowed to update the gas schedule resource. /// Criticality: Critical /// Implementation: The gas_schedule::set_gas_schedule function calls the assert_supra_framework function to ensure - /// that the signer is the aptos framework account. + /// that the signer is the supra framework account. /// Enforcement: Formally verified via [high-level-req-2](set_gas_schedule). /// /// No.: 3 @@ -39,7 +39,7 @@ spec supra_framework::gas_schedule { let addr = signer::address_of(supra_framework); /// [high-level-req-1] - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; /// [high-level-req-3.3] aborts_if len(gas_schedule_blob) == 0; aborts_if exists(addr); @@ -65,7 +65,7 @@ spec supra_framework::gas_schedule { include staking_config::StakingRewardsConfigRequirement; /// [high-level-req-2] - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; /// [high-level-req-3.2] aborts_if len(gas_schedule_blob) == 0; let new_gas_schedule = util::spec_from_bytes(gas_schedule_blob); @@ -87,7 +87,7 @@ spec supra_framework::gas_schedule { pragma verify_duration_estimate = 600; requires exists(@supra_framework); requires exists>(@supra_framework); - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; include transaction_fee::RequiresCollectedFeesPerValueLeqBlockAptosSupply; include staking_config::StakingRewardsConfigRequirement; aborts_if !exists(@supra_framework); @@ -97,7 +97,7 @@ spec supra_framework::gas_schedule { spec set_for_next_epoch(supra_framework: &signer, gas_schedule_blob: vector) { use supra_framework::util; - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; include config_buffer::SetForNextEpochAbortsIf { account: supra_framework, config: gas_schedule_blob @@ -113,7 +113,7 @@ spec supra_framework::gas_schedule { use std::features; use supra_framework::util; - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; include config_buffer::SetForNextEpochAbortsIf { account: supra_framework, config: new_gas_schedule_blob @@ -131,12 +131,12 @@ spec supra_framework::gas_schedule { } spec set_storage_gas_config(supra_framework: &signer, config: storage_gas::StorageGasConfig) { - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; aborts_if !exists(@supra_framework); } spec set_storage_gas_config_for_next_epoch(supra_framework: &signer, config: storage_gas::StorageGasConfig) { - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; aborts_if !exists(@supra_framework); } } diff --git a/aptos-move/framework/supra-framework/sources/configs/staking_config.move b/aptos-move/framework/supra-framework/sources/configs/staking_config.move index f79079402d05d..ad87e570564b6 100644 --- a/aptos-move/framework/supra-framework/sources/configs/staking_config.move +++ b/aptos-move/framework/supra-framework/sources/configs/staking_config.move @@ -304,7 +304,7 @@ module supra_framework::staking_config { } /// Update the recurring lockup duration. - /// Can only be called as part of the Supra governance proposal process established by the AptosGovernance module. + /// Can only be called as part of the Supra governance proposal process established by the SupraGovernance module. public fun update_recurring_lockup_duration_secs( supra_framework: &signer, new_recurring_lockup_duration_secs: u64 ) acquires StakingConfig { @@ -320,7 +320,7 @@ module supra_framework::staking_config { /// DEPRECATING /// Update the rewards rate. - /// Can only be called as part of the Supra governance proposal process established by the AptosGovernance module. + /// Can only be called as part of the Supra governance proposal process established by the SupraGovernance module. public fun update_rewards_rate( supra_framework: &signer, new_rewards_rate: u64, @@ -395,7 +395,7 @@ module supra_framework::staking_config { } /// Update the joining limit %. - /// Can only be called as part of the Supra governance proposal process established by the AptosGovernance module. + /// Can only be called as part of the Supra governance proposal process established by the SupraGovernance module. public fun update_voting_power_increase_limit( supra_framework: &signer, new_voting_power_increase_limit: u64 ) acquires StakingConfig { diff --git a/aptos-move/framework/supra-framework/sources/configs/version.spec.move b/aptos-move/framework/supra-framework/sources/configs/version.spec.move index 69345174ca667..efdc36c2e45a1 100644 --- a/aptos-move/framework/supra-framework/sources/configs/version.spec.move +++ b/aptos-move/framework/supra-framework/sources/configs/version.spec.move @@ -4,7 +4,7 @@ spec supra_framework::version { /// Requirement: During genesis, the Version resource should be initialized with the initial version and stored along /// with its capability under the supra framework account. /// Criticality: Medium - /// Implementation: The initialize function ensures that the signer is the aptos framework account and stores the + /// Implementation: The initialize function ensures that the signer is the supra framework account and stores the /// Version and SetVersionCapability resources in it. /// Enforcement: Formally verified via [high-level-req-1](initialize). /// diff --git a/aptos-move/framework/supra-framework/sources/genesis.move b/aptos-move/framework/supra-framework/sources/genesis.move index fdc65bb97fa0f..0880a66a17136 100644 --- a/aptos-move/framework/supra-framework/sources/genesis.move +++ b/aptos-move/framework/supra-framework/sources/genesis.move @@ -119,7 +119,7 @@ module supra_framework::genesis { unlock_period_duration: u64, } - /// Genesis step 1: Initialize aptos framework account and core modules on chain. + /// Genesis step 1: Initialize supra framework account and core modules on chain. fun initialize( gas_schedule: vector, chain_id: u8, @@ -138,11 +138,11 @@ module supra_framework::genesis { genesis_timestamp_in_microseconds: u64, evm_config: vector, ) { - // Initialize the aptos framework account. This is the account where system resources and modules will be + // Initialize the supra framework account. This is the account where system resources and modules will be // deployed to. This will be entirely managed by on-chain governance and no entities have the key or privileges // to use this account. let (supra_framework_account, supra_framework_signer_cap) = account::create_framework_reserved_account(@supra_framework); - // Initialize account configs on aptos framework account. + // Initialize account configs on supra framework account. account::initialize(&supra_framework_account); transaction_validation::initialize( @@ -156,7 +156,7 @@ module supra_framework::genesis { // Give the decentralized on-chain governance control over the core framework account. supra_governance::store_signer_cap(&supra_framework_account, @supra_framework, supra_framework_signer_cap); - // put reserved framework reserved accounts under aptos governance + // put reserved framework reserved accounts under supra governance let framework_reserved_addresses = vector
[@0x2, @0x3, @0x4, @0x5, @0x6, @0x7, @0x8, @0x9, @0xa]; while (!vector::is_empty(&framework_reserved_addresses)) { let address = vector::pop_back
(&mut framework_reserved_addresses); @@ -544,6 +544,7 @@ module supra_framework::genesis { ); } + fun create_vesting_without_staking_pools( vesting_pool_map : vector ) { diff --git a/aptos-move/framework/supra-framework/sources/genesis.spec.move b/aptos-move/framework/supra-framework/sources/genesis.spec.move index f5dfcc59d532f..8eb8dc6c33a04 100644 --- a/aptos-move/framework/supra-framework/sources/genesis.spec.move +++ b/aptos-move/framework/supra-framework/sources/genesis.spec.move @@ -13,7 +13,7 @@ spec supra_framework::genesis { /// Enforcement: Formally verified via [high-level-req-1](initialize). /// /// No.: 2 - /// Requirement: Addresses ranging from 0x0 - 0xa should be reserved for the framework and part of aptos governance. + /// Requirement: Addresses ranging from 0x0 - 0xa should be reserved for the framework and part of supra governance. /// Criticality: Critical /// Implementation: The function genesis::initialize calls account::create_framework_reserved_account for addresses /// 0x0, 0x2, 0x3, 0x4, ..., 0xa which creates an account and authentication_key for them. This should be formally @@ -51,7 +51,7 @@ spec supra_framework::genesis { pragma aborts_if_is_partial; include InitalizeRequires; - // property 2: Addresses ranging from 0x0 - 0xa should be reserved for the framework and part of aptos governance. + // property 2: Addresses ranging from 0x0 - 0xa should be reserved for the framework and part of supra governance. // 0x1's pre and post conditions are written in requires schema and the following group of ensures. /// [high-level-req-2] aborts_if exists(@0x0); @@ -100,7 +100,7 @@ spec supra_framework::genesis { } spec initialize_supra_coin { - // property 3: The Supra coin should be initialized during genesis and only the Aptos framework account should + // property 3: The Supra coin should be initialized during genesis and only the Supra framework account should // own the mint and burn capabilities for the SUPRA token. /// [high-level-req-3] requires !exists(@supra_framework); diff --git a/aptos-move/framework/supra-framework/sources/governance_proposal.move b/aptos-move/framework/supra-framework/sources/governance_proposal.move index 894791916e8c2..5c6a1c2920e04 100644 --- a/aptos-move/framework/supra-framework/sources/governance_proposal.move +++ b/aptos-move/framework/supra-framework/sources/governance_proposal.move @@ -1,17 +1,17 @@ -/// Define the GovernanceProposal that will be used as part of on-chain governance by AptosGovernance. +/// Define the GovernanceProposal that will be used as part of on-chain governance by SupraGovernance. /// -/// This is separate from the AptosGovernance module to avoid circular dependency between AptosGovernance and Stake. +/// This is separate from the SupraGovernance module to avoid circular dependency between SupraGovernance and Stake. module supra_framework::governance_proposal { friend supra_framework::supra_governance; struct GovernanceProposal has store, drop {} - /// Create and return a GovernanceProposal resource. Can only be called by AptosGovernance + /// Create and return a GovernanceProposal resource. Can only be called by SupraGovernance public(friend) fun create_proposal(): GovernanceProposal { GovernanceProposal {} } - /// Useful for AptosGovernance to create an empty proposal as proof. + /// Useful for SupraGovernance to create an empty proposal as proof. public(friend) fun create_empty_proposal(): GovernanceProposal { create_proposal() } diff --git a/aptos-move/framework/supra-framework/sources/governance_proposal.spec.move b/aptos-move/framework/supra-framework/sources/governance_proposal.spec.move index 5923e7c2cd8b7..b52aae4154aa2 100644 --- a/aptos-move/framework/supra-framework/sources/governance_proposal.spec.move +++ b/aptos-move/framework/supra-framework/sources/governance_proposal.spec.move @@ -7,7 +7,7 @@ spec supra_framework::governance_proposal { /// Enforcement: Enforced via [high-level-req-1.1](create_proposal) and [high-level-req-1.2](create_empty_proposal). /// /// No.: 2 - /// Requirement: The governance proposal module should only be accessible to the aptos governance. + /// Requirement: The governance proposal module should only be accessible to the supra governance. /// Criticality: Medium /// Implementation: Both create_proposal and create_empty_proposal functions are only available to the friend module /// supra_framework::supra_governance. diff --git a/aptos-move/framework/supra-framework/sources/reconfiguration.spec.move b/aptos-move/framework/supra-framework/sources/reconfiguration.spec.move index 8174f259d761d..c2e2e36f3e6e8 100644 --- a/aptos-move/framework/supra-framework/sources/reconfiguration.spec.move +++ b/aptos-move/framework/supra-framework/sources/reconfiguration.spec.move @@ -53,7 +53,7 @@ spec supra_framework::reconfiguration { } /// Make sure the signer address is @supra_framework. - spec schema AbortsIfNotAptosFramework { + spec schema AbortsIfNotSupraFramework { supra_framework: &signer; let addr = signer::address_of(supra_framework); @@ -68,14 +68,14 @@ spec supra_framework::reconfiguration { use supra_framework::account::{Account}; use supra_framework::guid; - include AbortsIfNotAptosFramework; + include AbortsIfNotSupraFramework; let addr = signer::address_of(supra_framework); let post config = global(@supra_framework); requires exists(addr); aborts_if !(global(addr).guid_creation_num == 2); aborts_if exists(@supra_framework); // property 1: During the module's initialization, it guarantees that the Configuration resource will move under - // the Aptos framework account with initial values. + // the Supra framework account with initial values. /// [high-level-req-1] ensures exists(@supra_framework); ensures config.epoch == 0 && config.last_reconfiguration_time == 0; @@ -96,7 +96,7 @@ spec supra_framework::reconfiguration { } spec disable_reconfiguration(supra_framework: &signer) { - include AbortsIfNotAptosFramework; + include AbortsIfNotSupraFramework; aborts_if exists(@supra_framework); ensures exists(@supra_framework); } @@ -104,7 +104,7 @@ spec supra_framework::reconfiguration { /// Make sure the caller is admin and check the resource DisableReconfiguration. spec enable_reconfiguration(supra_framework: &signer) { use supra_framework::reconfiguration::{DisableReconfiguration}; - include AbortsIfNotAptosFramework; + include AbortsIfNotSupraFramework; aborts_if !exists(@supra_framework); ensures !exists(@supra_framework); } diff --git a/aptos-move/framework/supra-framework/sources/storage_gas.spec.move b/aptos-move/framework/supra-framework/sources/storage_gas.spec.move index 90a6681734ed5..2458ae4254ecd 100644 --- a/aptos-move/framework/supra-framework/sources/storage_gas.spec.move +++ b/aptos-move/framework/supra-framework/sources/storage_gas.spec.move @@ -120,7 +120,7 @@ spec supra_framework::storage_gas { /// Signer address must be @supra_framework and StorageGasConfig exists. spec set_config(supra_framework: &signer, config: StorageGasConfig) { - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; aborts_if !exists(@supra_framework); } @@ -128,7 +128,7 @@ spec supra_framework::storage_gas { /// Address @supra_framework does not exist StorageGasConfig and StorageGas before the function call is restricted /// and exists after the function is executed. spec initialize(supra_framework: &signer) { - include system_addresses::AbortsIfNotAptosFramework{ account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework{ account: supra_framework }; pragma verify_duration_estimate = 120; aborts_if exists(@supra_framework); aborts_if exists(@supra_framework); diff --git a/aptos-move/framework/supra-framework/sources/supra_coin.move b/aptos-move/framework/supra-framework/sources/supra_coin.move index c17b12749c6e1..a4d5bf20fd826 100644 --- a/aptos-move/framework/supra-framework/sources/supra_coin.move +++ b/aptos-move/framework/supra-framework/sources/supra_coin.move @@ -64,7 +64,7 @@ module supra_framework::supra_coin { exists(signer::address_of(account)) } - /// Only called during genesis to destroy the aptos framework account's mint capability once all initial validators + /// Only called during genesis to destroy the supra framework account's mint capability once all initial validators /// and accounts have been initialized during genesis. public(friend) fun destroy_mint_cap(supra_framework: &signer) acquires MintCapStore { system_addresses::assert_supra_framework(supra_framework); @@ -72,7 +72,7 @@ module supra_framework::supra_coin { coin::destroy_mint_cap(mint_cap); } - /// Can only be called during genesis for tests to grant mint capability to aptos framework and core resources + /// Can only be called during genesis for tests to grant mint capability to supra framework and core resources /// accounts. /// Expects account and SUPRA store to be registered before calling. public(friend) fun configure_accounts_for_test( diff --git a/aptos-move/framework/supra-framework/sources/supra_governance.move b/aptos-move/framework/supra-framework/sources/supra_governance.move index 88592a19eb49b..6f49a9b437810 100644 --- a/aptos-move/framework/supra-framework/sources/supra_governance.move +++ b/aptos-move/framework/supra-framework/sources/supra_governance.move @@ -4,7 +4,7 @@ /// the stake pool's lockup needs to be at least as long as the proposal's duration. /// /// It provides the following flow: -/// 1. Proposers can create a proposal by calling AptosGovernance::create_proposal. The proposer's backing stake pool +/// 1. Proposers can create a proposal by calling SupraGovernance::create_proposal. The proposer's backing stake pool /// needs to have the minimum proposer stake required. Off-chain components can subscribe to CreateProposalEvent to /// track proposal creation and proposal ids. /// 2. Voters can vote on a proposal. Their voting power is derived from the backing stake pool. A stake pool can vote @@ -179,7 +179,7 @@ module supra_framework::supra_governance { } /// Update the governance configurations. This can only be called as part of resolving a proposal in this same - /// AptosGovernance. + /// SupraGovernance. public fun update_supra_governance_config( supra_framework: &signer, voting_duration_secs: u64, diff --git a/aptos-move/framework/supra-framework/sources/system_addresses.spec.move b/aptos-move/framework/supra-framework/sources/system_addresses.spec.move index f6c64ce9ed406..ed61c55faa275 100644 --- a/aptos-move/framework/supra-framework/sources/system_addresses.spec.move +++ b/aptos-move/framework/supra-framework/sources/system_addresses.spec.move @@ -14,7 +14,7 @@ spec supra_framework::system_addresses { /// Criticality: High /// Implementation: The assert_supra_framework function ensures that the provided signer belongs to the /// @supra_framework account. - /// Enforcement: Formally verified via [high-level-req-2](AbortsIfNotAptosFramework). + /// Enforcement: Formally verified via [high-level-req-2](AbortsIfNotSupraFramework). /// /// No.: 3 /// Requirement: Asserting that a provided address corresponds to the VM address should always yield a true result when @@ -54,7 +54,7 @@ spec supra_framework::system_addresses { spec assert_supra_framework(account: &signer) { pragma opaque; - include AbortsIfNotAptosFramework; + include AbortsIfNotSupraFramework; } spec assert_framework_reserved_address(account: &signer) { @@ -64,8 +64,8 @@ spec supra_framework::system_addresses { spec assert_framework_reserved(addr: address) { aborts_if !is_framework_reserved_address(addr); } - /// Specifies that a function aborts if the account does not have the aptos framework address. - spec schema AbortsIfNotAptosFramework { + /// Specifies that a function aborts if the account does not have the supra framework address. + spec schema AbortsIfNotSupraFramework { account: signer; /// [high-level-req-2] aborts_if signer::address_of(account) != @supra_framework with error::PERMISSION_DENIED; diff --git a/aptos-move/framework/supra-framework/sources/timestamp.move b/aptos-move/framework/supra-framework/sources/timestamp.move index 4c9f25bd06c82..e126a3c656ccd 100644 --- a/aptos-move/framework/supra-framework/sources/timestamp.move +++ b/aptos-move/framework/supra-framework/sources/timestamp.move @@ -21,7 +21,7 @@ module supra_framework::timestamp { /// An invalid timestamp was provided const EINVALID_TIMESTAMP: u64 = 2; - /// Marks that time has started. This can only be called from genesis and with the aptos framework account. + /// Marks that time has started. This can only be called from genesis and with the supra framework account. public(friend) fun set_time_has_started(supra_framework: &signer, start_time_in_microseconds: u64) { system_addresses::assert_supra_framework(supra_framework); let timer = CurrentTimeMicroseconds { microseconds: start_time_in_microseconds }; diff --git a/aptos-move/framework/supra-framework/sources/transaction_fee.spec.move b/aptos-move/framework/supra-framework/sources/transaction_fee.spec.move index 0464966ff45f0..39664c7974c41 100644 --- a/aptos-move/framework/supra-framework/sources/transaction_fee.spec.move +++ b/aptos-move/framework/supra-framework/sources/transaction_fee.spec.move @@ -84,7 +84,7 @@ spec supra_framework::transaction_fee { aborts_if !system_addresses::is_supra_framework_address(aptos_addr); aborts_if exists(aptos_addr); - include system_addresses::AbortsIfNotAptosFramework { account: supra_framework }; + include system_addresses::AbortsIfNotSupraFramework { account: supra_framework }; include aggregator_factory::CreateAggregatorInternalAbortsIf; aborts_if exists(aptos_addr); diff --git a/aptos-move/framework/supra-framework/sources/voting.move b/aptos-move/framework/supra-framework/sources/voting.move index 27e8a46cb88ef..d027efa26c439 100644 --- a/aptos-move/framework/supra-framework/sources/voting.move +++ b/aptos-move/framework/supra-framework/sources/voting.move @@ -6,7 +6,7 @@ /// /// The voting flow: /// 1. The Voting module can be deployed at a known address (e.g. 0x1 for Supra on-chain governance) -/// 2. The governance module, e.g. AptosGovernance, can be deployed later and define a GovernanceProposal resource type +/// 2. The governance module, e.g. SupraGovernance, can be deployed later and define a GovernanceProposal resource type /// that can also contain other information such as Capability resource for authorization. /// 3. The governance module's owner can then register the ProposalType with Voting. This also hosts the proposal list /// (forum) on the calling account. diff --git a/crates/aptos/src/test/mod.rs b/crates/aptos/src/test/mod.rs index 6d7d2ef1ddf77..eedf5cd9f6010 100644 --- a/crates/aptos/src/test/mod.rs +++ b/crates/aptos/src/test/mod.rs @@ -1182,7 +1182,6 @@ impl CliTestFramework { is_multi_step: bool, ) -> CliTypedResult { SubmitProposal { - // pool_address_args: PoolAddressArgs { pool_address }, args: SubmitProposalArgs { #[cfg(feature = "no-upload-proposal")] metadata_path: None, diff --git a/testsuite/smoke-test/src/lib.rs b/testsuite/smoke-test/src/lib.rs index 84b0a815b8403..f0b03818c0096 100644 --- a/testsuite/smoke-test/src/lib.rs +++ b/testsuite/smoke-test/src/lib.rs @@ -37,7 +37,7 @@ mod randomness; #[cfg(test)] mod rest_api; #[cfg(test)] -// mod rosetta; +// mod rosetta; // The test is disabled because it has compilation errors #[cfg(test)] mod state_sync; #[cfg(test)] diff --git a/types/src/on_chain_config/evm_config.rs b/types/src/on_chain_config/evm_config.rs index 2fe51f0277921..bae4b63a43c96 100644 --- a/types/src/on_chain_config/evm_config.rs +++ b/types/src/on_chain_config/evm_config.rs @@ -1,4 +1,4 @@ -// Copyright (c) Aptos Foundation +// Copyright (c) Supra Foundation // SPDX-License-Identifier: Apache-2.0 use serde::{Deserialize, Serialize}; From fe4fd6193dd9e91e834d13a474228e8fd7fd6424 Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Mon, 17 Feb 2025 15:09:41 +0100 Subject: [PATCH 07/12] fix bls test --- .../sources/cryptography/bls12381.move | 18 +++++++++--------- .../src/unit_tests/bls12381_test.rs | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move b/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move index 86f74d4fe7e43..f924d19155c15 100644 --- a/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move +++ b/aptos-move/framework/aptos-stdlib/sources/cryptography/bls12381.move @@ -480,12 +480,12 @@ module aptos_std::bls12381 { // /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. - /// The message signed is "Hello Supra!" and the associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. - const RANDOM_SIGNATURE: vector = x"a01a65854f987d3434149b7f08f70730e30b241984e8712bc2aca885d632aafced4c3f661209debb6b1c8601326623cc16ca2f6c9edc53b7b88b7435fb6b05ddece418d2c34dc6aca2f5a11a79e67774582c14084a01dcb7820e4cb4bad0ea8d"; + /// The message signed is "Hello Supra!" and the associated SK is 2692ef93b9f00fde863c8cf01755ddfc7a56c993f2310a1dea0773c14382c455. + const RANDOM_SIGNATURE: vector = x"8263cc8197e0f4b5f0bc8d2344ea6629b3d22d3088c979cb67375734b4f533609b0c7e7ee40cd3e2b3427023d5596ad10556e010fc24179dc922185e80b037e287e45c77a4ff71cce152d467aed0704a40dddf88fc668ea605da702e8cb10c04"; /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. - /// The associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. - const RANDOM_PK: vector = x"8a53e7ae5270e3e765cd8a4032c2e77c6f7e87a44ebb85bf28a4d7865565698f975346714262f9e47c6f3e0d5d951660"; + /// The associated SK is 2692ef93b9f00fde863c8cf01755ddfc7a56c993f2310a1dea0773c14382c455. + const RANDOM_PK: vector = x"8856a63c1d9679f0cfee94844923736d79d7ad3730429075cee2efe9476fe94248a72fad10dfa94e7e287456b803da0f"; // // Tests @@ -845,23 +845,23 @@ module aptos_std::bls12381 { // Test case generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in // `crates/aptos-crypto` // ============================================================================================================= - // SK: 077c8a56f26259215a4a245373ab6ddf328ac6e00e5ea38d8700efa361bdc58d + // SK: 2692ef93b9f00fde863c8cf01755ddfc7a56c993f2310a1dea0773c14382c455 let message = b"Hello Supra!"; // First, test signatures that verify let ok = verify_normal_signature( - &signature_from_bytes(x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7"), - &option::extract(&mut public_key_from_bytes(x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858")), + &signature_from_bytes(RANDOM_SIGNATURE), + &option::extract(&mut public_key_from_bytes(RANDOM_PK)), message, ); assert!(ok == true, 1); - let pk = option::extract(&mut public_key_from_bytes(x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858")); + let pk = option::extract(&mut public_key_from_bytes(RANDOM_PK)); let pk_with_pop = PublicKeyWithPoP { bytes: pk.bytes }; let ok = verify_signature_share( - &signature_from_bytes(x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7"), + &signature_from_bytes(RANDOM_SIGNATURE), &pk_with_pop, message, ); diff --git a/crates/aptos-crypto/src/unit_tests/bls12381_test.rs b/crates/aptos-crypto/src/unit_tests/bls12381_test.rs index 40be873cfa414..a9ac11979044a 100644 --- a/crates/aptos-crypto/src/unit_tests/bls12381_test.rs +++ b/crates/aptos-crypto/src/unit_tests/bls12381_test.rs @@ -418,7 +418,7 @@ fn bls12381_sample_signature() { let sk = keypair.private_key; let pk = keypair.public_key; - let message = b"Hello Aptos!"; + let message = b"Hello Supra!"; let signature = sk.sign_arbitrary_message(message); println!("SK: {}", hex::encode(sk.to_bytes())); From 7362d1a7abf8a9bbeb822e9c00f66aada8772094 Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Tue, 18 Feb 2025 16:58:29 +0100 Subject: [PATCH 08/12] add todo docs --- .../framework/supra-framework/sources/configs/evm_config.move | 1 + types/src/on_chain_config/evm_config.rs | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/aptos-move/framework/supra-framework/sources/configs/evm_config.move b/aptos-move/framework/supra-framework/sources/configs/evm_config.move index edd2710770f08..cf11719bd395d 100644 --- a/aptos-move/framework/supra-framework/sources/configs/evm_config.move +++ b/aptos-move/framework/supra-framework/sources/configs/evm_config.move @@ -36,6 +36,7 @@ module supra_framework::evm_config { assert!(!vector::is_empty(&config), error::invalid_argument(EINVALID_CONFIG)); std::config_buffer::upsert(EvmConfig {config}); } + /// Only used in reconfigurations to apply the pending `EvmConfig` in buffer, if there is any. /// If supra_framework has a EvmConfig, then update the new config to supra_framework. /// Otherwise, move the new config to supra_framework. diff --git a/types/src/on_chain_config/evm_config.rs b/types/src/on_chain_config/evm_config.rs index bae4b63a43c96..09eed9148682d 100644 --- a/types/src/on_chain_config/evm_config.rs +++ b/types/src/on_chain_config/evm_config.rs @@ -16,10 +16,11 @@ pub struct EvmConfigV1 { } impl OnChainEvmConfig { + /// TODO: remove, and allow config from genesis parameter. pub fn default_for_test() -> Self { Self::V1(EvmConfigV1 { chain_id: 0x12_3456_7890 }) } - + /// TODO: remove, and allow config from genesis parameter. pub fn default_for_mainnet() -> Self { Self::V1(EvmConfigV1 { chain_id: 0xffff_aaaa_eeee }) } From 85de60c12ca78b31d0ee3f349476a7c620e5367e Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Tue, 18 Feb 2025 18:22:31 +0100 Subject: [PATCH 09/12] update generated .md files --- .../framework/aptos-stdlib/doc/bls12381.md | 8 ++-- .../framework/supra-framework/doc/account.md | 4 +- .../framework/supra-framework/doc/block.md | 40 +++++++++---------- .../supra-framework/doc/gas_schedule.md | 6 +-- .../supra-framework/doc/multisig_account.md | 4 +- .../supra-framework/doc/multisig_voting.md | 4 +- .../framework/supra-framework/doc/object.md | 16 ++++---- .../supra-framework/doc/randomness.md | 6 +-- .../supra-framework/doc/supra_governance.md | 6 +-- .../framework/supra-framework/doc/voting.md | 4 +- 10 files changed, 49 insertions(+), 49 deletions(-) diff --git a/aptos-move/framework/aptos-stdlib/doc/bls12381.md b/aptos-move/framework/aptos-stdlib/doc/bls12381.md index c28a8fb58bd26..1dfebbce4acaf 100644 --- a/aptos-move/framework/aptos-stdlib/doc/bls12381.md +++ b/aptos-move/framework/aptos-stdlib/doc/bls12381.md @@ -313,10 +313,10 @@ The public key size, in bytes Random signature generated by running cargo test -- bls12381_sample_signature --nocapture --include-ignored in crates/aptos-crypto. -The associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. +The associated SK is 2692ef93b9f00fde863c8cf01755ddfc7a56c993f2310a1dea0773c14382c455. -
const RANDOM_PK: vector<u8> = [138, 83, 231, 174, 82, 112, 227, 231, 101, 205, 138, 64, 50, 194, 231, 124, 111, 126, 135, 164, 78, 187, 133, 191, 40, 164, 215, 134, 85, 101, 105, 143, 151, 83, 70, 113, 66, 98, 249, 228, 124, 111, 62, 13, 93, 149, 22, 96];
+
const RANDOM_PK: vector<u8> = [136, 86, 166, 60, 29, 150, 121, 240, 207, 238, 148, 132, 73, 35, 115, 109, 121, 215, 173, 55, 48, 66, 144, 117, 206, 226, 239, 233, 71, 111, 233, 66, 72, 167, 47, 173, 16, 223, 169, 78, 126, 40, 116, 86, 184, 3, 218, 15];
 
@@ -324,10 +324,10 @@ The associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc Random signature generated by running cargo test -- bls12381_sample_signature --nocapture --include-ignored in crates/aptos-crypto. -The message signed is "Hello Supra!" and the associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. +The message signed is "Hello Supra!" and the associated SK is 2692ef93b9f00fde863c8cf01755ddfc7a56c993f2310a1dea0773c14382c455. -
const RANDOM_SIGNATURE: vector<u8> = [160, 26, 101, 133, 79, 152, 125, 52, 52, 20, 155, 127, 8, 247, 7, 48, 227, 11, 36, 25, 132, 232, 113, 43, 194, 172, 168, 133, 214, 50, 170, 252, 237, 76, 63, 102, 18, 9, 222, 187, 107, 28, 134, 1, 50, 102, 35, 204, 22, 202, 47, 108, 158, 220, 83, 183, 184, 139, 116, 53, 251, 107, 5, 221, 236, 228, 24, 210, 195, 77, 198, 172, 162, 245, 161, 26, 121, 230, 119, 116, 88, 44, 20, 8, 74, 1, 220, 183, 130, 14, 76, 180, 186, 208, 234, 141];
+
const RANDOM_SIGNATURE: vector<u8> = [130, 99, 204, 129, 151, 224, 244, 181, 240, 188, 141, 35, 68, 234, 102, 41, 179, 210, 45, 48, 136, 201, 121, 203, 103, 55, 87, 52, 180, 245, 51, 96, 155, 12, 126, 126, 228, 12, 211, 226, 179, 66, 112, 35, 213, 89, 106, 209, 5, 86, 224, 16, 252, 36, 23, 157, 201, 34, 24, 94, 128, 176, 55, 226, 135, 228, 92, 119, 164, 255, 113, 204, 225, 82, 212, 103, 174, 208, 112, 74, 64, 221, 223, 136, 252, 102, 142, 166, 5, 218, 112, 46, 140, 177, 12, 4];
 
diff --git a/aptos-move/framework/supra-framework/doc/account.md b/aptos-move/framework/supra-framework/doc/account.md index 4fc29c93fda93..732c5684af74a 100644 --- a/aptos-move/framework/supra-framework/doc/account.md +++ b/aptos-move/framework/supra-framework/doc/account.md @@ -102,7 +102,7 @@ use 0x1::features; use 0x1::from_bcs; use 0x1::guid; -use 0x1::hash; +use 0x1::hash; use 0x1::multi_ed25519; use 0x1::option; use 0x1::signer; @@ -1929,7 +1929,7 @@ involves the use of a cryptographic hash operation and should be use thoughtfull let bytes = bcs::to_bytes(source); vector::append(&mut bytes, seed); vector::push_back(&mut bytes, DERIVE_RESOURCE_ACCOUNT_SCHEME); - from_bcs::to_address(hash::sha3_256(bytes)) + from_bcs::to_address(hash::sha3_256(bytes)) }
diff --git a/aptos-move/framework/supra-framework/doc/block.md b/aptos-move/framework/supra-framework/doc/block.md index 29402816443c2..ac8b98cabfd93 100644 --- a/aptos-move/framework/supra-framework/doc/block.md +++ b/aptos-move/framework/supra-framework/doc/block.md @@ -163,7 +163,7 @@ Should be in-sync with NewBlockEvent rust struct in new_block.rs
-hash: address +hash: address
@@ -268,7 +268,7 @@ Should be in-sync with NewBlockEvent rust struct in new_block.rs
-hash: address +hash: address
@@ -557,7 +557,7 @@ Return epoch interval in seconds. -
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
+
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
 
@@ -568,7 +568,7 @@ Return epoch interval in seconds.
fun block_prologue_common(
     vm: &signer,
-    hash: address,
+    hash: address,
     epoch: u64,
     round: u64,
     proposer: address,
@@ -595,7 +595,7 @@ Return epoch interval in seconds.
 
     // Emit both event v1 and v2 for compatibility. Eventually only module events will be kept.
     let new_block_event = NewBlockEvent {
-        hash,
+        hash,
         epoch,
         round,
         height: block_metadata_ref.height,
@@ -605,7 +605,7 @@ Return epoch interval in seconds.
         time_microseconds: timestamp,
     };
     let new_block_event_v2 = NewBlock {
-        hash,
+        hash,
         epoch,
         round,
         height: block_metadata_ref.height,
@@ -646,7 +646,7 @@ Set the metadata for the current block.
 The runtime always runs this before executing the transactions in a block.
 
 
-
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
+
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
 
@@ -657,7 +657,7 @@ The runtime always runs this before executing the transactions in a block.
fun block_prologue(
     vm: signer,
-    hash: address,
+    hash: address,
     epoch: u64,
     round: u64,
     proposer: address,
@@ -665,7 +665,7 @@ The runtime always runs this before executing the transactions in a block.
     previous_block_votes_bitvec: vector<u8>,
     timestamp: u64
 ) acquires BlockResource, CommitHistory {
-    let epoch_interval = block_prologue_common(&vm, hash, epoch, round, proposer, failed_proposer_indices, previous_block_votes_bitvec, timestamp);
+    let epoch_interval = block_prologue_common(&vm, hash, epoch, round, proposer, failed_proposer_indices, previous_block_votes_bitvec, timestamp);
     randomness::on_new_block(&vm, epoch, round, option::none());
     if (timestamp - reconfiguration::last_reconfiguration_time() >= epoch_interval) {
         reconfiguration::reconfigure();
@@ -684,7 +684,7 @@ The runtime always runs this before executing the transactions in a block.
 block_prologue() but trigger reconfiguration with DKG after epoch timed out.
 
 
-
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
+
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
 
@@ -695,7 +695,7 @@ The runtime always runs this before executing the transactions in a block.
fun block_prologue_ext(
     vm: signer,
-    hash: address,
+    hash: address,
     epoch: u64,
     round: u64,
     proposer: address,
@@ -706,7 +706,7 @@ The runtime always runs this before executing the transactions in a block.
 ) acquires BlockResource, CommitHistory {
     let epoch_interval = block_prologue_common(
         &vm,
-        hash,
+        hash,
         epoch,
         round,
         proposer,
@@ -826,7 +826,7 @@ reconfiguration event.
         &vm,
         &mut block_metadata_ref.new_block_events,
         NewBlockEvent {
-            hash: genesis_id,
+            hash: genesis_id,
             epoch: 0,
             round: 0,
             height: 0,
@@ -836,7 +836,7 @@ reconfiguration event.
             time_microseconds: timestamp::now_microseconds(),
         },
         NewBlock {
-            hash: genesis_id,
+            hash: genesis_id,
             epoch: 0,
             round: 0,
             height: 0,
@@ -879,7 +879,7 @@ new block event for WriteSetPayload.
         vm_signer,
         &mut block_metadata_ref.new_block_events,
         NewBlockEvent {
-            hash: fake_block_hash,
+            hash: fake_block_hash,
             epoch: reconfiguration::current_epoch(),
             round: MAX_U64,
             height: block_metadata_ref.height,
@@ -889,7 +889,7 @@ new block event for WriteSetPayload.
             time_microseconds: timestamp::now_microseconds(),
         },
         NewBlock {
-            hash: fake_block_hash,
+            hash: fake_block_hash,
             epoch: reconfiguration::current_epoch(),
             round: MAX_U64,
             height: block_metadata_ref.height,
@@ -1094,7 +1094,7 @@ The number of new events created does not exceed MAX_U64.
 
 
schema BlockRequirement {
     vm: signer;
-    hash: address;
+    hash: address;
     epoch: u64;
     round: u64;
     proposer: address;
@@ -1213,7 +1213,7 @@ The BlockResource existed under the @supra_framework.
 ### Function `block_prologue_common`
 
 
-
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
+
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
 
@@ -1231,7 +1231,7 @@ The BlockResource existed under the @supra_framework. ### Function `block_prologue` -
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
+
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
 
@@ -1250,7 +1250,7 @@ The BlockResource existed under the @supra_framework. ### Function `block_prologue_ext` -
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
+
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
 
diff --git a/aptos-move/framework/supra-framework/doc/gas_schedule.md b/aptos-move/framework/supra-framework/doc/gas_schedule.md index 8af2b941e8668..c899966f021e4 100644 --- a/aptos-move/framework/supra-framework/doc/gas_schedule.md +++ b/aptos-move/framework/supra-framework/doc/gas_schedule.md @@ -30,7 +30,7 @@ it costs to execute Move on the network. - [Function `set_storage_gas_config_for_next_epoch`](#@Specification_1_set_storage_gas_config_for_next_epoch) -
use 0x1::aptos_hash;
+
use 0x1::aptos_hash;
 use 0x1::bcs;
 use 0x1::chain_status;
 use 0x1::config_buffer;
@@ -328,7 +328,7 @@ Require a hash of the old gas schedule to be provided and will abort if the hash
             error::invalid_argument(EINVALID_GAS_FEATURE_VERSION)
         );
         let cur_gas_schedule_bytes = bcs::to_bytes(cur_gas_schedule);
-        let cur_gas_schedule_hash = aptos_hash::sha3_512(cur_gas_schedule_bytes);
+        let cur_gas_schedule_hash = aptos_hash::sha3_512(cur_gas_schedule_bytes);
         assert!(
             cur_gas_schedule_hash == old_gas_schedule_hash,
             error::invalid_argument(EINVALID_GAS_SCHEDULE_HASH)
@@ -586,7 +586,7 @@ Only used in reconfigurations to apply the pending util::spec_from_bytes<GasScheduleV2>(new_gas_schedule_blob);
 let cur_gas_schedule = global<GasScheduleV2>(@supra_framework);
 aborts_if exists<GasScheduleV2>(@supra_framework) && new_gas_schedule.feature_version < cur_gas_schedule.feature_version;
-aborts_if exists<GasScheduleV2>(@supra_framework) && (!features::spec_sha_512_and_ripemd_160_enabled() || aptos_hash::spec_sha3_512_internal(bcs::serialize(cur_gas_schedule)) != old_gas_schedule_hash);
+aborts_if exists<GasScheduleV2>(@supra_framework) && (!features::spec_sha_512_and_ripemd_160_enabled() || aptos_hash::spec_sha3_512_internal(bcs::serialize(cur_gas_schedule)) != old_gas_schedule_hash);
 
diff --git a/aptos-move/framework/supra-framework/doc/multisig_account.md b/aptos-move/framework/supra-framework/doc/multisig_account.md index 5a7fabf9ea7e3..8dc5f656b7b29 100644 --- a/aptos-move/framework/supra-framework/doc/multisig_account.md +++ b/aptos-move/framework/supra-framework/doc/multisig_account.md @@ -154,7 +154,7 @@ and implement the governance voting logic on top. use 0x1::error; use 0x1::event; use 0x1::features; -use 0x1::hash; +use 0x1::hash; use 0x1::option; use 0x1::signer; use 0x1::simple_map; @@ -2926,7 +2926,7 @@ to provide the full payload, which will be validated against the hash stored on- multisig_account: address, payload_hash: vector<u8>, ) acquires MultisigAccount { - // Payload hash is a sha3-256 hash, so it must be exactly 32 bytes. + // Payload hash is a sha3-256 hash, so it must be exactly 32 bytes. assert!(vector::length(&payload_hash) == 32, error::invalid_argument(EINVALID_PAYLOAD_HASH)); assert_multisig_account_exists(multisig_account); diff --git a/aptos-move/framework/supra-framework/doc/multisig_voting.md b/aptos-move/framework/supra-framework/doc/multisig_voting.md index 26a2d464452e8..f9e1349f786a6 100644 --- a/aptos-move/framework/supra-framework/doc/multisig_voting.md +++ b/aptos-move/framework/supra-framework/doc/multisig_voting.md @@ -942,7 +942,7 @@ resolve this proposal. is_multi_step_proposal: bool, ): u64 acquires VotingForum { - // Make sure the execution script's hash is not empty. + // Make sure the execution script's hash is not empty. assert!(vector::length(&execution_hash) != 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); assert!(min_vote_threshold > 1, error::invalid_argument(ETHRESHOLD_MUST_BE_GREATER_THAN_ONE)); @@ -1297,7 +1297,7 @@ there are more yes votes than no. If either of these conditions is not met, this }; } else { // If the current step is not the last step, - // update the proposal's execution hash on-chain to the execution hash of the next step. + // update the proposal's execution hash on-chain to the execution hash of the next step. proposal.execution_hash = next_execution_hash; }; diff --git a/aptos-move/framework/supra-framework/doc/object.md b/aptos-move/framework/supra-framework/doc/object.md index f59f5def50f92..49563de509864 100644 --- a/aptos-move/framework/supra-framework/doc/object.md +++ b/aptos-move/framework/supra-framework/doc/object.md @@ -143,7 +143,7 @@ make it so that a reference to a global object can be returned from a function. use 0x1::features; use 0x1::from_bcs; use 0x1::guid; -use 0x1::hash; +use 0x1::hash; use 0x1::signer; use 0x1::transaction_context; use 0x1::vector; @@ -911,7 +911,7 @@ Derives an object address from source material: sha3_256([creator address | seed let bytes = bcs::to_bytes(source); vector::append(&mut bytes, seed); vector::push_back(&mut bytes, OBJECT_FROM_SEED_ADDRESS_SCHEME); - from_bcs::to_address(hash::sha3_256(bytes)) + from_bcs::to_address(hash::sha3_256(bytes)) }
@@ -964,7 +964,7 @@ Derives an object address from the source address and an object: sha3_256([sourc let bytes = bcs::to_bytes(&source); vector::append(&mut bytes, bcs::to_bytes(&derive_from)); vector::push_back(&mut bytes, OBJECT_DERIVED_SCHEME); - from_bcs::to_address(hash::sha3_256(bytes)) + from_bcs::to_address(hash::sha3_256(bytes)) } }
@@ -993,7 +993,7 @@ Derives an object from an Account GUID. let id = guid::create_id(source, creation_num); let bytes = bcs::to_bytes(&id); vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME); - from_bcs::to_address(hash::sha3_256(bytes)) + from_bcs::to_address(hash::sha3_256(bytes)) }
@@ -1293,7 +1293,7 @@ doesn't have the same bottlenecks.
fun create_object_from_guid(creator_address: address, guid: guid::GUID): ConstructorRef {
     let bytes = bcs::to_bytes(&guid);
     vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME);
-    let obj_addr = from_bcs::to_address(hash::sha3_256(bytes));
+    let obj_addr = from_bcs::to_address(hash::sha3_256(bytes));
     create_object_internal(creator_address, obj_addr, true)
 }
 
@@ -2771,7 +2771,7 @@ to determine the identity of the starting point of ownership. }; let bytes_spec = bcs::to_bytes(guid); let bytes = concat(bytes_spec, vec<u8>(OBJECT_FROM_GUID_ADDRESS_SCHEME)); -let hash_bytes = hash::sha3_256(bytes); +let hash_bytes = hash::sha3_256(bytes); let obj_addr = from_bcs::deserialize<address>(hash_bytes); aborts_if exists<ObjectCore>(obj_addr); aborts_if !from_bcs::deserializable<address>(hash_bytes); @@ -2823,7 +2823,7 @@ to determine the identity of the starting point of ownership. }; let bytes_spec = bcs::to_bytes(guid); let bytes = concat(bytes_spec, vec<u8>(OBJECT_FROM_GUID_ADDRESS_SCHEME)); -let hash_bytes = hash::sha3_256(bytes); +let hash_bytes = hash::sha3_256(bytes); let obj_addr = from_bcs::deserialize<address>(hash_bytes); aborts_if exists<ObjectCore>(obj_addr); aborts_if !from_bcs::deserializable<address>(hash_bytes); @@ -2861,7 +2861,7 @@ to determine the identity of the starting point of ownership.
let bytes_spec = bcs::to_bytes(guid);
 let bytes = concat(bytes_spec, vec<u8>(OBJECT_FROM_GUID_ADDRESS_SCHEME));
-let hash_bytes = hash::sha3_256(bytes);
+let hash_bytes = hash::sha3_256(bytes);
 let obj_addr = from_bcs::deserialize<address>(hash_bytes);
 aborts_if exists<ObjectCore>(obj_addr);
 aborts_if !from_bcs::deserializable<address>(hash_bytes);
diff --git a/aptos-move/framework/supra-framework/doc/randomness.md b/aptos-move/framework/supra-framework/doc/randomness.md
index 9823c1d8d023c..514d7d17c30c4 100644
--- a/aptos-move/framework/supra-framework/doc/randomness.md
+++ b/aptos-move/framework/supra-framework/doc/randomness.md
@@ -61,7 +61,7 @@ Security holds under the same proof-of-stake assumption that secures the Supra n
 
 
 
use 0x1::event;
-use 0x1::hash;
+use 0x1::hash;
 use 0x1::option;
 use 0x1::system_addresses;
 use 0x1::transaction_context;
@@ -292,7 +292,7 @@ of the hash function).
     vector::append(&mut input, seed);
     vector::append(&mut input, transaction_context::get_transaction_hash());
     vector::append(&mut input, fetch_and_increment_txn_counter());
-    hash::sha3_256(input)
+    hash::sha3_256(input)
 }
 
@@ -1074,7 +1074,7 @@ function as its payload. let txn_hash = transaction_context::spec_get_txn_hash(); let txn_counter = spec_fetch_and_increment_txn_counter(); ensures len(result) == 32; -ensures result == hash::sha3_256(concat(concat(concat(input, seed), txn_hash), txn_counter)); +ensures result == hash::sha3_256(concat(concat(concat(input, seed), txn_hash), txn_counter));
diff --git a/aptos-move/framework/supra-framework/doc/supra_governance.md b/aptos-move/framework/supra-framework/doc/supra_governance.md index 5bc61628b5b50..0f970d6f0afab 100644 --- a/aptos-move/framework/supra-framework/doc/supra_governance.md +++ b/aptos-move/framework/supra-framework/doc/supra_governance.md @@ -1115,7 +1115,7 @@ are too large (e.g. module upgrades). let execution_hash = multisig_voting::get_execution_hash<GovernanceProposal>(@supra_framework, proposal_id); // If this is a multi-step proposal, the proposal id will already exist in the ApprovedExecutionHashes map. - // We will update execution hash in ApprovedExecutionHashes to be the next_execution_hash. + // We will update execution hash in ApprovedExecutionHashes to be the next_execution_hash. if (simple_map::contains_key(&approved_hashes.hashes, &proposal_id)) { let current_execution_hash = simple_map::borrow_mut(&mut approved_hashes.hashes, &proposal_id); *current_execution_hash = execution_hash; @@ -1183,12 +1183,12 @@ Resolve a successful multi-step proposal. This would fail if the proposal is not ): signer acquires GovernanceResponsbility, ApprovedExecutionHashes { multisig_voting::resolve_proposal_v2<GovernanceProposal>(@supra_framework, proposal_id, next_execution_hash); // If the current step is the last step of this multi-step proposal, - // we will remove the execution hash from the ApprovedExecutionHashes map. + // we will remove the execution hash from the ApprovedExecutionHashes map. if (vector::length(&next_execution_hash) == 0) { remove_supra_approved_hash(proposal_id); } else { // If the current step is not the last step of this proposal, - // we replace the current execution hash with the next execution hash + // we replace the current execution hash with the next execution hash // in the ApprovedExecutionHashes map. add_supra_approved_script_hash(proposal_id) }; diff --git a/aptos-move/framework/supra-framework/doc/voting.md b/aptos-move/framework/supra-framework/doc/voting.md index d00efdf78d45d..23e2abc208d09 100644 --- a/aptos-move/framework/supra-framework/doc/voting.md +++ b/aptos-move/framework/supra-framework/doc/voting.md @@ -934,7 +934,7 @@ resolve this proposal. error::invalid_argument(EINVALID_MIN_VOTE_THRESHOLD), ); }; - // Make sure the execution script's hash is not empty. + // Make sure the execution script's hash is not empty. assert!(vector::length(&execution_hash) != 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); let voting_forum = borrow_global_mut<VotingForum<ProposalType>>(voting_forum_address); @@ -1266,7 +1266,7 @@ there are more yes votes than no. If either of these conditions is not met, this }; } else { // If the current step is not the last step, - // update the proposal's execution hash on-chain to the execution hash of the next step. + // update the proposal's execution hash on-chain to the execution hash of the next step. proposal.execution_hash = next_execution_hash; }; From d5a0faf2283093cc5624f3cf608781c9f9936c7b Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Mon, 24 Feb 2025 15:38:46 +0100 Subject: [PATCH 10/12] update .md docs --- .../framework/aptos-stdlib/doc/bls12381.md | 36 - .../aptos-stdlib/doc/fixed_point64.md | 31 - .../src/aptos_framework_sdk_builder.rs | 82 - .../move-stdlib/doc/fixed_point32.md | 31 - .../framework/supra-framework/doc/account.md | 4 +- .../framework/supra-framework/doc/block.md | 108 +- .../framework/supra-framework/doc/code.md | 2 +- .../framework/supra-framework/doc/coin.md | 12 +- .../supra-framework/doc/committee_map.md | 12 +- .../supra-framework/doc/consensus_config.md | 6 +- .../supra-framework/doc/execution_config.md | 4 +- .../supra-framework/doc/gas_schedule.md | 6 +- .../framework/supra-framework/doc/genesis.md | 14 +- .../supra-framework/doc/multisig_account.md | 24 +- .../supra-framework/doc/multisig_voting.md | 6 +- .../framework/supra-framework/doc/object.md | 16 +- .../doc/pbo_delegation_pool.md | 1464 +++++++++++------ .../supra-framework/doc/randomness.md | 6 +- .../framework/supra-framework/doc/stake.md | 15 +- .../supra-framework/doc/staking_config.md | 16 +- .../supra-framework/doc/staking_contract.md | 8 +- .../supra-framework/doc/storage_gas.md | 2 +- .../supra-framework/doc/supra_config.md | 4 +- .../supra-framework/doc/supra_governance.md | 6 +- .../supra-framework/doc/transaction_fee.md | 2 +- .../doc/transaction_validation.md | 2 +- .../framework/supra-framework/doc/vesting.md | 10 +- .../doc/vesting_without_staking.md | 576 ++----- .../framework/supra-framework/doc/voting.md | 6 +- 29 files changed, 1274 insertions(+), 1237 deletions(-) diff --git a/aptos-move/framework/aptos-stdlib/doc/bls12381.md b/aptos-move/framework/aptos-stdlib/doc/bls12381.md index 1dfebbce4acaf..f189b128aeddb 100644 --- a/aptos-move/framework/aptos-stdlib/doc/bls12381.md +++ b/aptos-move/framework/aptos-stdlib/doc/bls12381.md @@ -22,7 +22,6 @@ as per the [IETF BLS draft standard](https://datatracker.ietf.org/doc/html/draft - [Function `proof_of_possession_from_bytes`](#0x1_bls12381_proof_of_possession_from_bytes) - [Function `proof_of_possession_to_bytes`](#0x1_bls12381_proof_of_possession_to_bytes) - [Function `public_key_from_bytes_with_pop`](#0x1_bls12381_public_key_from_bytes_with_pop) -- [Function `public_key_from_bytes_with_pop_externally_verified`](#0x1_bls12381_public_key_from_bytes_with_pop_externally_verified) - [Function `public_key_with_pop_to_normal`](#0x1_bls12381_public_key_with_pop_to_normal) - [Function `public_key_with_pop_to_bytes`](#0x1_bls12381_public_key_with_pop_to_bytes) - [Function `signature_from_bytes`](#0x1_bls12381_signature_from_bytes) @@ -479,41 +478,6 @@ Creates a PoP'd public key from a normal public key and a corresponding proof-of - - - - -## Function `public_key_from_bytes_with_pop_externally_verified` - -CRYPTOGRAPHY WARNING: Using this function to create PublicKeyWithPoP' without first externally verifying the pop can -result in rogue-key attacks. -Creates a PoP'd public key from a normal public key assuming the pop is verified externally -This function in contrast to public_key_from_bytes_with_pop' does not require pop and assumes that -the pop is already verified and we donot wish to verify it again or pop is unavailable due to some reason. - - -
public fun public_key_from_bytes_with_pop_externally_verified(pk_bytes: vector<u8>): option::Option<bls12381::PublicKeyWithPoP>
-
- - - -
-Implementation - - -
public fun public_key_from_bytes_with_pop_externally_verified(pk_bytes: vector<u8>): Option<PublicKeyWithPoP> {
-    if (validate_pubkey_internal(pk_bytes)) {
-        option::some(PublicKeyWithPoP {
-            bytes: pk_bytes
-        })
-    } else {
-        option::none<PublicKeyWithPoP>()
-    }
-}
-
- - -
diff --git a/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md b/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md index 642601dc34a1b..22571462f6c30 100644 --- a/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md +++ b/aptos-move/framework/aptos-stdlib/doc/fixed_point64.md @@ -12,7 +12,6 @@ a 64-bit fractional part. - [Function `sub`](#0x1_fixed_point64_sub) - [Function `add`](#0x1_fixed_point64_add) - [Function `multiply_u128`](#0x1_fixed_point64_multiply_u128) -- [Function `multiply_u128_return_fixpoint64`](#0x1_fixed_point64_multiply_u128_return_fixpoint64) - [Function `divide_u128`](#0x1_fixed_point64_divide_u128) - [Function `create_from_rational`](#0x1_fixed_point64_create_from_rational) - [Function `create_from_raw_value`](#0x1_fixed_point64_create_from_raw_value) @@ -256,36 +255,6 @@ overflows. - - - - -## Function `multiply_u128_return_fixpoint64` - - - -
public fun multiply_u128_return_fixpoint64(val: u128, multiplier: fixed_point64::FixedPoint64): fixed_point64::FixedPoint64
-
- - - -
-Implementation - - -
public fun multiply_u128_return_fixpoint64(val: u128, multiplier: FixedPoint64): FixedPoint64 {
-    // The product of two 128 bit values has 256 bits, so perform the
-    // multiplication with u256 types and keep the full 256 bit product
-    // to avoid losing accuracy.
-    let unscaled_product = (val as u256) * (multiplier.value as u256);
-    // Check whether the value is too large.
-    assert!(unscaled_product <= MAX_U128, EMULTIPLICATION);
-    create_from_raw_value((unscaled_product as u128))
-}
-
- - -
diff --git a/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs b/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs index a2d053ca281bd..a75cf4008e055 100644 --- a/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs +++ b/aptos-move/framework/cached-packages/src/aptos_framework_sdk_builder.rs @@ -602,20 +602,6 @@ pub enum EntryFunctionCall { new_commission_percentage: u64, }, - /// Pre-condition: `cumulative_unlocked_fraction` should be zero, which would indicate that even - /// though there are principle stake holders, none of those have yet called `unlock` on the pool - /// thus it is ``safe'' to change the schedule - /// This is a temporary measure to allow Supra Foundation to change the schedule for those pools - /// there were initialized with ``dummy/default'' schedule. This method must be disabled - /// before external validators are allowed to join the validator set. - PboDelegationPoolUpdateUnlockingSchedule { - pool_address: AccountAddress, - unlock_numerators: Vec, - unlock_denominator: u64, - unlock_start_time: u64, - unlock_duration: u64, - }, - /// Withdraw `amount` of owned inactive stake from the delegation pool at `pool_address`. PboDelegationPoolWithdraw { pool_address: AccountAddress, @@ -1552,19 +1538,6 @@ impl EntryFunctionCall { PboDelegationPoolUpdateCommissionPercentage { new_commission_percentage, } => pbo_delegation_pool_update_commission_percentage(new_commission_percentage), - PboDelegationPoolUpdateUnlockingSchedule { - pool_address, - unlock_numerators, - unlock_denominator, - unlock_start_time, - unlock_duration, - } => pbo_delegation_pool_update_unlocking_schedule( - pool_address, - unlock_numerators, - unlock_denominator, - unlock_start_time, - unlock_duration, - ), PboDelegationPoolWithdraw { pool_address, amount, @@ -3493,39 +3466,6 @@ pub fn pbo_delegation_pool_update_commission_percentage( )) } -/// Pre-condition: `cumulative_unlocked_fraction` should be zero, which would indicate that even -/// though there are principle stake holders, none of those have yet called `unlock` on the pool -/// thus it is ``safe'' to change the schedule -/// This is a temporary measure to allow Supra Foundation to change the schedule for those pools -/// there were initialized with ``dummy/default'' schedule. This method must be disabled -/// before external validators are allowed to join the validator set. -pub fn pbo_delegation_pool_update_unlocking_schedule( - pool_address: AccountAddress, - unlock_numerators: Vec, - unlock_denominator: u64, - unlock_start_time: u64, - unlock_duration: u64, -) -> TransactionPayload { - TransactionPayload::EntryFunction(EntryFunction::new( - ModuleId::new( - AccountAddress::new([ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 1, - ]), - ident_str!("pbo_delegation_pool").to_owned(), - ), - ident_str!("update_unlocking_schedule").to_owned(), - vec![], - vec![ - bcs::to_bytes(&pool_address).unwrap(), - bcs::to_bytes(&unlock_numerators).unwrap(), - bcs::to_bytes(&unlock_denominator).unwrap(), - bcs::to_bytes(&unlock_start_time).unwrap(), - bcs::to_bytes(&unlock_duration).unwrap(), - ], - )) -} - /// Withdraw `amount` of owned inactive stake from the delegation pool at `pool_address`. pub fn pbo_delegation_pool_withdraw( pool_address: AccountAddress, @@ -6138,24 +6078,6 @@ mod decoder { } } - pub fn pbo_delegation_pool_update_unlocking_schedule( - payload: &TransactionPayload, - ) -> Option { - if let TransactionPayload::EntryFunction(script) = payload { - Some( - EntryFunctionCall::PboDelegationPoolUpdateUnlockingSchedule { - pool_address: bcs::from_bytes(script.args().get(0)?).ok()?, - unlock_numerators: bcs::from_bytes(script.args().get(1)?).ok()?, - unlock_denominator: bcs::from_bytes(script.args().get(2)?).ok()?, - unlock_start_time: bcs::from_bytes(script.args().get(3)?).ok()?, - unlock_duration: bcs::from_bytes(script.args().get(4)?).ok()?, - }, - ) - } else { - None - } - } - pub fn pbo_delegation_pool_withdraw(payload: &TransactionPayload) -> Option { if let TransactionPayload::EntryFunction(script) = payload { Some(EntryFunctionCall::PboDelegationPoolWithdraw { @@ -7440,10 +7362,6 @@ static SCRIPT_FUNCTION_DECODER_MAP: once_cell::sync::Lazy - - - -## Function `multiply_u64_return_fixpoint32` - - - -
public fun multiply_u64_return_fixpoint32(val: u64, multiplier: fixed_point32::FixedPoint32): fixed_point32::FixedPoint32
-
- - - -
-Implementation - - -
public fun multiply_u64_return_fixpoint32(val: u64, multiplier: FixedPoint32): FixedPoint32 {
-    // The product of two 64 bit values has 128 bits, so perform the
-    // multiplication with u128 types and keep the full 128 bit product
-    // to avoid losing accuracy.
-    let unscaled_product = (val as u128) * (multiplier.value as u128);
-    // Check whether the value is too large.
-    assert!(unscaled_product <= MAX_U64, EMULTIPLICATION);
-    create_from_raw_value((unscaled_product as u64))
-}
-
- - -
diff --git a/aptos-move/framework/supra-framework/doc/account.md b/aptos-move/framework/supra-framework/doc/account.md index 732c5684af74a..4fc29c93fda93 100644 --- a/aptos-move/framework/supra-framework/doc/account.md +++ b/aptos-move/framework/supra-framework/doc/account.md @@ -102,7 +102,7 @@ use 0x1::features; use 0x1::from_bcs; use 0x1::guid; -use 0x1::hash; +use 0x1::hash; use 0x1::multi_ed25519; use 0x1::option; use 0x1::signer; @@ -1929,7 +1929,7 @@ involves the use of a cryptographic hash operation and should be use thoughtfull let bytes = bcs::to_bytes(source); vector::append(&mut bytes, seed); vector::push_back(&mut bytes, DERIVE_RESOURCE_ACCOUNT_SCHEME); - from_bcs::to_address(hash::sha3_256(bytes)) + from_bcs::to_address(hash::sha3_256(bytes)) }
diff --git a/aptos-move/framework/supra-framework/doc/block.md b/aptos-move/framework/supra-framework/doc/block.md index ac8b98cabfd93..5591796018e2a 100644 --- a/aptos-move/framework/supra-framework/doc/block.md +++ b/aptos-move/framework/supra-framework/doc/block.md @@ -163,7 +163,7 @@ Should be in-sync with NewBlockEvent rust struct in new_block.rs
-hash: address +hash: address
@@ -268,7 +268,7 @@ Should be in-sync with NewBlockEvent rust struct in new_block.rs
-hash: address +hash: address
@@ -427,7 +427,7 @@ This can only be called during Genesis.
public(friend) fun initialize(supra_framework: &signer, epoch_interval_microsecs: u64) {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(epoch_interval_microsecs != 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
+    assert!(epoch_interval_microsecs > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
 
     move_to<CommitHistory>(supra_framework, CommitHistory {
         max_capacity: 2000,
@@ -468,7 +468,7 @@ Initialize the commit history resource if it's not in genesis.
 
 
 
public fun initialize_commit_history(fx: &signer, max_capacity: u32) {
-    assert!(max_capacity != 0, error::invalid_argument(EZERO_MAX_CAPACITY));
+    assert!(max_capacity > 0, error::invalid_argument(EZERO_MAX_CAPACITY));
     move_to<CommitHistory>(fx, CommitHistory {
         max_capacity,
         next_idx: 0,
@@ -503,7 +503,7 @@ Can only be called as part of the Supra governance proposal process established
     new_epoch_interval: u64,
 ) acquires BlockResource {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(new_epoch_interval != 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
+    assert!(new_epoch_interval > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL));
 
     let block_resource = borrow_global_mut<BlockResource>(@supra_framework);
     let old_epoch_interval = block_resource.epoch_interval;
@@ -557,7 +557,7 @@ Return epoch interval in seconds.
 
 
 
-
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
+
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
 
@@ -568,7 +568,7 @@ Return epoch interval in seconds.
fun block_prologue_common(
     vm: &signer,
-    hash: address,
+    hash: address,
     epoch: u64,
     round: u64,
     proposer: address,
@@ -595,7 +595,7 @@ Return epoch interval in seconds.
 
     // Emit both event v1 and v2 for compatibility. Eventually only module events will be kept.
     let new_block_event = NewBlockEvent {
-        hash,
+        hash,
         epoch,
         round,
         height: block_metadata_ref.height,
@@ -605,7 +605,7 @@ Return epoch interval in seconds.
         time_microseconds: timestamp,
     };
     let new_block_event_v2 = NewBlock {
-        hash,
+        hash,
         epoch,
         round,
         height: block_metadata_ref.height,
@@ -646,7 +646,7 @@ Set the metadata for the current block.
 The runtime always runs this before executing the transactions in a block.
 
 
-
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
+
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
 
@@ -657,7 +657,7 @@ The runtime always runs this before executing the transactions in a block.
fun block_prologue(
     vm: signer,
-    hash: address,
+    hash: address,
     epoch: u64,
     round: u64,
     proposer: address,
@@ -665,7 +665,7 @@ The runtime always runs this before executing the transactions in a block.
     previous_block_votes_bitvec: vector<u8>,
     timestamp: u64
 ) acquires BlockResource, CommitHistory {
-    let epoch_interval = block_prologue_common(&vm, hash, epoch, round, proposer, failed_proposer_indices, previous_block_votes_bitvec, timestamp);
+    let epoch_interval = block_prologue_common(&vm, hash, epoch, round, proposer, failed_proposer_indices, previous_block_votes_bitvec, timestamp);
     randomness::on_new_block(&vm, epoch, round, option::none());
     if (timestamp - reconfiguration::last_reconfiguration_time() >= epoch_interval) {
         reconfiguration::reconfigure();
@@ -684,7 +684,7 @@ The runtime always runs this before executing the transactions in a block.
 block_prologue() but trigger reconfiguration with DKG after epoch timed out.
 
 
-
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
+
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
 
@@ -695,7 +695,7 @@ The runtime always runs this before executing the transactions in a block.
fun block_prologue_ext(
     vm: signer,
-    hash: address,
+    hash: address,
     epoch: u64,
     round: u64,
     proposer: address,
@@ -706,7 +706,7 @@ The runtime always runs this before executing the transactions in a block.
 ) acquires BlockResource, CommitHistory {
     let epoch_interval = block_prologue_common(
         &vm,
-        hash,
+        hash,
         epoch,
         round,
         proposer,
@@ -826,7 +826,7 @@ reconfiguration event.
         &vm,
         &mut block_metadata_ref.new_block_events,
         NewBlockEvent {
-            hash: genesis_id,
+            hash: genesis_id,
             epoch: 0,
             round: 0,
             height: 0,
@@ -836,7 +836,7 @@ reconfiguration event.
             time_microseconds: timestamp::now_microseconds(),
         },
         NewBlock {
-            hash: genesis_id,
+            hash: genesis_id,
             epoch: 0,
             round: 0,
             height: 0,
@@ -879,7 +879,7 @@ new block event for WriteSetPayload.
         vm_signer,
         &mut block_metadata_ref.new_block_events,
         NewBlockEvent {
-            hash: fake_block_hash,
+            hash: fake_block_hash,
             epoch: reconfiguration::current_epoch(),
             round: MAX_U64,
             height: block_metadata_ref.height,
@@ -889,7 +889,7 @@ new block event for WriteSetPayload.
             time_microseconds: timestamp::now_microseconds(),
         },
         NewBlock {
-            hash: fake_block_hash,
+            hash: fake_block_hash,
             epoch: reconfiguration::current_epoch(),
             round: MAX_U64,
             height: block_metadata_ref.height,
@@ -1088,70 +1088,6 @@ The number of new events created does not exceed MAX_U64.
 
 
 
-
-
-
-
-
schema BlockRequirement {
-    vm: signer;
-    hash: address;
-    epoch: u64;
-    round: u64;
-    proposer: address;
-    failed_proposer_indices: vector<u64>;
-    previous_block_votes_bitvec: vector<u8>;
-    timestamp: u64;
-    requires chain_status::is_operating();
-    requires system_addresses::is_vm(vm);
-    // This enforces high-level requirement 4:
-    requires proposer == @vm_reserved || stake::spec_is_current_epoch_validator(proposer);
-    requires (proposer == @vm_reserved) ==> (timestamp::spec_now_microseconds() == timestamp);
-    requires (proposer != @vm_reserved) ==> (timestamp::spec_now_microseconds() < timestamp);
-    requires exists<stake::ValidatorFees>(@supra_framework);
-    requires exists<CoinInfo<SupraCoin>>(@supra_framework);
-    include transaction_fee::RequiresCollectedFeesPerValueLeqBlockAptosSupply;
-    include staking_config::StakingRewardsConfigRequirement;
-}
-
- - - - - - - -
schema Initialize {
-    supra_framework: signer;
-    epoch_interval_microsecs: u64;
-    let addr = signer::address_of(supra_framework);
-    // This enforces high-level requirement 2:
-    aborts_if addr != @supra_framework;
-    aborts_if epoch_interval_microsecs == 0;
-    aborts_if exists<BlockResource>(addr);
-    aborts_if exists<CommitHistory>(addr);
-    ensures exists<BlockResource>(addr);
-    ensures exists<CommitHistory>(addr);
-    ensures global<BlockResource>(addr).height == 0;
-}
-
- - - - - - - -
schema NewEventHandle {
-    supra_framework: signer;
-    let addr = signer::address_of(supra_framework);
-    let account = global<account::Account>(addr);
-    aborts_if !exists<account::Account>(addr);
-    aborts_if account.guid_creation_num + 2 > MAX_U64;
-}
-
- - - ### Function `update_epoch_interval_microsecs` @@ -1213,7 +1149,7 @@ The BlockResource existed under the @supra_framework. ### Function `block_prologue_common` -
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
+
fun block_prologue_common(vm: &signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64): u64
 
@@ -1231,7 +1167,7 @@ The BlockResource existed under the @supra_framework. ### Function `block_prologue` -
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
+
fun block_prologue(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64)
 
@@ -1250,7 +1186,7 @@ The BlockResource existed under the @supra_framework. ### Function `block_prologue_ext` -
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
+
fun block_prologue_ext(vm: signer, hash: address, epoch: u64, round: u64, proposer: address, failed_proposer_indices: vector<u64>, previous_block_votes_bitvec: vector<u8>, timestamp: u64, randomness_seed: option::Option<vector<u8>>)
 
diff --git a/aptos-move/framework/supra-framework/doc/code.md b/aptos-move/framework/supra-framework/doc/code.md index 22f315eb80d27..36721ea20c942 100644 --- a/aptos-move/framework/supra-framework/doc/code.md +++ b/aptos-move/framework/supra-framework/doc/code.md @@ -646,7 +646,7 @@ package. event::emit(PublishPackage { code_address: addr, - is_upgrade: upgrade_number != 0 + is_upgrade: upgrade_number > 0 }); // Request publish diff --git a/aptos-move/framework/supra-framework/doc/coin.md b/aptos-move/framework/supra-framework/doc/coin.md index a3ef151ae9436..47dd35a6e76fa 100644 --- a/aptos-move/framework/supra-framework/doc/coin.md +++ b/aptos-move/framework/supra-framework/doc/coin.md @@ -2224,13 +2224,13 @@ Collects a specified amount of coin form an account into aggregatable coin. account_addr, amount ); - let coin = if (coin_amount_to_collect != 0) { + let coin = if (coin_amount_to_collect > 0) { let coin_store = borrow_global_mut<CoinStore<CoinType>>(account_addr); extract(&mut coin_store.coin, coin_amount_to_collect) } else { zero() }; - if (fa_amount_to_collect != 0) { + if (fa_amount_to_collect > 0) { let store_addr = primary_fungible_store::primary_store_address( account_addr, option::destroy_some(paired_metadata<CoinType>()) @@ -2837,12 +2837,12 @@ Note: This bypasses CoinStore::frozen -- coins within a frozen CoinStore can be account_addr, amount ); - if (coin_amount_to_burn != 0) { + if (coin_amount_to_burn > 0) { let coin_store = borrow_global_mut<CoinStore<CoinType>>(account_addr); let coin_to_burn = extract(&mut coin_store.coin, coin_amount_to_burn); burn(coin_to_burn, burn_cap); }; - if (fa_amount_to_burn != 0) { + if (fa_amount_to_burn > 0) { fungible_asset::burn_from( borrow_paired_burn_ref(burn_cap), primary_fungible_store::primary_store(account_addr, option::destroy_some(paired_metadata<CoinType>())), @@ -3581,7 +3581,7 @@ Withdraw specified amount of coin CoinType from the si account_addr, amount ); - let withdrawn_coin = if (coin_amount_to_withdraw != 0) { + let withdrawn_coin = if (coin_amount_to_withdraw > 0) { let coin_store = borrow_global_mut<CoinStore<CoinType>>(account_addr); assert!( !coin_store.frozen, @@ -3602,7 +3602,7 @@ Withdraw specified amount of coin CoinType from the si } else { zero() }; - if (fa_amount_to_withdraw != 0) { + if (fa_amount_to_withdraw > 0) { let fa = primary_fungible_store::withdraw( account, option::destroy_some(paired_metadata<CoinType>()), diff --git a/aptos-move/framework/supra-framework/doc/committee_map.md b/aptos-move/framework/supra-framework/doc/committee_map.md index 9146990f8d213..ff00adc120f84 100644 --- a/aptos-move/framework/supra-framework/doc/committee_map.md +++ b/aptos-move/framework/supra-framework/doc/committee_map.md @@ -970,7 +970,7 @@ Get the committee's node vector and committee type let committee = simple_map::borrow(&committee_store.committee_map, &id); let (addrs, nodes) = simple_map::to_vec_pair(committee.map); let node_data_vec = vector::empty<NodeData>(); - while (vector::length(&addrs) != 0) { + while (vector::length(&addrs) > 0) { let addr = vector::pop_back(&mut addrs); let node_info = vector::pop_back(&mut nodes); let node_data = NodeData { @@ -1289,7 +1289,7 @@ This function is used to add a new committee to the store let committee_store = borrow_global_mut<CommitteeInfoStore>(com_store_addr); let node_infos = vector::empty<NodeInfo>(); let node_addresses_for_iteration = node_addresses; - while (vector::length(&node_addresses_for_iteration) != 0) { + while (vector::length(&node_addresses_for_iteration) > 0) { let ip_public_address = vector::pop_back(&mut ip_public_address); let node_public_key = vector::pop_back(&mut node_public_key); let network_public_key = vector::pop_back(&mut network_public_key); @@ -1402,7 +1402,7 @@ Add the committee in bulk ids_len == vector::length(&rpc_por_bulkt), error::invalid_argument(INVALID_COMMITTEE_NUMBERS) ); - while (vector::length(&ids) != 0) { + while (vector::length(&ids) > 0) { let id = vector::pop_back(&mut ids); let node_addresses = vector::pop_back(&mut node_addresses_bulk); let ip_public_address = vector::pop_back(&mut ip_public_address_bulk); @@ -1465,7 +1465,7 @@ Remove the committee from the store let (id, committee_info) = simple_map::remove(&mut committee_store.committee_map, &id); // Also remove the node_to_committee_map let (addrs, _) = simple_map::to_vec_pair(committee_info.map); - while (vector::length(&addrs) != 0) { + while (vector::length(&addrs) > 0) { let addr = vector::pop_back(&mut addrs); assert!( simple_map::contains_key(&committee_store.node_to_committee_map, &addr), @@ -1508,7 +1508,7 @@ Remove the committee in bulk com_store_addr: address, ids: vector<u64> ) acquires CommitteeInfoStore, SupraCommitteeEventHandler { - while (vector::length(&ids) != 0) { + while (vector::length(&ids) > 0) { let id = vector::pop_back(&mut ids); remove_committee(owner_signer, com_store_addr, id); } @@ -1644,7 +1644,7 @@ Upsert nodes to the committee vector::length(&ids) == vector::length(&rpc_port), error::invalid_argument(INVALID_COMMITTEE_NUMBERS) ); - while (vector::length(&ids) != 0) { + while (vector::length(&ids) > 0) { let id = vector::pop_back(&mut ids); let node_address = vector::pop_back(&mut node_addresses); let ip_public_address = vector::pop_back(&mut ip_public_address); diff --git a/aptos-move/framework/supra-framework/doc/consensus_config.md b/aptos-move/framework/supra-framework/doc/consensus_config.md index b4374a973d71b..90bca73bc051c 100644 --- a/aptos-move/framework/supra-framework/doc/consensus_config.md +++ b/aptos-move/framework/supra-framework/doc/consensus_config.md @@ -95,7 +95,7 @@ Publishes the ConsensusConfig config.
public(friend) fun initialize(supra_framework: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
     move_to(supra_framework, ConsensusConfig { config });
 }
 
@@ -127,7 +127,7 @@ TODO: update all the tests that reference this function, then disable this funct
public fun set(account: &signer, config: vector<u8>) acquires ConsensusConfig {
     system_addresses::assert_supra_framework(account);
     chain_status::assert_genesis();
-    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
 
     let config_ref = &mut borrow_global_mut<ConsensusConfig>(@supra_framework).config;
     *config_ref = config;
@@ -164,7 +164,7 @@ supra_framework::supra_governance::reconfigure(&framework_signer);
 
 
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(account);
-    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
     std::config_buffer::upsert<ConsensusConfig>(ConsensusConfig {config});
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/execution_config.md b/aptos-move/framework/supra-framework/doc/execution_config.md index 019027dceed44..25625078d0474 100644 --- a/aptos-move/framework/supra-framework/doc/execution_config.md +++ b/aptos-move/framework/supra-framework/doc/execution_config.md @@ -93,7 +93,7 @@ TODO: update all the tests that reference this function, then disable this funct system_addresses::assert_supra_framework(account); chain_status::assert_genesis(); - assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG)); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); if (exists<ExecutionConfig>(@supra_framework)) { let config_ref = &mut borrow_global_mut<ExecutionConfig>(@supra_framework).config; @@ -133,7 +133,7 @@ supra_framework::aptos_governance::reconfigure(&framework_signer);
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(account);
-    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
     config_buffer::upsert(ExecutionConfig { config });
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/gas_schedule.md b/aptos-move/framework/supra-framework/doc/gas_schedule.md index c899966f021e4..8af2b941e8668 100644 --- a/aptos-move/framework/supra-framework/doc/gas_schedule.md +++ b/aptos-move/framework/supra-framework/doc/gas_schedule.md @@ -30,7 +30,7 @@ it costs to execute Move on the network. - [Function `set_storage_gas_config_for_next_epoch`](#@Specification_1_set_storage_gas_config_for_next_epoch) -
use 0x1::aptos_hash;
+
use 0x1::aptos_hash;
 use 0x1::bcs;
 use 0x1::chain_status;
 use 0x1::config_buffer;
@@ -328,7 +328,7 @@ Require a hash of the old gas schedule to be provided and will abort if the hash
             error::invalid_argument(EINVALID_GAS_FEATURE_VERSION)
         );
         let cur_gas_schedule_bytes = bcs::to_bytes(cur_gas_schedule);
-        let cur_gas_schedule_hash = aptos_hash::sha3_512(cur_gas_schedule_bytes);
+        let cur_gas_schedule_hash = aptos_hash::sha3_512(cur_gas_schedule_bytes);
         assert!(
             cur_gas_schedule_hash == old_gas_schedule_hash,
             error::invalid_argument(EINVALID_GAS_SCHEDULE_HASH)
@@ -586,7 +586,7 @@ Only used in reconfigurations to apply the pending util::spec_from_bytes<GasScheduleV2>(new_gas_schedule_blob);
 let cur_gas_schedule = global<GasScheduleV2>(@supra_framework);
 aborts_if exists<GasScheduleV2>(@supra_framework) && new_gas_schedule.feature_version < cur_gas_schedule.feature_version;
-aborts_if exists<GasScheduleV2>(@supra_framework) && (!features::spec_sha_512_and_ripemd_160_enabled() || aptos_hash::spec_sha3_512_internal(bcs::serialize(cur_gas_schedule)) != old_gas_schedule_hash);
+aborts_if exists<GasScheduleV2>(@supra_framework) && (!features::spec_sha_512_and_ripemd_160_enabled() || aptos_hash::spec_sha3_512_internal(bcs::serialize(cur_gas_schedule)) != old_gas_schedule_hash);
 
diff --git a/aptos-move/framework/supra-framework/doc/genesis.md b/aptos-move/framework/supra-framework/doc/genesis.md index 2b89f6a3e56f8..1be1262374f04 100644 --- a/aptos-move/framework/supra-framework/doc/genesis.md +++ b/aptos-move/framework/supra-framework/doc/genesis.md @@ -1129,7 +1129,7 @@ encoded in a single BCS byte array. delegation_percentage: u64, ) { let unique_accounts: vector<address> = vector::empty(); - assert!(delegation_percentage != 0 && delegation_percentage <= 100, error::invalid_argument(EPERCENTAGE_INVALID)); + assert!(delegation_percentage > 0 && delegation_percentage <= 100, error::invalid_argument(EPERCENTAGE_INVALID)); vector::for_each_ref(&pbo_delegator_configs, |pbo_delegator_config| { let pbo_delegator_config: &PboDelegatorConfiguration = pbo_delegator_config; assert!(!vector::contains(&unique_accounts,&pbo_delegator_config.delegator_config.owner_address), @@ -1163,7 +1163,7 @@ encoded in a single BCS byte array. pbo_delegator_config: &PboDelegatorConfiguration, delegation_percentage: u64, ) { - assert!(delegation_percentage != 0 && delegation_percentage<=100,error::invalid_argument(EPERCENTAGE_INVALID)); + assert!(delegation_percentage>0 && delegation_percentage<=100,error::invalid_argument(EPERCENTAGE_INVALID)); let unique_accounts:vector<address> = vector::empty(); vector::for_each_ref(&pbo_delegator_config.delegator_config.delegator_addresses, |delegator_address| { let delegator_address: &address = delegator_address; @@ -1272,9 +1272,9 @@ encoded in a single BCS byte array. let pool_config: &VestingPoolsMap = pool_config; let schedule = vector::empty(); let schedule_length = vector::length(&pool_config.vesting_numerators); - assert!(schedule_length != 0, error::invalid_argument(EVESTING_SCHEDULE_IS_ZERO)); - assert!(pool_config.vesting_denominator != 0, error::invalid_argument(EDENOMINATOR_IS_ZERO)); - assert!(pool_config.vpool_locking_percentage != 0 && pool_config.vpool_locking_percentage <=100 , + assert!(schedule_length > 0, error::invalid_argument(EVESTING_SCHEDULE_IS_ZERO)); + assert!(pool_config.vesting_denominator > 0, error::invalid_argument(EDENOMINATOR_IS_ZERO)); + assert!(pool_config.vpool_locking_percentage > 0 && pool_config.vpool_locking_percentage <=100 , error::invalid_argument(EPERCENTAGE_INVALID)); //check the sum of numerator are <= denominator. let sum = vector::fold(pool_config.vesting_numerators,0,|acc, x| acc + x); @@ -1290,7 +1290,7 @@ encoded in a single BCS byte array. let j=0; while (j < schedule_length) { let numerator = *vector::borrow(&pool_config.vesting_numerators,j); - assert!(numerator != 0, error::invalid_argument(ENUMERATOR_IS_ZERO)); + assert!(numerator > 0, error::invalid_argument(ENUMERATOR_IS_ZERO)); let event = fixed_point32::create_from_rational(numerator,pool_config.vesting_denominator); vector::push_back(&mut schedule,event); j = j + 1; @@ -1304,7 +1304,7 @@ encoded in a single BCS byte array. let buy_ins = simple_map::create(); let num_shareholders = vector::length(&pool_config.shareholders); - assert!(num_shareholders != 0, error::invalid_argument(ENO_SHAREHOLDERS)); + assert!(num_shareholders > 0, error::invalid_argument(ENO_SHAREHOLDERS)); let j = 0; while (j < num_shareholders) { let shareholder = *vector::borrow(&pool_config.shareholders,j); diff --git a/aptos-move/framework/supra-framework/doc/multisig_account.md b/aptos-move/framework/supra-framework/doc/multisig_account.md index 8dc5f656b7b29..5c0091e90f434 100644 --- a/aptos-move/framework/supra-framework/doc/multisig_account.md +++ b/aptos-move/framework/supra-framework/doc/multisig_account.md @@ -154,7 +154,7 @@ and implement the governance voting logic on top. use 0x1::error; use 0x1::event; use 0x1::features; -use 0x1::hash; +use 0x1::hash; use 0x1::option; use 0x1::signer; use 0x1::simple_map; @@ -1693,7 +1693,7 @@ Return the transaction with the given transaction id. ): MultisigTransaction acquires MultisigAccount { let multisig_account_resource = borrow_global<MultisigAccount>(multisig_account); assert!( - sequence_number != 0 && sequence_number < multisig_account_resource.next_sequence_number, + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, error::invalid_argument(EINVALID_SEQUENCE_NUMBER), ); *table::borrow(&multisig_account_resource.transactions, sequence_number) @@ -2033,7 +2033,7 @@ Return a bool tuple indicating whether an owner has voted and if so, whether the multisig_account: address, sequence_number: u64, owner: address): (bool, bool) acquires MultisigAccount { let multisig_account_resource = borrow_global_mut<MultisigAccount>(multisig_account); assert!( - sequence_number != 0 && sequence_number < multisig_account_resource.next_sequence_number, + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, error::invalid_argument(EINVALID_SEQUENCE_NUMBER), ); let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); @@ -2387,7 +2387,7 @@ be an owner after the vanity multisig address has been secured. ) acquires MultisigAccount { assert!(features::multisig_accounts_enabled(), error::unavailable(EMULTISIG_ACCOUNTS_NOT_ENABLED_YET)); assert!( - num_signatures_required != 0 && num_signatures_required <= vector::length(&owners), + num_signatures_required > 0 && num_signatures_required <= vector::length(&owners), error::invalid_argument(EINVALID_SIGNATURES_REQUIRED), ); @@ -2882,7 +2882,7 @@ Create a multisig transaction, which will have one approval initially (from the multisig_account: address, payload: vector<u8>, ) acquires MultisigAccount { - assert!(vector::length(&payload) != 0, error::invalid_argument(EPAYLOAD_CANNOT_BE_EMPTY)); + assert!(vector::length(&payload) > 0, error::invalid_argument(EPAYLOAD_CANNOT_BE_EMPTY)); assert_multisig_account_exists(multisig_account); assert_is_owner(owner, multisig_account); @@ -2926,7 +2926,7 @@ to provide the full payload, which will be validated against the hash stored on- multisig_account: address, payload_hash: vector<u8>, ) acquires MultisigAccount { - // Payload hash is a sha3-256 hash, so it must be exactly 32 bytes. + // Payload hash is a sha3-256 hash, so it must be exactly 32 bytes. assert!(vector::length(&payload_hash) == 32, error::invalid_argument(EINVALID_PAYLOAD_HASH)); assert_multisig_account_exists(multisig_account); @@ -3502,7 +3502,7 @@ This function is private so no other code can call this beside the VM itself as ) { if (features::multisig_v2_enhancement_feature_enabled()) { assert!( - available_transaction_queue_capacity(multisig_account) != 0, + available_transaction_queue_capacity(multisig_account) > 0, error::invalid_state(EMAX_PENDING_TRANSACTIONS_EXCEEDED) ); }; @@ -3832,7 +3832,7 @@ This function is private so no other code can call this beside the VM itself as
inline fun assert_valid_sequence_number(multisig_account: address, sequence_number: u64) acquires MultisigAccount {
     let multisig_account_resource = borrow_global<MultisigAccount>(multisig_account);
     assert!(
-        sequence_number != 0 && sequence_number < multisig_account_resource.next_sequence_number,
+        sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number,
         error::invalid_argument(EINVALID_SEQUENCE_NUMBER),
     );
 }
@@ -3903,7 +3903,7 @@ Add new owners, remove owners to remove, update signatures required.
         )
     });
     // If new owners provided, try to add them and emit an event.
-    if (vector::length(&new_owners) != 0) {
+    if (vector::length(&new_owners) > 0) {
         vector::append(&mut multisig_account_ref_mut.owners, new_owners);
         validate_owners(
             &multisig_account_ref_mut.owners,
@@ -3918,7 +3918,7 @@ Add new owners, remove owners to remove, update signatures required.
         );
     };
     // If owners to remove provided, try to remove them.
-    if (vector::length(&owners_to_remove) != 0) {
+    if (vector::length(&owners_to_remove) > 0) {
         let owners_ref_mut = &mut multisig_account_ref_mut.owners;
         let owners_removed = vector[];
         vector::for_each_ref(&owners_to_remove, |owner_to_remove_ref| {
@@ -3932,7 +3932,7 @@ Add new owners, remove owners to remove, update signatures required.
             }
         });
         // Only emit event if owner(s) actually removed.
-        if (vector::length(&owners_removed) != 0) {
+        if (vector::length(&owners_removed) > 0) {
             if (std::features::module_event_migration_enabled()) {
                 emit(
                     RemoveOwners { multisig_account: multisig_address, owners_removed }
@@ -3949,7 +3949,7 @@ Add new owners, remove owners to remove, update signatures required.
         let new_num_signatures_required =
             option::extract(&mut optional_new_num_signatures_required);
         assert!(
-            new_num_signatures_required != 0,
+            new_num_signatures_required > 0,
             error::invalid_argument(EINVALID_SIGNATURES_REQUIRED)
         );
         let old_num_signatures_required =
diff --git a/aptos-move/framework/supra-framework/doc/multisig_voting.md b/aptos-move/framework/supra-framework/doc/multisig_voting.md
index f9e1349f786a6..5cbc4038e75a6 100644
--- a/aptos-move/framework/supra-framework/doc/multisig_voting.md
+++ b/aptos-move/framework/supra-framework/doc/multisig_voting.md
@@ -942,8 +942,8 @@ resolve this proposal.
     is_multi_step_proposal: bool,
 ): u64 acquires VotingForum {
 
-    // Make sure the execution script's hash is not empty.
-    assert!(vector::length(&execution_hash) != 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH));
+    // Make sure the execution script's hash is not empty.
+    assert!(vector::length(&execution_hash) > 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH));
 
     assert!(min_vote_threshold > 1, error::invalid_argument(ETHRESHOLD_MUST_BE_GREATER_THAN_ONE));
 
@@ -1297,7 +1297,7 @@ there are more yes votes than no. If either of these conditions is not met, this
         };
     } else {
         // If the current step is not the last step,
-        // update the proposal's execution hash on-chain to the execution hash of the next step.
+        // update the proposal's execution hash on-chain to the execution hash of the next step.
         proposal.execution_hash = next_execution_hash;
     };
 
diff --git a/aptos-move/framework/supra-framework/doc/object.md b/aptos-move/framework/supra-framework/doc/object.md
index 49563de509864..f59f5def50f92 100644
--- a/aptos-move/framework/supra-framework/doc/object.md
+++ b/aptos-move/framework/supra-framework/doc/object.md
@@ -143,7 +143,7 @@ make it so that a reference to a global object can be returned from a function.
 use 0x1::features;
 use 0x1::from_bcs;
 use 0x1::guid;
-use 0x1::hash;
+use 0x1::hash;
 use 0x1::signer;
 use 0x1::transaction_context;
 use 0x1::vector;
@@ -911,7 +911,7 @@ Derives an object address from source material: sha3_256([creator address | seed
     let bytes = bcs::to_bytes(source);
     vector::append(&mut bytes, seed);
     vector::push_back(&mut bytes, OBJECT_FROM_SEED_ADDRESS_SCHEME);
-    from_bcs::to_address(hash::sha3_256(bytes))
+    from_bcs::to_address(hash::sha3_256(bytes))
 }
 
@@ -964,7 +964,7 @@ Derives an object address from the source address and an object: sha3_256([sourc let bytes = bcs::to_bytes(&source); vector::append(&mut bytes, bcs::to_bytes(&derive_from)); vector::push_back(&mut bytes, OBJECT_DERIVED_SCHEME); - from_bcs::to_address(hash::sha3_256(bytes)) + from_bcs::to_address(hash::sha3_256(bytes)) } }
@@ -993,7 +993,7 @@ Derives an object from an Account GUID. let id = guid::create_id(source, creation_num); let bytes = bcs::to_bytes(&id); vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME); - from_bcs::to_address(hash::sha3_256(bytes)) + from_bcs::to_address(hash::sha3_256(bytes)) }
@@ -1293,7 +1293,7 @@ doesn't have the same bottlenecks.
fun create_object_from_guid(creator_address: address, guid: guid::GUID): ConstructorRef {
     let bytes = bcs::to_bytes(&guid);
     vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME);
-    let obj_addr = from_bcs::to_address(hash::sha3_256(bytes));
+    let obj_addr = from_bcs::to_address(hash::sha3_256(bytes));
     create_object_internal(creator_address, obj_addr, true)
 }
 
@@ -2771,7 +2771,7 @@ to determine the identity of the starting point of ownership. }; let bytes_spec = bcs::to_bytes(guid); let bytes = concat(bytes_spec, vec<u8>(OBJECT_FROM_GUID_ADDRESS_SCHEME)); -let hash_bytes = hash::sha3_256(bytes); +let hash_bytes = hash::sha3_256(bytes); let obj_addr = from_bcs::deserialize<address>(hash_bytes); aborts_if exists<ObjectCore>(obj_addr); aborts_if !from_bcs::deserializable<address>(hash_bytes); @@ -2823,7 +2823,7 @@ to determine the identity of the starting point of ownership. }; let bytes_spec = bcs::to_bytes(guid); let bytes = concat(bytes_spec, vec<u8>(OBJECT_FROM_GUID_ADDRESS_SCHEME)); -let hash_bytes = hash::sha3_256(bytes); +let hash_bytes = hash::sha3_256(bytes); let obj_addr = from_bcs::deserialize<address>(hash_bytes); aborts_if exists<ObjectCore>(obj_addr); aborts_if !from_bcs::deserializable<address>(hash_bytes); @@ -2861,7 +2861,7 @@ to determine the identity of the starting point of ownership.
let bytes_spec = bcs::to_bytes(guid);
 let bytes = concat(bytes_spec, vec<u8>(OBJECT_FROM_GUID_ADDRESS_SCHEME));
-let hash_bytes = hash::sha3_256(bytes);
+let hash_bytes = hash::sha3_256(bytes);
 let obj_addr = from_bcs::deserialize<address>(hash_bytes);
 aborts_if exists<ObjectCore>(obj_addr);
 aborts_if !from_bcs::deserializable<address>(hash_bytes);
diff --git a/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md b/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md
index 2c81bf8676847..5ca21e1694513 100644
--- a/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md
+++ b/aptos-move/framework/supra-framework/doc/pbo_delegation_pool.md
@@ -131,7 +131,6 @@ transferred to A
 -  [Struct `UnlockStakeEvent`](#0x1_pbo_delegation_pool_UnlockStakeEvent)
 -  [Struct `WithdrawStakeEvent`](#0x1_pbo_delegation_pool_WithdrawStakeEvent)
 -  [Struct `DistributeCommissionEvent`](#0x1_pbo_delegation_pool_DistributeCommissionEvent)
--  [Struct `UnlockScheduleUpdated`](#0x1_pbo_delegation_pool_UnlockScheduleUpdated)
 -  [Struct `DistributeCommission`](#0x1_pbo_delegation_pool_DistributeCommission)
 -  [Struct `DelegatorReplacemendEvent`](#0x1_pbo_delegation_pool_DelegatorReplacemendEvent)
 -  [Struct `VoteEvent`](#0x1_pbo_delegation_pool_VoteEvent)
@@ -159,6 +158,9 @@ transferred to A
 -  [Function `get_expected_stake_pool_address`](#0x1_pbo_delegation_pool_get_expected_stake_pool_address)
 -  [Function `min_remaining_secs_for_commission_change`](#0x1_pbo_delegation_pool_min_remaining_secs_for_commission_change)
 -  [Function `initialize_delegation_pool`](#0x1_pbo_delegation_pool_initialize_delegation_pool)
+-  [Function `fund_delegators_with_locked_stake`](#0x1_pbo_delegation_pool_fund_delegators_with_locked_stake)
+-  [Function `fund_delegators_with_stake`](#0x1_pbo_delegation_pool_fund_delegators_with_stake)
+-  [Function `is_admin`](#0x1_pbo_delegation_pool_is_admin)
 -  [Function `get_admin`](#0x1_pbo_delegation_pool_get_admin)
 -  [Function `beneficiary_for_operator`](#0x1_pbo_delegation_pool_beneficiary_for_operator)
 -  [Function `enable_partial_governance_voting`](#0x1_pbo_delegation_pool_enable_partial_governance_voting)
@@ -188,9 +190,12 @@ transferred to A
 -  [Function `set_delegated_voter`](#0x1_pbo_delegation_pool_set_delegated_voter)
 -  [Function `delegate_voting_power`](#0x1_pbo_delegation_pool_delegate_voting_power)
 -  [Function `add_stake_initialization`](#0x1_pbo_delegation_pool_add_stake_initialization)
+-  [Function `fund_delegator_stake`](#0x1_pbo_delegation_pool_fund_delegator_stake)
 -  [Function `add_stake`](#0x1_pbo_delegation_pool_add_stake)
 -  [Function `replace_in_smart_tables`](#0x1_pbo_delegation_pool_replace_in_smart_tables)
 -  [Function `replace_delegator`](#0x1_pbo_delegation_pool_replace_delegator)
+-  [Function `is_principle_stakeholder`](#0x1_pbo_delegation_pool_is_principle_stakeholder)
+-  [Function `get_principle_stake`](#0x1_pbo_delegation_pool_get_principle_stake)
 -  [Function `cached_unlockable_balance`](#0x1_pbo_delegation_pool_cached_unlockable_balance)
 -  [Function `can_principle_unlock`](#0x1_pbo_delegation_pool_can_principle_unlock)
 -  [Function `unlock`](#0x1_pbo_delegation_pool_unlock)
@@ -908,58 +913,6 @@ This struct should be stored in the delegation pool resource account.
 
- - - - -## Struct `UnlockScheduleUpdated` - - - -
#[event]
-struct UnlockScheduleUpdated has drop, store
-
- - - -
-Fields - - -
-
-pool_address: address -
-
- -
-
-unlock_numerators: vector<u64> -
-
- -
-
-unlock_denominator: u64 -
-
- -
-
-unlock_start_time: u64 -
-
- -
-
-unlock_duration: u64 -
-
- -
-
- -
@@ -1631,15 +1584,6 @@ Commission percentage change is too late in this lockup period, and should be do - - - - -
const EUNLOCKING_ALREADY_STARTED: u64 = 41;
-
- - - Vector length is not the same. @@ -1824,8 +1768,8 @@ Return whether a delegation pool has already enabled partial govnernance voting.
public fun partial_governance_voting_enabled(pool_address: address): bool {
-    exists<GovernanceRecords>(pool_address) && stake::get_delegated_voter(pool_address) ==
-         pool_address
+    exists<GovernanceRecords>(pool_address)
+        && stake::get_delegated_voter(pool_address) == pool_address
 }
 
@@ -1877,9 +1821,12 @@ Return whether the commission percentage for the next lockup cycle is effective. Implementation -
public fun is_next_commission_percentage_effective(pool_address: address): bool acquires NextCommissionPercentage {
-    exists<NextCommissionPercentage>(pool_address) && timestamp::now_seconds() >= borrow_global<
-        NextCommissionPercentage>(pool_address).effective_after_secs
+
public fun is_next_commission_percentage_effective(
+    pool_address: address
+): bool acquires NextCommissionPercentage {
+    exists<NextCommissionPercentage>(pool_address)
+        && timestamp::now_seconds()
+            >= borrow_global<NextCommissionPercentage>(pool_address).effective_after_secs
 }
 
@@ -1904,7 +1851,9 @@ Return the operator commission percentage set on the delegation pool pool_ Implementation -
public fun operator_commission_percentage(pool_address: address): u64 acquires DelegationPool, NextCommissionPercentage {
+
public fun operator_commission_percentage(
+    pool_address: address
+): u64 acquires DelegationPool, NextCommissionPercentage {
     assert_delegation_pool_exists(pool_address);
     if (is_next_commission_percentage_effective(pool_address)) {
         operator_commission_percentage_next_lockup_cycle(pool_address)
@@ -1935,7 +1884,9 @@ Return the operator commission percentage for the next lockup cycle.
 Implementation
 
 
-
public fun operator_commission_percentage_next_lockup_cycle(pool_address: address): u64 acquires DelegationPool, NextCommissionPercentage {
+
public fun operator_commission_percentage_next_lockup_cycle(
+    pool_address: address
+): u64 acquires DelegationPool, NextCommissionPercentage {
     assert_delegation_pool_exists(pool_address);
     if (exists<NextCommissionPercentage>(pool_address)) {
         borrow_global<NextCommissionPercentage>(pool_address).commission_percentage_next_lockup_cycle
@@ -1968,7 +1919,9 @@ Return the number of delegators owning active stake within pool_addresspublic fun shareholders_count_active_pool(pool_address: address): u64 acquires DelegationPool {
     assert_delegation_pool_exists(pool_address);
-    pool_u64::shareholders_count(&borrow_global<DelegationPool>(pool_address).active_shares)
+    pool_u64::shareholders_count(
+        &borrow_global<DelegationPool>(pool_address).active_shares
+    )
 }
 
@@ -2022,31 +1975,32 @@ some stake and the stake pool's lockup cycle has not ended, their coins are not Implementation -
public fun get_pending_withdrawal(pool_address: address, delegator_address: address)
-    : (bool, u64) acquires DelegationPool {
+
public fun get_pending_withdrawal(
+    pool_address: address, delegator_address: address
+): (bool, u64) acquires DelegationPool {
     assert_delegation_pool_exists(pool_address);
     let pool = borrow_global<DelegationPool>(pool_address);
-    let (lockup_cycle_ended, _, pending_inactive, _, commission_pending_inactive) = calculate_stake_pool_drift(
-        pool
-    );
+    let (lockup_cycle_ended, _, pending_inactive, _, commission_pending_inactive) =
+        calculate_stake_pool_drift(pool);
 
-    let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool,
-        delegator_address);
+    let (withdrawal_exists, withdrawal_olc) =
+        pending_withdrawal_exists(pool, delegator_address);
     if (!withdrawal_exists) {
         // if no pending withdrawal, there is neither inactive nor pending_inactive stake
-        (false, 0) } else {
+        (false, 0)
+    } else {
         // delegator has either inactive or pending_inactive stake due to automatic withdrawals
         let inactive_shares = table::borrow(&pool.inactive_shares, withdrawal_olc);
         if (withdrawal_olc.index < pool.observed_lockup_cycle.index) {
             // if withdrawal's lockup cycle ended on delegation pool then it is inactive
             (true, pool_u64::balance(inactive_shares, delegator_address))
-        }
-        else {
+        } else {
             pending_inactive = pool_u64::shares_to_amount_with_total_coins(
                 inactive_shares,
                 pool_u64::shares(inactive_shares, delegator_address),
                 // exclude operator pending_inactive rewards not converted to shares yet
-                pending_inactive - commission_pending_inactive);
+                pending_inactive - commission_pending_inactive
+            );
             // if withdrawal's lockup cycle ended ONLY on stake pool then it is also inactive
             (lockup_cycle_ended, pending_inactive)
         }
@@ -2076,39 +2030,44 @@ in each of its individual states: (active,inactive,Implementation
 
 
-
public fun get_stake(pool_address: address, delegator_address: address): (u64, u64, u64) acquires DelegationPool, BeneficiaryForOperator {
+
public fun get_stake(
+    pool_address: address, delegator_address: address
+): (u64, u64, u64) acquires DelegationPool, BeneficiaryForOperator {
     assert_delegation_pool_exists(pool_address);
     let pool = borrow_global<DelegationPool>(pool_address);
     let (lockup_cycle_ended, active, _, commission_active, commission_pending_inactive) =
-         calculate_stake_pool_drift(pool);
+
+        calculate_stake_pool_drift(pool);
 
     let total_active_shares = pool_u64::total_shares(&pool.active_shares);
-    let delegator_active_shares = pool_u64::shares(&pool.active_shares,
-        delegator_address);
+    let delegator_active_shares =
+        pool_u64::shares(&pool.active_shares, delegator_address);
 
     let (_, _, pending_active, _) = stake::get_stake(pool_address);
     if (pending_active == 0) {
         // zero `pending_active` stake indicates that either there are no `add_stake` fees or
         // previous epoch has ended and should identify shares owning these fees as released
-        total_active_shares = total_active_shares - pool_u64::shares(&pool.active_shares,
-            NULL_SHAREHOLDER);
+        total_active_shares = total_active_shares
+            - pool_u64::shares(&pool.active_shares, NULL_SHAREHOLDER);
         if (delegator_address == NULL_SHAREHOLDER) {
             delegator_active_shares = 0
         }
     };
-    active = pool_u64::shares_to_amount_with_total_stats(&pool.active_shares,
+    active = pool_u64::shares_to_amount_with_total_stats(
+        &pool.active_shares,
         delegator_active_shares,
         // exclude operator active rewards not converted to shares yet
-        active - commission_active, total_active_shares);
+        active - commission_active,
+        total_active_shares
+    );
 
     // get state and stake (0 if there is none) of the pending withdrawal
-    let (withdrawal_inactive, withdrawal_stake) = get_pending_withdrawal(pool_address,
-        delegator_address);
+    let (withdrawal_inactive, withdrawal_stake) =
+        get_pending_withdrawal(pool_address, delegator_address);
     // report non-active stakes accordingly to the state of the pending withdrawal
-    let (inactive, pending_inactive) = if (withdrawal_inactive)
-        (withdrawal_stake, 0)
-    else
-        (0, withdrawal_stake);
+    let (inactive, pending_inactive) =
+        if (withdrawal_inactive) (withdrawal_stake, 0)
+        else (0, withdrawal_stake);
 
     // should also include commission rewards in case of the operator account
     // operator rewards are actually used to buy shares which is introducing
@@ -2156,19 +2115,21 @@ extracted-fee = (amount - extracted-fee) * reward-rate% * (100% - operator-commi
 Implementation
 
 
-
public fun get_add_stake_fee(pool_address: address, amount: u64): u64 acquires DelegationPool, NextCommissionPercentage {
+
public fun get_add_stake_fee(
+    pool_address: address, amount: u64
+): u64 acquires DelegationPool, NextCommissionPercentage {
     if (stake::is_current_epoch_validator(pool_address)) {
-        let (rewards_rate, rewards_rate_denominator) = staking_config::get_reward_rate(&staking_config::get());
+        let (rewards_rate, rewards_rate_denominator) =
+            staking_config::get_reward_rate(&staking_config::get());
         if (rewards_rate_denominator > 0) {
             assert_delegation_pool_exists(pool_address);
 
-            rewards_rate = rewards_rate * (MAX_FEE - operator_commission_percentage(
-                    pool_address
-                ));
+            rewards_rate = rewards_rate
+                * (MAX_FEE - operator_commission_percentage(pool_address));
             rewards_rate_denominator = rewards_rate_denominator * MAX_FEE;
             (
-                (((amount as u128) * (rewards_rate as u128)) / ((rewards_rate as u128)
-                            + (rewards_rate_denominator as u128))) as u64
+                (((amount as u128) * (rewards_rate as u128))
+                    / ((rewards_rate as u128) + (rewards_rate_denominator as u128))) as u64
             )
         } else { 0 }
     } else { 0 }
@@ -2199,8 +2160,8 @@ the validator had gone inactive before its lockup expired.
 
 
 
public fun can_withdraw_pending_inactive(pool_address: address): bool {
-    stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE && timestamp::now_seconds()
-        >= stake::get_lockup_secs(pool_address)
+    stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE
+        && timestamp::now_seconds() >= stake::get_lockup_secs(pool_address)
 }
 
@@ -2226,16 +2187,17 @@ latest state. Implementation -
public fun calculate_and_update_voter_total_voting_power(pool_address: address, voter: address)
-    : u64 acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
public fun calculate_and_update_voter_total_voting_power(
+    pool_address: address, voter: address
+): u64 acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     assert_partial_governance_voting_enabled(pool_address);
     // Delegation pool need to be synced to explain rewards(which could change the coin amount) and
     // commission(which could cause share transfer).
     synchronize_delegation_pool(pool_address);
     let pool = borrow_global<DelegationPool>(pool_address);
     let governance_records = borrow_global_mut<GovernanceRecords>(pool_address);
-    let latest_delegated_votes = update_and_borrow_mut_delegated_votes(pool,
-        governance_records, voter);
+    let latest_delegated_votes =
+        update_and_borrow_mut_delegated_votes(pool, governance_records, voter);
     calculate_total_voting_power(pool, latest_delegated_votes)
 }
 
@@ -2266,11 +2228,11 @@ latest state. pool_address: address, delegator_address: address ): address acquires DelegationPool, GovernanceRecords { assert_partial_governance_voting_enabled(pool_address); - calculate_and_update_delegator_voter_internal(borrow_global<DelegationPool>( - pool_address - ), + calculate_and_update_delegator_voter_internal( + borrow_global<DelegationPool>(pool_address), borrow_global_mut<GovernanceRecords>(pool_address), - delegator_address) + delegator_address + ) }
@@ -2364,74 +2326,105 @@ Ownership over setting the operator/voter is granted to owner who h unlock_numerators: vector<u64>, unlock_denominator: u64, unlock_start_time: u64, - unlock_duration: u64, + unlock_duration: u64 ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { //if there is an admin, it must be a multisig if (option::is_some<address>(&multisig_admin)) { // `ms_admin` is guaranteed to be NOT `@0x0` here let ms_admin = option::get_with_default<address>(&multisig_admin, @0x0); - assert!(ms_admin != @0x0, error::invalid_argument(EADMIN_ADDRESS_CANNOT_BE_ZERO)); - assert!(multisig_account::num_signatures_required(ms_admin) >= 2, - EADMIN_NOT_MULTISIG); + assert!( + ms_admin != @0x0, + error::invalid_argument(EADMIN_ADDRESS_CANNOT_BE_ZERO) + ); + assert!( + multisig_account::num_signatures_required(ms_admin) >= 2, + EADMIN_NOT_MULTISIG + ); }; // fail if the length of delegator_address and principle_stake is not the same - assert!(vector::length(&delegator_address) == vector::length(&principle_stake), - error::invalid_argument(EVECTOR_LENGTH_NOT_SAME)); + assert!( + vector::length(&delegator_address) == vector::length(&principle_stake), + error::invalid_argument(EVECTOR_LENGTH_NOT_SAME) + ); //Delegation pool must be enabled - assert!(features::delegation_pools_enabled(), - error::invalid_state(EDELEGATION_POOLS_DISABLED)); + assert!( + features::delegation_pools_enabled(), + error::invalid_state(EDELEGATION_POOLS_DISABLED) + ); //Unlock start time can not be in the past - assert!(unlock_start_time >= timestamp::now_seconds(), - error::invalid_argument(ESTARTUP_TIME_IN_PAST)); + assert!( + unlock_start_time >= timestamp::now_seconds(), + error::invalid_argument(ESTARTUP_TIME_IN_PAST) + ); //Unlock duration can not be zero assert!(unlock_duration > 0, error::invalid_argument(EPERIOD_DURATION_IS_ZERO)); //Fraction denominator can not be zero assert!(unlock_denominator != 0, error::invalid_argument(EDENOMINATOR_IS_ZERO)); //Fraction numerators can not be empty - assert!(vector::length(&unlock_numerators) > 0, - error::invalid_argument(EEMPTY_UNLOCK_SCHEDULE)); + assert!( + vector::length(&unlock_numerators) > 0, + error::invalid_argument(EEMPTY_UNLOCK_SCHEDULE) + ); //Fraction numerators can not be zero - assert!(!vector::any(&unlock_numerators, |e| { *e == 0 }), - error::invalid_argument(ESCHEDULE_WITH_ZERO_FRACTION)); + assert!( + !vector::any(&unlock_numerators, |e| { *e == 0 }), + error::invalid_argument(ESCHEDULE_WITH_ZERO_FRACTION) + ); let sum = vector::foldr(unlock_numerators, 0, |e, a| { e + a }); //Sum of numerators can not be greater than denominators - assert!(sum <= unlock_denominator, - error::invalid_argument(ENUMERATORS_GRATER_THAN_DENOMINATOR)); + assert!( + sum <= unlock_denominator, + error::invalid_argument(ENUMERATORS_GRATER_THAN_DENOMINATOR) + ); let owner_address = signer::address_of(owner); - assert!(!owner_cap_exists(owner_address), - error::already_exists(EOWNER_CAP_ALREADY_EXISTS)); - assert!(operator_commission_percentage <= MAX_FEE, - error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE)); + assert!( + !owner_cap_exists(owner_address), + error::already_exists(EOWNER_CAP_ALREADY_EXISTS) + ); + assert!( + operator_commission_percentage <= MAX_FEE, + error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE) + ); let sum = vector::fold(principle_stake, 0, |a, e| { a + e }); // fail if the value of coin and the sum of principle_stake is not the same - assert!(coin::value(&coin) == sum, - error::invalid_state(ECOIN_VALUE_NOT_SAME_AS_PRINCIPAL_STAKE)); + assert!( + coin::value(&coin) == sum, + error::invalid_state(ECOIN_VALUE_NOT_SAME_AS_PRINCIPAL_STAKE) + ); // generate a seed to be used to create the resource account hosting the delegation pool let seed = create_resource_account_seed(delegation_pool_creation_seed); - let (stake_pool_signer, stake_pool_signer_cap) = account::create_resource_account(owner, seed); + let (stake_pool_signer, stake_pool_signer_cap) = + account::create_resource_account(owner, seed); coin::register<SupraCoin>(&stake_pool_signer); // stake_pool_signer will be owner of the stake pool and have its `stake::OwnerCapability` let pool_address = signer::address_of(&stake_pool_signer); - stake::initialize_stake_owner(&stake_pool_signer, 0, owner_address, owner_address); + stake::initialize_stake_owner( + &stake_pool_signer, + 0, + owner_address, + owner_address + ); coin::deposit(pool_address, coin); let inactive_shares = table::new<ObservedLockupCycle, pool_u64::Pool>(); - table::add(&mut inactive_shares, + table::add( + &mut inactive_shares, olc_with_index(0), - pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR)); + pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR) + ); let delegator_address_copy = copy delegator_address; let principle_stake_copy = copy principle_stake; // initialize the principle stake table let principle_stake_table = table::new<address, u64>(); // initialize the principle stake table - while (vector::length(&delegator_address) != 0) { + while (vector::length(&delegator_address) > 0) { let delegator = vector::pop_back(&mut delegator_address); let stake = vector::pop_back(&mut principle_stake); table::add(&mut principle_stake_table, delegator, stake); @@ -2439,14 +2432,19 @@ Ownership over setting the operator/voter is granted to owner who h //Create unlock schedule let schedule = vector::empty(); - vector::for_each_ref(&unlock_numerators, + vector::for_each_ref( + &unlock_numerators, |e| { - let fraction = fixed_point64::create_from_rational((*e as u128), - (unlock_denominator as u128)); + let fraction = + fixed_point64::create_from_rational( + (*e as u128), (unlock_denominator as u128) + ); vector::push_back(&mut schedule, fraction); - }); + } + ); - move_to(&stake_pool_signer, + move_to( + &stake_pool_signer, DelegationPool { multisig_admin: multisig_admin, active_shares: pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR), @@ -2461,33 +2459,49 @@ Ownership over setting the operator/voter is granted to owner who h start_timestamp_secs: unlock_start_time, period_duration: unlock_duration, last_unlock_period: 0, - cumulative_unlocked_fraction: fixed_point64::create_from_rational(0, 1), + cumulative_unlocked_fraction: fixed_point64::create_from_rational( + 0, 1 + ) }, principle_stake: principle_stake_table, - add_stake_events: account::new_event_handle<AddStakeEvent>(&stake_pool_signer), - reactivate_stake_events: account::new_event_handle<ReactivateStakeEvent>(&stake_pool_signer), - unlock_stake_events: account::new_event_handle<UnlockStakeEvent>(&stake_pool_signer), - withdraw_stake_events: account::new_event_handle<WithdrawStakeEvent>(&stake_pool_signer), - distribute_commission_events: account::new_event_handle<DistributeCommissionEvent>(&stake_pool_signer), - }); + add_stake_events: account::new_event_handle<AddStakeEvent>( + &stake_pool_signer + ), + reactivate_stake_events: account::new_event_handle<ReactivateStakeEvent>( + &stake_pool_signer + ), + unlock_stake_events: account::new_event_handle<UnlockStakeEvent>( + &stake_pool_signer + ), + withdraw_stake_events: account::new_event_handle<WithdrawStakeEvent>( + &stake_pool_signer + ), + distribute_commission_events: account::new_event_handle< + DistributeCommissionEvent>(&stake_pool_signer) + } + ); // save delegation pool ownership and resource account address (inner stake pool address) on `owner` move_to(owner, DelegationPoolOwnership { pool_address }); // Add stake to each delegator - while (vector::length(&delegator_address_copy) != 0) { + while (vector::length(&delegator_address_copy) > 0) { let delegator = vector::pop_back(&mut delegator_address_copy); let stake = vector::pop_back(&mut principle_stake_copy); add_stake_initialization(delegator, pool_address, stake); }; let (active_stake, _, _, _) = stake::get_stake(pool_address); // fail if coin in StakePool.active does not match with the balance in active_shares pool. - assert!(active_stake == pool_u64::total_coins(&borrow_global<DelegationPool>( - pool_address - ).active_shares), - error::invalid_state(EACTIVE_COIN_VALUE_NOT_SAME_STAKE_DELEGATION_POOL)); + assert!( + active_stake + == pool_u64::total_coins( + &borrow_global<DelegationPool>(pool_address).active_shares + ), + error::invalid_state(EACTIVE_COIN_VALUE_NOT_SAME_STAKE_DELEGATION_POOL) + ); // All delegation pool enable partial governace voting by default once the feature flag is enabled. - if (features::partial_governance_voting_enabled() && features::delegation_pool_partial_governance_voting_enabled()) { + if (features::partial_governance_voting_enabled() + && features::delegation_pool_partial_governance_voting_enabled()) { enable_partial_governance_voting(pool_address); } } @@ -2495,6 +2509,130 @@ Ownership over setting the operator/voter is granted to owner who h + + + + +## Function `fund_delegators_with_locked_stake` + + + +
public entry fun fund_delegators_with_locked_stake(funder: &signer, pool_address: address, delegators: vector<address>, stakes: vector<u64>)
+
+ + + +
+Implementation + + +
public entry fun fund_delegators_with_locked_stake(
+    funder: &signer,
+    pool_address: address,
+    delegators: vector<address>,
+    stakes: vector<u64>
+) acquires DelegationPool, BeneficiaryForOperator, GovernanceRecords, NextCommissionPercentage {
+    {
+        assert!(
+            is_admin(signer::address_of(funder), pool_address),
+            error::permission_denied(ENOT_AUTHORIZED)
+        );
+    };
+    let principle_stake_table =
+        &mut (borrow_global_mut<DelegationPool>(pool_address).principle_stake);
+
+    vector::zip_reverse(
+        delegators,
+        stakes,
+        |delegator, stake| {
+            //Ignore if stake to be added is `0`
+            if (stake > 0) {
+                //Compute the actual stake that would be added, `principle_stake` has to be
+                //populated in the table accordingly
+                if (table::contains(principle_stake_table, delegator)) {
+                    let stake_amount =
+                        table::borrow_mut(principle_stake_table, delegator);
+                    *stake_amount = *stake_amount + stake;
+                } else {
+                    table::add(principle_stake_table, delegator, stake);
+                }
+            }
+        }
+    );
+
+    fund_delegators_with_stake(funder, pool_address, delegators, stakes);
+}
+
+ + + +
+ + + +## Function `fund_delegators_with_stake` + + + +
public entry fun fund_delegators_with_stake(funder: &signer, pool_address: address, delegators: vector<address>, stakes: vector<u64>)
+
+ + + +
+Implementation + + +
public entry fun fund_delegators_with_stake(
+    funder: &signer,
+    pool_address: address,
+    delegators: vector<address>,
+    stakes: vector<u64>
+) acquires DelegationPool, BeneficiaryForOperator, GovernanceRecords, NextCommissionPercentage {
+    //length equality check is performed by `zip_reverse`
+    vector::zip_reverse(
+        delegators,
+        stakes,
+        |delegator, stake| {
+            fund_delegator_stake(funder, pool_address, delegator, stake);
+        }
+    );
+
+}
+
+ + + +
+ + + +## Function `is_admin` + + + +
#[view]
+public fun is_admin(user_addr: address, pool_address: address): bool
+
+ + + +
+Implementation + + +
public fun is_admin(user_addr: address, pool_address: address): bool acquires DelegationPool {
+    let option_multisig = get_admin(pool_address);
+    if (!option::is_some(&option_multisig)) {
+        return false
+    } else {
+        user_addr == *option::borrow(&option_multisig)
+    }
+}
+
+ + +
@@ -2542,7 +2680,9 @@ Return the beneficiary address of the operator.
public fun beneficiary_for_operator(operator: address): address acquires BeneficiaryForOperator {
     if (exists<BeneficiaryForOperator>(operator)) {
         return borrow_global<BeneficiaryForOperator>(operator).beneficiary_for_operator
-    } else { operator }
+    } else {
+        operator
+    }
 }
 
@@ -2567,11 +2707,17 @@ THe existing voter will be replaced. The function is permissionless. Implementation -
public entry fun enable_partial_governance_voting(pool_address: address,) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
-    assert!(features::partial_governance_voting_enabled(),
-        error::invalid_state(EDISABLED_FUNCTION));
-    assert!(features::delegation_pool_partial_governance_voting_enabled(),
-        error::invalid_state(EDISABLED_FUNCTION));
+
public entry fun enable_partial_governance_voting(
+    pool_address: address
+) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+    assert!(
+        features::partial_governance_voting_enabled(),
+        error::invalid_state(EDISABLED_FUNCTION)
+    );
+    assert!(
+        features::delegation_pool_partial_governance_voting_enabled(),
+        error::invalid_state(EDISABLED_FUNCTION)
+    );
     assert_delegation_pool_exists(pool_address);
     // synchronize delegation and stake pools before any user operation.
     synchronize_delegation_pool(pool_address);
@@ -2580,19 +2726,25 @@ THe existing voter will be replaced. The function is permissionless.
     let stake_pool_signer = retrieve_stake_pool_owner(delegation_pool);
     // delegated_voter is managed by the stake pool itself, which signer capability is managed by DelegationPool.
     // So voting power of this stake pool can only be used through this module.
-    stake::set_delegated_voter(&stake_pool_signer,
-        signer::address_of(&stake_pool_signer));
+    stake::set_delegated_voter(
+        &stake_pool_signer, signer::address_of(&stake_pool_signer)
+    );
 
-    move_to(&stake_pool_signer,
+    move_to(
+        &stake_pool_signer,
         GovernanceRecords {
             votes: smart_table::new(),
             votes_per_proposal: smart_table::new(),
             vote_delegation: smart_table::new(),
             delegated_votes: smart_table::new(),
             vote_events: account::new_event_handle<VoteEvent>(&stake_pool_signer),
-            create_proposal_events: account::new_event_handle<CreateProposalEvent>(&stake_pool_signer),
-            delegate_voting_power_events: account::new_event_handle<DelegateVotingPowerEvent>(&stake_pool_signer),
-        });
+            create_proposal_events: account::new_event_handle<CreateProposalEvent>(
+                &stake_pool_signer
+            ),
+            delegate_voting_power_events: account::new_event_handle<
+                DelegateVotingPowerEvent>(&stake_pool_signer)
+        }
+    );
 }
 
@@ -2640,8 +2792,10 @@ THe existing voter will be replaced. The function is permissionless.
fun assert_delegation_pool_exists(pool_address: address) {
-    assert!(delegation_pool_exists(pool_address),
-        error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST));
+    assert!(
+        delegation_pool_exists(pool_address),
+        error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST)
+    );
 }
 
@@ -2664,10 +2818,14 @@ THe existing voter will be replaced. The function is permissionless. Implementation -
fun assert_min_active_balance(pool: &DelegationPool, delegator_address: address) {
+
fun assert_min_active_balance(
+    pool: &DelegationPool, delegator_address: address
+) {
     let balance = pool_u64::balance(&pool.active_shares, delegator_address);
-    assert!(balance >= MIN_COINS_ON_SHARES_POOL,
-        error::invalid_argument(EDELEGATOR_ACTIVE_BALANCE_TOO_LOW));
+    assert!(
+        balance >= MIN_COINS_ON_SHARES_POOL,
+        error::invalid_argument(EDELEGATOR_ACTIVE_BALANCE_TOO_LOW)
+    );
 }
 
@@ -2690,11 +2848,15 @@ THe existing voter will be replaced. The function is permissionless. Implementation -
fun assert_min_pending_inactive_balance(pool: &DelegationPool, delegator_address: address) {
-    let balance = pool_u64::balance(pending_inactive_shares_pool(pool),
-        delegator_address);
-    assert!(balance >= MIN_COINS_ON_SHARES_POOL,
-        error::invalid_argument(EDELEGATOR_PENDING_INACTIVE_BALANCE_TOO_LOW));
+
fun assert_min_pending_inactive_balance(
+    pool: &DelegationPool, delegator_address: address
+) {
+    let balance =
+        pool_u64::balance(pending_inactive_shares_pool(pool), delegator_address);
+    assert!(
+        balance >= MIN_COINS_ON_SHARES_POOL,
+        error::invalid_argument(EDELEGATOR_PENDING_INACTIVE_BALANCE_TOO_LOW)
+    );
 }
 
@@ -2719,8 +2881,10 @@ THe existing voter will be replaced. The function is permissionless.
fun assert_partial_governance_voting_enabled(pool_address: address) {
     assert_delegation_pool_exists(pool_address);
-    assert!(partial_governance_voting_enabled(pool_address),
-        error::invalid_state(EPARTIAL_GOVERNANCE_VOTING_NOT_ENABLED));
+    assert!(
+        partial_governance_voting_enabled(pool_address),
+        error::invalid_state(EPARTIAL_GOVERNANCE_VOTING_NOT_ENABLED)
+    );
 }
 
@@ -2744,11 +2908,14 @@ THe existing voter will be replaced. The function is permissionless.
fun coins_to_redeem_to_ensure_min_stake(
-    src_shares_pool: &pool_u64::Pool, shareholder: address, amount: u64,
+    src_shares_pool: &pool_u64::Pool, shareholder: address, amount: u64
 ): u64 {
     // find how many coins would be redeemed if supplying `amount`
-    let redeemed_coins = pool_u64::shares_to_amount(src_shares_pool,
-        amount_to_shares_to_redeem(src_shares_pool, shareholder, amount));
+    let redeemed_coins =
+        pool_u64::shares_to_amount(
+            src_shares_pool,
+            amount_to_shares_to_redeem(src_shares_pool, shareholder, amount)
+        );
     // if balance drops under threshold then redeem it entirely
     let src_balance = pool_u64::balance(src_shares_pool, shareholder);
     if (src_balance - redeemed_coins < MIN_COINS_ON_SHARES_POOL) {
@@ -2781,11 +2948,14 @@ THe existing voter will be replaced. The function is permissionless.
     src_shares_pool: &pool_u64::Pool,
     dst_shares_pool: &pool_u64::Pool,
     shareholder: address,
-    amount: u64,
+    amount: u64
 ): u64 {
     // find how many coins would be redeemed from source if supplying `amount`
-    let redeemed_coins = pool_u64::shares_to_amount(src_shares_pool,
-        amount_to_shares_to_redeem(src_shares_pool, shareholder, amount));
+    let redeemed_coins =
+        pool_u64::shares_to_amount(
+            src_shares_pool,
+            amount_to_shares_to_redeem(src_shares_pool, shareholder, amount)
+        );
     // if balance on destination would be less than threshold then redeem difference to threshold
     let dst_balance = pool_u64::balance(dst_shares_pool, shareholder);
     if (dst_balance + redeemed_coins < MIN_COINS_ON_SHARES_POOL) {
@@ -2868,7 +3038,9 @@ Get the active share amount of the delegator.
 Implementation
 
 
-
fun get_delegator_active_shares(pool: &DelegationPool, delegator: address): u128 {
+
fun get_delegator_active_shares(
+    pool: &DelegationPool, delegator: address
+): u128 {
     pool_u64::shares(&pool.active_shares, delegator)
 }
 
@@ -2893,7 +3065,9 @@ Get the pending inactive share amount of the delegator. Implementation -
fun get_delegator_pending_inactive_shares(pool: &DelegationPool, delegator: address): u128 {
+
fun get_delegator_pending_inactive_shares(
+    pool: &DelegationPool, delegator: address
+): u128 {
     pool_u64::shares(pending_inactive_shares_pool(pool), delegator)
 }
 
@@ -2922,7 +3096,7 @@ Get the used voting power of a voter on a proposal. governance_records: &GovernanceRecords, voter: address, proposal_id: u64 ): u64 { let votes = &governance_records.votes; - let key = VotingRecordKey { voter, proposal_id, }; + let key = VotingRecordKey { voter, proposal_id }; *smart_table::borrow_with_default(votes, key, &0) }
@@ -2947,7 +3121,9 @@ Create the seed to derive the resource account address. Implementation -
fun create_resource_account_seed(delegation_pool_creation_seed: vector<u8>,): vector<u8> {
+
fun create_resource_account_seed(
+    delegation_pool_creation_seed: vector<u8>
+): vector<u8> {
     let seed = vector::empty<u8>();
     // include module salt (before any subseeds) to avoid conflicts with other modules creating resource accounts
     vector::append(&mut seed, MODULE_SALT);
@@ -2981,7 +3157,7 @@ Borrow the mutable used voting power of a voter on a proposal.
     governance_records: &mut GovernanceRecords, voter: address, proposal_id: u64
 ): &mut u64 {
     let votes = &mut governance_records.votes;
-    let key = VotingRecordKey { proposal_id, voter, };
+    let key = VotingRecordKey { proposal_id, voter };
     smart_table::borrow_mut_with_default(votes, key, 0)
 }
 
@@ -3007,7 +3183,9 @@ Update VoteDelegation of a delegator to up-to-date then borrow_mut it.
fun update_and_borrow_mut_delegator_vote_delegation(
-    pool: &DelegationPool, governance_records: &mut GovernanceRecords, delegator: address
+    pool: &DelegationPool,
+    governance_records: &mut GovernanceRecords,
+    delegator: address
 ): &mut VoteDelegation {
     let pool_address = get_pool_address(pool);
     let locked_until_secs = stake::get_lockup_secs(pool_address);
@@ -3016,20 +3194,21 @@ Update VoteDelegation of a delegator to up-to-date then borrow_mut it.
     // By default, a delegator's delegated voter is itself.
     // TODO: recycle storage when VoteDelegation equals to default value.
     if (!smart_table::contains(vote_delegation_table, delegator)) {
-        return smart_table::borrow_mut_with_default(vote_delegation_table,
+        return smart_table::borrow_mut_with_default(
+            vote_delegation_table,
             delegator,
             VoteDelegation {
                 voter: delegator,
                 last_locked_until_secs: locked_until_secs,
-                pending_voter: delegator,
+                pending_voter: delegator
             }
         )
     };
 
     let vote_delegation = smart_table::borrow_mut(vote_delegation_table, delegator);
     // A lockup period has passed since last time `vote_delegation` was updated. Pending voter takes effect.
-    if (vote_delegation.last_locked_until_secs < locked_until_secs && vote_delegation.voter != vote_delegation
-        .pending_voter) {
+    if (vote_delegation.last_locked_until_secs < locked_until_secs
+        && vote_delegation.voter != vote_delegation.pending_voter) {
         vote_delegation.voter = vote_delegation.pending_voter;
     };
     vote_delegation
@@ -3068,13 +3247,14 @@ Update DelegatedVotes of a voter to up-to-date then borrow_mut it.
     if (!smart_table::contains(delegated_votes_per_voter, voter)) {
         let active_shares = get_delegator_active_shares(pool, voter);
         let inactive_shares = get_delegator_pending_inactive_shares(pool, voter);
-        return smart_table::borrow_mut_with_default(delegated_votes_per_voter,
+        return smart_table::borrow_mut_with_default(
+            delegated_votes_per_voter,
             voter,
             DelegatedVotes {
                 active_shares,
                 pending_inactive_shares: inactive_shares,
                 active_shares_next_lockup: active_shares,
-                last_locked_until_secs: locked_until_secs,
+                last_locked_until_secs: locked_until_secs
             }
         )
     };
@@ -3138,11 +3318,15 @@ power, which equals to the sum of the coin amounts.
 
fun calculate_total_voting_power(
     delegation_pool: &DelegationPool, latest_delegated_votes: &DelegatedVotes
 ): u64 {
-    let active_amount = pool_u64::shares_to_amount(&delegation_pool.active_shares,
-        latest_delegated_votes.active_shares);
-    let pending_inactive_amount = pool_u64::shares_to_amount(
-        pending_inactive_shares_pool(delegation_pool),
-        latest_delegated_votes.pending_inactive_shares);
+    let active_amount =
+        pool_u64::shares_to_amount(
+            &delegation_pool.active_shares, latest_delegated_votes.active_shares
+        );
+    let pending_inactive_amount =
+        pool_u64::shares_to_amount(
+            pending_inactive_shares_pool(delegation_pool),
+            latest_delegated_votes.pending_inactive_shares
+        );
     active_amount + pending_inactive_amount
 }
 
@@ -3168,10 +3352,14 @@ Update VoteDelegation of a delegator to up-to-date then return the latest voter.
fun calculate_and_update_delegator_voter_internal(
-    pool: &DelegationPool, governance_records: &mut GovernanceRecords, delegator: address
+    pool: &DelegationPool,
+    governance_records: &mut GovernanceRecords,
+    delegator: address
 ): address {
-    let vote_delegation = update_and_borrow_mut_delegator_vote_delegation(pool,
-        governance_records, delegator);
+    let vote_delegation =
+        update_and_borrow_mut_delegator_vote_delegation(
+            pool, governance_records, delegator
+        );
     vote_delegation.voter
 }
 
@@ -3199,8 +3387,8 @@ Update DelegatedVotes of a voter to up-to-date then return the total voting powe
fun calculate_and_update_delegated_votes(
     pool: &DelegationPool, governance_records: &mut GovernanceRecords, voter: address
 ): u64 {
-    let delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records,
-        voter);
+    let delegated_votes =
+        update_and_borrow_mut_delegated_votes(pool, governance_records, voter);
     calculate_total_voting_power(pool, delegated_votes)
 }
 
@@ -3225,14 +3413,17 @@ Allows an owner to change the operator of the underlying stake pool. Implementation -
public entry fun set_operator(owner: &signer, new_operator: address) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
public entry fun set_operator(
+    owner: &signer, new_operator: address
+) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     let pool_address = get_owned_pool_address(signer::address_of(owner));
     // synchronize delegation and stake pools before any user operation
     // ensure the old operator is paid its uncommitted commission rewards
     synchronize_delegation_pool(pool_address);
-    stake::set_operator(&retrieve_stake_pool_owner(borrow_global<DelegationPool>(
-                pool_address
-            )), new_operator);
+    stake::set_operator(
+        &retrieve_stake_pool_owner(borrow_global<DelegationPool>(pool_address)),
+        new_operator
+    );
 }
 
@@ -3259,27 +3450,34 @@ one for each pool. Implementation -
public entry fun set_beneficiary_for_operator(operator: &signer, new_beneficiary: address) acquires BeneficiaryForOperator {
-    assert!(features::operator_beneficiary_change_enabled(),
-        std::error::invalid_state(EOPERATOR_BENEFICIARY_CHANGE_NOT_SUPPORTED));
+
public entry fun set_beneficiary_for_operator(
+    operator: &signer, new_beneficiary: address
+) acquires BeneficiaryForOperator {
+    assert!(
+        features::operator_beneficiary_change_enabled(),
+        std::error::invalid_state(EOPERATOR_BENEFICIARY_CHANGE_NOT_SUPPORTED)
+    );
     // The beneficiay address of an operator is stored under the operator's address.
     // So, the operator does not need to be validated with respect to a staking pool.
     let operator_addr = signer::address_of(operator);
     let old_beneficiary = beneficiary_for_operator(operator_addr);
     if (exists<BeneficiaryForOperator>(operator_addr)) {
         borrow_global_mut<BeneficiaryForOperator>(operator_addr).beneficiary_for_operator =
-             new_beneficiary;
+            new_beneficiary;
     } else {
-        move_to(operator, BeneficiaryForOperator {
-                beneficiary_for_operator: new_beneficiary
-            });
+        move_to(
+            operator,
+            BeneficiaryForOperator { beneficiary_for_operator: new_beneficiary }
+        );
     };
 
-    emit(SetBeneficiaryForOperator {
+    emit(
+        SetBeneficiaryForOperator {
             operator: operator_addr,
             old_beneficiary,
-            new_beneficiary,
-        });
+            new_beneficiary
+        }
+    );
 }
 
@@ -3303,17 +3501,29 @@ Allows an owner to update the commission percentage for the operator of the unde Implementation -
public entry fun update_commission_percentage(owner: &signer, new_commission_percentage: u64) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
-    assert!(features::commission_change_delegation_pool_enabled(),
-        error::invalid_state(ECOMMISSION_RATE_CHANGE_NOT_SUPPORTED));
-    assert!(new_commission_percentage <= MAX_FEE,
-        error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE));
+
public entry fun update_commission_percentage(
+    owner: &signer, new_commission_percentage: u64
+) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+    assert!(
+        features::commission_change_delegation_pool_enabled(),
+        error::invalid_state(ECOMMISSION_RATE_CHANGE_NOT_SUPPORTED)
+    );
+    assert!(
+        new_commission_percentage <= MAX_FEE,
+        error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE)
+    );
     let owner_address = signer::address_of(owner);
     let pool_address = get_owned_pool_address(owner_address);
-    assert!(operator_commission_percentage(pool_address) + MAX_COMMISSION_INCREASE >= new_commission_percentage,
-        error::invalid_argument(ETOO_LARGE_COMMISSION_INCREASE));
-    assert!(stake::get_remaining_lockup_secs(pool_address) >= min_remaining_secs_for_commission_change(),
-        error::invalid_state(ETOO_LATE_COMMISSION_CHANGE));
+    assert!(
+        operator_commission_percentage(pool_address) + MAX_COMMISSION_INCREASE
+            >= new_commission_percentage,
+        error::invalid_argument(ETOO_LARGE_COMMISSION_INCREASE)
+    );
+    assert!(
+        stake::get_remaining_lockup_secs(pool_address)
+            >= min_remaining_secs_for_commission_change(),
+        error::invalid_state(ETOO_LATE_COMMISSION_CHANGE)
+    );
 
     // synchronize delegation and stake pools before any user operation. this ensures:
     // (1) the operator is paid its uncommitted commission rewards with the old commission percentage, and
@@ -3321,28 +3531,34 @@ Allows an owner to update the commission percentage for the operator of the unde
     synchronize_delegation_pool(pool_address);
 
     if (exists<NextCommissionPercentage>(pool_address)) {
-        let commission_percentage = borrow_global_mut<NextCommissionPercentage>(
-            pool_address
-        );
+        let commission_percentage =
+            borrow_global_mut<NextCommissionPercentage>(pool_address);
         commission_percentage.commission_percentage_next_lockup_cycle = new_commission_percentage;
         commission_percentage.effective_after_secs = stake::get_lockup_secs(
             pool_address
         );
     } else {
         let delegation_pool = borrow_global<DelegationPool>(pool_address);
-        let pool_signer = account::create_signer_with_capability(&delegation_pool.stake_pool_signer_cap);
-        move_to(&pool_signer,
+        let pool_signer =
+            account::create_signer_with_capability(
+                &delegation_pool.stake_pool_signer_cap
+            );
+        move_to(
+            &pool_signer,
             NextCommissionPercentage {
                 commission_percentage_next_lockup_cycle: new_commission_percentage,
-                effective_after_secs: stake::get_lockup_secs(pool_address),
-            });
+                effective_after_secs: stake::get_lockup_secs(pool_address)
+            }
+        );
     };
 
-    event::emit(CommissionPercentageChange {
+    event::emit(
+        CommissionPercentageChange {
             pool_address,
             owner: owner_address,
-            commission_percentage_next_lockup_cycle: new_commission_percentage,
-        });
+            commission_percentage_next_lockup_cycle: new_commission_percentage
+        }
+    );
 }
 
@@ -3366,16 +3582,21 @@ Allows an owner to change the delegated voter of the underlying stake pool. Implementation -
public entry fun set_delegated_voter(owner: &signer, new_voter: address) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
public entry fun set_delegated_voter(
+    owner: &signer, new_voter: address
+) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     // No one can change delegated_voter once the partial governance voting feature is enabled.
-    assert!(!features::delegation_pool_partial_governance_voting_enabled(),
-        error::invalid_state(EDEPRECATED_FUNCTION));
+    assert!(
+        !features::delegation_pool_partial_governance_voting_enabled(),
+        error::invalid_state(EDEPRECATED_FUNCTION)
+    );
     let pool_address = get_owned_pool_address(signer::address_of(owner));
     // synchronize delegation and stake pools before any user operation
     synchronize_delegation_pool(pool_address);
-    stake::set_delegated_voter(&retrieve_stake_pool_owner(borrow_global<DelegationPool>(
-                pool_address
-            )), new_voter);
+    stake::set_delegated_voter(
+        &retrieve_stake_pool_owner(borrow_global<DelegationPool>(pool_address)),
+        new_voter
+    );
 }
 
@@ -3411,35 +3632,40 @@ this change won't take effects until the next lockup period. let delegator_address = signer::address_of(delegator); let delegation_pool = borrow_global<DelegationPool>(pool_address); let governance_records = borrow_global_mut<GovernanceRecords>(pool_address); - let delegator_vote_delegation = update_and_borrow_mut_delegator_vote_delegation( - delegation_pool, governance_records, delegator_address - ); + let delegator_vote_delegation = + update_and_borrow_mut_delegator_vote_delegation( + delegation_pool, governance_records, delegator_address + ); let pending_voter: address = delegator_vote_delegation.pending_voter; // No need to update if the voter doesn't really change. if (pending_voter != new_voter) { delegator_vote_delegation.pending_voter = new_voter; - let active_shares = get_delegator_active_shares(delegation_pool, - delegator_address); + let active_shares = + get_delegator_active_shares(delegation_pool, delegator_address); // <active shares> of <pending voter of shareholder> -= <active_shares> // <active shares> of <new voter of shareholder> += <active_shares> - let pending_delegated_votes = update_and_borrow_mut_delegated_votes( - delegation_pool, governance_records, pending_voter - ); + let pending_delegated_votes = + update_and_borrow_mut_delegated_votes( + delegation_pool, governance_records, pending_voter + ); pending_delegated_votes.active_shares_next_lockup = pending_delegated_votes.active_shares_next_lockup - active_shares; - let new_delegated_votes = update_and_borrow_mut_delegated_votes(delegation_pool, - governance_records, new_voter); + let new_delegated_votes = + update_and_borrow_mut_delegated_votes( + delegation_pool, governance_records, new_voter + ); new_delegated_votes.active_shares_next_lockup = new_delegated_votes.active_shares_next_lockup + active_shares; }; - event::emit_event(&mut governance_records.delegate_voting_power_events, + event::emit_event( + &mut governance_records.delegate_voting_power_events, DelegateVotingPowerEvent { pool_address, delegator: delegator_address, - voter: new_voter, + voter: new_voter } ); } @@ -3465,7 +3691,9 @@ Add amount of coins to the delegation pool pool_addressImplementation -
fun add_stake_initialization(delegator_address: address, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords {
+
fun add_stake_initialization(
+    delegator_address: address, pool_address: address, amount: u64
+) acquires DelegationPool, GovernanceRecords {
     // short-circuit if amount to add is 0 so no event is emitted
     if (amount == 0) { return };
 
@@ -3482,14 +3710,13 @@ Add amount of coins to the delegation pool pool_address
 
-
+
 
-## Function `add_stake`
+## Function `fund_delegator_stake`
 
-Add amount of coins to the delegation pool pool_address.
 
 
-
public entry fun add_stake(delegator: &signer, pool_address: address, amount: u64)
+
fun fund_delegator_stake(funder: &signer, pool_address: address, delegator_address: address, amount: u64)
 
@@ -3498,7 +3725,12 @@ Add amount of coins to the delegation pool pool_addressImplementation -
public entry fun add_stake(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
fun fund_delegator_stake(
+    funder: &signer,
+    pool_address: address,
+    delegator_address: address,
+    amount: u64
+) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     // short-circuit if amount to add is 0 so no event is emitted
     if (amount == 0) { return };
     // synchronize delegation and stake pools before any user operation
@@ -3507,11 +3739,10 @@ Add amount of coins to the delegation pool pool_addressto be charged for adding `amount` stake on this delegation pool at this epoch
     let add_stake_fee = get_add_stake_fee(pool_address, amount);
 
+    supra_account::transfer(funder, pool_address, amount);
     let pool = borrow_global_mut<DelegationPool>(pool_address);
-    let delegator_address = signer::address_of(delegator);
 
     // stake the entire amount to the stake pool
-    supra_account::transfer(delegator, pool_address, amount);
     stake::add_stake(&retrieve_stake_pool_owner(pool), amount);
 
     // but buy shares for delegator just for the remaining amount after fee
@@ -3524,14 +3755,48 @@ Add amount of coins to the delegation pool pool_addressto appreciate all shares on the active pool atomically
     buy_in_active_shares(pool, NULL_SHAREHOLDER, add_stake_fee);
 
-    event::emit_event(&mut pool.add_stake_events,
+    event::emit_event(
+        &mut pool.add_stake_events,
         AddStakeEvent {
             pool_address,
             delegator_address,
             amount_added: amount,
-            add_stake_fee,
-        },
+            add_stake_fee
+        }
     );
+
+}
+
+ + + + + + + +## Function `add_stake` + +Add amount of coins to the delegation pool pool_address. + + +
public entry fun add_stake(delegator: &signer, pool_address: address, amount: u64)
+
+ + + +
+Implementation + + +
public entry fun add_stake(
+    delegator: &signer, pool_address: address, amount: u64
+) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+    fund_delegator_stake(
+        delegator,
+        pool_address,
+        signer::address_of(delegator),
+        amount
+    )
 }
 
@@ -3555,7 +3820,9 @@ Add amount of coins to the delegation pool pool_addressfun replace_in_smart_tables<Key: copy + drop, Val>( - table: &mut SmartTable<Key, Val>, old_entry: Key, new_entry: Key + table: &mut SmartTable<Key, Val>, + old_entry: Key, + new_entry: Key ) { if (smart_table::contains(table, old_entry)) { let val = smart_table::remove(table, old_entry); @@ -3588,43 +3855,61 @@ This does not apply to anyone who added stake later or operator
public entry fun replace_delegator(
-    multisig_admin: &signer, pool_address: address, old_delegator: address, new_delegator: address
+    multisig_admin: &signer,
+    pool_address: address,
+    old_delegator: address,
+    new_delegator: address
 ) acquires DelegationPool, GovernanceRecords {
 
+    //Ensure that authorized admin is calling
+    let admin_addr = signer::address_of(multisig_admin);
+    assert!(
+        is_admin(admin_addr, pool_address),
+        error::permission_denied(ENOT_AUTHORIZED)
+    );
     //Ensure replacement address is different
-    assert!(old_delegator != new_delegator,
-        error::invalid_argument(ENEW_IS_SAME_AS_OLD_DELEGATOR));
+    assert!(
+        old_delegator != new_delegator,
+        error::invalid_argument(ENEW_IS_SAME_AS_OLD_DELEGATOR)
+    );
     //Ensure it is a valid `pool_addres`
-    assert!(exists<DelegationPool>(pool_address),
-        error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST));
+    assert!(
+        exists<DelegationPool>(pool_address),
+        error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST)
+    );
 
     let pool: &mut DelegationPool = borrow_global_mut<DelegationPool>(pool_address);
-    let admin_addr = signer::address_of(multisig_admin);
-    //Ensure that authorized admin is calling
-    assert!(admin_addr != @0x0, error::invalid_argument(EADMIN_ADDRESS_CANNOT_BE_ZERO));
-    assert!(admin_addr == option::get_with_default(&pool.multisig_admin, @0x0),
-        error::permission_denied(ENOT_AUTHORIZED));
-
     //Ensure `old_delegator` is part of original principle stakers before commencing the replacement
-    assert!(table::contains(&pool.principle_stake, old_delegator),
-        error::unavailable(EDELEGATOR_DOES_NOT_EXIST));
+    assert!(
+        table::contains(&pool.principle_stake, old_delegator),
+        error::unavailable(EDELEGATOR_DOES_NOT_EXIST)
+    );
 
     //replace in `active_shares` pool
     {
         let active_pool = &mut pool.active_shares;
         let active_shares = pool_u64::shares(active_pool, old_delegator);
-        pool_u64::transfer_shares(active_pool, old_delegator, new_delegator,
-            active_shares);
+        pool_u64::transfer_shares(
+            active_pool,
+            old_delegator,
+            new_delegator,
+            active_shares
+        );
     };
 
     //replace in `inactive_shares` pool
-    let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool,
-        old_delegator);
+    let (withdrawal_exists, withdrawal_olc) =
+        pending_withdrawal_exists(pool, old_delegator);
     if (withdrawal_exists) {
-        let inactive_pool = table::borrow_mut(&mut pool.inactive_shares, withdrawal_olc);
+        let inactive_pool =
+            table::borrow_mut(&mut pool.inactive_shares, withdrawal_olc);
         let inactive_shares = pool_u64::shares(inactive_pool, old_delegator);
-        pool_u64::transfer_shares(inactive_pool, old_delegator, new_delegator,
-            inactive_shares);
+        pool_u64::transfer_shares(
+            inactive_pool,
+            old_delegator,
+            new_delegator,
+            inactive_shares
+        );
 
         //replace in `pending_withdrawals`
         {
@@ -3639,28 +3924,39 @@ This does not apply to anyone who added stake later or operator
     {
         if (features::partial_governance_voting_enabled()) {
             let grecords = borrow_global_mut<GovernanceRecords>(pool_address);
-            replace_in_smart_tables(&mut grecords.vote_delegation, old_delegator,
-                new_delegator);
-            replace_in_smart_tables(&mut grecords.delegated_votes, old_delegator,
-                new_delegator);
+            replace_in_smart_tables(
+                &mut grecords.vote_delegation, old_delegator, new_delegator
+            );
+            replace_in_smart_tables(
+                &mut grecords.delegated_votes, old_delegator, new_delegator
+            );
             let old_keys: vector<VotingRecordKey> = vector::empty();
             let new_keys: vector<VotingRecordKey> = vector::empty();
-            smart_table::for_each_ref<VotingRecordKey, u64>(&grecords.votes,
+            smart_table::for_each_ref<VotingRecordKey, u64>(
+                &grecords.votes,
                 |key, _val| {
                     let VotingRecordKey { voter, proposal_id } = *key;
                     if (voter == old_delegator) {
-                        vector::push_back(&mut new_keys, VotingRecordKey {
+                        vector::push_back(
+                            &mut new_keys,
+                            VotingRecordKey {
                                 voter: new_delegator,
                                 proposal_id: proposal_id
-                            });
+                            }
+                        );
                         vector::push_back(&mut old_keys, *key);
                     };
 
-                });
+                }
+            );
 
-            vector::zip_ref(&old_keys, &new_keys, |old, new| {
+            vector::zip_ref(
+                &old_keys,
+                &new_keys,
+                |old, new| {
                     replace_in_smart_tables(&mut grecords.votes, *old, *new);
-                });
+                }
+            );
         }
     };
     // replace in principle_stake table
@@ -3669,8 +3965,69 @@ This does not apply to anyone who added stake later or operator
         table::add(&mut pool.principle_stake, new_delegator, val);
     };
 
-    event::emit(DelegatorReplacemendEvent { pool_address, old_delegator, new_delegator },);
+    event::emit(
+        DelegatorReplacemendEvent { pool_address, old_delegator, new_delegator }
+    );
+
+}
+
+ + + +
+ + + +## Function `is_principle_stakeholder` + + + +
#[view]
+public fun is_principle_stakeholder(delegator_addr: address, pool_addr: address): bool
+
+ + + +
+Implementation + +
public fun is_principle_stakeholder(
+    delegator_addr: address, pool_addr: address
+): bool acquires DelegationPool {
+    let pool = borrow_global<DelegationPool>(pool_addr);
+    table::contains(&pool.principle_stake, delegator_addr)
+}
+
+ + + +
+ + + +## Function `get_principle_stake` + + + +
#[view]
+public fun get_principle_stake(delegator_addr: address, pool_addr: address): u64
+
+ + + +
+Implementation + + +
public fun get_principle_stake(
+    delegator_addr: address, pool_addr: address
+): u64 acquires DelegationPool {
+    let pool = borrow_global<DelegationPool>(pool_addr);
+    if (!table::contains(&pool.principle_stake, delegator_addr)) { 0 }
+    else {
+        *table::borrow(&pool.principle_stake, delegator_addr)
+    }
 }
 
@@ -3697,23 +4054,37 @@ accurate as time passes Implementation -
public fun cached_unlockable_balance(delegator_addr: address, pool_addr: address): u64 acquires DelegationPool {
-    assert!(exists<DelegationPool>(pool_addr),
-        error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST));
+
public fun cached_unlockable_balance(
+    delegator_addr: address, pool_addr: address
+): u64 acquires DelegationPool {
+    assert!(
+        exists<DelegationPool>(pool_addr),
+        error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST)
+    );
     let pool = borrow_global<DelegationPool>(pool_addr);
-    let delegator_active_balance = pool_u64::balance(&pool.active_shares, delegator_addr);
-    let unlockable_fraction = pool.principle_unlock_schedule.cumulative_unlocked_fraction;
-    let delegator_principle_stake = *table::borrow(&pool.principle_stake, delegator_addr);
+    let delegator_active_balance =
+        pool_u64::balance(&pool.active_shares, delegator_addr);
+    let unlockable_fraction =
+        pool.principle_unlock_schedule.cumulative_unlocked_fraction;
+    let delegator_principle_stake =
+        *table::borrow(&pool.principle_stake, delegator_addr);
 
     //To avoid problem even if fraction is slightly above 1
-    let unlockable_principle_stake = (math128::min(fixed_point64::multiply_u128(
-                (delegator_principle_stake as u128), unlockable_fraction
-            ),
-            (delegator_principle_stake as u128)) as u64);
+    let unlockable_principle_stake =
+        (
+            math128::min(
+                fixed_point64::multiply_u128(
+                    (delegator_principle_stake as u128), unlockable_fraction
+                ),
+                (delegator_principle_stake as u128)
+            ) as u64
+        );
     let locked_amount = delegator_principle_stake - unlockable_principle_stake;
 
-    assert!(delegator_active_balance >= locked_amount,
-        error::invalid_state(EDELEGATOR_ACTIVE_BALANCE_TOO_LOW));
+    assert!(
+        delegator_active_balance >= locked_amount,
+        error::invalid_state(EDELEGATOR_ACTIVE_BALANCE_TOO_LOW)
+    );
     delegator_active_balance - locked_amount
 
 }
@@ -3727,6 +4098,7 @@ accurate as time passes
 
 ## Function `can_principle_unlock`
 
+Note: this does not synchronize with stake pool, therefore the answer may be conservative
 
 
 
public fun can_principle_unlock(delegator_addr: address, pool_address: address, amount: u64): bool
@@ -3738,41 +4110,51 @@ accurate as time passes
 Implementation
 
 
-
public fun can_principle_unlock(delegator_addr: address, pool_address: address, amount: u64)
-    : bool acquires DelegationPool {
+
public fun can_principle_unlock(
+    delegator_addr: address, pool_address: address, amount: u64
+): bool acquires DelegationPool {
 
-    let principle_stake_table = &borrow_global<DelegationPool>(pool_address).principle_stake;
+    let principle_stake_table =
+        &borrow_global<DelegationPool>(pool_address).principle_stake;
 
     if (!table::contains(principle_stake_table, delegator_addr)) {
-        return true
+        return false
     };
 
-    let unlock_schedule = &mut borrow_global_mut<DelegationPool>(pool_address).principle_unlock_schedule;
+    let unlock_schedule =
+        &mut borrow_global_mut<DelegationPool>(pool_address).principle_unlock_schedule;
     let one = fixed_point64::create_from_rational(1, 1);
-    if (fixed_point64::greater_or_equal(unlock_schedule.cumulative_unlocked_fraction, one)) {
+    if (fixed_point64::greater_or_equal(
+        unlock_schedule.cumulative_unlocked_fraction, one
+    )) {
         return true
     };
     if (unlock_schedule.start_timestamp_secs > timestamp::now_seconds()) {
-        let unlockable_amount = cached_unlockable_balance(delegator_addr, pool_address);
+        let unlockable_amount =
+            cached_unlockable_balance(delegator_addr, pool_address);
         return amount <= unlockable_amount
     };
 
     //subtraction safety due to check above
-    let unlock_periods_passed = (timestamp::now_seconds() - unlock_schedule.start_timestamp_secs)
-        / unlock_schedule.period_duration;
+    let unlock_periods_passed =
+        (timestamp::now_seconds() - unlock_schedule.start_timestamp_secs)
+            / unlock_schedule.period_duration;
     let last_unlocked_period = unlock_schedule.last_unlock_period;
     let schedule_length = vector::length(&unlock_schedule.schedule);
     let cfraction = unlock_schedule.cumulative_unlocked_fraction;
-    while (last_unlocked_period < unlock_periods_passed && fixed_point64::less(
-            cfraction, one
-        )) {
-        let next_fraction = if (schedule_length <= last_unlocked_period) {
-            *vector::borrow(&unlock_schedule.schedule, schedule_length - 1)
-        } else { *vector::borrow(&unlock_schedule.schedule, last_unlocked_period) };
+    while (last_unlocked_period < unlock_periods_passed
+        && fixed_point64::less(cfraction, one)) {
+        let next_fraction =
+            if (schedule_length <= last_unlocked_period) {
+                *vector::borrow(&unlock_schedule.schedule, schedule_length - 1)
+            } else {
+                *vector::borrow(&unlock_schedule.schedule, last_unlocked_period)
+            };
         cfraction = fixed_point64::add(cfraction, next_fraction);
 
         last_unlocked_period = last_unlocked_period + 1;
     };
+
     unlock_schedule.cumulative_unlocked_fraction = cfraction;
     unlock_schedule.last_unlock_period = unlock_periods_passed;
     let unlockable_amount = cached_unlockable_balance(delegator_addr, pool_address);
@@ -3802,36 +4184,51 @@ at most how much active stake there is on the stake pool.
 Implementation
 
 
-
public entry fun unlock(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
public entry fun unlock(
+    delegator: &signer, pool_address: address, amount: u64
+) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     // short-circuit if amount to unlock is 0 so no event is emitted
     if (amount == 0) { return };
     // fail unlock of more stake than `active` on the stake pool
     let (active, _, _, _) = stake::get_stake(pool_address);
-    assert!(amount <= active,
-        error::invalid_argument(ENOT_ENOUGH_ACTIVE_STAKE_TO_UNLOCK));
+    assert!(
+        amount <= active,
+        error::invalid_argument(ENOT_ENOUGH_ACTIVE_STAKE_TO_UNLOCK)
+    );
 
     // synchronize delegation and stake pools before any user operation
     synchronize_delegation_pool(pool_address);
 
     let delegator_address = signer::address_of(delegator);
     // fail if the amount after withdraw is less than the principle stake and the lockup time is not expired
-    assert!(can_principle_unlock(delegator_address, pool_address, amount),
-        error::invalid_argument(EAMOUNT_REQUESTED_NOT_UNLOCKABLE));
+    if (is_principle_stakeholder(delegator_address, pool_address)) {
+        assert!(
+            can_principle_unlock(delegator_address, pool_address, amount),
+            error::invalid_argument(EAMOUNT_REQUESTED_NOT_UNLOCKABLE)
+        );
+    };
     let pool = borrow_global_mut<DelegationPool>(pool_address);
-    amount = coins_to_transfer_to_ensure_min_stake(&pool.active_shares,
-        pending_inactive_shares_pool(pool), delegator_address, amount,);
+    amount = coins_to_transfer_to_ensure_min_stake(
+        &pool.active_shares,
+        pending_inactive_shares_pool(pool),
+        delegator_address,
+        amount
+    );
     amount = redeem_active_shares(pool, delegator_address, amount);
     stake::unlock(&retrieve_stake_pool_owner(pool), amount);
 
     buy_in_pending_inactive_shares(pool, delegator_address, amount);
     assert_min_pending_inactive_balance(pool, delegator_address);
 
-    event::emit_event(&mut pool.unlock_stake_events,
-        UnlockStakeEvent { pool_address, delegator_address, amount_unlocked: amount, },
+    event::emit_event(
+        &mut pool.unlock_stake_events,
+        UnlockStakeEvent { pool_address, delegator_address, amount_unlocked: amount }
     );
     let (active_stake, _, pending_active, _) = stake::get_stake(pool_address);
-    assert!(active_stake + pending_active == pool_u64::total_coins(&pool.active_shares),
-        error::invalid_state(EACTIVE_COIN_VALUE_NOT_SAME_STAKE_DELEGATION_POOL));
+    assert!(
+        active_stake + pending_active == pool_u64::total_coins(&pool.active_shares),
+        error::invalid_state(EACTIVE_COIN_VALUE_NOT_SAME_STAKE_DELEGATION_POOL)
+    );
 }
 
@@ -3855,7 +4252,9 @@ Move amount of coins from pending_inactive to active. Implementation -
public entry fun reactivate_stake(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
public entry fun reactivate_stake(
+    delegator: &signer, pool_address: address, amount: u64
+) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     // short-circuit if amount to reactivate is 0 so no event is emitted
     if (amount == 0) { return };
     // synchronize delegation and stake pools before any user operation
@@ -3864,19 +4263,32 @@ Move amount of coins from pending_inactive to active.
     let pool = borrow_global_mut<DelegationPool>(pool_address);
     let delegator_address = signer::address_of(delegator);
 
-    amount = coins_to_transfer_to_ensure_min_stake(pending_inactive_shares_pool(pool), &pool
-        .active_shares, delegator_address, amount,);
+    amount = coins_to_transfer_to_ensure_min_stake(
+        pending_inactive_shares_pool(pool),
+        &pool.active_shares,
+        delegator_address,
+        amount
+    );
     let observed_lockup_cycle = pool.observed_lockup_cycle;
-    amount = redeem_inactive_shares(pool, delegator_address, amount,
-        observed_lockup_cycle);
+    amount = redeem_inactive_shares(
+        pool,
+        delegator_address,
+        amount,
+        observed_lockup_cycle
+    );
 
     stake::reactivate_stake(&retrieve_stake_pool_owner(pool), amount);
 
     buy_in_active_shares(pool, delegator_address, amount);
     assert_min_active_balance(pool, delegator_address);
 
-    event::emit_event(&mut pool.reactivate_stake_events,
-        ReactivateStakeEvent { pool_address, delegator_address, amount_reactivated: amount, },
+    event::emit_event(
+        &mut pool.reactivate_stake_events,
+        ReactivateStakeEvent {
+            pool_address,
+            delegator_address,
+            amount_reactivated: amount
+        }
     );
 }
 
@@ -3901,12 +4313,17 @@ Withdraw amount of owned inactive stake from the delegation pool at Implementation -
public entry fun withdraw(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
public entry fun withdraw(
+    delegator: &signer, pool_address: address, amount: u64
+) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     assert!(amount > 0, error::invalid_argument(EWITHDRAW_ZERO_STAKE));
     // synchronize delegation and stake pools before any user operation
     synchronize_delegation_pool(pool_address);
-    withdraw_internal(borrow_global_mut<DelegationPool>(pool_address),
-        signer::address_of(delegator), amount);
+    withdraw_internal(
+        borrow_global_mut<DelegationPool>(pool_address),
+        signer::address_of(delegator),
+        amount
+    );
 }
 
@@ -3929,25 +4346,38 @@ Withdraw amount of owned inactive stake from the delegation pool at Implementation -
fun withdraw_internal(pool: &mut DelegationPool, delegator_address: address, amount: u64) acquires GovernanceRecords {
+
fun withdraw_internal(
+    pool: &mut DelegationPool, delegator_address: address, amount: u64
+) acquires GovernanceRecords {
     // TODO: recycle storage when a delegator fully exits the delegation pool.
     // short-circuit if amount to withdraw is 0 so no event is emitted
     if (amount == 0) { return };
 
     let pool_address = get_pool_address(pool);
-    let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool,
-        delegator_address);
+    let (withdrawal_exists, withdrawal_olc) =
+        pending_withdrawal_exists(pool, delegator_address);
     // exit if no withdrawal or (it is pending and cannot withdraw pending_inactive stake from stake pool)
-    if (!(withdrawal_exists
-            && (withdrawal_olc.index < pool.observed_lockup_cycle.index || can_withdraw_pending_inactive(
-                    pool_address
-                )))) { return };
+    if (!(
+        withdrawal_exists
+            && (
+                withdrawal_olc.index < pool.observed_lockup_cycle.index
+                    || can_withdraw_pending_inactive(pool_address)
+            )
+    )) { return };
 
     if (withdrawal_olc.index == pool.observed_lockup_cycle.index) {
-        amount = coins_to_redeem_to_ensure_min_stake(pending_inactive_shares_pool(pool),
-            delegator_address, amount,)
+        amount = coins_to_redeem_to_ensure_min_stake(
+            pending_inactive_shares_pool(pool),
+            delegator_address,
+            amount
+        )
     };
-    amount = redeem_inactive_shares(pool, delegator_address, amount, withdrawal_olc);
+    amount = redeem_inactive_shares(
+        pool,
+        delegator_address,
+        amount,
+        withdrawal_olc
+    );
 
     let stake_pool_owner = &retrieve_stake_pool_owner(pool);
     // stake pool will inactivate entire pending_inactive stake at `stake::withdraw` to make it withdrawable
@@ -3976,8 +4406,9 @@ Withdraw amount of owned inactive stake from the delegation pool at
     let (_, inactive, _, _) = stake::get_stake(pool_address);
     pool.total_coins_inactive = inactive;
 
-    event::emit_event(&mut pool.withdraw_stake_events,
-        WithdrawStakeEvent { pool_address, delegator_address, amount_withdrawn: amount, },
+    event::emit_event(
+        &mut pool.withdraw_stake_events,
+        WithdrawStakeEvent { pool_address, delegator_address, amount_withdrawn: amount }
     );
 }
 
@@ -4004,12 +4435,14 @@ A bool is returned to signal if a pending withdrawal exists at all. Implementation -
fun pending_withdrawal_exists(pool: &DelegationPool, delegator_address: address)
-    : (bool,
-    ObservedLockupCycle) {
+
fun pending_withdrawal_exists(
+    pool: &DelegationPool, delegator_address: address
+): (bool, ObservedLockupCycle) {
     if (table::contains(&pool.pending_withdrawals, delegator_address)) {
         (true, *table::borrow(&pool.pending_withdrawals, delegator_address))
-    } else { (false, olc_with_index(0)) }
+    } else {
+        (false, olc_with_index(0))
+    }
 }
 
@@ -4087,10 +4520,13 @@ be explicitly withdrawn by delegator Implementation -
fun execute_pending_withdrawal(pool: &mut DelegationPool, delegator_address: address) acquires GovernanceRecords {
-    let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool,
-        delegator_address);
-    if (withdrawal_exists && withdrawal_olc.index < pool.observed_lockup_cycle.index) {
+
fun execute_pending_withdrawal(
+    pool: &mut DelegationPool, delegator_address: address
+) acquires GovernanceRecords {
+    let (withdrawal_exists, withdrawal_olc) =
+        pending_withdrawal_exists(pool, delegator_address);
+    if (withdrawal_exists
+        && withdrawal_olc.index < pool.observed_lockup_cycle.index) {
         withdraw_internal(pool, delegator_address, MAX_U64);
     }
 }
@@ -4117,8 +4553,9 @@ deposited coins_amount. This function doesn't make any coin transfe
 Implementation
 
 
-
fun buy_in_active_shares(pool: &mut DelegationPool, shareholder: address, coins_amount: u64,)
-    : u128 acquires GovernanceRecords {
+
fun buy_in_active_shares(
+    pool: &mut DelegationPool, shareholder: address, coins_amount: u64
+): u128 acquires GovernanceRecords {
     let new_shares = pool_u64::amount_to_shares(&pool.active_shares, coins_amount);
     // No need to buy 0 shares.
     if (new_shares == 0) {
@@ -4128,8 +4565,9 @@ deposited coins_amount. This function doesn't make any coin transfe
     // Always update governance records before any change to the shares pool.
     let pool_address = get_pool_address(pool);
     if (partial_governance_voting_enabled(pool_address)) {
-        update_governance_records_for_buy_in_active_shares(pool, pool_address,
-            new_shares, shareholder);
+        update_governance_records_for_buy_in_active_shares(
+            pool, pool_address, new_shares, shareholder
+        );
     };
 
     pool_u64::buy_in(&mut pool.active_shares, shareholder, coins_amount);
@@ -4161,10 +4599,12 @@ to ensure there is always only one withdrawal request.
 
 
 
fun buy_in_pending_inactive_shares(
-    pool: &mut DelegationPool, shareholder: address, coins_amount: u64,
+    pool: &mut DelegationPool, shareholder: address, coins_amount: u64
 ): u128 acquires GovernanceRecords {
-    let new_shares = pool_u64::amount_to_shares(pending_inactive_shares_pool(pool),
-        coins_amount);
+    let new_shares =
+        pool_u64::amount_to_shares(
+            pending_inactive_shares_pool(pool), coins_amount
+        );
     // never create a new pending withdrawal unless delegator owns some pending_inactive shares
     if (new_shares == 0) {
         return 0
@@ -4173,21 +4613,27 @@ to ensure there is always only one withdrawal request.
     // Always update governance records before any change to the shares pool.
     let pool_address = get_pool_address(pool);
     if (partial_governance_voting_enabled(pool_address)) {
-        update_governance_records_for_buy_in_pending_inactive_shares(pool, pool_address,
-            new_shares, shareholder);
+        update_governance_records_for_buy_in_pending_inactive_shares(
+            pool, pool_address, new_shares, shareholder
+        );
     };
 
     // cannot buy inactive shares, only pending_inactive at current lockup cycle
-    pool_u64::buy_in(pending_inactive_shares_pool_mut(pool), shareholder, coins_amount);
+    pool_u64::buy_in(
+        pending_inactive_shares_pool_mut(pool), shareholder, coins_amount
+    );
 
     // execute the pending withdrawal if exists and is inactive before creating a new one
     execute_pending_withdrawal(pool, shareholder);
 
     // save observed lockup cycle for the new pending withdrawal
     let observed_lockup_cycle = pool.observed_lockup_cycle;
-    assert!(*table::borrow_mut_with_default(&mut pool.pending_withdrawals, shareholder,
-            observed_lockup_cycle) == observed_lockup_cycle,
-        error::invalid_state(EPENDING_WITHDRAWAL_EXISTS));
+    assert!(
+        *table::borrow_mut_with_default(
+            &mut pool.pending_withdrawals, shareholder, observed_lockup_cycle
+        ) == observed_lockup_cycle,
+        error::invalid_state(EPENDING_WITHDRAWAL_EXISTS)
+    );
 
     new_shares
 }
@@ -4215,7 +4661,7 @@ to the exact number of shares to redeem in order to achieve this.
 
 
 
fun amount_to_shares_to_redeem(
-    shares_pool: &pool_u64::Pool, shareholder: address, coins_amount: u64,
+    shares_pool: &pool_u64::Pool, shareholder: address, coins_amount: u64
 ): u128 {
     if (coins_amount >= pool_u64::balance(shares_pool, shareholder)) {
         // cap result at total shares of shareholder to pass `EINSUFFICIENT_SHARES` on subsequent redeem
@@ -4249,18 +4695,23 @@ be available for withdrawal when current OLC ends.
 Implementation
 
 
-
fun redeem_active_shares(pool: &mut DelegationPool, shareholder: address, coins_amount: u64,)
-    : u64 acquires GovernanceRecords {
-    let shares_to_redeem = amount_to_shares_to_redeem(&pool.active_shares, shareholder,
-        coins_amount);
+
fun redeem_active_shares(
+    pool: &mut DelegationPool, shareholder: address, coins_amount: u64
+): u64 acquires GovernanceRecords {
+    let shares_to_redeem =
+        amount_to_shares_to_redeem(&pool.active_shares, shareholder, coins_amount);
     // silently exit if not a shareholder otherwise redeem would fail with `ESHAREHOLDER_NOT_FOUND`
     if (shares_to_redeem == 0) return 0;
 
     // Always update governance records before any change to the shares pool.
     let pool_address = get_pool_address(pool);
     if (partial_governance_voting_enabled(pool_address)) {
-        update_governanace_records_for_redeem_active_shares(pool, pool_address,
-            shares_to_redeem, shareholder);
+        update_governanace_records_for_redeem_active_shares(
+            pool,
+            pool_address,
+            shares_to_redeem,
+            shareholder
+        );
     };
 
     pool_u64::redeem_shares(&mut pool.active_shares, shareholder, shares_to_redeem)
@@ -4296,26 +4747,34 @@ escape inactivation when current lockup ends.
     pool: &mut DelegationPool,
     shareholder: address,
     coins_amount: u64,
-    lockup_cycle: ObservedLockupCycle,
+    lockup_cycle: ObservedLockupCycle
 ): u64 acquires GovernanceRecords {
-    let shares_to_redeem = amount_to_shares_to_redeem(table::borrow(&pool.inactive_shares,
-            lockup_cycle), shareholder, coins_amount);
+    let shares_to_redeem =
+        amount_to_shares_to_redeem(
+            table::borrow(&pool.inactive_shares, lockup_cycle),
+            shareholder,
+            coins_amount
+        );
     // silently exit if not a shareholder otherwise redeem would fail with `ESHAREHOLDER_NOT_FOUND`
     if (shares_to_redeem == 0) return 0;
 
     // Always update governance records before any change to the shares pool.
     let pool_address = get_pool_address(pool);
     // Only redeem shares from the pending_inactive pool at `lockup_cycle` == current OLC.
-    if (partial_governance_voting_enabled(pool_address) && lockup_cycle.index == pool.observed_lockup_cycle
-        .index) {
-        update_governanace_records_for_redeem_pending_inactive_shares(pool, pool_address,
-            shares_to_redeem, shareholder);
+    if (partial_governance_voting_enabled(pool_address)
+        && lockup_cycle.index == pool.observed_lockup_cycle.index) {
+        update_governanace_records_for_redeem_pending_inactive_shares(
+            pool,
+            pool_address,
+            shares_to_redeem,
+            shareholder
+        );
     };
 
     let inactive_shares = table::borrow_mut(&mut pool.inactive_shares, lockup_cycle);
     // 1. reaching here means delegator owns inactive/pending_inactive shares at OLC `lockup_cycle`
-    let redeemed_coins = pool_u64::redeem_shares(inactive_shares, shareholder,
-        shares_to_redeem);
+    let redeemed_coins =
+        pool_u64::redeem_shares(inactive_shares, shareholder, shares_to_redeem);
 
     // if entirely reactivated pending_inactive stake or withdrawn inactive one,
     // re-enable unlocking for delegator by deleting this pending withdrawal
@@ -4325,8 +4784,11 @@ escape inactivation when current lockup ends.
         table::remove(&mut pool.pending_withdrawals, shareholder);
     };
     // destroy inactive shares pool of past OLC if all its stake has been withdrawn
-    if (lockup_cycle.index < pool.observed_lockup_cycle.index && total_coins(inactive_shares) == 0) {
-        pool_u64::destroy_empty(table::remove(&mut pool.inactive_shares, lockup_cycle));
+    if (lockup_cycle.index < pool.observed_lockup_cycle.index
+        && total_coins(inactive_shares) == 0) {
+        pool_u64::destroy_empty(
+            table::remove(&mut pool.inactive_shares, lockup_cycle)
+        );
     };
 
     redeemed_coins
@@ -4356,10 +4818,12 @@ whether the lockup expired on the stake pool.
 
 
 
fun calculate_stake_pool_drift(pool: &DelegationPool): (bool, u64, u64, u64, u64) {
-    let (active, inactive, pending_active, pending_inactive) = stake::get_stake(
-        get_pool_address(pool));
-    assert!(inactive >= pool.total_coins_inactive,
-        error::invalid_state(ESLASHED_INACTIVE_STAKE_ON_PAST_OLC));
+    let (active, inactive, pending_active, pending_inactive) =
+        stake::get_stake(get_pool_address(pool));
+    assert!(
+        inactive >= pool.total_coins_inactive,
+        error::invalid_state(ESLASHED_INACTIVE_STAKE_ON_PAST_OLC)
+    );
     // determine whether a new lockup cycle has been ended on the stake pool and
     // inactivated SOME `pending_inactive` stake which should stop earning rewards now,
     // thus requiring separation of the `pending_inactive` stake on current observed lockup
@@ -4382,23 +4846,36 @@ whether the lockup expired on the stake pool.
 
     // operator `active` rewards not persisted yet to the active shares pool
     let pool_active = total_coins(&pool.active_shares);
-    let commission_active = if (active > pool_active) {
-        math64::mul_div(active - pool_active, pool.operator_commission_percentage,
-            MAX_FEE)
-    } else {
-        // handle any slashing applied to `active` stake
-        0 };
+    let commission_active =
+        if (active > pool_active) {
+            math64::mul_div(
+                active - pool_active, pool.operator_commission_percentage, MAX_FEE
+            )
+        } else {
+            // handle any slashing applied to `active` stake
+            0
+        };
     // operator `pending_inactive` rewards not persisted yet to the pending_inactive shares pool
     let pool_pending_inactive = total_coins(pending_inactive_shares_pool(pool));
-    let commission_pending_inactive = if (pending_inactive > pool_pending_inactive) {
-        math64::mul_div(pending_inactive - pool_pending_inactive, pool.operator_commission_percentage,
-            MAX_FEE)
-    } else {
-        // handle any slashing applied to `pending_inactive` stake
-        0 };
+    let commission_pending_inactive =
+        if (pending_inactive > pool_pending_inactive) {
+            math64::mul_div(
+                pending_inactive - pool_pending_inactive,
+                pool.operator_commission_percentage,
+                MAX_FEE
+            )
+        } else {
+            // handle any slashing applied to `pending_inactive` stake
+            0
+        };
 
-    (lockup_cycle_ended, active, pending_inactive, commission_active,
-        commission_pending_inactive)
+    (
+        lockup_cycle_ended,
+        active,
+        pending_inactive,
+        commission_active,
+        commission_pending_inactive
+    )
 }
 
@@ -4423,11 +4900,18 @@ shares pools, assign commission to operator and eventually prepare delegation po Implementation -
public entry fun synchronize_delegation_pool(pool_address: address) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
+
public entry fun synchronize_delegation_pool(
+    pool_address: address
+) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage {
     assert_delegation_pool_exists(pool_address);
     let pool = borrow_global_mut<DelegationPool>(pool_address);
-    let (lockup_cycle_ended, active, pending_inactive, commission_active,
-        commission_pending_inactive) = calculate_stake_pool_drift(pool);
+    let (
+        lockup_cycle_ended,
+        active,
+        pending_inactive,
+        commission_active,
+        commission_pending_inactive
+    ) = calculate_stake_pool_drift(pool);
 
     // zero `pending_active` stake indicates that either there are no `add_stake` fees or
     // previous epoch has ended and should release the shares owning the existing fees
@@ -4444,35 +4928,49 @@ shares pools, assign commission to operator and eventually prepare delegation po
 
     // update total coins accumulated by `active` + `pending_active` shares
     // redeemed `add_stake` fees are restored and distributed to the rest of the pool as rewards
-    pool_u64::update_total_coins(&mut pool.active_shares, active - commission_active);
+    pool_u64::update_total_coins(&mut pool.active_shares, active
+        - commission_active);
     // update total coins accumulated by `pending_inactive` shares at current observed lockup cycle
-    pool_u64::update_total_coins(pending_inactive_shares_pool_mut(pool),
-        pending_inactive - commission_pending_inactive);
+    pool_u64::update_total_coins(
+        pending_inactive_shares_pool_mut(pool),
+        pending_inactive - commission_pending_inactive
+    );
 
     // reward operator its commission out of uncommitted active rewards (`add_stake` fees already excluded)
-    buy_in_active_shares(pool,
-        beneficiary_for_operator(stake::get_operator(pool_address)), commission_active);
+    buy_in_active_shares(
+        pool,
+        beneficiary_for_operator(stake::get_operator(pool_address)),
+        commission_active
+    );
     // reward operator its commission out of uncommitted pending_inactive rewards
-    buy_in_pending_inactive_shares(pool,
+    buy_in_pending_inactive_shares(
+        pool,
         beneficiary_for_operator(stake::get_operator(pool_address)),
-        commission_pending_inactive);
+        commission_pending_inactive
+    );
 
-    event::emit_event(&mut pool.distribute_commission_events,
+    event::emit_event(
+        &mut pool.distribute_commission_events,
         DistributeCommissionEvent {
             pool_address,
             operator: stake::get_operator(pool_address),
             commission_active,
-            commission_pending_inactive,
-        },);
+            commission_pending_inactive
+        }
+    );
 
     if (features::operator_beneficiary_change_enabled()) {
-        emit(DistributeCommission {
+        emit(
+            DistributeCommission {
                 pool_address,
                 operator: stake::get_operator(pool_address),
-                beneficiary: beneficiary_for_operator(stake::get_operator(pool_address)),
+                beneficiary: beneficiary_for_operator(
+                    stake::get_operator(pool_address)
+                ),
                 commission_active,
-                commission_pending_inactive,
-            })
+                commission_pending_inactive
+            }
+        )
     };
 
     // advance lockup cycle on delegation pool if already ended on stake pool (AND stake explicitly inactivated)
@@ -4484,9 +4982,11 @@ shares pools, assign commission to operator and eventually prepare delegation po
         // advance lockup cycle on the delegation pool
         pool.observed_lockup_cycle.index = pool.observed_lockup_cycle.index + 1;
         // start new lockup cycle with a fresh shares pool for `pending_inactive` stake
-        table::add(&mut pool.inactive_shares,
+        table::add(
+            &mut pool.inactive_shares,
             pool.observed_lockup_cycle,
-            pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR));
+            pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR)
+        );
     };
 
     if (is_next_commission_percentage_effective(pool_address)) {
@@ -4517,25 +5017,35 @@ shares pools, assign commission to operator and eventually prepare delegation po
 
 
 
fun update_governance_records_for_buy_in_active_shares(
-    pool: &DelegationPool, pool_address: address, new_shares: u128, shareholder: address
+    pool: &DelegationPool,
+    pool_address: address,
+    new_shares: u128,
+    shareholder: address
 ) acquires GovernanceRecords {
     // <active shares> of <shareholder> += <new_shares> ---->
     // <active shares> of <current voter of shareholder> += <new_shares>
     // <active shares> of <next voter of shareholder> += <new_shares>
     let governance_records = borrow_global_mut<GovernanceRecords>(pool_address);
-    let vote_delegation = update_and_borrow_mut_delegator_vote_delegation(pool,
-        governance_records, shareholder);
+    let vote_delegation =
+        update_and_borrow_mut_delegator_vote_delegation(
+            pool, governance_records, shareholder
+        );
     let current_voter = vote_delegation.voter;
     let pending_voter = vote_delegation.pending_voter;
-    let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool,
-        governance_records, current_voter);
-    current_delegated_votes.active_shares = current_delegated_votes.active_shares + new_shares;
+    let current_delegated_votes =
+        update_and_borrow_mut_delegated_votes(
+            pool, governance_records, current_voter
+        );
+    current_delegated_votes.active_shares = current_delegated_votes.active_shares
+        + new_shares;
     if (pending_voter == current_voter) {
         current_delegated_votes.active_shares_next_lockup = current_delegated_votes.active_shares_next_lockup
             + new_shares;
     } else {
-        let pending_delegated_votes = update_and_borrow_mut_delegated_votes(pool,
-            governance_records, pending_voter);
+        let pending_delegated_votes =
+            update_and_borrow_mut_delegated_votes(
+                pool, governance_records, pending_voter
+            );
         pending_delegated_votes.active_shares_next_lockup = pending_delegated_votes.active_shares_next_lockup
             + new_shares;
     };
@@ -4562,16 +5072,23 @@ shares pools, assign commission to operator and eventually prepare delegation po
 
 
 
fun update_governance_records_for_buy_in_pending_inactive_shares(
-    pool: &DelegationPool, pool_address: address, new_shares: u128, shareholder: address
+    pool: &DelegationPool,
+    pool_address: address,
+    new_shares: u128,
+    shareholder: address
 ) acquires GovernanceRecords {
     // <pending inactive shares> of <shareholder> += <new_shares>   ---->
     // <pending inactive shares> of <current voter of shareholder> += <new_shares>
     // no impact on <pending inactive shares> of <next voter of shareholder>
     let governance_records = borrow_global_mut<GovernanceRecords>(pool_address);
-    let current_voter = calculate_and_update_delegator_voter_internal(pool,
-        governance_records, shareholder);
-    let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool,
-        governance_records, current_voter);
+    let current_voter =
+        calculate_and_update_delegator_voter_internal(
+            pool, governance_records, shareholder
+        );
+    let current_delegated_votes =
+        update_and_borrow_mut_delegated_votes(
+            pool, governance_records, current_voter
+        );
     current_delegated_votes.pending_inactive_shares = current_delegated_votes.pending_inactive_shares
         + new_shares;
 }
@@ -4597,25 +5114,35 @@ shares pools, assign commission to operator and eventually prepare delegation po
 
 
 
fun update_governanace_records_for_redeem_active_shares(
-    pool: &DelegationPool, pool_address: address, shares_to_redeem: u128, shareholder: address
+    pool: &DelegationPool,
+    pool_address: address,
+    shares_to_redeem: u128,
+    shareholder: address
 ) acquires GovernanceRecords {
     // <active shares> of <shareholder> -= <shares_to_redeem> ---->
     // <active shares> of <current voter of shareholder> -= <shares_to_redeem>
     // <active shares> of <next voter of shareholder> -= <shares_to_redeem>
     let governance_records = borrow_global_mut<GovernanceRecords>(pool_address);
-    let vote_delegation = update_and_borrow_mut_delegator_vote_delegation(pool,
-        governance_records, shareholder);
+    let vote_delegation =
+        update_and_borrow_mut_delegator_vote_delegation(
+            pool, governance_records, shareholder
+        );
     let current_voter = vote_delegation.voter;
     let pending_voter = vote_delegation.pending_voter;
-    let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool,
-        governance_records, current_voter);
-    current_delegated_votes.active_shares = current_delegated_votes.active_shares - shares_to_redeem;
+    let current_delegated_votes =
+        update_and_borrow_mut_delegated_votes(
+            pool, governance_records, current_voter
+        );
+    current_delegated_votes.active_shares = current_delegated_votes.active_shares
+        - shares_to_redeem;
     if (current_voter == pending_voter) {
         current_delegated_votes.active_shares_next_lockup = current_delegated_votes.active_shares_next_lockup
             - shares_to_redeem;
     } else {
-        let pending_delegated_votes = update_and_borrow_mut_delegated_votes(pool,
-            governance_records, pending_voter);
+        let pending_delegated_votes =
+            update_and_borrow_mut_delegated_votes(
+                pool, governance_records, pending_voter
+            );
         pending_delegated_votes.active_shares_next_lockup = pending_delegated_votes.active_shares_next_lockup
             - shares_to_redeem;
     };
@@ -4642,16 +5169,23 @@ shares pools, assign commission to operator and eventually prepare delegation po
 
 
 
fun update_governanace_records_for_redeem_pending_inactive_shares(
-    pool: &DelegationPool, pool_address: address, shares_to_redeem: u128, shareholder: address
+    pool: &DelegationPool,
+    pool_address: address,
+    shares_to_redeem: u128,
+    shareholder: address
 ) acquires GovernanceRecords {
     // <pending inactive shares> of <shareholder> -= <shares_to_redeem>  ---->
     // <pending inactive shares> of <current voter of shareholder> -= <shares_to_redeem>
     // no impact on <pending inactive shares> of <next voter of shareholder>
     let governance_records = borrow_global_mut<GovernanceRecords>(pool_address);
-    let current_voter = calculate_and_update_delegator_voter_internal(pool,
-        governance_records, shareholder);
-    let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool,
-        governance_records, current_voter);
+    let current_voter =
+        calculate_and_update_delegator_voter_internal(
+            pool, governance_records, shareholder
+        );
+    let current_delegated_votes =
+        update_and_borrow_mut_delegated_votes(
+            pool, governance_records, current_voter
+        );
     current_delegated_votes.pending_inactive_shares = current_delegated_votes.pending_inactive_shares
         - shares_to_redeem;
 }
diff --git a/aptos-move/framework/supra-framework/doc/randomness.md b/aptos-move/framework/supra-framework/doc/randomness.md
index 514d7d17c30c4..9823c1d8d023c 100644
--- a/aptos-move/framework/supra-framework/doc/randomness.md
+++ b/aptos-move/framework/supra-framework/doc/randomness.md
@@ -61,7 +61,7 @@ Security holds under the same proof-of-stake assumption that secures the Supra n
 
 
 
use 0x1::event;
-use 0x1::hash;
+use 0x1::hash;
 use 0x1::option;
 use 0x1::system_addresses;
 use 0x1::transaction_context;
@@ -292,7 +292,7 @@ of the hash function).
     vector::append(&mut input, seed);
     vector::append(&mut input, transaction_context::get_transaction_hash());
     vector::append(&mut input, fetch_and_increment_txn_counter());
-    hash::sha3_256(input)
+    hash::sha3_256(input)
 }
 
@@ -1074,7 +1074,7 @@ function as its payload. let txn_hash = transaction_context::spec_get_txn_hash(); let txn_counter = spec_fetch_and_increment_txn_counter(); ensures len(result) == 32; -ensures result == hash::sha3_256(concat(concat(concat(input, seed), txn_hash), txn_counter)); +ensures result == hash::sha3_256(concat(concat(concat(input, seed), txn_hash), txn_counter));
diff --git a/aptos-move/framework/supra-framework/doc/stake.md b/aptos-move/framework/supra-framework/doc/stake.md index 113f9e9e709dc..6f8c32f667cc2 100644 --- a/aptos-move/framework/supra-framework/doc/stake.md +++ b/aptos-move/framework/supra-framework/doc/stake.md @@ -2462,7 +2462,7 @@ to set later. validator_index: 0, }); - if (initial_stake_amount != 0) { + if (initial_stake_amount > 0) { add_stake(owner, initial_stake_amount); }; @@ -3576,7 +3576,7 @@ Can only be called by the operator of the validator/staking pool. assert!(option::is_some(&maybe_active_index), error::invalid_state(ENOT_VALIDATOR)); let validator_info = vector::swap_remove( &mut validator_set.active_validators, option::extract(&mut maybe_active_index)); - assert!(vector::length(&validator_set.active_validators) != 0, error::invalid_state(ELAST_VALIDATOR)); + assert!(vector::length(&validator_set.active_validators) > 0, error::invalid_state(ELAST_VALIDATOR)); vector::push_back(&mut validator_set.pending_inactive, validator_info); if (std::features::module_event_migration_enabled()) { @@ -3928,7 +3928,7 @@ Return the ValidatorConsensusInfo of each current validator, sorted let cur_pending_active = coin::value(&stake_pool.pending_active); let cur_pending_inactive = coin::value(&stake_pool.pending_inactive); - let cur_reward = if (candidate_in_current_validator_set && cur_active != 0) { + let cur_reward = if (candidate_in_current_validator_set && cur_active > 0) { spec { assert candidate.config.validator_index < len(validator_perf.validators); }; @@ -4269,7 +4269,7 @@ Calculate the rewards amount. // We do multiplication in u128 before division to avoid the overflow and minimize the rounding error. let rewards_numerator = (stake_amount as u128) * (rewards_rate as u128) * (num_successful_proposals as u128); let rewards_denominator = (rewards_rate_denominator as u128) * (num_total_proposals as u128); - if (rewards_denominator != 0) { + if (rewards_denominator > 0) { ((rewards_numerator / rewards_denominator) as u64) } else { 0 @@ -4305,7 +4305,7 @@ Mint rewards corresponding to current epoch's acquires SupraCoinCapabilities { let stake_amount = coin::value(stake); - let rewards_amount = if (stake_amount != 0) { + let rewards_amount = if (stake_amount > 0) { calculate_rewards_amount( stake_amount, num_successful_proposals, @@ -4316,7 +4316,7 @@ Mint rewards corresponding to current epoch's else { 0 }; - if (rewards_amount != 0) { + if (rewards_amount > 0) { let mint_cap = &borrow_global<SupraCoinCapabilities>(@supra_framework).mint_cap; let rewards = coin::mint(rewards_amount, mint_cap); coin::merge(stake, rewards); @@ -4474,7 +4474,7 @@ Returns validator's next epoch voting power, including pending_active, active, a validator_set.total_joining_power = validator_set.total_joining_power + (increase_amount as u128); // Only validator voting power increase if the current validator set's voting power > 0. - if (validator_set.total_voting_power != 0) { + if (validator_set.total_voting_power > 0) { assert!( validator_set.total_joining_power <= validator_set.total_voting_power * voting_power_increase_limit / 100, error::invalid_argument(EVOTING_POWER_INCREASE_EXCEEDS_LIMIT), @@ -5491,6 +5491,7 @@ Returns validator's next epoch voting power, including pending_active, active, a
pragma verify = false;
+pragma disable_invariants_in_body;
 include ResourceRequirement;
 include GetReconfigStartTimeRequirement;
 include staking_config::StakingRewardsConfigRequirement;
diff --git a/aptos-move/framework/supra-framework/doc/staking_config.md b/aptos-move/framework/supra-framework/doc/staking_config.md
index c431a45175c0b..f74624e2a25a0 100644
--- a/aptos-move/framework/supra-framework/doc/staking_config.md
+++ b/aptos-move/framework/supra-framework/doc/staking_config.md
@@ -362,15 +362,15 @@ Only called during genesis.
     validate_required_stake(minimum_stake, maximum_stake);
 
     assert!(
-        recurring_lockup_duration_secs != 0,
+        recurring_lockup_duration_secs > 0,
         error::invalid_argument(EZERO_LOCKUP_DURATION)
     );
     assert!(
-        rewards_rate_denominator != 0,
+        rewards_rate_denominator > 0,
         error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR)
     );
     assert!(
-        voting_power_increase_limit != 0 && voting_power_increase_limit <= 50,
+        voting_power_increase_limit > 0 && voting_power_increase_limit <= 50,
         error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT)
     );
 
@@ -805,7 +805,7 @@ Can only be called as part of the Supra governance proposal process established
     supra_framework: &signer, new_recurring_lockup_duration_secs: u64
 ) acquires StakingConfig {
     assert!(
-        new_recurring_lockup_duration_secs != 0,
+        new_recurring_lockup_duration_secs > 0,
         error::invalid_argument(EZERO_LOCKUP_DURATION)
     );
     system_addresses::assert_supra_framework(supra_framework);
@@ -848,7 +848,7 @@ Can only be called as part of the Supra governance proposal process established
     );
     system_addresses::assert_supra_framework(supra_framework);
     assert!(
-        new_rewards_rate_denominator != 0,
+        new_rewards_rate_denominator > 0,
         error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR)
     );
     // `rewards_rate` which is the numerator is limited to be `<= MAX_REWARDS_RATE` in order to avoid the arithmetic
@@ -977,7 +977,7 @@ Can only be called as part of the Supra governance proposal process established
 ) acquires StakingConfig {
     system_addresses::assert_supra_framework(supra_framework);
     assert!(
-        new_voting_power_increase_limit != 0
+        new_voting_power_increase_limit > 0
             && new_voting_power_increase_limit <= 50,
         error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT)
     );
@@ -1008,7 +1008,7 @@ Can only be called as part of the Supra governance proposal process established
 
 
fun validate_required_stake(minimum_stake: u64, maximum_stake: u64) {
     assert!(
-        minimum_stake <= maximum_stake && maximum_stake != 0,
+        minimum_stake <= maximum_stake && maximum_stake > 0,
         error::invalid_argument(EINVALID_STAKE_RANGE)
     );
 }
@@ -1056,7 +1056,7 @@ Can only be called as part of the Supra governance proposal process established
     // This field, rewards_rate_period_in_secs must be greater than 0.
     // TODO: rewards_rate_period_in_secs should be longer than the epoch duration but reading epoch duration causes a circular dependency.
     assert!(
-        rewards_rate_period_in_secs != 0,
+        rewards_rate_period_in_secs > 0,
         error::invalid_argument(EINVALID_REWARDS_RATE_PERIOD)
     );
 }
diff --git a/aptos-move/framework/supra-framework/doc/staking_contract.md b/aptos-move/framework/supra-framework/doc/staking_contract.md
index 3b91343b7af5b..fdf925a255408 100644
--- a/aptos-move/framework/supra-framework/doc/staking_contract.md
+++ b/aptos-move/framework/supra-framework/doc/staking_contract.md
@@ -1686,7 +1686,7 @@ Staker can call this function to create a simple staking contract with a specifi
     contract_creation_seed: vector<u8>,
 ): address acquires Store {
     assert!(
-        commission_percentage <= 100,
+        commission_percentage >= 0 && commission_percentage <= 100,
         error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE),
     );
     // The amount should be at least the min_stake_required, so the stake pool will be eligible to join the
@@ -1889,7 +1889,7 @@ TODO: fix the typo in function name. commision -> commission
     new_commission_percentage: u64
 ) acquires Store, BeneficiaryForOperator, StakingGroupUpdateCommissionEvent {
     assert!(
-        new_commission_percentage <= 100,
+        new_commission_percentage >= 0 && new_commission_percentage <= 100,
         error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE),
     );
 
@@ -2358,7 +2358,7 @@ Distribute all unlocked (inactive) funds according to distribution shares.
         distribution_pool, distribution_amount, operator, staking_contract.commission_percentage);
 
     // Buy all recipients out of the distribution pool.
-    while (pool_u64::shareholders_count(distribution_pool) != 0) {
+    while (pool_u64::shareholders_count(distribution_pool) > 0) {
         let recipients = pool_u64::shareholders(distribution_pool);
         let recipient = *vector::borrow(&mut recipients, 0);
         let current_shares = pool_u64::shares(distribution_pool, recipient);
@@ -2379,7 +2379,7 @@ Distribute all unlocked (inactive) funds according to distribution shares.
     };
 
     // In case there's any dust left, send them all to the staker.
-    if (coin::value(&coins) != 0) {
+    if (coin::value(&coins) > 0) {
         supra_account::deposit_coins(staker, coins);
         pool_u64::update_total_coins(distribution_pool, 0);
     } else {
diff --git a/aptos-move/framework/supra-framework/doc/storage_gas.md b/aptos-move/framework/supra-framework/doc/storage_gas.md
index 20b96b608320f..95dc5823fceb3 100644
--- a/aptos-move/framework/supra-framework/doc/storage_gas.md
+++ b/aptos-move/framework/supra-framework/doc/storage_gas.md
@@ -774,7 +774,7 @@ Which means that the price above min_gas is approximately
 
 
 
public fun new_usage_gas_config(target_usage: u64, read_curve: GasCurve, create_curve: GasCurve, write_curve: GasCurve): UsageGasConfig {
-    assert!(target_usage != 0, error::invalid_argument(EZERO_TARGET_USAGE));
+    assert!(target_usage > 0, error::invalid_argument(EZERO_TARGET_USAGE));
     assert!(target_usage <= MAX_U64 / BASIS_POINT_DENOMINATION, error::invalid_argument(ETARGET_USAGE_TOO_BIG));
     UsageGasConfig {
         target_usage,
diff --git a/aptos-move/framework/supra-framework/doc/supra_config.md b/aptos-move/framework/supra-framework/doc/supra_config.md
index bb3c8507dc91b..ec43b19a3078d 100644
--- a/aptos-move/framework/supra-framework/doc/supra_config.md
+++ b/aptos-move/framework/supra-framework/doc/supra_config.md
@@ -87,7 +87,7 @@ Publishes the SupraConfig config.
 
 
public(friend) fun initialize(supra_framework: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(supra_framework);
-    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
     move_to(supra_framework, SupraConfig { config });
 }
 
@@ -119,7 +119,7 @@ supra_framework::supra_governance::reconfigure(&framework_signer);
public fun set_for_next_epoch(account: &signer, config: vector<u8>) {
     system_addresses::assert_supra_framework(account);
-    assert!(vector::length(&config) != 0, error::invalid_argument(EINVALID_CONFIG));
+    assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG));
     std::config_buffer::upsert<SupraConfig>(SupraConfig {config});
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/supra_governance.md b/aptos-move/framework/supra-framework/doc/supra_governance.md index 0f970d6f0afab..5bc61628b5b50 100644 --- a/aptos-move/framework/supra-framework/doc/supra_governance.md +++ b/aptos-move/framework/supra-framework/doc/supra_governance.md @@ -1115,7 +1115,7 @@ are too large (e.g. module upgrades). let execution_hash = multisig_voting::get_execution_hash<GovernanceProposal>(@supra_framework, proposal_id); // If this is a multi-step proposal, the proposal id will already exist in the ApprovedExecutionHashes map. - // We will update execution hash in ApprovedExecutionHashes to be the next_execution_hash. + // We will update execution hash in ApprovedExecutionHashes to be the next_execution_hash. if (simple_map::contains_key(&approved_hashes.hashes, &proposal_id)) { let current_execution_hash = simple_map::borrow_mut(&mut approved_hashes.hashes, &proposal_id); *current_execution_hash = execution_hash; @@ -1183,12 +1183,12 @@ Resolve a successful multi-step proposal. This would fail if the proposal is not ): signer acquires GovernanceResponsbility, ApprovedExecutionHashes { multisig_voting::resolve_proposal_v2<GovernanceProposal>(@supra_framework, proposal_id, next_execution_hash); // If the current step is the last step of this multi-step proposal, - // we will remove the execution hash from the ApprovedExecutionHashes map. + // we will remove the execution hash from the ApprovedExecutionHashes map. if (vector::length(&next_execution_hash) == 0) { remove_supra_approved_hash(proposal_id); } else { // If the current step is not the last step of this proposal, - // we replace the current execution hash with the next execution hash + // we replace the current execution hash with the next execution hash // in the ApprovedExecutionHashes map. add_supra_approved_script_hash(proposal_id) }; diff --git a/aptos-move/framework/supra-framework/doc/transaction_fee.md b/aptos-move/framework/supra-framework/doc/transaction_fee.md index e442a3a58695b..bd54dceea5937 100644 --- a/aptos-move/framework/supra-framework/doc/transaction_fee.md +++ b/aptos-move/framework/supra-framework/doc/transaction_fee.md @@ -460,7 +460,7 @@ Burns a specified fraction of the coin. assume burn_percentage * collected_amount <= MAX_U64; }; let amount_to_burn = (burn_percentage as u64) * collected_amount / 100; - if (amount_to_burn != 0) { + if (amount_to_burn > 0) { let coin_to_burn = coin::extract(coin, amount_to_burn); coin::burn( coin_to_burn, diff --git a/aptos-move/framework/supra-framework/doc/transaction_validation.md b/aptos-move/framework/supra-framework/doc/transaction_validation.md index 28cfa55c3429b..5aa36bc15fedf 100644 --- a/aptos-move/framework/supra-framework/doc/transaction_validation.md +++ b/aptos-move/framework/supra-framework/doc/transaction_validation.md @@ -300,7 +300,7 @@ Only called during genesis to initialize system resources for this module. transaction_sender == gas_payer || account::exists_at(transaction_sender) || !features::sponsored_automatic_account_creation_enabled() - || txn_sequence_number != 0 + || txn_sequence_number > 0 ) { assert!(account::exists_at(transaction_sender), error::invalid_argument(PROLOGUE_EACCOUNT_DOES_NOT_EXIST)); assert!( diff --git a/aptos-move/framework/supra-framework/doc/vesting.md b/aptos-move/framework/supra-framework/doc/vesting.md index 41af9e584b85a..d472cbb7abc6e 100644 --- a/aptos-move/framework/supra-framework/doc/vesting.md +++ b/aptos-move/framework/supra-framework/doc/vesting.md @@ -2114,8 +2114,8 @@ Create a vesting schedule with the given schedule of distributions, a vesting st start_timestamp_secs: u64, period_duration: u64, ): VestingSchedule { - assert!(vector::length(&schedule) != 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE)); - assert!(period_duration != 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD)); + assert!(vector::length(&schedule) > 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE)); + assert!(period_duration > 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD)); assert!( start_timestamp_secs >= timestamp::now_seconds(), error::invalid_argument(EVESTING_START_TOO_SOON), @@ -2167,7 +2167,7 @@ Create a vesting contract with a given configurations. error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS), ); assert_account_is_registered_for_supra(withdrawal_address); - assert!(vector::length(shareholders) != 0, error::invalid_argument(ENO_SHAREHOLDERS)); + assert!(vector::length(shareholders) > 0, error::invalid_argument(ENO_SHAREHOLDERS)); assert!( simple_map::length(&buy_ins) == vector::length(shareholders), error::invalid_argument(ESHARES_LENGTH_MISMATCH), @@ -2189,7 +2189,7 @@ Create a vesting contract with a given configurations. ); grant_amount = grant_amount + buy_in_amount; }); - assert!(grant_amount != 0, error::invalid_argument(EZERO_GRANT)); + assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT)); // If this is the first time this admin account has created a vesting contract, initialize the admin store. let admin_address = signer::address_of(admin); @@ -2482,7 +2482,7 @@ Distribute any withdrawable stake from the stake pool. }); // Send any remaining "dust" (leftover due to rounding error) to the withdrawal address. - if (coin::value(&coins) != 0) { + if (coin::value(&coins) > 0) { supra_account::deposit_coins(vesting_contract.withdrawal_address, coins); } else { coin::destroy_zero(coins); diff --git a/aptos-move/framework/supra-framework/doc/vesting_without_staking.md b/aptos-move/framework/supra-framework/doc/vesting_without_staking.md index f9d0d9d7f450d..f0280f356953c 100644 --- a/aptos-move/framework/supra-framework/doc/vesting_without_staking.md +++ b/aptos-move/framework/supra-framework/doc/vesting_without_staking.md @@ -21,9 +21,6 @@ Vesting without staking contract - [Constants](#@Constants_0) - [Function `vesting_start_secs`](#0x1_vesting_without_staking_vesting_start_secs) - [Function `period_duration_secs`](#0x1_vesting_without_staking_period_duration_secs) -- [Function `get_withdrawal_addr`](#0x1_vesting_without_staking_get_withdrawal_addr) -- [Function `get_contract_admin`](#0x1_vesting_without_staking_get_contract_admin) -- [Function `get_vesting_record`](#0x1_vesting_without_staking_get_vesting_record) - [Function `remaining_grant`](#0x1_vesting_without_staking_remaining_grant) - [Function `beneficiary`](#0x1_vesting_without_staking_beneficiary) - [Function `vesting_contracts`](#0x1_vesting_without_staking_vesting_contracts) @@ -866,93 +863,6 @@ This errors out if the vesting contract with the provided address doesn't exist. -
- - - -## Function `get_withdrawal_addr` - - - -
#[view]
-public fun get_withdrawal_addr(vesting_contract_addr: address): address
-
- - - -
-Implementation - - -
public fun get_withdrawal_addr(vesting_contract_addr: address): address acquires VestingContract {
-    borrow_global<VestingContract>(vesting_contract_addr).withdrawal_address
-}
-
- - - -
- - - -## Function `get_contract_admin` - - - -
#[view]
-public fun get_contract_admin(vesting_contract_addr: address): address
-
- - - -
-Implementation - - -
public fun get_contract_admin(vesting_contract_addr: address): address acquires VestingContract {
-    borrow_global<VestingContract>(vesting_contract_addr).admin
-}
-
- - - -
- - - -## Function `get_vesting_record` - - - -
#[view]
-public fun get_vesting_record(vesting_contract_address: address, shareholder_address: address): (u64, u64, u64)
-
- - - -
-Implementation - - -
public fun get_vesting_record(
-    vesting_contract_address: address, shareholder_address: address
-): (u64, u64, u64) acquires VestingContract {
-    assert_vesting_contract_exists(vesting_contract_address);
-    let vesting_record =
-        simple_map::borrow(
-            &borrow_global<VestingContract>(vesting_contract_address).shareholders,
-            &shareholder_address
-        );
-    (
-        vesting_record.init_amount,
-        vesting_record.left_amount,
-        vesting_record.last_vested_period
-    )
-}
-
- - -
@@ -972,14 +882,11 @@ Return the remaining grant of shareholder Implementation -
public fun remaining_grant(
-    vesting_contract_address: address, shareholder_address: address
-): u64 acquires VestingContract {
+
public fun remaining_grant(vesting_contract_address: address, shareholder_address: address)
+    : u64 acquires VestingContract {
     assert_vesting_contract_exists(vesting_contract_address);
-    simple_map::borrow(
-        &borrow_global<VestingContract>(vesting_contract_address).shareholders,
-        &shareholder_address
-    ).left_amount
+    simple_map::borrow(&borrow_global<VestingContract>(vesting_contract_address).shareholders,
+        &shareholder_address).left_amount
 }
 
@@ -1007,13 +914,10 @@ This errors out if the vesting contract with the provided address doesn't exist. Implementation -
public fun beneficiary(
-    vesting_contract_address: address, shareholder: address
-): address acquires VestingContract {
+
public fun beneficiary(vesting_contract_address: address, shareholder: address): address acquires VestingContract {
     assert_vesting_contract_exists(vesting_contract_address);
-    get_beneficiary(
-        borrow_global<VestingContract>(vesting_contract_address), shareholder
-    )
+    get_beneficiary(borrow_global<VestingContract>(vesting_contract_address),
+        shareholder)
 }
 
@@ -1076,9 +980,7 @@ This errors out if the vesting contract with the provided address doesn't exist. Implementation -
public fun vesting_schedule(
-    vesting_contract_address: address
-): VestingSchedule acquires VestingContract {
+
public fun vesting_schedule(vesting_contract_address: address): VestingSchedule acquires VestingContract {
     assert_vesting_contract_exists(vesting_contract_address);
     borrow_global<VestingContract>(vesting_contract_address).vesting_schedule
 }
@@ -1105,9 +1007,7 @@ Return the list of all shareholders in the vesting contract.
 Implementation
 
 
-
public fun shareholders(
-    vesting_contract_address: address
-): vector<address> acquires VestingContract {
+
public fun shareholders(vesting_contract_address: address): vector<address> acquires VestingContract {
     assert_active_vesting_contract(vesting_contract_address);
 
     let vesting_contract = borrow_global<VestingContract>(vesting_contract_address);
@@ -1141,9 +1041,8 @@ This returns 0x0 if no shareholder is found for the given beneficiary / the addr
 Implementation
 
 
-
public fun shareholder(
-    vesting_contract_address: address, shareholder_or_beneficiary: address
-): address acquires VestingContract {
+
public fun shareholder(vesting_contract_address: address, shareholder_or_beneficiary: address)
+    : address acquires VestingContract {
     assert_active_vesting_contract(vesting_contract_address);
 
     let shareholders = &shareholders(vesting_contract_address);
@@ -1153,9 +1052,7 @@ This returns 0x0 if no shareholder is found for the given beneficiary / the addr
     let vesting_contract = borrow_global<VestingContract>(vesting_contract_address);
     let result = @0x0;
     let (sh_vec, ben_vec) = simple_map::to_vec_pair(vesting_contract.beneficiaries);
-    let (found, found_index) = vector::index_of(
-        &ben_vec, &shareholder_or_beneficiary
-    );
+    let (found, found_index) = vector::index_of(&ben_vec, &shareholder_or_beneficiary);
     if (found) {
         result = *vector::borrow(&sh_vec, found_index);
     };
@@ -1184,31 +1081,23 @@ Create a vesting schedule with the given schedule of distributions, a vesting st
 
 
 
public fun create_vesting_schedule(
-    schedule: vector<FixedPoint32>,
-    start_timestamp_secs: u64,
-    period_duration: u64
+    schedule: vector<FixedPoint32>, start_timestamp_secs: u64, period_duration: u64,
 ): VestingSchedule {
     let schedule_len = vector::length(&schedule);
-    assert!(schedule_len != 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
+    assert!(schedule_len > 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
     // If the first vesting fraction is zero, we can replace it with nonzero by increasing start time
-    assert!(
-        fixed_point32::get_raw_value(*vector::borrow(&schedule, 0)) != 0,
-        error::invalid_argument(EEMPTY_VESTING_SCHEDULE)
-    );
+    assert!(fixed_point32::get_raw_value(*vector::borrow(&schedule, 0)) != 0,
+        error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
     // last vesting fraction must be non zero to ensure that no amount remains unvested forever.
-    assert!(
-        fixed_point32::get_raw_value(*vector::borrow(&schedule, schedule_len - 1))
-            != 0,
-        error::invalid_argument(EEMPTY_VESTING_SCHEDULE)
-    );
-    assert!(
-        period_duration != 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD)
-    );
+    assert!(fixed_point32::get_raw_value(*vector::borrow(&schedule, schedule_len - 1))
+        != 0,
+        error::invalid_argument(EEMPTY_VESTING_SCHEDULE));
+    assert!(period_duration > 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD));
     VestingSchedule {
         schedule,
         start_timestamp_secs,
         period_duration,
-        last_vested_period: 0
+        last_vested_period: 0,
     }
 }
 
@@ -1232,7 +1121,7 @@ Create a vesting schedule with the given schedule of distributions, a vesting st Implementation -
public entry fun create_vesting_contract_with_amounts(
+
public entry fun create_vesting_contract_with_amounts (
     admin: &signer,
     shareholders: vector<address>,
     shares: vector<u64>,
@@ -1241,106 +1130,82 @@ Create a vesting schedule with the given schedule of distributions, a vesting st
     start_timestamp_secs: u64,
     period_duration: u64,
     withdrawal_address: address,
-    contract_creation_seed: vector<u8>
+    contract_creation_seed: vector<u8>,
 ) acquires AdminStore {
-    assert!(
-        !system_addresses::is_reserved_address(withdrawal_address),
-        error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS)
-    );
+    assert!(!system_addresses::is_reserved_address(withdrawal_address),
+        error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS),);
     assert_account_is_registered_for_supra(withdrawal_address);
-    assert!(
-        vector::length(&shareholders) != 0,
-        error::invalid_argument(ENO_SHAREHOLDERS)
-    );
+    assert!(vector::length(&shareholders) > 0,
+        error::invalid_argument(ENO_SHAREHOLDERS));
     assert!(
         vector::length(&shareholders) == vector::length(&shares),
-        error::invalid_argument(ESHARES_LENGTH_MISMATCH)
+        error::invalid_argument(ESHARES_LENGTH_MISMATCH),
     );
 
     // If this is the first time this admin account has created a vesting contract, initialize the admin store.
     let admin_address = signer::address_of(admin);
     if (!exists<AdminStore>(admin_address)) {
-        move_to(
-            admin,
+        move_to(admin,
             AdminStore {
                 vesting_contracts: vector::empty<address>(),
                 nonce: 0,
-                create_events: new_event_handle<CreateVestingContractEvent>(admin)
-            }
-        );
+                create_events: new_event_handle<CreateVestingContractEvent>(admin),
+            });
     };
 
     // Initialize the vesting contract in a new resource account. This allows the same admin to create multiple
     // pools.
-    let (contract_signer, contract_signer_cap) =
-        create_vesting_contract_account(admin, contract_creation_seed);
+    let (contract_signer, contract_signer_cap) = create_vesting_contract_account(admin,
+        contract_creation_seed);
     let contract_signer_address = signer::address_of(&contract_signer);
-    let schedule = vector::map_ref(
-        &vesting_numerators,
-        |numerator| {
-            let event =
-                fixed_point32::create_from_rational(*numerator, vesting_denominator);
-            event
-        }
-    );
+    let schedule = vector::map_ref(&vesting_numerators, |numerator| {
+        let event = fixed_point32::create_from_rational(*numerator, vesting_denominator);
+        event
+    });
 
-    let vesting_schedule =
-        create_vesting_schedule(schedule, start_timestamp_secs, period_duration);
+    let vesting_schedule = create_vesting_schedule(schedule, start_timestamp_secs, period_duration);
     let shareholders_map = simple_map::create<address, VestingRecord>();
     let grant_amount = 0;
-    vector::for_each_reverse(
-        shares,
-        |amount| {
-            let shareholder = vector::pop_back(&mut shareholders);
-            simple_map::add(
-                &mut shareholders_map,
-                shareholder,
-                VestingRecord {
-                    init_amount: amount,
-                    left_amount: amount,
-                    last_vested_period: vesting_schedule.last_vested_period
-                }
-            );
-            grant_amount = grant_amount + amount;
-        }
-    );
-    assert!(grant_amount != 0, error::invalid_argument(EZERO_GRANT));
+    vector::for_each_reverse(shares, |amount| {
+        let shareholder = vector::pop_back(&mut shareholders);
+        simple_map::add(&mut shareholders_map,
+            shareholder,
+            VestingRecord {
+                init_amount: amount,
+                left_amount: amount,
+                last_vested_period: vesting_schedule.last_vested_period,
+            }
+        );
+        grant_amount = grant_amount + amount;
+    });
+    assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT));
     coin::transfer<SupraCoin>(admin, contract_signer_address, grant_amount);
 
     let admin_store = borrow_global_mut<AdminStore>(admin_address);
     vector::push_back(&mut admin_store.vesting_contracts, contract_signer_address);
-    emit_event(
-        &mut admin_store.create_events,
+    emit_event(&mut admin_store.create_events,
         CreateVestingContractEvent {
             withdrawal_address,
             grant_amount,
-            vesting_contract_address: contract_signer_address
-        }
+            vesting_contract_address: contract_signer_address,
+        },
     );
 
-    move_to(
-        &contract_signer,
+    move_to(&contract_signer,
         VestingContract {
             state: VESTING_POOL_ACTIVE,
             admin: admin_address,
-            shareholders: shareholders_map,
+            shareholders:shareholders_map,
             beneficiaries: simple_map::create<address, address>(),
             vesting_schedule,
             withdrawal_address,
             signer_cap: contract_signer_cap,
-            set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>(
-                &contract_signer
-            ),
+            set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>(&contract_signer),
             vest_events: new_event_handle<VestEvent>(&contract_signer),
             terminate_events: new_event_handle<TerminateEvent>(&contract_signer),
-            admin_withdraw_events: new_event_handle<AdminWithdrawEvent>(
-                &contract_signer
-            ),
-            shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>(
-                &contract_signer
-            )
-        }
-    );
+            admin_withdraw_events: new_event_handle<AdminWithdrawEvent>(&contract_signer),
+            shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>(&contract_signer),
+        });
 }
 
@@ -1369,74 +1234,65 @@ Create a vesting contract with a given configurations. buy_ins: SimpleMap<address, Coin<SupraCoin>>, vesting_schedule: VestingSchedule, withdrawal_address: address, - contract_creation_seed: vector<u8> + contract_creation_seed: vector<u8>, ): address acquires AdminStore { - assert!( - !system_addresses::is_reserved_address(withdrawal_address), - error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS) - ); + assert!(!system_addresses::is_reserved_address(withdrawal_address), + error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS),); assert_account_is_registered_for_supra(withdrawal_address); let shareholders_address = &simple_map::keys(&buy_ins); - assert!( - vector::length(shareholders_address) != 0, - error::invalid_argument(ENO_SHAREHOLDERS) - ); + assert!(vector::length(shareholders_address) > 0, + error::invalid_argument(ENO_SHAREHOLDERS)); let shareholders = simple_map::create<address, VestingRecord>(); let grant = coin::zero<SupraCoin>(); let grant_amount = 0; let (shareholders_address, buy_ins) = simple_map::to_vec_pair(buy_ins); - while (vector::length(&shareholders_address) != 0) { + while (vector::length(&shareholders_address) > 0) { let shareholder = vector::pop_back(&mut shareholders_address); let buy_in = vector::pop_back(&mut buy_ins); let init = coin::value(&buy_in); coin::merge(&mut grant, buy_in); - simple_map::add( - &mut shareholders, + simple_map::add(&mut shareholders, shareholder, VestingRecord { init_amount: init, left_amount: init, - last_vested_period: vesting_schedule.last_vested_period + last_vested_period: vesting_schedule.last_vested_period, } ); grant_amount = grant_amount + init; }; - assert!(grant_amount != 0, error::invalid_argument(EZERO_GRANT)); + assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT)); // If this is the first time this admin account has created a vesting contract, initialize the admin store. let admin_address = signer::address_of(admin); if (!exists<AdminStore>(admin_address)) { - move_to( - admin, + move_to(admin, AdminStore { vesting_contracts: vector::empty<address>(), nonce: 0, - create_events: new_event_handle<CreateVestingContractEvent>(admin) - } - ); + create_events: new_event_handle<CreateVestingContractEvent>(admin), + }); }; // Initialize the vesting contract in a new resource account. This allows the same admin to create multiple // pools. - let (contract_signer, contract_signer_cap) = - create_vesting_contract_account(admin, contract_creation_seed); + let (contract_signer, contract_signer_cap) = create_vesting_contract_account(admin, + contract_creation_seed); let contract_signer_address = signer::address_of(&contract_signer); coin::deposit(contract_signer_address, grant); let admin_store = borrow_global_mut<AdminStore>(admin_address); vector::push_back(&mut admin_store.vesting_contracts, contract_signer_address); - emit_event( - &mut admin_store.create_events, + emit_event(&mut admin_store.create_events, CreateVestingContractEvent { withdrawal_address, grant_amount, - vesting_contract_address: contract_signer_address - } + vesting_contract_address: contract_signer_address, + }, ); - move_to( - &contract_signer, + move_to(&contract_signer, VestingContract { state: VESTING_POOL_ACTIVE, admin: admin_address, @@ -1445,19 +1301,12 @@ Create a vesting contract with a given configurations. vesting_schedule, withdrawal_address, signer_cap: contract_signer_cap, - set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>( - &contract_signer - ), + set_beneficiary_events: new_event_handle<SetBeneficiaryEvent>(&contract_signer), vest_events: new_event_handle<VestEvent>(&contract_signer), terminate_events: new_event_handle<TerminateEvent>(&contract_signer), - admin_withdraw_events: new_event_handle<AdminWithdrawEvent>( - &contract_signer - ), - shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>( - &contract_signer - ) - } - ); + admin_withdraw_events: new_event_handle<AdminWithdrawEvent>(&contract_signer), + shareholder_removed_events: new_event_handle<ShareHolderRemovedEvent>(&contract_signer), + }); vector::destroy_empty(buy_ins); contract_signer_address @@ -1488,11 +1337,10 @@ Unlock any vested portion of the grant. assert_active_vesting_contract(contract_address); let vesting_contract = borrow_global_mut<VestingContract>(contract_address); // Short-circuit if vesting hasn't started yet. - if (vesting_contract.vesting_schedule.start_timestamp_secs - > timestamp::now_seconds()) { return }; + if (vesting_contract.vesting_schedule.start_timestamp_secs > timestamp::now_seconds()) { return }; let shareholders = simple_map::keys(&vesting_contract.shareholders); - while (vector::length(&shareholders) != 0) { + while (vector::length(&shareholders) > 0) { let shareholder = vector::pop_back(&mut shareholders); vest_individual(contract_address, shareholder); }; @@ -1522,22 +1370,16 @@ Unlock any vested portion of the grant. Implementation -
public entry fun vest_individual(
-    contract_address: address, shareholder_address: address
-) acquires VestingContract {
+
public entry fun vest_individual(contract_address: address, shareholder_address: address) acquires VestingContract {
     //check if contract exist, active and shareholder is a member of the contract
     assert_shareholder_exists(contract_address, shareholder_address);
 
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     let beneficiary = get_beneficiary(vesting_contract, shareholder_address);
     // Short-circuit if vesting hasn't started yet.
-    if (vesting_contract.vesting_schedule.start_timestamp_secs
-        > timestamp::now_seconds()) { return };
+    if (vesting_contract.vesting_schedule.start_timestamp_secs > timestamp::now_seconds()) { return };
 
-    let vesting_record =
-        simple_map::borrow_mut(
-            &mut vesting_contract.shareholders, &shareholder_address
-        );
+    let vesting_record = simple_map::borrow_mut(&mut vesting_contract.shareholders, &shareholder_address);
     let signer_cap = &vesting_contract.signer_cap;
 
     // Check if the next vested period has already passed. If not, short-circuit since there's nothing to vest.
@@ -1545,58 +1387,29 @@ Unlock any vested portion of the grant.
     let schedule = &vesting_schedule.schedule;
     let last_vested_period = vesting_record.last_vested_period;
     let next_period_to_vest = last_vested_period + 1;
-    let last_completed_period =
-        (timestamp::now_seconds() - vesting_schedule.start_timestamp_secs)
-            / vesting_schedule.period_duration;
+    let last_completed_period = (timestamp::now_seconds() - vesting_schedule.start_timestamp_secs)
+        / vesting_schedule.period_duration;
 
     // Index is 0-based while period is 1-based so we need to subtract 1.
-
-    while (last_completed_period >= next_period_to_vest && vesting_record.left_amount != 0 && next_period_to_vest <= vector::length(schedule)) {
+    while (last_completed_period >= next_period_to_vest && vesting_record.left_amount > 0) {
         let schedule_index = next_period_to_vest - 1;
-        let vesting_fraction = *vector::borrow(schedule, schedule_index);
-        vest_transfer(vesting_record, signer_cap, beneficiary, vesting_fraction);
-        emit_event(&mut vesting_contract.vest_events,
-            VestEvent {
-                admin: vesting_contract.admin,
-                shareholder_address,
-                vesting_contract_address: contract_address,
-                period_vested: next_period_to_vest
-            }
-        );
-        next_period_to_vest = next_period_to_vest + 1;
-    };
-
-    if(last_completed_period >= next_period_to_vest && vesting_record.left_amount != 0) {
-        let final_fraction = *vector::borrow(schedule, vector::length(schedule) - 1);
-        let final_fraction_amount = fixed_point32::multiply_u64(vesting_record.init_amount, final_fraction);
-        // Determine how many periods is needed based on the left_amount
-        let added_fraction = fixed_point32::multiply_u64_return_fixpoint32(last_completed_period - next_period_to_vest + 1, final_fraction);
-        // If the added_fraction is greater than or equal to the left_amount, then we can vest all the left_amount
-        let periods_need =
-            if (fixed_point32::multiply_u64(vesting_record.init_amount, added_fraction) >= vesting_record.left_amount){
-            let result =  vesting_record.left_amount / final_fraction_amount;
-                // check if `left_amount` is perfectly divisible by `final_fraction_amount`
-                  if (vesting_record.left_amount == final_fraction_amount*result) {
-                   result
-                } else {
-                   result + 1
-                }
+        let vesting_fraction = if (schedule_index < vector::length(schedule)) {
+            *vector::borrow(schedule, schedule_index)
         } else {
-            last_completed_period - next_period_to_vest + 1
+            // Last vesting schedule fraction will repeat until the grant runs out.
+            *vector::borrow(schedule, vector::length(schedule) - 1)
         };
+        vest_transfer(vesting_record, signer_cap, beneficiary, vesting_fraction);
 
-        let total_fraction = fixed_point32::multiply_u64_return_fixpoint32(periods_need, final_fraction);
-        // We don't need to check vesting_record.left_amount > 0 because vest_transfer will handle that.
-        vest_transfer(vesting_record, signer_cap, beneficiary, total_fraction);
-        next_period_to_vest = next_period_to_vest + periods_need;
         emit_event(&mut vesting_contract.vest_events,
             VestEvent {
                 admin: vesting_contract.admin,
-                shareholder_address,
+                shareholder_address: shareholder_address,
                 vesting_contract_address: contract_address,
                 period_vested: next_period_to_vest,
             },
         );
+        next_period_to_vest = next_period_to_vest + 1;
     };
 
     //update last_vested_period for the shareholder
@@ -1632,13 +1445,8 @@ Unlock any vested portion of the grant.
     let vesting_signer = account::create_signer_with_capability(signer_cap);
 
     //amount to be transfer is minimum of what is left and vesting fraction due of init_amount
-    let amount =
-        min(
-            vesting_record.left_amount,
-            fixed_point32::multiply_u64(
-                vesting_record.init_amount, vesting_fraction
-            )
-        );
+    let amount = min(vesting_record.left_amount,
+        fixed_point32::multiply_u64(vesting_record.init_amount, vesting_fraction));
     //update left_amount for the shareholder
     vesting_record.left_amount = vesting_record.left_amount - amount;
     coin::transfer<SupraCoin>(&vesting_signer, beneficiary, amount);
@@ -1673,43 +1481,38 @@ Example usage: If admin find shareholder suspicious, admin can remove it.
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
     let vesting_signer = get_vesting_account_signer_internal(vesting_contract);
-    let shareholder_amount =
-        simple_map::borrow(&vesting_contract.shareholders, &shareholder_address).left_amount;
-    coin::transfer<SupraCoin>(
-        &vesting_signer, vesting_contract.withdrawal_address, shareholder_amount
-    );
-    emit_event(
-        &mut vesting_contract.admin_withdraw_events,
+    let shareholder_amount = simple_map::borrow(&vesting_contract.shareholders, &shareholder_address)
+        .left_amount;
+    coin::transfer<SupraCoin>(&vesting_signer, vesting_contract.withdrawal_address,
+        shareholder_amount);
+    emit_event(&mut vesting_contract.admin_withdraw_events,
         AdminWithdrawEvent {
             admin: vesting_contract.admin,
             vesting_contract_address: contract_address,
-            amount: shareholder_amount
-        }
+            amount: shareholder_amount,
+        },
     );
 
     // remove `shareholder_address`` from `vesting_contract.shareholders`
     let shareholders = &mut vesting_contract.shareholders;
-    let (_, shareholders_vesting) =
-        simple_map::remove(shareholders, &shareholder_address);
+    let (_, shareholders_vesting) = simple_map::remove(shareholders, &shareholder_address);
 
     // remove `shareholder_address` from `vesting_contract.beneficiaries`
     let beneficiary = option::none();
     let shareholder_beneficiaries = &mut vesting_contract.beneficiaries;
     // Not all shareholders have their beneficiaries, so before removing them, we need to check if the beneficiary exists
     if (simple_map::contains_key(shareholder_beneficiaries, &shareholder_address)) {
-        let (_, shareholder_baneficiary) =
-            simple_map::remove(shareholder_beneficiaries, &shareholder_address);
+        let (_, shareholder_baneficiary) = simple_map::remove(shareholder_beneficiaries, &shareholder_address);
         beneficiary = option::some(shareholder_baneficiary);
     };
 
     // Emit ShareHolderRemovedEvent
-    emit_event(
-        &mut vesting_contract.shareholder_removed_events,
+    emit_event(&mut vesting_contract.shareholder_removed_events,
         ShareHolderRemovedEvent {
             shareholder: shareholder_address,
             beneficiary,
-            amount: shareholders_vesting.left_amount
-        }
+            amount: shareholders_vesting.left_amount,
+        },
     );
 }
 
@@ -1734,9 +1537,7 @@ Terminate the vesting contract and send all funds back to the withdrawal address Implementation -
public entry fun terminate_vesting_contract(
-    admin: &signer, contract_address: address
-) acquires VestingContract {
+
public entry fun terminate_vesting_contract(admin: &signer, contract_address: address) acquires VestingContract {
     assert_active_vesting_contract(contract_address);
 
     vest(contract_address);
@@ -1746,16 +1547,12 @@ Terminate the vesting contract and send all funds back to the withdrawal address
 
     // Distribute remaining coins to withdrawal address of vesting contract.
     let shareholders_address = simple_map::keys(&vesting_contract.shareholders);
-    vector::for_each_ref(
-        &shareholders_address,
+    vector::for_each_ref(&shareholders_address,
         |shareholder| {
-            let shareholder_amount =
-                simple_map::borrow_mut(
-                    &mut vesting_contract.shareholders, shareholder
-                );
+            let shareholder_amount = simple_map::borrow_mut(&mut vesting_contract.shareholders,
+                shareholder);
             shareholder_amount.left_amount = 0;
-        }
-    );
+        });
     set_terminate_vesting_contract(contract_address);
 }
 
@@ -1781,30 +1578,24 @@ has already been terminated. Implementation -
public entry fun admin_withdraw(
-    admin: &signer, contract_address: address
-) acquires VestingContract {
+
public entry fun admin_withdraw(admin: &signer, contract_address: address) acquires VestingContract {
     let vesting_contract = borrow_global<VestingContract>(contract_address);
-    assert!(
-        vesting_contract.state == VESTING_POOL_TERMINATED,
-        error::invalid_state(EVESTING_CONTRACT_STILL_ACTIVE)
-    );
+    assert!(vesting_contract.state == VESTING_POOL_TERMINATED,
+        error::invalid_state(EVESTING_CONTRACT_STILL_ACTIVE));
 
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
     let total_balance = coin::balance<SupraCoin>(contract_address);
     let vesting_signer = get_vesting_account_signer_internal(vesting_contract);
-    coin::transfer<SupraCoin>(
-        &vesting_signer, vesting_contract.withdrawal_address, total_balance
-    );
+    coin::transfer<SupraCoin>(&vesting_signer, vesting_contract.withdrawal_address,
+        total_balance);
 
-    emit_event(
-        &mut vesting_contract.admin_withdraw_events,
+    emit_event(&mut vesting_contract.admin_withdraw_events,
         AdminWithdrawEvent {
             admin: vesting_contract.admin,
             vesting_contract_address: contract_address,
-            amount: total_balance
-        }
+            amount: total_balance,
+        },
     );
 }
 
@@ -1832,7 +1623,7 @@ has already been terminated. admin: &signer, contract_address: address, shareholder: address, - new_beneficiary: address + new_beneficiary: address, ) acquires VestingContract { // Verify that the beneficiary account is set up to receive SUPRA. This is a requirement so distribute() wouldn't // fail and block all other accounts from receiving SUPRA if one beneficiary is not registered. @@ -1845,15 +1636,14 @@ has already been terminated. let beneficiaries = &mut vesting_contract.beneficiaries; simple_map::upsert(beneficiaries, shareholder, new_beneficiary); - emit_event( - &mut vesting_contract.set_beneficiary_events, + emit_event(&mut vesting_contract.set_beneficiary_events, SetBeneficiaryEvent { admin: vesting_contract.admin, vesting_contract_address: contract_address, shareholder, old_beneficiary, - new_beneficiary - } + new_beneficiary, + }, ); }
@@ -1880,20 +1670,13 @@ account.
public entry fun reset_beneficiary(
-    account: &signer,
-    contract_address: address,
-    shareholder: address
+    account: &signer, contract_address: address, shareholder: address,
 ) acquires VestingAccountManagement, VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     let addr = signer::address_of(account);
-    assert!(
-        addr == vesting_contract.admin
-            || addr
-                == get_role_holder(
-                    contract_address, utf8(ROLE_BENEFICIARY_RESETTER)
-                ),
-        error::permission_denied(EPERMISSION_DENIED)
-    );
+    assert!(addr == vesting_contract.admin || addr == get_role_holder(contract_address,
+            utf8(ROLE_BENEFICIARY_RESETTER)),
+        error::permission_denied(EPERMISSION_DENIED),);
 
     let beneficiaries = &mut vesting_contract.beneficiaries;
     if (simple_map::contains_key(beneficiaries, &shareholder)) {
@@ -1925,22 +1708,17 @@ account.
     admin: &signer,
     contract_address: address,
     role: String,
-    role_holder: address
+    role_holder: address,
 ) acquires VestingAccountManagement, VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
 
     if (!exists<VestingAccountManagement>(contract_address)) {
         let contract_signer = &get_vesting_account_signer_internal(vesting_contract);
-        move_to(
-            contract_signer,
-            VestingAccountManagement {
-                roles: simple_map::create<String, address>()
-            }
-        )
+        move_to(contract_signer,
+            VestingAccountManagement { roles: simple_map::create<String, address>(), })
     };
-    let roles =
-        &mut borrow_global_mut<VestingAccountManagement>(contract_address).roles;
+    let roles = &mut borrow_global_mut<VestingAccountManagement>(contract_address).roles;
     simple_map::upsert(roles, role, role_holder);
 }
 
@@ -1965,16 +1743,10 @@ account.
public entry fun set_beneficiary_resetter(
-    admin: &signer,
-    contract_address: address,
-    beneficiary_resetter: address
+    admin: &signer, contract_address: address, beneficiary_resetter: address,
 ) acquires VestingAccountManagement, VestingContract {
-    set_management_role(
-        admin,
-        contract_address,
-        utf8(ROLE_BENEFICIARY_RESETTER),
-        beneficiary_resetter
-    );
+    set_management_role(admin, contract_address, utf8(ROLE_BENEFICIARY_RESETTER),
+        beneficiary_resetter);
 }
 
@@ -1997,17 +1769,11 @@ account. Implementation -
public fun get_role_holder(
-    contract_address: address, role: String
-): address acquires VestingAccountManagement {
-    assert!(
-        exists<VestingAccountManagement>(contract_address),
-        error::not_found(EVESTING_ACCOUNT_HAS_NO_ROLES)
-    );
+
public fun get_role_holder(contract_address: address, role: String): address acquires VestingAccountManagement {
+    assert!(exists<VestingAccountManagement>(contract_address),
+        error::not_found(EVESTING_ACCOUNT_HAS_NO_ROLES));
     let roles = &borrow_global<VestingAccountManagement>(contract_address).roles;
-    assert!(
-        simple_map::contains_key(roles, &role), error::not_found(EROLE_NOT_FOUND)
-    );
+    assert!(simple_map::contains_key(roles, &role), error::not_found(EROLE_NOT_FOUND));
     *simple_map::borrow(roles, &role)
 }
 
@@ -2032,9 +1798,7 @@ For emergency use in case the admin needs emergency control of vesting contract Implementation -
public fun get_vesting_account_signer(
-    admin: &signer, contract_address: address
-): signer acquires VestingContract {
+
public fun get_vesting_account_signer(admin: &signer, contract_address: address): signer acquires VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     verify_admin(admin, vesting_contract);
     get_vesting_account_signer_internal(vesting_contract)
@@ -2060,9 +1824,7 @@ For emergency use in case the admin needs emergency control of vesting contract
 Implementation
 
 
-
fun get_vesting_account_signer_internal(
-    vesting_contract: &VestingContract
-): signer {
+
fun get_vesting_account_signer_internal(vesting_contract: &VestingContract): signer {
     account::create_signer_with_capability(&vesting_contract.signer_cap)
 }
 
@@ -2088,9 +1850,8 @@ This address should be deterministic for the same admin and vesting contract cre Implementation -
fun create_vesting_contract_account(
-    admin: &signer, contract_creation_seed: vector<u8>
-): (signer, SignerCapability) acquires AdminStore {
+
fun create_vesting_contract_account(admin: &signer, contract_creation_seed: vector<u8>,)
+    : (signer, SignerCapability) acquires AdminStore {
     let admin_store = borrow_global_mut<AdminStore>(signer::address_of(admin));
     let seed = bcs::to_bytes(&signer::address_of(admin));
     vector::append(&mut seed, bcs::to_bytes(&admin_store.nonce));
@@ -2129,10 +1890,8 @@ This address should be deterministic for the same admin and vesting contract cre
 
 
 
fun verify_admin(admin: &signer, vesting_contract: &VestingContract) {
-    assert!(
-        signer::address_of(admin) == vesting_contract.admin,
-        error::unauthenticated(ENOT_ADMIN)
-    );
+    assert!(signer::address_of(admin) == vesting_contract.admin,
+        error::unauthenticated(ENOT_ADMIN));
 }
 
@@ -2156,10 +1915,8 @@ This address should be deterministic for the same admin and vesting contract cre
fun assert_vesting_contract_exists(contract_address: address) {
-    assert!(
-        exists<VestingContract>(contract_address),
-        error::not_found(EVESTING_CONTRACT_NOT_FOUND)
-    );
+    assert!(exists<VestingContract>(contract_address),
+        error::not_found(EVESTING_CONTRACT_NOT_FOUND));
 }
 
@@ -2182,17 +1939,11 @@ This address should be deterministic for the same admin and vesting contract cre Implementation -
fun assert_shareholder_exists(
-    contract_address: address, shareholder_address: address
-) acquires VestingContract {
+
fun assert_shareholder_exists(contract_address: address, shareholder_address: address) acquires VestingContract {
     assert_active_vesting_contract(contract_address);
-    assert!(
-        simple_map::contains_key(
-            &borrow_global<VestingContract>(contract_address).shareholders,
-            &shareholder_address
-        ),
-        error::not_found(ESHAREHOLDER_NOT_EXIST)
-    );
+    assert!(simple_map::contains_key(&borrow_global<VestingContract>(contract_address)
+                .shareholders, &shareholder_address),
+        error::not_found(ESHAREHOLDER_NOT_EXIST));
 }
 
@@ -2218,10 +1969,8 @@ This address should be deterministic for the same admin and vesting contract cre
fun assert_active_vesting_contract(contract_address: address) acquires VestingContract {
     assert_vesting_contract_exists(contract_address);
     let vesting_contract = borrow_global<VestingContract>(contract_address);
-    assert!(
-        vesting_contract.state == VESTING_POOL_ACTIVE,
-        error::invalid_state(EVESTING_CONTRACT_NOT_ACTIVE)
-    );
+    assert!(vesting_contract.state == VESTING_POOL_ACTIVE,
+        error::invalid_state(EVESTING_CONTRACT_NOT_ACTIVE));
 }
 
@@ -2247,9 +1996,7 @@ This address should be deterministic for the same admin and vesting contract cre
fun get_beneficiary(contract: &VestingContract, shareholder: address): address {
     if (simple_map::contains_key(&contract.beneficiaries, &shareholder)) {
         *simple_map::borrow(&contract.beneficiaries, &shareholder)
-    } else {
-        shareholder
-    }
+    } else { shareholder }
 }
 
@@ -2275,12 +2022,11 @@ This address should be deterministic for the same admin and vesting contract cre
fun set_terminate_vesting_contract(contract_address: address) acquires VestingContract {
     let vesting_contract = borrow_global_mut<VestingContract>(contract_address);
     vesting_contract.state = VESTING_POOL_TERMINATED;
-    emit_event(
-        &mut vesting_contract.terminate_events,
+    emit_event(&mut vesting_contract.terminate_events,
         TerminateEvent {
             admin: vesting_contract.admin,
-            vesting_contract_address: contract_address
-        }
+            vesting_contract_address: contract_address,
+        },
     );
 }
 
diff --git a/aptos-move/framework/supra-framework/doc/voting.md b/aptos-move/framework/supra-framework/doc/voting.md index 23e2abc208d09..30ed0a483d8ad 100644 --- a/aptos-move/framework/supra-framework/doc/voting.md +++ b/aptos-move/framework/supra-framework/doc/voting.md @@ -934,8 +934,8 @@ resolve this proposal. error::invalid_argument(EINVALID_MIN_VOTE_THRESHOLD), ); }; - // Make sure the execution script's hash is not empty. - assert!(vector::length(&execution_hash) != 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); + // Make sure the execution script's hash is not empty. + assert!(vector::length(&execution_hash) > 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); let voting_forum = borrow_global_mut<VotingForum<ProposalType>>(voting_forum_address); let proposal_id = voting_forum.next_proposal_id; @@ -1266,7 +1266,7 @@ there are more yes votes than no. If either of these conditions is not met, this }; } else { // If the current step is not the last step, - // update the proposal's execution hash on-chain to the execution hash of the next step. + // update the proposal's execution hash on-chain to the execution hash of the next step. proposal.execution_hash = next_execution_hash; }; From 5c6b872e3940fc0be273ba3d3b396b1413f29a5f Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Tue, 25 Feb 2025 18:11:12 +0100 Subject: [PATCH 11/12] derive evm chain id from move chainid --- aptos-move/vm-genesis/src/lib.rs | 13 +++++-------- crates/aptos-genesis/src/lib.rs | 1 - types/src/on_chain_config/evm_config.rs | 16 +++++++++------- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/aptos-move/vm-genesis/src/lib.rs b/aptos-move/vm-genesis/src/lib.rs index 8f1f227a159b6..1eb1f92f5fff1 100644 --- a/aptos-move/vm-genesis/src/lib.rs +++ b/aptos-move/vm-genesis/src/lib.rs @@ -155,7 +155,8 @@ pub fn encode_supra_mainnet_genesis_transaction( let consensus_config = OnChainConsensusConfig::default_for_genesis(); let execution_config = OnChainExecutionConfig::default_for_genesis(); let gas_schedule = default_gas_schedule(); - let evm_config = OnChainEvmConfig::default_for_mainnet(); + // Derive the EVM config from the chain ID. + let evm_config = OnChainEvmConfig::new_v1(chain_id); initialize( &mut session, chain_id, @@ -248,7 +249,6 @@ pub fn encode_genesis_transaction_for_testnet( execution_config: &OnChainExecutionConfig, gas_schedule: &GasScheduleV2, supra_config_bytes: Vec, - evm_config: &OnChainEvmConfig, ) -> Transaction { Transaction::GenesisTransaction(WriteSetPayload::Direct( encode_genesis_change_set_for_testnet( @@ -268,7 +268,6 @@ pub fn encode_genesis_transaction_for_testnet( execution_config, gas_schedule, supra_config_bytes, - evm_config, ), )) } @@ -290,10 +289,10 @@ pub fn encode_genesis_change_set_for_testnet( execution_config: &OnChainExecutionConfig, gas_schedule: &GasScheduleV2, supra_config_bytes: Vec, - evm_config: &OnChainEvmConfig, ) -> ChangeSet { validate_genesis_config(genesis_config); - + // Derive the EVM config from the chain ID. + let evm_config = OnChainEvmConfig::new_v1(chain_id); // Create a Move VM session so we can invoke on-chain genesis initializations. let mut state_view = GenesisStateView::new(); for (module_bytes, module) in framework.code_and_compiled_modules() { @@ -313,7 +312,7 @@ pub fn encode_genesis_change_set_for_testnet( execution_config, gas_schedule, supra_config_bytes, - evm_config, + &evm_config, ); initialize_features( &mut session, @@ -1211,7 +1210,6 @@ pub fn generate_test_genesis( &OnChainExecutionConfig::default_for_genesis(), &default_gas_schedule(), b"test".to_vec(), - &OnChainEvmConfig::default_for_test(), ); (genesis, test_validators) } @@ -1242,7 +1240,6 @@ pub fn generate_mainnet_genesis( &OnChainExecutionConfig::default_for_genesis(), &default_gas_schedule(), b"test".to_vec(), - &OnChainEvmConfig::default_for_test(), ); (genesis, test_validators) } diff --git a/crates/aptos-genesis/src/lib.rs b/crates/aptos-genesis/src/lib.rs index a204189749536..97e380342bfd4 100644 --- a/crates/aptos-genesis/src/lib.rs +++ b/crates/aptos-genesis/src/lib.rs @@ -168,7 +168,6 @@ impl GenesisInfo { &self.execution_config, &self.gas_schedule, b"test".to_vec(), - &OnChainEvmConfig::default_for_test(), ) } diff --git a/types/src/on_chain_config/evm_config.rs b/types/src/on_chain_config/evm_config.rs index 09eed9148682d..f26e197c6be66 100644 --- a/types/src/on_chain_config/evm_config.rs +++ b/types/src/on_chain_config/evm_config.rs @@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize}; use anyhow::{Result, anyhow}; +use crate::chain_id::ChainId; + use super::OnChainConfig; #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] @@ -16,13 +18,13 @@ pub struct EvmConfigV1 { } impl OnChainEvmConfig { - /// TODO: remove, and allow config from genesis parameter. - pub fn default_for_test() -> Self { - Self::V1(EvmConfigV1 { chain_id: 0x12_3456_7890 }) - } - /// TODO: remove, and allow config from genesis parameter. - pub fn default_for_mainnet() -> Self { - Self::V1(EvmConfigV1 { chain_id: 0xffff_aaaa_eeee }) + /// Create a new EvmConfigV1 with the given move chain_id. + /// The EVM chain_id is derived from the move chain_id. + /// `evm_chain_id = move_chain_id << 32 | move_chain_id << 16 | move_chain_id` + pub fn new_v1(chain_id: ChainId) -> Self { + let chain_id = chain_id.id() as u64; + let chain_id = chain_id << 32 | chain_id << 16 | chain_id; + Self::V1(EvmConfigV1 { chain_id }) } } From 5fa093a6da4bffd303d8deb9d2bf822e6a214ac9 Mon Sep 17 00:00:00 2001 From: Simon Chen Date: Wed, 26 Feb 2025 15:29:53 +0100 Subject: [PATCH 12/12] get chainid method --- types/src/on_chain_config/evm_config.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/src/on_chain_config/evm_config.rs b/types/src/on_chain_config/evm_config.rs index f26e197c6be66..ff464c4113431 100644 --- a/types/src/on_chain_config/evm_config.rs +++ b/types/src/on_chain_config/evm_config.rs @@ -26,6 +26,12 @@ impl OnChainEvmConfig { let chain_id = chain_id << 32 | chain_id << 16 | chain_id; Self::V1(EvmConfigV1 { chain_id }) } + + pub fn chain_id(&self) -> u64 { + match self { + Self::V1(config) => config.chain_id, + } + } }