diff --git a/.gitattributes b/.gitattributes index 8b137891..3e86637f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ - +# Best-effort syntax highlighting for Move: just use Rust highlighter +*.move linguist-language=Rust diff --git a/.github/workflows/build_test.yml b/.github/workflows/build_test.yml index 0dd9e67d..d3cb8f47 100644 --- a/.github/workflows/build_test.yml +++ b/.github/workflows/build_test.yml @@ -3,7 +3,6 @@ on: pull_request: branches: - main - - genesis_dao jobs: build-and-test: @@ -21,7 +20,7 @@ jobs: profile: minimal - name: setup environment run: | - bash scripts/dev_setup.sh -b -t -y -p + bash scripts/dev_setup.sh -b -t -y -p - name: test run: | source "$HOME/.profile" @@ -29,7 +28,7 @@ jobs: - name: integration test run: | source "$HOME/.profile" - mpm integration-test --current-as-stdlib + mpm integration-test - name: move-prover-test run: | source "$HOME/.profile" @@ -40,4 +39,4 @@ jobs: source "$HOME/.profile" bash ./scripts/build.sh - name: check changed files - run: bash ./scripts/changed_files.sh + run: bash ./scripts/changed_files.sh \ No newline at end of file diff --git a/.gitignore b/.gitignore index 7716a27e..aa6aa3ab 100644 --- a/.gitignore +++ b/.gitignore @@ -42,7 +42,6 @@ packages-microsoft-prod.deb # Move Build Output sources build/StarcoinFramework/sources/*.move -StarcoinFramework build/UnitTest # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries diff --git a/.starcoin-ide/config b/.starcoin-ide/config deleted file mode 100644 index 82c22df2..00000000 --- a/.starcoin-ide/config +++ /dev/null @@ -1,5 +0,0 @@ -[mpm.package.build] -OPTIONS=["--doc", "--abi", "--force"] - -[mpm.integration-test] -OPTIONS=["--current-as-stdlib"] \ No newline at end of file diff --git a/README.md b/README.md index ad544359..c2501b63 100644 --- a/README.md +++ b/README.md @@ -12,20 +12,6 @@ - [latest](./build/StarcoinFramework/docs) - [v11](./release/v11/docs) -## Usage - -Add `address` and `dependency` to the project's Move.toml - -``` -[addresses] -StarcoinFramework = "0x1" - -[dependencies] -StarcoinFramework = {git = "https://github.com/starcoinorg/starcoin-framework.git", rev="cf1deda180af40a8b3e26c0c7b548c4c290cd7e7"} -``` - -* v11 git version: cf1deda180af40a8b3e26c0c7b548c4c290cd7e7 - ## Build and Test Setup dev environment: @@ -72,11 +58,11 @@ Contributions in the following are welcome: 1. Add New Move module to `sources` dir, such as `MyModule.move`. 2. Write Move code and add unit test in the module file. -3. Add an integration test to [integration-tests](./integration-tests) dir, such as: `test_my_module.move`. +3. Add an integration test to [integration-tests](../integration-tests) dir, such as: `test_my_module.move`. 4. Run the integration test `mpm integration-test test_my_module.move `. 5. Run script `./script/build.sh` for build and generate documents. 6. Commit the changes and create a pull request. -If you are not sure that the module belongs to starcoin-framework, please submit it to [move-funs](https://github.com/movefuns/movefuns) first. +If you are not sure that the module belongs to starcoin-framework, please submit it to [starcoin-framework-commons](https://github.com/starcoinorg/starcoin-framework-commons) first. You can view our [Code of Conduct](./CODE_OF_CONDUCT.md). diff --git a/release/v12/BuildInfo.yaml b/build/StarcoinFramework/BuildInfo.yaml similarity index 75% rename from release/v12/BuildInfo.yaml rename to build/StarcoinFramework/BuildInfo.yaml index 6c1f4789..78e85dbd 100644 --- a/release/v12/BuildInfo.yaml +++ b/build/StarcoinFramework/BuildInfo.yaml @@ -6,18 +6,12 @@ compiled_package_info: StarcoinFramework: "0x00000000000000000000000000000001" VMReserved: "0x00000000000000000000000000000000" module_resolution_metadata: - ? address: "0x00000000000000000000000000000001" - name: ASCII - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Account : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: AccountScripts : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: AnyMemberPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Arith : StarcoinFramework @@ -51,9 +45,6 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: Config : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: ConfigProposalPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: ConsensusConfig : StarcoinFramework @@ -63,21 +54,6 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: CoreAddresses : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: DAOAccount - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: DAOExtensionPoint - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: DAOPluginMarketplace - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: DAORegistry - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: DAOSpace - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Dao : StarcoinFramework @@ -108,18 +84,9 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: Event : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: EventUtil - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: FixedPoint32 : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: GasOracle - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: GasOracleProposalPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Genesis : StarcoinFramework @@ -132,9 +99,6 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: GenesisSignerCapability : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: GrantProposalPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Hash : StarcoinFramework @@ -144,18 +108,12 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: IdentifierNFTScripts : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: InstallPluginProposalPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: LanguageVersion : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Math : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: MemberProposalPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: MerkleNFTDistributor : StarcoinFramework @@ -165,9 +123,6 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: MintDaoProposal : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: MintProposalPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: MintScripts : StarcoinFramework @@ -195,9 +150,6 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: OnChainConfigScripts : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: OnChainStarcoinDAOConfig - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Option : StarcoinFramework @@ -219,12 +171,6 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: RewardConfig : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: Ring - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: SBTVoteStrategy - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: SIP_2 : StarcoinFramework @@ -249,27 +195,9 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: Signer : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: SimpleMap - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: SnapshotUtil - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: StakeToSBTPlugin - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: StarcoinDAO - : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: StarcoinVerifier - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: StdlibUpgradeScripts : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: StructuredHash - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: Timestamp : StarcoinFramework @@ -297,27 +225,18 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: Treasury : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: TreasuryPlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: TreasuryScripts : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: TreasuryWithdrawDaoProposal : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: TypeInfo - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: U256 : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: UpgradeModuleDaoProposal : StarcoinFramework - ? address: "0x00000000000000000000000000000001" - name: UpgradeModulePlugin - : StarcoinFramework ? address: "0x00000000000000000000000000000001" name: VMConfig : StarcoinFramework @@ -333,7 +252,7 @@ compiled_package_info: ? address: "0x00000000000000000000000000000001" name: YieldFarmingV2 : StarcoinFramework - source_digest: E90F2F8FC8A933897A28C415C88680705ED69370B7BE7AE1025E9CE037CE07FC + source_digest: DC688BF938B40FD9B3D5BE2F97C93640AC08F67382227622875406514244667D build_flags: dev_mode: false test_mode: false diff --git a/build/StarcoinFramework/abis/Genesis/initialize.abi b/build/StarcoinFramework/abis/Genesis/initialize.abi index 6ec0ef0c..a2f881ae 100644 Binary files a/build/StarcoinFramework/abis/Genesis/initialize.abi and b/build/StarcoinFramework/abis/Genesis/initialize.abi differ diff --git a/build/StarcoinFramework/abis/Offer/take_offer.abi b/build/StarcoinFramework/abis/Offer/take_offer.abi index d601d280..a9ad0fa8 100644 Binary files a/build/StarcoinFramework/abis/Offer/take_offer.abi and b/build/StarcoinFramework/abis/Offer/take_offer.abi differ diff --git a/build/StarcoinFramework/abis/StdlibUpgradeScripts/upgrade_from_v11_to_v12.abi b/build/StarcoinFramework/abis/StdlibUpgradeScripts/upgrade_from_v11_to_v12.abi deleted file mode 100644 index 4e6f60b3..00000000 Binary files a/build/StarcoinFramework/abis/StdlibUpgradeScripts/upgrade_from_v11_to_v12.abi and /dev/null differ diff --git a/build/StarcoinFramework/bytecode_modules/Account.mv b/build/StarcoinFramework/bytecode_modules/Account.mv index 4e1d4368..35c1be98 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Account.mv and b/build/StarcoinFramework/bytecode_modules/Account.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/AccountScripts.mv b/build/StarcoinFramework/bytecode_modules/AccountScripts.mv index 4f709474..f2f9121c 100644 Binary files a/build/StarcoinFramework/bytecode_modules/AccountScripts.mv and b/build/StarcoinFramework/bytecode_modules/AccountScripts.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Authenticator.mv b/build/StarcoinFramework/bytecode_modules/Authenticator.mv index 9626d9c1..2c4afcf2 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Authenticator.mv and b/build/StarcoinFramework/bytecode_modules/Authenticator.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/BCS.mv b/build/StarcoinFramework/bytecode_modules/BCS.mv index 83ccc945..262389f2 100644 Binary files a/build/StarcoinFramework/bytecode_modules/BCS.mv and b/build/StarcoinFramework/bytecode_modules/BCS.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Block.mv b/build/StarcoinFramework/bytecode_modules/Block.mv index a7fdecd2..c6049e5e 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Block.mv and b/build/StarcoinFramework/bytecode_modules/Block.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/BlockReward.mv b/build/StarcoinFramework/bytecode_modules/BlockReward.mv index e7027b75..eb9ba50f 100644 Binary files a/build/StarcoinFramework/bytecode_modules/BlockReward.mv and b/build/StarcoinFramework/bytecode_modules/BlockReward.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Compare.mv b/build/StarcoinFramework/bytecode_modules/Compare.mv index 9fc383b4..670997b1 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Compare.mv and b/build/StarcoinFramework/bytecode_modules/Compare.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/EVMAddress.mv b/build/StarcoinFramework/bytecode_modules/EVMAddress.mv index 5d447d73..b1f33ef7 100644 Binary files a/build/StarcoinFramework/bytecode_modules/EVMAddress.mv and b/build/StarcoinFramework/bytecode_modules/EVMAddress.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Event.mv b/build/StarcoinFramework/bytecode_modules/Event.mv index cfcb7069..95c907ad 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Event.mv and b/build/StarcoinFramework/bytecode_modules/Event.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Genesis.mv b/build/StarcoinFramework/bytecode_modules/Genesis.mv index 67dd4287..ac1c22e9 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Genesis.mv and b/build/StarcoinFramework/bytecode_modules/Genesis.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/GenesisNFT.mv b/build/StarcoinFramework/bytecode_modules/GenesisNFT.mv index 48c1bbde..76dd0b7a 100644 Binary files a/build/StarcoinFramework/bytecode_modules/GenesisNFT.mv and b/build/StarcoinFramework/bytecode_modules/GenesisNFT.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/GenesisNFTScripts.mv b/build/StarcoinFramework/bytecode_modules/GenesisNFTScripts.mv index 3aa46b0b..7ee755dd 100644 Binary files a/build/StarcoinFramework/bytecode_modules/GenesisNFTScripts.mv and b/build/StarcoinFramework/bytecode_modules/GenesisNFTScripts.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/GenesisSignerCapability.mv b/build/StarcoinFramework/bytecode_modules/GenesisSignerCapability.mv index 8f2da435..d2321ed4 100644 Binary files a/build/StarcoinFramework/bytecode_modules/GenesisSignerCapability.mv and b/build/StarcoinFramework/bytecode_modules/GenesisSignerCapability.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/IdentifierNFT.mv b/build/StarcoinFramework/bytecode_modules/IdentifierNFT.mv index 816454d7..4965211c 100644 Binary files a/build/StarcoinFramework/bytecode_modules/IdentifierNFT.mv and b/build/StarcoinFramework/bytecode_modules/IdentifierNFT.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/IdentifierNFTScripts.mv b/build/StarcoinFramework/bytecode_modules/IdentifierNFTScripts.mv index 23ca97d3..5a4879c7 100644 Binary files a/build/StarcoinFramework/bytecode_modules/IdentifierNFTScripts.mv and b/build/StarcoinFramework/bytecode_modules/IdentifierNFTScripts.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/InstallPluginProposalPlugin.mv b/build/StarcoinFramework/bytecode_modules/InstallPluginProposalPlugin.mv deleted file mode 100644 index 511e0a87..00000000 Binary files a/build/StarcoinFramework/bytecode_modules/InstallPluginProposalPlugin.mv and /dev/null differ diff --git a/build/StarcoinFramework/bytecode_modules/MemberProposalPlugin.mv b/build/StarcoinFramework/bytecode_modules/MemberProposalPlugin.mv deleted file mode 100644 index 3e83c189..00000000 Binary files a/build/StarcoinFramework/bytecode_modules/MemberProposalPlugin.mv and /dev/null differ diff --git a/build/StarcoinFramework/bytecode_modules/MerkleNFTDistributor.mv b/build/StarcoinFramework/bytecode_modules/MerkleNFTDistributor.mv index c37a0416..c384493f 100644 Binary files a/build/StarcoinFramework/bytecode_modules/MerkleNFTDistributor.mv and b/build/StarcoinFramework/bytecode_modules/MerkleNFTDistributor.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/ModifyDaoConfigProposal.mv b/build/StarcoinFramework/bytecode_modules/ModifyDaoConfigProposal.mv index 5c00c614..5f2ff88a 100644 Binary files a/build/StarcoinFramework/bytecode_modules/ModifyDaoConfigProposal.mv and b/build/StarcoinFramework/bytecode_modules/ModifyDaoConfigProposal.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/ModuleUpgradeScripts.mv b/build/StarcoinFramework/bytecode_modules/ModuleUpgradeScripts.mv index 1bfea8bd..58cd57f1 100644 Binary files a/build/StarcoinFramework/bytecode_modules/ModuleUpgradeScripts.mv and b/build/StarcoinFramework/bytecode_modules/ModuleUpgradeScripts.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/NFTGallery.mv b/build/StarcoinFramework/bytecode_modules/NFTGallery.mv index 9f3fb03e..14374d03 100644 Binary files a/build/StarcoinFramework/bytecode_modules/NFTGallery.mv and b/build/StarcoinFramework/bytecode_modules/NFTGallery.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/NFTGalleryScripts.mv b/build/StarcoinFramework/bytecode_modules/NFTGalleryScripts.mv index d7954ee6..8b82da2e 100644 Binary files a/build/StarcoinFramework/bytecode_modules/NFTGalleryScripts.mv and b/build/StarcoinFramework/bytecode_modules/NFTGalleryScripts.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Offer.mv b/build/StarcoinFramework/bytecode_modules/Offer.mv index c8216dd6..69425dab 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Offer.mv and b/build/StarcoinFramework/bytecode_modules/Offer.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/OnChainConfigDao.mv b/build/StarcoinFramework/bytecode_modules/OnChainConfigDao.mv index 5e578fd1..61110fcf 100644 Binary files a/build/StarcoinFramework/bytecode_modules/OnChainConfigDao.mv and b/build/StarcoinFramework/bytecode_modules/OnChainConfigDao.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Oracle.mv b/build/StarcoinFramework/bytecode_modules/Oracle.mv index b2ef22b9..fac74536 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Oracle.mv and b/build/StarcoinFramework/bytecode_modules/Oracle.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/PackageTxnManager.mv b/build/StarcoinFramework/bytecode_modules/PackageTxnManager.mv index de91a6bd..1c27d3b9 100644 Binary files a/build/StarcoinFramework/bytecode_modules/PackageTxnManager.mv and b/build/StarcoinFramework/bytecode_modules/PackageTxnManager.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/PriceOracle.mv b/build/StarcoinFramework/bytecode_modules/PriceOracle.mv index 3fca8abf..ce5b5f7b 100644 Binary files a/build/StarcoinFramework/bytecode_modules/PriceOracle.mv and b/build/StarcoinFramework/bytecode_modules/PriceOracle.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/PriceOracleScripts.mv b/build/StarcoinFramework/bytecode_modules/PriceOracleScripts.mv index c433d2c0..ead679c0 100644 Binary files a/build/StarcoinFramework/bytecode_modules/PriceOracleScripts.mv and b/build/StarcoinFramework/bytecode_modules/PriceOracleScripts.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Ring.mv b/build/StarcoinFramework/bytecode_modules/Ring.mv deleted file mode 100644 index d14fabef..00000000 Binary files a/build/StarcoinFramework/bytecode_modules/Ring.mv and /dev/null differ diff --git a/build/StarcoinFramework/bytecode_modules/STC.mv b/build/StarcoinFramework/bytecode_modules/STC.mv index 83f51548..281eb50f 100644 Binary files a/build/StarcoinFramework/bytecode_modules/STC.mv and b/build/StarcoinFramework/bytecode_modules/STC.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/Signature.mv b/build/StarcoinFramework/bytecode_modules/Signature.mv index a5743312..b28c15e4 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Signature.mv and b/build/StarcoinFramework/bytecode_modules/Signature.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/SignedInteger64.mv b/build/StarcoinFramework/bytecode_modules/SignedInteger64.mv index 366352d8..d11b7f7a 100644 Binary files a/build/StarcoinFramework/bytecode_modules/SignedInteger64.mv and b/build/StarcoinFramework/bytecode_modules/SignedInteger64.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/StarcoinVerifier.mv b/build/StarcoinFramework/bytecode_modules/StarcoinVerifier.mv deleted file mode 100644 index 2151161e..00000000 Binary files a/build/StarcoinFramework/bytecode_modules/StarcoinVerifier.mv and /dev/null differ diff --git a/build/StarcoinFramework/bytecode_modules/StdlibUpgradeScripts.mv b/build/StarcoinFramework/bytecode_modules/StdlibUpgradeScripts.mv index 9d3125c8..55b53b9d 100644 Binary files a/build/StarcoinFramework/bytecode_modules/StdlibUpgradeScripts.mv and b/build/StarcoinFramework/bytecode_modules/StdlibUpgradeScripts.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/StructuredHash.mv b/build/StarcoinFramework/bytecode_modules/StructuredHash.mv deleted file mode 100644 index 5ff2d183..00000000 Binary files a/build/StarcoinFramework/bytecode_modules/StructuredHash.mv and /dev/null differ diff --git a/build/StarcoinFramework/bytecode_modules/Token.mv b/build/StarcoinFramework/bytecode_modules/Token.mv index 57123b45..09f0518f 100644 Binary files a/build/StarcoinFramework/bytecode_modules/Token.mv and b/build/StarcoinFramework/bytecode_modules/Token.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/TransactionManager.mv b/build/StarcoinFramework/bytecode_modules/TransactionManager.mv index 7ba1dba8..6c44b85e 100644 Binary files a/build/StarcoinFramework/bytecode_modules/TransactionManager.mv and b/build/StarcoinFramework/bytecode_modules/TransactionManager.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/TreasuryWithdrawDaoProposal.mv b/build/StarcoinFramework/bytecode_modules/TreasuryWithdrawDaoProposal.mv index d5e8e732..d6257ff4 100644 Binary files a/build/StarcoinFramework/bytecode_modules/TreasuryWithdrawDaoProposal.mv and b/build/StarcoinFramework/bytecode_modules/TreasuryWithdrawDaoProposal.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/U256.mv b/build/StarcoinFramework/bytecode_modules/U256.mv index f93df531..0d9c2da9 100644 Binary files a/build/StarcoinFramework/bytecode_modules/U256.mv and b/build/StarcoinFramework/bytecode_modules/U256.mv differ diff --git a/build/StarcoinFramework/bytecode_modules/UpgradeModuleDaoProposal.mv b/build/StarcoinFramework/bytecode_modules/UpgradeModuleDaoProposal.mv index a09eefb5..e93b0392 100644 Binary files a/build/StarcoinFramework/bytecode_modules/UpgradeModuleDaoProposal.mv and b/build/StarcoinFramework/bytecode_modules/UpgradeModuleDaoProposal.mv differ diff --git a/build/StarcoinFramework/docs/Account.md b/build/StarcoinFramework/docs/Account.md index 50885860..5aa8ee74 100644 --- a/build/StarcoinFramework/docs/Account.md +++ b/build/StarcoinFramework/docs/Account.md @@ -22,7 +22,6 @@ The module for the account resource that governs every account - [Resource `EventStore`](#0x1_Account_EventStore) - [Constants](#@Constants_0) - [Function `remove_signer_capability`](#0x1_Account_remove_signer_capability) -- [Function `get_genesis_capability`](#0x1_Account_get_genesis_capability) - [Function `create_signer_with_cap`](#0x1_Account_create_signer_with_cap) - [Function `destroy_signer_cap`](#0x1_Account_destroy_signer_cap) - [Function `signer_address`](#0x1_Account_signer_address) @@ -35,9 +34,7 @@ The module for the account resource that governs every account - [Function `create_signer`](#0x1_Account_create_signer) - [Function `create_account_with_initial_amount`](#0x1_Account_create_account_with_initial_amount) - [Function `create_account_with_initial_amount_v2`](#0x1_Account_create_account_with_initial_amount_v2) -- [Function `create_account_with_initial_amount_entry`](#0x1_Account_create_account_with_initial_amount_entry) - [Function `create_delegate_account`](#0x1_Account_create_delegate_account) -- [Function `generate_fresh_address`](#0x1_Account_generate_fresh_address) - [Function `deposit_to_self`](#0x1_Account_deposit_to_self) - [Function `deposit`](#0x1_Account_deposit) - [Function `deposit_with_metadata`](#0x1_Account_deposit_with_metadata) @@ -59,17 +56,13 @@ The module for the account resource that governs every account - [Function `restore_key_rotation_capability`](#0x1_Account_restore_key_rotation_capability) - [Function `destroy_key_rotation_capability`](#0x1_Account_destroy_key_rotation_capability) - [Function `rotate_authentication_key`](#0x1_Account_rotate_authentication_key) -- [Function `rotate_authentication_key_entry`](#0x1_Account_rotate_authentication_key_entry) -- [Function `do_rotate_authentication_key`](#0x1_Account_do_rotate_authentication_key) - [Function `balance_for`](#0x1_Account_balance_for) - [Function `balance`](#0x1_Account_balance) - [Function `do_accept_token`](#0x1_Account_do_accept_token) - [Function `accept_token`](#0x1_Account_accept_token) -- [Function `accept_token_entry`](#0x1_Account_accept_token_entry) - [Function `is_accepts_token`](#0x1_Account_is_accepts_token) - [Function `is_accept_token`](#0x1_Account_is_accept_token) - [Function `can_auto_accept_token`](#0x1_Account_can_auto_accept_token) -- [Function `set_auto_accept_token_entry`](#0x1_Account_set_auto_accept_token_entry) - [Function `set_auto_accept_token`](#0x1_Account_set_auto_accept_token) - [Function `try_accept_token`](#0x1_Account_try_accept_token) - [Function `sequence_number_for_account`](#0x1_Account_sequence_number_for_account) @@ -82,12 +75,8 @@ The module for the account resource that governs every account - [Function `exists_at`](#0x1_Account_exists_at) - [Function `is_dummy_auth_key`](#0x1_Account_is_dummy_auth_key) - [Function `txn_prologue`](#0x1_Account_txn_prologue) -- [Function `txn_prologue_v2`](#0x1_Account_txn_prologue_v2) - [Function `txn_epilogue`](#0x1_Account_txn_epilogue) -- [Function `transaction_fee_simulate`](#0x1_Account_transaction_fee_simulate) - [Function `txn_epilogue_v2`](#0x1_Account_txn_epilogue_v2) -- [Function `txn_epilogue_v3`](#0x1_Account_txn_epilogue_v3) -- [Function `remove_zero_balance_entry`](#0x1_Account_remove_zero_balance_entry) - [Function `remove_zero_balance`](#0x1_Account_remove_zero_balance) - [Function `make_event_store_if_not_exist`](#0x1_Account_make_event_store_if_not_exist) - [Module Specification](#@Module_Specification_1) @@ -99,7 +88,6 @@ The module for the account resource that governs every account use 0x1::Errors; use 0x1::Event; use 0x1::Hash; -use 0x1::Math; use 0x1::Option; use 0x1::STC; use 0x1::Signer; @@ -615,6 +603,15 @@ Message for SignerDelegate events + + + + +
const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0;
+
+ + + The address bytes length @@ -706,15 +703,6 @@ The address bytes length - - - - -
const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0;
-
- - - @@ -842,31 +830,6 @@ This function can only called once by signer. - - - - -## Function `get_genesis_capability` - - - -
public(friend) fun get_genesis_capability(): Account::SignerCapability
-
- - - -
-Implementation - - -
public (friend) fun get_genesis_capability():SignerCapability{
-    let signer_cap = SignerCapability {addr: Token::token_address<STC>() };
-    signer_cap
-}
-
- - -
@@ -1236,7 +1199,7 @@ reserved address for the MoveVM.
public(script) fun create_account_with_initial_amount<TokenType: store>(account: signer, fresh_address: address, _auth_key: vector<u8>, initial_amount: u128)
 acquires Account, Balance, AutoAcceptToken {
-    create_account_with_initial_amount_entry<TokenType>(account, fresh_address, initial_amount);
+     create_account_with_initial_amount_v2<TokenType>(account, fresh_address, initial_amount)
 }
 
@@ -1273,7 +1236,10 @@ reserved address for the MoveVM.
public(script) fun create_account_with_initial_amount_v2<TokenType: store>(account: signer, fresh_address: address, initial_amount: u128)
 acquires Account, Balance, AutoAcceptToken {
-    create_account_with_initial_amount_entry<TokenType>(account, fresh_address, initial_amount);
+    create_account_with_address<TokenType>(fresh_address);
+    if (initial_amount > 0) {
+        pay_from<TokenType>(&account, fresh_address, initial_amount);
+    };
 }
 
@@ -1291,34 +1257,6 @@ reserved address for the MoveVM. - - - - -## Function `create_account_with_initial_amount_entry` - - - -
public(script) fun create_account_with_initial_amount_entry<TokenType: store>(account: signer, fresh_address: address, initial_amount: u128)
-
- - - -
-Implementation - - -
public(script) fun create_account_with_initial_amount_entry<TokenType: store>(account: signer, fresh_address: address, initial_amount: u128)
-acquires Account, Balance, AutoAcceptToken {
-    create_account_with_address<TokenType>(fresh_address);
-    if (initial_amount > 0) {
-        pay_from<TokenType>(&account, fresh_address, initial_amount);
-    };
-}
-
- - -
@@ -1338,7 +1276,23 @@ Generate an new address and create a new account, then delegate the account and
public fun create_delegate_account(sender: &signer) : (address, SignerCapability) acquires Balance, Account, EventStore {
-    let new_address = generate_fresh_address(sender);
+    let sender_address = Signer::address_of(sender);
+    let sequence_number = Self::sequence_number(sender_address);
+    // use stc balance as part of seed, just for new address more random.
+    let stc_balance = Self::balance<STC>(sender_address);
+
+    let seed_bytes = BCS::to_bytes(&sender_address);
+    Vector::append(&mut seed_bytes, BCS::to_bytes(&sequence_number));
+    Vector::append(&mut seed_bytes, BCS::to_bytes(&stc_balance));
+
+    let seed_hash = Hash::sha3_256(seed_bytes);
+    let i = 0;
+    let address_bytes = Vector::empty();
+    while (i < ADDRESS_LENGTH) {
+        Vector::push_back(&mut address_bytes, *Vector::borrow(&seed_hash,i));
+        i = i + 1;
+    };
+    let new_address = BCS::to_address(address_bytes);
     Self::create_account_with_address<STC>(new_address);
     let new_signer = Self::create_signer(new_address);
     (new_address, Self::remove_signer_capability(&new_signer))
@@ -1359,60 +1313,6 @@ Generate an new address and create a new account, then delegate the account and
 
 
 
-
-
-
-
-## Function `generate_fresh_address`
-
-Generate a fresh address from the sender address and the sender's sequence number, and ensure the generated address is not exists onchain.
-
-
-
public fun generate_fresh_address(sender: &signer): address
-
- - - -
-Implementation - - -
public fun generate_fresh_address(sender: &signer) : address acquires Balance, Account {
-    let try_times = 0u64;
-    while(true){
-        let sender_address = Signer::address_of(sender);
-        let sequence_number = Self::sequence_number(sender_address);
-        // use stc balance as part of seed, just for new address more random.
-        let stc_balance = Self::balance<STC>(sender_address);
-
-        let seed_bytes = BCS::to_bytes(&sender_address);
-        Vector::append(&mut seed_bytes, BCS::to_bytes(&sequence_number));
-        Vector::append(&mut seed_bytes, BCS::to_bytes(&stc_balance));
-        Vector::append(&mut seed_bytes, BCS::to_bytes(&try_times));
-
-        let seed_hash = Hash::sha3_256(seed_bytes);
-
-        let i = 0;
-        let address_bytes = Vector::empty();
-        while (i < ADDRESS_LENGTH) {
-            Vector::push_back(&mut address_bytes, *Vector::borrow(&seed_hash,i));
-            i = i + 1;
-        };
-        let new_address = BCS::to_address(address_bytes);
-        if (Self::exists_at(new_address)){
-            try_times = try_times + 1;
-            continue
-        }else{
-            return new_address
-        }
-    };
-    //unreachable
-    abort 0
-}
-
- - -
@@ -2376,7 +2276,20 @@ Return the key rotation capability to the account it originally came from
public(script) fun rotate_authentication_key(account: signer, new_key: vector<u8>) acquires Account, EventStore {
-    rotate_authentication_key_entry(account, new_key);
+    let key_rotation_capability = extract_key_rotation_capability(&account);
+    rotate_authentication_key_with_capability(&key_rotation_capability, copy new_key);
+    restore_key_rotation_capability(key_rotation_capability);
+
+    make_event_store_if_not_exist(&account);
+    let signer_addr = Signer::address_of(&account);
+    let event_store = borrow_global_mut<EventStore>(signer_addr);
+    Event::emit_event<RotateAuthKeyEvent>(
+        &mut event_store.rotate_auth_key_events,
+        RotateAuthKeyEvent {
+            account_address: signer_addr,
+            new_auth_key: new_key,
+        }
+    );
 }
 
@@ -2394,67 +2307,6 @@ Return the key rotation capability to the account it originally came from - - - - -## Function `rotate_authentication_key_entry` - - - -
public(script) fun rotate_authentication_key_entry(account: signer, new_key: vector<u8>)
-
- - - -
-Implementation - - -
public(script) fun rotate_authentication_key_entry(account: signer, new_key: vector<u8>) acquires Account, EventStore {
-    do_rotate_authentication_key(&account, new_key);
-}
-
- - - -
- - - -## Function `do_rotate_authentication_key` - - - -
public fun do_rotate_authentication_key(account: &signer, new_key: vector<u8>)
-
- - - -
-Implementation - - -
public fun do_rotate_authentication_key(account: &signer, new_key: vector<u8>) acquires Account, EventStore {
-    let key_rotation_capability = extract_key_rotation_capability(account);
-    rotate_authentication_key_with_capability(&key_rotation_capability, copy new_key);
-    restore_key_rotation_capability(key_rotation_capability);
-
-    make_event_store_if_not_exist(account);
-    let signer_addr = Signer::address_of(account);
-    let event_store = borrow_global_mut<EventStore>(signer_addr);
-    Event::emit_event<RotateAuthKeyEvent>(
-        &mut event_store.rotate_auth_key_events,
-        RotateAuthKeyEvent {
-            account_address: signer_addr,
-            new_auth_key: new_key,
-        }
-    );
-}
-
- - -
@@ -2587,7 +2439,7 @@ Add a balance of Token type to the
public(script) fun accept_token<TokenType: store>(account: signer) acquires Account {
-    accept_token_entry<TokenType>(account);
+    do_accept_token<TokenType>(&account);
 }
 
@@ -2605,30 +2457,6 @@ Add a balance of Token type to the - - - - -## Function `accept_token_entry` - - - -
public(script) fun accept_token_entry<TokenType: store>(account: signer)
-
- - - -
-Implementation - - -
public(script) fun accept_token_entry<TokenType: store>(account: signer) acquires Account {
-    do_accept_token<TokenType>(&account);
-}
-
- - -
@@ -2742,30 +2570,6 @@ Check whether the address can auto accept token. - - - - -## Function `set_auto_accept_token_entry` - - - -
public(script) fun set_auto_accept_token_entry(account: signer, enable: bool)
-
- - - -
-Implementation - - -
public(script) fun set_auto_accept_token_entry(account: signer, enable: bool) acquires AutoAcceptToken {
-    set_auto_accept_token(&account, enable);
-}
-
- - -
@@ -3192,64 +2996,6 @@ It verifies: txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, -) acquires Account, Balance { - txn_prologue_v2<TokenType>( - account, - txn_sender, - txn_sequence_number, - txn_authentication_key_preimage, - txn_gas_price, - txn_max_gas_units, - 1, - 1, - ) -} -
- - - - - -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Account>(txn_sender);
-aborts_if global<Account>(txn_sender).authentication_key == DUMMY_AUTH_KEY && Authenticator::spec_derived_address(Hash::sha3_256(txn_authentication_key_preimage)) != txn_sender;
-aborts_if global<Account>(txn_sender).authentication_key != DUMMY_AUTH_KEY && Hash::sha3_256(txn_authentication_key_preimage) != global<Account>(txn_sender).authentication_key;
-aborts_if txn_sequence_number < global<Account>(txn_sender).sequence_number;
-
- - - -
- - - -## Function `txn_prologue_v2` - - - -
public fun txn_prologue_v2<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, stc_price: u128, stc_price_scaling: u128)
-
- - - -
-Implementation - - -
public fun txn_prologue_v2<TokenType: store>(
-    account: &signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    stc_price: u128,
-    stc_price_scaling: u128
 ) acquires Account, Balance {
     CoreAddresses::assert_genesis_address(account);
 
@@ -3274,61 +3020,31 @@ It verifies:
             Errors::invalid_argument(EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY)
         );
     };
+
     // Check that the account has enough balance for all of the gas
-    let (max_transaction_fee_stc,max_transaction_fee_token) = transaction_fee_simulate(txn_gas_price,txn_max_gas_units,0, stc_price, stc_price_scaling);
     assert!(
-        max_transaction_fee_stc <= MAX_U64,
+        (txn_gas_price as u128) * (txn_max_gas_units as u128) <= MAX_U64,
         Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT),
     );
-    if (max_transaction_fee_stc > 0) {
+    let max_transaction_fee = txn_gas_price * txn_max_gas_units;
+    if (max_transaction_fee > 0) {
+        assert!(
+            STC::is_stc<TokenType>(),
+            Errors::invalid_argument(EBAD_TRANSACTION_FEE_TOKEN)
+        );
+
+        let balance_amount = balance<TokenType>(txn_sender);
+        assert!(balance_amount >= (max_transaction_fee as u128), Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT));
+
         assert!(
             (txn_sequence_number as u128) < MAX_U64,
             Errors::limit_exceeded(EPROLOGUE_SEQUENCE_NUMBER_TOO_BIG)
         );
-        let balance_amount_token = balance<TokenType>(txn_sender);
-        assert!(balance_amount_token >= max_transaction_fee_token, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT));
-        if (!is_stc<TokenType>()){
-            let balance_amount_stc= balance<STC>(CoreAddresses::GENESIS_ADDRESS());
-            assert!(balance_amount_stc >= max_transaction_fee_stc, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT));
-        }
     };
+
     // Check that the transaction sequence number matches the sequence number of the account
     assert!(txn_sequence_number >= sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_OLD));
     assert!(txn_sequence_number == sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_NEW));
-
-}
-
- - - -
- - - -## Function `txn_epilogue` - -The epilogue is invoked at the end of transactions. -It collects gas and bumps the sequence number - - -
public fun txn_epilogue<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64)
-
- - - -
-Implementation - - -
public fun txn_epilogue<TokenType: store>(
-    account: &signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining: u64,
-) acquires Account, Balance {
-    txn_epilogue_v3<TokenType>(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining,1,1)
 }
 
@@ -3341,55 +3057,32 @@ It collects gas and bumps the sequence number -
pragma verify = false;
-
- - - -
- - - -## Function `transaction_fee_simulate` - - - -
public fun transaction_fee_simulate(txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64, stc_price: u128, stc_price_scaling: u128): (u128, u128)
-
- - - -
-Implementation - - -
public fun transaction_fee_simulate(
-    txn_gas_price:u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining:u64,
-    stc_price: u128,
-    stc_price_scaling: u128,
-): (u128, u128){
-    let transaction_fee_stc =(txn_gas_price * (txn_max_gas_units - gas_units_remaining) as u128);
-    let transaction_fee_token= Math::mul_div((transaction_fee_stc as u128), stc_price, stc_price_scaling);
-    transaction_fee_token = if (transaction_fee_token == 0 && transaction_fee_stc > 0 ) { 1 } else { transaction_fee_token};
-    (transaction_fee_stc, transaction_fee_token)
-}
+
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
+aborts_if !exists<Account>(txn_sender);
+aborts_if global<Account>(txn_sender).authentication_key == DUMMY_AUTH_KEY && Authenticator::spec_derived_address(Hash::sha3_256(txn_authentication_key_preimage)) != txn_sender;
+aborts_if global<Account>(txn_sender).authentication_key != DUMMY_AUTH_KEY && Hash::sha3_256(txn_authentication_key_preimage) != global<Account>(txn_sender).authentication_key;
+aborts_if txn_gas_price * txn_max_gas_units > max_u64();
+aborts_if txn_gas_price * txn_max_gas_units > 0 && !exists<Balance<TokenType>>(txn_sender);
+aborts_if txn_gas_price * txn_max_gas_units > 0 && Token::spec_token_code<TokenType>() != Token::spec_token_code<STC>();
+aborts_if txn_gas_price * txn_max_gas_units > 0 && global<Balance<TokenType>>(txn_sender).token.value < txn_gas_price * txn_max_gas_units;
+aborts_if txn_gas_price * txn_max_gas_units > 0 && txn_sequence_number >= max_u64();
+aborts_if txn_sequence_number < global<Account>(txn_sender).sequence_number;
+aborts_if txn_sequence_number != global<Account>(txn_sender).sequence_number;
 
- + -## Function `txn_epilogue_v2` +## Function `txn_epilogue` The epilogue is invoked at the end of transactions. It collects gas and bumps the sequence number -
public fun txn_epilogue_v2<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64)
+
public fun txn_epilogue<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64)
 
@@ -3398,23 +3091,15 @@ It collects gas and bumps the sequence number Implementation -
public fun txn_epilogue_v2<TokenType: store>(
+
public fun txn_epilogue<TokenType: store>(
     account: &signer,
     txn_sender: address,
     txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
     txn_gas_price: u64,
     txn_max_gas_units: u64,
     gas_units_remaining: u64,
 ) acquires Account, Balance {
-    txn_epilogue_v3<TokenType>(
-        account,
-        txn_sender,
-        txn_sequence_number,
-        txn_authentication_key_preimage,
-        txn_gas_price,
-        txn_max_gas_units,
-        gas_units_remaining,1,1)
+    txn_epilogue_v2<TokenType>(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining)
 }
 
@@ -3428,47 +3113,21 @@ It collects gas and bumps the sequence number
pragma verify = false;
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Account>(txn_sender);
-aborts_if !exists<Balance<TokenType>>(txn_sender);
-aborts_if txn_max_gas_units < gas_units_remaining;
-let transaction_fee_amount = txn_gas_price * (txn_max_gas_units - gas_units_remaining);
-aborts_if transaction_fee_amount > max_u128();
-aborts_if global<Balance<TokenType>>(txn_sender).token.value < transaction_fee_amount;
-aborts_if txn_sequence_number + 1 > max_u64();
-aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
-          global<Balance<TokenType>>(txn_sender).token.value  < txn_gas_price * (txn_max_gas_units - gas_units_remaining);
-aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
-          !exists<TransactionFee::TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
-          global<TransactionFee::TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS()).fee.value + txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u128();
-
- - - - -
pragma verify = false;
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Account>(txn_sender);
-aborts_if !exists<Balance<TokenType>>(txn_sender);
-aborts_if txn_sequence_number + 1 > max_u64();
-aborts_if !exists<Balance<TokenType>>(txn_sender);
-aborts_if txn_max_gas_units < gas_units_remaining;
 
- + -## Function `txn_epilogue_v3` +## Function `txn_epilogue_v2` The epilogue is invoked at the end of transactions. It collects gas and bumps the sequence number -
public fun txn_epilogue_v3<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64, stc_price: u128, stc_price_scaling: u128)
+
public fun txn_epilogue_v2<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64)
 
@@ -3477,7 +3136,7 @@ It collects gas and bumps the sequence number Implementation -
public fun txn_epilogue_v3<TokenType: store>(
+
public fun txn_epilogue_v2<TokenType: store>(
     account: &signer,
     txn_sender: address,
     txn_sequence_number: u64,
@@ -3485,43 +3144,32 @@ It collects gas and bumps the sequence number
     txn_gas_price: u64,
     txn_max_gas_units: u64,
     gas_units_remaining: u64,
-    stc_price: u128,
-    stc_price_scaling: u128,
 ) acquires Account, Balance {
     CoreAddresses::assert_genesis_address(account);
+
+    // Load the transaction sender's account and balance resources
+    let sender_account = borrow_global_mut<Account>(txn_sender);
+    let sender_balance = borrow_global_mut<Balance<TokenType>>(txn_sender);
+
     // Charge for gas
-    let (transaction_fee_amount_stc,transaction_fee_amount_token) = transaction_fee_simulate(
-        txn_gas_price,
-        txn_max_gas_units,
-        gas_units_remaining,
-        stc_price,
-        stc_price_scaling);
+    let transaction_fee_amount =(txn_gas_price * (txn_max_gas_units - gas_units_remaining) as u128);
     assert!(
-        balance<TokenType>(txn_sender) >= transaction_fee_amount_token,
+        balance_for(sender_balance) >= transaction_fee_amount,
         Errors::limit_exceeded(EINSUFFICIENT_BALANCE)
     );
-    if (!is_stc<TokenType>()){
-        let genesis_balance_amount_stc=balance<STC>(CoreAddresses::GENESIS_ADDRESS());
-        assert!(genesis_balance_amount_stc >= transaction_fee_amount_stc,
-            Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT)
-        );
-    };
-    // Load the transaction sender's account and balance resources
-    let sender_account = borrow_global_mut<Account>(txn_sender);
+
     // Bump the sequence number
     sender_account.sequence_number = txn_sequence_number + 1;
     // Set auth key when user send transaction first.
     if (is_dummy_auth_key(sender_account) && !Vector::is_empty(&txn_authentication_key_preimage)){
         sender_account.authentication_key = Hash::sha3_256(txn_authentication_key_preimage);
     };
-    if (transaction_fee_amount_stc > 0) {
-        let transaction_fee_token = withdraw_from_balance(
-        borrow_global_mut<Balance<TokenType>>(txn_sender),
-            transaction_fee_amount_token
+    if (transaction_fee_amount > 0) {
+        let transaction_fee = withdraw_from_balance(
+                sender_balance,
+                transaction_fee_amount
         );
-        deposit_to_balance(borrow_global_mut<Balance<TokenType>>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_token);
-        let stc_fee_token = withdraw_from_balance(borrow_global_mut<Balance<STC>>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_amount_stc);
-        TransactionFee::pay_fee(stc_fee_token);
+        TransactionFee::pay_fee(transaction_fee);
     };
 }
 
@@ -3530,24 +3178,26 @@ It collects gas and bumps the sequence number - - -## Function `remove_zero_balance_entry` - - - -
public(script) fun remove_zero_balance_entry<TokenType: store>(account: signer)
-
- - -
-Implementation +Specification -
public(script) fun remove_zero_balance_entry<TokenType: store>(account: signer) acquires Balance {
-    remove_zero_balance<TokenType>(&account);
-}
+
+
pragma verify = false;
+aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
+aborts_if !exists<Account>(txn_sender);
+aborts_if !exists<Balance<TokenType>>(txn_sender);
+aborts_if txn_max_gas_units < gas_units_remaining;
+let transaction_fee_amount = txn_gas_price * (txn_max_gas_units - gas_units_remaining);
+aborts_if transaction_fee_amount > max_u128();
+aborts_if global<Balance<TokenType>>(txn_sender).token.value < transaction_fee_amount;
+aborts_if txn_sequence_number + 1 > max_u64();
+aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
+        global<Balance<TokenType>>(txn_sender).token.value  < txn_gas_price * (txn_max_gas_units - gas_units_remaining);
+aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
+        !exists<TransactionFee::TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS());
+aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
+        global<TransactionFee::TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS()).fee.value + txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u128();
 
diff --git a/build/StarcoinFramework/docs/AccountScripts.md b/build/StarcoinFramework/docs/AccountScripts.md index 0a0a0d74..07c1a5e1 100644 --- a/build/StarcoinFramework/docs/AccountScripts.md +++ b/build/StarcoinFramework/docs/AccountScripts.md @@ -33,7 +33,7 @@ The script function is reenterable.
public(script) fun enable_auto_accept_token(account: signer) {
-    Account::set_auto_accept_token_entry(account, true);
+    Account::set_auto_accept_token(&account, true);
 }
 
@@ -59,7 +59,7 @@ The script function is reenterable.
public(script) fun disable_auto_accept_token(account: signer) {
-    Account::set_auto_accept_token_entry(account, false);
+    Account::set_auto_accept_token(&account, false);
 }
 
@@ -84,7 +84,7 @@ Remove zero Balance
public(script) fun remove_zero_balance<TokenType: store>(account: signer) {
-    Account::remove_zero_balance_entry<TokenType>(account);
+    Account::remove_zero_balance<TokenType>(&account);
 }
 
diff --git a/build/StarcoinFramework/docs/BCS.md b/build/StarcoinFramework/docs/BCS.md index 9af233ec..ad28b902 100644 --- a/build/StarcoinFramework/docs/BCS.md +++ b/build/StarcoinFramework/docs/BCS.md @@ -8,104 +8,12 @@ Serialization). BCS is the binary encoding for Move resources and other non-modu published on-chain. -- [Constants](#@Constants_0) - [Function `to_bytes`](#0x1_BCS_to_bytes) - [Function `to_address`](#0x1_BCS_to_address) -- [Function `deserialize_option_bytes_vector`](#0x1_BCS_deserialize_option_bytes_vector) -- [Function `deserialize_option_tuple`](#0x1_BCS_deserialize_option_tuple) -- [Function `deserialize_bytes_vector`](#0x1_BCS_deserialize_bytes_vector) -- [Function `deserialize_u64_vector`](#0x1_BCS_deserialize_u64_vector) -- [Function `deserialize_u128_vector`](#0x1_BCS_deserialize_u128_vector) -- [Function `deserialize_option_bytes`](#0x1_BCS_deserialize_option_bytes) -- [Function `deserialize_address`](#0x1_BCS_deserialize_address) -- [Function `deserialize_16_bytes`](#0x1_BCS_deserialize_16_bytes) -- [Function `deserialize_bytes`](#0x1_BCS_deserialize_bytes) -- [Function `deserialize_u128`](#0x1_BCS_deserialize_u128) -- [Function `deserialize_u64`](#0x1_BCS_deserialize_u64) -- [Function `deserialize_u32`](#0x1_BCS_deserialize_u32) -- [Function `deserialize_u16`](#0x1_BCS_deserialize_u16) -- [Function `deserialize_u8`](#0x1_BCS_deserialize_u8) -- [Function `deserialize_option_tag`](#0x1_BCS_deserialize_option_tag) -- [Function `deserialize_len`](#0x1_BCS_deserialize_len) -- [Function `deserialize_bool`](#0x1_BCS_deserialize_bool) -- [Function `get_byte`](#0x1_BCS_get_byte) -- [Function `get_n_bytes`](#0x1_BCS_get_n_bytes) -- [Function `get_n_bytes_as_u128`](#0x1_BCS_get_n_bytes_as_u128) -- [Function `deserialize_uleb128_as_u32`](#0x1_BCS_deserialize_uleb128_as_u32) -- [Function `serialize_u32_as_uleb128`](#0x1_BCS_serialize_u32_as_uleb128) -- [Function `skip_option_bytes_vector`](#0x1_BCS_skip_option_bytes_vector) -- [Function `skip_option_bytes`](#0x1_BCS_skip_option_bytes) -- [Function `skip_bytes_vector`](#0x1_BCS_skip_bytes_vector) -- [Function `skip_bytes`](#0x1_BCS_skip_bytes) -- [Function `skip_n_bytes`](#0x1_BCS_skip_n_bytes) -- [Function `skip_u64_vector`](#0x1_BCS_skip_u64_vector) -- [Function `skip_u128_vector`](#0x1_BCS_skip_u128_vector) -- [Function `skip_u256`](#0x1_BCS_skip_u256) -- [Function `skip_u128`](#0x1_BCS_skip_u128) -- [Function `skip_u64`](#0x1_BCS_skip_u64) -- [Function `skip_u32`](#0x1_BCS_skip_u32) -- [Function `skip_u16`](#0x1_BCS_skip_u16) -- [Function `skip_u8`](#0x1_BCS_skip_u8) -- [Function `skip_address`](#0x1_BCS_skip_address) -- [Function `skip_bool`](#0x1_BCS_skip_bool) -- [Function `can_skip`](#0x1_BCS_can_skip) -- [Module Specification](#@Module_Specification_1) +- [Module Specification](#@Module_Specification_0) -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Constants - - - - - - -
const ERR_INPUT_NOT_LARGE_ENOUGH: u64 = 201;
-
- - - - - - - -
const ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT: u64 = 207;
-
- - - - - - - -
const ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32: u64 = 206;
-
- - - - - - - -
const ERR_UNEXPECTED_BOOL_VALUE: u64 = 205;
-
- - - - - - - -
const INTEGER32_MAX_VALUE: u64 = 2147483647;
-
+
@@ -116,7 +24,7 @@ published on-chain. Return the binary representation of v in BCS (Starcoin Canonical Serialization) format -
public fun to_bytes<MoveValue>(v: &MoveValue): vector<u8>
+
public fun to_bytes<MoveValue: store>(v: &MoveValue): vector<u8>
 
@@ -125,7 +33,7 @@ Return the binary representation of v in BCS (Starcoin Canonical Se Implementation -
native public fun to_bytes<MoveValue>(v: &MoveValue): vector<u8>;
+
native public fun to_bytes<MoveValue: store>(v: &MoveValue): vector<u8>;
 
@@ -155,1514 +63,7 @@ Return the address of key bytes
- - -## Function `deserialize_option_bytes_vector` - - - -
public fun deserialize_option_bytes_vector(input: &vector<u8>, offset: u64): (vector<Option::Option<vector<u8>>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_bytes_vector(input: &vector<u8>, offset: u64): (vector<Option::Option<vector<u8>>>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<Option::Option<vector<u8>>>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_option_bytes(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_option_tuple` - - - -
public fun deserialize_option_tuple(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, Option::Option<vector<u8>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_tuple(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, Option::Option<vector<u8>>, u64) {
-    let (tag, new_offset) = deserialize_option_tag(input, offset);
-    if (!tag) {
-        return (Option::none<vector<u8>>(), Option::none<vector<u8>>(), new_offset)
-    } else {
-        let (bs1, new_offset) = deserialize_bytes(input, new_offset);
-        let (bs2, new_offset) = deserialize_bytes(input, new_offset);
-
-        (Option::some<vector<u8>>(bs1), Option::some<vector<u8>>(bs2), new_offset)
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_bytes_vector` - - - -
public fun deserialize_bytes_vector(input: &vector<u8>, offset: u64): (vector<vector<u8>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_bytes_vector(input: &vector<u8>, offset: u64): (vector<vector<u8>>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<vector<u8>>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_bytes(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u64_vector` - - - -
public fun deserialize_u64_vector(input: &vector<u8>, offset: u64): (vector<u64>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u64_vector(input: &vector<u8>, offset: u64): (vector<u64>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<u64>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_u64(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u128_vector` - - - -
public fun deserialize_u128_vector(input: &vector<u8>, offset: u64): (vector<u128>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u128_vector(input: &vector<u8>, offset: u64): (vector<u128>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<u128>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_u128(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_option_bytes` - - - -
public fun deserialize_option_bytes(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_bytes(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, u64) {
-    let (tag, new_offset) = deserialize_option_tag(input, offset);
-    if (!tag) {
-        return (Option::none<vector<u8>>(), new_offset)
-    } else {
-        let (bs, new_offset) = deserialize_bytes(input, new_offset);
-        return (Option::some<vector<u8>>(bs), new_offset)
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_address` - - - -
public fun deserialize_address(input: &vector<u8>, offset: u64): (address, u64)
-
- - - -
-Implementation - - -
public fun deserialize_address(input: &vector<u8>, offset: u64): (address, u64) {
-    let (content, new_offset) = deserialize_16_bytes(input, offset);
-    (BCS::to_address(content), new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_16_bytes` - - - -
public fun deserialize_16_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_16_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64) {
-    let content = get_n_bytes(input, offset, 16);
-    (content, offset + 16)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_bytes` - - - -
public fun deserialize_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let content = get_n_bytes(input, new_offset, len);
-    (content, new_offset + len)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u128` - - - -
public fun deserialize_u128(input: &vector<u8>, offset: u64): (u128, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u128(input: &vector<u8>, offset: u64): (u128, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 16);
-    (u, offset + 16)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u64` - - - -
public fun deserialize_u64(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u64(input: &vector<u8>, offset: u64): (u64, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 8);
-    ((u as u64), offset + 8)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u32` - - - -
public fun deserialize_u32(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u32(input: &vector<u8>, offset: u64): (u64, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 4);
-    ((u as u64), offset + 4)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u16` - - - -
public fun deserialize_u16(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u16(input: &vector<u8>, offset: u64): (u64, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 2);
-    ((u as u64), offset + 2)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u8` - - - -
public fun deserialize_u8(input: &vector<u8>, offset: u64): (u8, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u8(input: &vector<u8>, offset: u64): (u8, u64) {
-    let u = get_byte(input, offset);
-    (u, offset + 1)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_option_tag` - - - -
public fun deserialize_option_tag(input: &vector<u8>, offset: u64): (bool, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_tag(input: &vector<u8>, offset: u64): (bool, u64) {
-    deserialize_bool(input, offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_len` - - - -
public fun deserialize_len(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_len(input: &vector<u8>, offset: u64): (u64, u64) {
-    deserialize_uleb128_as_u32(input, offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_bool` - - - -
public fun deserialize_bool(input: &vector<u8>, offset: u64): (bool, u64)
-
- - - -
-Implementation - - -
public fun deserialize_bool(input: &vector<u8>, offset: u64): (bool, u64) {
-    let b = get_byte(input, offset);
-    if (b == 1) {
-        return (true, offset + 1)
-    } else if (b == 0) {
-        return (false, offset + 1)
-    } else {
-        abort ERR_UNEXPECTED_BOOL_VALUE
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_byte` - - - -
fun get_byte(input: &vector<u8>, offset: u64): u8
-
- - - -
-Implementation - - -
fun get_byte(input: &vector<u8>, offset: u64): u8 {
-    assert!(((offset + 1) <= Vector::length(input)) && (offset < offset + 1), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-    *Vector::borrow(input, offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_n_bytes` - - - -
fun get_n_bytes(input: &vector<u8>, offset: u64, n: u64): vector<u8>
-
- - - -
-Implementation - - -
fun get_n_bytes(input: &vector<u8>, offset: u64, n: u64): vector<u8> {
-    assert!(((offset + n) <= Vector::length(input)) && (offset <= offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-    let i = 0;
-    let content = Vector::empty<u8>();
-    while (i < n) {
-        let b = *Vector::borrow(input, offset + i);
-        Vector::push_back(&mut content, b);
-        i = i + 1;
-    };
-    content
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_n_bytes_as_u128` - - - -
fun get_n_bytes_as_u128(input: &vector<u8>, offset: u64, n: u64): u128
-
- - - -
-Implementation - - -
fun get_n_bytes_as_u128(input: &vector<u8>, offset: u64, n: u64): u128 {
-    assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-    let number: u128 = 0;
-    let i = 0;
-    while (i < n) {
-        let byte = *Vector::borrow(input, offset + i);
-        let s = (i as u8) * 8;
-        number = number + ((byte as u128) << s);
-        i = i + 1;
-    };
-    number
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_uleb128_as_u32` - - - -
public fun deserialize_uleb128_as_u32(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_uleb128_as_u32(input: &vector<u8>, offset: u64): (u64, u64) {
-    let value: u64 = 0;
-    let shift = 0;
-    let new_offset = offset;
-    while (shift < 32) {
-        let x = get_byte(input, new_offset);
-        new_offset = new_offset + 1;
-        let digit: u8 = x & 0x7F;
-        value = value | (digit as u64) << shift;
-        if ((value < 0) || (value > INTEGER32_MAX_VALUE)) {
-            abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32
-        };
-        if (digit == x) {
-            if (shift > 0 && digit == 0) {
-                abort ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT
-            };
-            return (value, new_offset)
-        };
-        shift = shift + 7
-    };
-    abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `serialize_u32_as_uleb128` - - - -
fun serialize_u32_as_uleb128(value: u64): vector<u8>
-
- - - -
-Implementation - - -
fun serialize_u32_as_uleb128(value: u64): vector<u8> {
-    let output = Vector::empty<u8>();
-    while ((value >> 7) != 0) {
-        Vector::push_back(&mut output, (((value & 0x7f) | 0x80) as u8));
-        value = value >> 7;
-    };
-    Vector::push_back(&mut output, (value as u8));
-    output
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_option_bytes_vector` - - - -
public fun skip_option_bytes_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_option_bytes_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    while (i < len) {
-        new_offset = skip_option_bytes(input, new_offset);
-        i = i + 1;
-    };
-    new_offset
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_option_bytes` - - - -
public fun skip_option_bytes(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_option_bytes(input: &vector<u8>, offset: u64):  u64 {
-    let (tag, new_offset) = deserialize_option_tag(input, offset);
-    if (!tag) {
-        new_offset
-    } else {
-        skip_bytes(input, new_offset)
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_bytes_vector` - - - -
public fun skip_bytes_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_bytes_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    while (i < len) {
-        new_offset = skip_bytes(input, new_offset);
-        i = i + 1;
-    };
-    new_offset
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_bytes` - - - -
public fun skip_bytes(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_bytes(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    new_offset + len
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_n_bytes` - - - -
public fun skip_n_bytes(input: &vector<u8>, offset: u64, n: u64): u64
-
- - - -
-Implementation - - -
public fun skip_n_bytes(input: &vector<u8>, offset: u64, n:u64): u64 {
-    can_skip(input, offset, n );
-    offset + n
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u64_vector` - - - -
public fun skip_u64_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u64_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    can_skip(input, new_offset, len * 8);
-    new_offset + len * 8
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u128_vector` - - - -
public fun skip_u128_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u128_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    can_skip(input, new_offset, len * 16);
-    new_offset + len * 16
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u256` - - - -
public fun skip_u256(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u256(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 32 );
-    offset + 32
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u128` - - - -
public fun skip_u128(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u128(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 16 );
-    offset + 16
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u64` - - - -
public fun skip_u64(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u64(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 8 );
-    offset + 8
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u32` - - - -
public fun skip_u32(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u32(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 4 );
-    offset + 4
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u16` - - - -
public fun skip_u16(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u16(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 2 );
-    offset + 2
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u8` - - - -
public fun skip_u8(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u8(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 1 );
-    offset + 1
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_address` - - - -
public fun skip_address(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_address(input: &vector<u8>, offset: u64): u64 {
-    skip_n_bytes(input, offset, 16)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_bool` - - - -
public fun skip_bool(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_bool(input: &vector<u8>, offset: u64):  u64{
-    can_skip(input, offset, 1);
-    offset + 1
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `can_skip` - - - -
fun can_skip(input: &vector<u8>, offset: u64, n: u64)
-
- - - -
-Implementation - - -
fun can_skip(input: &vector<u8>, offset: u64, n: u64){
-    assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - + ## Module Specification diff --git a/build/StarcoinFramework/docs/Block.md b/build/StarcoinFramework/docs/Block.md index 7a24f46d..7368a1bc 100644 --- a/build/StarcoinFramework/docs/Block.md +++ b/build/StarcoinFramework/docs/Block.md @@ -8,36 +8,19 @@ Block module provide metadata for generated blocks. - [Resource `BlockMetadata`](#0x1_Block_BlockMetadata) - [Struct `NewBlockEvent`](#0x1_Block_NewBlockEvent) -- [Struct `Checkpoint`](#0x1_Block_Checkpoint) -- [Resource `Checkpoints`](#0x1_Block_Checkpoints) - [Constants](#@Constants_0) - [Function `initialize`](#0x1_Block_initialize) - [Function `get_current_block_number`](#0x1_Block_get_current_block_number) - [Function `get_parent_hash`](#0x1_Block_get_parent_hash) - [Function `get_current_author`](#0x1_Block_get_current_author) - [Function `process_block_metadata`](#0x1_Block_process_block_metadata) -- [Function `checkpoints_init`](#0x1_Block_checkpoints_init) -- [Function `checkpoint_entry`](#0x1_Block_checkpoint_entry) -- [Function `checkpoint`](#0x1_Block_checkpoint) -- [Function `base_checkpoint`](#0x1_Block_base_checkpoint) -- [Function `latest_state_root`](#0x1_Block_latest_state_root) -- [Function `base_latest_state_root`](#0x1_Block_base_latest_state_root) -- [Function `update_state_root_entry`](#0x1_Block_update_state_root_entry) -- [Function `update_state_root`](#0x1_Block_update_state_root) -- [Function `base_update_state_root`](#0x1_Block_base_update_state_root) - [Module Specification](#@Module_Specification_1) -
use 0x1::BCS;
-use 0x1::CoreAddresses;
+
use 0x1::CoreAddresses;
 use 0x1::Errors;
 use 0x1::Event;
-use 0x1::GenesisSignerCapability;
-use 0x1::Hash;
-use 0x1::Option;
-use 0x1::Ring;
 use 0x1::Timestamp;
-use 0x1::Vector;
 
@@ -138,84 +121,6 @@ Events emitted when new block generated. - - - - -## Struct `Checkpoint` - - - -
struct Checkpoint has copy, drop, store
-
- - - -
-Fields - - -
-
-block_number: u64 -
-
- -
-
-block_hash: vector<u8> -
-
- -
-
-state_root: Option::Option<vector<u8>> -
-
- -
-
- - -
- - - -## Resource `Checkpoints` - - - -
struct Checkpoints has store, key
-
- - - -
-Fields - - -
-
-checkpoints: Ring::Ring<Block::Checkpoint> -
-
- -
-
-index: u64 -
-
- -
-
-last_number: u64 -
-
- -
-
- -
@@ -223,42 +128,6 @@ Events emitted when new block generated. ## Constants - - - - -
const ERR_ALREADY_INITIALIZED: u64 = 21;
-
- - - - - - - -
const BLOCK_HEADER_LENGTH: u64 = 247;
-
- - - - - - - -
const BLOCK_INTERVAL_NUMBER: u64 = 5;
-
- - - - - - - -
const CHECKPOINT_LENGTH: u64 = 60;
-
- - - @@ -268,33 +137,6 @@ Events emitted when new block generated. - - - - -
const ERROR_INTERVAL_TOO_LITTLE: u64 = 20;
-
- - - - - - - -
const ERROR_NOT_BLOCK_HEADER: u64 = 19;
-
- - - - - - - -
const ERROR_NO_HAVE_CHECKPOINT: u64 = 18;
-
- - - ## Function `initialize` @@ -521,425 +363,6 @@ Call at block prologue - - - - -## Function `checkpoints_init` - - - -
public fun checkpoints_init()
-
- - - -
-Implementation - - -
public fun checkpoints_init(){
-
-    assert!(!exists<Checkpoints>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED));
-    let signer = GenesisSignerCapability::get_genesis_signer();
-
-    let checkpoints = Ring::create_with_capacity<Checkpoint>(CHECKPOINT_LENGTH);
-    move_to<Checkpoints>(
-        &signer,
-        Checkpoints {
-           checkpoints  : checkpoints,
-           index        : 0,
-           last_number  : 0,
-    });
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `checkpoint_entry` - - - -
public(script) fun checkpoint_entry(_account: signer)
-
- - - -
-Implementation - - -
public (script) fun checkpoint_entry(_account: signer) acquires BlockMetadata, Checkpoints {
-    checkpoint();
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `checkpoint` - - - -
public fun checkpoint()
-
- - - -
-Implementation - - -
public fun checkpoint() acquires BlockMetadata, Checkpoints{
-    let parent_block_number = get_current_block_number() - 1;
-    let parent_block_hash   = get_parent_hash();
-
-    let checkpoints = borrow_global_mut<Checkpoints>(CoreAddresses::GENESIS_ADDRESS());
-    base_checkpoint(checkpoints, parent_block_number, parent_block_hash);
-
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `base_checkpoint` - - - -
fun base_checkpoint(checkpoints: &mut Block::Checkpoints, parent_block_number: u64, parent_block_hash: vector<u8>)
-
- - - -
-Implementation - - -
fun base_checkpoint(checkpoints: &mut Checkpoints, parent_block_number: u64, parent_block_hash:vector<u8>){
-    assert!(checkpoints.last_number + BLOCK_INTERVAL_NUMBER <= parent_block_number || checkpoints.last_number == 0, Errors::invalid_argument(ERROR_INTERVAL_TOO_LITTLE));
-
-    checkpoints.index = checkpoints.index + 1;
-    checkpoints.last_number = parent_block_number;
-    let op_checkpoint = Ring::push<Checkpoint>(&mut checkpoints.checkpoints, Checkpoint {
-                                                            block_number: parent_block_number,
-                                                            block_hash: parent_block_hash,
-                                                            state_root: Option::none<vector<u8>>(),
-                                                        } );
-    if(Option::is_some(&op_checkpoint)){
-        Option::destroy_some(op_checkpoint);
-    }else{
-        Option::destroy_none(op_checkpoint);
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `latest_state_root` - - - -
public fun latest_state_root(): (u64, vector<u8>)
-
- - - -
-Implementation - - -
public fun latest_state_root():(u64,vector<u8>) acquires  Checkpoints{
-    let checkpoints = borrow_global<Checkpoints>(CoreAddresses::GENESIS_ADDRESS());
-    base_latest_state_root(checkpoints)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `base_latest_state_root` - - - -
fun base_latest_state_root(checkpoints: &Block::Checkpoints): (u64, vector<u8>)
-
- - - -
-Implementation - - -
fun base_latest_state_root(checkpoints: &Checkpoints):(u64,vector<u8>){
-    let len = Ring::capacity<Checkpoint>(&checkpoints.checkpoints);
-    let j = if(checkpoints.index < len - 1){
-        checkpoints.index
-    }else{
-        len
-    };
-    let i = checkpoints.index;
-    while( j > 0){
-        let op_checkpoint = Ring::borrow(&checkpoints.checkpoints, i - 1 );
-        if( Option::is_some(op_checkpoint) && Option::is_some(&Option::borrow(op_checkpoint).state_root) ) {
-            let state_root = Option::borrow(&Option::borrow(op_checkpoint).state_root);
-            return (Option::borrow(op_checkpoint).block_number, *state_root)
-        };
-        j = j - 1;
-        i = i - 1;
-    };
-
-    abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `update_state_root_entry` - - - -
public(script) fun update_state_root_entry(_account: signer, header: vector<u8>)
-
- - - -
-Implementation - - -
public (script) fun update_state_root_entry(_account: signer , header: vector<u8>)
-acquires Checkpoints {
-    update_state_root(header);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `update_state_root` - - - -
public fun update_state_root(header: vector<u8>)
-
- - - -
-Implementation - - -
public fun update_state_root(header: vector<u8>) acquires  Checkpoints {
-    let checkpoints = borrow_global_mut<Checkpoints>(CoreAddresses::GENESIS_ADDRESS());
-    base_update_state_root(checkpoints, header);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `base_update_state_root` - - - -
fun base_update_state_root(checkpoints: &mut Block::Checkpoints, header: vector<u8>)
-
- - - -
-Implementation - - -
fun base_update_state_root(checkpoints: &mut Checkpoints, header: vector<u8>){
-    let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader");
-
-    //parent_hash
-    let new_offset = BCS::skip_bytes(&header,0);
-    //timestamp
-    let new_offset = BCS::skip_u64(&header,new_offset);
-    //number
-    let (number,new_offset) = BCS::deserialize_u64(&header,new_offset);
-    //author
-    new_offset = BCS::skip_address(&header,new_offset);
-    //author_auth_key
-    new_offset = BCS::skip_option_bytes(&header,new_offset);
-    //txn_accumulator_root
-    new_offset = BCS::skip_bytes(&header,new_offset);
-    //block_accumulator_root
-    new_offset = BCS::skip_bytes(&header,new_offset);
-    //state_root
-    let (state_root,_new_offset) = BCS::deserialize_bytes(&header,new_offset);
-
-    Vector::append(&mut prefix,header);
-    let block_hash = Hash::sha3_256(prefix);
-
-    let len = Ring::capacity<Checkpoint>(&checkpoints.checkpoints);
-    let j = if(checkpoints.index < len - 1){
-        checkpoints.index
-    }else{
-        len
-    };
-    let i = checkpoints.index;
-    while( j > 0){
-        let op_checkpoint = Ring::borrow_mut(&mut checkpoints.checkpoints, i - 1);
-
-        if( Option::is_some(op_checkpoint) && &Option::borrow(op_checkpoint).block_hash == &block_hash && Option::borrow<Checkpoint>(op_checkpoint).block_number == number) {
-
-            let op_state_root = &mut Option::borrow_mut<Checkpoint>(op_checkpoint).state_root;
-            if(Option::is_some(op_state_root)){
-                Option::swap(op_state_root, state_root);
-            }else{
-                Option::fill(op_state_root, state_root);
-            };
-            return
-        };
-        j = j - 1;
-        i = i - 1;
-    };
-
-    abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - -
diff --git a/build/StarcoinFramework/docs/BlockReward.md b/build/StarcoinFramework/docs/BlockReward.md index 4499e64e..213d255d 100644 --- a/build/StarcoinFramework/docs/BlockReward.md +++ b/build/StarcoinFramework/docs/BlockReward.md @@ -24,7 +24,7 @@ The module provide block rewarding calculation logic. use 0x1::Timestamp; use 0x1::Token; use 0x1::Treasury; -use 0x1::TreasuryPlugin; +use 0x1::TreasuryWithdrawDaoProposal; use 0x1::Vector;
@@ -317,7 +317,7 @@ Process the given block rewards. block_reward = treasury_balance; }; if (block_reward > 0) { - let reward = TreasuryPlugin::withdraw_for_block_reward<STC>(account, block_reward); + let reward = TreasuryWithdrawDaoProposal::withdraw_for_block_reward<STC>(account, block_reward); Token::deposit(&mut total_reward, reward); }; }; diff --git a/build/StarcoinFramework/docs/Compare.md b/build/StarcoinFramework/docs/Compare.md index cd7ba32c..006370d0 100644 --- a/build/StarcoinFramework/docs/Compare.md +++ b/build/StarcoinFramework/docs/Compare.md @@ -8,10 +8,8 @@ - [Constants](#@Constants_0) - [Function `cmp_bcs_bytes`](#0x1_Compare_cmp_bcs_bytes) - [Function `cmp_bytes`](#0x1_Compare_cmp_bytes) +- [Function `cmp_u8`](#0x1_Compare_cmp_u8) - [Function `cmp_u64`](#0x1_Compare_cmp_u64) -- [Function `is_equal`](#0x1_Compare_is_equal) -- [Function `is_less_than`](#0x1_Compare_is_less_than) -- [Function `is_greater_than`](#0x1_Compare_is_greater_than) - [Module Specification](#@Module_Specification_1) @@ -102,11 +100,7 @@ Keep this in mind when using this function to compare addresses. while (i1 > 0 && i2 > 0) { i1 = i1 - 1; i2 = i2 - 1; - let v1 = *Vector::borrow(v1, i1); - let v2 = *Vector::borrow(v2, i2); - let elem_cmp = if (v1 == v2) EQUAL - else if (v1 < v2) LESS_THAN - else GREATER_THAN; + let elem_cmp = cmp_u8(*Vector::borrow(v1, i1), *Vector::borrow(v2, i2)); if (elem_cmp != 0) return elem_cmp // else, compare next element }; @@ -150,18 +144,16 @@ Keep this in mind when using this function to compare addresses. let l1 = Vector::length(v1); let l2 = Vector::length(v2); let len_cmp = cmp_u64(l1, l2); - let i = 0; - while (i < l1 && i < l2) { - let v1 = *Vector::borrow(v1, i); - let v2 = *Vector::borrow(v2, i); - let elem_cmp = if (v1 == v2) EQUAL - else if (v1 < v2) LESS_THAN - else GREATER_THAN; + let i1 = 0; + let i2 = 0; + while (i1 < l1 && i2 < l2) { + let elem_cmp = cmp_u8(*Vector::borrow(v1, i1), *Vector::borrow(v2, i2)); if (elem_cmp != 0) { return elem_cmp }; // else, compare next element - i = i + 1; + i1 = i1 + 1; + i2 = i2 + 1; }; // all compared elements equal; use length comparison to break the tie len_cmp @@ -184,13 +176,13 @@ Keep this in mind when using this function to compare addresses. - + -## Function `cmp_u64` +## Function `cmp_u8` -
fun cmp_u64(i1: u64, i2: u64): u8
+
fun cmp_u8(i1: u8, i2: u8): u8
 
@@ -199,7 +191,7 @@ Keep this in mind when using this function to compare addresses. Implementation -
fun cmp_u64(i1: u64, i2: u64): u8 {
+
fun cmp_u8(i1: u8, i2: u8): u8 {
     if (i1 == i2) EQUAL
     else if (i1 < i2) LESS_THAN
     else GREATER_THAN
@@ -222,85 +214,13 @@ Keep this in mind when using this function to compare addresses.
 
 
 
-
-
-## Function `is_equal`
-
-
-
-
public fun is_equal(result: u8): bool
-
- - - -
-Implementation - - -
public fun is_equal(result: u8): bool {
-    result == EQUAL
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_less_than` - - - -
public fun is_less_than(result: u8): bool
-
- - - -
-Implementation - - -
public fun is_less_than(result: u8): bool {
-    result == LESS_THAN
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - + -## Function `is_greater_than` +## Function `cmp_u64` -
public fun is_greater_than(result: u8): bool
+
fun cmp_u64(i1: u64, i2: u64): u8
 
@@ -309,8 +229,10 @@ Keep this in mind when using this function to compare addresses. Implementation -
public fun is_greater_than(result: u8): bool {
-    result == GREATER_THAN
+
fun cmp_u64(i1: u64, i2: u64): u8 {
+    if (i1 == i2) EQUAL
+    else if (i1 < i2) LESS_THAN
+    else GREATER_THAN
 }
 
diff --git a/build/StarcoinFramework/docs/Genesis.md b/build/StarcoinFramework/docs/Genesis.md index 1bebd584..9a994b7a 100644 --- a/build/StarcoinFramework/docs/Genesis.md +++ b/build/StarcoinFramework/docs/Genesis.md @@ -14,49 +14,34 @@ The module for init Genesis
use 0x1::Account;
-use 0x1::AnyMemberPlugin;
 use 0x1::Block;
 use 0x1::BlockReward;
 use 0x1::ChainId;
+use 0x1::Collection;
 use 0x1::Config;
-use 0x1::ConfigProposalPlugin;
 use 0x1::ConsensusConfig;
 use 0x1::ConsensusStrategy;
 use 0x1::CoreAddresses;
-use 0x1::DAOExtensionPoint;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAORegistry;
 use 0x1::DummyToken;
 use 0x1::Epoch;
-use 0x1::Errors;
-use 0x1::GasOracleProposalPlugin;
 use 0x1::GenesisNFT;
 use 0x1::GenesisSignerCapability;
-use 0x1::GrantProposalPlugin;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::LanguageVersion;
-use 0x1::MemberProposalPlugin;
-use 0x1::MintProposalPlugin;
 use 0x1::Option;
 use 0x1::PackageTxnManager;
-use 0x1::RewardConfig;
 use 0x1::STC;
 use 0x1::STCUSDOracle;
 use 0x1::Signer;
-use 0x1::StakeToSBTPlugin;
-use 0x1::StarcoinDAO;
+use 0x1::StdlibUpgradeScripts;
 use 0x1::Timestamp;
 use 0x1::Token;
 use 0x1::TransactionFee;
 use 0x1::TransactionPublishOption;
 use 0x1::TransactionTimeoutConfig;
 use 0x1::Treasury;
-use 0x1::TreasuryPlugin;
-use 0x1::UpgradeModulePlugin;
+use 0x1::TreasuryWithdrawDaoProposal;
 use 0x1::VMConfig;
 use 0x1::Vector;
 use 0x1::Version;
-use 0x1::WithdrawPlugin;
 
@@ -67,7 +52,7 @@ The module for init Genesis -
public(script) fun initialize(_stdlib_version: u64, _reward_delay: u64, _pre_mine_stc_amount: u128, _time_mint_stc_amount: u128, _time_mint_stc_period: u64, _parent_hash: vector<u8>, _association_auth_key: vector<u8>, _genesis_auth_key: vector<u8>, _chain_id: u8, _genesis_timestamp: u64, _uncle_rate_target: u64, _epoch_block_count: u64, _base_block_time_target: u64, _base_block_difficulty_window: u64, _base_reward_per_block: u128, _base_reward_per_uncle_percent: u64, _min_block_time_target: u64, _max_block_time_target: u64, _base_max_uncles_per_block: u64, _base_block_gas_limit: u64, _strategy: u8, _script_allowed: bool, _module_publishing_allowed: bool, _instruction_schedule: vector<u8>, _native_schedule: vector<u8>, _global_memory_per_byte_cost: u64, _global_memory_per_byte_write_cost: u64, _min_transaction_gas_units: u64, _large_transaction_cutoff: u64, _instrinsic_gas_per_byte: u64, _maximum_number_of_gas_units: u64, _min_price_per_gas_unit: u64, _max_price_per_gas_unit: u64, _max_transaction_size_in_bytes: u64, _gas_unit_scaling_factor: u64, _default_account_size: u64, _voting_delay: u64, _voting_period: u64, _voting_quorum_rate: u8, _min_action_delay: u64, _transaction_timeout: u64)
+
public(script) fun initialize(stdlib_version: u64, reward_delay: u64, pre_mine_stc_amount: u128, time_mint_stc_amount: u128, time_mint_stc_period: u64, parent_hash: vector<u8>, association_auth_key: vector<u8>, genesis_auth_key: vector<u8>, chain_id: u8, genesis_timestamp: u64, uncle_rate_target: u64, epoch_block_count: u64, base_block_time_target: u64, base_block_difficulty_window: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, script_allowed: bool, module_publishing_allowed: bool, instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, transaction_timeout: u64)
 
@@ -77,55 +62,149 @@ The module for init Genesis
public(script) fun initialize(
-    _stdlib_version: u64,
+    stdlib_version: u64,
+
     // block reward config
-    _reward_delay: u64,
-    _pre_mine_stc_amount: u128,
-    _time_mint_stc_amount: u128,
-    _time_mint_stc_period: u64,
-    _parent_hash: vector<u8>,
-    _association_auth_key: vector<u8>,
-    _genesis_auth_key: vector<u8>,
-    _chain_id: u8,
-    _genesis_timestamp: u64,
+    reward_delay: u64,
+
+    pre_mine_stc_amount: u128,
+    time_mint_stc_amount: u128,
+    time_mint_stc_period: u64,
+    parent_hash: vector<u8>,
+    association_auth_key: vector<u8>,
+    genesis_auth_key: vector<u8>,
+    chain_id: u8,
+    genesis_timestamp: u64,
+
     //consensus config
-    _uncle_rate_target: u64,
-    _epoch_block_count: u64,
-    _base_block_time_target: u64,
-    _base_block_difficulty_window: u64,
-    _base_reward_per_block: u128,
-    _base_reward_per_uncle_percent: u64,
-    _min_block_time_target: u64,
-    _max_block_time_target: u64,
-    _base_max_uncles_per_block: u64,
-    _base_block_gas_limit: u64,
-    _strategy: u8,
+    uncle_rate_target: u64,
+    epoch_block_count: u64,
+    base_block_time_target: u64,
+    base_block_difficulty_window: u64,
+    base_reward_per_block: u128,
+    base_reward_per_uncle_percent: u64,
+    min_block_time_target: u64,
+    max_block_time_target: u64,
+    base_max_uncles_per_block: u64,
+    base_block_gas_limit: u64,
+    strategy: u8,
+
     //vm config
-    _script_allowed: bool,
-    _module_publishing_allowed: bool,
-    _instruction_schedule: vector<u8>,
-    _native_schedule: vector<u8>,
+    script_allowed: bool,
+    module_publishing_allowed: bool,
+    instruction_schedule: vector<u8>,
+    native_schedule: vector<u8>,
+
     //gas constants
-    _global_memory_per_byte_cost: u64,
-    _global_memory_per_byte_write_cost: u64,
-    _min_transaction_gas_units: u64,
-    _large_transaction_cutoff: u64,
-    _instrinsic_gas_per_byte: u64,
-    _maximum_number_of_gas_units: u64,
-    _min_price_per_gas_unit: u64,
-    _max_price_per_gas_unit: u64,
-    _max_transaction_size_in_bytes: u64,
-    _gas_unit_scaling_factor: u64,
-    _default_account_size: u64,
+    global_memory_per_byte_cost: u64,
+    global_memory_per_byte_write_cost: u64,
+    min_transaction_gas_units: u64,
+    large_transaction_cutoff: u64,
+    instrinsic_gas_per_byte: u64,
+    maximum_number_of_gas_units: u64,
+    min_price_per_gas_unit: u64,
+    max_price_per_gas_unit: u64,
+    max_transaction_size_in_bytes: u64,
+    gas_unit_scaling_factor: u64,
+    default_account_size: u64,
+
     // dao config
-    _voting_delay: u64,
-    _voting_period: u64,
-    _voting_quorum_rate: u8,
-    _min_action_delay: u64,
+    voting_delay: u64,
+    voting_period: u64,
+    voting_quorum_rate: u8,
+    min_action_delay: u64,
+
     // transaction timeout config
-    _transaction_timeout: u64,
+    transaction_timeout: u64,
 ) {
-    abort Errors::deprecated(1)
+    assert!(Timestamp::is_genesis(), 1);
+    // create genesis account
+    let genesis_account = Account::create_genesis_account(CoreAddresses::GENESIS_ADDRESS());
+    //Init global time
+    Timestamp::initialize(&genesis_account, genesis_timestamp);
+    ChainId::initialize(&genesis_account, chain_id);
+    ConsensusStrategy::initialize(&genesis_account, strategy);
+    Block::initialize(&genesis_account, parent_hash);
+    TransactionPublishOption::initialize(
+        &genesis_account,
+        script_allowed,
+        module_publishing_allowed,
+    );
+    // init config
+    VMConfig::initialize(
+        &genesis_account,
+        instruction_schedule,
+        native_schedule,
+        global_memory_per_byte_cost,
+        global_memory_per_byte_write_cost,
+        min_transaction_gas_units,
+        large_transaction_cutoff,
+        instrinsic_gas_per_byte,
+        maximum_number_of_gas_units,
+        min_price_per_gas_unit,
+        max_price_per_gas_unit,
+        max_transaction_size_in_bytes,
+        gas_unit_scaling_factor,
+        default_account_size,
+    );
+    TransactionTimeoutConfig::initialize(&genesis_account, transaction_timeout);
+    ConsensusConfig::initialize(
+        &genesis_account,
+        uncle_rate_target,
+        epoch_block_count,
+        base_block_time_target,
+        base_block_difficulty_window,
+        base_reward_per_block,
+        base_reward_per_uncle_percent,
+        min_block_time_target,
+        max_block_time_target,
+        base_max_uncles_per_block,
+        base_block_gas_limit,
+        strategy,
+    );
+    Epoch::initialize(&genesis_account);
+    BlockReward::initialize(&genesis_account, reward_delay);
+    TransactionFee::initialize(&genesis_account);
+    let association = Account::create_genesis_account(
+        CoreAddresses::ASSOCIATION_ROOT_ADDRESS(),
+    );
+    Config::publish_new_config<Version::Version>(&genesis_account, Version::new_version(stdlib_version));
+    // stdlib use two phase upgrade strategy.
+    PackageTxnManager::update_module_upgrade_strategy(
+        &genesis_account,
+        PackageTxnManager::get_strategy_two_phase(),
+        Option::some(0u64),
+    );
+    // stc should be initialized after genesis_account's module upgrade strategy set.
+    {
+        STC::initialize(&genesis_account, voting_delay, voting_period, voting_quorum_rate, min_action_delay);
+        Account::do_accept_token<STC>(&genesis_account);
+        DummyToken::initialize(&genesis_account);
+        Account::do_accept_token<STC>(&association);
+    };
+    if (pre_mine_stc_amount > 0) {
+        let stc = Token::mint<STC>(&genesis_account, pre_mine_stc_amount);
+        Account::deposit(Signer::address_of(&association), stc);
+    };
+    if (time_mint_stc_amount > 0) {
+        let cap = Token::remove_mint_capability<STC>(&genesis_account);
+        let key = Token::issue_linear_mint_key<STC>(&cap, time_mint_stc_amount, time_mint_stc_period);
+        Token::add_mint_capability(&genesis_account, cap);
+        Collection::put(&association, key);
+    };
+    // only dev network set genesis auth key.
+    if (!Vector::is_empty(&genesis_auth_key)) {
+        let genesis_rotate_key_cap = Account::extract_key_rotation_capability(&genesis_account);
+        Account::rotate_authentication_key_with_capability(&genesis_rotate_key_cap, genesis_auth_key);
+        Account::restore_key_rotation_capability(genesis_rotate_key_cap);
+    };
+    let assoc_rotate_key_cap = Account::extract_key_rotation_capability(&association);
+    Account::rotate_authentication_key_with_capability(&assoc_rotate_key_cap, association_auth_key);
+    Account::restore_key_rotation_capability(assoc_rotate_key_cap);
+    //Start time, Timestamp::is_genesis() will return false. this call should at the end of genesis init.
+    Timestamp::set_time_has_started(&genesis_account);
+    Account::release_genesis_signer(genesis_account);
+    Account::release_genesis_signer(association);
 }
 
@@ -150,17 +229,20 @@ The module for init Genesis
public(script) fun initialize_v2(
     stdlib_version: u64,
+
     // block reward and stc config
     reward_delay: u64,
     total_stc_amount: u128,
     pre_mine_stc_amount: u128,
     time_mint_stc_amount: u128,
     time_mint_stc_period: u64,
+
     parent_hash: vector<u8>,
     association_auth_key: vector<u8>,
     genesis_auth_key: vector<u8>,
     chain_id: u8,
     genesis_timestamp: u64,
+
     //consensus config
     uncle_rate_target: u64,
     epoch_block_count: u64,
@@ -173,11 +255,13 @@ The module for init Genesis
     base_max_uncles_per_block: u64,
     base_block_gas_limit: u64,
     strategy: u8,
+
     //vm config
     script_allowed: bool,
     module_publishing_allowed: bool,
     instruction_schedule: vector<u8>,
     native_schedule: vector<u8>,
+
     //gas constants
     global_memory_per_byte_cost: u64,
     global_memory_per_byte_write_cost: u64,
@@ -190,57 +274,59 @@ The module for init Genesis
     max_transaction_size_in_bytes: u64,
     gas_unit_scaling_factor: u64,
     default_account_size: u64,
+
     // dao config
     voting_delay: u64,
     voting_period: u64,
     voting_quorum_rate: u8,
     min_action_delay: u64,
+
     // transaction timeout config
     transaction_timeout: u64,
 ) {
     Self::do_initialize(
-        stdlib_version,
-        reward_delay,
-        total_stc_amount,
-        pre_mine_stc_amount,
-        time_mint_stc_amount,
-        time_mint_stc_period,
-        parent_hash,
-        association_auth_key,
-        genesis_auth_key,
-        chain_id,
-        genesis_timestamp,
-        uncle_rate_target,
-        epoch_block_count,
-        base_block_time_target,
-        base_block_difficulty_window,
-        base_reward_per_block,
-        base_reward_per_uncle_percent,
-        min_block_time_target,
-        max_block_time_target,
-        base_max_uncles_per_block,
-        base_block_gas_limit,
-        strategy,
-        script_allowed,
-        module_publishing_allowed,
-        instruction_schedule,
-        native_schedule,
-        global_memory_per_byte_cost,
-        global_memory_per_byte_write_cost,
-        min_transaction_gas_units,
-        large_transaction_cutoff,
-        instrinsic_gas_per_byte,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit,
-        max_transaction_size_in_bytes,
-        gas_unit_scaling_factor,
-        default_account_size,
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-        transaction_timeout,
+    stdlib_version,
+    reward_delay,
+    total_stc_amount,
+    pre_mine_stc_amount,
+    time_mint_stc_amount,
+    time_mint_stc_period,
+    parent_hash,
+    association_auth_key,
+    genesis_auth_key,
+    chain_id,
+    genesis_timestamp,
+    uncle_rate_target,
+    epoch_block_count,
+    base_block_time_target,
+    base_block_difficulty_window,
+    base_reward_per_block,
+    base_reward_per_uncle_percent,
+    min_block_time_target,
+    max_block_time_target,
+    base_max_uncles_per_block,
+    base_block_gas_limit,
+    strategy,
+    script_allowed,
+    module_publishing_allowed,
+    instruction_schedule,
+    native_schedule,
+    global_memory_per_byte_cost,
+    global_memory_per_byte_write_cost,
+    min_transaction_gas_units,
+    large_transaction_cutoff,
+    instrinsic_gas_per_byte,
+    maximum_number_of_gas_units,
+    min_price_per_gas_unit,
+    max_price_per_gas_unit,
+    max_transaction_size_in_bytes,
+    gas_unit_scaling_factor,
+    default_account_size,
+    voting_delay,
+    voting_period,
+    voting_quorum_rate,
+    min_action_delay,
+    transaction_timeout,
     );
 }
 
@@ -266,17 +352,20 @@ The module for init Genesis
fun do_initialize(
     stdlib_version: u64,
+
     // block reward and stc config
     reward_delay: u64,
     total_stc_amount: u128,
     pre_mine_stc_amount: u128,
     time_mint_stc_amount: u128,
     time_mint_stc_period: u64,
+
     parent_hash: vector<u8>,
     association_auth_key: vector<u8>,
     genesis_auth_key: vector<u8>,
     chain_id: u8,
     genesis_timestamp: u64,
+
     //consensus config
     uncle_rate_target: u64,
     epoch_block_count: u64,
@@ -289,11 +378,13 @@ The module for init Genesis
     base_max_uncles_per_block: u64,
     base_block_gas_limit: u64,
     strategy: u8,
+
     //vm config
     script_allowed: bool,
     module_publishing_allowed: bool,
     instruction_schedule: vector<u8>,
     native_schedule: vector<u8>,
+
     //gas constants
     global_memory_per_byte_cost: u64,
     global_memory_per_byte_write_cost: u64,
@@ -306,14 +397,16 @@ The module for init Genesis
     max_transaction_size_in_bytes: u64,
     gas_unit_scaling_factor: u64,
     default_account_size: u64,
+
     // dao config
     voting_delay: u64,
     voting_period: u64,
     voting_quorum_rate: u8,
     min_action_delay: u64,
+
     // transaction timeout config
     transaction_timeout: u64,
-) {
+){
     Timestamp::assert_genesis();
     // create genesis account
     let genesis_account = Account::create_genesis_account(CoreAddresses::GENESIS_ADDRESS());
@@ -373,7 +466,7 @@ The module for init Genesis
     BlockReward::initialize(&genesis_account, reward_delay);
 
     // stc should be initialized after genesis_account's module upgrade strategy set and all on chain config init.
-    let withdraw_cap = STC::initialize_v3(&genesis_account, total_stc_amount);
+    let withdraw_cap = STC::initialize_v2(&genesis_account, total_stc_amount, voting_delay, voting_period, voting_quorum_rate, min_action_delay);
     Account::do_accept_token<STC>(&genesis_account);
     Account::do_accept_token<STC>(&association);
 
@@ -389,7 +482,7 @@ The module for init Genesis
     };
 
     // Lock the TreasuryWithdrawCapability to Dao
-    TreasuryPlugin::delegate_capability<STC>(&genesis_account, withdraw_cap);
+    TreasuryWithdrawDaoProposal::plugin(&genesis_account, withdraw_cap);
 
     TransactionFee::initialize(&genesis_account);
 
@@ -414,48 +507,7 @@ The module for init Genesis
         let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY";
         GenesisNFT::initialize(&genesis_account, merkle_root, 1639u64, image);
     };
-    Config::publish_new_config(&genesis_account, LanguageVersion::new(4));
-
-    //v11 -> v12
-    Block::checkpoints_init();
-    DAORegistry::initialize();
-
-    DAOExtensionPoint::initialize();
-    DAOPluginMarketplace::initialize();
-
-    AnyMemberPlugin::initialize(&genesis_account);
-    ConfigProposalPlugin::initialize(&genesis_account);
-    GrantProposalPlugin::initialize(&genesis_account);
-    InstallPluginProposalPlugin::initialize(&genesis_account);
-    MemberProposalPlugin::initialize(&genesis_account);
-    MintProposalPlugin::initialize(&genesis_account);
-    StakeToSBTPlugin::initialize(&genesis_account);
-    UpgradeModulePlugin::initialize(&genesis_account);
-    GasOracleProposalPlugin::initialize(&genesis_account);
-    TreasuryPlugin::initialize(&genesis_account);
-
-    let signer_cap = Account::get_genesis_capability();
-    let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(&genesis_account);
-    StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, voting_delay, voting_period, voting_quorum_rate, min_action_delay, 1000 * 1000 * 1000 * 1000);
-
-    StarcoinDAO::delegate_config_capability<STC, TransactionPublishOption::TransactionPublishOption>(
-        Config::extract_modify_config_capability<TransactionPublishOption::TransactionPublishOption>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, VMConfig::VMConfig>(
-        Config::extract_modify_config_capability<VMConfig::VMConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, ConsensusConfig::ConsensusConfig>(
-        Config::extract_modify_config_capability<ConsensusConfig::ConsensusConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, RewardConfig::RewardConfig>(
-        Config::extract_modify_config_capability<RewardConfig::RewardConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>(
-        Config::extract_modify_config_capability<TransactionTimeoutConfig::TransactionTimeoutConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, LanguageVersion::LanguageVersion>(
-        Config::extract_modify_config_capability<LanguageVersion::LanguageVersion>(&genesis_account));
-    StarcoinDAO::set_treasury_withdraw_proposal_scale(100);
-
-    // v12 -> v13
-    WithdrawPlugin::initialize(&genesis_account);
-    StarcoinDAO::upgrade_dao();
-
+    StdlibUpgradeScripts::do_upgrade_from_v6_to_v7_with_language_version(&genesis_account, 4);
     //Start time, Timestamp::is_genesis() will return false. this call should at the end of genesis init.
     Timestamp::set_time_has_started(&genesis_account);
     Account::release_genesis_signer(genesis_account);
@@ -483,19 +535,19 @@ Init the genesis for unit tests
 Implementation
 
 
-
public fun initialize_for_unit_tests() {
+
public fun initialize_for_unit_tests(){
     let stdlib_version: u64 = 6;
     let reward_delay: u64 = 7;
     let total_stc_amount: u128 = 3185136000000000000u128;
     let pre_mine_stc_amount: u128 = 159256800000000000u128;
-    let time_mint_stc_amount: u128 = (85043130u128 * 3u128 + 74213670u128 * 3u128) * 1000000000u128;
+    let time_mint_stc_amount: u128 = (85043130u128 * 3u128 + 74213670u128 * 3u128)*1000000000u128;
     let time_mint_stc_period: u64 = 1000000000;
 
     let parent_hash: vector<u8> = x"0000000000000000000000000000000000000000000000000000000000000000";
     let association_auth_key: vector<u8> = x"0000000000000000000000000000000000000000000000000000000000000000";
     let genesis_auth_key: vector<u8> = x"0000000000000000000000000000000000000000000000000000000000000000";
     let chain_id: u8 = 255;
-    let genesis_timestamp: u64 = 0;
+    let genesis_timestamp: u64 =0;
 
     //consensus config
     let uncle_rate_target: u64 = 80;
@@ -526,13 +578,13 @@ Init the genesis for unit tests
     let maximum_number_of_gas_units: u64 = 1;
     let min_price_per_gas_unit: u64 = 1;
     let max_price_per_gas_unit: u64 = 10000;
-    let max_transaction_size_in_bytes: u64 = 1024 * 1024;
+    let max_transaction_size_in_bytes: u64 = 1024*1024;
     let gas_unit_scaling_factor: u64 = 1;
     let default_account_size: u64 = 600;
 
     // dao config
     let voting_delay: u64 = 1000;
-    let voting_period: u64 = 6000;
+    let voting_period: u64 =  6000;
     let voting_quorum_rate: u8 = 4;
     let min_action_delay: u64 = 1000;
 
diff --git a/build/StarcoinFramework/docs/GenesisNFT.md b/build/StarcoinFramework/docs/GenesisNFT.md
index b25f6504..8dfc03e3 100644
--- a/build/StarcoinFramework/docs/GenesisNFT.md
+++ b/build/StarcoinFramework/docs/GenesisNFT.md
@@ -31,7 +31,7 @@ Mint a GenesisNFT
 
 
 
public(script) fun mint(sender: signer, index: u64, merkle_proof:vector<vector<u8>>) {
-    GenesisNFT::mint_entry(sender, index, merkle_proof);
+    GenesisNFT::mint(&sender, index, merkle_proof);
 }
 
diff --git a/build/StarcoinFramework/docs/InstallPluginProposalPlugin.md b/build/StarcoinFramework/docs/InstallPluginProposalPlugin.md deleted file mode 100644 index 908486f8..00000000 --- a/build/StarcoinFramework/docs/InstallPluginProposalPlugin.md +++ /dev/null @@ -1,233 +0,0 @@ - - - -# Module `0x1::InstallPluginProposalPlugin` - - - -- [Struct `InstallPluginProposalPlugin`](#0x1_InstallPluginProposalPlugin_InstallPluginProposalPlugin) -- [Struct `InstallPluginAction`](#0x1_InstallPluginProposalPlugin_InstallPluginAction) -- [Function `initialize`](#0x1_InstallPluginProposalPlugin_initialize) -- [Function `required_caps`](#0x1_InstallPluginProposalPlugin_required_caps) -- [Function `create_proposal`](#0x1_InstallPluginProposalPlugin_create_proposal) -- [Function `execute_proposal`](#0x1_InstallPluginProposalPlugin_execute_proposal) -- [Function `execute_proposal_entry`](#0x1_InstallPluginProposalPlugin_execute_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `InstallPluginProposalPlugin` - - - -
struct InstallPluginProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `InstallPluginAction` - - - -
struct InstallPluginAction<ToInstallPluginT> has drop, store
-
- - - -
-Fields - - -
-
-required_caps: vector<DAOSpace::CapType> -
-
- -
-
- - -
- - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = InstallPluginProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<InstallPluginProposalPlugin>(
-        &witness,
-        b"0x1::InstallPluginProposalPlugin",
-        b"The plugin for install plugin proposal",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<InstallPluginProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://install-plugin-proposal-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps():vector<CapType>{
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_proposal` - -Create a proposal to install a plugin. -We do not provide a entry function for create_proposal, because we can not use CapType as an entry function parameter, -every plugin should provide a entry function to create proposal to install self. - - -
public fun create_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, required_caps: vector<DAOSpace::CapType>, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, required_caps: vector<CapType>, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay: u64){
-    let witness = InstallPluginProposalPlugin{};
-
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, InstallPluginProposalPlugin>(&witness);
-    let action = InstallPluginAction<ToInstallPluginT>{
-        required_caps,
-    };
-
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `execute_proposal` - - - -
public fun execute_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, proposal_id: u64){
-    let witness = InstallPluginProposalPlugin{};
-
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, InstallPluginProposalPlugin>(&witness);
-    let InstallPluginAction{required_caps} = DAOSpace::execute_proposal<DAOT, InstallPluginProposalPlugin, InstallPluginAction<ToInstallPluginT>>(&proposal_cap, sender, proposal_id);
-
-    let install_plugin_cap = DAOSpace::acquire_install_plugin_cap<DAOT, InstallPluginProposalPlugin>(&witness);
-    DAOSpace::install_plugin<DAOT, InstallPluginProposalPlugin, ToInstallPluginT>(&install_plugin_cap, required_caps);
-}
-
- - - -
- - - -## Function `execute_proposal_entry` - - - -
public(script) fun execute_proposal_entry<DAOT: store, ToInstallPluginT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_proposal_entry<DAOT: store, ToInstallPluginT: store>(sender: signer, proposal_id: u64) {
-    execute_proposal<DAOT, ToInstallPluginT>(&sender, proposal_id);
-}
-
- - - -
diff --git a/build/StarcoinFramework/docs/MemberProposalPlugin.md b/build/StarcoinFramework/docs/MemberProposalPlugin.md deleted file mode 100644 index 818e6e9c..00000000 --- a/build/StarcoinFramework/docs/MemberProposalPlugin.md +++ /dev/null @@ -1,360 +0,0 @@ - - - -# Module `0x1::MemberProposalPlugin` - - - -- [Struct `MemberProposalPlugin`](#0x1_MemberProposalPlugin_MemberProposalPlugin) -- [Struct `MemberJoinAction`](#0x1_MemberProposalPlugin_MemberJoinAction) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_MemberProposalPlugin_initialize) -- [Function `required_caps`](#0x1_MemberProposalPlugin_required_caps) -- [Function `create_proposal`](#0x1_MemberProposalPlugin_create_proposal) -- [Function `create_proposal_entry`](#0x1_MemberProposalPlugin_create_proposal_entry) -- [Function `execute_proposal`](#0x1_MemberProposalPlugin_execute_proposal) -- [Function `execute_proposal_entry`](#0x1_MemberProposalPlugin_execute_proposal_entry) -- [Function `install_plugin_proposal`](#0x1_MemberProposalPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_MemberProposalPlugin_install_plugin_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Errors;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `MemberProposalPlugin` - - - -
struct MemberProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `MemberJoinAction` - - - -
struct MemberJoinAction has drop, store
-
- - - -
-Fields - - -
-
-member: address -
-
- -
-
-init_sbt: u128 -
-
- -
-
-image_url: vector<u8> -
-
- -
-
-image_data: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_MEMBER_EXIST: u64 = 101;
-
- - - - - - - -
const ERR_MEMBER_OFFER_EXIST: u64 = 102;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = MemberProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<MemberProposalPlugin>(
-        &witness,
-        b"0x1::MemberProposalPlugin",
-        b"The plugin for member proposal",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<MemberProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://member-proposal-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps():vector<CapType>{
-    let caps = Vector::singleton(DAOSpace::member_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::proposal_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_proposal` - - - -
public fun create_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, member: address, image_data: vector<u8>, image_url: vector<u8>, init_sbt: u128, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_proposal<DAOT: store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, member: address, image_data:vector<u8>, image_url:vector<u8>, init_sbt: u128, action_delay: u64){
-    let witness = MemberProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, MemberProposalPlugin>(&witness);
-    let action = MemberJoinAction{
-        member,
-        init_sbt,
-        image_data,
-        image_url
-    };
-    assert!(!DAOSpace::is_exist_member_offer<DAOT>(member), Errors::already_published(ERR_MEMBER_OFFER_EXIST));
-    assert!(!DAOSpace::is_member<DAOT>(member), Errors::already_published(ERR_MEMBER_EXIST));
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `create_proposal_entry` - - - -
public(script) fun create_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, member: address, image_data: vector<u8>, image_url: vector<u8>, init_sbt: u128, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun create_proposal_entry<DAOT: store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, member: address, image_data:vector<u8>, image_url:vector<u8>, init_sbt: u128, action_delay: u64){
-    create_proposal<DAOT>(&sender, title, introduction, extend, member, image_data, image_url, init_sbt, action_delay);
-}
-
- - - -
- - - -## Function `execute_proposal` - - - -
public fun execute_proposal<DAOT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_proposal<DAOT: store>(sender: &signer, proposal_id: u64){
-    let witness = MemberProposalPlugin{};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, MemberProposalPlugin>(&witness);
-    let MemberJoinAction{member, init_sbt, image_data, image_url} = DAOSpace::execute_proposal<DAOT, MemberProposalPlugin, MemberJoinAction>(&proposal_cap, sender, proposal_id);
-    let member_cap = DAOSpace::acquire_member_cap<DAOT, MemberProposalPlugin>(&witness);
-    let op_image_data = if(Vector::length(&image_data) == 0){
-        Option::none<vector<u8>>()
-    }else{
-        Option::some(image_data)
-    };
-    let op_image_url = if(Vector::length(&image_url) == 0){
-        Option::none<vector<u8>>()
-    }else{
-        Option::some(image_url)
-    };
-    DAOSpace::issue_member_offer(&member_cap, member,op_image_data , op_image_url , init_sbt);
-}
-
- - - -
- - - -## Function `execute_proposal_entry` - - - -
public(script) fun execute_proposal_entry<DAOT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_proposal_entry<DAOT: store>(sender: signer, proposal_id: u64){
-    execute_proposal<DAOT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT:store>(sender:&signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>,action_delay:u64){
-    InstallPluginProposalPlugin::create_proposal<DAOT, MemberProposalPlugin>(sender, required_caps(), title, introduction, extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun install_plugin_proposal_entry<DAOT:store>(sender:signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/build/StarcoinFramework/docs/MerkleNFT.md b/build/StarcoinFramework/docs/MerkleNFT.md index 93a2088b..abb38d9d 100644 --- a/build/StarcoinFramework/docs/MerkleNFT.md +++ b/build/StarcoinFramework/docs/MerkleNFT.md @@ -8,7 +8,6 @@ - [Resource `MerkleNFTDistribution`](#0x1_MerkleNFTDistributor_MerkleNFTDistribution) - [Constants](#@Constants_0) - [Function `register`](#0x1_MerkleNFTDistributor_register) -- [Function `register_v2`](#0x1_MerkleNFTDistributor_register_v2) - [Function `mint_with_cap`](#0x1_MerkleNFTDistributor_mint_with_cap) - [Function `encode_leaf`](#0x1_MerkleNFTDistributor_encode_leaf) - [Function `set_minted_`](#0x1_MerkleNFTDistributor_set_minted_) @@ -97,7 +96,6 @@ ## Function `register` -Deprecated, use register_v2 instead.
public fun register<NFTMeta: copy, drop, store, Info: copy, drop, store>(signer: &signer, merkle_root: vector<u8>, leafs: u64, info: Info, meta: NFT::Metadata): NFT::MintCapability<NFTMeta>
@@ -109,13 +107,7 @@ Deprecated, use register_v2 instead.
 Implementation
 
 
-
public fun register<NFTMeta: copy + store + drop, Info: copy + store + drop>(
-    signer: &signer,
-    merkle_root: vector<u8>,
-    leafs: u64,
-    info: Info,
-    meta: Metadata
-): MintCapability<NFTMeta> {
+
public fun register<NFTMeta: copy + store + drop, Info: copy + store + drop>(signer: &signer, merkle_root: vector<u8>, leafs: u64, info: Info, meta: Metadata): MintCapability<NFTMeta> {
     let bitmap_count = leafs / 128;
     if (bitmap_count * 128 < leafs) {
         bitmap_count = bitmap_count + 1;
@@ -138,46 +130,6 @@ Deprecated, use register_v2 instead.
 
 
 
-
-
-
-
-## Function `register_v2`
-
-
-
-
public fun register_v2<NFTMeta: copy, drop, store>(signer: &signer, merkle_root: vector<u8>, leafs: u64, meta: NFT::Metadata): NFT::MintCapability<NFTMeta>
-
- - - -
-Implementation - - -
public fun register_v2<NFTMeta: copy + store + drop>(signer: &signer, merkle_root: vector<u8>, leafs: u64, meta: Metadata): MintCapability<NFTMeta> {
-    let bitmap_count = leafs / 128;
-    if (bitmap_count * 128 < leafs) {
-        bitmap_count = bitmap_count + 1;
-    };
-    let claimed_bitmap = Vector::empty();
-    let j = 0;
-    while (j < bitmap_count) {
-        Vector::push_back( &mut claimed_bitmap, 0u128);
-        j = j + 1;
-    };
-    let distribution = MerkleNFTDistribution<NFTMeta>{
-        merkle_root,
-        claimed_bitmap
-    };
-    NFT::register_v2<NFTMeta>(signer, meta);
-    move_to(signer, distribution);
-    NFT::remove_mint_capability<NFTMeta>(signer)
-}
-
- - -
diff --git a/build/StarcoinFramework/docs/ModifyDaoConfigProposal.md b/build/StarcoinFramework/docs/ModifyDaoConfigProposal.md index c602b98d..8efd0995 100644 --- a/build/StarcoinFramework/docs/ModifyDaoConfigProposal.md +++ b/build/StarcoinFramework/docs/ModifyDaoConfigProposal.md @@ -10,7 +10,6 @@ A proposal module which is used to modify Token's DAO configuration. - [Struct `DaoConfigUpdate`](#0x1_ModifyDaoConfigProposal_DaoConfigUpdate) - [Constants](#@Constants_0) - [Function `plugin`](#0x1_ModifyDaoConfigProposal_plugin) -- [Function `destroy_modify_config_capability`](#0x1_ModifyDaoConfigProposal_destroy_modify_config_capability) - [Function `propose`](#0x1_ModifyDaoConfigProposal_propose) - [Function `execute`](#0x1_ModifyDaoConfigProposal_execute) - [Module Specification](#@Module_Specification_1) @@ -174,48 +173,6 @@ Should be called by token issuer. - - - - -## Function `destroy_modify_config_capability` - -Destroy ModifyConfigCapability - - -
public fun destroy_modify_config_capability<TokenT: copy, drop, store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun destroy_modify_config_capability<TokenT: copy + drop + store>(sender: &signer)
-acquires DaoConfigModifyCapability {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-
-    let DaoConfigModifyCapability {cap} = move_from<DaoConfigModifyCapability<TokenT>>(token_issuer);
-    Config::destroy_modify_config_capability<DaoConfig<TokenT>>(cap);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - -
diff --git a/build/StarcoinFramework/docs/ModuleUpgradeScripts.md b/build/StarcoinFramework/docs/ModuleUpgradeScripts.md index cbca2aef..75885ab7 100644 --- a/build/StarcoinFramework/docs/ModuleUpgradeScripts.md +++ b/build/StarcoinFramework/docs/ModuleUpgradeScripts.md @@ -5,19 +5,16 @@ -- [Constants](#@Constants_0) - [Function `propose_module_upgrade_v2`](#0x1_ModuleUpgradeScripts_propose_module_upgrade_v2) - [Function `update_module_upgrade_strategy`](#0x1_ModuleUpgradeScripts_update_module_upgrade_strategy) -- [Function `update_module_upgrade_strategy_with_min_time`](#0x1_ModuleUpgradeScripts_update_module_upgrade_strategy_with_min_time) - [Function `submit_module_upgrade_plan`](#0x1_ModuleUpgradeScripts_submit_module_upgrade_plan) - [Function `execute_module_upgrade_plan_propose`](#0x1_ModuleUpgradeScripts_execute_module_upgrade_plan_propose) - [Function `submit_upgrade_plan`](#0x1_ModuleUpgradeScripts_submit_upgrade_plan) - [Function `cancel_upgrade_plan`](#0x1_ModuleUpgradeScripts_cancel_upgrade_plan) -- [Module Specification](#@Module_Specification_1) +- [Module Specification](#@Module_Specification_0)
use 0x1::Config;
-use 0x1::Errors;
 use 0x1::Option;
 use 0x1::PackageTxnManager;
 use 0x1::Signer;
@@ -27,20 +24,6 @@
 
 
 
-
-
-## Constants
-
-
-
-
-
-
-
const ERR_WRONG_UPGRADE_STRATEGY: u64 = 100;
-
- - - ## Function `propose_module_upgrade_v2` @@ -117,43 +100,6 @@ Update sender's module upgrade strategy to strategy - - - - -## Function `update_module_upgrade_strategy_with_min_time` - -Update sender's module upgrade strategy to strategy with min_time_limit. -This can only be invoked when strategy is STRATEGY_TWO_PHASE. - - -
public(script) fun update_module_upgrade_strategy_with_min_time(sender: signer, strategy: u8, min_time_limit: u64)
-
- - - -
-Implementation - - -
public(script) fun update_module_upgrade_strategy_with_min_time(
-    sender: signer,
-    strategy: u8,
-    min_time_limit: u64,
-){
-    // 1. check version
-    assert!(strategy == PackageTxnManager::get_strategy_two_phase(), Errors::invalid_argument(ERR_WRONG_UPGRADE_STRATEGY));
-    // 2. update strategy
-    PackageTxnManager::update_module_upgrade_strategy(
-        &sender,
-        strategy,
-        Option::some<u64>(min_time_limit),
-    );
-}
-
- - -
@@ -302,7 +248,7 @@ Cancel current upgrade plan, the sender must have UpgradePlan - + ## Module Specification diff --git a/build/StarcoinFramework/docs/NFT.md b/build/StarcoinFramework/docs/NFT.md index 3cca6422..c43e4d72 100644 --- a/build/StarcoinFramework/docs/NFT.md +++ b/build/StarcoinFramework/docs/NFT.md @@ -33,7 +33,7 @@ Init a NFTGallery for accept NFT
public(script) fun accept<NFTMeta: copy + store + drop, NFTBody: store>(sender: signer) {
-    NFTGallery::accept_entry<NFTMeta, NFTBody>(sender);
+    NFTGallery::accept<NFTMeta, NFTBody>(&sender);
 }
 
@@ -61,7 +61,7 @@ Transfer NFT with id from sender to sender: signer, id: u64, receiver: address ) { - NFTGallery::transfer_entry<NFTMeta, NFTBody>(sender, id, receiver); + NFTGallery::transfer<NFTMeta, NFTBody>(&sender, id, receiver); }
@@ -86,7 +86,7 @@ Remove empty NFTGallery.
public(script) fun remove_empty_gallery<NFTMeta: copy + store + drop, NFTBody: store>(sender: signer) {
-    NFTGallery::remove_empty_gallery_entry<NFTMeta, NFTBody>(sender);
+    NFTGallery::remove_empty_gallery<NFTMeta, NFTBody>(&sender);
 }
 
diff --git a/build/StarcoinFramework/docs/Offer.md b/build/StarcoinFramework/docs/Offer.md index 4540012a..37508102 100644 --- a/build/StarcoinFramework/docs/Offer.md +++ b/build/StarcoinFramework/docs/Offer.md @@ -6,35 +6,19 @@ - [Resource `Offer`](#0x1_Offer_Offer) -- [Resource `Offers`](#0x1_Offer_Offers) -- [Struct `OfferInfo`](#0x1_Offer_OfferInfo) - [Constants](#@Constants_0) - [Function `create`](#0x1_Offer_create) -- [Function `create_v2`](#0x1_Offer_create_v2) -- [Function `create_offers`](#0x1_Offer_create_offers) -- [Function `push`](#0x1_Offer_push) - [Function `redeem`](#0x1_Offer_redeem) -- [Function `redeem_v2`](#0x1_Offer_redeem_v2) - [Function `exists_at`](#0x1_Offer_exists_at) -- [Function `exists_at_v2`](#0x1_Offer_exists_at_v2) - [Function `address_of`](#0x1_Offer_address_of) -- [Function `address_of_v2`](#0x1_Offer_address_of_v2) -- [Function `retake`](#0x1_Offer_retake) -- [Function `get_offers_infos`](#0x1_Offer_get_offers_infos) -- [Function `get_offers_info`](#0x1_Offer_get_offers_info) -- [Function `unpack_offer_info`](#0x1_Offer_unpack_offer_info) -- [Function `get_offers_length`](#0x1_Offer_get_offers_length) -- [Function `is_offers_empty`](#0x1_Offer_is_offers_empty) - [Function `take_offer`](#0x1_Offer_take_offer) -- [Function `find_offer`](#0x1_Offer_find_offer) - [Module Specification](#@Module_Specification_1) -
use 0x1::Errors;
-use 0x1::Option;
+
use 0x1::Collection2;
+use 0x1::Errors;
 use 0x1::Signer;
 use 0x1::Timestamp;
-use 0x1::Vector;
 
@@ -46,7 +30,7 @@ A wrapper around value offered that can be claimed by the address stored in for when after lock time. -
struct Offer<Offered> has store, key
+
struct Offer<Offered> has key
 
@@ -77,66 +61,6 @@ A wrapper around value offered that can be claimed by the address s - - - - -## Resource `Offers` - - - -
struct Offers<Offered: store> has key
-
- - - -
-Fields - - -
-
-offers: vector<Offer::Offer<Offered>> -
-
- -
-
- - -
- - - -## Struct `OfferInfo` - - - -
struct OfferInfo has copy, drop, store
-
- - - -
-Fields - - -
-
-for: address -
-
- -
-
-time_lock: u64 -
-
- -
-
- -
@@ -154,24 +78,6 @@ An offer of the specified type for the account does not match - - - - -
const EOFFER_HAVE_OFFER: u64 = 106;
-
- - - - - - - -
const EOFFER_NOT_HAVE_OFFER: u64 = 105;
-
- - - Offer is not unlocked yet. @@ -182,42 +88,6 @@ Offer is not unlocked yet. - - - - -
const EOFFER_OFFERS_ARG_LEN_NOT_SAME: u64 = 104;
-
- - - - - - - -
const EOFFER_OFFERS_EMPTY: u64 = 107;
-
- - - - - - - -
const EOFFER_OFFERS_ZERO: u64 = 103;
-
- - - - - - - -
const ERR_DEPRECATED: u64 = 1;
-
- - - ## Function `create` @@ -235,20 +105,10 @@ either the for address or the transaction sender. Implementation -
public fun create<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offer, Offers{
+
public fun create<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64) {
     let time_lock = Timestamp::now_seconds() + lock_period;
-    let account_address = Signer::address_of(account);
-    if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        Vector::push_back(offers, Offer<Offered> { offered, for, time_lock });
-    }else {
-        let offers = Vector::empty<Offer<Offered>>();
-        if(exists<Offer<Offered>>(account_address)){
-            Vector::push_back(&mut offers, move_from<Offer<Offered>>(account_address));
-        };
-        Vector::push_back(&mut offers, Offer<Offered> { offered, for, time_lock });
-        move_to(account, Offers<Offered> { offers });
-    }
+    //TODO should support multi Offer?
+    move_to(account, Offer<Offered> { offered, for, time_lock });
 }
 
@@ -268,159 +128,6 @@ either the for address or the transaction sender. - - - - -## Function `create_v2` - - - -
public fun create_v2<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64)
-
- - - -
-Implementation - - -
public fun create_v2<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offers, Offer{
-    let account_address = Signer::address_of(account);
-    let time_lock = Timestamp::now_seconds() + lock_period;
-
-    if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        Vector::push_back(offers, Offer<Offered> { offered, for, time_lock });
-    }else {
-        let offers = Vector::empty<Offer<Offered>>();
-        if(exists<Offer<Offered>>(account_address)){
-            Vector::push_back(&mut offers, move_from<Offer<Offered>>(account_address));
-        };
-        Vector::push_back(&mut offers, Offer<Offered> { offered, for, time_lock });
-        move_to(account, Offers<Offered> { offers });
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `create_offers` - - - -
public fun create_offers<Offered: store>(account: &signer, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>)
-
- - - -
-Implementation - - -
public fun create_offers<Offered: store>(account: &signer, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>) acquires Offers, Offer {
-    let offer_length = Vector::length(&offereds);
-    assert!(offer_length > 0, Errors::invalid_argument(EOFFER_OFFERS_ZERO));
-    assert!(offer_length == Vector::length(&for) && offer_length == Vector::length(&lock_periods), Errors::invalid_argument(EOFFER_OFFERS_ARG_LEN_NOT_SAME));
-    let account_address = Signer::address_of(account);
-
-    if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        push(offers, offereds, for, lock_periods);
-    }else {
-        let offers = Vector::empty<Offer<Offered>>();
-        if(exists<Offer<Offered>>(account_address)){
-            Vector::push_back(&mut offers, move_from<Offer<Offered>>(account_address));
-        };
-        push(&mut offers, offereds, for, lock_periods);
-        move_to(account, Offers<Offered> { offers });
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `push` - - - -
fun push<Offered: store>(offers: &mut vector<Offer::Offer<Offered>>, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>)
-
- - - -
-Implementation - - -
fun push<Offered: store>(offers: &mut vector<Offer<Offered>>, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>){
-    let now = Timestamp::now_seconds();
-    let offer_length = Vector::length(&offereds);
-
-    let i = offer_length - 1;
-    loop{
-        Vector::push_back(offers, Offer<Offered> {
-            offered: Vector::remove(&mut offereds, i),
-            for: Vector::remove(&mut for, i),
-            time_lock: now + Vector::remove(&mut lock_periods, i)
-        });
-        if(i == 0){
-            break
-        };
-        i = i - 1;
-    };
-    Vector::destroy_empty(offereds);
-    Vector::destroy_empty(for);
-    Vector::destroy_empty(lock_periods);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - -
@@ -442,27 +149,11 @@ Also fails if no such value exists. Implementation -
public fun redeem<Offered: store>(account: &signer, offer_address: address): Offered acquires Offer, Offers {
-    let account_address = Signer::address_of(account);
-    let Offer<Offered> { offered, for, time_lock } = if(exists<Offers<Offered>>(offer_address)){
-        let op_index = find_offer<Offered>(offer_address, account_address);
-        assert!(Option::is_some(&op_index),Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT));
-        let offers = &mut borrow_global_mut<Offers<Offered>>(offer_address).offers;
-        let index = Option::destroy_some(op_index);
-        let offer = Vector::remove(offers , index);
-        if(Vector::length(offers) == 0){
-            let Offers { offers } = move_from<Offers<Offered>>(offer_address);
-            Vector::destroy_empty(offers);
-        };
-        offer
-    }else if(exists<Offer<Offered>>(offer_address)){
-        move_from<Offer<Offered>>(offer_address)
-    }else{
-        abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)
-    };
-
+
public fun redeem<Offered: store>(account: &signer, offer_address: address): Offered acquires Offer {
+    let Offer<Offered> { offered, for, time_lock } = move_from<Offer<Offered>>(offer_address);
+    let sender = Signer::address_of(account);
     let now = Timestamp::now_seconds();
-    assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT));
+    assert!(sender == for || sender == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT));
     assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED));
     offered
 }
@@ -485,61 +176,6 @@ Also fails if no such value exists.
 
 
 
-
-
-
-
-## Function `redeem_v2`
-
-
-
-
public fun redeem_v2<Offered: store>(account: &signer, offer_address: address, idx: u64): Offered
-
- - - -
-Implementation - - -
public fun redeem_v2<Offered: store>(account: &signer, offer_address: address, idx: u64): Offered acquires Offer, Offers {
-    let account_address = Signer::address_of(account);
-    let Offer<Offered> { offered, for, time_lock } = if(exists<Offers<Offered>>(offer_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(offer_address).offers;
-        assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-        let offer = Vector::remove(offers, idx);
-        if(Vector::length(offers) == 0){
-            let Offers { offers } = move_from<Offers<Offered>>(offer_address);
-            Vector::destroy_empty(offers);
-        };
-        offer
-    }else if(exists<Offer<Offered>>(offer_address)){
-        move_from<Offer<Offered>>(offer_address)
-    }else{
-        abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)
-    };
-
-    let now = Timestamp::now_seconds();
-    assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT));
-    assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED));
-    offered
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - -
@@ -559,7 +195,7 @@ Returns true if an offer of type Offered exists at offer_addr
public fun exists_at<Offered: store>(offer_address: address): bool {
-    exists<Offer<Offered>>(offer_address) || exists<Offers<Offered>>(offer_address)
+    exists<Offer<Offered>>(offer_address)
 }
 
@@ -572,43 +208,7 @@ Returns true if an offer of type Offered exists at offer_addr -
pragma verify = false;
-
- - - - - - - -## Function `exists_at_v2` - - - -
public fun exists_at_v2<Offered: store>(offer_address: address): bool
-
- - - -
-Implementation - - -
public fun exists_at_v2<Offered: store>(offer_address: address): bool{
-    exists<Offers<Offered>>(offer_address)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
+
aborts_if false;
 
@@ -632,14 +232,8 @@ Fails if no such Offer exists. Implementation -
public fun address_of<Offered: store>(offer_address: address): address acquires Offer, Offers {
-    if(exists<Offer<Offered>>(offer_address)){
-        borrow_global<Offer<Offered>>(offer_address).for
-    }else{
-        assert!(!is_offers_empty<Offered>(offer_address), Errors::invalid_argument(EOFFER_OFFERS_EMPTY));
-        address_of_v2<Offered>(offer_address, get_offers_length<Offered>(offer_address) - 1)
-    }
-
+
public fun address_of<Offered: store>(offer_address: address): address acquires Offer {
+    borrow_global<Offer<Offered>>(offer_address).for
 }
 
@@ -653,302 +247,6 @@ Fails if no such Offer exists.
aborts_if !exists<Offer<Offered>>(offer_address);
-aborts_if !exists<Offers<Offered>>(offer_address);
-
- - - -
- - - -## Function `address_of_v2` - - - -
public fun address_of_v2<Offered: store>(offer_address: address, idx: u64): address
-
- - - -
-Implementation - - -
public fun address_of_v2<Offered: store>(offer_address: address, idx: u64): address acquires Offers {
-    assert!(exists<Offers<Offered>>(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    Vector::borrow(offers, idx).for
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `retake` - - - -
public fun retake<Offered: store>(account: &signer, idx: u64): Offered
-
- - - -
-Implementation - - -
public fun retake<Offered: store>(account: &signer, idx: u64): Offered acquires Offer, Offers {
-    let account_address = Signer::address_of(account);
-    let Offer<Offered> { offered: offered, for: _, time_lock: time_lock } = if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-        let offer = Vector::remove(offers, idx);
-        if(Vector::length(offers) == 0){
-            let Offers { offers } = move_from<Offers<Offered>>(account_address);
-            Vector::destroy_empty(offers);
-        };
-        offer
-    }else if(exists<Offer<Offered>>(account_address)){
-        move_from<Offer<Offered>>(account_address)
-    }else{
-        abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)
-    };
-    let now = Timestamp::now_seconds();
-    assert!(now >= time_lock + ( 3600 * 24 * 30 * 3 ), Errors::not_published(EOFFER_NOT_UNLOCKED));
-    offered
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_offers_infos` - - - -
public fun get_offers_infos<Offered: store>(offer_address: address): Option::Option<vector<Offer::OfferInfo>>
-
- - - -
-Implementation - - -
public fun get_offers_infos<Offered: store>(offer_address: address): Option::Option<vector<OfferInfo>> acquires Offers{
-    if(!exists_at_v2<Offered>(offer_address)){
-        return Option::none<vector<OfferInfo>>()
-    };
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    let offer_infos = Vector::empty<OfferInfo>();
-    let i = 0;
-    let length = Vector::length(offers);
-    while(i < length){
-        Vector::push_back(&mut offer_infos, OfferInfo { for: Vector::borrow(offers, i).for, time_lock: Vector::borrow(offers, i).time_lock });
-        i = i + 1;
-    };
-    Option::some(offer_infos)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_offers_info` - - - -
public fun get_offers_info<Offered: store>(offer_address: address, idx: u64): Option::Option<Offer::OfferInfo>
-
- - - -
-Implementation - - -
public fun get_offers_info<Offered: store>(offer_address: address, idx: u64): Option::Option<OfferInfo> acquires Offers{
-    if(!exists_at_v2<Offered>(offer_address)){
-        return Option::none<OfferInfo>()
-    };
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    assert!(Vector::length(offers) >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    Option::some(OfferInfo { for: Vector::borrow(offers, idx).for, time_lock: Vector::borrow(offers, idx).time_lock })
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `unpack_offer_info` - - - -
public fun unpack_offer_info(offer_info: Offer::OfferInfo): (address, u64)
-
- - - -
-Implementation - - -
public fun unpack_offer_info(offer_info: OfferInfo):(address, u64){
-    let OfferInfo{ for, time_lock } = offer_info;
-    ( for, time_lock )
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_offers_length` - - - -
public fun get_offers_length<Offered: store>(offer_address: address): u64
-
- - - -
-Implementation - - -
public fun get_offers_length<Offered: store>(offer_address: address): u64 acquires Offers{
-    assert!(exists_at_v2<Offered>(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    Vector::length(offers)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `is_offers_empty` - - - -
public fun is_offers_empty<Offered: store>(offer_address: address): bool
-
- - - -
-Implementation - - -
public fun is_offers_empty<Offered: store>(offer_address: address): bool acquires Offers{
-    if( get_offers_length<Offered>(offer_address) == 0){
-        true
-    }else{
-        false
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
 
@@ -962,7 +260,7 @@ Fails if no such Offer exists. Take Offer and put to signer's Collection. -
public(script) fun take_offer<Offered: store>(_signer: signer, _offer_address: address)
+
public(script) fun take_offer<Offered: store>(signer: signer, offer_address: address)
 
@@ -971,57 +269,12 @@ Take Offer and put to signer's Collection. Implementation -
public(script) fun take_offer<Offered: store>(_signer: signer, _offer_address: address){
-    abort Errors::invalid_state(ERR_DEPRECATED)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `find_offer` - - - -
public fun find_offer<Offered: store>(offer_address: address, for: address): Option::Option<u64>
-
- - - -
-Implementation - - -
public fun find_offer<Offered: store>(offer_address: address, for: address):Option::Option<u64> acquires Offers {
-    if(!exists_at_v2<Offered>(offer_address)){
-        return Option::none<u64>()
-    };
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    let length = Vector::length(offers);
-    let i = 0;
-    while(i < length){
-        let offer = Vector::borrow(offers, i);
-        if( offer.for == for ){
-            return Option::some(i)
-        };
-        i = i + 1;
-    };
-    Option::none<u64>()
+
public(script) fun take_offer<Offered: store>(
+    signer: signer,
+    offer_address: address,
+) acquires Offer {
+    let offered = redeem<Offered>(&signer, offer_address);
+    Collection2::put(&signer, Signer::address_of(&signer), offered);
 }
 
@@ -1047,6 +300,6 @@ Take Offer and put to signer's Collection. -
pragma verify = false;
+
pragma verify = true;
 pragma aborts_if_is_strict = true;
 
diff --git a/build/StarcoinFramework/docs/OnChainConfigDao.md b/build/StarcoinFramework/docs/OnChainConfigDao.md index 90a98f79..1fc075ec 100644 --- a/build/StarcoinFramework/docs/OnChainConfigDao.md +++ b/build/StarcoinFramework/docs/OnChainConfigDao.md @@ -12,12 +12,10 @@ OnChainConfigDao is a DAO proposal for modify onchain configuration. - [Function `plugin`](#0x1_OnChainConfigDao_plugin) - [Function `propose_update`](#0x1_OnChainConfigDao_propose_update) - [Function `execute`](#0x1_OnChainConfigDao_execute) -- [Function `config_cap`](#0x1_OnChainConfigDao_config_cap) - [Module Specification](#@Module_Specification_1)
use 0x1::Config;
-use 0x1::CoreAddresses;
 use 0x1::Dao;
 use 0x1::Errors;
 use 0x1::Signer;
@@ -245,31 +243,6 @@ the kind of this proposal module.
 
 
 
-
- - - -## Function `config_cap` - - - -
public(friend) fun config_cap<TokenT: store, ConfigT: copy, drop, store>(): Config::ModifyConfigCapability<ConfigT>
-
- - - -
-Implementation - - -
public (friend) fun config_cap<TokenT: store, ConfigT: copy + drop + store>():Config::ModifyConfigCapability<ConfigT>acquires WrappedConfigModifyCapability{
-    let WrappedConfigModifyCapability <TokenT, ConfigT>{cap} = move_from<WrappedConfigModifyCapability<TokenT, ConfigT>>(CoreAddresses::GENESIS_ADDRESS());
-    cap
-}
-
- - -
diff --git a/build/StarcoinFramework/docs/Oracle.md b/build/StarcoinFramework/docs/Oracle.md index f0066760..e2f92fa4 100644 --- a/build/StarcoinFramework/docs/Oracle.md +++ b/build/StarcoinFramework/docs/Oracle.md @@ -31,7 +31,7 @@
public(script) fun register_oracle<OracleT: copy+store+drop>(sender: signer, precision: u8){
-    PriceOracle::register_oracle_entry<OracleT>(sender, precision);
+    PriceOracle::register_oracle<OracleT>(&sender, precision)
 }
 
@@ -55,7 +55,7 @@
public(script) fun init_data_source<OracleT: copy+store+drop>(sender: signer, init_value: u128){
-    PriceOracle::init_data_source_entry<OracleT>(sender, init_value);
+    PriceOracle::init_data_source<OracleT>(&sender, init_value);
 }
 
@@ -79,7 +79,7 @@
public(script) fun update<OracleT: copy+store+drop>(sender: signer, value: u128){
-    PriceOracle::update_entry<OracleT>(sender, value);
+    PriceOracle::update<OracleT>(&sender, value);
 }
 
diff --git a/build/StarcoinFramework/docs/PackageTxnManager.md b/build/StarcoinFramework/docs/PackageTxnManager.md index 2e9bafae..9c9cbc20 100644 --- a/build/StarcoinFramework/docs/PackageTxnManager.md +++ b/build/StarcoinFramework/docs/PackageTxnManager.md @@ -14,8 +14,6 @@ The module provides strategies for module upgrading. - [Struct `TwoPhaseUpgradeConfig`](#0x1_PackageTxnManager_TwoPhaseUpgradeConfig) - [Resource `TwoPhaseUpgradeV2`](#0x1_PackageTxnManager_TwoPhaseUpgradeV2) - [Struct `UpgradeEvent`](#0x1_PackageTxnManager_UpgradeEvent) -- [Resource `UpgradePlanEventHolder`](#0x1_PackageTxnManager_UpgradePlanEventHolder) -- [Struct `UpgradePlanEvent`](#0x1_PackageTxnManager_UpgradePlanEvent) - [Constants](#@Constants_0) - [Function `get_strategy_arbitrary`](#0x1_PackageTxnManager_get_strategy_arbitrary) - [Function `get_strategy_two_phase`](#0x1_PackageTxnManager_get_strategy_two_phase) @@ -40,7 +38,6 @@ The module provides strategies for module upgrading. - [Function `package_txn_prologue`](#0x1_PackageTxnManager_package_txn_prologue) - [Function `package_txn_prologue_v2`](#0x1_PackageTxnManager_package_txn_prologue_v2) - [Function `package_txn_epilogue`](#0x1_PackageTxnManager_package_txn_epilogue) -- [Function `exists_upgrade_plan_cap`](#0x1_PackageTxnManager_exists_upgrade_plan_cap) - [Module Specification](#@Module_Specification_1) @@ -358,67 +355,6 @@ module upgrade event. - - - - -## Resource `UpgradePlanEventHolder` - - - -
struct UpgradePlanEventHolder has key
-
- - - -
-Fields - - -
-
-upgrade_plan_event: Event::EventHandle<PackageTxnManager::UpgradePlanEvent> -
-
- -
-
- - -
- - - -## Struct `UpgradePlanEvent` - -module upgrade plan event when submitting a module upgrade plan - - -
struct UpgradePlanEvent has drop, store
-
- - - -
-Fields - - -
-
-package_address: address -
-
- -
-
-plan: PackageTxnManager::UpgradePlanV2 -
-
- -
-
- -
@@ -674,8 +610,7 @@ Update account's ModuleUpgradeStrategy Implementation -
public fun update_module_upgrade_strategy(account: &signer, strategy: u8, min_time: Option<u64>)
-acquires ModuleUpgradeStrategy, TwoPhaseUpgrade, TwoPhaseUpgradeV2, UpgradePlanCapability, UpgradePlanEventHolder{
+
public fun update_module_upgrade_strategy(account: &signer, strategy: u8, min_time: Option<u64>) acquires ModuleUpgradeStrategy, TwoPhaseUpgrade, TwoPhaseUpgradeV2, UpgradePlanCapability{
     assert!(strategy == STRATEGY_ARBITRARY || strategy == STRATEGY_TWO_PHASE || strategy == STRATEGY_NEW_MODULE || strategy == STRATEGY_FREEZE, Errors::invalid_argument(EUNKNOWN_STRATEGY));
     let account_address = Signer::address_of(account);
     let previous_strategy = get_module_upgrade_strategy(account_address);
@@ -688,16 +623,13 @@ Update account's ModuleUpgradeStrategy
     if (strategy == STRATEGY_TWO_PHASE){
         let version_cap = Config::extract_modify_config_capability<Version::Version>(account);
         let min_time_limit = Option::get_with_default(&min_time, DEFAULT_MIN_TIME_LIMIT);
-        move_to(account, UpgradePlanCapability{ account_address});
-        move_to(account, TwoPhaseUpgradeV2 {
-            config: TwoPhaseUpgradeConfig { min_time_limit },
+        move_to(account, UpgradePlanCapability{ account_address: account_address});
+        move_to(account, TwoPhaseUpgradeV2{
+            config: TwoPhaseUpgradeConfig{min_time_limit: min_time_limit},
             plan: Option::none<UpgradePlanV2>(),
-            version_cap,
-            upgrade_event: Event::new_event_handle<UpgradeEvent>(account)
-        });
-        move_to(account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(account)
-        });
+            version_cap: version_cap,
+            upgrade_event: Event::new_event_handle<Self::UpgradeEvent>(account)}
+        );
     };
     //clean two phase upgrade resource
     if (previous_strategy == STRATEGY_TWO_PHASE){
@@ -709,12 +641,8 @@ Update account's ModuleUpgradeStrategy
         };
         if (exists<TwoPhaseUpgradeV2>(account_address)) {
             let tpu = move_from<TwoPhaseUpgradeV2>(account_address);
-            let TwoPhaseUpgradeV2{config: _, plan: _, version_cap, upgrade_event } = tpu;
-            Event::destroy_handle<UpgradeEvent>(upgrade_event);
-            if (exists<UpgradePlanEventHolder>(account_address)) {
-                let UpgradePlanEventHolder{ upgrade_plan_event } = move_from<UpgradePlanEventHolder>(account_address);
-                Event::destroy_handle<UpgradePlanEvent>(upgrade_plan_event);
-            };
+            let TwoPhaseUpgradeV2{plan:_, version_cap, upgrade_event, config: _} = tpu;
+            Event::destroy_handle<Self::UpgradeEvent>(upgrade_event);
             Config::destroy_modify_config_capability<Version::Version>(version_cap);
         };
         // UpgradePlanCapability may be extracted
@@ -879,27 +807,21 @@ extract out UpgradePlanCapability from signer.
     if (Option::is_some(&plan)) {
         let old_plan = Option::borrow(&plan);
         move_to(&account, TwoPhaseUpgradeV2{
-            config,
+            config: config,
             plan: Option::some(UpgradePlanV2 {
                 package_hash: *&old_plan.package_hash,
                 active_after_time: old_plan.active_after_time,
                 version: old_plan.version,
                 enforced: false }),
-            version_cap,
-            upgrade_event
-        });
-        move_to(&account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(&account)
+            version_cap: version_cap,
+            upgrade_event: upgrade_event
         });
     } else {
-        move_to(&account, TwoPhaseUpgradeV2 {
-            config,
+        move_to(&account, TwoPhaseUpgradeV2{
+            config: config,
             plan: Option::none<UpgradePlanV2>(),
-            version_cap,
-            upgrade_event
-        });
-        move_to(&account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(&account)
+            version_cap: version_cap,
+            upgrade_event: upgrade_event
         });
     };
 }
@@ -936,16 +858,9 @@ extract out UpgradePlanCapability from signer.
 Implementation
 
 
-
public fun submit_upgrade_plan_v2(account: &signer, package_hash: vector<u8>, version:u64, enforced: bool)
-acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy,UpgradePlanEventHolder{
+
public fun submit_upgrade_plan_v2(account: &signer, package_hash: vector<u8>, version:u64, enforced: bool) acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy{
     let account_address = Signer::address_of(account);
     let cap = borrow_global<UpgradePlanCapability>(account_address);
-    assert!(get_module_upgrade_strategy(cap.account_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE));
-    if (!exists<UpgradePlanEventHolder>(account_address)) {
-        move_to(account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(account)
-        })
-    };
     submit_upgrade_plan_with_cap_v2(cap, package_hash, version, enforced);
 }
 
@@ -984,27 +899,12 @@ extract out UpgradePlanCapability from signer. Implementation -
public fun submit_upgrade_plan_with_cap_v2(cap: &UpgradePlanCapability, package_hash: vector<u8>, version: u64, enforced: bool)
-acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy, UpgradePlanEventHolder{
+
public fun submit_upgrade_plan_with_cap_v2(cap: &UpgradePlanCapability, package_hash: vector<u8>, version: u64, enforced: bool) acquires TwoPhaseUpgradeV2,ModuleUpgradeStrategy{
     let package_address = cap.account_address;
     assert!(get_module_upgrade_strategy(package_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE));
-
     let tpu = borrow_global_mut<TwoPhaseUpgradeV2>(package_address);
     let active_after_time = Timestamp::now_milliseconds() + tpu.config.min_time_limit;
-    let plan = UpgradePlanV2 { package_hash, active_after_time, version, enforced };
-    tpu.plan = Option::some(copy plan);
-
-    // TODO
-    // if UpgradePlanCapability was delegated to DAO or contract,
-    // it's hard to upgrade the address to claim an UpgradePlanEventHolder.
-    // Try to fix this!
-    if (exists<UpgradePlanEventHolder>(package_address)) {
-        let event_holder = borrow_global_mut<UpgradePlanEventHolder>(package_address);
-        Event::emit_event<UpgradePlanEvent>(&mut event_holder.upgrade_plan_event, UpgradePlanEvent {
-            package_address,
-            plan
-        });
-    }
+    tpu.plan = Option::some(UpgradePlanV2 { package_hash, active_after_time, version, enforced });
 }
 
@@ -1401,7 +1301,7 @@ Check againest on the given package data. let plan = Option::borrow(&tpu.plan); Config::set_with_capability<Version::Version>(&mut tpu.version_cap, Version::new_version(plan.version)); Event::emit_event<Self::UpgradeEvent>(&mut tpu.upgrade_event, UpgradeEvent { - package_address, + package_address: package_address, package_hash: *&plan.package_hash, version: plan.version}); }; @@ -1541,42 +1441,6 @@ Package txn finished, and clean UpgradePlan - - - - -## Function `exists_upgrade_plan_cap` - - - -
public fun exists_upgrade_plan_cap(addr: address): bool
-
- - - -
-Implementation - - -
public fun exists_upgrade_plan_cap(addr :address):bool{
-    exists<UpgradePlanCapability>(addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - -
diff --git a/build/StarcoinFramework/docs/README.md b/build/StarcoinFramework/docs/README.md index 4552316e..c4593a86 100644 --- a/build/StarcoinFramework/docs/README.md +++ b/build/StarcoinFramework/docs/README.md @@ -12,10 +12,8 @@ This is the root document for the Move StarcoinFramework module documentation. T ## Index -- [`0x1::ASCII`](ASCII.md#0x1_ASCII) - [`0x1::Account`](Account.md#0x1_Account) - [`0x1::AccountScripts`](AccountScripts.md#0x1_AccountScripts) -- [`0x1::AnyMemberPlugin`](AnyMemberPlugin.md#0x1_AnyMemberPlugin) - [`0x1::Arith`](U256.md#0x1_Arith) - [`0x1::Authenticator`](Authenticator.md#0x1_Authenticator) - [`0x1::BCS`](BCS.md#0x1_BCS) @@ -27,15 +25,9 @@ This is the root document for the Move StarcoinFramework module documentation. T - [`0x1::Collection2`](Collection2.md#0x1_Collection2) - [`0x1::Compare`](Compare.md#0x1_Compare) - [`0x1::Config`](Config.md#0x1_Config) -- [`0x1::ConfigProposalPlugin`](ConfigProposalPlugin.md#0x1_ConfigProposalPlugin) - [`0x1::ConsensusConfig`](ConsensusConfig.md#0x1_ConsensusConfig) - [`0x1::ConsensusStrategy`](ConsensusStrategy.md#0x1_ConsensusStrategy) - [`0x1::CoreAddresses`](CoreAddresses.md#0x1_CoreAddresses) -- [`0x1::DAOAccount`](DAOAccount.md#0x1_DAOAccount) -- [`0x1::DAOExtensionPoint`](DAOExtensionPoint.md#0x1_DAOExtensionPoint) -- [`0x1::DAOPluginMarketplace`](DAOPluginMarketplace.md#0x1_DAOPluginMarketplace) -- [`0x1::DAORegistry`](DAORegistry.md#0x1_DAORegistry) -- [`0x1::DAOSpace`](DAOSpace.md#0x1_DAOSpace) - [`0x1::Dao`](Dao.md#0x1_Dao) - [`0x1::DaoVoteScripts`](DaoVoteScripts.md#0x1_DaoVoteScripts) - [`0x1::Debug`](Debug.md#0x1_Debug) @@ -46,26 +38,19 @@ This is the root document for the Move StarcoinFramework module documentation. T - [`0x1::Epoch`](Epoch.md#0x1_Epoch) - [`0x1::Errors`](Errors.md#0x1_Errors) - [`0x1::Event`](Event.md#0x1_Event) -- [`0x1::EventUtil`](EventUtil.md#0x1_EventUtil) - [`0x1::FixedPoint32`](FixedPoint32.md#0x1_FixedPoint32) -- [`0x1::GasOracle`](Oracle.md#0x1_GasOracle) -- [`0x1::GasOracleProposalPlugin`](GasOracleProposalPlugin.md#0x1_GasOracleProposalPlugin) - [`0x1::Genesis`](Genesis.md#0x1_Genesis) - [`0x1::GenesisNFT`](GenesisNFT.md#0x1_GenesisNFT) - [`0x1::GenesisNFTScripts`](GenesisNFT.md#0x1_GenesisNFTScripts) - [`0x1::GenesisSignerCapability`](GenesisSignerCapability.md#0x1_GenesisSignerCapability) -- [`0x1::GrantProposalPlugin`](GrantProposalPlugin.md#0x1_GrantProposalPlugin) - [`0x1::Hash`](Hash.md#0x1_Hash) - [`0x1::IdentifierNFT`](NFT.md#0x1_IdentifierNFT) - [`0x1::IdentifierNFTScripts`](NFT.md#0x1_IdentifierNFTScripts) -- [`0x1::InstallPluginProposalPlugin`](InstallPluginProposalPlugin.md#0x1_InstallPluginProposalPlugin) - [`0x1::LanguageVersion`](LanguageVersion.md#0x1_LanguageVersion) - [`0x1::Math`](Math.md#0x1_Math) -- [`0x1::MemberProposalPlugin`](MemberProposalPlugin.md#0x1_MemberProposalPlugin) - [`0x1::MerkleNFTDistributor`](MerkleNFT.md#0x1_MerkleNFTDistributor) - [`0x1::MerkleProof`](MerkleNFT.md#0x1_MerkleProof) - [`0x1::MintDaoProposal`](MintDaoProposal.md#0x1_MintDaoProposal) -- [`0x1::MintProposalPlugin`](MintProposalPlugin.md#0x1_MintProposalPlugin) - [`0x1::MintScripts`](MintScripts.md#0x1_MintScripts) - [`0x1::ModifyDaoConfigProposal`](ModifyDaoConfigProposal.md#0x1_ModifyDaoConfigProposal) - [`0x1::ModuleUpgradeScripts`](ModuleUpgradeScripts.md#0x1_ModuleUpgradeScripts) @@ -75,7 +60,6 @@ This is the root document for the Move StarcoinFramework module documentation. T - [`0x1::Offer`](Offer.md#0x1_Offer) - [`0x1::OnChainConfigDao`](OnChainConfigDao.md#0x1_OnChainConfigDao) - [`0x1::OnChainConfigScripts`](OnChainConfigScripts.md#0x1_OnChainConfigScripts) -- [`0x1::OnChainStarcoinDAOConfig`](OnChainStarcoinDAOConfig.md#0x1_OnChainStarcoinDAOConfig) - [`0x1::Option`](Option.md#0x1_Option) - [`0x1::Oracle`](Oracle.md#0x1_Oracle) - [`0x1::PackageTxnManager`](PackageTxnManager.md#0x1_PackageTxnManager) @@ -83,8 +67,6 @@ This is the root document for the Move StarcoinFramework module documentation. T - [`0x1::PriceOracleAggregator`](Oracle.md#0x1_PriceOracleAggregator) - [`0x1::PriceOracleScripts`](Oracle.md#0x1_PriceOracleScripts) - [`0x1::RewardConfig`](RewardConfig.md#0x1_RewardConfig) -- [`0x1::Ring`](Ring.md#0x1_Ring) -- [`0x1::SBTVoteStrategy`](SBTVoteStrategy.md#0x1_SBTVoteStrategy) - [`0x1::SIP_2`](SIPs.md#0x1_SIP_2) - [`0x1::SIP_3`](SIPs.md#0x1_SIP_3) - [`0x1::STC`](STC.md#0x1_STC) @@ -93,13 +75,7 @@ This is the root document for the Move StarcoinFramework module documentation. T - [`0x1::Signature`](Signature.md#0x1_Signature) - [`0x1::SignedInteger64`](SignedInteger64.md#0x1_SignedInteger64) - [`0x1::Signer`](Signer.md#0x1_Signer) -- [`0x1::SimpleMap`](SimpleMap.md#0x1_SimpleMap) -- [`0x1::SnapshotUtil`](SnapshotUtil.md#0x1_SnapshotUtil) -- [`0x1::StakeToSBTPlugin`](StakeToSBTPlugin.md#0x1_StakeToSBTPlugin) -- [`0x1::StarcoinDAO`](StarcoinDAO.md#0x1_StarcoinDAO) -- [`0x1::StarcoinVerifier`](StarcoinVerifier.md#0x1_StarcoinVerifier) - [`0x1::StdlibUpgradeScripts`](StdlibUpgradeScripts.md#0x1_StdlibUpgradeScripts) -- [`0x1::StructuredHash`](StarcoinVerifier.md#0x1_StructuredHash) - [`0x1::Timestamp`](Timestamp.md#0x1_Timestamp) - [`0x1::Token`](Token.md#0x1_Token) - [`0x1::TransactionFee`](TransactionFee.md#0x1_TransactionFee) @@ -109,16 +85,12 @@ This is the root document for the Move StarcoinFramework module documentation. T - [`0x1::TransactionTimeoutConfig`](TransactionTimeoutConfig.md#0x1_TransactionTimeoutConfig) - [`0x1::TransferScripts`](TransferScripts.md#0x1_TransferScripts) - [`0x1::Treasury`](Treasury.md#0x1_Treasury) -- [`0x1::TreasuryPlugin`](TreasuryPlugin.md#0x1_TreasuryPlugin) - [`0x1::TreasuryScripts`](TreasuryScripts.md#0x1_TreasuryScripts) - [`0x1::TreasuryWithdrawDaoProposal`](TreasuryWithdrawDaoProposal.md#0x1_TreasuryWithdrawDaoProposal) -- [`0x1::TypeInfo`](TypeInfo.md#0x1_TypeInfo) - [`0x1::U256`](U256.md#0x1_U256) - [`0x1::UpgradeModuleDaoProposal`](UpgradeModuleDaoProposal.md#0x1_UpgradeModuleDaoProposal) -- [`0x1::UpgradeModulePlugin`](UpgradeModulePlugin.md#0x1_UpgradeModulePlugin) - [`0x1::VMConfig`](VMConfig.md#0x1_VMConfig) - [`0x1::Vector`](Vector.md#0x1_Vector) - [`0x1::Version`](Version.md#0x1_Version) -- [`0x1::WithdrawPlugin`](WithdrawPlugin.md#0x1_WithdrawPlugin) - [`0x1::YieldFarming`](YieldFarming.md#0x1_YieldFarming) - [`0x1::YieldFarmingV2`](YieldFarmingV2.md#0x1_YieldFarmingV2) diff --git a/build/StarcoinFramework/docs/Ring.md b/build/StarcoinFramework/docs/Ring.md deleted file mode 100644 index 9fa1f7ef..00000000 --- a/build/StarcoinFramework/docs/Ring.md +++ /dev/null @@ -1,437 +0,0 @@ - - - -# Module `0x1::Ring` - -A ring-shaped container that can hold any type, indexed from 0 -The capacity is fixed at creation time, and the accessible index is constantly growing - - -- [Struct `Ring`](#0x1_Ring_Ring) -- [Constants](#@Constants_0) -- [Function `create_with_capacity`](#0x1_Ring_create_with_capacity) -- [Function `is_full`](#0x1_Ring_is_full) -- [Function `capacity`](#0x1_Ring_capacity) -- [Function `push`](#0x1_Ring_push) -- [Function `borrow`](#0x1_Ring_borrow) -- [Function `borrow_mut`](#0x1_Ring_borrow_mut) -- [Function `index_of`](#0x1_Ring_index_of) -- [Function `destroy`](#0x1_Ring_destroy) - - -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `Ring` - - - -
struct Ring<Element> has store
-
- - - -
-Fields - - -
-
-data: vector<Option::Option<Element>> -
-
- -
-
-insertion_index: u64 -
-
- -
-
-external_index: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -The index into the vector is out of bounds - - -
const ERROR_RING_INDEX_OUT_OF_BOUNDS: u64 = 101;
-
- - - - - -## Function `create_with_capacity` - -Create a Ring with capacity. - - -
public fun create_with_capacity<Element>(len: u64): Ring::Ring<Element>
-
- - - -
-Implementation - - -
public fun create_with_capacity<Element>( len: u64 ):Ring<Element>{
-    let data = Vector::empty<Option::Option<Element>>();
-    let i = 0;
-    while(i < len){
-        Vector::push_back(&mut data , Option::none<Element>());
-        i = i + 1;
-    };
-    Ring {
-        data             : data,
-        insertion_index  : 0,
-        external_index   : 0,
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `is_full` - -is Ring full - - -
public fun is_full<Element>(r: &Ring::Ring<Element>): bool
-
- - - -
-Implementation - - -
public fun is_full<Element>(r: &Ring<Element>):bool{
-    Option::is_some(Vector::borrow(&r.data, r.insertion_index))
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `capacity` - -Return the capacity of the Ring. - - -
public fun capacity<Element>(r: &Ring::Ring<Element>): u64
-
- - - -
-Implementation - - -
public fun capacity<Element>(r: &Ring<Element>): u64{
-    Vector::length( &r.data )
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `push` - -Add element e to the insertion_index of the Ring r. - - -
public fun push<Element>(r: &mut Ring::Ring<Element>, e: Element): Option::Option<Element>
-
- - - -
-Implementation - - -
public fun push<Element> (r: &mut Ring<Element> , e: Element):Option::Option<Element>{
-    let op_e = Vector::borrow_mut<Option::Option<Element>>(&mut r.data, r.insertion_index);
-    let res = if(  Option::is_none<Element>(op_e) ){
-        Option::fill( op_e, e);
-        Option::none<Element>()
-    }else{
-       Option::some<Element>( Option::swap( op_e, e) )
-    };
-    r.insertion_index = ( r.insertion_index + 1 ) % Vector::length(&r.data);
-    r.external_index = r.external_index + 1;
-    res
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `borrow` - -Return a reference to the ith element in the Ring r. - - -
public fun borrow<Element>(r: &Ring::Ring<Element>, i: u64): &Option::Option<Element>
-
- - - -
-Implementation - - -
public fun borrow<Element>(r:& Ring<Element>, i: u64):&Option::Option<Element>{
-    let len = capacity<Element>(r);
-    if( r.external_index > len - 1) {
-        assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow(&r.data, i % len)
-    }else {
-        assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow(&r.data, i )
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the ith element in the Ring r. - - -
public fun borrow_mut<Element>(r: &mut Ring::Ring<Element>, i: u64): &mut Option::Option<Element>
-
- - - -
-Implementation - - -
public fun borrow_mut<Element>(r: &mut Ring<Element>, i: u64):&mut Option::Option<Element>{
-    let len = capacity<Element>(r);
-    if( r.external_index > len - 1) {
-        assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow_mut(&mut r.data, i % len)
-    }else {
-        assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow_mut(&mut r.data, i )
-    }
-
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `index_of` - -Return Option::Option<u64> if e is in the Ring r at index i. -Otherwise, returns Option::none<u64>. - - -
public fun index_of<Element>(r: &Ring::Ring<Element>, e: &Element): Option::Option<u64>
-
- - - -
-Implementation - - -
public fun index_of<Element>(r: &Ring<Element>, e: &Element):Option::Option<u64>{
-    let i = 0;
-    let len = capacity<Element>(r);
-    while ( i < len ) {
-        if ( Option::borrow(Vector::borrow( &r.data, i )) == e) return Option::some(i + r.external_index - len);
-        i = i + 1;
-    };
-    Option::none<u64>()
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `destroy` - -Destroy the Ring r. -Returns the vector saved by ring - - -
public fun destroy<Element>(r: Ring::Ring<Element>): vector<Element>
-
- - - -
-Implementation - - -
public fun destroy<Element>(r: Ring<Element>):vector<Element>{
-    let Ring {
-        data            : data ,
-        insertion_index : _,
-        external_index  : _,
-    } = r ;
-    let len = Vector::length(&data);
-    let i = 0;
-    let vec = Vector::empty<Element>();
-    while ( i < len ) {
-        let op_e = Vector::pop_back( &mut data );
-        if ( Option::is_some(&op_e) ) {
-            Vector::push_back(&mut vec, Option::destroy_some(op_e))
-        }else {
-           Option::destroy_none(op_e)
-        };
-        i = i + 1;
-    };
-    Vector::destroy_empty(data);
-    vec
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
diff --git a/build/StarcoinFramework/docs/STC.md b/build/StarcoinFramework/docs/STC.md index 74bed864..b22272d5 100644 --- a/build/StarcoinFramework/docs/STC.md +++ b/build/StarcoinFramework/docs/STC.md @@ -13,17 +13,25 @@ It uses apis defined in the Token - [Function `initialize`](#0x1_STC_initialize) - [Function `upgrade_from_v1_to_v2`](#0x1_STC_upgrade_from_v1_to_v2) - [Function `initialize_v2`](#0x1_STC_initialize_v2) -- [Function `initialize_v3`](#0x1_STC_initialize_v3) - [Function `is_stc`](#0x1_STC_is_stc) - [Function `burn`](#0x1_STC_burn) - [Function `token_address`](#0x1_STC_token_address) - [Module Specification](#@Module_Specification_1) -
use 0x1::CoreAddresses;
-use 0x1::Errors;
+
use 0x1::ConsensusConfig;
+use 0x1::CoreAddresses;
+use 0x1::Dao;
+use 0x1::ModifyDaoConfigProposal;
+use 0x1::OnChainConfigDao;
+use 0x1::PackageTxnManager;
+use 0x1::RewardConfig;
 use 0x1::Token;
+use 0x1::TransactionPublishOption;
+use 0x1::TransactionTimeoutConfig;
 use 0x1::Treasury;
+use 0x1::UpgradeModuleDaoProposal;
+use 0x1::VMConfig;
 
@@ -106,7 +114,7 @@ precision of STC token. STC initialization. -
public fun initialize(_account: &signer, _voting_delay: u64, _voting_period: u64, _voting_quorum_rate: u8, _min_action_delay: u64)
+
public fun initialize(account: &signer, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64)
 
@@ -116,13 +124,34 @@ STC initialization.
public fun initialize(
-    _account: &signer,
-    _voting_delay: u64,
-    _voting_period: u64,
-    _voting_quorum_rate: u8,
-    _min_action_delay: u64,
+    account: &signer,
+    voting_delay: u64,
+    voting_period: u64,
+    voting_quorum_rate: u8,
+    min_action_delay: u64,
 ) {
-    abort Errors::deprecated(1)
+    Token::register_token<STC>(account, PRECISION);
+    let burn_cap = Token::remove_burn_capability<STC>(account);
+    move_to(account, SharedBurnCapability { cap: burn_cap });
+    Dao::plugin<STC>(
+        account,
+        voting_delay,
+        voting_period,
+        voting_quorum_rate,
+        min_action_delay,
+    );
+    ModifyDaoConfigProposal::plugin<STC>(account);
+    let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(account);
+    UpgradeModuleDaoProposal::plugin<STC>(
+        account,
+        upgrade_plan_cap,
+    );
+    // the following configurations are gov-ed by Dao.
+    OnChainConfigDao::plugin<STC, TransactionPublishOption::TransactionPublishOption>(account);
+    OnChainConfigDao::plugin<STC, VMConfig::VMConfig>(account);
+    OnChainConfigDao::plugin<STC, ConsensusConfig::ConsensusConfig>(account);
+    OnChainConfigDao::plugin<STC, RewardConfig::RewardConfig>(account);
+    OnChainConfigDao::plugin<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>(account);
 }
 
@@ -135,7 +164,7 @@ STC initialization. -
pragma verify = false;
+
include Token::RegisterTokenAbortsIf<STC>{precision: PRECISION};
 
@@ -157,11 +186,11 @@ STC initialization. Implementation -
public fun upgrade_from_v1_to_v2(account: &signer, total_amount: u128, ): Treasury::WithdrawCapability<STC> {
+
public fun upgrade_from_v1_to_v2(account: &signer,total_amount: u128,): Treasury::WithdrawCapability<STC> {
     CoreAddresses::assert_genesis_address(account);
 
     // Mint all stc, and destroy mint capability
-    let total_stc = Token::mint<STC>(account, total_amount - Token::market_cap<STC>());
+    let total_stc = Token::mint<STC>(account, total_amount-Token::market_cap<STC>());
     let withdraw_cap = Treasury::initialize(account, total_stc);
     let mint_cap = Token::remove_mint_capability<STC>(account);
     Token::destroy_mint_capability(mint_cap);
@@ -192,7 +221,7 @@ STC initialization.
 STC initialization.
 
 
-
public fun initialize_v2(_account: &signer, _total_amount: u128, _voting_delay: u64, _voting_period: u64, _voting_quorum_rate: u8, _min_action_delay: u64): Treasury::WithdrawCapability<STC::STC>
+
public fun initialize_v2(account: &signer, total_amount: u128, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64): Treasury::WithdrawCapability<STC::STC>
 
@@ -202,52 +231,12 @@ STC initialization.
public fun initialize_v2(
-    _account: &signer,
-    _total_amount: u128,
-    _voting_delay: u64,
-    _voting_period: u64,
-    _voting_quorum_rate: u8,
-    _min_action_delay: u64,
-): Treasury::WithdrawCapability<STC> {
-    abort Errors::deprecated(1)
-}
-
- - - - - -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `initialize_v3` - -STC initialization. - - -
public fun initialize_v3(account: &signer, total_amount: u128): Treasury::WithdrawCapability<STC::STC>
-
- - - -
-Implementation - - -
public fun initialize_v3(
     account: &signer,
     total_amount: u128,
+    voting_delay: u64,
+    voting_period: u64,
+    voting_quorum_rate: u8,
+    min_action_delay: u64,
 ): Treasury::WithdrawCapability<STC> {
     Token::register_token<STC>(account, PRECISION);
 
@@ -260,6 +249,25 @@ STC initialization.
 
     let burn_cap = Token::remove_burn_capability<STC>(account);
     move_to(account, SharedBurnCapability { cap: burn_cap });
+    Dao::plugin<STC>(
+        account,
+        voting_delay,
+        voting_period,
+        voting_quorum_rate,
+        min_action_delay,
+    );
+    ModifyDaoConfigProposal::plugin<STC>(account);
+    let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(account);
+    UpgradeModuleDaoProposal::plugin<STC>(
+        account,
+        upgrade_plan_cap,
+    );
+    // the following configurations are gov-ed by Dao.
+    OnChainConfigDao::plugin<STC, TransactionPublishOption::TransactionPublishOption>(account);
+    OnChainConfigDao::plugin<STC, VMConfig::VMConfig>(account);
+    OnChainConfigDao::plugin<STC, ConsensusConfig::ConsensusConfig>(account);
+    OnChainConfigDao::plugin<STC, RewardConfig::RewardConfig>(account);
+    OnChainConfigDao::plugin<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>(account);
     withdraw_cap
 }
 
@@ -273,7 +281,7 @@ STC initialization. -
include Token::RegisterTokenAbortsIf<STC> { precision: PRECISION };
+
include Token::RegisterTokenAbortsIf<STC>{precision: PRECISION};
 
diff --git a/build/StarcoinFramework/docs/Signature.md b/build/StarcoinFramework/docs/Signature.md index e819d8cf..ea42a890 100644 --- a/build/StarcoinFramework/docs/Signature.md +++ b/build/StarcoinFramework/docs/Signature.md @@ -10,7 +10,6 @@ Contains functions for [ed25519](https://en.wikipedia.org/wiki/EdDSA) digital si - [Function `ed25519_verify`](#0x1_Signature_ed25519_verify) - [Function `native_ecrecover`](#0x1_Signature_native_ecrecover) - [Function `ecrecover`](#0x1_Signature_ecrecover) -- [Function `secp256k1_verify`](#0x1_Signature_secp256k1_verify) - [Module Specification](#@Module_Specification_0) @@ -116,32 +115,6 @@ recover address from ECDSA signature, if recover fail, return None -
- - - -## Function `secp256k1_verify` - - - -
public fun secp256k1_verify(signature: vector<u8>, addr: vector<u8>, message: vector<u8>): bool
-
- - - -
-Implementation - - -
public fun secp256k1_verify(signature: vector<u8>, addr: vector<u8>, message: vector<u8>) : bool{
-  let receover_address_opt:Option<EVMAddress>  = ecrecover(message, signature);
-  let expect_address =  EVMAddress::new(addr);
-  &Option::destroy_some<EVMAddress>(receover_address_opt) == &expect_address
-}
-
- - -
diff --git a/build/StarcoinFramework/docs/SignedInteger64.md b/build/StarcoinFramework/docs/SignedInteger64.md index 5d4c8fc2..81d8dbda 100644 --- a/build/StarcoinFramework/docs/SignedInteger64.md +++ b/build/StarcoinFramework/docs/SignedInteger64.md @@ -73,7 +73,7 @@ Multiply a u64 integer by a signed integer number.
public fun multiply_u64(num: u64, multiplier: SignedInteger64): SignedInteger64 {
     let product = multiplier.value * num;
-    SignedInteger64 { value: product, is_negative: multiplier.is_negative }
+    SignedInteger64 { value: (product as u64), is_negative: multiplier.is_negative }
 }
 
@@ -111,7 +111,7 @@ Divide a u64 integer by a signed integer number.
public fun divide_u64(num: u64, divisor: SignedInteger64): SignedInteger64 {
     let quotient = num / divisor.value;
-    SignedInteger64 { value: quotient, is_negative: divisor.is_negative }
+    SignedInteger64 { value: (quotient as u64), is_negative: divisor.is_negative }
 }
 
@@ -150,14 +150,14 @@ Sub: num - minus
public fun sub_u64(num: u64, minus: SignedInteger64): SignedInteger64 {
     if (minus.is_negative) {
         let result = num + minus.value;
-        SignedInteger64 { value: result, is_negative: false }
+        SignedInteger64 { value: (result as u64), is_negative: false }
     } else {
-        if (num >= minus.value) {
+        if (num > minus.value)  {
             let result = num - minus.value;
-            SignedInteger64 { value: result, is_negative: false }
+            SignedInteger64 { value: (result as u64), is_negative: false }
         }else {
             let result = minus.value - num;
-            SignedInteger64 { value: result, is_negative: true }
+            SignedInteger64 { value: (result as u64), is_negative: true }
         }
     }
 }
@@ -197,16 +197,16 @@ Add: num + addend
 
 
public fun add_u64(num: u64, addend: SignedInteger64): SignedInteger64 {
     if (addend.is_negative) {
-        if (num >= addend.value) {
-            let result = num - addend.value;
-            SignedInteger64 { value: result, is_negative: false }
-        }else {
-            let result = addend.value - num;
-            SignedInteger64 { value: result, is_negative: true }
-        }
+       if (num > addend.value)  {
+           let result = num - addend.value;
+           SignedInteger64 { value: (result as u64), is_negative: false }
+       }else {
+           let result = addend.value - num;
+           SignedInteger64 { value: (result as u64), is_negative: true }
+       }
     } else {
-        let result = num + addend.value;
-        SignedInteger64 { value: result, is_negative: false }
+         let result = num + addend.value;
+         SignedInteger64 { value: (result as u64), is_negative: false }
     }
 }
 
diff --git a/build/StarcoinFramework/docs/StarcoinVerifier.md b/build/StarcoinFramework/docs/StarcoinVerifier.md deleted file mode 100644 index 21650547..00000000 --- a/build/StarcoinFramework/docs/StarcoinVerifier.md +++ /dev/null @@ -1,703 +0,0 @@ - - - -# Module `0x1::StarcoinVerifier` - - - -- [Struct `AccountState`](#0x1_StarcoinVerifier_AccountState) -- [Struct `StateProof`](#0x1_StarcoinVerifier_StateProof) -- [Struct `SparseMerkleProof`](#0x1_StarcoinVerifier_SparseMerkleProof) -- [Struct `SMTNode`](#0x1_StarcoinVerifier_SMTNode) -- [Constants](#@Constants_0) -- [Function `bcs_deserialize_account_state`](#0x1_StarcoinVerifier_bcs_deserialize_account_state) -- [Function `new_state_proof`](#0x1_StarcoinVerifier_new_state_proof) -- [Function `new_sparse_merkle_proof`](#0x1_StarcoinVerifier_new_sparse_merkle_proof) -- [Function `new_smt_node`](#0x1_StarcoinVerifier_new_smt_node) -- [Function `empty_smt_node`](#0x1_StarcoinVerifier_empty_smt_node) -- [Function `verify_state_proof`](#0x1_StarcoinVerifier_verify_state_proof) -- [Function `verify_smp`](#0x1_StarcoinVerifier_verify_smp) -- [Function `compute_smp_root_by_path_and_node_hash`](#0x1_StarcoinVerifier_compute_smp_root_by_path_and_node_hash) -- [Function `placeholder`](#0x1_StarcoinVerifier_placeholder) -- [Function `create_literal_hash`](#0x1_StarcoinVerifier_create_literal_hash) -- [Function `hash_key`](#0x1_StarcoinVerifier_hash_key) -- [Function `hash_value`](#0x1_StarcoinVerifier_hash_value) -- [Function `count_common_prefix`](#0x1_StarcoinVerifier_count_common_prefix) -- [Function `get_bit_at_from_msb`](#0x1_StarcoinVerifier_get_bit_at_from_msb) - - -
use 0x1::BCS;
-use 0x1::Hash;
-use 0x1::Option;
-use 0x1::StructuredHash;
-use 0x1::Vector;
-
- - - - - -## Struct `AccountState` - - - -
struct AccountState has copy, drop, store
-
- - - -
-Fields - - -
-
-storage_roots: vector<Option::Option<vector<u8>>> -
-
- -
-
- - -
- - - -## Struct `StateProof` - - - -
struct StateProof has copy, drop, store
-
- - - -
-Fields - - -
-
-account_proof: StarcoinVerifier::SparseMerkleProof -
-
- - * Account state's proof for global state root. - -
-
-account_state: vector<u8> -
-
- - * Account state including storage roots. - -
-
-proof: StarcoinVerifier::SparseMerkleProof -
-
- - * State's proof for account storage root. - -
-
- - -
- - - -## Struct `SparseMerkleProof` - - - -
struct SparseMerkleProof has copy, drop, store
-
- - - -
-Fields - - -
-
-siblings: vector<vector<u8>> -
-
- -
-
-leaf: StarcoinVerifier::SMTNode -
-
- -
-
- - -
- - - -## Struct `SMTNode` - - - -
struct SMTNode has copy, drop, store
-
- - - -
-Fields - - -
-
-hash1: vector<u8> -
-
- -
-
-hash2: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ACCOUNT_STORAGE_INDEX_RESOURCE: u64 = 1;
-
- - - - - - - -
const BLOB_HASH_PREFIX: vector<u8> = [66, 108, 111, 98];
-
- - - - - - - -
const DEFAULT_VALUE: vector<u8> = [];
-
- - - - - - - -
const ERROR_ACCOUNT_STORAGE_ROOTS: u64 = 101;
-
- - - - - - - -
const ERROR_LITERAL_HASH_WRONG_LENGTH: u64 = 102;
-
- - - - - - - -
const HASH_LEN_IN_BITS: u64 = 256;
-
- - - - - - - -
const SPARSE_MERKLE_INTERNAL_NODE: vector<u8> = [83, 112, 97, 114, 115, 101, 77, 101, 114, 107, 108, 101, 73, 110, 116, 101, 114, 110, 97, 108, 78, 111, 100, 101];
-
- - - - - - - -
const SPARSE_MERKLE_LEAF_NODE: vector<u8> = [83, 112, 97, 114, 115, 101, 77, 101, 114, 107, 108, 101, 76, 101, 97, 102, 78, 111, 100, 101];
-
- - - - - - - -
const SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL: vector<u8> = [83, 80, 65, 82, 83, 69, 95, 77, 69, 82, 75, 76, 69, 95, 80, 76, 65, 67, 69, 72, 79, 76, 68, 69, 82, 95, 72, 65, 83, 72];
-
- - - - - -## Function `bcs_deserialize_account_state` - - - -
public fun bcs_deserialize_account_state(data: &vector<u8>): StarcoinVerifier::AccountState
-
- - - -
-Implementation - - -
public fun bcs_deserialize_account_state(data: &vector<u8>): AccountState {
-    let (vec, _) = BCS::deserialize_option_bytes_vector(data, 0);
-    AccountState{
-        storage_roots: vec
-    }
-}
-
- - - -
- - - -## Function `new_state_proof` - - - -
public fun new_state_proof(account_proof: StarcoinVerifier::SparseMerkleProof, account_state: vector<u8>, proof: StarcoinVerifier::SparseMerkleProof): StarcoinVerifier::StateProof
-
- - - -
-Implementation - - -
public fun new_state_proof(account_proof: SparseMerkleProof, account_state: vector<u8>, proof: SparseMerkleProof): StateProof {
-    StateProof{
-        account_proof,
-        account_state,
-        proof,
-    }
-}
-
- - - -
- - - -## Function `new_sparse_merkle_proof` - - - -
public fun new_sparse_merkle_proof(siblings: vector<vector<u8>>, leaf: StarcoinVerifier::SMTNode): StarcoinVerifier::SparseMerkleProof
-
- - - -
-Implementation - - -
public fun new_sparse_merkle_proof(siblings: vector<vector<u8>>, leaf: SMTNode): SparseMerkleProof {
-    SparseMerkleProof{
-        siblings,
-        leaf,
-    }
-}
-
- - - -
- - - -## Function `new_smt_node` - - - -
public fun new_smt_node(hash1: vector<u8>, hash2: vector<u8>): StarcoinVerifier::SMTNode
-
- - - -
-Implementation - - -
public fun new_smt_node(hash1: vector<u8>, hash2: vector<u8>): SMTNode {
-    SMTNode{
-        hash1,
-        hash2,
-    }
-}
-
- - - -
- - - -## Function `empty_smt_node` - - - -
public fun empty_smt_node(): StarcoinVerifier::SMTNode
-
- - - -
-Implementation - - -
public fun empty_smt_node(): SMTNode {
-    SMTNode{
-        hash1: Vector::empty(),
-        hash2: Vector::empty(),
-    }
-}
-
- - - -
- - - -## Function `verify_state_proof` - - - -
public fun verify_state_proof(state_proof: &StarcoinVerifier::StateProof, state_root: &vector<u8>, account_address: address, resource_struct_tag: &vector<u8>, state: &vector<u8>): bool
-
- - - -
-Implementation - - -
public fun verify_state_proof(state_proof: &StateProof, state_root: &vector<u8>,
-                                       account_address: address, resource_struct_tag: &vector<u8>,
-                                       state: &vector<u8>): bool {
-    let accountState: AccountState = bcs_deserialize_account_state(&state_proof.account_state);
-    assert!(Vector::length(&accountState.storage_roots) > ACCOUNT_STORAGE_INDEX_RESOURCE, ERROR_ACCOUNT_STORAGE_ROOTS);
-
-    // First, verify state for storage root.
-    let storageRoot = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE));
-    let ok: bool = verify_smp(&state_proof.proof.siblings,
-        &state_proof.proof.leaf,
-        storageRoot,
-        resource_struct_tag, // resource struct tag BCS serialized as key
-        state);
-    if (!ok) {
-        return false
-    };
-
-    // Then, verify account state for global state root.
-    ok = verify_smp(&state_proof.account_proof.siblings,
-        &state_proof.account_proof.leaf,
-        state_root,
-        &BCS::to_bytes<address>(&account_address), // account address as key
-        &state_proof.account_state,
-    );
-    ok
-}
-
- - - -
- - - -## Function `verify_smp` - -Verify sparse merkle proof by key and value. - - -
public fun verify_smp(sibling_nodes: &vector<vector<u8>>, leaf_data: &StarcoinVerifier::SMTNode, expected_root: &vector<u8>, key: &vector<u8>, value: &vector<u8>): bool
-
- - - -
-Implementation - - -
public fun verify_smp(sibling_nodes: &vector<vector<u8>>, leaf_data: &SMTNode, expected_root: &vector<u8>, key: &vector<u8>, value: &vector<u8>): bool {
-    let path = hash_key(key);
-    let current_hash: vector<u8>;
-    if (*value == DEFAULT_VALUE) {
-        // Non-membership proof.
-        if (empty_smt_node() == *leaf_data) {
-            current_hash = placeholder();
-        } else {
-            if (*&leaf_data.hash1 == *&path) {
-                return false
-            };
-            if (!(count_common_prefix(&leaf_data.hash1, &path) >= Vector::length(sibling_nodes))) {
-                return false
-            };
-            current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data);
-        };
-    } else {
-        // Membership proof.
-        if (empty_smt_node() == *leaf_data) {
-            return false
-        };
-        if (*&leaf_data.hash1 != *&path) {
-            return false
-        };
-        let value_hash = hash_value(value);
-        if (*&leaf_data.hash2 != value_hash) {
-            return false
-        };
-        current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data);
-    };
-
-    current_hash = compute_smp_root_by_path_and_node_hash(sibling_nodes, &path, ¤t_hash);
-    current_hash == *expected_root
-}
-
- - - -
- - - -## Function `compute_smp_root_by_path_and_node_hash` - - - -
public fun compute_smp_root_by_path_and_node_hash(sibling_nodes: &vector<vector<u8>>, path: &vector<u8>, node_hash: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
public fun compute_smp_root_by_path_and_node_hash(sibling_nodes: &vector<vector<u8>>, path: &vector<u8>, node_hash: &vector<u8>): vector<u8> {
-    let current_hash = *node_hash;
-    let i = 0;
-    let proof_length = Vector::length(sibling_nodes);
-    while (i < proof_length) {
-        let sibling = *Vector::borrow(sibling_nodes, i);
-        let bit = get_bit_at_from_msb(path, proof_length - i - 1);
-        let internal_node = if (bit) {
-            SMTNode{ hash1: sibling, hash2: current_hash }
-        } else {
-            SMTNode{ hash1: current_hash, hash2: sibling }
-        };
-        current_hash = StructuredHash::hash(SPARSE_MERKLE_INTERNAL_NODE, &internal_node);
-        i = i + 1;
-    };
-    current_hash
-}
-
- - - -
- - - -## Function `placeholder` - - - -
public fun placeholder(): vector<u8>
-
- - - -
-Implementation - - -
public fun placeholder(): vector<u8> {
-    create_literal_hash(&SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL)
-}
-
- - - -
- - - -## Function `create_literal_hash` - - - -
public fun create_literal_hash(word: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
public fun create_literal_hash(word: &vector<u8>): vector<u8> {
-    if (Vector::length(word)  <= 32) {
-        let lenZero = 32 - Vector::length(word);
-        let i = 0;
-        let r = *word;
-        while (i < lenZero) {
-            Vector::push_back(&mut r, 0);
-            i = i + 1;
-        };
-        return r
-    };
-    abort ERROR_LITERAL_HASH_WRONG_LENGTH
-}
-
- - - -
- - - -## Function `hash_key` - - - -
fun hash_key(key: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
fun hash_key(key: &vector<u8>): vector<u8> {
-    Hash::sha3_256(*key)
-}
-
- - - -
- - - -## Function `hash_value` - - - -
fun hash_value(value: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
fun hash_value(value: &vector<u8>): vector<u8> {
-    StructuredHash::hash(BLOB_HASH_PREFIX, value)
-}
-
- - - -
- - - -## Function `count_common_prefix` - - - -
fun count_common_prefix(data1: &vector<u8>, data2: &vector<u8>): u64
-
- - - -
-Implementation - - -
fun count_common_prefix(data1: &vector<u8>, data2: &vector<u8>): u64 {
-    let count = 0;
-    let i = 0;
-    while ( i < Vector::length(data1) * 8) {
-        if (get_bit_at_from_msb(data1, i) == get_bit_at_from_msb(data2, i)) {
-            count = count + 1;
-        } else {
-            break
-        };
-        i = i + 1;
-    };
-    count
-}
-
- - - -
- - - -## Function `get_bit_at_from_msb` - - - -
fun get_bit_at_from_msb(data: &vector<u8>, index: u64): bool
-
- - - -
-Implementation - - -
fun get_bit_at_from_msb(data: &vector<u8>, index: u64): bool {
-    let pos = index / 8;
-    let bit = (7 - index % 8);
-    (*Vector::borrow(data, pos) >> (bit as u8)) & 1u8 != 0
-}
-
- - - -
diff --git a/build/StarcoinFramework/docs/StdlibUpgradeScripts.md b/build/StarcoinFramework/docs/StdlibUpgradeScripts.md index 05209e21..6bf98043 100644 --- a/build/StarcoinFramework/docs/StdlibUpgradeScripts.md +++ b/build/StarcoinFramework/docs/StdlibUpgradeScripts.md @@ -15,55 +15,26 @@ The module for StdlibUpgrade init scripts - [Function `do_upgrade_from_v6_to_v7_with_language_version`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v6_to_v7_with_language_version) - [Function `upgrade_from_v7_to_v8`](#0x1_StdlibUpgradeScripts_upgrade_from_v7_to_v8) - [Function `do_upgrade_from_v7_to_v8`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v7_to_v8) -- [Function `upgrade_from_v11_to_v12`](#0x1_StdlibUpgradeScripts_upgrade_from_v11_to_v12) -- [Function `do_upgrade_from_v11_to_v12`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v11_to_v12) -- [Function `upgrade_from_v12_to_v13`](#0x1_StdlibUpgradeScripts_upgrade_from_v12_to_v13) -- [Function `do_upgrade_from_v12_to_v13`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v12_to_v13) - [Module Specification](#@Module_Specification_0)
use 0x1::Account;
-use 0x1::AnyMemberPlugin;
-use 0x1::Block;
 use 0x1::Collection;
 use 0x1::Config;
-use 0x1::ConfigProposalPlugin;
-use 0x1::ConsensusConfig;
 use 0x1::CoreAddresses;
-use 0x1::DAOExtensionPoint;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAORegistry;
-use 0x1::Dao;
-use 0x1::GasOracleProposalPlugin;
 use 0x1::GenesisNFT;
 use 0x1::GenesisSignerCapability;
-use 0x1::GrantProposalPlugin;
-use 0x1::InstallPluginProposalPlugin;
 use 0x1::LanguageVersion;
-use 0x1::MemberProposalPlugin;
-use 0x1::MintProposalPlugin;
-use 0x1::ModifyDaoConfigProposal;
 use 0x1::NFT;
 use 0x1::Offer;
 use 0x1::OnChainConfigDao;
 use 0x1::Oracle;
-use 0x1::PackageTxnManager;
-use 0x1::RewardConfig;
 use 0x1::STC;
 use 0x1::STCUSDOracle;
-use 0x1::StakeToSBTPlugin;
-use 0x1::StarcoinDAO;
 use 0x1::Timestamp;
 use 0x1::Token;
-use 0x1::TransactionPublishOption;
-use 0x1::TransactionTimeoutConfig;
 use 0x1::Treasury;
-use 0x1::TreasuryPlugin;
 use 0x1::TreasuryWithdrawDaoProposal;
-use 0x1::UpgradeModuleDaoProposal;
-use 0x1::UpgradeModulePlugin;
-use 0x1::VMConfig;
-use 0x1::WithdrawPlugin;
 
@@ -84,7 +55,7 @@ Stdlib upgrade script from v2 to v3 Implementation -
public(script) fun upgrade_from_v2_to_v3(account: signer, total_stc_amount: u128) {
+
public(script) fun upgrade_from_v2_to_v3(account: signer, total_stc_amount: u128 ) {
     CoreAddresses::assert_genesis_address(&account);
 
     let withdraw_cap = STC::upgrade_from_v1_to_v2(&account, total_stc_amount);
@@ -95,7 +66,7 @@ Stdlib upgrade script from v2 to v3
     Collection::return_collection(mint_keys);
 
     let now = Timestamp::now_seconds();
-    let linear_withdraw_cap = Treasury::issue_linear_withdraw_capability(&mut withdraw_cap, total - minted, period - (now - start_time));
+    let linear_withdraw_cap = Treasury::issue_linear_withdraw_capability(&mut withdraw_cap, total-minted, period - (now - start_time));
     // Lock the TreasuryWithdrawCapability to Dao
     TreasuryWithdrawDaoProposal::plugin(&account, withdraw_cap);
     // Give a LinearWithdrawCapability Offer to association, association need to take the offer, and destroy old LinearTimeMintKey.
@@ -123,7 +94,7 @@ association account should call this script after upgrade from v2 to v3.
 Implementation
 
 
-
public(script) fun take_linear_withdraw_capability(signer: signer) {
+
public(script) fun take_linear_withdraw_capability(signer: signer){
     let offered = Offer::redeem<LinearWithdrawCapability<STC>>(&signer, CoreAddresses::GENESIS_ADDRESS());
     Treasury::add_linear_withdraw_capability(&signer, offered);
     let mint_key = Collection::take<LinearTimeMintKey<STC>>(&signer);
@@ -182,7 +153,7 @@ association account should call this script after upgrade from v2 to v3.
 
 
 
public(script) fun upgrade_from_v5_to_v6(sender: signer) {
-    Self::do_upgrade_from_v5_to_v6(&sender)
+   Self::do_upgrade_from_v5_to_v6(&sender)
 }
 
@@ -231,7 +202,7 @@ deprecated, use do_upgrade_from_v6_to_v7_with_language_version.
public fun do_upgrade_from_v6_to_v7(sender: &signer) {
-    do_upgrade_from_v6_to_v7_with_language_version(sender, 2);
+   do_upgrade_from_v6_to_v7_with_language_version(sender, 2);
 }
 
@@ -322,150 +293,6 @@ deprecated, use do_upgrade_from_v6_to_v7_with_language_version. - - - - -## Function `upgrade_from_v11_to_v12` - - - -
public(script) fun upgrade_from_v11_to_v12()
-
- - - -
-Implementation - - -
public(script) fun upgrade_from_v11_to_v12() {
-    do_upgrade_from_v11_to_v12();
-}
-
- - - -
- - - -## Function `do_upgrade_from_v11_to_v12` - - - -
public fun do_upgrade_from_v11_to_v12()
-
- - - -
-Implementation - - -
public fun do_upgrade_from_v11_to_v12() {
-    let genessis_signer = GenesisSignerCapability::get_genesis_signer();
-    Block::checkpoints_init();
-    DAORegistry::initialize();
-
-    DAOExtensionPoint::initialize();
-    DAOPluginMarketplace::initialize();
-
-    AnyMemberPlugin::initialize(&genessis_signer);
-    ConfigProposalPlugin::initialize(&genessis_signer);
-    GrantProposalPlugin::initialize(&genessis_signer);
-    InstallPluginProposalPlugin::initialize(&genessis_signer);
-    MemberProposalPlugin::initialize(&genessis_signer);
-    MintProposalPlugin::initialize(&genessis_signer);
-    StakeToSBTPlugin::initialize(&genessis_signer);
-    UpgradeModulePlugin::initialize(&genessis_signer);
-    GasOracleProposalPlugin::initialize(&genessis_signer);
-    TreasuryPlugin::initialize(&genessis_signer);
-
-    //TODO : config rate need mind
-    // voting_delay: 60000 ms
-    // voting_period: 3600000 ms
-    // voting_quorum_rate: 4
-    // min_action_delay: 3600000 ms
-    let signer_cap = Account::get_genesis_capability();
-    let upgrade_plan_cap = UpgradeModuleDaoProposal::get_genesis_upgrade_cap<STC>();
-    StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, Dao::voting_delay<STC>(), Dao::voting_period<STC>(), Dao::voting_quorum_rate<STC>(), Dao::min_action_delay<STC>(), 1000 * 1000 * 1000 * 1000);
-
-    StarcoinDAO::delegate_config_capability<STC, TransactionPublishOption::TransactionPublishOption>(
-        OnChainConfigDao::config_cap<STC, TransactionPublishOption::TransactionPublishOption>());
-    StarcoinDAO::delegate_config_capability<STC, VMConfig::VMConfig>(
-        OnChainConfigDao::config_cap<STC, VMConfig::VMConfig>());
-    StarcoinDAO::delegate_config_capability<STC, ConsensusConfig::ConsensusConfig>(
-        OnChainConfigDao::config_cap<STC, ConsensusConfig::ConsensusConfig>());
-    StarcoinDAO::delegate_config_capability<STC, RewardConfig::RewardConfig>(
-        OnChainConfigDao::config_cap<STC, RewardConfig::RewardConfig>());
-    StarcoinDAO::delegate_config_capability<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>(
-        OnChainConfigDao::config_cap<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>());
-    StarcoinDAO::delegate_config_capability<STC, LanguageVersion::LanguageVersion>(
-        OnChainConfigDao::config_cap<STC, LanguageVersion::LanguageVersion>());
-
-    let signer = GenesisSignerCapability::get_genesis_signer();
-    let cap = TreasuryWithdrawDaoProposal::takeout_withdraw_capability<STC>(&signer);
-    TreasuryPlugin::delegate_capability<STC>(&signer, cap);
-    StarcoinDAO::set_treasury_withdraw_proposal_scale(100);
-
-    // clean old DAO resources
-    ModifyDaoConfigProposal::destroy_modify_config_capability<STC>(&genessis_signer);
-}
-
- - - -
- - - -## Function `upgrade_from_v12_to_v13` - - - -
public(script) fun upgrade_from_v12_to_v13()
-
- - - -
-Implementation - - -
public(script) fun upgrade_from_v12_to_v13() {
-    do_upgrade_from_v12_to_v13();
-}
-
- - - -
- - - -## Function `do_upgrade_from_v12_to_v13` - - - -
public fun do_upgrade_from_v12_to_v13()
-
- - - -
-Implementation - - -
public fun do_upgrade_from_v12_to_v13() {
-    let genessis_signer = GenesisSignerCapability::get_genesis_signer();
-    WithdrawPlugin::initialize(&genessis_signer);
-    StarcoinDAO::upgrade_dao();
-}
-
- - -
diff --git a/build/StarcoinFramework/docs/Token.md b/build/StarcoinFramework/docs/Token.md index a32c5fb7..ec75f7fb 100644 --- a/build/StarcoinFramework/docs/Token.md +++ b/build/StarcoinFramework/docs/Token.md @@ -45,7 +45,6 @@ Token implementation of Starcoin. - [Function `is_same_token`](#0x1_Token_is_same_token) - [Function `token_address`](#0x1_Token_token_address) - [Function `token_code`](#0x1_Token_token_code) -- [Function `type_of`](#0x1_Token_type_of) - [Function `name_of`](#0x1_Token_name_of) - [Function `name_of_token`](#0x1_Token_name_of_token) - [Module Specification](#@Module_Specification_1) @@ -1710,30 +1709,6 @@ does not matter for the verification of callers. - - - - -## Function `type_of` - - - -
public(friend) fun type_of<T>(): (address, vector<u8>, vector<u8>)
-
- - - -
-Implementation - - -
public (friend) fun type_of<T>(): (address, vector<u8>, vector<u8>){
-    name_of<T>()
-}
-
- - -
@@ -1743,7 +1718,7 @@ does not matter for the verification of callers. Return Token's module address, module name, and type name of TokenType. -
fun name_of<TokenType>(): (address, vector<u8>, vector<u8>)
+
fun name_of<TokenType: store>(): (address, vector<u8>, vector<u8>)
 
@@ -1752,7 +1727,7 @@ Return Token's module address, module name, and type name of TokenTypeImplementation -
native fun name_of<TokenType>(): (address, vector<u8>, vector<u8>);
+
native fun name_of<TokenType: store>(): (address, vector<u8>, vector<u8>);
 
diff --git a/build/StarcoinFramework/docs/TransactionManager.md b/build/StarcoinFramework/docs/TransactionManager.md index b1686d9e..6254c35f 100644 --- a/build/StarcoinFramework/docs/TransactionManager.md +++ b/build/StarcoinFramework/docs/TransactionManager.md @@ -23,12 +23,9 @@ use 0x1::CoreAddresses; use 0x1::Epoch; use 0x1::Errors; -use 0x1::GasOracle; -use 0x1::GasOracleProposalPlugin; use 0x1::PackageTxnManager; use 0x1::STC; use 0x1::Signer; -use 0x1::StarcoinDAO; use 0x1::Timestamp; use 0x1::Token; use 0x1::TransactionFee; @@ -157,21 +154,13 @@ It verifies: // Check that the chain ID stored on-chain matches the chain ID // specified by the transaction assert!(ChainId::get() == chain_id, Errors::invalid_argument(EPROLOGUE_BAD_CHAIN_ID)); - let (stc_price,scaling_factor)= if (!STC::is_stc<TokenType>()){ - (GasOracleProposalPlugin::gas_oracle_read<StarcoinDAO, TokenType>(),GasOracle::get_scaling_factor<TokenType>()) - }else{ - (1,1) - }; - - Account::txn_prologue_v2<TokenType>( + Account::txn_prologue<TokenType>( &account, txn_sender, txn_sequence_number, txn_authentication_key_preimage, txn_gas_price, txn_max_gas_units, - stc_price, - scaling_factor, ); assert!( TransactionTimeout::is_valid_transaction_timestamp(txn_expiration_time), @@ -221,6 +210,8 @@ It verifies: include Timestamp::AbortsIfTimestampNotExists; include Block::AbortsIfBlockMetadataNotExist; aborts_if txn_gas_price * txn_max_gas_units > 0 && !exists<Account::Balance<TokenType>>(txn_sender); +aborts_if txn_gas_price * txn_max_gas_units > 0 && StarcoinFramework::Token::spec_token_code<TokenType>() != StarcoinFramework::Token::spec_token_code<STC>(); +aborts_if txn_gas_price * txn_max_gas_units > 0 && global<Account::Balance<TokenType>>(txn_sender).token.value < txn_gas_price * txn_max_gas_units; aborts_if txn_gas_price * txn_max_gas_units > 0 && txn_sequence_number >= max_u64(); aborts_if txn_sequence_number < global<Account::Account>(txn_sender).sequence_number; aborts_if txn_sequence_number != global<Account::Account>(txn_sender).sequence_number; @@ -332,13 +323,7 @@ It collects gas and bumps the sequence number success: bool, ) { CoreAddresses::assert_genesis_address(&account); - let (stc_price,scaling_factor) = - if (!STC::is_stc<TokenType>()){ - (GasOracleProposalPlugin::gas_oracle_read<StarcoinDAO, TokenType>(),GasOracle::get_scaling_factor<TokenType>()) - }else{ - (1,1) - }; - Account::txn_epilogue_v3<TokenType>( + Account::txn_epilogue_v2<TokenType>( &account, txn_sender, txn_sequence_number, @@ -346,8 +331,6 @@ It collects gas and bumps the sequence number txn_gas_price, txn_max_gas_units, gas_units_remaining, - stc_price, - scaling_factor ); if (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE) { PackageTxnManager::package_txn_epilogue( diff --git a/build/StarcoinFramework/docs/TransactionPublishOption.md b/build/StarcoinFramework/docs/TransactionPublishOption.md index cc211f66..9507c62a 100644 --- a/build/StarcoinFramework/docs/TransactionPublishOption.md +++ b/build/StarcoinFramework/docs/TransactionPublishOption.md @@ -77,31 +77,31 @@ We represent these as the following resource. - + +The script hash already exists in the allowlist -
const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0;
+
const EALLOWLIST_ALREADY_CONTAINS_SCRIPT: u64 = 1002;
 
- + -The script hash already exists in the allowlist +The script hash has an invalid length -
const EALLOWLIST_ALREADY_CONTAINS_SCRIPT: u64 = 1002;
+
const EINVALID_SCRIPT_HASH: u64 = 1001;
 
- + -The script hash has an invalid length -
const EINVALID_SCRIPT_HASH: u64 = 1001;
+
const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0;
 
diff --git a/build/StarcoinFramework/docs/TreasuryWithdrawDaoProposal.md b/build/StarcoinFramework/docs/TreasuryWithdrawDaoProposal.md index 2854c0c7..0e13d8cc 100644 --- a/build/StarcoinFramework/docs/TreasuryWithdrawDaoProposal.md +++ b/build/StarcoinFramework/docs/TreasuryWithdrawDaoProposal.md @@ -10,7 +10,6 @@ TreasuryWithdrawDaoProposal is a dao proposal for withdraw Token from Treasury. - [Struct `WithdrawToken`](#0x1_TreasuryWithdrawDaoProposal_WithdrawToken) - [Constants](#@Constants_0) - [Function `plugin`](#0x1_TreasuryWithdrawDaoProposal_plugin) -- [Function `takeout_withdraw_capability`](#0x1_TreasuryWithdrawDaoProposal_takeout_withdraw_capability) - [Function `propose_withdraw`](#0x1_TreasuryWithdrawDaoProposal_propose_withdraw) - [Function `execute_withdraw_proposal`](#0x1_TreasuryWithdrawDaoProposal_execute_withdraw_proposal) - [Function `withdraw_for_block_reward`](#0x1_TreasuryWithdrawDaoProposal_withdraw_for_block_reward) @@ -109,11 +108,12 @@ WithdrawToken request. - + +Only receiver can execute TreasuryWithdrawDaoProposal -
const ERR_CAPABILITY_NOT_EXIST: u64 = 104;
+
const ERR_NEED_RECEIVER_TO_EXECUTE: u64 = 102;
 
@@ -128,16 +128,6 @@ The withdraw amount of propose is too many. - - -Only receiver can execute TreasuryWithdrawDaoProposal - - -
const ERR_NEED_RECEIVER_TO_EXECUTE: u64 = 102;
-
- - - ## Function `plugin` @@ -182,37 +172,6 @@ Should be called by token issuer. - - - - -## Function `takeout_withdraw_capability` - -withdraw Treasury::WithdrawCapability - - -
public fun takeout_withdraw_capability<TokenT: store>(sender: &signer): Treasury::WithdrawCapability<TokenT>
-
- - - -
-Implementation - - -
public fun takeout_withdraw_capability<TokenT: store>(sender: &signer): Treasury::WithdrawCapability<TokenT>
-acquires WrappedWithdrawCapability {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-
-    assert!(exists<WrappedWithdrawCapability<TokenT>>(Signer::address_of(sender)), Errors::not_published(ERR_CAPABILITY_NOT_EXIST));
-    let WrappedWithdrawCapability<TokenT> { cap } = move_from<WrappedWithdrawCapability<TokenT>>(Signer::address_of(sender));
-    cap
-}
-
- - -
diff --git a/build/StarcoinFramework/docs/U256.md b/build/StarcoinFramework/docs/U256.md index 4abb01ba..4236f4d3 100644 --- a/build/StarcoinFramework/docs/U256.md +++ b/build/StarcoinFramework/docs/U256.md @@ -22,6 +22,8 @@ Implementation u256. - [Function `div`](#0x1_U256_div) - [Function `rem`](#0x1_U256_rem) - [Function `pow`](#0x1_U256_pow) +- [Function `add_nocarry`](#0x1_U256_add_nocarry) +- [Function `sub_noborrow`](#0x1_U256_sub_noborrow) - [Function `from_bytes`](#0x1_U256_from_bytes) - [Function `native_add`](#0x1_U256_native_add) - [Function `native_sub`](#0x1_U256_native_sub) @@ -32,7 +34,8 @@ Implementation u256. - [Module Specification](#@Module_Specification_1) -
use 0x1::Errors;
+
use 0x1::Arith;
+use 0x1::Errors;
 use 0x1::Vector;
 
@@ -675,6 +678,79 @@ vector should always has two elements. + + + + +## Function `add_nocarry` + +move implementation of native_add. + + +
fun add_nocarry(a: &mut U256::U256, b: &U256::U256)
+
+ + + +
+Implementation + + +
fun add_nocarry(a: &mut U256, b: &U256) {
+    let carry = 0;
+    let idx = 0;
+    let len = (WORD as u64);
+    while (idx < len) {
+        let a_bit = Vector::borrow_mut(&mut a.bits, idx);
+        let b_bit = Vector::borrow(&b.bits, idx);
+        *a_bit = StarcoinFramework::Arith::adc(*a_bit, *b_bit, &mut carry);
+        idx = idx + 1;
+    };
+
+    // check overflow
+    assert!(carry == 0, 100);
+}
+
+ + + +
+ + + +## Function `sub_noborrow` + +move implementation of native_sub. + + +
fun sub_noborrow(a: &mut U256::U256, b: &U256::U256)
+
+ + + +
+Implementation + + +
fun sub_noborrow(a: &mut U256, b: &U256) {
+    let borrow = 0;
+    let idx = 0;
+    let len = (WORD as u64);
+    while (idx < len) {
+        let a_bit = Vector::borrow_mut(&mut a.bits, idx);
+        let b_bit = Vector::borrow(&b.bits, idx);
+        *a_bit = StarcoinFramework::Arith::sbb(*a_bit, *b_bit, &mut borrow);
+        idx = idx + 1;
+    };
+
+    // check overflow
+    assert!(borrow == 0, 100);
+
+}
+
+ + +
diff --git a/build/StarcoinFramework/docs/UpgradeModuleDaoProposal.md b/build/StarcoinFramework/docs/UpgradeModuleDaoProposal.md index fc089941..add8f904 100644 --- a/build/StarcoinFramework/docs/UpgradeModuleDaoProposal.md +++ b/build/StarcoinFramework/docs/UpgradeModuleDaoProposal.md @@ -11,7 +11,6 @@ UpgradeModuleDaoProposal is a proposal moudle used to upgrade contract codes und - [Struct `UpgradeModuleV2`](#0x1_UpgradeModuleDaoProposal_UpgradeModuleV2) - [Constants](#@Constants_0) - [Function `plugin`](#0x1_UpgradeModuleDaoProposal_plugin) -- [Function `get_genesis_upgrade_cap`](#0x1_UpgradeModuleDaoProposal_get_genesis_upgrade_cap) - [Function `propose_module_upgrade_v2`](#0x1_UpgradeModuleDaoProposal_propose_module_upgrade_v2) - [Function `submit_module_upgrade_plan`](#0x1_UpgradeModuleDaoProposal_submit_module_upgrade_plan) - [Module Specification](#@Module_Specification_1) @@ -214,28 +213,16 @@ If this goverment can upgrade module, call this to register capability. - - - - -## Function `get_genesis_upgrade_cap` + -
public(friend) fun get_genesis_upgrade_cap<TokenT: store>(): PackageTxnManager::UpgradePlanCapability
-
- - - -
-Implementation - - -
public (friend) fun get_genesis_upgrade_cap<TokenT:store>():PackageTxnManager::UpgradePlanCapability acquires UpgradeModuleCapability{
-    let UpgradeModuleCapability<TokenT>{
-        cap
-    } = move_from(Token::token_address<TokenT>());
-    cap
+
schema AbortIfUnableUpgrade<TokenT> {
+    module_address: address;
+    let token_issuer = Token::SPEC_TOKEN_TEST_ADDRESS();
+    aborts_if !exists<UpgradeModuleCapability<TokenT>>(token_issuer);
+    let cap = global<UpgradeModuleCapability<TokenT>>(token_issuer).cap;
+    aborts_if PackageTxnManager::account_address(cap) != module_address;
 }
 
diff --git a/build/StarcoinFramework/source_maps/Account.mvsm b/build/StarcoinFramework/source_maps/Account.mvsm index 356adf3b..b1c5d6e5 100644 Binary files a/build/StarcoinFramework/source_maps/Account.mvsm and b/build/StarcoinFramework/source_maps/Account.mvsm differ diff --git a/build/StarcoinFramework/source_maps/AccountScripts.mvsm b/build/StarcoinFramework/source_maps/AccountScripts.mvsm index 58f14083..ae3221c7 100644 Binary files a/build/StarcoinFramework/source_maps/AccountScripts.mvsm and b/build/StarcoinFramework/source_maps/AccountScripts.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Arith.mvsm b/build/StarcoinFramework/source_maps/Arith.mvsm index 2d249cc2..2d86c319 100644 Binary files a/build/StarcoinFramework/source_maps/Arith.mvsm and b/build/StarcoinFramework/source_maps/Arith.mvsm differ diff --git a/build/StarcoinFramework/source_maps/BCS.mvsm b/build/StarcoinFramework/source_maps/BCS.mvsm index b6cf0c12..55ae8abc 100644 Binary files a/build/StarcoinFramework/source_maps/BCS.mvsm and b/build/StarcoinFramework/source_maps/BCS.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Block.mvsm b/build/StarcoinFramework/source_maps/Block.mvsm index dee05fbb..eada550c 100644 Binary files a/build/StarcoinFramework/source_maps/Block.mvsm and b/build/StarcoinFramework/source_maps/Block.mvsm differ diff --git a/build/StarcoinFramework/source_maps/BlockReward.mvsm b/build/StarcoinFramework/source_maps/BlockReward.mvsm index e8e01b8b..11f31a03 100644 Binary files a/build/StarcoinFramework/source_maps/BlockReward.mvsm and b/build/StarcoinFramework/source_maps/BlockReward.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Compare.mvsm b/build/StarcoinFramework/source_maps/Compare.mvsm index 27000bfa..6469c37c 100644 Binary files a/build/StarcoinFramework/source_maps/Compare.mvsm and b/build/StarcoinFramework/source_maps/Compare.mvsm differ diff --git a/build/StarcoinFramework/source_maps/EVMAddress.mvsm b/build/StarcoinFramework/source_maps/EVMAddress.mvsm index 0375d0f8..6e8ab0b4 100644 Binary files a/build/StarcoinFramework/source_maps/EVMAddress.mvsm and b/build/StarcoinFramework/source_maps/EVMAddress.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Genesis.mvsm b/build/StarcoinFramework/source_maps/Genesis.mvsm index 8288658d..f8f0f361 100644 Binary files a/build/StarcoinFramework/source_maps/Genesis.mvsm and b/build/StarcoinFramework/source_maps/Genesis.mvsm differ diff --git a/build/StarcoinFramework/source_maps/GenesisNFT.mvsm b/build/StarcoinFramework/source_maps/GenesisNFT.mvsm index 14a6f17f..2b02023b 100644 Binary files a/build/StarcoinFramework/source_maps/GenesisNFT.mvsm and b/build/StarcoinFramework/source_maps/GenesisNFT.mvsm differ diff --git a/build/StarcoinFramework/source_maps/GenesisNFTScripts.mvsm b/build/StarcoinFramework/source_maps/GenesisNFTScripts.mvsm index d11198e8..d3936b96 100644 Binary files a/build/StarcoinFramework/source_maps/GenesisNFTScripts.mvsm and b/build/StarcoinFramework/source_maps/GenesisNFTScripts.mvsm differ diff --git a/build/StarcoinFramework/source_maps/GenesisSignerCapability.mvsm b/build/StarcoinFramework/source_maps/GenesisSignerCapability.mvsm index 998e3cd8..dcf6533e 100644 Binary files a/build/StarcoinFramework/source_maps/GenesisSignerCapability.mvsm and b/build/StarcoinFramework/source_maps/GenesisSignerCapability.mvsm differ diff --git a/build/StarcoinFramework/source_maps/IdentifierNFT.mvsm b/build/StarcoinFramework/source_maps/IdentifierNFT.mvsm index 9f1b3d4c..991be210 100644 Binary files a/build/StarcoinFramework/source_maps/IdentifierNFT.mvsm and b/build/StarcoinFramework/source_maps/IdentifierNFT.mvsm differ diff --git a/build/StarcoinFramework/source_maps/IdentifierNFTScripts.mvsm b/build/StarcoinFramework/source_maps/IdentifierNFTScripts.mvsm index 4e9e4589..9b3d3a60 100644 Binary files a/build/StarcoinFramework/source_maps/IdentifierNFTScripts.mvsm and b/build/StarcoinFramework/source_maps/IdentifierNFTScripts.mvsm differ diff --git a/build/StarcoinFramework/source_maps/InstallPluginProposalPlugin.mvsm b/build/StarcoinFramework/source_maps/InstallPluginProposalPlugin.mvsm deleted file mode 100644 index 2f0007d1..00000000 Binary files a/build/StarcoinFramework/source_maps/InstallPluginProposalPlugin.mvsm and /dev/null differ diff --git a/build/StarcoinFramework/source_maps/MemberProposalPlugin.mvsm b/build/StarcoinFramework/source_maps/MemberProposalPlugin.mvsm deleted file mode 100644 index b3485cbc..00000000 Binary files a/build/StarcoinFramework/source_maps/MemberProposalPlugin.mvsm and /dev/null differ diff --git a/build/StarcoinFramework/source_maps/MerkleNFTDistributor.mvsm b/build/StarcoinFramework/source_maps/MerkleNFTDistributor.mvsm index eb54fa0f..5b196958 100644 Binary files a/build/StarcoinFramework/source_maps/MerkleNFTDistributor.mvsm and b/build/StarcoinFramework/source_maps/MerkleNFTDistributor.mvsm differ diff --git a/build/StarcoinFramework/source_maps/MerkleProof.mvsm b/build/StarcoinFramework/source_maps/MerkleProof.mvsm index 234610da..c9a44b97 100644 Binary files a/build/StarcoinFramework/source_maps/MerkleProof.mvsm and b/build/StarcoinFramework/source_maps/MerkleProof.mvsm differ diff --git a/build/StarcoinFramework/source_maps/ModifyDaoConfigProposal.mvsm b/build/StarcoinFramework/source_maps/ModifyDaoConfigProposal.mvsm index e033d6cb..2149947d 100644 Binary files a/build/StarcoinFramework/source_maps/ModifyDaoConfigProposal.mvsm and b/build/StarcoinFramework/source_maps/ModifyDaoConfigProposal.mvsm differ diff --git a/build/StarcoinFramework/source_maps/ModuleUpgradeScripts.mvsm b/build/StarcoinFramework/source_maps/ModuleUpgradeScripts.mvsm index a3981d95..53401317 100644 Binary files a/build/StarcoinFramework/source_maps/ModuleUpgradeScripts.mvsm and b/build/StarcoinFramework/source_maps/ModuleUpgradeScripts.mvsm differ diff --git a/build/StarcoinFramework/source_maps/NFT.mvsm b/build/StarcoinFramework/source_maps/NFT.mvsm index b27322cb..378db39f 100644 Binary files a/build/StarcoinFramework/source_maps/NFT.mvsm and b/build/StarcoinFramework/source_maps/NFT.mvsm differ diff --git a/build/StarcoinFramework/source_maps/NFTGallery.mvsm b/build/StarcoinFramework/source_maps/NFTGallery.mvsm index 26147d3e..0cf28100 100644 Binary files a/build/StarcoinFramework/source_maps/NFTGallery.mvsm and b/build/StarcoinFramework/source_maps/NFTGallery.mvsm differ diff --git a/build/StarcoinFramework/source_maps/NFTGalleryScripts.mvsm b/build/StarcoinFramework/source_maps/NFTGalleryScripts.mvsm index 4e781a7a..ab91419f 100644 Binary files a/build/StarcoinFramework/source_maps/NFTGalleryScripts.mvsm and b/build/StarcoinFramework/source_maps/NFTGalleryScripts.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Offer.mvsm b/build/StarcoinFramework/source_maps/Offer.mvsm index 9659b966..eed0447b 100644 Binary files a/build/StarcoinFramework/source_maps/Offer.mvsm and b/build/StarcoinFramework/source_maps/Offer.mvsm differ diff --git a/build/StarcoinFramework/source_maps/OnChainConfigDao.mvsm b/build/StarcoinFramework/source_maps/OnChainConfigDao.mvsm index f9bd60c1..65d6cd52 100644 Binary files a/build/StarcoinFramework/source_maps/OnChainConfigDao.mvsm and b/build/StarcoinFramework/source_maps/OnChainConfigDao.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Oracle.mvsm b/build/StarcoinFramework/source_maps/Oracle.mvsm index 5723aa3c..a620282d 100644 Binary files a/build/StarcoinFramework/source_maps/Oracle.mvsm and b/build/StarcoinFramework/source_maps/Oracle.mvsm differ diff --git a/build/StarcoinFramework/source_maps/PackageTxnManager.mvsm b/build/StarcoinFramework/source_maps/PackageTxnManager.mvsm index 17c79436..ac4f936c 100644 Binary files a/build/StarcoinFramework/source_maps/PackageTxnManager.mvsm and b/build/StarcoinFramework/source_maps/PackageTxnManager.mvsm differ diff --git a/build/StarcoinFramework/source_maps/PriceOracle.mvsm b/build/StarcoinFramework/source_maps/PriceOracle.mvsm index 73871f2f..1b14ce86 100644 Binary files a/build/StarcoinFramework/source_maps/PriceOracle.mvsm and b/build/StarcoinFramework/source_maps/PriceOracle.mvsm differ diff --git a/build/StarcoinFramework/source_maps/PriceOracleAggregator.mvsm b/build/StarcoinFramework/source_maps/PriceOracleAggregator.mvsm index f892dfdc..39ed8375 100644 Binary files a/build/StarcoinFramework/source_maps/PriceOracleAggregator.mvsm and b/build/StarcoinFramework/source_maps/PriceOracleAggregator.mvsm differ diff --git a/build/StarcoinFramework/source_maps/PriceOracleScripts.mvsm b/build/StarcoinFramework/source_maps/PriceOracleScripts.mvsm index 59a0413c..99f2e901 100644 Binary files a/build/StarcoinFramework/source_maps/PriceOracleScripts.mvsm and b/build/StarcoinFramework/source_maps/PriceOracleScripts.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Ring.mvsm b/build/StarcoinFramework/source_maps/Ring.mvsm deleted file mode 100644 index 1247e5ea..00000000 Binary files a/build/StarcoinFramework/source_maps/Ring.mvsm and /dev/null differ diff --git a/build/StarcoinFramework/source_maps/STC.mvsm b/build/StarcoinFramework/source_maps/STC.mvsm index f0bfaeec..9689fa7c 100644 Binary files a/build/StarcoinFramework/source_maps/STC.mvsm and b/build/StarcoinFramework/source_maps/STC.mvsm differ diff --git a/build/StarcoinFramework/source_maps/STCUSDOracle.mvsm b/build/StarcoinFramework/source_maps/STCUSDOracle.mvsm index a1ef79bc..79d87d40 100644 Binary files a/build/StarcoinFramework/source_maps/STCUSDOracle.mvsm and b/build/StarcoinFramework/source_maps/STCUSDOracle.mvsm differ diff --git a/build/StarcoinFramework/source_maps/Signature.mvsm b/build/StarcoinFramework/source_maps/Signature.mvsm index b2b491f2..8ee4a28c 100644 Binary files a/build/StarcoinFramework/source_maps/Signature.mvsm and b/build/StarcoinFramework/source_maps/Signature.mvsm differ diff --git a/build/StarcoinFramework/source_maps/SignedInteger64.mvsm b/build/StarcoinFramework/source_maps/SignedInteger64.mvsm index 1c9f9d8b..61f62596 100644 Binary files a/build/StarcoinFramework/source_maps/SignedInteger64.mvsm and b/build/StarcoinFramework/source_maps/SignedInteger64.mvsm differ diff --git a/build/StarcoinFramework/source_maps/StarcoinVerifier.mvsm b/build/StarcoinFramework/source_maps/StarcoinVerifier.mvsm deleted file mode 100644 index 06917792..00000000 Binary files a/build/StarcoinFramework/source_maps/StarcoinVerifier.mvsm and /dev/null differ diff --git a/build/StarcoinFramework/source_maps/StdlibUpgradeScripts.mvsm b/build/StarcoinFramework/source_maps/StdlibUpgradeScripts.mvsm index a81d3d60..99d1ab52 100644 Binary files a/build/StarcoinFramework/source_maps/StdlibUpgradeScripts.mvsm and b/build/StarcoinFramework/source_maps/StdlibUpgradeScripts.mvsm differ diff --git a/build/StarcoinFramework/source_maps/StructuredHash.mvsm b/build/StarcoinFramework/source_maps/StructuredHash.mvsm deleted file mode 100644 index a60c3dc6..00000000 Binary files a/build/StarcoinFramework/source_maps/StructuredHash.mvsm and /dev/null differ diff --git a/build/StarcoinFramework/source_maps/Token.mvsm b/build/StarcoinFramework/source_maps/Token.mvsm index cfb8ab7d..17143847 100644 Binary files a/build/StarcoinFramework/source_maps/Token.mvsm and b/build/StarcoinFramework/source_maps/Token.mvsm differ diff --git a/build/StarcoinFramework/source_maps/TransactionManager.mvsm b/build/StarcoinFramework/source_maps/TransactionManager.mvsm index 25092a0c..58d95853 100644 Binary files a/build/StarcoinFramework/source_maps/TransactionManager.mvsm and b/build/StarcoinFramework/source_maps/TransactionManager.mvsm differ diff --git a/build/StarcoinFramework/source_maps/TreasuryWithdrawDaoProposal.mvsm b/build/StarcoinFramework/source_maps/TreasuryWithdrawDaoProposal.mvsm index 84561dc8..697914b5 100644 Binary files a/build/StarcoinFramework/source_maps/TreasuryWithdrawDaoProposal.mvsm and b/build/StarcoinFramework/source_maps/TreasuryWithdrawDaoProposal.mvsm differ diff --git a/build/StarcoinFramework/source_maps/U256.mvsm b/build/StarcoinFramework/source_maps/U256.mvsm index 78433b97..b552ee0e 100644 Binary files a/build/StarcoinFramework/source_maps/U256.mvsm and b/build/StarcoinFramework/source_maps/U256.mvsm differ diff --git a/build/StarcoinFramework/source_maps/UpgradeModuleDaoProposal.mvsm b/build/StarcoinFramework/source_maps/UpgradeModuleDaoProposal.mvsm index 695f18f2..bdfc2b8a 100644 Binary files a/build/StarcoinFramework/source_maps/UpgradeModuleDaoProposal.mvsm and b/build/StarcoinFramework/source_maps/UpgradeModuleDaoProposal.mvsm differ diff --git a/deprecated/integration-tests/dao/test_dao_failure.exp b/deprecated/integration-tests/dao/test_dao_failure.exp deleted file mode 100644 index 2c5fcfe3..00000000 --- a/deprecated/integration-tests/dao/test_dao_failure.exp +++ /dev/null @@ -1,384 +0,0 @@ -processed 43 tasks - -task 5 'run'. lines 12-29: -{ - "gas_used": 313160, - "status": "Executed" -} - -task 6 'run'. lines 31-41: -{ - "gas_used": 12417, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ModifyDaoConfigProposal" - } - }, - "abort_code": "102919" - } - } -} - -task 7 'run'. lines 44-54: -{ - "gas_used": 162267, - "status": "Executed" -} - -task 8 'run'. lines 58-68: -{ - "gas_used": 162267, - "status": "Executed" -} - -task 9 'run'. lines 71-81: -{ - "gas_used": 125294, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "function": 18, - "code_offset": 45 - } - } -} - -task 11 'run'. lines 86-104: -{ - "gas_used": 148929, - "status": "Executed" -} - -task 12 'run'. lines 107-127: -{ - "gas_used": 162344, - "status": "Executed" -} - -task 13 'run'. lines 131-155: -{ - "gas_used": 149577, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360449" - } - } -} - -task 14 'run'. lines 158-176: -{ - "gas_used": 94115, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360967" - } - } -} - -task 15 'run'. lines 179-197: -{ - "gas_used": 76714, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359431" - } - } -} - -task 16 'run'. lines 200-218: -{ - "gas_used": 59161, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359687" - } - } -} - -task 17 'run'. lines 221-239: -{ - "gas_used": 41374, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359431" - } - } -} - -task 18 'run'. lines 242-255: -{ - "gas_used": 32131, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359687" - } - } -} - -task 19 'run'. lines 258-271: -{ - "gas_used": 33839, - "status": "Executed" -} - -task 20 'run'. lines 274-287: -{ - "gas_used": 15108, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359431" - } - } -} - -task 21 'run'. lines 290-304: -{ - "gas_used": 29499, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359169" - } - } -} - -task 23 'run'. lines 309-324: -{ - "gas_used": 37415, - "status": "Executed" -} - -task 24 'run'. lines 327-341: -{ - "gas_used": 36805, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359682" - } - } -} - -task 25 'run'. lines 344-364: -{ - "gas_used": 102595, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359169" - } - } -} - -task 26 'run'. lines 367-381: -{ - "gas_used": 40995, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359169" - } - } -} - -task 27 'run'. lines 384-402: -{ - "gas_used": 53206, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359169" - } - } -} - -task 28 'run'. lines 406-424: -{ - "gas_used": 69415, - "status": "Executed" -} - -task 30 'run'. lines 430-452: -{ - "gas_used": 163394, - "status": "Executed" -} - -task 32 'run'. lines 456-470: -{ - "gas_used": 76680, - "status": "Executed" -} - -task 33 'run'. lines 473-488: -{ - "gas_used": 39375, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359169" - } - } -} - -task 34 'run'. lines 491-505: -{ - "gas_used": 74710, - "status": "Executed" -} - -task 35 'run'. lines 508-519: -{ - "gas_used": 162267, - "status": "Executed" -} - -task 37 'run'. lines 525-545: -{ - "gas_used": 108170, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360967" - } - } -} - -task 38 'run'. lines 548-566: -{ - "gas_used": 59295, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360967" - } - } -} - -task 39 'run'. lines 570-583: -{ - "gas_used": 32279, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360967" - } - } -} - -task 40 'run'. lines 586-606: -{ - "gas_used": 162344, - "status": "Executed" -} - -task 42 'run'. lines 612-630: -{ - "gas_used": 51131, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360967" - } - } -} diff --git a/deprecated/integration-tests/on_chain_config/test_onchain_config_dao.exp b/deprecated/integration-tests/on_chain_config/test_onchain_config_dao.exp deleted file mode 100644 index dd472f39..00000000 --- a/deprecated/integration-tests/on_chain_config/test_onchain_config_dao.exp +++ /dev/null @@ -1,58 +0,0 @@ -processed 14 tasks - -task 4 'run'. lines 10-21: -{ - "gas_used": 216046, - "status": "Executed" -} - -task 5 'run'. lines 22-31: -{ - "gas_used": 21947, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "OnChainConfigDao" - } - }, - "abort_code": "102658" - } - } -} - -task 6 'run'. lines 32-42: -{ - "gas_used": 161955, - "status": "Executed" -} - -task 8 'run'. lines 47-60: -{ - "gas_used": 148289, - "status": "Executed" -} - -task 11 'run'. lines 67-87: -{ - "gas_used": 157265, - "status": "Executed" -} - -task 13 'run'. lines 92-106: -{ - "gas_used": 68033, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "OnChainConfigDao" - } - }, - "function": 1, - "code_offset": 6 - } - } -} diff --git a/deprecated/integration-tests/token/init_stc.exp b/deprecated/integration-tests/token/init_stc.exp deleted file mode 100644 index dbedd327..00000000 --- a/deprecated/integration-tests/token/init_stc.exp +++ /dev/null @@ -1,34 +0,0 @@ -processed 5 tasks - -task 3 'run'. lines 7-16: -{ - "gas_used": 34612, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "abort_code": "25858" - } - } -} - -task 4 'run'. lines 20-30: -{ - "gas_used": 80642, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "function": 21, - "code_offset": 42 - } - } -} diff --git a/deprecated/integration-tests/transaction_scripts/execute_on_chain_config_proposal.exp b/deprecated/integration-tests/transaction_scripts/execute_on_chain_config_proposal.exp deleted file mode 100644 index d8b6aa50..00000000 --- a/deprecated/integration-tests/transaction_scripts/execute_on_chain_config_proposal.exp +++ /dev/null @@ -1,42 +0,0 @@ -processed 12 tasks - -task 4 'run'. lines 10-20: -{ - "gas_used": 168481, - "status": "Executed" -} - -task 6 'run'. lines 23-43: -{ - "gas_used": 153230, - "status": "Executed" -} - -task 8 'run'. lines 48-64: -{ - "gas_used": 40133, - "status": "Executed" -} - -task 9 'run'. lines 66-83: -{ - "gas_used": 89072, - "status": "Executed" -} - -task 11 'run'. lines 87-100: -{ - "gas_used": 54480, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "OnChainConfigDao" - } - }, - "function": 1, - "code_offset": 6 - } - } -} diff --git a/integration-tests/account/basic.exp b/integration-tests/account/basic.exp index 7a886797..036af33e 100644 --- a/integration-tests/account/basic.exp +++ b/integration-tests/account/basic.exp @@ -3,21 +3,25 @@ processed 14 tasks task 5 'run'. lines 30-41: { "gas_used": 139240, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 44-55: { "gas_used": 43065, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "26119" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 26119 + ] } } } @@ -26,14 +30,16 @@ task 7 'run'. lines 58-74: { "gas_used": 58850, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "26369" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 26369 + ] } } } @@ -41,35 +47,47 @@ task 7 'run'. lines 58-74: task 8 'run'. lines 76-95: { "gas_used": 129486, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 98-110: { "gas_used": 154312, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 112-121: { "gas_used": 11474, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 123-135: { "gas_used": 396842, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 138-147: { "gas_used": 20214, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 150-159: { "gas_used": 52949, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/account/delegate_account.exp b/integration-tests/account/delegate_account.exp index 55b9b9d3..8b42863a 100644 --- a/integration-tests/account/delegate_account.exp +++ b/integration-tests/account/delegate_account.exp @@ -2,12 +2,16 @@ processed 7 tasks task 5 'run'. lines 27-44: { - "gas_used": 638014, - "status": "Executed" + "gas_used": 618395, + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 47-62: { "gas_used": 139958, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/account/delegate_account_retry.exp b/integration-tests/account/delegate_account_retry.exp deleted file mode 100644 index 95d7c98c..00000000 --- a/integration-tests/account/delegate_account_retry.exp +++ /dev/null @@ -1,7 +0,0 @@ -processed 3 tasks - -task 2 'run'. lines 5-26: -{ - "gas_used": 13887841, - "status": "Executed" -} diff --git a/integration-tests/account/delegate_account_retry.move b/integration-tests/account/delegate_account_retry.move deleted file mode 100644 index 4fdaa1e3..00000000 --- a/integration-tests/account/delegate_account_retry.move +++ /dev/null @@ -1,27 +0,0 @@ -//# init -n dev - -//# faucet --addr alice --amount 2000000000 - -//# run --signers alice - -script { - use StarcoinFramework::Account; - - fun main(sender: signer) { - let (_new_address, signer_cap) = Account::create_delegate_account(&sender); - let new_account_signer = Account::create_signer_with_cap(&signer_cap); - - let (address_0, cap_0) = Account::create_delegate_account(&new_account_signer); - let i = 1; - while(i < 10){ - let (address_i, cap_i) = Account::create_delegate_account(&new_account_signer); - assert!(address_0 != address_i, 1000); - Account::destroy_signer_cap(cap_i); - i = i + 1; - }; - Account::destroy_signer_cap(cap_0); - Account::destroy_signer_cap(signer_cap); - } -} -// check: EXECUTED - diff --git a/integration-tests/account/deposit_zero_token.exp b/integration-tests/account/deposit_zero_token.exp index a61232ce..3399f631 100644 --- a/integration-tests/account/deposit_zero_token.exp +++ b/integration-tests/account/deposit_zero_token.exp @@ -3,11 +3,15 @@ processed 4 tasks task 2 'run'. lines 6-16: { "gas_used": 45962, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 19-30: { "gas_used": 31287, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/account/remove_zero_balance.exp b/integration-tests/account/remove_zero_balance.exp index 37e4e01c..ca19e51e 100644 --- a/integration-tests/account/remove_zero_balance.exp +++ b/integration-tests/account/remove_zero_balance.exp @@ -3,21 +3,25 @@ processed 4 tasks task 2 'run'. lines 5-17: { "gas_used": 92550, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 19-30: { "gas_used": 146733, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "abort_code": "4097" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Token" + } + }, + 4097 + ] } } } diff --git a/integration-tests/account/txn_prologue_and_epilogue.exp b/integration-tests/account/txn_prologue_and_epilogue.exp index 96cdc291..0ef2bb54 100644 --- a/integration-tests/account/txn_prologue_and_epilogue.exp +++ b/integration-tests/account/txn_prologue_and_epilogue.exp @@ -1,153 +1,143 @@ -processed 15 tasks +processed 12 tasks -task 3 'run'. lines 7-28: +task 3 'run'. lines 8-23: { - "gas_used": 621301, - "status": "Executed" + "gas_used": 494124, + "status": { + "Keep": "Executed" + } } -task 4 'run'. lines 30-62: +task 4 'run'. lines 27-59: { - "gas_used": 180803, + "gas_used": 174759, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "CoreAddresses" - } - }, - "abort_code": "2818" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "CoreAddresses" + } + }, + 2818 + ] } } } -task 5 'run'. lines 66-92: +task 5 'run'. lines 63-90: { - "gas_used": 330588, + "gas_used": 329083, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "1031" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 1031 + ] } } } -task 6 'run'. lines 96-124: +task 6 'run'. lines 94-122: { - "gas_used": 306856, + "gas_used": 300870, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "263" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 263 + ] } } } -task 7 'run'. lines 128-158: +task 7 'run'. lines 126-156: { - "gas_used": 355103, + "gas_used": 335601, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "775" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 775 + ] } } } -task 8 'run'. lines 162-207: -{ - "gas_used": 478362, - "status": "Executed" -} - -task 9 'run'. lines 211-241: +task 8 'run'. lines 160-205: { - "gas_used": 354973, + "gas_used": 403810, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "519" - } + "Keep": "Executed" } } -task 10 'run'. lines 245-276: +task 9 'run'. lines 209-239: { - "gas_used": 197287, + "gas_used": 335471, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "2568" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 519 + ] } } } -task 11 'run'. lines 280-311: +task 10 'run'. lines 243-274: { - "gas_used": 175186, + "gas_used": 180123, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "CoreAddresses" - } - }, - "abort_code": "2818" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 2568 + ] } } } -task 12 'run'. lines 313-349: +task 11 'run'. lines 278-309: { - "gas_used": 359119, + "gas_used": 174016, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "1031" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "CoreAddresses" + } + }, + 2818 + ] } } } - -task 13 'run'. lines 351-401: -{ - "gas_used": 517887, - "status": "Executed" -} - -task 14 'run'. lines 404-427: -{ - "gas_used": 37463, - "status": "Executed" -} diff --git a/integration-tests/account/txn_prologue_and_epilogue.move b/integration-tests/account/txn_prologue_and_epilogue.move index 0dd194e8..ddb27004 100644 --- a/integration-tests/account/txn_prologue_and_epilogue.move +++ b/integration-tests/account/txn_prologue_and_epilogue.move @@ -1,8 +1,9 @@ //# init -n dev +//# faucet --addr alice --amount 10000000 + //# faucet --addr Genesis -//# faucet --addr alice --amount 10000000 //# run --signers alice // create txn sender account @@ -10,8 +11,6 @@ script { use StarcoinFramework::STC::STC; use StarcoinFramework::Account; use StarcoinFramework::Authenticator; - use StarcoinFramework::DummyToken; - use StarcoinFramework::DummyToken::DummyToken; fun main(account: signer) { let txn_public_key = x"c48b687a1dd8265101b33df6ae0b6825234e3f28df9ecb38fb286cf76dae919d"; @@ -19,14 +18,12 @@ script { let address = Authenticator::derived_address(auth_key_vec); Account::create_account_with_address(address); Account::pay_from(&account, address, 5000); - let coin = DummyToken::mint(&account, 500); - Account::deposit(address, coin); - assert!(Account::balance(address) == 500, 1000); - } } // check: EXECUTED + + //# run --signers alice // prologue sender is not genesis script { @@ -79,6 +76,7 @@ script { let txn_sequence_number = 0; let txn_gas_price = 1; let txn_max_gas_units = 10000; //EPROLOGUE_CANT_PAY_GAS_DEPOSIT + Account::txn_prologue( &account, txn_sender, @@ -308,120 +306,4 @@ script { ); } } -// check: "Keep(ABORTED { code: 2818" - -//# run --signers Genesis -// epilouge cant pay gas deposit - -script { - use StarcoinFramework::Account; - use StarcoinFramework::Authenticator; - use StarcoinFramework::Vector; - use StarcoinFramework::DummyToken::DummyToken; - - fun main(account: signer) { - let txn_public_key = x"c48b687a1dd8265101b33df6ae0b6825234e3f28df9ecb38fb286cf76dae919d"; - let auth_key_vec = Authenticator::ed25519_authentication_key(copy txn_public_key); - let txn_sender = Authenticator::derived_address(copy auth_key_vec); - Vector::push_back(&mut txn_public_key, 0u8); //create preimage - - let seq = Account::sequence_number(txn_sender); - assert!(seq == 1, 1005); - - let txn_sequence_number = 1; - let txn_gas_price = 1; - let txn_max_gas_units = 2510; - Account::do_accept_token(&account); - - Account::txn_prologue_v2( - &account, - txn_sender, - txn_sequence_number, - txn_public_key, - txn_gas_price, - txn_max_gas_units, - 2, - 10, - ); - } - -} -// check: "Keep(ABORTED { code: 1031" - -//# run --signers Genesis -// successfully executed -script { - use StarcoinFramework::Account; - use StarcoinFramework::Authenticator; - use StarcoinFramework::Vector; - use StarcoinFramework::DummyToken::DummyToken; - - fun main(account: signer) { - let txn_public_key = x"c48b687a1dd8265101b33df6ae0b6825234e3f28df9ecb38fb286cf76dae919d"; - let auth_key_vec = Authenticator::ed25519_authentication_key(copy txn_public_key); - let txn_sender = Authenticator::derived_address(copy auth_key_vec); - Vector::push_back(&mut txn_public_key, 0u8); //create preimage - - let seq = Account::sequence_number(txn_sender); - assert!(seq == 1, 1005); - - let txn_sequence_number = 1; - let txn_gas_price = 1; - let txn_max_gas_units = 2500; - Account::do_accept_token(&account); - - Account::txn_prologue_v2( - &account, - txn_sender, - txn_sequence_number, - txn_public_key, - txn_gas_price, - txn_max_gas_units, - 2, - 10, - ); - // execute the txn... - let gas_units_remaining = 10; - Account::txn_epilogue_v3( - &account, - txn_sender, - txn_sequence_number, - Vector::empty(), - txn_gas_price, - txn_max_gas_units, - gas_units_remaining, - 2, - 10, - ); - let seq = Account::sequence_number(txn_sender); - assert!(seq == 2, 1006); - } - -} -// check: EXECUTED - - -//# run --signers Genesis -script { - use StarcoinFramework::Account; - - fun main(_account: signer){ - let (txn_gas_price, txn_max_gas_units, gas_units_remaining, - stc_price, stc_price_scaling - ) = (1, 100000, 0, 43793, 1000000000000000); - let (stc_amount, token_amount) = Account::transaction_fee_simulate(txn_gas_price, txn_max_gas_units, gas_units_remaining, - stc_price, stc_price_scaling); - assert!(stc_amount==100000, 100); - assert!(token_amount==1, 101); - - let (txn_gas_price, txn_max_gas_units, gas_units_remaining, - stc_price, stc_price_scaling - ) = (1000000, 100000, 0, 43793, 1000000000000000); - let (stc_amount, token_amount) = Account::transaction_fee_simulate(txn_gas_price, txn_max_gas_units, gas_units_remaining, - stc_price, stc_price_scaling); - assert!(stc_amount==100000000000, 102); - assert!(token_amount==4, 103); - - } -} -// check: EXECUTED +// check: "Keep(ABORTED { code: 2818" \ No newline at end of file diff --git a/integration-tests/account/withdraw_capability.exp b/integration-tests/account/withdraw_capability.exp index 639e8c7c..be6f17f9 100644 --- a/integration-tests/account/withdraw_capability.exp +++ b/integration-tests/account/withdraw_capability.exp @@ -3,21 +3,25 @@ processed 12 tasks task 5 'run'. lines 25-38: { "gas_used": 60573, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 41-55: { "gas_used": 25450, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "25857" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 25857 + ] } } } @@ -26,14 +30,16 @@ task 7 'run'. lines 58-73: { "gas_used": 25450, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Account" - } - }, - "abort_code": "25857" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Account" + } + }, + 25857 + ] } } } @@ -41,23 +47,31 @@ task 7 'run'. lines 58-73: task 8 'run'. lines 76-88: { "gas_used": 139240, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 91-103: { "gas_used": 158256, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 106-117: { "gas_used": 96005, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 120-132: { "gas_used": 146440, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/account/withdraw_zero_token.exp b/integration-tests/account/withdraw_zero_token.exp index fdd4ff3c..dd7fecb9 100644 --- a/integration-tests/account/withdraw_zero_token.exp +++ b/integration-tests/account/withdraw_zero_token.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 6-16: { "gas_used": 35928, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/authenticator/authenticator.exp b/integration-tests/authenticator/authenticator.exp index 5a9c4861..adb13f22 100644 --- a/integration-tests/authenticator/authenticator.exp +++ b/integration-tests/authenticator/authenticator.exp @@ -3,21 +3,25 @@ processed 11 tasks task 2 'run'. lines 6-50: { "gas_used": 447187, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 52-67: { "gas_used": 14893, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Authenticator" - } - }, - "abort_code": "26119" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Authenticator" + } + }, + 26119 + ] } } } @@ -26,14 +30,16 @@ task 4 'run'. lines 69-84: { "gas_used": 14964, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Authenticator" - } - }, - "abort_code": "26375" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Authenticator" + } + }, + 26375 + ] } } } @@ -42,14 +48,16 @@ task 5 'run'. lines 86-106: { "gas_used": 100057, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Authenticator" - } - }, - "abort_code": "26631" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Authenticator" + } + }, + 26631 + ] } } } @@ -58,14 +66,16 @@ task 6 'run'. lines 109-128: { "gas_used": 19157, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Authenticator" - } - }, - "abort_code": "26375" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Authenticator" + } + }, + 26375 + ] } } } @@ -74,14 +84,16 @@ task 7 'run'. lines 131-150: { "gas_used": 19086, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Authenticator" - } - }, - "abort_code": "26119" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Authenticator" + } + }, + 26119 + ] } } } @@ -89,27 +101,33 @@ task 7 'run'. lines 131-150: task 8 'run'. lines 153-182: { "gas_used": 75325, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 184-196: { "gas_used": 396842, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 198-206: { "gas_used": 11900, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Authenticator" - } - }, - "abort_code": "25863" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Authenticator" + } + }, + 25863 + ] } } } diff --git a/integration-tests/bitwise/operators.exp b/integration-tests/bitwise/operators.exp index d7d6efa3..0ce45086 100644 --- a/integration-tests/bitwise/operators.exp +++ b/integration-tests/bitwise/operators.exp @@ -3,11 +3,15 @@ processed 4 tasks task 2 'run'. lines 6-26: { "gas_used": 65599, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 28-43: { "gas_used": 33510, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/block/block_checkpoints.exp b/integration-tests/block/block_checkpoints.exp deleted file mode 100644 index 4ffca21f..00000000 --- a/integration-tests/block/block_checkpoints.exp +++ /dev/null @@ -1,25 +0,0 @@ -processed 7 tasks - -task 3 'run'. lines 157-166: -{ - "gas_used": 442844, - "status": "Executed" -} - -task 4 'run'. lines 168-179: -{ - "gas_used": 73780, - "status": "Executed" -} - -task 5 'run'. lines 182-192: -{ - "gas_used": 565771, - "status": "Executed" -} - -task 6 'run'. lines 194-205: -{ - "gas_used": 95873, - "status": "Executed" -} diff --git a/integration-tests/block/block_checkpoints.move b/integration-tests/block/block_checkpoints.move deleted file mode 100644 index 1fe0810a..00000000 --- a/integration-tests/block/block_checkpoints.move +++ /dev/null @@ -1,205 +0,0 @@ -//# init -n dev - -//# faucet --addr alice - -//# publish -module alice::Block_test{ - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::Ring; - use StarcoinFramework::BCS; - use StarcoinFramework::Hash; - - struct Checkpoint has copy,drop,store{ - //number of the block - block_number: u64, - //Hash of the block - block_hash: vector, - //State root of the block - state_root: Option::Option>, - } - const EBLOCK_NUMBER_MISMATCH : u64 = 17; - const ERROR_NO_HAVE_CHECKPOINT: u64 = 18; - const ERROR_NOT_BLOCK_HEADER : u64 = 19; - const ERROR_INTERVAL_TOO_LITTLE: u64 = 20; - const ERR_ALREADY_INITIALIZED : u64 = 21; - - const CHECKPOINT_LENGTH : u64 = 60; - const BLOCK_HEADER_LENGTH : u64 = 247; - const BLOCK_INTERVAL_NUMBER : u64 = 5; - // - struct Checkpoints has key,store{ - //all checkpoints - checkpoints : Ring::Ring, - index : u64, - last_number : u64, - } - public fun checkpoints_init(account:&signer){ - assert!(!exists(@alice), Errors::already_published(ERR_ALREADY_INITIALIZED)); - - let checkpoints = Ring::create_with_capacity(CHECKPOINT_LENGTH); - move_to( - account, - Checkpoints { - checkpoints : checkpoints, - index : 0, - last_number : 0, - }); - } - - public fun checkpoint(parent_block_number:u64,parent_block_hash:vector) acquires Checkpoints{ - let checkpoints = borrow_global_mut(@alice); - base_checkpoint(checkpoints, parent_block_number, parent_block_hash); - - } - - fun base_checkpoint(checkpoints: &mut Checkpoints, parent_block_number: u64, parent_block_hash:vector){ - assert!(checkpoints.last_number + BLOCK_INTERVAL_NUMBER <= parent_block_number || checkpoints.last_number == 0, Errors::invalid_argument(ERROR_INTERVAL_TOO_LITTLE)); - - checkpoints.index = checkpoints.index + 1; - checkpoints.last_number = parent_block_number; - let op_checkpoint = Ring::push(&mut checkpoints.checkpoints, Checkpoint { - block_number: parent_block_number, - block_hash: parent_block_hash, - state_root: Option::none>(), - } ); - if(Option::is_some(&op_checkpoint)){ - Option::destroy_some(op_checkpoint); - }else{ - Option::destroy_none(op_checkpoint); - } - } - - public fun latest_state_root():(u64,vector) acquires Checkpoints{ - let checkpoints = borrow_global(@alice); - base_latest_state_root(checkpoints) - } - - fun base_latest_state_root(checkpoints: &Checkpoints):(u64,vector){ - let len = Ring::capacity(&checkpoints.checkpoints); - let j = if(checkpoints.index < len - 1){ - checkpoints.index - }else{ - len - }; - let i = checkpoints.index; - while( j > 0){ - let op_checkpoint = Ring::borrow(&checkpoints.checkpoints, i - 1 ); - if( Option::is_some(op_checkpoint) && Option::is_some(&Option::borrow(op_checkpoint).state_root) ) { - let state_root = Option::borrow(&Option::borrow(op_checkpoint).state_root); - return (Option::borrow(op_checkpoint).block_number, *state_root) - }; - j = j - 1; - i = i - 1; - }; - - abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT) - } - - public fun update_state_root(header: vector)acquires Checkpoints { - let checkpoints = borrow_global_mut(@alice); - base_update_state_root(checkpoints, header); - } - - - fun base_update_state_root(checkpoints: &mut Checkpoints, header: vector){ - let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader"); - - //parent_hash - let new_offset = BCS::skip_bytes(&header,0); - //timestamp - let new_offset = BCS::skip_u64(&header,new_offset); - //number - let (number,new_offset) = BCS::deserialize_u64(&header,new_offset); - //author - new_offset = BCS::skip_address(&header,new_offset); - //author_auth_key - new_offset = BCS::skip_option_bytes(&header,new_offset); - //txn_accumulator_root - new_offset = BCS::skip_bytes(&header,new_offset); - //block_accumulator_root - new_offset = BCS::skip_bytes(&header,new_offset); - //state_root - let (state_root,_new_offset) = BCS::deserialize_bytes(&header,new_offset); - - Vector::append(&mut prefix,header); - let block_hash = Hash::sha3_256(prefix); - - let len = Ring::capacity(&checkpoints.checkpoints); - let j = if(checkpoints.index < len - 1){ - checkpoints.index - }else{ - len - }; - let i = checkpoints.index; - while( j > 0){ - let op_checkpoint = Ring::borrow_mut(&mut checkpoints.checkpoints, i - 1); - - if( Option::is_some(op_checkpoint) && &Option::borrow(op_checkpoint).block_hash == &block_hash && Option::borrow(op_checkpoint).block_number == number) { - - let op_state_root = &mut Option::borrow_mut(op_checkpoint).state_root; - if(Option::is_some(op_state_root)){ - Option::swap(op_state_root, state_root); - }else{ - Option::fill(op_state_root, state_root); - }; - return - }; - j = j - 1; - i = i - 1; - }; - - abort ERROR_NO_HAVE_CHECKPOINT - } -} - -//# run --signers alice -script { - use alice::Block_test; - - - fun init(account: signer) { - Block_test::checkpoints_init(&account); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use alice::Block_test; - - - fun init(_account: signer) { - let number = 6677628; - let hash = x"e1bfffa1218462207a9807562422ccb40e2a27a6e3f0834a39364efd1cafb84f"; - Block_test::checkpoint(number, hash); - } -} -// check: EXECUTED - - -//# run --signers alice -script { - use alice::Block_test; - - - fun update(_account: signer) { - let header = x"20f9ccf1b2d18066977f1285aa23dd63a39739f22237aa2973476ed3326055369935d2e0db810100007ce46500000000005555ad74ce032cae631e7c83796880290020c0251fee2b98b5af7148ab4bcb5e0d65172b4639730d36208bb12fcfb581c01220211bdc20127db53f9179f8d873c0111cd971f852b8cacff91e801e7d27f74e182021e83a4306b24ba553f5b7b69a44d349d18cc3b52308994486fa3e53f69bb2860000000000000000000000000000000000000000000000000000000000000000000000001205509820c01e0329de6d899348a8ef4bd51db56175b3fa0988e57c3dcec8eaf13a164d9701a109000d694e533f"; - Block_test::update_state_root(header); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use alice::Block_test; - - - fun latest(_account: signer) { - let (number ,state_root) = Block_test::latest_state_root(); - assert!(number == 6677628, 10000); - assert!(state_root == x"21e83a4306b24ba553f5b7b69a44d349d18cc3b52308994486fa3e53f69bb286",10001); - } -} -// check: EXECUTED \ No newline at end of file diff --git a/integration-tests/block/block_metadata.exp b/integration-tests/block/block_metadata.exp index 1643c9e6..93954344 100644 --- a/integration-tests/block/block_metadata.exp +++ b/integration-tests/block/block_metadata.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-15: { "gas_used": 16339, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/block/checkpoints_test.exp b/integration-tests/block/checkpoints_test.exp deleted file mode 100644 index 78de5d73..00000000 --- a/integration-tests/block/checkpoints_test.exp +++ /dev/null @@ -1,35 +0,0 @@ -processed 13 tasks - -task 4 'run'. lines 9-27: -{ - "gas_used": 114532, - "status": "Executed" -} - -task 7 'run'. lines 33-46: -{ - "gas_used": 532278, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Block" - } - }, - "abort_code": "4609" - } - } -} - -task 10 'run'. lines 53-64: -{ - "gas_used": 577624, - "status": "Executed" -} - -task 12 'run'. lines 68-81: -{ - "gas_used": 103932, - "status": "Executed" -} diff --git a/integration-tests/block/checkpoints_test.move b/integration-tests/block/checkpoints_test.move deleted file mode 100644 index 40fb48ed..00000000 --- a/integration-tests/block/checkpoints_test.move +++ /dev/null @@ -1,81 +0,0 @@ -//# init -n dev --debug - -//# faucet --addr alice - -//# block --author=0x2 --timestamp 86420000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} --args {{$.call-api[0].head.state_root}} -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun checkpoint(_account: signer, parent_hash: vector, state_root: vector) { - let expect_parent_hash = Block::get_parent_hash(); - Debug::print(&expect_parent_hash); - Debug::print(&parent_hash); - Debug::print(&state_root); - assert!( expect_parent_hash == parent_hash, 1001); - - let current_block_number = Block::get_current_block_number(); - Debug::print(¤t_block_number); - - Block::checkpoint(); - } -} -// check: EXECUTED - -//# block --author=0x2 --timestamp 86430000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.block_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun update(_account: signer, raw_header: vector) { - let current_block_number = Block::get_current_block_number(); - Debug::print(¤t_block_number); - Debug::print(&raw_header); - Block::update_state_root(raw_header); - } -} -// check: ABORT. reason: Block from call-api[0] is not in checkpoint, its parent is in. - - -//# block --author=0x3 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[2].raw.header}} - -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun update(_account: signer, raw_header: vector) { - Debug::print(&raw_header); - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}"] - -//# run --signers alice --args {{$.call-api[3].header.state_root}} -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun latest(_account: signer, expect_state_root: vector) { - let (number, state_root) = Block::latest_state_root(); - Debug::print(&number); - Debug::print(&state_root); - Debug::print(&expect_state_root); - assert!(state_root == expect_state_root, 1002) - } -} -// check: EXECUTED \ No newline at end of file diff --git a/integration-tests/block_reward/basic.exp b/integration-tests/block_reward/basic.exp index bfc13109..4c7a11a7 100644 --- a/integration-tests/block_reward/basic.exp +++ b/integration-tests/block_reward/basic.exp @@ -3,21 +3,25 @@ processed 12 tasks task 3 'run'. lines 7-21: { "gas_used": 202807, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 24-40: { "gas_used": 30790, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "CoreAddresses" - } - }, - "abort_code": "2818" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "CoreAddresses" + } + }, + 2818 + ] } } } @@ -25,21 +29,25 @@ task 4 'run'. lines 24-40: task 5 'run'. lines 43-58: { "gas_used": 35600, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 61-76: { "gas_used": 36780, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "BlockReward" - } - }, - "abort_code": "26119" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "BlockReward" + } + }, + 26119 + ] } } } @@ -47,29 +55,39 @@ task 6 'run'. lines 61-76: task 7 'run'. lines 80-96: { "gas_used": 597319, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 99-115: { "gas_used": 473890, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 118-133: { "gas_used": 210007, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 136-150: { "gas_used": 95714, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 153-167: { "gas_used": 210007, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/chain_id/chain_id.exp b/integration-tests/chain_id/chain_id.exp index 0356c570..14d94b0f 100644 --- a/integration-tests/chain_id/chain_id.exp +++ b/integration-tests/chain_id/chain_id.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-12: { "gas_used": 14559, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/check/delta_size_check.exp b/integration-tests/check/delta_size_check.exp index 5883fa11..7dc1c863 100644 --- a/integration-tests/check/delta_size_check.exp +++ b/integration-tests/check/delta_size_check.exp @@ -3,11 +3,15 @@ processed 7 tasks task 5 'run'. lines 42-54: { "gas_used": 17924, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 58-74: { "gas_used": 17842, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/check/gas_check.exp b/integration-tests/check/gas_check.exp index 8b4bbae0..0c5cdddd 100644 --- a/integration-tests/check/gas_check.exp +++ b/integration-tests/check/gas_check.exp @@ -3,17 +3,16 @@ processed 5 tasks task 2 'run'. lines 5-14: { "gas_used": 1000, - "status": "OutOfGas" + "status": { + "Keep": "OutOfGas" + } } task 3 'run'. lines 17-26: { "gas_used": 0, "status": { - "Discard": { - "status_code": "14", - "status_code_name": "MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS" - } + "Discard": 14 } } @@ -21,9 +20,6 @@ task 4 'run'. lines 29-38: { "gas_used": 0, "status": { - "Discard": { - "status_code": "13", - "status_code_name": "MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND" - } + "Discard": 13 } } diff --git a/integration-tests/check/gas_used_out.exp b/integration-tests/check/gas_used_out.exp index e15038ba..2865080b 100644 --- a/integration-tests/check/gas_used_out.exp +++ b/integration-tests/check/gas_used_out.exp @@ -3,11 +3,15 @@ processed 6 tasks task 4 'run'. lines 9-30: { "gas_used": 700, - "status": "OutOfGas" + "status": { + "Keep": "OutOfGas" + } } task 5 'run'. lines 33-44: { "gas_used": 24183, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/check/resource_move_to_or_from.exp b/integration-tests/check/resource_move_to_or_from.exp index 749a5076..feb90c02 100644 --- a/integration-tests/check/resource_move_to_or_from.exp +++ b/integration-tests/check/resource_move_to_or_from.exp @@ -3,23 +3,31 @@ processed 8 tasks task 4 'run'. lines 45-56: { "gas_used": 15813, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 60-71: { "gas_used": 25462, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 75-88: { "gas_used": 32836, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 91-104: { "gas_used": 27668, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/collection2/collection_add_by_other.exp b/integration-tests/collection2/collection_add_by_other.exp index 3f97aa29..65e72977 100644 --- a/integration-tests/collection2/collection_add_by_other.exp +++ b/integration-tests/collection2/collection_add_by_other.exp @@ -3,33 +3,41 @@ processed 9 tasks task 5 'run'. lines 33-42: { "gas_used": 24244, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 45-58: { "gas_used": 76259, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 61-73: { "gas_used": 64099, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 76-93: { "gas_used": 40545, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Collection2" - } - }, - "abort_code": "26370" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Collection2" + } + }, + 26370 + ] } } } diff --git a/integration-tests/collection2/collection_by_owner.exp b/integration-tests/collection2/collection_by_owner.exp index 83fccdb8..bb68201f 100644 --- a/integration-tests/collection2/collection_by_owner.exp +++ b/integration-tests/collection2/collection_by_owner.exp @@ -3,45 +3,57 @@ processed 13 tasks task 5 'run'. lines 29-42: { "gas_used": 104529, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 45-61: { "gas_used": 89785, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 64-81: { "gas_used": 107654, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 84-107: { "gas_used": 102649, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 110-124: { "gas_used": 79522, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 127-142: { "gas_used": 40869, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Collection2" - } - }, - "abort_code": "26626" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Collection2" + } + }, + 26626 + ] } } } @@ -49,21 +61,25 @@ task 10 'run'. lines 127-142: task 11 'run'. lines 146-170: { "gas_used": 164204, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 173-188: { "gas_used": 21613, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Collection2" - } - }, - "abort_code": "25857" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Collection2" + } + }, + 25857 + ] } } } diff --git a/integration-tests/collection2/collection_mut_by_other.exp b/integration-tests/collection2/collection_mut_by_other.exp index 7eb7b245..3ded5848 100644 --- a/integration-tests/collection2/collection_mut_by_other.exp +++ b/integration-tests/collection2/collection_mut_by_other.exp @@ -3,21 +3,25 @@ processed 10 tasks task 5 'run'. lines 35-44: { "gas_used": 24244, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 47-63: { "gas_used": 43443, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Collection2" - } - }, - "abort_code": "26114" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Collection2" + } + }, + 26114 + ] } } } @@ -25,17 +29,23 @@ task 6 'run'. lines 47-63: task 7 'run'. lines 66-79: { "gas_used": 69059, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 82-95: { "gas_used": 77874, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 98-111: { "gas_used": 69522, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/compare/compare.exp b/integration-tests/compare/compare.exp index 51489a97..4cfd3bd0 100644 --- a/integration-tests/compare/compare.exp +++ b/integration-tests/compare/compare.exp @@ -2,6 +2,8 @@ processed 3 tasks task 2 'run'. lines 5-62: { - "gas_used": 1789891, - "status": "Executed" + "gas_used": 2338303, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/dao/VoteStrategy.exp b/integration-tests/dao/VoteStrategy.exp deleted file mode 100644 index fc5a4436..00000000 --- a/integration-tests/dao/VoteStrategy.exp +++ /dev/null @@ -1 +0,0 @@ -processed 3 tasks diff --git a/integration-tests/dao/VoteStrategy.move b/integration-tests/dao/VoteStrategy.move deleted file mode 100644 index cfc6d475..00000000 --- a/integration-tests/dao/VoteStrategy.move +++ /dev/null @@ -1,365 +0,0 @@ -//# init -n dev - -//# faucet --addr default - -//# publish -module default::VoteStrategy{ -// use StarcoinFramework::DAOSpace::{Self, ProposalPluginCapability}; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::BCS; - use StarcoinFramework::Signer; - #[test_only] - use StarcoinFramework::Debug; - use StarcoinFramework::Vector; - use StarcoinFramework::Errors; - - const ERR_VOTING_STRATEGY_MAPPING_EXIST: u64 = 1411; - const ERR_PRE_ORDER_TYPE_INVALID: u64 = 1413; - const ERR_BCS_STATE_NTFS_LENGHT_TYPE_INVALID: u64 = 1414; - - - struct VoteStrategyPluginCapability has key{ - } - - struct SBTStrategy has key { - // https://stcscan.io/barnard/address/0x6bfb460477adf9dd0455d3de2fc7f211/resources - // 0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>, 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - // {"json":{"nft":{"vec":[{"base_meta":{"description":"0x","image":"0x","image_data":"0x69616d67655f64617461","name":"0x64616f313031"},"body":{"sbt":{"value":100}},"creator":"0x6bfb460477adf9dd0455d3de2fc7f211","id":1,"type_meta":{"id":1111}}]}},"raw":"0x016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"} - - strategy_name: vector, - // access_path: vector, - // access_path_suffix = user_address + access_path_suffix - access_path_suffix: vector, // /1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>, 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - // state: vector, - pre_order_types_vector: vector>, //sbt token deserialize pre order types vector in state bcs value - weight_factor: u128, // How to abstract into a function ? default 1 - } - - // veSTAR value - struct VeSTARStrategy has key { - strategy_name: vector, - // 0x6E9B83ADaA64f901048AE4bEAD8A1016/1/0x8c109349c6bd91411d6bc962e080c4a3::TokenSwapFarmBoost::UserInfo<0x00000000000000000000000000000001::STC::STC,0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - // access_path: vector, - // access_path_suffix = user_address + access_path_suffix - access_path_suffix: vector, // /1/0x8c109349c6bd91411d6bc962e080c4a3::TokenSwapFarmBoost::UserInfo<0x00000000000000000000000000000001::STC::STC,0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - // state: vector, - pre_order_types_vector: vector>, //sbt token deserialize pre order types vector in state bcs value - weight_factor: u128, // How to abstract into a function ? default 1 - } - - struct BalanceStrategy has key { - // 0x8c109349c6bd91411d6bc962e080c4a3::TokenSwapFarmBoost::UserInfo<0x00000000000000000000000000000001::STC::STC, 0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - // - // {"json":{"boost_factor":250,"locked_vetoken":{"token":{"value":47945205478}},"user_amount":0},"raw":"0xfa00000000000000e6c6c1290b000000000000000000000000000000000000000000000000000000"} - - strategy_name: vector, //need by unique -// 0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> -// 0xcCF1ADEdf0Ba6f9BdB9A6905173A5d72/1/0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - // access_path_suffix = user_address + access_path_suffix - access_path_suffix: vector, // /1/0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - // state: vector, - pre_order_types_vector: vector>, //token balance deserialize pre order types vector in state bcs value - weight_factor: u128, // How to abstract into a function ? default 1 - } - - - // TODO extend to List to support multi stragegies for a DAO ? - struct StrategyMapping has key { - strategy_name: vector, - access_path_suffix: vector, // /1/0x8c109349c6bd91411d6bc962e080c4a3::TokenSwapFarmBoost::UserInfo<0x00000000000000000000000000000001::STC::STC,0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - offset: u64, //sbt token deserialize offset in state bcs value - weight_factor: u128, // How to abstract into a function ? default 1 - } - - public fun install_vote_strategy_plugin(_cap: &VoteStrategyPluginCapability, installer: &signer, strategy_name: vector, access_path_suffix:vector, offset: u64, weight_factor: u128){ - //TODO get dao_singer cap - let dao_signer = installer; - let dao_addr = Signer::address_of(dao_signer); - //TODO support multi stragegies for a DAO ? - assert!(exists>(dao_addr), ERR_VOTING_STRATEGY_MAPPING_EXIST); - - //TODO check vote strategy template - - let strategy = StrategyMapping{ - strategy_name, - access_path_suffix, - offset, - weight_factor, - }; - move_to(dao_signer, strategy); - } - - public fun uninstall_vote_strategy_plugin(_cap: &VoteStrategyPluginCapability, _uninstaller: &signer) acquires StrategyMapping { -// let dao_addr = Signer::address_of(dao_signer); - let dao_addr = DAORegistry::dao_address(); - let StrategyMapping { - strategy_name: _, - access_path_suffix: _, - offset: _, - weight_factor: _, - } = move_from>(dao_addr); - } - - - public fun get_vote_strategy_plugin():(vector, vector, u64, u128) acquires StrategyMapping{ - let dao_addr = DAORegistry::dao_address(); - let strategy_mapping = borrow_global>(dao_addr); - (*&strategy_mapping.strategy_name, *&strategy_mapping.access_path_suffix, strategy_mapping.offset, strategy_mapping.weight_factor) - } - - /// read snapshot vote value from state - public fun get_voting_power(_sender: address, _state_root: &vector, state: &vector) : u128 acquires StrategyMapping{ - //TODO how to verify state ? - - let dao_addr = DAORegistry::dao_address(); - let strategy_mapping = borrow_global>(dao_addr); - - //TODO check state with access_path_suffix ? - let offset = strategy_mapping.offset; - - let (value, _) = BCS::deserialize_u128(state, offset); - - //TODO calculate weight_factor - value - } - - /// Move types - const TYPE_U8: vector = b"u8"; - const TYPE_U64: vector = b"u64"; - const TYPE_U128: vector = b"u128"; - const TYPE_BYTES: vector = b"bytes"; - const TYPE_BYTES_VECTOR: vector = b"bytes_vector"; - const TYPE_ADDRESS: vector = b"address"; - const TYPE_BOOL: vector = b"bool"; - const TYPE_OPTION_BYTES: vector = b"option_bytes"; - - - /// deserialize sbt value from bcs state - public fun deserialize_sbt_value_from_bcs_state(state: &vector, pre_order_types_vector: &vector>) : u128{ - let len = Vector::length>(pre_order_types_vector); - if (len == 0) { - return 0u128 - }; - - // nfts array length - let ctype = Vector::borrow(&mut *pre_order_types_vector, 0); - assert!(TYPE_U8 == *ctype, Errors::invalid_state(ERR_BCS_STATE_NTFS_LENGHT_TYPE_INVALID)); - let offset = 0; - let (nfts_len, _offset) = BCS::deserialize_u8(state, offset); - // user has no sbt yet - if (nfts_len == 0) { - return 0u128 - }; - deserialize_resource_value(state, pre_order_types_vector) - } - - public fun deserialize_vestar_value_from_bcs_state(state: &vector, pre_order_types_vector: &vector>) : u128{ - let len = Vector::length>(pre_order_types_vector); - if (len == 0) { - return 0u128 - }; - deserialize_resource_value(state, pre_order_types_vector) - } - - public fun deserialize_balance_from_bcs_state(state: &vector, pre_order_types_vector: &vector>) : u128{ - let len = Vector::length>(pre_order_types_vector); - if (len == 0) { - return 0u128 - }; - deserialize_resource_value(state, pre_order_types_vector) - } - - public fun deserialize_resource_value(input: &vector, pre_order_types_vector: &vector>) : u128{ - // {address, u64, {...}, {...}, {...}} - let len = Vector::length>(pre_order_types_vector); - if (len == 0) { - return 0u128 - }; - let idx = 0; - let offset = 0; - loop { - if (idx >= len) { - break - }; - let ctype = Vector::borrow(pre_order_types_vector, idx); - offset = deserialize_one_type_cursor(input, ctype, offset); - idx = idx + 1; - }; - let (amount_value, _offset) = BCS::deserialize_u128(input, offset); - amount_value - } - - public fun deserialize_one_type_cursor(input: &vector, ctype: &vector, offset:u64) : u64 { - if (TYPE_U8 == *ctype) { - offset = BCS::skip_u8(input, offset); - } else if (TYPE_U64 == *ctype) { - offset = BCS::skip_u64(input, offset); - } else if (TYPE_U128 == *ctype) { - offset = BCS::skip_u128(input, offset); - } else if (TYPE_BYTES == *ctype) { - offset = BCS::skip_bytes(input, offset); - } else if (TYPE_BYTES_VECTOR == *ctype) { - offset = BCS::skip_bytes_vector(input, offset); - } else if (TYPE_ADDRESS == *ctype) { - offset = BCS::skip_address(input, offset); - } else if (TYPE_BOOL == *ctype) { - offset = BCS::skip_bool(input, offset); - } else if (TYPE_OPTION_BYTES == *ctype) { - offset = BCS::skip_option_bytes(input, offset); - } else { - abort Errors::invalid_argument(ERR_PRE_ORDER_TYPE_INVALID) - }; - offset - } - - #[test] - fun test_deserialize_sbt_value() { - let _state = x"016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"; - - let pre_order_types_vector = Vector::empty>(); - Vector::push_back(&mut pre_order_types_vector, b"u8"); - Vector::push_back(&mut pre_order_types_vector, b"address"); - Vector::push_back(&mut pre_order_types_vector, b"u64"); - Vector::push_back(&mut pre_order_types_vector, b"bytes"); - Vector::push_back(&mut pre_order_types_vector, b"bytes"); - Vector::push_back(&mut pre_order_types_vector, b"bytes"); - Vector::push_back(&mut pre_order_types_vector, b"bytes"); - Vector::push_back(&mut pre_order_types_vector, b"u64"); - - let sbt_value = deserialize_sbt_value_from_bcs_state(&_state, &pre_order_types_vector); - let _expect_sb_value = 100; - assert!(_expect_sb_value == sbt_value, 8001); - Debug::print(&sbt_value); - } - - - #[test] - fun test_origin_deserialize_sbt_value_from_bcs_state() { - // https://stcscan.io/barnard/address/0x6bfb460477adf9dd0455d3de2fc7f211/resources - // 0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>, 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - // {"json":{"nft":{"vec":[{"base_meta":{"description":"0x","image":"0x","image_data":"0x69616d67655f64617461","name":"0x64616f313031"},"body":{"sbt":{"value":100}},"creator":"0x6bfb460477adf9dd0455d3de2fc7f211","id":1,"type_meta":{"id":1111}}]}},"raw":"0x016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"} - let bs = x"016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"; - Debug::print>(&bs); - let offset = 0; - - // array length - let offset = BCS::skip_u8(&bs, offset); - // creator - let offset = BCS::skip_address(&bs, offset); - // id - let offset = BCS::skip_u64(&bs, offset); - Debug::print(&offset); - // base_meta - let offset = BCS::skip_bytes(&bs, offset); - let offset = BCS::skip_bytes(&bs, offset); - let offset = BCS::skip_bytes(&bs, offset); - let offset = BCS::skip_bytes(&bs, offset); - // type_meta - let offset = BCS::skip_u64(&bs, offset); - Debug::print(&offset); - // body - let (sbt_value, offset) = BCS::deserialize_u128(&bs, offset); - Debug::print(&sbt_value); - Debug::print(&offset); - let expect_sb_value = 100; - assert!(expect_sb_value == sbt_value, 8003); - Debug::print(&b"testdao02"); - } - - - #[test] - fun test_origin_deserialize_vestar_value_from_bcs_state() { - // {"json":{"boost_factor":250,"locked_vetoken":{"token":{"value":47945205478}},"user_amount":0},"raw":"0xfa00000000000000e6c6c1290b000000000000000000000000000000000000000000000000000000"} - let bs = x"fa0000000000000038bc7e1800000000000000000000000000000000000000000000000000000000"; - Debug::print>(&bs); - - let (r, offset) = BCS::deserialize_u64(&bs, 0); - Debug::print(&r); - Debug::print(&offset); - let (r, offset) = BCS::deserialize_u128(&bs, offset); - Debug::print(&r); - Debug::print(&offset); - let (r, offset) = BCS::deserialize_u128(&bs, offset); - Debug::print(&r); - Debug::print(&offset); - } - - #[test] - fun test_origin_deserialize_balance_from_bcs_state() { - // {"json":{"token":{"value":40350083678552}},"raw":"0x588167bcb22400000000000000000000"} - - let bs = x"588167bcb22400000000000000000000"; - Debug::print>(&bs); - let offset = 0; - - let (balance, offset) = BCS::deserialize_u128(&bs, offset); - Debug::print(&balance); - Debug::print(&offset); - } - - #[test] - fun test_bcs() { - // vector - let v = x""; - let expected_output = x"00"; - let v_bcs = BCS::to_bytes(&v); - Debug::print(&v_bcs); - assert!(copy v_bcs == expected_output, 8006); - - let offset = 0; - let (_r, offset) = BCS::deserialize_bytes(&v_bcs, offset); - Debug::print(&_r); - Debug::print(&offset); - - // vector> - } - - #[test] - fun test_origin_deserialize_nfts_from_bcs_state() { - // https://stcscan.io/main/address/0x44bc6adfdc1f718ed2014699b239f035/resources - // 0x00000000000000000000000000000001::NFTGallery::NFTGallery<0x2d32bee4f260694a0b3f1143c64a505a::Market::GoodsNFTInfo, 0x2d32bee4f260694a0b3f1143c64a505a::Market::GoodsNFTBody> - // {"json":{"deposit_events":{"counter":2,"guid":"0x180000000000000044bc6adfdc1f718ed2014699b239f035"},"items":[{"base_meta":{"description":"0x41646f707420746865206669727374204e4654206f6e2053746172636f696e2066726f6d2074686520426f72656420456c697a616265746820494920636f6c6c656374696f6e2e2068747470733a2f2f747769747465722e636f6d2f426f726564456c697a6162657468","image":"0x68747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f393437353333373132313434313834362e706e673f782d6f73732d70726f636573733d696d6167652f726573697a652c775f3634302f726573697a652c685f363430","image_data":"0x","name":"0x233131"},"body":{"quantity":1},"creator":"0xa86c0fdd86072f8a4a36c1eb756defec","id":499,"type_meta":{"has_in_kind":false,"mail":"0x","resource_url":"0x68747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f393437353333373132313434313834362e706e67","type":1002}},{"base_meta":{"description":"0x41646f707420746865206669727374204e4654206f6e2053746172636f696e2066726f6d2074686520426f72656420456c697a616265746820494920636f6c6c656374696f6e2e2068747470733a2f2f747769747465722e636f6d2f426f726564456c697a6162657468","image":"0x68747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f373336333338333932393234323336392e706e673f782d6f73732d70726f636573733d696d6167652f726573697a652c775f3634302f726573697a652c685f363430","image_data":"0x","name":"0x233233"},"body":{"quantity":1},"creator":"0xa86c0fdd86072f8a4a36c1eb756defec","id":501,"type_meta":{"has_in_kind":false,"mail":"0x","resource_url":"0x68747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f373336333338333932393234323336392e706e67","type":1002}}],"withdraw_events":{"counter":0,"guid":"0x170000000000000044bc6adfdc1f718ed2014699b239f035"}},"raw":"0x000000000000000018170000000000000044bc6adfdc1f718ed2014699b239f035020000000000000018180000000000000044bc6adfdc1f718ed2014699b239f03502a86c0fdd86072f8a4a36c1eb756defecf30100000000000003233131940168747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f393437353333373132313434313834362e706e673f782d6f73732d70726f636573733d696d6167652f726573697a652c775f3634302f726573697a652c685f363430006a41646f707420746865206669727374204e4654206f6e2053746172636f696e2066726f6d2074686520426f72656420456c697a616265746820494920636f6c6c656374696f6e2e2068747470733a2f2f747769747465722e636f6d2f426f726564456c697a616265746800ea030000000000006668747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f393437353333373132313434313834362e706e67000100000000000000a86c0fdd86072f8a4a36c1eb756defecf50100000000000003233233940168747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f373336333338333932393234323336392e706e673f782d6f73732d70726f636573733d696d6167652f726573697a652c775f3634302f726573697a652c685f363430006a41646f707420746865206669727374204e4654206f6e2053746172636f696e2066726f6d2074686520426f72656420456c697a616265746820494920636f6c6c656374696f6e2e2068747470733a2f2f747769747465722e636f6d2f426f726564456c697a616265746800ea030000000000006668747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f373336333338333932393234323336392e706e67000100000000000000"} - - let bs = x"000000000000000018170000000000000044bc6adfdc1f718ed2014699b239f035020000000000000018180000000000000044bc6adfdc1f718ed2014699b239f03502a86c0fdd86072f8a4a36c1eb756defecf30100000000000003233131940168747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f393437353333373132313434313834362e706e673f782d6f73732d70726f636573733d696d6167652f726573697a652c775f3634302f726573697a652c685f363430006a41646f707420746865206669727374204e4654206f6e2053746172636f696e2066726f6d2074686520426f72656420456c697a616265746820494920636f6c6c656374696f6e2e2068747470733a2f2f747769747465722e636f6d2f426f726564456c697a616265746800ea030000000000006668747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f393437353333373132313434313834362e706e67000100000000000000a86c0fdd86072f8a4a36c1eb756defecf50100000000000003233233940168747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f373336333338333932393234323336392e706e673f782d6f73732d70726f636573733d696d6167652f726573697a652c775f3634302f726573697a652c685f363430006a41646f707420746865206669727374204e4654206f6e2053746172636f696e2066726f6d2074686520426f72656420456c697a616265746820494920636f6c6c656374696f6e2e2068747470733a2f2f747769747465722e636f6d2f426f726564456c697a616265746800ea030000000000006668747470733a2f2f6333722e6f73732d636e2d6265696a696e672e616c6979756e63732e636f6d2f6e6f726d616c2f307861383663306664643836303732663861346133366331656237353664656665632f373336333338333932393234323336392e706e67000100000000000000"; - Debug::print>(&bs); - let offset = 0; - - let (_r, offset) = BCS::deserialize_u64(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - let (_r, offset) = BCS::deserialize_bytes(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - - let (_r, offset) = BCS::deserialize_u64(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - let (_r, offset) = BCS::deserialize_bytes(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - - // array length - let (_r, offset) = BCS::deserialize_u8(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - - let (_r, offset) = BCS::deserialize_address(&bs, offset); - Debug::print(&_r); - Debug::print(&@0xa86c0fdd86072f8a4a36c1eb756defec); - let (_r, offset) = BCS::deserialize_u64(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - let (_r, offset) = BCS::deserialize_bytes(&bs, offset); - let (_r, offset) = BCS::deserialize_bytes(&bs, offset); - let offset = BCS::skip_bytes(&bs, offset); - let offset = BCS::skip_bytes(&bs, offset); - let offset = BCS::skip_u64(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - let (_r, offset) = BCS::deserialize_u128(&bs, offset); - Debug::print(&_r); - Debug::print(&offset); - } - - -} \ No newline at end of file diff --git a/integration-tests/dao/test_dao_config.exp b/integration-tests/dao/test_dao_config.exp index eed65019..8c1e1b3e 100644 --- a/integration-tests/dao/test_dao_config.exp +++ b/integration-tests/dao/test_dao_config.exp @@ -3,27 +3,33 @@ processed 18 tasks task 4 'run'. lines 25-43: { "gas_used": 254270, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 46-67: { "gas_used": 212057, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 70-85: { "gas_used": 38559, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } @@ -32,14 +38,16 @@ task 7 'run'. lines 88-103: { "gas_used": 38559, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } @@ -48,14 +56,16 @@ task 8 'run'. lines 106-121: { "gas_used": 38664, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359943" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359943 + ] } } } @@ -64,14 +74,16 @@ task 9 'run'. lines 124-139: { "gas_used": 38559, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } @@ -80,14 +92,16 @@ task 10 'run'. lines 142-152: { "gas_used": 21364, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ModifyDaoConfigProposal" - } - }, - "abort_code": "102658" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ModifyDaoConfigProposal" + } + }, + 102658 + ] } } } @@ -95,21 +109,25 @@ task 10 'run'. lines 142-152: task 11 'run'. lines 155-195: { "gas_used": 131941, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 199-226: { "gas_used": 52355, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359943" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359943 + ] } } } @@ -118,14 +136,16 @@ task 13 'run'. lines 229-249: { "gas_used": 11212, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } @@ -134,14 +154,16 @@ task 14 'run'. lines 252-272: { "gas_used": 11250, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } @@ -150,14 +172,16 @@ task 15 'run'. lines 275-295: { "gas_used": 11358, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } @@ -166,14 +190,16 @@ task 16 'run'. lines 298-318: { "gas_used": 11393, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } @@ -182,14 +208,16 @@ task 17 'run'. lines 321-341: { "gas_used": 11431, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "360199" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360199 + ] } } } diff --git a/integration-tests/dao/test_dao_failure.exp b/integration-tests/dao/test_dao_failure.exp new file mode 100644 index 00000000..618bc66b --- /dev/null +++ b/integration-tests/dao/test_dao_failure.exp @@ -0,0 +1,448 @@ +processed 43 tasks + +task 5 'run'. lines 12-29: +{ + "gas_used": 313160, + "status": { + "Keep": "Executed" + } +} + +task 6 'run'. lines 31-41: +{ + "gas_used": 12417, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ModifyDaoConfigProposal" + } + }, + 102919 + ] + } + } +} + +task 7 'run'. lines 44-54: +{ + "gas_used": 162267, + "status": { + "Keep": "Executed" + } +} + +task 8 'run'. lines 58-68: +{ + "gas_used": 162267, + "status": { + "Keep": "Executed" + } +} + +task 9 'run'. lines 71-81: +{ + "gas_used": 125294, + "status": { + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + "function": 18, + "code_offset": 45 + } + } + } +} + +task 11 'run'. lines 86-104: +{ + "gas_used": 148929, + "status": { + "Keep": "Executed" + } +} + +task 12 'run'. lines 107-127: +{ + "gas_used": 162344, + "status": { + "Keep": "Executed" + } +} + +task 13 'run'. lines 131-155: +{ + "gas_used": 149577, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360449 + ] + } + } +} + +task 14 'run'. lines 158-176: +{ + "gas_used": 94115, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360967 + ] + } + } +} + +task 15 'run'. lines 179-197: +{ + "gas_used": 76714, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359431 + ] + } + } +} + +task 16 'run'. lines 200-218: +{ + "gas_used": 59161, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359687 + ] + } + } +} + +task 17 'run'. lines 221-239: +{ + "gas_used": 41374, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359431 + ] + } + } +} + +task 18 'run'. lines 242-255: +{ + "gas_used": 32131, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359687 + ] + } + } +} + +task 19 'run'. lines 258-271: +{ + "gas_used": 33839, + "status": { + "Keep": "Executed" + } +} + +task 20 'run'. lines 274-287: +{ + "gas_used": 15108, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359431 + ] + } + } +} + +task 21 'run'. lines 290-304: +{ + "gas_used": 29499, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359169 + ] + } + } +} + +task 23 'run'. lines 309-324: +{ + "gas_used": 37415, + "status": { + "Keep": "Executed" + } +} + +task 24 'run'. lines 327-341: +{ + "gas_used": 36805, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359682 + ] + } + } +} + +task 25 'run'. lines 344-364: +{ + "gas_used": 102595, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359169 + ] + } + } +} + +task 26 'run'. lines 367-381: +{ + "gas_used": 40995, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359169 + ] + } + } +} + +task 27 'run'. lines 384-402: +{ + "gas_used": 53206, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359169 + ] + } + } +} + +task 28 'run'. lines 406-424: +{ + "gas_used": 69415, + "status": { + "Keep": "Executed" + } +} + +task 30 'run'. lines 430-452: +{ + "gas_used": 163394, + "status": { + "Keep": "Executed" + } +} + +task 32 'run'. lines 456-470: +{ + "gas_used": 76680, + "status": { + "Keep": "Executed" + } +} + +task 33 'run'. lines 473-488: +{ + "gas_used": 39375, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359169 + ] + } + } +} + +task 34 'run'. lines 491-505: +{ + "gas_used": 74710, + "status": { + "Keep": "Executed" + } +} + +task 35 'run'. lines 508-519: +{ + "gas_used": 162267, + "status": { + "Keep": "Executed" + } +} + +task 37 'run'. lines 525-545: +{ + "gas_used": 108170, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360967 + ] + } + } +} + +task 38 'run'. lines 548-566: +{ + "gas_used": 59295, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360967 + ] + } + } +} + +task 39 'run'. lines 570-583: +{ + "gas_used": 32279, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360967 + ] + } + } +} + +task 40 'run'. lines 586-606: +{ + "gas_used": 162344, + "status": { + "Keep": "Executed" + } +} + +task 42 'run'. lines 612-630: +{ + "gas_used": 51131, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 360967 + ] + } + } +} diff --git a/deprecated/integration-tests/dao/test_dao_failure.move b/integration-tests/dao/test_dao_failure.move similarity index 100% rename from deprecated/integration-tests/dao/test_dao_failure.move rename to integration-tests/dao/test_dao_failure.move diff --git a/deprecated/integration-tests/dao/test_dao_propose.exp b/integration-tests/dao/test_dao_propose.exp similarity index 52% rename from deprecated/integration-tests/dao/test_dao_propose.exp rename to integration-tests/dao/test_dao_propose.exp index 1c3ff333..52ecc619 100644 --- a/deprecated/integration-tests/dao/test_dao_propose.exp +++ b/integration-tests/dao/test_dao_propose.exp @@ -3,69 +3,89 @@ processed 21 tasks task 4 'run'. lines 10-24: { "gas_used": 216046, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 27-37: { "gas_used": 162267, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 40-62: { "gas_used": 26430, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 68-84: { "gas_used": 148289, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 87-103: { "gas_used": 140583, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 109-127: { "gas_used": 171029, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 131-151: { "gas_used": 154638, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 154-187: { "gas_used": 503674, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 15 'run'. lines 194-216: { "gas_used": 157265, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 17 'run'. lines 223-235: { "gas_used": 32339, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "359169" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 359169 + ] } } } @@ -73,11 +93,15 @@ task 17 'run'. lines 223-235: task 18 'run'. lines 238-254: { "gas_used": 163394, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 20 'run'. lines 261-275: { "gas_used": 76680, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/deprecated/integration-tests/dao/test_dao_propose.move b/integration-tests/dao/test_dao_propose.move similarity index 100% rename from deprecated/integration-tests/dao/test_dao_propose.move rename to integration-tests/dao/test_dao_propose.move diff --git a/integration-tests/dao/test_mint_dao_proposal.exp b/integration-tests/dao/test_mint_dao_proposal.exp index b54a16e2..6b095d53 100644 --- a/integration-tests/dao/test_mint_dao_proposal.exp +++ b/integration-tests/dao/test_mint_dao_proposal.exp @@ -3,39 +3,49 @@ processed 19 tasks task 5 'run'. lines 32-52: { "gas_used": 125500, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 54-68: { "gas_used": 116988, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 71-82: { "gas_used": 34360, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 85-98: { "gas_used": 119972, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 101-110: { "gas_used": 25986, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Dao" - } - }, - "abort_code": "358658" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Dao" + } + }, + 358658 + ] } } } @@ -44,14 +54,16 @@ task 10 'run'. lines 113-124: { "gas_used": 21364, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "MintDaoProposal" - } - }, - "abort_code": "102658" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "MintDaoProposal" + } + }, + 102658 + ] } } } @@ -59,29 +71,39 @@ task 10 'run'. lines 113-124: task 11 'run'. lines 127-137: { "gas_used": 163397, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 140-150: { "gas_used": 150826, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 14 'run'. lines 156-172: { "gas_used": 141603, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 16 'run'. lines 177-198: { "gas_used": 157785, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 18 'run'. lines 204-222: { "gas_used": 161473, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/daospace/dao_account.exp b/integration-tests/daospace/dao_account.exp deleted file mode 100644 index d5653729..00000000 --- a/integration-tests/daospace/dao_account.exp +++ /dev/null @@ -1,45 +0,0 @@ -processed 6 tasks - -task 2 'run'. lines 6-23: -{ - "gas_used": 904650, - "status": "Executed" -} - -task 3 'run'. lines 28-40: -{ - "gas_used": 95609, - "status": "Executed" -} - -task 4 'run'. lines 42-51: -{ - "gas_used": 780020, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOAccount" - } - }, - "abort_code": "25862" - } - } -} - -task 5 'run'. lines 53-61: -{ - "gas_used": 778789, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOAccount" - } - }, - "abort_code": "25862" - } - } -} diff --git a/integration-tests/daospace/dao_account.move b/integration-tests/daospace/dao_account.move deleted file mode 100644 index 04161ad9..00000000 --- a/integration-tests/daospace/dao_account.move +++ /dev/null @@ -1,61 +0,0 @@ -//# init -n dev - -//# faucet --addr alice --amount 10000000 - - -//# run --signers alice -script { - use StarcoinFramework::STC::STC; - use StarcoinFramework::Account; - use StarcoinFramework::DAOAccount; - use StarcoinFramework::Signer; - - fun main(sender: signer) { - let dao_cap = DAOAccount::create_account(&sender); - let dao_signer = DAOAccount::dao_signer(&dao_cap); - let dao_address= Signer::address_of(&dao_signer); - Account::pay_from(&sender, dao_address, 10000); - let dao_balance = Account::balance(dao_address); - assert!(dao_balance == 10000, 1001); - DAOAccount::restore_dao_account_cap(&sender, dao_cap); - } -} -// check: EXECUTED - - - - -//# run --signers alice -script { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::Vector; - - fun main(sender: signer) { - let dao_cap = DAOAccount::extract_dao_account_cap(&sender); - let package_hash = Vector::empty(); - DAOAccount::submit_upgrade_plan(&dao_cap, package_hash, 2, false); - DAOAccount::restore_dao_account_cap(&sender, dao_cap); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::DAOAccount; - - fun main(sender: signer) { - let dao_cap = DAOAccount::create_account(&sender); - DAOAccount::restore_dao_account_cap(&sender, dao_cap); - } -} -// check: ABORT, code 25862. Reason: alice already has a DAOAccountCap - -//# run --signers alice -script { - use StarcoinFramework::DAOAccount; - - fun main(sender: signer) { - DAOAccount::create_account_entry(sender); - } -} -// check: ABORT, code 25862. Reason: alice already has a DAOAccountCap \ No newline at end of file diff --git a/integration-tests/daospace/dao_create.exp b/integration-tests/daospace/dao_create.exp deleted file mode 100644 index 14bc41a1..00000000 --- a/integration-tests/daospace/dao_create.exp +++ /dev/null @@ -1,24 +0,0 @@ -processed 11 tasks - -task 4 'run'. lines 9-17: -{ - "gas_used": 791553, - "status": "Executed" -} - -task 5 'view'. lines 19-19: -store key 0x00000000000000000000000000000001::DAOAccount::DAOAccountCap { - dao_address: bf3a917cf4fb6425b95cc12763e6038b -} - -task 7 'run'. lines 55-63: -{ - "gas_used": 79013, - "status": "Executed" -} - -task 10 'run'. lines 69-77: -{ - "gas_used": 1058109, - "status": "Executed" -} diff --git a/integration-tests/daospace/dao_create.move b/integration-tests/daospace/dao_create.move deleted file mode 100644 index 03a0e3fc..00000000 --- a/integration-tests/daospace/dao_create.move +++ /dev/null @@ -1,77 +0,0 @@ -//# init -n dev - -//# faucet --addr alice --amount 10000000000 - -//# faucet --addr bob --amount 10000000000 - -//# block --author=0x3 --timestamp 900000 - -//# run --signers alice -script{ - use StarcoinFramework::DAOAccount; - - fun main(sender: signer){ - DAOAccount::create_account_entry(sender); - } -} -// check: EXECUTED - -//# view --address alice --resource 0x1::DAOAccount::DAOAccountCap - -//# package -module 0xbf3a917cf4fb6425b95cc12763e6038b::XDAO { - use StarcoinFramework::Option; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::DAOAccount; - struct X has store, drop {} - - const NAME: vector = b"X"; - public (script) fun create_new_proposal_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,) - { - - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - - let cap = DAOAccount::extract_dao_account_cap(&sender); - DAOSpace::create_dao(cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let witness = X {}; - let member_cap = DAOSpace::acquire_member_cap(&witness); - DAOSpace::join_member_with_member_cap(&member_cap, &sender, Option::none>(), Option::none>(), 1); - } -} - -//# run --signers alice --args {{$.package[0].package_hash}} -script{ - use StarcoinFramework::DAOAccount; - - fun main(sender: signer, package_hash: vector){ - DAOAccount::submit_upgrade_plan_entry(sender, package_hash, 1, false); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 90240000 - -//# deploy {{$.package[0].file}} --signers bob - -//# run --signers alice -script{ - use 0xbf3a917cf4fb6425b95cc12763e6038b::XDAO; - - fun main(sender: signer){ - XDAO::create_new_proposal_dao(sender, 1000, 1000, 1, 1000, 1000); - } -} -// check: EXECUTED \ No newline at end of file diff --git a/integration-tests/daospace/dao_extension_point_init.exp b/integration-tests/daospace/dao_extension_point_init.exp deleted file mode 100644 index a5ebe27b..00000000 --- a/integration-tests/daospace/dao_extension_point_init.exp +++ /dev/null @@ -1,22 +0,0 @@ -processed 5 tasks - -task 3 'view'. lines 7-7: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 1 -} - -task 4 'run'. lines 9-17: -{ - "gas_used": 13211, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "25606" - } - } -} diff --git a/integration-tests/daospace/dao_extension_point_init.move b/integration-tests/daospace/dao_extension_point_init.move deleted file mode 100644 index 39279266..00000000 --- a/integration-tests/daospace/dao_extension_point_init.move +++ /dev/null @@ -1,19 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr bob --amount 2000000000 - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# run --signers Genesis -script { - use StarcoinFramework::DAOExtensionPoint; - - fun main(_sender: signer) { - DAOExtensionPoint::initialize(); - } -} -// check: MoveAbort - - diff --git a/integration-tests/daospace/dao_extension_point_publish_version.exp b/integration-tests/daospace/dao_extension_point_publish_version.exp deleted file mode 100644 index d3083287..00000000 --- a/integration-tests/daospace/dao_extension_point_publish_version.exp +++ /dev/null @@ -1,178 +0,0 @@ -processed 16 tasks - -task 4 'run'. lines 46-54: -{ - "gas_used": 418615, - "status": "Executed" -} - -task 5 'view'. lines 56-56: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 6 'view'. lines 58-58: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 54657374457874656e74696f6e506f696e74 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 2 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f70625f646f63 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 7 'run'. lines 60-68: -{ - "gas_used": 152078, - "status": "Executed" -} - -task 8 'view'. lines 70-70: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 9 'view'. lines 72-72: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 54657374457874656e74696f6e506f696e74 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 3 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f70625f646f63 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 2 - tag: 76302e312e31 - types_d_ts: 697066733a2f2f74797065735f645f74735f31 - document: 697066733a2f2f70625f646f6331 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 10 'run'. lines 74-82: -{ - "gas_used": 156078, - "status": "Executed" -} - -task 11 'view'. lines 84-84: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 12 'view'. lines 86-86: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 54657374457874656e74696f6e506f696e74 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 4 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f70625f646f63 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 2 - tag: 76302e312e31 - types_d_ts: 697066733a2f2f74797065735f645f74735f31 - document: 697066733a2f2f70625f646f6331 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 3 - tag: 76302e312e32 - types_d_ts: 697066733a2f2f74797065735f645f74735f32 - document: 697066733a2f2f6474735f646f6332 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 13 'run'. lines 88-96: -{ - "gas_used": 111323, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "27399" - } - } -} - -task 14 'view'. lines 98-98: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 15 'view'. lines 100-100: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 54657374457874656e74696f6e506f696e74 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 4 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f70625f646f63 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 2 - tag: 76302e312e31 - types_d_ts: 697066733a2f2f74797065735f645f74735f31 - document: 697066733a2f2f70625f646f6331 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 3 - tag: 76302e312e32 - types_d_ts: 697066733a2f2f74797065735f645f74735f32 - document: 697066733a2f2f6474735f646f6332 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} diff --git a/integration-tests/daospace/dao_extension_point_publish_version.move b/integration-tests/daospace/dao_extension_point_publish_version.move deleted file mode 100644 index e3ab3fa8..00000000 --- a/integration-tests/daospace/dao_extension_point_publish_version.move +++ /dev/null @@ -1,100 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# publish -module creator::TestExtentionPoint { - use StarcoinFramework::Option; - use StarcoinFramework::DAOExtensionPoint; - - struct TestExtentionPoint has store, copy, drop {} - - const NAME: vector = b"TestExtentionPoint"; - - public(script) fun initialize(sender: signer) { - DAOExtensionPoint::register( - &sender, - NAME, - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://pb_doc", - Option::none(), - ); - } - - public(script) fun publish_version_v1(sender: signer) { - DAOExtensionPoint::publish_version( - &sender, - b"v0.1.1", - b"ipfs://types_d_ts_1", - b"ipfs://pb_doc1", - ); - } - - public(script) fun publish_version_v2(sender: signer) { - DAOExtensionPoint::publish_version( - &sender, - b"v0.1.2", - b"ipfs://types_d_ts_2", - b"ipfs://dts_doc2", - ); - } -} - -//# run --signers creator -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::initialize(sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> - -//# run --signers creator -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::publish_version_v1(sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> - -//# run --signers creator -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::publish_version_v2(sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> - -//# run --signers creator -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::publish_version_v2(sender); - } -} -// check: MoveAbort - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> diff --git a/integration-tests/daospace/dao_extension_point_register.exp b/integration-tests/daospace/dao_extension_point_register.exp deleted file mode 100644 index 10b5f221..00000000 --- a/integration-tests/daospace/dao_extension_point_register.exp +++ /dev/null @@ -1,108 +0,0 @@ -processed 13 tasks - -task 4 'run'. lines 48-56: -{ - "gas_used": 466466, - "status": "Executed" -} - -task 5 'view'. lines 58-58: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 6 'view'. lines 60-60: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 54657374457874656e74696f6e506f696e74 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - 4f533d53746172636f696e, - 53746f72653d49504653, - ] - next_version_number: 2 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f6474735f646f63 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 7 'run'. lines 62-70: -{ - "gas_used": 60246, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "26630" - } - } -} - -task 8 'view'. lines 72-72: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 54657374457874656e74696f6e506f696e74 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - 4f533d53746172636f696e, - 53746f72653d49504653, - ] - next_version_number: 2 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f6474735f646f63 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 10 'run'. lines 100-108: -{ - "gas_used": 38409, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "28167" - } - } -} - -task 12 'run'. lines 137-145: -{ - "gas_used": 137491, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "28167" - } - } -} diff --git a/integration-tests/daospace/dao_extension_point_register.move b/integration-tests/daospace/dao_extension_point_register.move deleted file mode 100644 index c2f85179..00000000 --- a/integration-tests/daospace/dao_extension_point_register.move +++ /dev/null @@ -1,145 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# publish -module creator::TestExtentionPoint { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOExtensionPoint; - - struct TestExtentionPoint has store, copy, drop {} - - const NAME: vector = b"TestExtentionPoint"; - - public(script) fun initialize(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOExtensionPoint::register( - &sender, - NAME, - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://dts_doc", - Option::some(labels), - ); - } - - public(script) fun initialize_with_long_text(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOExtensionPoint::register( - &sender, - b"0123456789012345678901234567890123456789012345678901234567890123456789", - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://dts_doc", - Option::some(labels), - ); - } -} - -//# run --signers creator -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::initialize(sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> - -//# run --signers creator -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::initialize(sender); - } -} -// check: MoveAbort - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> - -//# publish -module creator::TestExtentionPoint2 { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOExtensionPoint; - - struct TestExtentionPoint2 has store, copy, drop {} - - const NAME: vector = b"TestExtentionPoint2"; - - public(script) fun initialize_with_long_text(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOExtensionPoint::register( - &sender, - b"0123456789012345678901234567890123456789012345678901234567890123456789", - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://dts_doc", - Option::some(labels), - ); - } -} - -//# run --signers creator -script { - use creator::TestExtentionPoint2; - - fun main(sender: signer) { - TestExtentionPoint2::initialize_with_long_text(sender); - } -} -// check: MoveAbort - - -//# publish -module creator::TestExtentionPoint3 { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOExtensionPoint; - - struct TestExtentionPoint3 has store, copy, drop {} - - const NAME: vector = b"TestExtentionPoint3"; - - public(script) fun initialize_with_long_text(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=ipfs://0123456789012345678901234567890123456789012345678901234567890123456789"); - - DAOExtensionPoint::register( - &sender, - b"XXXX", - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://dts_doc", - Option::some(labels), - ); - } -} - -//# run --signers creator -script { - use creator::TestExtentionPoint3; - - fun main(sender: signer) { - TestExtentionPoint3::initialize_with_long_text(sender); - } -} -// check: MoveAbort diff --git a/integration-tests/daospace/dao_extension_point_star_and_unstar.exp b/integration-tests/daospace/dao_extension_point_star_and_unstar.exp deleted file mode 100644 index 38b8a71f..00000000 --- a/integration-tests/daospace/dao_extension_point_star_and_unstar.exp +++ /dev/null @@ -1,62 +0,0 @@ -processed 12 tasks - -task 6 'run'. lines 32-40: -{ - "gas_used": 418615, - "status": "Executed" -} - -task 7 'run'. lines 42-51: -{ - "gas_used": 59320, - "status": "Executed" -} - -task 8 'run'. lines 53-62: -{ - "gas_used": 15374, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "26881" - } - } -} - -task 9 'run'. lines 64-73: -{ - "gas_used": 59320, - "status": "Executed" -} - -task 10 'view'. lines 75-75: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 11 'view'. lines 77-77: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 54657374457874656e74696f6e506f696e74 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 2 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f70625f646f63 - created_at: 10 - }, - ] - star_count: 2 - created_at: 10 - updated_at: 10 -} diff --git a/integration-tests/daospace/dao_extension_point_star_and_unstar.move b/integration-tests/daospace/dao_extension_point_star_and_unstar.move deleted file mode 100644 index 434764af..00000000 --- a/integration-tests/daospace/dao_extension_point_star_and_unstar.move +++ /dev/null @@ -1,77 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr bob --amount 2000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::TestExtentionPoint { - use StarcoinFramework::Option; - use StarcoinFramework::DAOExtensionPoint; - - struct TestExtentionPoint has store, copy, drop {} - - const NAME: vector = b"TestExtentionPoint"; - - public(script) fun initialize(sender: signer) { - DAOExtensionPoint::register( - &sender, - NAME, - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://pb_doc", - Option::none(), - ); - } -} - -//# run --signers creator -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::initialize(sender); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::DAOExtensionPoint; - use creator::TestExtentionPoint; - - fun main(sender: signer) { - DAOExtensionPoint::star(&sender); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::DAOExtensionPoint; - use creator::TestExtentionPoint; - - fun main(sender: signer) { - DAOExtensionPoint::star(&sender); - } -} -// check: MoveAbort - -//# run --signers alice -script { - use StarcoinFramework::DAOExtensionPoint; - use creator::TestExtentionPoint; - - fun main(sender: signer) { - DAOExtensionPoint::star(&sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> diff --git a/integration-tests/daospace/dao_extension_point_transfer_owner.exp b/integration-tests/daospace/dao_extension_point_transfer_owner.exp deleted file mode 100644 index 6bef1039..00000000 --- a/integration-tests/daospace/dao_extension_point_transfer_owner.exp +++ /dev/null @@ -1,162 +0,0 @@ -processed 17 tasks - -task 6 'run'. lines 32-40: -{ - "gas_used": 418615, - "status": "Executed" -} - -task 7 'run'. lines 42-61: -{ - "gas_used": 64233, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "26113" - } - } -} - -task 8 'run'. lines 63-72: -{ - "gas_used": 80067, - "status": "Executed" -} - -task 9 'view'. lines 74-74: -store key 0x00000000000000000000000000000001::NFTGallery::NFTGallery<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta, 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTBody> { - withdraw_events: store 0x00000000000000000000000000000001::Event::EventHandle<0x00000000000000000000000000000001::NFTGallery::WithdrawEvent<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta>> { - counter: 0 - guid: 0300000000000000b5d577dc9ce59725e29886632e69ecdf - } - deposit_events: store 0x00000000000000000000000000000001::Event::EventHandle<0x00000000000000000000000000000001::NFTGallery::DepositEvent<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta>> { - counter: 1 - guid: 0400000000000000b5d577dc9ce59725e29886632e69ecdf - } - items: [ - store 0x00000000000000000000000000000001::NFT::NFT<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta, 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTBody> { - creator: 1 - id: 1 - base_meta: copy drop store 0x00000000000000000000000000000001::NFT::Metadata { - name: 457874506f696e744f776e65724e4654 - image: - image_data: 697066733a2f2f516d6454776468466936317a68524d334d74504c78754b7961717633655045434c47734d6739704d726550763469 - description: 54686520657874656e73696f6e20706f696e74206f776e6572204e4654 - } - type_meta: copy drop store 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta { - extpoint_id: 1 - registry_address: 1 - } - body: store 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTBody { - dummy_field: false - } - }, - ] -} - -task 10 'run'. lines 76-85: -{ - "gas_used": 200904, - "status": "Executed" -} - -task 11 'view'. lines 87-87: -store key 0x00000000000000000000000000000001::NFTGallery::NFTGallery<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta, 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTBody> { - withdraw_events: store 0x00000000000000000000000000000001::Event::EventHandle<0x00000000000000000000000000000001::NFTGallery::WithdrawEvent<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta>> { - counter: 1 - guid: 0300000000000000b5d577dc9ce59725e29886632e69ecdf - } - deposit_events: store 0x00000000000000000000000000000001::Event::EventHandle<0x00000000000000000000000000000001::NFTGallery::DepositEvent<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta>> { - counter: 1 - guid: 0400000000000000b5d577dc9ce59725e29886632e69ecdf - } - items: [ - ] -} - -task 12 'view'. lines 89-89: -store key 0x00000000000000000000000000000001::NFTGallery::NFTGallery<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta, 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTBody> { - withdraw_events: store 0x00000000000000000000000000000001::Event::EventHandle<0x00000000000000000000000000000001::NFTGallery::WithdrawEvent<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta>> { - counter: 0 - guid: 0300000000000000a7dcef9aef26202fce82a7c7d6672afb - } - deposit_events: store 0x00000000000000000000000000000001::Event::EventHandle<0x00000000000000000000000000000001::NFTGallery::DepositEvent<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta>> { - counter: 1 - guid: 0400000000000000a7dcef9aef26202fce82a7c7d6672afb - } - items: [ - store 0x00000000000000000000000000000001::NFT::NFT<0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta, 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTBody> { - creator: 1 - id: 1 - base_meta: copy drop store 0x00000000000000000000000000000001::NFT::Metadata { - name: 457874506f696e744f776e65724e4654 - image: - image_data: 697066733a2f2f516d6454776468466936317a68524d334d74504c78754b7961717633655045434c47734d6739704d726550763469 - description: 54686520657874656e73696f6e20706f696e74206f776e6572204e4654 - } - type_meta: copy drop store 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTMeta { - extpoint_id: 1 - registry_address: 1 - } - body: store 0x00000000000000000000000000000001::DAOExtensionPoint::OwnerNFTBody { - dummy_field: false - } - }, - ] -} - -task 13 'run'. lines 91-110: -{ - "gas_used": 183643, - "status": "Executed" -} - -task 14 'view'. lines 112-112: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 15 'view'. lines 114-114: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 74657374 - description: 697066733a2f2f6465736372697074696f6e32 - labels: [ - 4f533d53746172636f696e, - 53746f72653d49504653, - ] - next_version_number: 2 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f70625f646f63 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 16 'run'. lines 117-133: -{ - "gas_used": 150116, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "NFT" - } - }, - "abort_code": "26372" - } - } -} diff --git a/integration-tests/daospace/dao_extension_point_transfer_owner.move b/integration-tests/daospace/dao_extension_point_transfer_owner.move deleted file mode 100644 index 9610ab56..00000000 --- a/integration-tests/daospace/dao_extension_point_transfer_owner.move +++ /dev/null @@ -1,133 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr bob --amount 2000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::TestExtentionPoint { - use StarcoinFramework::Option; - use StarcoinFramework::DAOExtensionPoint; - - struct TestExtentionPoint has store, copy, drop {} - - const NAME: vector = b"TestExtentionPoint"; - - public(script) fun initialize(sender: signer) { - DAOExtensionPoint::register( - &sender, - NAME, - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://pb_doc", - Option::none(), - ); - } -} - -//# run --signers bob -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::initialize(sender); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOExtensionPoint; - use creator::TestExtentionPoint; - - fun main(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOExtensionPoint::update(&sender, - b"test", - b"ipfs://description2", - Option::some(labels), - ); - } -} -// check: MoveAbort - -//# run --signers alice -script { - use StarcoinFramework::NFTGallery; - use StarcoinFramework::DAOExtensionPoint; - - fun main(sender: signer) { - NFTGallery::accept(&sender); - } -} -// check: EXECUTED - -//# view --address bob --resource 0x1::NFTGallery::NFTGallery<0x1::DAOExtensionPoint::OwnerNFTMeta,0x1::DAOExtensionPoint::OwnerNFTBody> - -//# run --signers bob -script { - use StarcoinFramework::NFTGallery; - use StarcoinFramework::DAOExtensionPoint; - - fun main(sender: signer) { - NFTGallery::transfer(&sender, 1, @alice); - } -} -// check: EXECUTED - -//# view --address bob --resource 0x1::NFTGallery::NFTGallery<0x1::DAOExtensionPoint::OwnerNFTMeta,0x1::DAOExtensionPoint::OwnerNFTBody> - -//# view --address alice --resource 0x1::NFTGallery::NFTGallery<0x1::DAOExtensionPoint::OwnerNFTMeta,0x1::DAOExtensionPoint::OwnerNFTBody> - -//# run --signers alice -script { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOExtensionPoint; - use creator::TestExtentionPoint; - - fun main(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOExtensionPoint::update(&sender, - b"test", - b"ipfs://description2", - Option::some(labels), - ); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> - - -//# run --signers alice -script { - use StarcoinFramework::NFT; - use StarcoinFramework::NFTGallery; - use StarcoinFramework::DAOExtensionPoint; - - fun main(sender: signer) { - let nft = NFTGallery::withdraw_one(&sender); - - let base_meta = *NFT::get_base_meta(&nft); - let type_meta = *NFT::get_type_meta(&nft); - NFT::update_meta(&sender, &mut nft, base_meta, type_meta); - - NFTGallery::deposit(&sender, nft); - } -} -// check: MoveAbort \ No newline at end of file diff --git a/integration-tests/daospace/dao_extension_point_update.exp b/integration-tests/daospace/dao_extension_point_update.exp deleted file mode 100644 index 96feca72..00000000 --- a/integration-tests/daospace/dao_extension_point_update.exp +++ /dev/null @@ -1,58 +0,0 @@ -processed 11 tasks - -task 6 'run'. lines 32-40: -{ - "gas_used": 418615, - "status": "Executed" -} - -task 7 'run'. lines 42-61: -{ - "gas_used": 64233, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOExtensionPoint" - } - }, - "abort_code": "26113" - } - } -} - -task 8 'run'. lines 63-82: -{ - "gas_used": 183643, - "status": "Executed" -} - -task 9 'view'. lines 84-84: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Registry { - next_id: 2 -} - -task 10 'view'. lines 86-86: -store key 0x00000000000000000000000000000001::DAOExtensionPoint::Entry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestExtentionPoint::TestExtentionPoint> { - id: 1 - name: 74657374 - description: 697066733a2f2f6465736372697074696f6e32 - labels: [ - 4f533d53746172636f696e, - 53746f72653d49504653, - ] - next_version_number: 2 - versions: [ - store 0x00000000000000000000000000000001::DAOExtensionPoint::Version { - number: 1 - tag: 76302e312e30 - types_d_ts: 697066733a2f2f74797065735f645f7473 - document: 697066733a2f2f70625f646f63 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} diff --git a/integration-tests/daospace/dao_extension_point_update.move b/integration-tests/daospace/dao_extension_point_update.move deleted file mode 100644 index f15c653e..00000000 --- a/integration-tests/daospace/dao_extension_point_update.move +++ /dev/null @@ -1,86 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr bob --amount 2000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::TestExtentionPoint { - use StarcoinFramework::Option; - use StarcoinFramework::DAOExtensionPoint; - - struct TestExtentionPoint has store, copy, drop {} - - const NAME: vector = b"TestExtentionPoint"; - - public(script) fun initialize(sender: signer) { - DAOExtensionPoint::register( - &sender, - NAME, - b"ipfs://description", - b"ipfs://types_d_ts", - b"ipfs://pb_doc", - Option::none(), - ); - } -} - -//# run --signers bob -script { - use creator::TestExtentionPoint; - - fun main(sender: signer) { - TestExtentionPoint::initialize(sender); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOExtensionPoint; - use creator::TestExtentionPoint; - - fun main(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOExtensionPoint::update(&sender, - b"test", - b"ipfs://description2", - Option::some(labels), - ); - } -} -// check: MoveAbort - -//# run --signers bob -script { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOExtensionPoint; - use creator::TestExtentionPoint; - - fun main(sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOExtensionPoint::update(&sender, - b"test", - b"ipfs://description2", - Option::some(labels), - ); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Registry - -//# view --address Genesis --resource 0x1::DAOExtensionPoint::Entry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestExtentionPoint::TestExtentionPoint> diff --git a/integration-tests/daospace/dao_grant.exp b/integration-tests/daospace/dao_grant.exp deleted file mode 100644 index 2ddbde11..00000000 --- a/integration-tests/daospace/dao_grant.exp +++ /dev/null @@ -1,53 +0,0 @@ -processed 17 tasks - -task 8 'run'. lines 104-115: -{ - "gas_used": 1677839, - "status": "Executed" -} - -task 9 'run'. lines 117-136: -{ - "gas_used": 445521, - "status": "Executed" -} - -task 10 'run'. lines 138-170: -{ - "gas_used": 666211, - "status": "Executed" -} - -task 12 'run'. lines 174-186: -{ - "gas_used": 52853, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOSpace" - } - }, - "abort_code": "77319" - } - } -} - -task 13 'run'. lines 188-208: -{ - "gas_used": 253287, - "status": "Executed" -} - -task 15 'run'. lines 212-232: -{ - "gas_used": 240921, - "status": "Executed" -} - -task 16 'run'. lines 234-248: -{ - "gas_used": 362869, - "status": "Executed" -} diff --git a/integration-tests/daospace/dao_grant.move b/integration-tests/daospace/dao_grant.move deleted file mode 100644 index 44606d73..00000000 --- a/integration-tests/daospace/dao_grant.move +++ /dev/null @@ -1,248 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//# faucet --addr bob --amount 10000000000 - -//# faucet --addr cindy --amount 10000000000 - -//# block --author 0x1 --timestamp 86200000 - -//# publish -module creator::DAOHelper { - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::STC; - use StarcoinFramework::Option; - use StarcoinFramework::Signer; - use StarcoinFramework::InstallPluginProposalPlugin::InstallPluginProposalPlugin; - use StarcoinFramework::AnyMemberPlugin::AnyMemberPlugin; - use StarcoinFramework::AnyMemberPlugin; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct X has store, copy, drop{} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,){ - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, required_caps()); - } - - struct XPlugin has store, drop{} - - public fun initialize_x_plugin(_sender: &signer) { - let witness = XPlugin{}; - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::XPlugin", - b"The X plugin.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://x-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::withdraw_token_cap_type()); - Vector::push_back(&mut caps, DAOSpace::grant_cap_type()); - caps - } - - public fun create_grant(sender:&signer, total:u128, start_time:u64,period:u64){ - let witness = XPlugin{}; - let grant_cap = DAOSpace::acquire_grant_cap(&witness); - DAOSpace::grant_offer(&grant_cap, Signer::address_of(sender), total, start_time, period); - DAOSpace::grant_accept_offer(sender) - } - - public fun grant_revoke(grantee:address){ - let witness = XPlugin{}; - let grant_cap = DAOSpace::acquire_grant_cap(&witness); - DAOSpace::grant_revoke(&grant_cap, grantee); - } -} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers creator -script{ - use creator::DAOHelper; - - fun main(sender: signer){ - DAOHelper::initialize_x_plugin(&sender); - - // time unit is millsecond - DAOHelper::create_dao(sender, 10000, 3600000, 2, 10000, 10); - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use creator::DAOHelper::{Self, X, XPlugin}; - use StarcoinFramework::DAOSpace::{query_grant, query_grant_withdrawable_amount}; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::STC; - - //alice create grant to alice - fun create_grant(sender: signer){ - DAOHelper::create_grant(&sender, 1000000000u128, 86400u64, 3600u64); - let grant_info = query_grant(@alice); - assert!(DAOSpace::query_grant_info_total(&grant_info) == 1000000000,1001); - assert!(DAOSpace::query_grant_info_withdraw(&grant_info)== 0,1002); - assert!(DAOSpace::query_grant_info_start_time(&grant_info) == 86400,1003); - assert!(DAOSpace::query_grant_info_period(&grant_info) == 3600,1004); - - assert!(query_grant_withdrawable_amount(@alice) == 0,1005); - } -} -// check: EXECUTED - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X, XPlugin}; - use StarcoinFramework::DAOSpace::{Self,query_grant, query_grant_withdrawable_amount, grant_withdraw}; - use StarcoinFramework::STC; - use StarcoinFramework::Account; - - //bob create grant to bob - fun create_grant(sender: signer){ - DAOHelper::create_grant(&sender, 1000000000u128, 86400u64, 0u64); - let grant_info = query_grant(@bob); - assert!(DAOSpace::query_grant_info_total(&grant_info) == 1000000000,1005); - assert!(DAOSpace::query_grant_info_withdraw(&grant_info)== 0,1006); - assert!(DAOSpace::query_grant_info_start_time(&grant_info) == 86400,1007); - assert!(DAOSpace::query_grant_info_period(&grant_info) == 0,1008); - - assert!(query_grant_withdrawable_amount(@bob) == 1000000000,1009); - - grant_withdraw(&sender, 500000000u128); - assert!(Account::balance(@bob) == 10000000000 + 500000000, 1010); - - let grant_info = query_grant(@bob); - assert!(DAOSpace::query_grant_info_total(&grant_info) == 1000000000,1011); - assert!(DAOSpace::query_grant_info_withdraw(&grant_info)== 500000000,1012); - assert!(DAOSpace::query_grant_info_start_time(&grant_info) == 86400,1013); - assert!(DAOSpace::query_grant_info_period(&grant_info) == 0,1014); - assert!(query_grant_withdrawable_amount(@bob) == 500000000,1015); - - DAOHelper::grant_revoke(@bob); - assert!(DAOSpace::is_exist_grant(@bob) == false, 1016); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86401000 - -//# run --signers alice -script{ - use creator::DAOHelper::{X, XPlugin}; - use StarcoinFramework::DAOSpace::{Self, query_grant_withdrawable_amount}; - use StarcoinFramework::STC; - - //alice withdraw more grant - fun withdraw_grant(sender: signer){ - assert!(query_grant_withdrawable_amount(@alice) == 277777, 1001); - DAOSpace::grant_withdraw(&sender, 377777u128); - } -} -// check: MoveAbort 77319 - -//# run --signers alice -script{ - use creator::DAOHelper::{X, XPlugin}; - use StarcoinFramework::DAOSpace::{Self, query_grant, query_grant_withdrawable_amount}; - use StarcoinFramework::STC; - use StarcoinFramework::Account; - - //alice withdraw grant - fun withdraw_grant(sender: signer){ - assert!(query_grant_withdrawable_amount(@alice) == 277777, 1001); - let old_balance = Account::balance(@alice); - DAOSpace::grant_withdraw(&sender, 277777u128); - assert!(Account::balance(@alice) == old_balance + 277777, 1002); - let grant_info = query_grant(@alice); - assert!(DAOSpace::query_grant_info_total(&grant_info) == 1000000000,1003); - assert!(DAOSpace::query_grant_info_withdraw(&grant_info)== 277777,1004); - assert!(DAOSpace::query_grant_info_start_time(&grant_info) == 86400,1005); - assert!(DAOSpace::query_grant_info_period(&grant_info) == 3600,1006); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 90000000 - -//# run --signers alice -script{ - use creator::DAOHelper::{X, XPlugin}; - use StarcoinFramework::DAOSpace::{Self, query_grant, query_grant_withdrawable_amount}; - use StarcoinFramework::STC; - use StarcoinFramework::Account; - - //alice withdraw grant - fun withdraw_grant(sender: signer){ - assert!(query_grant_withdrawable_amount(@alice) == 1000000000 - 277777, 1001); - let old_balance = Account::balance(@alice); - DAOSpace::grant_withdraw(&sender, 1000000000 - 277777); - assert!(Account::balance(@alice) == old_balance + 1000000000 - 277777, 1002); - let grant_info = query_grant(@alice); - assert!(DAOSpace::query_grant_info_total(&grant_info) == 1000000000,1003); - assert!(DAOSpace::query_grant_info_withdraw(&grant_info)== 1000000000,1004); - assert!(DAOSpace::query_grant_info_start_time(&grant_info) == 86400,1005); - assert!(DAOSpace::query_grant_info_period(&grant_info) == 3600,1006); - } -} -// check: EXECUTED - -//# run --signers cindy -script{ - use creator::DAOHelper::{Self, X, XPlugin}; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::STC; - - //alice create grant to cindy - fun create_grant(sender: signer){ - DAOHelper::create_grant(&sender, 1000000000u128, 90000u64, 3600u64); - assert!(DAOSpace::is_exist_grant(@cindy) == true, 1001); - DAOSpace::refund_grant(&sender); - assert!(DAOSpace::is_exist_grant(@cindy) == false, 1002); - } -} -// check: EXECUTED \ No newline at end of file diff --git a/integration-tests/daospace/dao_member_proposal.exp b/integration-tests/daospace/dao_member_proposal.exp deleted file mode 100644 index 8aa4c7f1..00000000 --- a/integration-tests/daospace/dao_member_proposal.exp +++ /dev/null @@ -1,58 +0,0 @@ -processed 29 tasks - -task 8 'run'. lines 69-78: -{ - "gas_used": 1292086, - "status": "Executed" -} - -task 10 'run'. lines 82-89: -{ - "gas_used": 630062, - "status": "Executed" -} - -task 15 'run'. lines 98-112: -{ - "gas_used": 104830, - "status": "Executed" -} - -task 17 'run'. lines 116-127: -{ - "gas_used": 577624, - "status": "Executed" -} - -task 18 'run'. lines 129-138: -{ - "gas_used": 523042, - "status": "Executed" -} - -task 21 'call'. lines 144-144: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>" - -task 23 'run'. lines 148-162: -{ - "gas_used": 6238590, - "status": "Executed" -} - -task 25 'run'. lines 166-176: -{ - "gas_used": 109761, - "status": "Executed" -} - -task 27 'run'. lines 180-190: -{ - "gas_used": 490902, - "status": "Executed" -} - -task 28 'run'. lines 192-202: -{ - "gas_used": 428125, - "status": "Executed" -} diff --git a/integration-tests/daospace/dao_member_proposal.move b/integration-tests/daospace/dao_member_proposal.move deleted file mode 100644 index a0efc501..00000000 --- a/integration-tests/daospace/dao_member_proposal.move +++ /dev/null @@ -1,202 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//# faucet --addr bob --amount 10000000000 - -//# faucet --addr cindy --amount 10000000000 - -//# block --author 0x1 --timestamp 86200000 - -//# publish -module creator::DAOHelper { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace::{Self}; - use StarcoinFramework::Option; - use StarcoinFramework::InstallPluginProposalPlugin::InstallPluginProposalPlugin; - use StarcoinFramework::AnyMemberPlugin::AnyMemberPlugin; - use StarcoinFramework::AnyMemberPlugin; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::MemberProposalPlugin; - use StarcoinFramework::MemberProposalPlugin::MemberProposalPlugin; - - struct X has store, copy, drop{} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,){ - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, MemberProposalPlugin::required_caps()); - } - - public fun create_offer_proposal(sender: &signer, title:vector, introduction:vector, description: vector, member: address, image_data:vector, image_url:vector, init_sbt: u128, action_delay: u64){ - MemberProposalPlugin::create_proposal(sender, title, introduction, description, member, image_data, image_url,init_sbt, action_delay); - } - - public fun execute_offer_proposal(sender: &signer, proposal_id: u64){ - MemberProposalPlugin::execute_proposal(sender, proposal_id); - } - - public fun add_member(sender: &signer, image_data:vector, image_url:vector){ - AnyMemberPlugin::join(sender, image_data, image_url); - } -} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers creator -script{ - use creator::DAOHelper; - - fun main(sender: signer){ - // time unit is millsecond - DAOHelper::create_dao(sender, 10000, 3600000, 2, 10000, 10); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86400010 - -//# run --signers alice -script { - use creator::DAOHelper::{Self}; - fun add_member(sender: signer){ - DAOHelper::add_member(&sender, b"",b"ipfs://"); - } - -} -//# block --author 0x1 --timestamp 86400020 - -//# block --author 0x1 --timestamp 86400030 - -//# block --author 0x1 --timestamp 86400040 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - Debug::print(&expect_parent_hash); - Debug::print(&parent_hash); - assert!(expect_parent_hash == parent_hash, 1001); - - Block::checkpoint(); - } -} -// check: EXECUTED - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun update(_account: signer, raw_header: vector) { - Debug::print(&raw_header); - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use creator::DAOHelper::{Self}; - - //alice create grant to alice - fun create_offer_proposal(sender: signer){ - DAOHelper::create_offer_proposal(&sender, b"Add member",b"Add bob to DAO", b"ipfs://",@bob,b"",b"ipfs://",1, 10000); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86411000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X --args {{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[2].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[3]}} -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Debug; - - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let choice = DAOSpace::choice_yes(); - Debug::print(&choice); - - DAOSpace::cast_vote(&sender, 1, snpashot_raw_proofs, choice); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 90012000 - -//# run --signers bob -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::DAOSpace; - - // execute action - fun queue_proposal_action(_sender: signer){ - DAOSpace::queue_proposal_action(1); - } -} -// check: EXECUTED - -//# block --author 0x4 --timestamp 90022000 - -//# run --signers alice -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::MemberProposalPlugin; - - // execute action - fun execute_action(sender: signer){ - MemberProposalPlugin::execute_proposal(&sender,1); - } -} -// check: EXECUTED - -//# run --signers bob -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::DAOSpace; - - // execute action - fun join(sender: signer){ - DAOSpace::accept_member_offer_entry(sender); - } -} -// check: EXECUTED \ No newline at end of file diff --git a/integration-tests/daospace/dao_plugin_marketplace_init.exp b/integration-tests/daospace/dao_plugin_marketplace_init.exp deleted file mode 100644 index 02c35924..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_init.exp +++ /dev/null @@ -1,17 +0,0 @@ -processed 4 tasks - -task 3 'run'. lines 7-15: -{ - "gas_used": 13211, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "25606" - } - } -} diff --git a/integration-tests/daospace/dao_plugin_marketplace_init.move b/integration-tests/daospace/dao_plugin_marketplace_init.move deleted file mode 100644 index 6e2984c5..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_init.move +++ /dev/null @@ -1,15 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr bob --amount 2000000000 - -//# run --signers Genesis -script { - use StarcoinFramework::DAOPluginMarketplace; - - fun main(_sender: signer) { - DAOPluginMarketplace::initialize(); - } -} -// check: MoveAbort \ No newline at end of file diff --git a/integration-tests/daospace/dao_plugin_marketplace_publish_plugin_version.exp b/integration-tests/daospace/dao_plugin_marketplace_publish_plugin_version.exp deleted file mode 100644 index 58056ecc..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_publish_plugin_version.exp +++ /dev/null @@ -1,228 +0,0 @@ -processed 14 tasks - -task 6 'run'. lines 46-54: -{ - "gas_used": 235944, - "status": "Executed" -} - -task 7 'run'. lines 56-64: -{ - "gas_used": 139939, - "status": "Executed" -} - -task 8 'run'. lines 66-74: -{ - "gas_used": 82611, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "27399" - } - } -} - -task 9 'view'. lines 76-76: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin::TestPlugin> { - id: 12 - name: 54657374506c7567696e - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 2 - versions: [ - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 1 - tag: 76302e312e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 10 'run'. lines 78-91: -{ - "gas_used": 870495, - "status": "Executed" -} - -task 11 'view'. lines 93-93: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin::TestPlugin> { - id: 12 - name: 54657374506c7567696e - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 8 - versions: [ - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 3 - tag: 76302e332e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 4 - tag: 76302e342e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 5 - tag: 76302e352e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 6 - tag: 76302e362e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 7 - tag: 76302e372e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 12 'run'. lines 95-103: -{ - "gas_used": 98367, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "27399" - } - } -} - -task 13 'view'. lines 105-105: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin::TestPlugin> { - id: 12 - name: 54657374506c7567696e - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 8 - versions: [ - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 3 - tag: 76302e332e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 4 - tag: 76302e342e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 5 - tag: 76302e352e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 6 - tag: 76302e362e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - store 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginVersion { - number: 7 - tag: 76302e372e30 - implement_extpoints: [ - 746573745f706c7567696e, - ] - depend_extpoints: [ - 746573745f706c7567696e, - ] - js_entry_uri: 697066733a2f2f6a735f656e7472795f757269 - created_at: 10 - }, - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} diff --git a/integration-tests/daospace/dao_plugin_marketplace_publish_plugin_version.move b/integration-tests/daospace/dao_plugin_marketplace_publish_plugin_version.move deleted file mode 100644 index 880d8f80..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_publish_plugin_version.move +++ /dev/null @@ -1,105 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr bob --amount 2000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::TestPlugin { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOPluginMarketplace; - - struct TestPlugin has store, drop {} - - const NAME: vector = b"TestPlugin"; - - public(script) fun register(_sender: signer) { - let witness = TestPlugin{}; - DAOPluginMarketplace::register_plugin( - &witness, - NAME, - b"ipfs://description", - Option::none(), - ); - } - - public fun publish_version(_sender: &signer, tag: vector) { - let vec = Vector::empty>(); - Vector::push_back>(&mut vec, b"test_plugin"); - - let witness = TestPlugin{}; - DAOPluginMarketplace::publish_plugin_version( - &witness, - tag, - *&vec, - *&vec, - b"ipfs://js_entry_uri" - ); - } -} - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::register(sender); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::publish_version(&sender, b"v0.1.0"); - } -} -// check: MoveAbort - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::publish_version(&sender, b"v0.1.0"); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin::TestPlugin> - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::publish_version(&sender, b"v0.2.0"); - TestPlugin::publish_version(&sender, b"v0.3.0"); - TestPlugin::publish_version(&sender, b"v0.4.0"); - TestPlugin::publish_version(&sender, b"v0.5.0"); - TestPlugin::publish_version(&sender, b"v0.6.0"); - TestPlugin::publish_version(&sender, b"v0.7.0"); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin::TestPlugin> - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::publish_version(&sender, b"v0.7.0"); - } -} -// check: MoveAbort - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin::TestPlugin> diff --git a/integration-tests/daospace/dao_plugin_marketplace_register_plugin.exp b/integration-tests/daospace/dao_plugin_marketplace_register_plugin.exp deleted file mode 100644 index adf29086..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_register_plugin.exp +++ /dev/null @@ -1,78 +0,0 @@ -processed 13 tasks - -task 6 'run'. lines 32-40: -{ - "gas_used": 235944, - "status": "Executed" -} - -task 7 'run'. lines 42-50: -{ - "gas_used": 33113, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "26630" - } - } -} - -task 8 'run'. lines 52-60: -{ - "gas_used": 33113, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "26630" - } - } -} - -task 10 'run'. lines 90-98: -{ - "gas_used": 283920, - "status": "Executed" -} - -task 11 'view'. lines 100-100: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin2::TestPlugin2> { - id: 13 - name: 54657374506c7567696e32 - description: 697066733a2f2f6465736372697074696f6e - labels: [ - 4f533d53746172636f696e, - 53746f72653d49504653, - ] - next_version_number: 1 - versions: [ - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 12 'run'. lines 102-110: -{ - "gas_used": 47029, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "26630" - } - } -} diff --git a/integration-tests/daospace/dao_plugin_marketplace_register_plugin.move b/integration-tests/daospace/dao_plugin_marketplace_register_plugin.move deleted file mode 100644 index 4072650b..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_register_plugin.move +++ /dev/null @@ -1,110 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr bob --amount 2000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::TestPlugin { - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - - struct TestPlugin has store, drop {} - - const NAME: vector = b"TestPlugin"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun register(_sender: signer) { - let witness = TestPlugin{}; - DAOPluginMarketplace::register_plugin( - &witness, - NAME, - b"ipfs://description", - Option::none(), - ); - } -} - -//# run --signers creator -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::register(sender); - } -} -// check: EXECUTED - -//# run --signers creator -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::register(sender); - } -} -// check: MoveAbort - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::register(sender); - } -} -// check: MoveAbort - - -//# publish -module creator::TestPlugin2 { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOPluginMarketplace; - - struct TestPlugin2 has store, drop {} - - const NAME: vector = b"TestPlugin2"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun register(_sender: signer) { - let witness = TestPlugin2{}; - - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - DAOPluginMarketplace::register_plugin( - &witness, - NAME, - b"ipfs://description", - Option::some(labels), - ); - } -} - -//# run --signers bob -script { - use creator::TestPlugin2; - - fun main(sender: signer) { - TestPlugin2::register(sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin2::TestPlugin2> - -//# run --signers alice -script { - use creator::TestPlugin2; - - fun main(sender: signer) { - TestPlugin2::register(sender); - } -} -// check: MoveAbort \ No newline at end of file diff --git a/integration-tests/daospace/dao_plugin_marketplace_star_plugin.exp b/integration-tests/daospace/dao_plugin_marketplace_star_plugin.exp deleted file mode 100644 index e90d2b59..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_star_plugin.exp +++ /dev/null @@ -1,87 +0,0 @@ -processed 14 tasks - -task 6 'run'. lines 46-54: -{ - "gas_used": 235944, - "status": "Executed" -} - -task 7 'run'. lines 56-67: -{ - "gas_used": 59320, - "status": "Executed" -} - -task 8 'run'. lines 69-80: -{ - "gas_used": 15374, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "26881" - } - } -} - -task 9 'run'. lines 82-93: -{ - "gas_used": 59320, - "status": "Executed" -} - -task 10 'view'. lines 95-95: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin::TestPlugin> { - id: 12 - name: 54657374506c7567696e - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 1 - versions: [ - ] - star_count: 2 - created_at: 10 - updated_at: 10 -} - -task 11 'run'. lines 98-109: -{ - "gas_used": 46959, - "status": "Executed" -} - -task 12 'view'. lines 111-111: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin::TestPlugin> { - id: 12 - name: 54657374506c7567696e - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 1 - versions: [ - ] - star_count: 1 - created_at: 10 - updated_at: 10 -} - -task 13 'run'. lines 113-124: -{ - "gas_used": 18574, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOPluginMarketplace" - } - }, - "abort_code": "27137" - } - } -} diff --git a/integration-tests/daospace/dao_plugin_marketplace_star_plugin.move b/integration-tests/daospace/dao_plugin_marketplace_star_plugin.move deleted file mode 100644 index a012ccde..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_star_plugin.move +++ /dev/null @@ -1,124 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr bob --amount 2000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::TestPlugin { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOPluginMarketplace; - - struct TestPlugin has store, drop {} - - const NAME: vector = b"TestPlugin"; - - public(script) fun register(_sender: signer) { - let witness = TestPlugin{}; - DAOPluginMarketplace::register_plugin( - &witness, - NAME, - b"ipfs://description", - Option::none(), - ); - } - - public(script) fun publish_version(_sender: signer) { - let vec = Vector::empty>(); - Vector::push_back>(&mut vec, b"test_plugin"); - - let witness = TestPlugin{}; - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&vec, - *&vec, - b"ipfs://js_entry_uri" - ); - } -} - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::register(sender); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::DAOPluginMarketplace; - use creator::TestPlugin; - - fun main(sender: signer) { - DAOPluginMarketplace::star_plugin( - &sender, - ); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::DAOPluginMarketplace; - use creator::TestPlugin; - - fun main(sender: signer) { - DAOPluginMarketplace::star_plugin( - &sender, - ); - } -} -// check: MoveAbort - -//# run --signers alice -script { - use StarcoinFramework::DAOPluginMarketplace; - use creator::TestPlugin; - - fun main(sender: signer) { - DAOPluginMarketplace::star_plugin( - &sender, - ); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin::TestPlugin> - - -//# run --signers alice -script { - use StarcoinFramework::DAOPluginMarketplace; - use creator::TestPlugin; - - fun main(sender: signer) { - DAOPluginMarketplace::unstar_plugin( - &sender, - ); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin::TestPlugin> - -//# run --signers alice -script { - use StarcoinFramework::DAOPluginMarketplace; - use creator::TestPlugin; - - fun main(sender: signer) { - DAOPluginMarketplace::unstar_plugin( - &sender, - ); - } -} -// check: MoveAbort diff --git a/integration-tests/daospace/dao_plugin_marketplace_update_plugin.exp b/integration-tests/daospace/dao_plugin_marketplace_update_plugin.exp deleted file mode 100644 index b9847d82..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_update_plugin.exp +++ /dev/null @@ -1,45 +0,0 @@ -processed 10 tasks - -task 6 'run'. lines 46-54: -{ - "gas_used": 235944, - "status": "Executed" -} - -task 7 'view'. lines 56-56: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin::TestPlugin> { - id: 12 - name: 54657374506c7567696e - description: 697066733a2f2f6465736372697074696f6e - labels: [ - ] - next_version_number: 1 - versions: [ - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} - -task 8 'run'. lines 58-66: -{ - "gas_used": 139490, - "status": "Executed" -} - -task 9 'view'. lines 68-68: -store key 0x00000000000000000000000000000001::DAOPluginMarketplace::PluginEntry<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::TestPlugin::TestPlugin> { - id: 12 - name: 54657374506c7567696e - description: 697066733a2f2f6465736372697074696f6e32 - labels: [ - 4f533d53746172636f696e, - 53746f72653d49504653, - ] - next_version_number: 1 - versions: [ - ] - star_count: 0 - created_at: 10 - updated_at: 10 -} diff --git a/integration-tests/daospace/dao_plugin_marketplace_update_plugin.move b/integration-tests/daospace/dao_plugin_marketplace_update_plugin.move deleted file mode 100644 index 91e2fb99..00000000 --- a/integration-tests/daospace/dao_plugin_marketplace_update_plugin.move +++ /dev/null @@ -1,70 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr bob --amount 2000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::TestPlugin { - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::DAOPluginMarketplace; - - struct TestPlugin has store, drop {} - - const NAME: vector = b"TestPlugin"; - - public(script) fun register(_sender: signer) { - let witness = TestPlugin{}; - DAOPluginMarketplace::register_plugin( - &witness, - NAME, - b"ipfs://description", - Option::none(), - ); - } - - public(script) fun update_plugin(_sender: signer) { - let labels = Vector::empty>(); - Vector::push_back>(&mut labels, b"OS=Starcoin"); - Vector::push_back>(&mut labels, b"Store=IPFS"); - - let witness = TestPlugin{}; - DAOPluginMarketplace::update_plugin( - &witness, - NAME, - b"ipfs://description2", - Option::some(labels), - ); - } -} - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::register(sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin::TestPlugin> - -//# run --signers bob -script { - use creator::TestPlugin; - - fun main(sender: signer) { - TestPlugin::update_plugin(sender); - } -} -// check: EXECUTED - -//# view --address Genesis --resource 0x1::DAOPluginMarketplace::PluginEntry<{{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::TestPlugin::TestPlugin> - - diff --git a/integration-tests/daospace/dao_proposal.exp b/integration-tests/daospace/dao_proposal.exp deleted file mode 100644 index 6ea78d11..00000000 --- a/integration-tests/daospace/dao_proposal.exp +++ /dev/null @@ -1,126 +0,0 @@ -processed 42 tasks - -task 7 'run'. lines 155-166: -{ - "gas_used": 1675042, - "status": "Executed" -} - -task 8 'run'. lines 168-182: -{ - "gas_used": 109239, - "status": "Executed" -} - -task 9 'run'. lines 184-209: -{ - "gas_used": 306386, - "status": "Executed" -} - -task 11 'run'. lines 214-223: -{ - "gas_used": 362766, - "status": "Executed" -} - -task 12 'run'. lines 225-234: -{ - "gas_used": 362766, - "status": "Executed" -} - -task 16 'run'. lines 242-256: -{ - "gas_used": 104944, - "status": "Executed" -} - -task 19 'run'. lines 263-276: -{ - "gas_used": 532278, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Block" - } - }, - "abort_code": "4609" - } - } -} - -task 22 'run'. lines 283-294: -{ - "gas_used": 577624, - "status": "Executed" -} - -task 23 'run'. lines 297-321: -{ - "gas_used": 510323, - "status": "Executed" -} - -task 25 'run'. lines 325-334: -{ - "gas_used": 11943, - "status": "Executed" -} - -task 26 'call'. lines 336-336: -"0xb5d577dc9ce59725e29886632e69ecdf/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>" - -task 28 'run'. lines 340-359: -{ - "gas_used": 6523189, - "status": "Executed" -} - -task 29 'call'. lines 362-362: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>" - -task 31 'run'. lines 366-379: -{ - "gas_used": 6195892, - "status": "Executed" -} - -task 32 'call'. lines 382-382: -"0x3d4926eeda5b14b0ac979269ee79e40e/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>" - -task 34 'run'. lines 386-399: -{ - "gas_used": 35135, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOSpace" - } - }, - "abort_code": "51201" - } - } -} - -task 36 'run'. lines 404-419: -{ - "gas_used": 106530, - "status": "Executed" -} - -task 39 'run'. lines 427-437: -{ - "gas_used": 115442, - "status": "Executed" -} - -task 41 'run'. lines 442-454: -{ - "gas_used": 487615, - "status": "Executed" -} diff --git a/integration-tests/daospace/dao_proposal.move b/integration-tests/daospace/dao_proposal.move deleted file mode 100644 index 5d50e415..00000000 --- a/integration-tests/daospace/dao_proposal.move +++ /dev/null @@ -1,454 +0,0 @@ -//# init -n dev - -//// creator address is 0x662ba5a1a1da0f1c70a9762c7eeb7aaf -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//// bob address is 0xb5d577dc9ce59725e29886632e69ecdf -//# faucet --addr bob --amount 10000000000 - -//# faucet --addr cindy --amount 10000000000 - -//# publish -module creator::DAOHelper { - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace::{Self, CapType, Proposal}; - use StarcoinFramework::MemberProposalPlugin::{Self, MemberProposalPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::Account; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - - struct X has store, copy, drop{} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,){ - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - // checkpoint store - let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - move_to(&dao_signer, Checkpoint { - proposal_id:0, - }); - - //let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, MemberProposalPlugin::required_caps()); - - DAOSpace::install_plugin(&install_cap, required_caps()); - } - - struct XPlugin has store, drop{} - - struct XAction has store, drop { - total: u128, - receiver: address, - } - - public fun initialize_x_plugin(_sender: &signer) { - let witness = XPlugin{}; - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::XPlugin", - b"The X plugin.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://x-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::withdraw_token_cap_type()); - caps - } - - public fun create_x_proposal(sender: &signer, total: u128, receiver:address, action_delay:u64): u64 acquires Checkpoint { - let witness = XPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = XAction{ - total, - receiver, - }; - let proposal_id = DAOSpace::create_proposal(&cap, sender, action,b"title",b"ipfs://introduction", b"ipfs://extend", action_delay, Option::none()); - checkpoint(proposal_id); - - proposal_id - } - - public fun execute_x_proposal(sender: &signer, proposal_id: u64){ - let witness = XPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let XAction{receiver, total} = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - let withdraw_cap = DAOSpace::acquire_withdraw_token_cap(&witness); - let token = DAOSpace::withdraw_token(&withdraw_cap, total); - Account::deposit(receiver, token); - } - - public fun queue_proposal_action(_sender: &signer, proposal_id: u64){ - DAOSpace::queue_proposal_action(proposal_id); - } - - public fun member_join(sender: &signer, init_sbt: u128){ - let witness = XPlugin{}; - let member_cap = DAOSpace::acquire_member_cap(&witness); - DAOSpace::join_member_with_member_cap(&member_cap, sender, Option::none>(), Option::none>(), init_sbt); - } - - struct Checkpoint has key{ - //last proposal id - proposal_id: u64, - } - - public fun checkpoint(proposal_id: u64) acquires Checkpoint { - let checkpoint = borrow_global_mut>(@creator); - checkpoint.proposal_id = proposal_id; - } - - public fun last_proposal_id(): u64 acquires Checkpoint { - let checkpoint = borrow_global>(@creator); - checkpoint.proposal_id - } - - public fun proposal_state(proposal_id: u64): u8 { - DAOSpace::proposal_state(proposal_id) - } - - public fun proposal(proposal_id: u64): Proposal { - DAOSpace::proposal(proposal_id) - } -} - -//# block --author 0x1 --timestamp 86410000 - -//# run --signers creator -script{ - use creator::DAOHelper; - - fun main(sender: signer){ - DAOHelper::initialize_x_plugin(&sender); - - // time unit is millsecond - DAOHelper::create_dao(sender, 10000, 600000, 2, 10000, 10); - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::Account; - use StarcoinFramework::STC::STC; - - //deposit to dao address - fun main(sender: signer){ - let dao_address = DAORegistry::dao_address(); - let deposit = Account::withdraw(&sender, 500000); - Account::deposit(dao_address, deposit); - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::Token; - use StarcoinFramework::Debug; - use StarcoinFramework::BCS; - - fun token_code(_sender: signer){ - // let struct_tag = b""; - let token_code = Token::token_code(); - let bcs_token_code = BCS::to_bytes(&token_code); - - let offset = 0; - let (address, offset) = BCS::deserialize_address(&bcs_token_code, offset); - let (module_name, offset) = BCS::deserialize_bytes(&bcs_token_code, offset); - let (name, _offset) = BCS::deserialize_bytes(&bcs_token_code, offset); - Debug::print(&address); - Debug::print(&module_name); - Debug::print(&name); - Debug::print(&110220); - Debug::print(&token_code); - Debug::print(&b"DAOHelper"); - Debug::print(&b"X"); - } -} -// check: EXECUTED - - -//# block --author=0x2 --timestamp 86415000 - -//# run --signers alice -script{ - use creator::DAOHelper::{Self, X}; - - //alice join dao - fun member_join(sender: signer){ - DAOHelper::member_join(&sender, 10000u128); - } -} -// check: EXECUTED - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X}; - - //bob join dao - fun member_join(sender: signer){ - DAOHelper::member_join(&sender, 30000u128); - } -} -// check: EXECUTED - -//# block --author=0x2 --timestamp 86418000 - -//# block --author=0x2 --timestamp 86420000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - Debug::print(&expect_parent_hash); - Debug::print(&parent_hash); - assert!(expect_parent_hash == parent_hash, 1001); - - Block::checkpoint(); - } -} -// check: EXECUTED - - -//# block --author=0x2 --timestamp 86430000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.block_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun update(_account: signer, raw_header: vector) { - let current_block_number = Block::get_current_block_number(); - Debug::print(¤t_block_number); - Debug::print(&raw_header); - Block::update_state_root(raw_header); - } -} -// check: ABORT. reason: Block from call-api[0] is not in checkpoint, its parent is in. - - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[2].raw.header}} - -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun update(_account: signer, raw_header: vector) { - Debug::print(&raw_header); - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - - -//# run --signers alice -script{ - use StarcoinFramework::STC::STC; - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Debug; - - //alice create proposal - fun create_proposal(sender: signer){ - let proposal_id = DAOHelper::create_x_proposal(&sender, 100u128, @alice, 10000); - let proposal = DAOSpace::proposal(proposal_id); - - let proposer = DAOSpace::proposal_proposer(&proposal); - let (start_time,end_time) = DAOSpace::proposal_time(&proposal); - let block_number = DAOSpace::proposal_block_number(&proposal); - let state_root = DAOSpace::proposal_state_root(&proposal); - - Debug::print(&proposer); - Debug::print(&start_time); - Debug::print(&end_time); - Debug::print(&block_number); - Debug::print(&state_root); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86461000 - -//# run --signers bob --args {{$.faucet[0].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} --args {{$.faucet[2].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} -script{ - use StarcoinFramework::Debug; - - /// faucet address generated from a hash of the faucet name - fun print_faucet(_sender: signer, address1: address, address2: address){ - Debug::print(&address1); - Debug::print(&address2); - } -} - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X --args {{$.faucet[2].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[2].header.state_root}}"] - -//# run --signers bob --args {{$.call-api[3]}} -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Debug; - - // bob vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = DAOHelper::last_proposal_id(); - let choice = DAOSpace::choice_yes(); - Debug::print(&snpashot_raw_proofs); - - //deserize sbt - // decode sbt value from snapshot state -// let vote_weight = SBTVoteStrategy::get_voting_power(&snapshot_proof.state); - - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - } -} -// check: EXECUTED - - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X --args {{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[1]}}","{{$.call-api[2].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[4]}} -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - // use StarcoinFramework::Debug; - - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = DAOHelper::last_proposal_id(); - let choice = DAOSpace::choice_abstain(); - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - } -} -// check: EXECUTED - - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X --args {{$.faucet[3].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[2]}}","{{$.call-api[2].header.state_root}}"] - -//# run --signers cindy --args {{$.call-api[5]}} -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - // use StarcoinFramework::Debug; - - // cindy vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = DAOHelper::last_proposal_id(); - let choice = DAOSpace::choice_yes(); - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - } -} -// check: ABORT - - -//# block --author 0x4 --timestamp 90060000 - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::Debug; - - fun get_proposal_info(_sender: signer){ - let proposal_id = DAOHelper::last_proposal_id(); - let proposal_state = DAOHelper::proposal_state(proposal_id); - Debug::print(&120100); - Debug::print(&proposal_state); - - let proposal = DAOHelper::proposal(proposal_id); - Debug::print(&proposal); - } -} -// check: EXECUTED - - -//# call-api state.list_resource ["0xb5d577dc9ce59725e29886632e69ecdf",{"decode":true}] - -//# call-api state.get_resource ["0xb5d577dc9ce59725e29886632e69ecdf","0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>",{"decode":true}] - - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X}; - - // execute action - fun queue_proposal_action(sender: signer){ - let proposal_id = DAOHelper::last_proposal_id(); - DAOHelper::queue_proposal_action(&sender, proposal_id); - } -} -// check: EXECUTED - - -//# block --author 0x4 --timestamp 90100000 - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::STC::STC; - // use StarcoinFramework::Debug; - - // execute action - fun execute_action(sender: signer){ - let proposal_id = DAOHelper::last_proposal_id(); - DAOHelper::execute_x_proposal(&sender, proposal_id); - } -} -// check: EXECUTED \ No newline at end of file diff --git a/integration-tests/daospace/dao_proposal_rejected.exp b/integration-tests/daospace/dao_proposal_rejected.exp deleted file mode 100644 index e802b180..00000000 --- a/integration-tests/daospace/dao_proposal_rejected.exp +++ /dev/null @@ -1,219 +0,0 @@ -processed 40 tasks - -task 7 'run'. lines 123-132: -{ - "gas_used": 1274227, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOSpace" - } - }, - "abort_code": "179201" - } - } -} - -task 8 'run'. lines 136-150: -{ - "gas_used": 5286, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAORegistry" - } - }, - "function": 0, - "code_offset": 1 - } - } -} - -task 9 'run'. lines 152-177: -{ - "gas_used": 306386, - "status": "Executed" -} - -task 11 'run'. lines 182-191: -{ - "gas_used": 17084, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAORegistry" - } - }, - "function": 0, - "code_offset": 1 - } - } -} - -task 12 'run'. lines 193-203: -{ - "gas_used": 17084, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAORegistry" - } - }, - "function": 0, - "code_offset": 1 - } - } -} - -task 16 'run'. lines 211-225: -{ - "gas_used": 104944, - "status": "Executed" -} - -task 19 'run'. lines 232-245: -{ - "gas_used": 532278, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Block" - } - }, - "abort_code": "4609" - } - } -} - -task 22 'run'. lines 252-263: -{ - "gas_used": 577624, - "status": "Executed" -} - -task 23 'run'. lines 266-290: -{ - "gas_used": 18867, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAORegistry" - } - }, - "function": 0, - "code_offset": 1 - } - } -} - -task 25 'run'. lines 294-303: -{ - "gas_used": 11943, - "status": "Executed" -} - -task 26 'call'. lines 305-305: -"0xb5d577dc9ce59725e29886632e69ecdf/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>" - -task 28 'run'. lines 309-328: -{ - "gas_used": 3733, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x662ba5a1a1da0f1c70a9762c7eeb7aaf", - "name": "DAOHelper" - } - }, - "function": 3, - "code_offset": 1 - } - } -} - -task 29 'call'. lines 331-331: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>" - -task 31 'run'. lines 335-348: -{ - "gas_used": 3205, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x662ba5a1a1da0f1c70a9762c7eeb7aaf", - "name": "DAOHelper" - } - }, - "function": 3, - "code_offset": 1 - } - } -} - -task 32 'call'. lines 351-351: -"0x3d4926eeda5b14b0ac979269ee79e40e/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>" - -task 34 'run'. lines 355-368: -{ - "gas_used": 3469, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x662ba5a1a1da0f1c70a9762c7eeb7aaf", - "name": "DAOHelper" - } - }, - "function": 3, - "code_offset": 1 - } - } -} - -task 36 'run'. lines 373-388: -{ - "gas_used": 2381, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x662ba5a1a1da0f1c70a9762c7eeb7aaf", - "name": "DAOHelper" - } - }, - "function": 3, - "code_offset": 1 - } - } -} - -task 39 'run'. lines 396-412: -{ - "gas_used": 17640, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAORegistry" - } - }, - "function": 0, - "code_offset": 1 - } - } -} diff --git a/integration-tests/daospace/dao_proposal_rejected.move b/integration-tests/daospace/dao_proposal_rejected.move deleted file mode 100644 index 620cc674..00000000 --- a/integration-tests/daospace/dao_proposal_rejected.move +++ /dev/null @@ -1,412 +0,0 @@ -//# init -n dev - -//// creator address is 0x662ba5a1a1da0f1c70a9762c7eeb7aaf -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//// bob address is 0xb5d577dc9ce59725e29886632e69ecdf -//# faucet --addr bob --amount 10000000000 - -//# faucet --addr cindy --amount 10000000000 - - -//# publish -module creator::DAOHelper { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace::{Self, CapType, Proposal}; - use StarcoinFramework::MemberProposalPlugin::{Self, MemberProposalPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - - struct X has store, copy, drop{} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,){ - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - // checkpoint store - let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - move_to(&dao_signer, Checkpoint { - proposal_id:0, - }); - - //let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, MemberProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, required_caps()); - } - - struct XPlugin has store, drop{} - - struct XAction has store, drop { - total: u128, - receiver: address, - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::withdraw_token_cap_type()); - caps - } - - public fun create_x_proposal(sender: &signer, total: u128, receiver:address, action_delay:u64): u64 acquires Checkpoint { - let witness = XPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = XAction{ - total, - receiver, - }; - let proposal_id = DAOSpace::create_proposal(&cap, sender, action,b"title",b"ipfs://introduction", b"ipfs://extend", action_delay, Option::none()); - checkpoint(proposal_id); - - proposal_id - } - - public fun reject_proposal(sender: &signer, proposal_id: u64){ - DAOSpace::reject_proposal>(sender, proposal_id); - } - - public fun member_join(sender: &signer, init_sbt: u128){ - let witness = XPlugin{}; - let member_cap = DAOSpace::acquire_member_cap(&witness); - DAOSpace::join_member_with_member_cap(&member_cap, sender, Option::none>(), Option::none>(), init_sbt); - } - - struct Checkpoint has key{ - //last proposal id - proposal_id: u64, - } - - public fun checkpoint(proposal_id: u64) acquires Checkpoint { - let checkpoint = borrow_global_mut>(@creator); - checkpoint.proposal_id = proposal_id; - } - - public fun last_proposal_id(): u64 acquires Checkpoint { - let checkpoint = borrow_global>(@creator); - checkpoint.proposal_id - } - - public fun proposal_state(proposal_id: u64): u8 { - DAOSpace::proposal_state(proposal_id) - } - - public fun proposal(proposal_id: u64): Proposal { - DAOSpace::proposal(proposal_id) - } -} - -//# block --author 0x1 --timestamp 86410000 - -//# run --signers creator -script{ - use creator::DAOHelper; - - fun main(sender: signer){ - // time unit is millsecond - DAOHelper::create_dao(sender, 10000, 600000, 2, 10000, 1000); - } -} -// check: EXECUTED - - - -//# run --signers alice -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::Account; - use StarcoinFramework::STC::STC; - - //deposit to dao address - fun main(sender: signer){ - let dao_address = DAORegistry::dao_address(); - let deposit = Account::withdraw(&sender, 500000); - Account::deposit(dao_address, deposit); - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use creator::DAOHelper::{X}; - use StarcoinFramework::Token; - use StarcoinFramework::Debug; - use StarcoinFramework::BCS; - - fun token_code(_sender: signer){ - // let struct_tag = b""; - let token_code = Token::token_code(); - let bcs_token_code = BCS::to_bytes(&token_code); - - let offset = 0; - let (address, offset) = BCS::deserialize_address(&bcs_token_code, offset); - let (module_name, offset) = BCS::deserialize_bytes(&bcs_token_code, offset); - let (name, _offset) = BCS::deserialize_bytes(&bcs_token_code, offset); - Debug::print(&address); - Debug::print(&module_name); - Debug::print(&name); - Debug::print(&110220); - Debug::print(&token_code); - Debug::print(&b"DAOHelper"); - Debug::print(&b"X"); - } -} -// check: EXECUTED - - -//# block --author=0x2 --timestamp 86415000 - -//# run --signers alice -script{ - use creator::DAOHelper::{Self, X}; - - //alice join dao - fun member_join(sender: signer){ - DAOHelper::member_join(&sender, 10000u128); - } -} -// check: EXECUTED - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X}; - - //bob join dao - fun member_join(sender: signer){ - //nft must be accept before grant - DAOHelper::member_join(&sender, 30000u128); - } -} -// check: EXECUTED - -//# block --author=0x2 --timestamp 86418000 - -//# block --author=0x2 --timestamp 86420000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - Debug::print(&expect_parent_hash); - Debug::print(&parent_hash); - assert!(expect_parent_hash == parent_hash, 1001); - - Block::checkpoint(); - } -} -// check: EXECUTED - - -//# block --author=0x2 --timestamp 86430000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.block_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun update(_account: signer, raw_header: vector) { - let current_block_number = Block::get_current_block_number(); - Debug::print(¤t_block_number); - Debug::print(&raw_header); - Block::update_state_root(raw_header); - } -} -// check: ABORT. reason: Block from call-api[0] is not in checkpoint, its parent is in. - - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[2].raw.header}} - -script { - use StarcoinFramework::Block; - use StarcoinFramework::Debug; - - fun update(_account: signer, raw_header: vector) { - Debug::print(&raw_header); - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - - -//# run --signers alice -script{ - use StarcoinFramework::STC::STC; - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Debug; - - //alice create proposal - fun create_proposal(sender: signer){ - let proposal_id = DAOHelper::create_x_proposal(&sender, 100u128, @alice, 10000); - let proposal = DAOSpace::proposal(proposal_id); - - let proposer = DAOSpace::proposal_proposer(&proposal); - let (start_time,end_time) = DAOSpace::proposal_time(&proposal); - let block_number = DAOSpace::proposal_block_number(&proposal); - let state_root = DAOSpace::proposal_state_root(&proposal); - - Debug::print(&proposer); - Debug::print(&start_time); - Debug::print(&end_time); - Debug::print(&block_number); - Debug::print(&state_root); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86461000 - -//# run --signers bob --args {{$.faucet[0].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} --args {{$.faucet[2].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} -script{ - use StarcoinFramework::Debug; - - /// faucet address generated from a hash of the faucet name - fun print_faucet(_sender: signer, address1: address, address2: address){ - Debug::print(&address1); - Debug::print(&address2); - } -} - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X --args {{$.faucet[2].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[2].header.state_root}}"] - -//# run --signers bob --args {{$.call-api[3]}} -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Debug; - - // bob vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = DAOHelper::last_proposal_id(); - let choice = DAOSpace::choice_no_with_veto(); - Debug::print(&snpashot_raw_proofs); - - //deserize sbt - // decode sbt value from snapshot state -// let vote_weight = SBTVoteStrategy::get_voting_power(&snapshot_proof.state); - - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - } -} -// check: EXECUTED - - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X --args {{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[1]}}","{{$.call-api[2].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[4]}} -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - // use StarcoinFramework::Debug; - - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = DAOHelper::last_proposal_id(); - let choice = DAOSpace::choice_no_with_veto(); - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - } -} -// check: EXECUTED - - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X --args {{$.faucet[3].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[2]}}","{{$.call-api[2].header.state_root}}"] - -//# run --signers cindy --args {{$.call-api[5]}} -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::DAOSpace; - // use StarcoinFramework::Debug; - - // cindy vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = DAOHelper::last_proposal_id(); - let choice = DAOSpace::choice_no_with_veto(); - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - } -} -// check: ABORT - - -//# block --author 0x4 --timestamp 90060000 - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::Debug; - - fun get_proposal_info(_sender: signer){ - let proposal_id = DAOHelper::last_proposal_id(); - let proposal_state = DAOHelper::proposal_state(proposal_id); - Debug::print(&120100); - Debug::print(&proposal_state); - - let proposal = DAOHelper::proposal(proposal_id); - Debug::print(&proposal); - } -} -// check: EXECUTED - - -//# call-api state.list_resource ["0xb5d577dc9ce59725e29886632e69ecdf",{"decode":true}] - -//# call-api state.get_resource ["0xb5d577dc9ce59725e29886632e69ecdf","0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::DAOHelper::X>>",{"decode":true}] - - -//# run --signers bob -script{ - use creator::DAOHelper::{Self, X}; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Token; - use StarcoinFramework::DAOSpace; - - // execute action - fun queue_proposal_action(sender: signer){ - let total = Token::market_cap(); - StarcoinFramework::Debug::print(&DAOSpace::proposal_state(1)); - let proposal_id = DAOHelper::last_proposal_id(); - DAOHelper::reject_proposal(&sender, proposal_id); - assert!(total - (1000 - 1000 / 10) == Token::market_cap(), 1001); - } -} -// check: EXECUTED \ No newline at end of file diff --git a/integration-tests/daospace/dao_upgrade.exp b/integration-tests/daospace/dao_upgrade.exp deleted file mode 100644 index 620d0969..00000000 --- a/integration-tests/daospace/dao_upgrade.exp +++ /dev/null @@ -1,40 +0,0 @@ -processed 17 tasks - -task 4 'run'. lines 96-104: -{ - "gas_used": 333211, - "status": "Executed" -} - -task 8 'run'. lines 120-127: -{ - "gas_used": 600, - "status": "MiscellaneousError" -} - -task 9 'run'. lines 129-143: -{ - "gas_used": 200239, - "status": "Executed" -} - -task 10 'run'. lines 144-153: -{ - "gas_used": 1154087, - "status": "Executed" -} - -task 11 'deploy'. lines 155-155: -Publish failure: Discard { status_code: StrView(2015), status_code_name: "UNEXPECTED_ERROR_FROM_KNOWN_MOVE_FUNCTION" } - -task 13 'run'. lines 159-166: -{ - "gas_used": 140814, - "status": "Executed" -} - -task 16 'run'. lines 172-179: -{ - "gas_used": 11344, - "status": "Executed" -} diff --git a/integration-tests/daospace/dao_upgrade.move b/integration-tests/daospace/dao_upgrade.move deleted file mode 100644 index d63f387b..00000000 --- a/integration-tests/daospace/dao_upgrade.move +++ /dev/null @@ -1,179 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -// //# run --signers creator -// script { -// use StarcoinFramework::StdlibUpgradeScripts; - -// fun upgrade_from_v11_to_v12() { -// StdlibUpgradeScripts::upgrade_from_v12_to_v12_1(); -// } -// } -// // check: EXECUTED - -//# publish -module creator::DAOHelper { - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::AnyMemberPlugin::{Self, AnyMemberPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - - struct X has store, copy, drop {} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128, ) { - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - - DAOSpace::install_plugin(&install_cap, required_caps()); - } - - struct XPlugin has store, drop {} - - public fun initialize_x_plugin(_sender: &signer) { - let witness = XPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::XPlugin", - b"The X plugin.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://x-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::upgrade_module_cap_type()); - caps - } - - public fun submit_upgrade_plan(package_hash: vector, version: u64, enforced: bool) { - let witness = XPlugin {}; - let upgrade_cap = DAOSpace::acquire_upgrade_module_cap(&witness); - DAOSpace::submit_upgrade_plan(&upgrade_cap, package_hash, version, enforced); - } -} - -//# run --signers creator -script { - use creator::DAOHelper; - - fun main(sender: signer) { - DAOHelper::initialize_x_plugin(&sender); - } -} -// check: EXECUTED - -//# package -module creator::test { - public fun hello() {} -} - -//# package -module creator::test { - public fun hello() {} - - public fun world() {} -} - -//# deploy {{$.package[0].file}} - -//# run --signers alice -script { - use creator::test; - - fun main(_sender: signer) { - test::world(); - } -} - -//# run --signers creator -script { - use StarcoinFramework::Config; - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::Version; - use StarcoinFramework::Option; - use StarcoinFramework::Signer; - - fun main(account: signer) { - Config::publish_new_config(&account, Version::new_version(1)); - PackageTxnManager::update_module_upgrade_strategy(&account, PackageTxnManager::get_strategy_two_phase(), Option::some(1)); - let strategy = PackageTxnManager::get_module_upgrade_strategy(Signer::address_of(&account)); - assert!(strategy == PackageTxnManager::get_strategy_two_phase(), 1001); - } -} -//# run --signers creator -script { - use creator::DAOHelper; - - fun main(sender: signer) { - // time unit is millsecond - DAOHelper::create_dao(sender, 10000, 3600000, 2, 10000, 10); - } -} -// check: EXECUTED - -//# deploy {{$.package[1].file}} --signers alice - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers alice --args {{$.package[1].package_hash}} -script { - use creator::DAOHelper; - - fun main(_sender: signer, package_hash: vector) { - DAOHelper::submit_upgrade_plan(package_hash, 2, false); - } -} - -//# block --author 0x1 --timestamp 86500000 - -//# deploy {{$.package[1].file}} --signers alice - -//# run --signers alice -script { - use creator::test; - - fun main(_sender: signer) { - test::world(); - } -} diff --git a/integration-tests/daospace/dao_upgrade_incompatible.exp b/integration-tests/daospace/dao_upgrade_incompatible.exp deleted file mode 100644 index f311f070..00000000 --- a/integration-tests/daospace/dao_upgrade_incompatible.exp +++ /dev/null @@ -1,46 +0,0 @@ -processed 20 tasks - -task 4 'run'. lines 86-94: -{ - "gas_used": 333211, - "status": "Executed" -} - -task 9 'run'. lines 116-131: -{ - "gas_used": 200239, - "status": "Executed" -} - -task 10 'run'. lines 133-142: -{ - "gas_used": 1154087, - "status": "Executed" -} - -task 12 'run'. lines 146-154: -{ - "gas_used": 140814, - "status": "Executed" -} - -task 15 'run'. lines 160-168: -{ - "gas_used": 11346, - "status": "Executed" -} - -task 16 'run'. lines 170-178: -{ - "gas_used": 140814, - "status": "Executed" -} - -task 18 'deploy'. lines 182-183: -Publish failure: MiscellaneousError - -task 19 'run'. lines 185-193: -{ - "gas_used": 600, - "status": "MiscellaneousError" -} diff --git a/integration-tests/daospace/dao_upgrade_incompatible.move b/integration-tests/daospace/dao_upgrade_incompatible.move deleted file mode 100644 index 7d593fb5..00000000 --- a/integration-tests/daospace/dao_upgrade_incompatible.move +++ /dev/null @@ -1,193 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::DAOHelper { - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::AnyMemberPlugin::{Self, AnyMemberPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - - struct X has store, copy, drop {} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128, ) { - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - - DAOSpace::install_plugin(&install_cap, required_caps()); - } - - struct XPlugin has store, drop {} - - public fun initialize_x_plugin(_sender: &signer) { - let witness = XPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::XPlugin", - b"The X plugin.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://x-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::upgrade_module_cap_type()); - caps - } - - public fun submit_upgrade_plan(package_hash: vector, version: u64, enforced: bool) { - let witness = XPlugin {}; - let upgrade_cap = DAOSpace::acquire_upgrade_module_cap(&witness); - DAOSpace::submit_upgrade_plan(&upgrade_cap, package_hash, version, enforced); - } -} - -//# run --signers creator -script { - use creator::DAOHelper; - - fun main(sender: signer) { - DAOHelper::initialize_x_plugin(&sender); - } -} -// check: EXECUTED - -//# package -module creator::test { - public fun hello() {} -} - -//# package -module creator::test { - public fun hello() {} - public fun world(_i: u8) {} -} - -//# package -module creator::test { - public fun hello(_i: u8) {} - - public fun world(_i: u8) {} -} - -//# deploy {{$.package[0].file}} - -//# run --signers creator -script { - use StarcoinFramework::Config; - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::Version; - use StarcoinFramework::Option; - use StarcoinFramework::Signer; - - fun main(account: signer) { - Config::publish_new_config(&account, Version::new_version(1)); - PackageTxnManager::update_module_upgrade_strategy(&account, PackageTxnManager::get_strategy_two_phase(), Option::some(1)); - let strategy = PackageTxnManager::get_module_upgrade_strategy(Signer::address_of(&account)); - assert!(strategy == PackageTxnManager::get_strategy_two_phase(), 1001); - } -} -//check: EXECUTED - -//# run --signers creator -script { - use creator::DAOHelper; - - fun main(sender: signer) { - // time unit is millsecond - DAOHelper::create_dao(sender, 10000, 3600000, 2, 10000, 10); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers alice --args {{$.package[1].package_hash}} -script { - use creator::DAOHelper; - - fun main(_sender: signer, package_hash: vector) { - DAOHelper::submit_upgrade_plan(package_hash, 2, true); - } -} -//check: EXECUTED - -//# block --author 0x1 --timestamp 86600000 - -//# deploy {{$.package[1].file}} --signers alice - -//# run --signers alice -script { - use creator::test; - - fun main(_sender: signer) { - test::world(2); - } -} -//check: EXECUTED - -//# run --signers alice --args {{$.package[2].package_hash}} -script { - use creator::DAOHelper; - - fun main(_sender: signer, package_hash: vector) { - DAOHelper::submit_upgrade_plan(package_hash, 2, true); - } -} -//check: EXECUTED - -//# block --author 0x1 --timestamp 86700000 - -//# deploy {{$.package[2].file}} --signers alice -//check: Publish failure: MiscellaneousError - -//# run --signers alice -script { - use creator::test; - - fun main(_sender: signer) { - test::hello(3); - } -} -//check: ABORT. incompatiable upgrade is not allowed. \ No newline at end of file diff --git a/integration-tests/daospace/xdao.exp b/integration-tests/daospace/xdao.exp deleted file mode 100644 index 58f2ac26..00000000 --- a/integration-tests/daospace/xdao.exp +++ /dev/null @@ -1,43 +0,0 @@ -processed 7 tasks - -task 3 'run'. lines 53-60: -{ - "gas_used": 1226477, - "status": "Executed" -} - -task 4 'view'. lines 62-62: -key 0x00000000000000000000000000000001::DAOSpace::DAO { - id: 2 - name: 58 - description: 697066733a2f2f6465736372697074696f6e - dao_address: 662ba5a1a1da0f1c70a9762c7eeb7aaf - next_member_id: 1 - next_proposal_id: 1 -} - -task 5 'view'. lines 64-64: -key 0x00000000000000000000000000000001::DAOSpace::InstalledPluginInfo<0x00000000000000000000000000000001::InstallPluginProposalPlugin::InstallPluginProposalPlugin> { - plugin_id: 4 - granted_caps: [ - copy drop store 0x00000000000000000000000000000001::DAOSpace::CapType { - code: 7u8 - }, - copy drop store 0x00000000000000000000000000000001::DAOSpace::CapType { - code: 0u8 - }, - ] -} - -task 6 'view'. lines 66-66: -key 0x00000000000000000000000000000001::DAOSpace::InstalledPluginInfo<0x00000000000000000000000000000001::MemberProposalPlugin::MemberProposalPlugin> { - plugin_id: 5 - granted_caps: [ - copy drop store 0x00000000000000000000000000000001::DAOSpace::CapType { - code: 6u8 - }, - copy drop store 0x00000000000000000000000000000001::DAOSpace::CapType { - code: 7u8 - }, - ] -} diff --git a/integration-tests/daospace/xdao.move b/integration-tests/daospace/xdao.move deleted file mode 100644 index 3fcc846a..00000000 --- a/integration-tests/daospace/xdao.move +++ /dev/null @@ -1,66 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -// TODO figure out how to call genesis init script in integration tests - -// //# run --signers creator -// script{ -// use StarcoinFramework::StdlibUpgradeScripts; - -// fun main(){ -// StdlibUpgradeScripts::upgrade_from_v12_to_v12_1(); -// } -// } - -//# publish -module creator::XDAO { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Option; - use StarcoinFramework::MemberProposalPlugin::{Self, MemberProposalPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - - struct X has store, drop {} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,){ - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - //let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(),b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, MemberProposalPlugin::required_caps()); - } -} - -//# run --signers creator -script{ - use creator::XDAO; - - fun main(sender: signer){ - XDAO::create_dao(sender, 10, 10, 10, 10, 10); - } -} - -//# view --address creator --resource 0x1::DAOSpace::DAO - -//# view --address creator --resource 0x1::DAOSpace::InstalledPluginInfo<0x1::InstallPluginProposalPlugin::InstallPluginProposalPlugin> - -//# view --address creator --resource 0x1::DAOSpace::InstalledPluginInfo<0x1::MemberProposalPlugin::MemberProposalPlugin> \ No newline at end of file diff --git a/integration-tests/daospaceplugin/gas_oracle_plugin.exp b/integration-tests/daospaceplugin/gas_oracle_plugin.exp deleted file mode 100644 index 8487e1b6..00000000 --- a/integration-tests/daospaceplugin/gas_oracle_plugin.exp +++ /dev/null @@ -1,70 +0,0 @@ -processed 27 tasks - -task 5 'run'. lines 67-75: -{ - "gas_used": 46617, - "status": "Executed" -} - -task 6 'run'. lines 77-85: -{ - "gas_used": 77620, - "status": "Executed" -} - -task 7 'run'. lines 87-96: -{ - "gas_used": 1292050, - "status": "Executed" -} - -task 9 'run'. lines 100-111: -{ - "gas_used": 616761, - "status": "Executed" -} - -task 13 'run'. lines 119-130: -{ - "gas_used": 101440, - "status": "Executed" -} - -task 16 'run'. lines 137-146: -{ - "gas_used": 575872, - "status": "Executed" -} - -task 17 'run'. lines 149-174: -{ - "gas_used": 489162, - "status": "Executed" -} - -task 19 'call'. lines 178-178: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::XDAO::XDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::XDAO::XDAO>>" - -task 21 'run'. lines 182-197: -{ - "gas_used": 7794857, - "status": "Executed" -} - -task 23 'run'. lines 201-214: -{ - "gas_used": 173636, - "status": "Executed" -} - -task 24 'run'. lines 216-224: -{ - "gas_used": 48325, - "status": "Executed" -} - -task 26 'run'. lines 229-246: -{ - "gas_used": 636705, - "status": "Executed" -} diff --git a/integration-tests/daospaceplugin/gas_oracle_plugin.move b/integration-tests/daospaceplugin/gas_oracle_plugin.move deleted file mode 100644 index 92db82e7..00000000 --- a/integration-tests/daospaceplugin/gas_oracle_plugin.move +++ /dev/null @@ -1,246 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::XDAO { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::AnyMemberPlugin::{Self, AnyMemberPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::Option; - use StarcoinFramework::GasOracleProposalPlugin::GasOracleProposalPlugin; - use StarcoinFramework::GasOracleProposalPlugin; - - struct XDAO has store, copy, drop {} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128, ) { - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), - Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&XDAO{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, GasOracleProposalPlugin::required_caps()); - } -} -// check: EXECUTED - - -//# publish -module alice::Token { - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - - struct AliceToken has copy, drop, store {} - - public fun init(account: &signer) { - assert!(Signer::address_of(account) == @alice, 100); - - Token::register_token( - account, - 9, - ); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::GasOracle; - use alice::Token::AliceToken; - fun main(account: signer) { - GasOracle::register_entry(account,9); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::GasOracle; - use alice::Token::AliceToken; - fun main(account: signer) { - GasOracle::init_data_source_entry(account,0); - } -} -// check: EXECUTED - -//# run --signers creator -script { - use creator::XDAO; - - fun main(sender: signer) { - // time unit is millsecond - XDAO::create_dao(sender, 10000, 360000, 1, 10000, 0); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use StarcoinFramework::AnyMemberPlugin; - - fun main(sender: signer) { - let image_data = b"image"; - let image_url = b""; - AnyMemberPlugin::join(&sender, image_data, image_url); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86401000 - -//# block --author 0x1 --timestamp 86402000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - assert!(expect_parent_hash == parent_hash, 1001); - - Block::checkpoint(); - } -} -// check: EXECUTED - - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - - fun update(_account: signer, raw_header: vector) { - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - - -//# run --signers alice -script { - use StarcoinFramework::GasOracleProposalPlugin; - use alice::Token::AliceToken; - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Debug; - - fun main(account: signer) { - let description = b"oracle select proposal"; - let action_delay = 0; - GasOracleProposalPlugin::create_oracle_add_proposal(account, b"oracle select proposal",b"oracle select proposal", description, action_delay, @alice); - let proposal = DAOSpace::proposal(1); - let proposer = DAOSpace::proposal_proposer(&proposal); - let (start_time, end_time) = DAOSpace::proposal_time(&proposal); - let block_number = DAOSpace::proposal_block_number(&proposal); - let state_root = DAOSpace::proposal_state_root(&proposal); - - Debug::print(&proposer); - Debug::print(&start_time); - Debug::print(&end_time); - Debug::print(&block_number); - Debug::print(&state_root); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86460000 - -//# call 0x1::SnapshotUtil::get_access_path --type-args {{$.faucet[0].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::XDAO::XDAO --args {{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[2]}} -script { - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - - fun cast_vote(sender: signer, snpashot_raw_proofs: vector) { - let proposal_id = 1; - let choice = DAOSpace::choice_yes(); - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - - let proposal_state = DAOSpace::proposal_state(1); - assert!(proposal_state == 2, 104); // DAOSpace::ACTIVE - } -} - -// check: EXECUTED - -//# block --author=0x3 --timestamp 86830000 - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - - // execute action - fun queue_proposal_action(_sender: signer) { - let proposal_id = 1; - let proposal_state = DAOSpace::proposal_state(proposal_id); - assert!(proposal_state == 5, 105); // DAOSpace::AGREED - DAOSpace::queue_proposal_action(proposal_id); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use alice::Token::AliceToken; - use StarcoinFramework::GasOracle; - - fun main(account: signer) { - GasOracle::update_entry(account, 100); - } -} - - -//# block --author=0x3 --timestamp 86840000 - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::GasOracleProposalPlugin; - use alice::Token::AliceToken; - - fun main(sender: signer) { - let proposal_id = 1; - let proposal_state = DAOSpace::proposal_state(proposal_id); - assert!(proposal_state == 7, 106); // DAOSpace::EXECUTABLE - GasOracleProposalPlugin::execute_oracle_add_proposal(sender, proposal_id); - - let price = GasOracleProposalPlugin::gas_oracle_read(); - assert!(price == 100, 107); - } -} -// check: EXECUTED diff --git a/integration-tests/daospaceplugin/mint_proposal_plugin.exp b/integration-tests/daospaceplugin/mint_proposal_plugin.exp deleted file mode 100644 index a585ac64..00000000 --- a/integration-tests/daospaceplugin/mint_proposal_plugin.exp +++ /dev/null @@ -1,81 +0,0 @@ -processed 29 tasks - -task 8 'run'. lines 69-83: -{ - "gas_used": 125914, - "status": "Executed" -} - -task 9 'run'. lines 85-94: -{ - "gas_used": 1292050, - "status": "Executed" -} - -task 10 'run'. lines 96-106: -{ - "gas_used": 53739, - "status": "Executed" -} - -task 11 'run'. lines 108-121: -{ - "gas_used": 8525, - "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "function": 16, - "code_offset": 2 - } - } -} - -task 12 'run'. lines 123-134: -{ - "gas_used": 616761, - "status": "Executed" -} - -task 16 'run'. lines 142-153: -{ - "gas_used": 101440, - "status": "Executed" -} - -task 19 'run'. lines 159-168: -{ - "gas_used": 575872, - "status": "Executed" -} - -task 20 'run'. lines 170-201: -{ - "gas_used": 486136, - "status": "Executed" -} - -task 22 'call'. lines 205-205: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::XDAO::XDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::XDAO::XDAO>>" - -task 24 'run'. lines 209-223: -{ - "gas_used": 8799122, - "status": "Executed" -} - -task 26 'run'. lines 227-241: -{ - "gas_used": 173636, - "status": "Executed" -} - -task 28 'run'. lines 245-266: -{ - "gas_used": 550893, - "status": "Executed" -} diff --git a/integration-tests/daospaceplugin/mint_proposal_plugin.move b/integration-tests/daospaceplugin/mint_proposal_plugin.move deleted file mode 100644 index 6cae3741..00000000 --- a/integration-tests/daospaceplugin/mint_proposal_plugin.move +++ /dev/null @@ -1,266 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//# faucet --addr bob --amount 10000000000 - -//# faucet --addr cindy --amount 10000000000 - -//# publish -module creator::XDAO { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::AnyMemberPlugin::{Self, AnyMemberPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::MintProposalPlugin::{Self, MintProposalPlugin}; - use StarcoinFramework::Option; - - struct XDAO has store, copy, drop{} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,){ - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - - //let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), - Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&XDAO{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, MintProposalPlugin::required_caps()); - } -} - -//# publish -module alice::AliceToken { - use StarcoinFramework::Token; - - struct AliceToken has copy, drop, store { } - - public fun init(account: &signer) { - Token::register_token( - account, - 3, - ); - } -} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers alice -script { - use alice::AliceToken::{AliceToken, Self}; - use StarcoinFramework::Account; - use StarcoinFramework::Token; - - fun main(account: signer) { - AliceToken::init(&account); - let market_cap = Token::market_cap(); - assert!(market_cap == 0, 101); - assert!(Token::is_registered_in(@alice), 102); - Account::do_accept_token(&account); - } -} -// check: EXECUTED - -//# run --signers creator -script{ - use creator::XDAO; - - fun main(sender: signer){ - // time unit is millsecond - XDAO::create_dao(sender, 10000, 360000, 1, 10000, 0); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use alice::AliceToken::AliceToken; - use creator::XDAO::XDAO; - use StarcoinFramework::MintProposalPlugin; - - fun main(sender: signer) { - MintProposalPlugin::delegate_token_mint_cap_entry(sender); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use alice::AliceToken::AliceToken; - use StarcoinFramework::Account; - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - - fun main(sender: signer) { - let token = Token::mint(&sender, 100000); - let receiver = Signer::address_of(&sender); - Account::deposit(receiver, token); - } -} -// check: ABORTED, Alice don't have MintCapability - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use StarcoinFramework::AnyMemberPlugin; - - fun main(sender: signer) { - let image_data = b"image"; - let image_url = b""; - AnyMemberPlugin::join(&sender, image_data, image_url); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86410000 - -//# block --author=0x2 --timestamp 86420000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - assert!(expect_parent_hash == parent_hash, 103); - - Block::checkpoint(); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - - fun update(_account: signer, raw_header: vector) { - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use alice::AliceToken::AliceToken; - use creator::XDAO::XDAO; - use StarcoinFramework::MintProposalPlugin; - - use StarcoinFramework::Debug; - use StarcoinFramework::DAOSpace; - - fun main(sender: signer) { - let description = b"mint to bob"; - let amount = 100000; - let action_delay = 0; - MintProposalPlugin::create_mint_proposal( - &sender,b"mint to bob", b"mint to bob", description, @bob, amount, action_delay); - - let proposal = DAOSpace::proposal(1); - - let proposer = DAOSpace::proposal_proposer(&proposal); - let (start_time,end_time) = DAOSpace::proposal_time(&proposal); - let block_number = DAOSpace::proposal_block_number(&proposal); - let state_root = DAOSpace::proposal_state_root(&proposal); - - Debug::print(&proposer); - Debug::print(&start_time); - Debug::print(&end_time); - Debug::print(&block_number); - Debug::print(&state_root); - - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86460000 - -//# call 0x1::SnapshotUtil::get_access_path --type-args {{$.faucet[0].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::XDAO::XDAO --args {{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[2]}} -script{ - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = 1; - let choice = DAOSpace::choice_yes(); - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - - let proposal_state = DAOSpace::proposal_state(1); - assert!(proposal_state == 2, 104); // DAOSpace::ACTIVE - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86830000 - -//# run --signers alice -script{ - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - - // execute action - fun queue_proposal_action(_sender: signer){ - let proposal_id = 1; - let proposal_state = DAOSpace::proposal_state(proposal_id); - assert!(proposal_state == 5, 105); // DAOSpace::AGREED - DAOSpace::queue_proposal_action(proposal_id); - - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86840000 - -//# run --signers bob -script { - use creator::XDAO::XDAO; - use alice::AliceToken::AliceToken; - use StarcoinFramework::MintProposalPlugin; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - use StarcoinFramework::Token; - use StarcoinFramework::DAOSpace; - - fun main(sender: signer) { - let proposal_id = 1; - let proposal_state = DAOSpace::proposal_state(proposal_id); - assert!(proposal_state == 7, 106); // DAOSpace::EXECUTABLE - - let addr = Signer::address_of(&sender); - MintProposalPlugin::execute_mint_proposal(&sender, proposal_id); - let balance = Account::balance(addr); - assert!(balance == 100000, 107); - assert!(Token::market_cap() == balance, 108); - } -} \ No newline at end of file diff --git a/integration-tests/daospaceplugin/salary_gov_plugin.exp b/integration-tests/daospaceplugin/salary_gov_plugin.exp deleted file mode 100644 index 1d975a26..00000000 --- a/integration-tests/daospaceplugin/salary_gov_plugin.exp +++ /dev/null @@ -1,81 +0,0 @@ -processed 21 tasks - -task 7 'run'. lines 256-268: -{ - "gas_used": 1701140, - "status": "Executed" -} - -task 8 'run'. lines 271-279: -{ - "gas_used": 74627, - "status": "Executed" -} - -task 10 'run'. lines 284-296: -{ - "gas_used": 409927, - "status": "Executed" -} - -task 11 'run'. lines 299-310: -{ - "gas_used": 428032, - "status": "Executed" -} - -task 13 'run'. lines 315-331: -{ - "gas_used": 308551, - "status": "Executed" -} - -task 14 'run'. lines 334-344: -{ - "gas_used": 22142, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x662ba5a1a1da0f1c70a9762c7eeb7aaf", - "name": "SalaryGovPlugin" - } - }, - "abort_code": "257025" - } - } -} - -task 16 'run'. lines 348-365: -{ - "gas_used": 489206, - "status": "Executed" -} - -task 18 'run'. lines 369-385: -{ - "gas_used": 308551, - "status": "Executed" -} - -task 19 'run'. lines 387-396: -{ - "gas_used": 25017, - "status": "Executed" -} - -task 20 'run'. lines 398-408: -{ - "gas_used": 22142, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x662ba5a1a1da0f1c70a9762c7eeb7aaf", - "name": "SalaryGovPlugin" - } - }, - "abort_code": "257025" - } - } -} diff --git a/integration-tests/daospaceplugin/salary_gov_plugin.move b/integration-tests/daospaceplugin/salary_gov_plugin.move deleted file mode 100644 index 12a16c01..00000000 --- a/integration-tests/daospaceplugin/salary_gov_plugin.move +++ /dev/null @@ -1,408 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 10000000000000 - -//# faucet --addr acting_boss --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//# publish -module creator::SalaryGovPlugin { - use StarcoinFramework::Signer; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Vector; - use StarcoinFramework::Account; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - - const ERR_PLUGIN_USER_NOT_MEMBER: u64 = 1002; - const ERR_PLUGIN_USER_IS_MEMBER: u64 = 1003; - const ERR_PLUGIN_USER_NOT_PRIVILEGE: u64 = 1004; - const ERR_PLUGIN_PERIOD_NOT_SAME: u64 = 1005; - const ERR_PLUGIN_PERIOD_APPLICATION: u64 = 1006; - - struct SalaryGovPlugin has store, drop {} - - struct PluginBossCap has key, store, drop {} - - struct SalaryReceive has key { - last_receive_time: u64, - } - - struct BossProposalAction has key, store, drop { - boss: address, - } - - public fun initialize(_sender: &signer) { - let witness = SalaryGovPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::SalaryGovPlugin", - b"The salary plugin for DAO", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://salary-gov-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::withdraw_token_cap_type()); - caps - } - - /// acting_boss_claim_cap - public fun acting_boss_claim_cap(sender: signer, _witness: &DAOT) { - move_to>(&sender, PluginBossCap {}); - } - - /// burn boss cap - public(script) fun burn_boss_cap(sender: signer) acquires PluginBossCap { - assert_boss(&sender); - let _ = move_from>(Signer::address_of(&sender)); - } - - public(script) fun join(sender: signer, image_data: vector, image_url: vector) { - let member = Signer::address_of(&sender); - assert!(!DAOSpace::is_member(member), Errors::invalid_state(ERR_PLUGIN_USER_IS_MEMBER)); - - let witness = SalaryGovPlugin {}; - let cap = DAOSpace::acquire_member_cap(&witness); - DAOSpace::join_member_with_member_cap(&cap, &sender, Option::some(image_data), Option::some(image_url), 0); - move_to(&sender, SalaryReceive { - last_receive_time: Timestamp::now_seconds(), - }); - } - - public(script) fun quit(sender: signer) - acquires SalaryReceive { - let member = Signer::address_of(&sender); - assert!(DAOSpace::is_member(member), Errors::invalid_state(ERR_PLUGIN_USER_NOT_MEMBER)); - - let witness = SalaryGovPlugin {}; - let cap = DAOSpace::acquire_member_cap(&witness); - DAOSpace::revoke_member(&cap, member); - - receive_with_amount(member, - compute_salary_amount(member)); - - let SalaryReceive { - last_receive_time: _, - } = move_from>(member); - } - - /// Increase salary per second for member - public(script) fun increase_salary(sender: signer, member: address, amount: u128) - acquires SalaryReceive { - assert_boss(&sender); - assert!(DAOSpace::is_member(member), Errors::invalid_state(ERR_PLUGIN_USER_NOT_MEMBER)); - - receive_with_amount(member, compute_salary_amount(member)); - - let witness = SalaryGovPlugin {}; - let cap = DAOSpace::acquire_member_cap(&witness); - DAOSpace::increase_member_sbt(&cap, member, amount); - } - - /// Decrease salary per second for member - public(script) fun decrease_salary(sender: signer, member: address, amount: u128) - acquires SalaryReceive { - assert_boss(&sender); - assert!(DAOSpace::is_member(member), Errors::invalid_state(ERR_PLUGIN_USER_NOT_MEMBER)); - - receive_with_amount(member, compute_salary_amount(member)); - - let witness = SalaryGovPlugin {}; - let cap = DAOSpace::acquire_member_cap(&witness); - DAOSpace::decrease_member_sbt(&cap, member, amount); - } - - public(script) fun receive(member: address) acquires SalaryReceive { - assert!(DAOSpace::is_member(member), Errors::invalid_state(ERR_PLUGIN_USER_NOT_MEMBER)); - - let amount = compute_salary_amount(member); - //assert!(now_seconds() - receive.last_receive_time > config.period, - // Errors::invalid_state(ERR_PLUGIN_RECEIVE_TIME_NOT_REACHED)) - receive_with_amount(member, amount); - } - - fun compute_salary_amount(member: address): u128 acquires SalaryReceive { - let sbt_amount = DAOSpace::query_sbt(member); - let receive = borrow_global>(member); - - sbt_amount * ((Timestamp::now_seconds() - receive.last_receive_time) as u128) - } - - /// Calling by member that receive salary - fun receive_with_amount(member: address, amount: u128) - acquires SalaryReceive { - let witness = SalaryGovPlugin {}; - - let withdraw_cap = - DAOSpace::acquire_withdraw_token_cap(&witness); - let token = DAOSpace::withdraw_token(&withdraw_cap, amount); - Account::deposit(member, token); - - let receive = borrow_global_mut>(member); - receive.last_receive_time = Timestamp::now_seconds(); - } - - /// Create proposal for specific admin account - public(script) fun create_boss_elect_proposal(sender: signer, title:vector, introduction:vector, description: vector, action_delay: u64) { - let witness = SalaryGovPlugin {}; - - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = BossProposalAction { - boss: Signer::address_of(&sender) - }; - DAOSpace::create_proposal(&cap, &sender, action, title, introduction, description, action_delay, Option::none()); - } - - public(script) fun execute_proposal(sender: signer, proposal_id: u64) { - let witness = SalaryGovPlugin {}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let BossProposalAction { boss } = - DAOSpace::execute_proposal>(&proposal_cap, &sender, proposal_id); - assert!(boss == Signer::address_of(&sender), Errors::invalid_state(ERR_PLUGIN_USER_NOT_PRIVILEGE)); - move_to(&sender, PluginBossCap {}) - } - - fun assert_boss(signer: &signer) { - let user = Signer::address_of(signer); - assert!(exists>(user), Errors::invalid_state(ERR_PLUGIN_USER_NOT_PRIVILEGE)) - } -} - -//# publish -module creator::XDAO { - use creator::SalaryGovPlugin::{Self, SalaryGovPlugin}; - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::AnyMemberPlugin::{Self, AnyMemberPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::Option; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - - const ERR_NOT_ACTING_BOSS: u64 = 1001; - - struct XDAO has store, copy, drop { - } - - struct Storage has store { - acting_boss: address - } - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128, - acting_boss: address) { - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - - //let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), - Option::none>(), b"ipfs://description", config); - - let witness = XDAO {}; - let install_cap = DAOSpace::acquire_install_plugin_cap(&witness); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, SalaryGovPlugin::required_caps()); - - let store_cap = DAOSpace::acquire_storage_cap(&witness); - DAOSpace::save_to_storage(&store_cap, Storage { acting_boss }); - } - - /// acting boss claim boss cap - public(script) fun acting_boss_claim_cap(sender: signer) { - let witness = XDAO {}; - let store_cap = DAOSpace::acquire_storage_cap(&witness); - let Storage { acting_boss } = DAOSpace::take_from_storage(&store_cap); - assert!(acting_boss == Signer::address_of(&sender), Errors::invalid_state(ERR_NOT_ACTING_BOSS)); - SalaryGovPlugin::acting_boss_claim_cap(sender, &witness); - } -} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers creator -script { - use creator::SalaryGovPlugin; - use creator::XDAO; - - fun main(sender: signer) { - SalaryGovPlugin::initialize(&sender); - - // time unit is millsecond - XDAO::create_dao(sender, 10000, 360000, 1, 10000, 0, @acting_boss); - } -} -// check: EXECUTED - - -//# run --signers acting_boss -script { - use creator::XDAO; - - fun main(sender: signer) { - XDAO::acting_boss_claim_cap(sender); - } -} -// check: EXECUTED - - -//# block --timestamp 86500000 - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - use StarcoinFramework::STC::STC; - - fun main(sender: signer) { - let image_data = b"image"; - let image_url = b""; - SalaryGovPlugin::join(sender, image_data, image_url); - } -} -// check: EXECUTED - - -//# run --signers acting_boss -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - use StarcoinFramework::STC::STC; - - fun main(sender: signer) { - let salary = 123332u128; - SalaryGovPlugin::increase_salary(sender, @alice, salary); - } -} -// check: EXECUTED - - -//# block --timestamp 87500000 - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Account; - - fun main(_sender: signer) { - let old_balance = Account::balance(@alice); - SalaryGovPlugin::receive(@alice); - let new_balance = Account::balance(@alice); - - let expect_received = 123332u128 * (87500 - 86500); - assert!(new_balance == old_balance + expect_received, 101); - } -} -// check: EXECUTED - - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - use StarcoinFramework::STC::STC; - - fun main(sender: signer) { - SalaryGovPlugin::increase_salary(sender, @alice, 20000u128); - } -} -// check: ABORTED, only boss can increase_salary - -//# block --timestamp 89500000 - -//# run --signers acting_boss -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Account; - - fun main(sender: signer) { - - let old_balance = Account::balance(@alice); - SalaryGovPlugin::increase_salary(sender, @alice, 20000u128); - let new_balance = Account::balance(@alice); - - let expect_received = 123332u128 * (89500 - 87500); - assert!(new_balance == old_balance + expect_received, 101); - } -} -// check: EXECUTED - -//# block --timestamp 901921000 - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Account; - - fun main(_sender: signer) { - let old_balance = Account::balance(@alice); - SalaryGovPlugin::receive(@alice); - let new_balance = Account::balance(@alice); - - let expect_received = (123332u128 + 20000u128) * (901921 - 89500); - assert!(new_balance == old_balance + expect_received, 101); - } -} -// check: EXECUTED - -//# run --signers acting_boss -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - - fun main(sender: signer) { - SalaryGovPlugin::burn_boss_cap(sender); - } -} -// check: EXECUTED - -//# run --signers acting_boss -script { - use creator::XDAO::XDAO; - use creator::SalaryGovPlugin; - use StarcoinFramework::STC::STC; - - fun main(sender: signer) { - SalaryGovPlugin::increase_salary(sender, @alice, 20000u128); - } -} -// check: ABORT, reason: acting_boss has no boss_cap anymore. \ No newline at end of file diff --git a/integration-tests/daospaceplugin/stake_to_sbt_plugin.exp b/integration-tests/daospaceplugin/stake_to_sbt_plugin.exp deleted file mode 100644 index 8077e933..00000000 --- a/integration-tests/daospaceplugin/stake_to_sbt_plugin.exp +++ /dev/null @@ -1,65 +0,0 @@ -processed 17 tasks - -task 5 'run'. lines 52-60: -{ - "gas_used": 1958252, - "status": "Executed" -} - -task 6 'run'. lines 62-98: -{ - "gas_used": 1159804, - "status": "Executed" -} - -task 7 'run'. lines 100-117: -{ - "gas_used": 62324, - "status": "Executed" -} - -task 9 'run'. lines 121-139: -{ - "gas_used": 313635, - "status": "Executed" -} - -task 10 'run'. lines 141-157: -{ - "gas_used": 475573, - "status": "Executed" -} - -task 12 'run'. lines 161-174: -{ - "gas_used": 554865, - "status": "Executed" -} - -task 13 'run'. lines 176-192: -{ - "gas_used": 609447, - "status": "Executed" -} - -task 15 'run'. lines 196-211: -{ - "gas_used": 278963, - "status": "Executed" -} - -task 16 'run'. lines 213-224: -{ - "gas_used": 656139, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "StakeToSBTPlugin" - } - }, - "abort_code": "257793" - } - } -} diff --git a/integration-tests/daospaceplugin/stake_to_sbt_plugin.move b/integration-tests/daospaceplugin/stake_to_sbt_plugin.move deleted file mode 100644 index 007ee0c1..00000000 --- a/integration-tests/daospaceplugin/stake_to_sbt_plugin.move +++ /dev/null @@ -1,224 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 1000000000000000 - -//# faucet --addr alice --amount 1000000000000000 - -//# block --author 0x1 --timestamp 86400000 - -//# publish -module creator::XDAO { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StakeToSBTPlugin::StakeToSBTPlugin; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Option; - - struct X has store, drop {} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128) { - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - //let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(),b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&X{}); - DAOSpace::install_plugin(&install_cap, StakeToSBTPlugin::required_caps()); - - let witness = X {}; - StakeToSBTPlugin::accept_token_by_dao(&witness); - - StakeToSBTPlugin::set_sbt_weight_by_dao(&witness, 10, 2000); - } -} -// check: EXECUTED - -//# run --signers creator -script { - use creator::XDAO; - - fun create_dao(sender: signer) { - XDAO::create_dao(sender, 10, 10, 10, 10, 10); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - use StarcoinFramework::Debug; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 10); - - let ( - stake_time, - lock_time, - weight, - sbt_amount, - token_amount - ) = StakeToSBTPlugin::query_stake(Signer::address_of(&sender), 1); - - Debug::print(&stake_time); - Debug::print(&lock_time); - Debug::print(&weight); - Debug::print(&sbt_amount); - Debug::print(&token_amount); - - assert!(stake_time == 86400, 1001); - assert!(lock_time == 10, 1002); - assert!(weight == 2000, 1003); - assert!(sbt_amount == 2000, 1004); - assert!(token_amount == 1000000000, 1005); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - - fun unstake_all(sender: signer) { - let sender_addr = Signer::address_of(&sender); - let balance = Account::balance(sender_addr); - StakeToSBTPlugin::unstake_all(&sender); - let new_balance = Account::balance(sender_addr); - assert!(balance == new_balance, 1001); // No item are available to unstake. - assert!(StakeToSBTPlugin::query_stake_count(sender_addr) == 1, 1002); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 87400000 - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Signer; - use StarcoinFramework::Account; - use StarcoinFramework::Token; - - fun unstake_all(sender: signer) { - let sender_addr = Signer::address_of(&sender); - let balance = Account::balance(sender_addr); - StakeToSBTPlugin::unstake_all(&sender); - let new_balance = Account::balance(sender_addr); - assert!(balance + 1 * Token::scaling_factor() == new_balance, 1001); - assert!(StakeToSBTPlugin::query_stake_count(sender_addr) <= 0, 1002); - } -} -// check: CHECKED - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Signer; - use StarcoinFramework::Account; - use StarcoinFramework::Token; - - fun stake_again(sender: signer) { - let user_addr = Signer::address_of(&sender); - let token = Account::withdraw(&sender, 1 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 10); - assert!(StakeToSBTPlugin::query_stake_count(user_addr) > 0, 10002); - } -} -// check: CHECKED - -//# block --author 0x1 --timestamp 89400000 - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Signer; - - fun stake_again(sender: signer) { - let sender_addr = Signer::address_of(&sender); - StakeToSBTPlugin::unstake_by_id(&sender, 2); - assert!(StakeToSBTPlugin::query_stake_count(sender_addr) <= 0, 10003); - } -} -// check: CHECKED - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::DAOSpace; - - fun stake_for_quit(sender: signer) { - let token = Account::withdraw(&sender, 1 * Token::scaling_factor()); - - assert!(StakeToSBTPlugin::stake(&sender, token, 10) == 3, 10004); - DAOSpace::quit_member(&sender); - } -} -// check: CHECKED - -//# block --author 0x1 --timestamp 89500000 - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Signer; - use StarcoinFramework::DAOSpace; - - fun quit_and_unstake(sender: signer) { - let sender_addr = Signer::address_of(&sender); - assert!(!DAOSpace::is_member(sender_addr), 10005); - StakeToSBTPlugin::unstake_by_id(&sender, 3); - assert!(StakeToSBTPlugin::query_stake_count(sender_addr) <= 0, 10006); - } -} -// check: CHECKED - -//# run --signers alice -script { - use creator::XDAO; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Account; - - fun test_block_time_not_exact_match(sender: signer) { - StakeToSBTPlugin::stake(&sender, Account::withdraw(&sender, 100), 50); - } -} -// check: ABORTED, 257793 \ No newline at end of file diff --git a/integration-tests/daospaceplugin/withdraw_plugin.exp b/integration-tests/daospaceplugin/withdraw_plugin.exp deleted file mode 100644 index 105a1869..00000000 --- a/integration-tests/daospaceplugin/withdraw_plugin.exp +++ /dev/null @@ -1,52 +0,0 @@ -processed 24 tasks - -task 6 'run'. lines 53-62: -{ - "gas_used": 1310842, - "status": "Executed" -} - -task 7 'run'. lines 64-75: -{ - "gas_used": 616761, - "status": "Executed" -} - -task 11 'run'. lines 83-94: -{ - "gas_used": 101440, - "status": "Executed" -} - -task 14 'run'. lines 100-109: -{ - "gas_used": 575872, - "status": "Executed" -} - -task 15 'run'. lines 111-142: -{ - "gas_used": 695776, - "status": "Executed" -} - -task 17 'call'. lines 146-146: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::XDAO::XDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x662ba5a1a1da0f1c70a9762c7eeb7aaf::XDAO::XDAO>>" - -task 19 'run'. lines 150-164: -{ - "gas_used": 7272743, - "status": "Executed" -} - -task 21 'run'. lines 168-182: -{ - "gas_used": 173636, - "status": "Executed" -} - -task 23 'run'. lines 186-206: -{ - "gas_used": 549277, - "status": "Executed" -} diff --git a/integration-tests/daospaceplugin/withdraw_plugin.move b/integration-tests/daospaceplugin/withdraw_plugin.move deleted file mode 100644 index 29e43f5d..00000000 --- a/integration-tests/daospaceplugin/withdraw_plugin.move +++ /dev/null @@ -1,206 +0,0 @@ -//# init -n dev - -//# faucet --addr creator --amount 100000000000 - -//# faucet --addr alice --amount 10000000000 - -//# faucet --addr bob --amount 10000000000 - -//# publish -module creator::XDAO { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::AnyMemberPlugin::{Self, AnyMemberPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::WithdrawPlugin::{Self, WithdrawPlugin}; - use StarcoinFramework::Option; - - struct XDAO has store, copy, drop{} - - const NAME: vector = b"X"; - - /// directly upgrade the sender account to DAOAccount and create DAO - public(script) fun create_dao( - sender: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128,){ - let dao_account_cap = DAOAccount::upgrade_to_dao(sender); - - - //let dao_signer = DAOAccount::dao_signer(&dao_account_cap); - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), - Option::none>(), b"ipfs://description", config); - - let install_cap = DAOSpace::acquire_install_plugin_cap(&XDAO{}); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, AnyMemberPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, WithdrawPlugin::required_caps()); - } -} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers creator -script{ - use creator::XDAO; - - fun main(sender: signer){ - // time unit is millsecond - XDAO::create_dao(sender, 10000, 360000, 1, 10000, 0); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use StarcoinFramework::AnyMemberPlugin; - - fun main(sender: signer) { - let image_data = b"image"; - let image_url = b""; - AnyMemberPlugin::join(&sender, image_data, image_url); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86410000 - -//# block --author=0x2 --timestamp 86420000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - assert!(expect_parent_hash == parent_hash, 103); - - Block::checkpoint(); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - - fun update(_account: signer, raw_header: vector) { - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use creator::XDAO::XDAO; - use StarcoinFramework::WithdrawPlugin; - - use StarcoinFramework::Debug; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::STC::STC; - - fun main(sender: signer) { - let description = b"mint to bob"; - let amount = 100000; - let action_delay = 0; - WithdrawPlugin::create_withdraw_proposal( - &sender,b"mint to bob", b"mint to bob", description, @bob, amount, action_delay); - - let proposal = DAOSpace::proposal(1); - - let proposer = DAOSpace::proposal_proposer(&proposal); - let (start_time,end_time) = DAOSpace::proposal_time(&proposal); - let block_number = DAOSpace::proposal_block_number(&proposal); - let state_root = DAOSpace::proposal_state_root(&proposal); - - Debug::print(&proposer); - Debug::print(&start_time); - Debug::print(&end_time); - Debug::print(&block_number); - Debug::print(&state_root); - - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86460000 - -//# call 0x1::SnapshotUtil::get_access_path --type-args {{$.faucet[0].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}}::XDAO::XDAO --args {{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[2]}} -script{ - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - let proposal_id = 1; - let choice = DAOSpace::choice_yes(); - DAOSpace::cast_vote(&sender, proposal_id, snpashot_raw_proofs, choice); - - let proposal_state = DAOSpace::proposal_state(1); - assert!(proposal_state == 2, 104); // DAOSpace::ACTIVE - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86830000 - -//# run --signers alice -script{ - use creator::XDAO::XDAO; - use StarcoinFramework::DAOSpace; - - // execute action - fun queue_proposal_action(_sender: signer){ - let proposal_id = 1; - let proposal_state = DAOSpace::proposal_state(proposal_id); - assert!(proposal_state == 5, 105); // DAOSpace::AGREED - DAOSpace::queue_proposal_action(proposal_id); - - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86840000 - -//# run --signers bob -script { - use creator::XDAO::XDAO; - use StarcoinFramework::WithdrawPlugin; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::STC::STC; - - fun main(sender: signer) { - let proposal_id = 1; - let proposal_state = DAOSpace::proposal_state(proposal_id); - assert!(proposal_state == 7, 106); // DAOSpace::EXECUTABLE - - let addr = Signer::address_of(&sender); - let balance = Account::balance(addr); - WithdrawPlugin::execute_withdraw_proposal(&sender, proposal_id); - let new_balance = Account::balance(addr); - assert!(balance + 100000 == new_balance, 107); - } -} \ No newline at end of file diff --git a/integration-tests/debug/debug.exp b/integration-tests/debug/debug.exp index e7c5034b..930aa8dc 100644 --- a/integration-tests/debug/debug.exp +++ b/integration-tests/debug/debug.exp @@ -3,5 +3,7 @@ processed 4 tasks task 3 'run'. lines 42-51: { "gas_used": 32136, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/dummy.exp b/integration-tests/dummy.exp index 06cb5292..3f3f3f16 100644 --- a/integration-tests/dummy.exp +++ b/integration-tests/dummy.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-10: { "gas_used": 8439, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/epilogue/out_of_gas_in_module.exp b/integration-tests/epilogue/out_of_gas_in_module.exp index e54bd6c2..1901e9ba 100644 --- a/integration-tests/epilogue/out_of_gas_in_module.exp +++ b/integration-tests/epilogue/out_of_gas_in_module.exp @@ -3,5 +3,7 @@ processed 4 tasks task 3 'run'. lines 26-35: { "gas_used": 620000, - "status": "OutOfGas" + "status": { + "Keep": "OutOfGas" + } } diff --git a/integration-tests/epilogue/out_of_gas_in_nested_module.exp b/integration-tests/epilogue/out_of_gas_in_nested_module.exp index 8d2d8ba6..6ba80911 100644 --- a/integration-tests/epilogue/out_of_gas_in_nested_module.exp +++ b/integration-tests/epilogue/out_of_gas_in_nested_module.exp @@ -3,5 +3,7 @@ processed 4 tasks task 3 'run'. lines 29-38: { "gas_used": 621000, - "status": "OutOfGas" + "status": { + "Keep": "OutOfGas" + } } diff --git a/integration-tests/epilogue/out_of_gas_in_script_after_module_call.exp b/integration-tests/epilogue/out_of_gas_in_script_after_module_call.exp index 07c1217b..ea3b9821 100644 --- a/integration-tests/epilogue/out_of_gas_in_script_after_module_call.exp +++ b/integration-tests/epilogue/out_of_gas_in_script_after_module_call.exp @@ -3,5 +3,7 @@ processed 4 tasks task 3 'run'. lines 10-35: { "gas_used": 700, - "status": "OutOfGas" + "status": { + "Keep": "OutOfGas" + } } diff --git a/integration-tests/epilogue/out_of_gas_recursive.exp b/integration-tests/epilogue/out_of_gas_recursive.exp index 4c548f8d..48c06f74 100644 --- a/integration-tests/epilogue/out_of_gas_recursive.exp +++ b/integration-tests/epilogue/out_of_gas_recursive.exp @@ -3,5 +3,7 @@ processed 4 tasks task 3 'run'. lines 11-20: { "gas_used": 600000, - "status": "OutOfGas" + "status": { + "Keep": "OutOfGas" + } } diff --git a/integration-tests/epoch/adjust_epoch_block_time_max.exp b/integration-tests/epoch/adjust_epoch_block_time_max.exp index 7c79b669..44545ae2 100644 --- a/integration-tests/epoch/adjust_epoch_block_time_max.exp +++ b/integration-tests/epoch/adjust_epoch_block_time_max.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-40: { "gas_used": 26828663, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/epoch/adjust_epoch_block_time_min.exp b/integration-tests/epoch/adjust_epoch_block_time_min.exp index 26f1870c..7a71fc4a 100644 --- a/integration-tests/epoch/adjust_epoch_block_time_min.exp +++ b/integration-tests/epoch/adjust_epoch_block_time_min.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 6-37: { "gas_used": 26552925, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/epoch/adjust_epoch_failed.exp b/integration-tests/epoch/adjust_epoch_failed.exp index ef73f557..6c13d735 100644 --- a/integration-tests/epoch/adjust_epoch_failed.exp +++ b/integration-tests/epoch/adjust_epoch_failed.exp @@ -4,14 +4,16 @@ task 3 'run'. lines 7-19: { "gas_used": 25350, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "CoreAddresses" - } - }, - "abort_code": "2818" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "CoreAddresses" + } + }, + 2818 + ] } } } @@ -19,21 +21,25 @@ task 3 'run'. lines 7-19: task 4 'run'. lines 22-34: { "gas_used": 42340, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 37-51: { "gas_used": 41727, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Epoch" - } - }, - "abort_code": "25863" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Epoch" + } + }, + 25863 + ] } } } @@ -42,14 +48,16 @@ task 6 'run'. lines 54-67: { "gas_used": 37998, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Epoch" - } - }, - "abort_code": "19" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Epoch" + } + }, + 19 + ] } } } @@ -58,14 +66,16 @@ task 7 'run'. lines 70-83: { "gas_used": 45142, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Epoch" - } - }, - "abort_code": "25863" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Epoch" + } + }, + 25863 + ] } } } @@ -73,5 +83,7 @@ task 7 'run'. lines 70-83: task 8 'run'. lines 86-99: { "gas_used": 172340, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/epoch/adjust_gas_limit.exp b/integration-tests/epoch/adjust_gas_limit.exp index f0cbd534..30b97e7e 100644 --- a/integration-tests/epoch/adjust_gas_limit.exp +++ b/integration-tests/epoch/adjust_gas_limit.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-45: { "gas_used": 219108, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/epoch/epoch_compute.exp b/integration-tests/epoch/epoch_compute.exp index 0efc9bee..a0c7e860 100644 --- a/integration-tests/epoch/epoch_compute.exp +++ b/integration-tests/epoch/epoch_compute.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-67: { "gas_used": 148138, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/epoch/epoch_data.exp b/integration-tests/epoch/epoch_data.exp index ce6e9d25..cba2b284 100644 --- a/integration-tests/epoch/epoch_data.exp +++ b/integration-tests/epoch/epoch_data.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-38: { "gas_used": 58167, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/error/basic.exp b/integration-tests/error/basic.exp index 1ffda2a1..cd880464 100644 --- a/integration-tests/error/basic.exp +++ b/integration-tests/error/basic.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-20: { "gas_used": 72519, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/fixedpoint32/create_div_zero.exp b/integration-tests/fixedpoint32/create_div_zero.exp index 474022f9..6ae3bcbe 100644 --- a/integration-tests/fixedpoint32/create_div_zero.exp +++ b/integration-tests/fixedpoint32/create_div_zero.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-17: { "gas_used": 11313, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "25863" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 25863 + ] } } } diff --git a/integration-tests/fixedpoint32/create_overflow.exp b/integration-tests/fixedpoint32/create_overflow.exp index df8f76a1..be681cb1 100644 --- a/integration-tests/fixedpoint32/create_overflow.exp +++ b/integration-tests/fixedpoint32/create_overflow.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-18: { "gas_used": 11652, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "26888" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 26888 + ] } } } diff --git a/integration-tests/fixedpoint32/create_underflow.exp b/integration-tests/fixedpoint32/create_underflow.exp index 31037b37..eb4f2c98 100644 --- a/integration-tests/fixedpoint32/create_underflow.exp +++ b/integration-tests/fixedpoint32/create_underflow.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-18: { "gas_used": 11679, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "26887" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 26887 + ] } } } diff --git a/integration-tests/fixedpoint32/create_zero.exp b/integration-tests/fixedpoint32/create_zero.exp index 1138a1e5..66c3adcc 100644 --- a/integration-tests/fixedpoint32/create_zero.exp +++ b/integration-tests/fixedpoint32/create_zero.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-13: { "gas_used": 16324, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/fixedpoint32/divide_by_zero.exp b/integration-tests/fixedpoint32/divide_by_zero.exp index 240d37c9..13754931 100644 --- a/integration-tests/fixedpoint32/divide_by_zero.exp +++ b/integration-tests/fixedpoint32/divide_by_zero.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-18: { "gas_used": 14235, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "26631" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 26631 + ] } } } diff --git a/integration-tests/fixedpoint32/divide_overflow1.exp b/integration-tests/fixedpoint32/divide_overflow1.exp index 3275104f..cd5b1b82 100644 --- a/integration-tests/fixedpoint32/divide_overflow1.exp +++ b/integration-tests/fixedpoint32/divide_overflow1.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-18: { "gas_used": 14481, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "26120" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 26120 + ] } } } diff --git a/integration-tests/fixedpoint32/divide_overflow2.exp b/integration-tests/fixedpoint32/divide_overflow2.exp index 241434a5..18c03da7 100644 --- a/integration-tests/fixedpoint32/divide_overflow2.exp +++ b/integration-tests/fixedpoint32/divide_overflow2.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-18: { "gas_used": 16199, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "26120" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 26120 + ] } } } diff --git a/integration-tests/fixedpoint32/multiply_overflow1.exp b/integration-tests/fixedpoint32/multiply_overflow1.exp index 617157b1..3a57a769 100644 --- a/integration-tests/fixedpoint32/multiply_overflow1.exp +++ b/integration-tests/fixedpoint32/multiply_overflow1.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-18: { "gas_used": 16092, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "26376" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 26376 + ] } } } diff --git a/integration-tests/fixedpoint32/multiply_overflow2.exp b/integration-tests/fixedpoint32/multiply_overflow2.exp index 247f845a..a0e82b6f 100644 --- a/integration-tests/fixedpoint32/multiply_overflow2.exp +++ b/integration-tests/fixedpoint32/multiply_overflow2.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-18: { "gas_used": 14374, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "FixedPoint32" - } - }, - "abort_code": "26376" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "FixedPoint32" + } + }, + 26376 + ] } } } diff --git a/integration-tests/fixedpoint32/test.exp b/integration-tests/fixedpoint32/test.exp index 5a26b5f8..683ecafe 100644 --- a/integration-tests/fixedpoint32/test.exp +++ b/integration-tests/fixedpoint32/test.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-32: { "gas_used": 49832, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/incubator/SortedLinkedList.exp b/integration-tests/incubator/SortedLinkedList.exp index c562a041..4541289f 100644 --- a/integration-tests/incubator/SortedLinkedList.exp +++ b/integration-tests/incubator/SortedLinkedList.exp @@ -3,110 +3,142 @@ processed 33 tasks task 9 'run'. lines 283-291: { "gas_used": 43829, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 293-303: { "gas_used": 8895, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x2747cabbb481a433679f6dc8aae833dd", - "name": "SortedLinkedList" - } - }, - "abort_code": "3" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x7846b2d468dea552692dd6c57e131670", + "name": "SortedLinkedList" + } + }, + 3 + ] } } } task 11 'run'. lines 305-317: { - "gas_used": 295841, - "status": "Executed" + "gas_used": 359425, + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 319-331: { - "gas_used": 399842, - "status": "Executed" + "gas_used": 495218, + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 333-343: { - "gas_used": 468138, - "status": "Executed" + "gas_used": 595306, + "status": { + "Keep": "Executed" + } } task 14 'run'. lines 345-365: { "gas_used": 116679, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 15 'run'. lines 367-377: { "gas_used": 84083, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 16 'run'. lines 379-389: { "gas_used": 74125, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 17 'run'. lines 391-401: { "gas_used": 117689, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 19 'run'. lines 504-512: { "gas_used": 60359, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 20 'run'. lines 514-523: { - "gas_used": 213146, - "status": "Executed" + "gas_used": 221094, + "status": { + "Keep": "Executed" + } } task 21 'run'. lines 525-534: { - "gas_used": 248042, - "status": "Executed" + "gas_used": 259964, + "status": { + "Keep": "Executed" + } } task 22 'run'. lines 536-545: { - "gas_used": 299336, - "status": "Executed" + "gas_used": 315232, + "status": { + "Keep": "Executed" + } } task 23 'run'. lines 547-557: { "gas_used": 31145, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 24 'run'. lines 559-568: { "gas_used": 112570, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 25 'run'. lines 570-580: { "gas_used": 31135, "status": { - "MoveAbort": { - "location": "Script", - "abort_code": "27" + "Keep": { + "MoveAbort": [ + "Script", + 27 + ] } } } @@ -114,5 +146,7 @@ task 25 'run'. lines 570-580: task 32 'run'. lines 595-605: { "gas_used": 138684, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/list/linked_list.exp b/integration-tests/list/linked_list.exp index 15697dd5..9c8a5a7d 100644 --- a/integration-tests/list/linked_list.exp +++ b/integration-tests/list/linked_list.exp @@ -3,39 +3,49 @@ processed 16 tasks task 9 'run'. lines 386-395: { "gas_used": 34392, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 397-410: { - "gas_used": 136100, - "status": "Executed" + "gas_used": 144048, + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 412-420: { "gas_used": 27117, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 422-431: { "gas_used": 40264, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 433-445: { "gas_used": 25964, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0xc65e3b77aaa8ab9d5810bcf0b41d1a31", - "name": "NonFungibleToken" - } - }, - "abort_code": "8004" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x30c836706bd45577b2e75f1876baa249", + "name": "NonFungibleToken" + } + }, + 8004 + ] } } } @@ -43,11 +53,15 @@ task 13 'run'. lines 433-445: task 14 'run'. lines 447-455: { "gas_used": 47150, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 15 'run'. lines 457-469: { "gas_used": 65087, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/math/max.exp b/integration-tests/math/max.exp index cb69b9e8..a9f03e8c 100644 --- a/integration-tests/math/max.exp +++ b/integration-tests/math/max.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-13: { "gas_used": 17865, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/math/mul_div.exp b/integration-tests/math/mul_div.exp index 8b7ffbfb..e5ed24a3 100644 --- a/integration-tests/math/mul_div.exp +++ b/integration-tests/math/mul_div.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-29: { "gas_used": 146381, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/math/pow.exp b/integration-tests/math/pow.exp index f15bc0f2..8303a4bf 100644 --- a/integration-tests/math/pow.exp +++ b/integration-tests/math/pow.exp @@ -3,22 +3,26 @@ processed 4 tasks task 2 'run'. lines 5-16: { "gas_used": 28743, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 18-27: { "gas_used": 4791, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Math" - } - }, - "function": 2, - "code_offset": 26 + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Math" + } + }, + "function": 2, + "code_offset": 26 + } } } } diff --git a/integration-tests/math/sqrt.exp b/integration-tests/math/sqrt.exp index 6dabab3e..377a6c46 100644 --- a/integration-tests/math/sqrt.exp +++ b/integration-tests/math/sqrt.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-22: { "gas_used": 41320, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/math/sum_avg.exp b/integration-tests/math/sum_avg.exp index 5db7428f..026c75c0 100644 --- a/integration-tests/math/sum_avg.exp +++ b/integration-tests/math/sum_avg.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-20: { "gas_used": 1149787, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/module_republish/cyclic_module_dependency.exp b/integration-tests/module_republish/cyclic_module_dependency.exp index 9fed705b..1ae81767 100644 --- a/integration-tests/module_republish/cyclic_module_dependency.exp +++ b/integration-tests/module_republish/cyclic_module_dependency.exp @@ -1,4 +1,4 @@ processed 6 tasks task 5 'publish'. lines 22-30: -Publish failure: MiscellaneousError +Error: Publish failure: Keep(MISCELLANEOUS_ERROR) diff --git a/integration-tests/move/borrow_test.exp b/integration-tests/move/borrow_test.exp index 496404cd..71137b19 100644 --- a/integration-tests/move/borrow_test.exp +++ b/integration-tests/move/borrow_test.exp @@ -3,17 +3,23 @@ processed 7 tasks task 4 'run'. lines 42-52: { "gas_used": 15813, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 54-64: { "gas_used": 17309, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 66-77: { "gas_used": 28475, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/move/option.exp b/integration-tests/move/option.exp index a25718b5..41b0b8bf 100644 --- a/integration-tests/move/option.exp +++ b/integration-tests/move/option.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-43: { "gas_used": 221256, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/natives/bcs.exp b/integration-tests/natives/bcs.exp index 9fc9675e..f2637978 100644 --- a/integration-tests/natives/bcs.exp +++ b/integration-tests/natives/bcs.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 5-13: { "gas_used": 2926, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "BCS" - } - }, - "abort_code": "454" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "BCS" + } + }, + 454 + ] } } } @@ -19,5 +21,7 @@ task 2 'run'. lines 5-13: task 3 'run'. lines 16-53: { "gas_used": 27447, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/natives/hash_test.exp b/integration-tests/natives/hash_test.exp index 416940d1..364fef8d 100644 --- a/integration-tests/natives/hash_test.exp +++ b/integration-tests/natives/hash_test.exp @@ -3,23 +3,31 @@ processed 6 tasks task 2 'run'. lines 5-18: { "gas_used": 10975, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 21-32: { "gas_used": 11104, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 34-45: { "gas_used": 11104, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 47-58: { "gas_used": 11032, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/natives/signature.exp b/integration-tests/natives/signature.exp index 7fb70f88..ce36fa5c 100644 --- a/integration-tests/natives/signature.exp +++ b/integration-tests/natives/signature.exp @@ -1,57 +1,25 @@ -processed 8 tasks +processed 5 tasks task 2 'run'. lines 5-25: { "gas_used": 20425, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 28-50: { "gas_used": 33522, - "status": "Executed" -} - -task 4 'run'. lines 52-87: -{ - "gas_used": 170726, - "status": "Executed" -} - -task 5 'run'. lines 91-104: -{ - "gas_used": 65216, - "status": "Executed" -} - -task 6 'run'. lines 106-119: -{ - "gas_used": 42272, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Option" - } - }, - "abort_code": "263" - } + "Keep": "Executed" } } -task 7 'run'. lines 121-141: +task 4 'run'. lines 52-87: { - "gas_used": 103702, + "gas_used": 170726, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Option" - } - }, - "abort_code": "263" - } + "Keep": "Executed" } } diff --git a/integration-tests/natives/signature.move b/integration-tests/natives/signature.move index 485010ca..702fd6bf 100644 --- a/integration-tests/natives/signature.move +++ b/integration-tests/natives/signature.move @@ -85,57 +85,3 @@ script { assert!(Option::is_none(&receover_address_opt), 1005); } } - - - -//# run --signers creator - -// test secp256k1_verify success case -script { - use StarcoinFramework::Signature; - - fun main() { - //test success - let signature = x"90a938f7457df6e8f741264c32697fc52f9a8f867c52dd70713d9d2d472f2e415d9c94148991bbe1f4a1818d1dff09165782749c877f5cf1eff4ef126e55714d1c"; - let msg_hash = x"b453bd4e271eed985cbab8231da609c4ce0a9cf1f763b6c1594e76315510e0f1"; - let address_bytes = x"29c76e6ad8f28bb1004902578fb108c507be341b"; - assert!(Signature::secp256k1_verify(copy signature, copy address_bytes, copy msg_hash), 1010); - } -} - -//# run --signers creator - -// test secp256k1_verify empty signature and empty msg case -script { - use StarcoinFramework::Signature; - - fun main() { - //test empty data failed - let empty_signature = x""; - let empty_msg_hash = x""; - let address_bytes = x"29c76e6ad8f28bb1004902578fb108c507be341b"; - assert!(!Signature::secp256k1_verify(empty_signature, copy address_bytes, empty_msg_hash), 1020); - } -} - -//# run --signers creator - -// test secp256k1_verify invalid hash or invalid signature case -script { - use StarcoinFramework::Signature; - - fun main() { - //test success - let signature = x"90a938f7457df6e8f741264c32697fc52f9a8f867c52dd70713d9d2d472f2e415d9c94148991bbe1f4a1818d1dff09165782749c877f5cf1eff4ef126e55714d1c"; - let msg_hash = x"b453bd4e271eed985cbab8231da609c4ce0a9cf1f763b6c1594e76315510e0f1"; - let address_bytes = x"29c76e6ad8f28bb1004902578fb108c507be341b"; - - //test invalid hash, change the last char from 1 to 0 - let invalid_msg_hash = x"b453bd4e271eed985cbab8231da609c4ce0a9cf1f763b6c1594e76315510e0f0"; - assert!(!Signature::secp256k1_verify(signature, copy address_bytes, invalid_msg_hash), 1030); - - // //test invalid signature, change the last char from 1 to 0 - let invalid_signature = x"90a938f7457df6e8f741264c32697fc52f9a8f867c52dd70713d9d2d472f2e415d9c94148991bbe1f4a1818d1dff09165782749c877f5cf1eff4ef126e55714d10"; - assert!(!Signature::secp256k1_verify(invalid_signature, address_bytes, msg_hash), 1031); - } -} \ No newline at end of file diff --git a/integration-tests/nft/identifier_nft.exp b/integration-tests/nft/identifier_nft.exp index 8e124aab..6f24ce09 100644 --- a/integration-tests/nft/identifier_nft.exp +++ b/integration-tests/nft/identifier_nft.exp @@ -3,29 +3,39 @@ processed 11 tasks task 5 'run'. lines 127-135: { "gas_used": 151177, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 137-145: { "gas_used": 176281, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 147-155: { "gas_used": 136416, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 158-166: { "gas_used": 96545, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 171-179: { "gas_used": 193000, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/nft/nft_boxminer.exp b/integration-tests/nft/nft_boxminer.exp index 3e3e9605..78c96f1e 100644 --- a/integration-tests/nft/nft_boxminer.exp +++ b/integration-tests/nft/nft_boxminer.exp @@ -3,11 +3,15 @@ processed 6 tasks task 4 'run'. lines 59-67: { "gas_used": 144164, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 69-79: { - "gas_used": 256837, - "status": "Executed" + "gas_used": 256523, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/nft/nft_card.exp b/integration-tests/nft/nft_card.exp index 0d6d20bb..88aa4867 100644 --- a/integration-tests/nft/nft_card.exp +++ b/integration-tests/nft/nft_card.exp @@ -3,29 +3,39 @@ processed 9 tasks task 4 'run'. lines 84-92: { "gas_used": 253696, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 94-104: { - "gas_used": 169452, - "status": "Executed" + "gas_used": 169138, + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 106-119: { - "gas_used": 123734, - "status": "Executed" + "gas_used": 120099, + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 122-134: { - "gas_used": 443435, - "status": "Executed" + "gas_used": 423019, + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 136-148: { - "gas_used": 36393, - "status": "Executed" + "gas_used": 29751, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/nft/nft_metadata.exp b/integration-tests/nft/nft_metadata.exp index 4cc2efce..569ac297 100644 --- a/integration-tests/nft/nft_metadata.exp +++ b/integration-tests/nft/nft_metadata.exp @@ -3,28 +3,36 @@ processed 10 tasks task 4 'run'. lines 91-99: { "gas_used": 150856, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 101-113: { - "gas_used": 260942, - "status": "Executed" + "gas_used": 260314, + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 118-130: { - "gas_used": 339370, - "status": "Executed" + "gas_used": 318954, + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 132-152: { - "gas_used": 135702, + "gas_used": 122330, "status": { - "MoveAbort": { - "location": "Script", - "abort_code": "1002" + "Keep": { + "MoveAbort": [ + "Script", + 1002 + ] } } } @@ -32,5 +40,7 @@ task 8 'run'. lines 132-152: task 9 'run'. lines 155-180: { "gas_used": 77133, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/nft/test_gallery.exp b/integration-tests/nft/test_gallery.exp index b2400f27..bffa0b51 100644 --- a/integration-tests/nft/test_gallery.exp +++ b/integration-tests/nft/test_gallery.exp @@ -3,77 +3,103 @@ processed 18 tasks task 5 'run'. lines 71-79: { "gas_used": 210684, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 81-89: { "gas_used": 85929, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 92-106: { - "gas_used": 63415, - "status": "Executed" + "gas_used": 56773, + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 108-116: { - "gas_used": 108904, - "status": "Executed" + "gas_used": 108590, + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 118-134: { - "gas_used": 119305, - "status": "Executed" + "gas_used": 112663, + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 136-144: { - "gas_used": 18703203, - "status": "Executed" + "gas_used": 18640403, + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 148-161: { - "gas_used": 3117308, - "status": "Executed" + "gas_used": 3113987, + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 164-185: { - "gas_used": 28391178, - "status": "Executed" + "gas_used": 28324758, + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 187-206: { - "gas_used": 2325375, - "status": "Executed" + "gas_used": 2262261, + "status": { + "Keep": "Executed" + } } task 14 'run'. lines 208-220: { - "gas_used": 22544, - "status": "Executed" + "gas_used": 19223, + "status": { + "Keep": "Executed" + } } task 15 'run'. lines 224-234: { - "gas_used": 155079, - "status": "Executed" + "gas_used": 145028, + "status": { + "Keep": "Executed" + } } task 16 'run'. lines 237-251: { - "gas_used": 2064296, - "status": "Executed" + "gas_used": 2060975, + "status": { + "Keep": "Executed" + } } task 17 'run'. lines 253-267: { - "gas_used": 338850, - "status": "Executed" + "gas_used": 328171, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/nft/test_genesis_nft.exp b/integration-tests/nft/test_genesis_nft.exp index aee58ca7..cd9be24b 100644 --- a/integration-tests/nft/test_genesis_nft.exp +++ b/integration-tests/nft/test_genesis_nft.exp @@ -4,14 +4,16 @@ task 2 'run'. lines 6-22: { "gas_used": 87590, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "MerkleNFTDistributor" - } - }, - "abort_code": "256511" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "MerkleNFTDistributor" + } + }, + 256511 + ] } } } diff --git a/integration-tests/nft/test_nft.exp b/integration-tests/nft/test_nft.exp index f96bd7f3..0248f9ee 100644 --- a/integration-tests/nft/test_nft.exp +++ b/integration-tests/nft/test_nft.exp @@ -2,24 +2,32 @@ processed 8 tasks task 4 'run'. lines 41-52: { - "gas_used": 296622, - "status": "Executed" + "gas_used": 296308, + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 54-65: { - "gas_used": 86081, - "status": "Executed" + "gas_used": 83074, + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 67-78: { - "gas_used": 198444, - "status": "Executed" + "gas_used": 190572, + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 80-91: { - "gas_used": 91643, - "status": "Executed" + "gas_used": 88322, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/offer/offer.exp b/integration-tests/offer/offer.exp index fd3b6c56..66b772b5 100644 --- a/integration-tests/offer/offer.exp +++ b/integration-tests/offer/offer.exp @@ -1,85 +1,53 @@ -processed 17 tasks +processed 10 tasks -task 4 'run'. lines 9-31: +task 4 'run'. lines 9-32: { - "gas_used": 140695, - "status": "Executed" -} - -task 5 'run'. lines 35-47: -{ - "gas_used": 80018, + "gas_used": 87526, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Offer" - } - }, - "abort_code": "26117" - } + "Keep": "Executed" } } -task 7 'run'. lines 51-63: +task 5 'run'. lines 36-49: { - "gas_used": 38916, + "gas_used": 25951, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Offer" - } - }, - "abort_code": "25863" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Offer" + } + }, + 26117 + ] } } } -task 9 'run'. lines 67-79: -{ - "gas_used": 146388, - "status": "Executed" -} - -task 10 'run'. lines 82-103: -{ - "gas_used": 258865, - "status": "Executed" -} - -task 11 'run'. lines 105-117: +task 7 'run'. lines 53-65: { - "gas_used": 40121, + "gas_used": 26009, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Offer" - } - }, - "abort_code": "26117" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Offer" + } + }, + 25863 + ] } } } -task 13 'run'. lines 121-145: +task 9 'run'. lines 69-82: { - "gas_used": 155351, - "status": "Executed" -} - -task 14 'run'. lines 147-159: -{ - "gas_used": 106491, - "status": "Executed" -} - -task 16 'run'. lines 163-177: -{ - "gas_used": 187043, - "status": "Executed" + "gas_used": 92321, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/offer/offer.move b/integration-tests/offer/offer.move index d9af5ea2..9134c772 100644 --- a/integration-tests/offer/offer.move +++ b/integration-tests/offer/offer.move @@ -23,6 +23,7 @@ script { assert!(Offer::address_of>(Signer::address_of(&account)) == @bob, 1002); } } + // check: EXECUTED //! block-prologue @@ -44,9 +45,10 @@ script { Account::deposit_to_self(&account, token); } } + // check: "Keep(ABORTED { code: 26117" -//# block --author alice --timestamp 86400000 +//# block --author alice //# run --signers carol script { @@ -62,7 +64,7 @@ script { } // check: "Keep(ABORTED { code: 25863" -//# block --author alice --timestamp 86405000 +//# block --author alice //# run --signers bob script { @@ -76,102 +78,5 @@ script { Account::deposit_to_self(&account, token); } } -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::Account; - use StarcoinFramework::Offer; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Signer; - use StarcoinFramework::Token::Token; - - fun create_offer_v2(account: signer) { - let token = Account::withdraw(&account, 10000); - Offer::create_v2(&account, token, @bob, 5); - let token = Account::withdraw(&account, 10000); - Offer::create_v2(&account, token, @bob, 10); - let token = Account::withdraw(&account, 10000); - Offer::create(&account, token, @bob, 10); - // test Offer::exists_at_v2 - assert!(Offer::exists_at_v2>(Signer::address_of(&account)), 1001); - // test Offer::address_of_v2 - assert!(Offer::address_of_v2>(Signer::address_of(&account), 0) == @bob, 1002); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::Account; - use StarcoinFramework::Offer; - use StarcoinFramework::Token::Token; - use StarcoinFramework::STC::STC; - - fun redeem_offer_v2(account: signer) { - let token = Offer::redeem_v2>(&account, @alice, 0); - Account::deposit_to_self(&account, token); - } -} -// check: "Keep(ABORTED { code: 26117" - -//# block --author alice --timestamp 86410000 - -//# run --signers carol -script { - use StarcoinFramework::Offer; - use StarcoinFramework::Token::Token; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::STC::STC; - - fun redeem_offer_v2(_account: signer) { - let op_offer_infos = Offer::get_offers_infos>(@alice); - assert!(Option::is_some(&op_offer_infos), 101); - let offer_infos = Option::destroy_some(op_offer_infos); - let offers_length = Offer::get_offers_length>(@alice); - assert!(Vector::length(&offer_infos) == 3, 102); - assert!(offers_length == 3,103); - let ( for, time_lock) = Offer::unpack_offer_info(Vector::remove(&mut offer_infos, 0)); - assert!(for == @bob, 104); - assert!(time_lock == 86410, 105); - - let op_idx = Offer::find_offer>(@alice, @bob); - assert!(Option::is_some(&op_idx), 106); - assert!(Option::destroy_some(op_idx) == 0, 107); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::Account; - use StarcoinFramework::Offer; - use StarcoinFramework::Token::Token; - use StarcoinFramework::STC::STC; - - fun redeem_offer_v2(account: signer) { - let token = Offer::redeem_v2>(&account, @alice, 0); - Account::deposit_to_self(&account, token); - } -} -// check: EXECUTED - -//# block --author alice --timestamp 7862415000 - -//# run --signers alice -script { - use StarcoinFramework::Account; - use StarcoinFramework::Offer; - use StarcoinFramework::Token::Token; - use StarcoinFramework::STC::STC; - - fun retake_offer(account: signer) { - let token = Offer::retake>(&account, 1); - Account::deposit_to_self(&account, token); - let token = Offer::retake>(&account, 0); - Account::deposit_to_self(&account, token); - } -} // check: EXECUTED diff --git a/integration-tests/on_chain_config/config.exp b/integration-tests/on_chain_config/config.exp index 6d471df0..2af051ea 100644 --- a/integration-tests/on_chain_config/config.exp +++ b/integration-tests/on_chain_config/config.exp @@ -3,39 +3,49 @@ processed 12 tasks task 4 'run'. lines 67-74: { "gas_used": 67332, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 77-84: { "gas_used": 95430, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 86-96: { "gas_used": 67138, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 99-106: { "gas_used": 38002, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 108-118: { "gas_used": 25867, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Config" - } - }, - "abort_code": "25860" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Config" + } + }, + 25860 + ] } } } @@ -43,17 +53,23 @@ task 8 'run'. lines 108-118: task 9 'run'. lines 120-129: { "gas_used": 45875, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 132-139: { "gas_used": 63276, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 142-152: { "gas_used": 67138, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/on_chain_config/consensus_config.exp b/integration-tests/on_chain_config/consensus_config.exp index b1daa446..903ef428 100644 --- a/integration-tests/on_chain_config/consensus_config.exp +++ b/integration-tests/on_chain_config/consensus_config.exp @@ -3,27 +3,33 @@ processed 11 tasks task 2 'run'. lines 5-41: { "gas_used": 67107, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 43-54: { "gas_used": 30437, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 56-87: { "gas_used": 21324, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ConsensusConfig" - } - }, - "abort_code": "4615" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ConsensusConfig" + } + }, + 4615 + ] } } } @@ -32,14 +38,16 @@ task 5 'run'. lines 89-120: { "gas_used": 21400, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ConsensusConfig" - } - }, - "abort_code": "4615" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ConsensusConfig" + } + }, + 4615 + ] } } } @@ -48,14 +56,16 @@ task 6 'run'. lines 122-153: { "gas_used": 21362, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ConsensusConfig" - } - }, - "abort_code": "4615" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ConsensusConfig" + } + }, + 4615 + ] } } } @@ -64,14 +74,16 @@ task 7 'run'. lines 155-187: { "gas_used": 21438, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ConsensusConfig" - } - }, - "abort_code": "4615" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ConsensusConfig" + } + }, + 4615 + ] } } } @@ -80,14 +92,16 @@ task 8 'run'. lines 189-221: { "gas_used": 21476, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ConsensusConfig" - } - }, - "abort_code": "4615" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ConsensusConfig" + } + }, + 4615 + ] } } } @@ -96,14 +110,16 @@ task 9 'run'. lines 223-255: { "gas_used": 21514, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ConsensusConfig" - } - }, - "abort_code": "4615" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ConsensusConfig" + } + }, + 4615 + ] } } } @@ -112,14 +128,16 @@ task 10 'run'. lines 257-289: { "gas_used": 21582, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "ConsensusConfig" - } - }, - "abort_code": "4615" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "ConsensusConfig" + } + }, + 4615 + ] } } } diff --git a/integration-tests/on_chain_config/consensus_strategy.exp b/integration-tests/on_chain_config/consensus_strategy.exp index d2b67cbb..5b5d3eac 100644 --- a/integration-tests/on_chain_config/consensus_strategy.exp +++ b/integration-tests/on_chain_config/consensus_strategy.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-12: { "gas_used": 17321, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/on_chain_config/is_genesis.exp b/integration-tests/on_chain_config/is_genesis.exp index fd8ebe33..e2d7e305 100644 --- a/integration-tests/on_chain_config/is_genesis.exp +++ b/integration-tests/on_chain_config/is_genesis.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 6-13: { "gas_used": 14623, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/on_chain_config/test_onchain_config_dao.exp b/integration-tests/on_chain_config/test_onchain_config_dao.exp new file mode 100644 index 00000000..3357108f --- /dev/null +++ b/integration-tests/on_chain_config/test_onchain_config_dao.exp @@ -0,0 +1,59 @@ +processed 14 tasks + +task 4 'run'. lines 10-21: +{ + "gas_used": 216046, + "status": { + "Keep": "Executed" + } +} + +task 5 'run'. lines 22-31: +{ + "gas_used": 21947, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "OnChainConfigDao" + } + }, + 102658 + ] + } + } +} + +task 6 'run'. lines 32-42: +{ + "gas_used": 161955, + "status": { + "Keep": "Executed" + } +} + +task 8 'run'. lines 47-60: +{ + "gas_used": 148289, + "status": { + "Keep": "Executed" + } +} + +task 11 'run'. lines 67-87: +{ + "gas_used": 157265, + "status": { + "Keep": "Executed" + } +} + +task 13 'run'. lines 92-106: +{ + "gas_used": 119263, + "status": { + "Keep": "Executed" + } +} diff --git a/deprecated/integration-tests/on_chain_config/test_onchain_config_dao.move b/integration-tests/on_chain_config/test_onchain_config_dao.move similarity index 97% rename from deprecated/integration-tests/on_chain_config/test_onchain_config_dao.move rename to integration-tests/on_chain_config/test_onchain_config_dao.move index 1bf159c2..c8eabbc0 100644 --- a/deprecated/integration-tests/on_chain_config/test_onchain_config_dao.move +++ b/integration-tests/on_chain_config/test_onchain_config_dao.move @@ -103,5 +103,5 @@ script { assert!(TransactionPublishOption::is_script_allowed(@StarcoinFramework), 402); } } -// check: ExecutionFailure, WrappedConfigModifyCapability is migrate to StarcoinDAO +// check: EXECUTED diff --git a/integration-tests/oracle/oracle.exp b/integration-tests/oracle/oracle.exp index 632d7cd8..5b1bc73a 100644 --- a/integration-tests/oracle/oracle.exp +++ b/integration-tests/oracle/oracle.exp @@ -3,67 +3,83 @@ processed 20 tasks task 5 'run'. lines 13-22: { "gas_used": 71562, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 24-33: { "gas_used": 71562, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 36-47: { "gas_used": 28872, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 49-61: { - "gas_used": 38445, - "status": "Executed" + "gas_used": 37189, + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 66-73: { "gas_used": 42267, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 76-84: { - "gas_used": 20505, - "status": "Executed" + "gas_used": 19877, + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 89-103: { - "gas_used": 77661, + "gas_used": 77033, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "PriceOracleAggregator" - } - }, - "abort_code": "25857" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "PriceOracleAggregator" + } + }, + 25857 + ] } } } task 14 'run'. lines 106-120: { - "gas_used": 77661, + "gas_used": 77033, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "PriceOracleAggregator" - } - }, - "abort_code": "25857" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "PriceOracleAggregator" + } + }, + 25857 + ] } } } @@ -71,21 +87,25 @@ task 14 'run'. lines 106-120: task 16 'run'. lines 146-155: { "gas_used": 20157, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 17 'run'. lines 158-167: { "gas_used": 22122, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Oracle" - } - }, - "abort_code": "26116" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Oracle" + } + }, + 26116 + ] } } } @@ -93,11 +113,15 @@ task 17 'run'. lines 158-167: task 18 'run'. lines 169-178: { "gas_used": 42981, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 19 'run'. lines 180-189: { - "gas_used": 14472, - "status": "Executed" + "gas_used": 14158, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/package_txn_manager/cancel_upgrade_plan.exp b/integration-tests/package_txn_manager/cancel_upgrade_plan.exp index e3c6887d..492c428b 100644 --- a/integration-tests/package_txn_manager/cancel_upgrade_plan.exp +++ b/integration-tests/package_txn_manager/cancel_upgrade_plan.exp @@ -3,39 +3,49 @@ processed 8 tasks task 3 'run'. lines 8-19: { "gas_used": 25443, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 21-35: { - "gas_used": 188044, - "status": "Executed" + "gas_used": 161503, + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 36-46: { "gas_used": 30790, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "PackageTxnManager" - } - }, - "abort_code": "26119" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "PackageTxnManager" + } + }, + 26119 + ] } } } task 6 'run'. lines 48-57: { - "gas_used": 65884, - "status": "Executed" + "gas_used": 50189, + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 59-67: { "gas_used": 35104, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/package_txn_manager/only_new_module.exp b/integration-tests/package_txn_manager/only_new_module.exp deleted file mode 100644 index 8a991150..00000000 --- a/integration-tests/package_txn_manager/only_new_module.exp +++ /dev/null @@ -1,16 +0,0 @@ -processed 11 tasks - -task 3 'run'. lines 7-18: -{ - "gas_used": 97932, - "status": "Executed" -} - -task 6 'run'. lines 26-34: -{ - "gas_used": 11344, - "status": "Executed" -} - -task 8 'deploy'. lines 42-42: -Publish failure: Discard { status_code: StrView(21), status_code_name: "INVALID_MODULE_PUBLISHER" } diff --git a/integration-tests/package_txn_manager/only_new_module.move b/integration-tests/package_txn_manager/only_new_module.move deleted file mode 100644 index bbd13e6c..00000000 --- a/integration-tests/package_txn_manager/only_new_module.move +++ /dev/null @@ -1,49 +0,0 @@ -//# init -n dev - -//# faucet --addr alice --amount 100000000000000000 - -//# faucet --addr bob - -//# run --signers alice -script { - use StarcoinFramework::Config; - use StarcoinFramework::Version; - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::Option; - fun main(account: signer) { - Config::publish_new_config(&account, Version::new_version(1)); - PackageTxnManager::update_module_upgrade_strategy(&account, PackageTxnManager::get_strategy_new_module(), Option::some(2)); - } -} -// check: EXECUTED - -//# package -module alice::hello { - public fun hello() {} -} -//# deploy {{$.package[0].file}} --signers alice - -//# run --signers alice -script { - use alice::hello; - - fun main(_account: signer) { - hello::hello(); - } -} -// check: EXECUTED - -//# package -module alice::hello { - public fun hello() {} - public fun hello_bob() {} -} - -//# deploy {{$.package[1].file}} --signers alice - -//# package -module alice::say { - public fun hello() {} -} - -//# deploy {{$.package[2].file}} --signers alice \ No newline at end of file diff --git a/integration-tests/package_txn_manager/override_upgrade_plan.exp b/integration-tests/package_txn_manager/override_upgrade_plan.exp index f9d06325..9631c8e3 100644 --- a/integration-tests/package_txn_manager/override_upgrade_plan.exp +++ b/integration-tests/package_txn_manager/override_upgrade_plan.exp @@ -3,35 +3,47 @@ processed 12 tasks task 3 'run'. lines 7-17: { "gas_used": 25443, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 19-31: { - "gas_used": 188044, - "status": "Executed" + "gas_used": 161503, + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 33-42: { - "gas_used": 65884, - "status": "Executed" + "gas_used": 50189, + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 46-55: { - "gas_used": 65884, - "status": "Executed" + "gas_used": 50189, + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 59-74: { "gas_used": 51694, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 79-89: { "gas_used": 51694, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/package_txn_manager/package_txn_manager.exp b/integration-tests/package_txn_manager/package_txn_manager.exp index 5d591f97..1ccd3b4e 100644 --- a/integration-tests/package_txn_manager/package_txn_manager.exp +++ b/integration-tests/package_txn_manager/package_txn_manager.exp @@ -3,49 +3,59 @@ processed 15 tasks task 3 'run'. lines 8-19: { "gas_used": 25443, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 21-35: { - "gas_used": 188044, - "status": "Executed" + "gas_used": 161503, + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 36-46: { "gas_used": 30790, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "PackageTxnManager" - } - }, - "abort_code": "26119" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "PackageTxnManager" + } + }, + 26119 + ] } } } task 6 'run'. lines 48-59: { - "gas_used": 65884, - "status": "Executed" + "gas_used": 50189, + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 60-70: { "gas_used": 50282, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "PackageTxnManager" - } - }, - "abort_code": "26631" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "PackageTxnManager" + } + }, + 26631 + ] } } } @@ -53,27 +63,33 @@ task 7 'run'. lines 60-70: task 9 'run'. lines 74-86: { "gas_used": 51694, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 87-97: { "gas_used": 35104, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 98-106: { "gas_used": 28816, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "PackageTxnManager" - } - }, - "abort_code": "26113" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "PackageTxnManager" + } + }, + 26113 + ] } } } @@ -82,26 +98,32 @@ task 12 'run'. lines 108-117: { "gas_used": 34693, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "PackageTxnManager" - } - }, - "abort_code": "27143" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "PackageTxnManager" + } + }, + 27143 + ] } } } task 13 'run'. lines 119-128: { - "gas_used": 144392, - "status": "Executed" + "gas_used": 120851, + "status": { + "Keep": "Executed" + } } task 14 'run'. lines 132-140: { "gas_used": 37241, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/resource/resource_example.exp b/integration-tests/resource/resource_example.exp index d32c48c4..ee37e4ec 100644 --- a/integration-tests/resource/resource_example.exp +++ b/integration-tests/resource/resource_example.exp @@ -3,11 +3,15 @@ processed 6 tasks task 4 'run'. lines 33-40: { "gas_used": 14463, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 42-50: { "gas_used": 24987, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/ring/rind_set.exp b/integration-tests/ring/rind_set.exp deleted file mode 100644 index 18900ac0..00000000 --- a/integration-tests/ring/rind_set.exp +++ /dev/null @@ -1,7 +0,0 @@ -processed 3 tasks - -task 2 'run'. lines 5-28: -{ - "gas_used": 504308, - "status": "Executed" -} diff --git a/integration-tests/ring/rind_set.move b/integration-tests/ring/rind_set.move deleted file mode 100644 index b60e12c6..00000000 --- a/integration-tests/ring/rind_set.move +++ /dev/null @@ -1,28 +0,0 @@ -//# init -n test - -//# faucet --addr alice --amount 100000000000000000 - -//# run --signers alice -script { -use StarcoinFramework::Ring; -use StarcoinFramework::Option; - -fun main() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - let i = 0; - while(i < 6){ - Ring::push(&mut ring , i); - i = i + 1; - }; - - assert!(*Option::borrow(Ring::borrow(&ring, 5)) == 5, 1002); - assert!(*Option::borrow(Ring::borrow(&ring, 1)) == 1, 1003); - assert!(*Option::borrow(Ring::borrow(&ring, 2)) == 2, 1004); - assert!(*Option::borrow(Ring::borrow(&ring, 3)) == 3, 1005); - assert!(*Option::borrow(Ring::borrow(&ring, 4)) == 4, 1006); - - _ = Ring::destroy( ring ); -} -} diff --git a/integration-tests/ring/ring_add.exp b/integration-tests/ring/ring_add.exp deleted file mode 100644 index b92e493a..00000000 --- a/integration-tests/ring/ring_add.exp +++ /dev/null @@ -1,7 +0,0 @@ -processed 3 tasks - -task 2 'run'. lines 5-15: -{ - "gas_used": 161829, - "status": "Executed" -} diff --git a/integration-tests/ring/ring_add.move b/integration-tests/ring/ring_add.move deleted file mode 100644 index 2500f352..00000000 --- a/integration-tests/ring/ring_add.move +++ /dev/null @@ -1,15 +0,0 @@ -//# init -n test - -//# faucet --addr alice --amount 100000000000000000 - -//# run --signers alice -script { -use StarcoinFramework::Ring; -fun main() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - - _ = Ring::destroy( ring ); -} -} diff --git a/integration-tests/ring/ring_borrow.exp b/integration-tests/ring/ring_borrow.exp deleted file mode 100644 index 23aa9c8d..00000000 --- a/integration-tests/ring/ring_borrow.exp +++ /dev/null @@ -1,7 +0,0 @@ -processed 3 tasks - -task 2 'run'. lines 5-28: -{ - "gas_used": 463521, - "status": "Executed" -} diff --git a/integration-tests/ring/ring_borrow.move b/integration-tests/ring/ring_borrow.move deleted file mode 100644 index 79f051d7..00000000 --- a/integration-tests/ring/ring_borrow.move +++ /dev/null @@ -1,28 +0,0 @@ -//# init -n test - -//# faucet --addr alice --amount 100000000000000000 - -//# run --signers alice -script { -use StarcoinFramework::Ring; -use StarcoinFramework::Option; - -fun main() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - let i = 0; - while(i < 5){ - Ring::push(&mut ring , i); - i = i + 1; - }; - - assert!(*Option::borrow(Ring::borrow(&ring, 0)) == 0, 1002); - assert!(*Option::borrow(Ring::borrow(&ring, 1)) == 1, 1003); - assert!(*Option::borrow(Ring::borrow(&ring, 2)) == 2, 1004); - assert!(*Option::borrow(Ring::borrow(&ring, 3)) == 3, 1005); - assert!(*Option::borrow(Ring::borrow(&ring, 4)) == 4, 1006); - - _ = Ring::destroy( ring ); -} -} diff --git a/integration-tests/ring/ring_borrow_mut.exp b/integration-tests/ring/ring_borrow_mut.exp deleted file mode 100644 index df6683bb..00000000 --- a/integration-tests/ring/ring_borrow_mut.exp +++ /dev/null @@ -1,7 +0,0 @@ -processed 3 tasks - -task 2 'run'. lines 5-33: -{ - "gas_used": 453800, - "status": "Executed" -} diff --git a/integration-tests/ring/ring_borrow_mut.move b/integration-tests/ring/ring_borrow_mut.move deleted file mode 100644 index 78904b97..00000000 --- a/integration-tests/ring/ring_borrow_mut.move +++ /dev/null @@ -1,33 +0,0 @@ -//# init -n test - -//# faucet --addr alice --amount 100000000000000000 - -//# run --signers alice -script { -use StarcoinFramework::Ring; -use StarcoinFramework::Option; - -fun main() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - let i = 0; - while(i < 5){ - let op_e = Ring::borrow_mut(&mut ring, i) ; - if( Option::is_some(op_e) ){ - Option::swap( op_e , i); - }else{ - Option::fill( op_e , i); - }; - i = i + 1; - }; - - assert!(*Option::borrow(Ring::borrow(&ring, 0)) == 0, 1002); - assert!(*Option::borrow(Ring::borrow(&ring, 1)) == 1, 1003); - assert!(*Option::borrow(Ring::borrow(&ring, 2)) == 2, 1004); - assert!(*Option::borrow(Ring::borrow(&ring, 3)) == 3, 1005); - assert!(*Option::borrow(Ring::borrow(&ring, 4)) == 4, 1006); - - _ = Ring::destroy( ring ); -} -} diff --git a/integration-tests/ring/ring_index_of.exp b/integration-tests/ring/ring_index_of.exp deleted file mode 100644 index dd48cfd9..00000000 --- a/integration-tests/ring/ring_index_of.exp +++ /dev/null @@ -1,45 +0,0 @@ -processed 6 tasks - -task 2 'run'. lines 5-33: -{ - "gas_used": 1051801, - "status": "Executed" -} - -task 3 'run'. lines 35-68: -{ - "gas_used": 1072590, - "status": "Executed" -} - -task 4 'run'. lines 71-93: -{ - "gas_used": 414425, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Ring" - } - }, - "abort_code": "25863" - } - } -} - -task 5 'run'. lines 96-118: -{ - "gas_used": 414507, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Ring" - } - }, - "abort_code": "25863" - } - } -} diff --git a/integration-tests/ring/ring_index_of.move b/integration-tests/ring/ring_index_of.move deleted file mode 100644 index 97d04035..00000000 --- a/integration-tests/ring/ring_index_of.move +++ /dev/null @@ -1,118 +0,0 @@ -//# init -n test - -//# faucet --addr alice --amount 100000000000000000 - -//# run --signers alice -script { -use StarcoinFramework::Ring; -use StarcoinFramework::Option; - -fun main() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - let i = 0; - while(i < 10){ - Ring::push(&mut ring , i + 1); - i = i + 1; - }; - // Ring : [6, 7, 8, 9, 10] - // index: 5, 6, 7, 8, 9 - assert!(Option::is_none( &Ring::index_of(&ring, &20)) , 1002 ); - - assert!(*Option::borrow( &Ring::index_of(&ring, &6)) == 5, 1003 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &7)) == 6, 1004 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &8)) == 7, 1005 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &9)) == 8, 1006 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &10)) == 9, 1007 ); - - _ = Ring::destroy( ring ); - -} -} -//check Executed - -//# run --signers alice -script { -use StarcoinFramework::Ring; -use StarcoinFramework::Option; - -fun find_and_use_index() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - let i = 0; - while(i < 10){ - Ring::push(&mut ring , i + 1); - i = i + 1; - }; - - // Ring : [6, 7, 8, 9, 10] - // index: 5, 6, 7, 8, 9 - assert!(*Option::borrow( &Ring::index_of(&ring, &6)) == 5, 1003 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &7)) == 6, 1004 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &8)) == 7, 1005 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &9)) == 8, 1006 ); - assert!(*Option::borrow( &Ring::index_of(&ring, &10)) == 9, 1007 ); - - assert!(*Option::borrow( Ring::borrow(&ring, 5)) == 6 , 1010); - assert!(*Option::borrow( Ring::borrow(&ring, 6)) == 7 , 1011); - assert!(*Option::borrow( Ring::borrow(&ring, 7)) == 8 , 1012); - assert!(*Option::borrow( Ring::borrow(&ring, 8)) == 9 , 1013); - assert!(*Option::borrow( Ring::borrow(&ring, 9)) == 10 , 1014); - - _ = Ring::destroy( ring ); - -} -} -//check Executed - - -//# run --signers alice -script { -use StarcoinFramework::Ring; -use StarcoinFramework::Option; - -fun exceed_the_lower_limit() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - let i = 0; - while(i < 10){ - Ring::push(&mut ring , i + 1); - i = i + 1; - }; - - // Ring : [6, 7, 8, 9, 10] - // index: 5, 6, 7, 8, 9 - *Option::borrow( Ring::borrow(&ring, 4)); - _ = Ring::destroy( ring ); - -} -} -//check MoveAbort 25863 - - -//# run --signers alice -script { -use StarcoinFramework::Ring; -use StarcoinFramework::Option; - -fun exceed_the_upper_limit() { - let ring = Ring::create_with_capacity(5); - - assert!(Ring::capacity(&ring) == 5, 1001); - let i = 0; - while(i < 10){ - Ring::push(&mut ring , i + 1); - i = i + 1; - }; - - // Ring : [6, 7, 8, 9, 10] - // index: 5, 6, 7, 8, 9 - *Option::borrow( Ring::borrow(&ring, 10)); - _ = Ring::destroy( ring ); - -} -} -//check MoveAbort 25863 \ No newline at end of file diff --git a/integration-tests/shared_ed25519_public_key/shared_key.exp b/integration-tests/shared_ed25519_public_key/shared_key.exp index 56ba53c7..7781050a 100644 --- a/integration-tests/shared_ed25519_public_key/shared_key.exp +++ b/integration-tests/shared_ed25519_public_key/shared_key.exp @@ -3,17 +3,16 @@ processed 7 tasks task 2 'run'. lines 6-38: { "gas_used": 132522, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 40-52: { "gas_used": 0, "status": { - "Discard": { - "status_code": "2", - "status_code_name": "INVALID_AUTH_KEY" - } + "Discard": 2 } } @@ -21,10 +20,7 @@ task 4 'run'. lines 54-69: { "gas_used": 0, "status": { - "Discard": { - "status_code": "2", - "status_code_name": "INVALID_AUTH_KEY" - } + "Discard": 2 } } @@ -32,10 +28,7 @@ task 5 'run'. lines 70-87: { "gas_used": 0, "status": { - "Discard": { - "status_code": "2", - "status_code_name": "INVALID_AUTH_KEY" - } + "Discard": 2 } } @@ -43,9 +36,6 @@ task 6 'run'. lines 88-102: { "gas_used": 0, "status": { - "Discard": { - "status_code": "2", - "status_code_name": "INVALID_AUTH_KEY" - } + "Discard": 2 } } diff --git a/integration-tests/signed_integer/add.exp b/integration-tests/signed_integer/add.exp index f6b3dc0b..923fbc75 100644 --- a/integration-tests/signed_integer/add.exp +++ b/integration-tests/signed_integer/add.exp @@ -1,7 +1,9 @@ processed 3 tasks -task 2 'run'. lines 5-41: +task 2 'run'. lines 5-26: { - "gas_used": 100723, - "status": "Executed" + "gas_used": 54451, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/signed_integer/add.move b/integration-tests/signed_integer/add.move index 12d9505f..efa879cd 100644 --- a/integration-tests/signed_integer/add.move +++ b/integration-tests/signed_integer/add.move @@ -22,20 +22,5 @@ fun main() { let i2 = SignedInteger64::create_from_raw_value(0, false); let z2 = SignedInteger64::add_u64(100, copy i2); assert!(SignedInteger64::get_value(z2) == 100, 6); - - let i3 = SignedInteger64::create_from_raw_value(1, true); - let z3 = SignedInteger64::add_u64(1, i3); - assert!(SignedInteger64::get_value(copy z3) == 0, 7); - assert!(SignedInteger64::is_negative(z3) == false, 8); - - let i4 = SignedInteger64::create_from_raw_value(0, true); - let z4 = SignedInteger64::add_u64(0, i4); - assert!(SignedInteger64::get_value(copy z4) == 0, 9); - assert!(SignedInteger64::is_negative(z4) == false, 10); - - let i5 = SignedInteger64::create_from_raw_value(0, false); - let z5 = SignedInteger64::add_u64(0, i5); - assert!(SignedInteger64::get_value(copy z5) == 0, 11); - assert!(SignedInteger64::is_negative(z5) == false, 12); } } \ No newline at end of file diff --git a/integration-tests/signed_integer/add_overflow.exp b/integration-tests/signed_integer/add_overflow.exp index c0510b88..130a228e 100644 --- a/integration-tests/signed_integer/add_overflow.exp +++ b/integration-tests/signed_integer/add_overflow.exp @@ -4,15 +4,17 @@ task 2 'run'. lines 5-16: { "gas_used": 8455, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "SignedInteger64" - } - }, - "function": 0, - "code_offset": 40 + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "SignedInteger64" + } + }, + "function": 0, + "code_offset": 42 + } } } } diff --git a/integration-tests/signed_integer/create.exp b/integration-tests/signed_integer/create.exp index 723a811f..29386535 100644 --- a/integration-tests/signed_integer/create.exp +++ b/integration-tests/signed_integer/create.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-16: { "gas_used": 18997, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/signed_integer/divide.exp b/integration-tests/signed_integer/divide.exp index 663ea9ce..8b4ee1cf 100644 --- a/integration-tests/signed_integer/divide.exp +++ b/integration-tests/signed_integer/divide.exp @@ -2,6 +2,8 @@ processed 3 tasks task 2 'run'. lines 5-26: { - "gas_used": 53253, - "status": "Executed" + "gas_used": 53261, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/signed_integer/divide_overflow.exp b/integration-tests/signed_integer/divide_overflow.exp index f87a6ae3..03b03c97 100644 --- a/integration-tests/signed_integer/divide_overflow.exp +++ b/integration-tests/signed_integer/divide_overflow.exp @@ -4,15 +4,17 @@ task 2 'run'. lines 5-16: { "gas_used": 8417, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "SignedInteger64" - } - }, - "function": 2, - "code_offset": 4 + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "SignedInteger64" + } + }, + "function": 2, + "code_offset": 4 + } } } } diff --git a/integration-tests/signed_integer/multiply.exp b/integration-tests/signed_integer/multiply.exp index 4f28423f..6e5e9157 100644 --- a/integration-tests/signed_integer/multiply.exp +++ b/integration-tests/signed_integer/multiply.exp @@ -2,6 +2,8 @@ processed 3 tasks task 2 'run'. lines 5-23: { - "gas_used": 45720, - "status": "Executed" + "gas_used": 45726, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/signed_integer/multiply_overflow.exp b/integration-tests/signed_integer/multiply_overflow.exp index 21bbf612..e869e515 100644 --- a/integration-tests/signed_integer/multiply_overflow.exp +++ b/integration-tests/signed_integer/multiply_overflow.exp @@ -4,15 +4,17 @@ task 2 'run'. lines 5-16: { "gas_used": 8415, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "SignedInteger64" - } - }, - "function": 5, - "code_offset": 4 + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "SignedInteger64" + } + }, + "function": 5, + "code_offset": 4 + } } } } diff --git a/integration-tests/signed_integer/sub.exp b/integration-tests/signed_integer/sub.exp index 927616f9..923fbc75 100644 --- a/integration-tests/signed_integer/sub.exp +++ b/integration-tests/signed_integer/sub.exp @@ -1,7 +1,9 @@ processed 3 tasks -task 2 'run'. lines 5-36: +task 2 'run'. lines 5-26: { - "gas_used": 84861, - "status": "Executed" + "gas_used": 54451, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/signed_integer/sub.move b/integration-tests/signed_integer/sub.move index c32676cd..1cc37569 100644 --- a/integration-tests/signed_integer/sub.move +++ b/integration-tests/signed_integer/sub.move @@ -22,15 +22,5 @@ fun main() { let i2 = SignedInteger64::create_from_raw_value(100, true); let z2 = SignedInteger64::sub_u64(100, copy i2); assert!(SignedInteger64::get_value(z2) == 200, 6); - - let i3 = SignedInteger64::create_from_raw_value(0, true); - let z3 = SignedInteger64::sub_u64(0, i3); - assert!(SignedInteger64::get_value(copy z3) == 0, 1); - assert!(SignedInteger64::is_negative(z3) == false, 2); - - let i4 = SignedInteger64::create_from_raw_value(0, false); - let z4 = SignedInteger64::sub_u64(0, i4); - assert!(SignedInteger64::get_value(copy z4) == 0, 1); - assert!(SignedInteger64::is_negative(z4) == false, 2); } } \ No newline at end of file diff --git a/integration-tests/signed_integer/sub_overflow.exp b/integration-tests/signed_integer/sub_overflow.exp index cfb9b576..172ce098 100644 --- a/integration-tests/signed_integer/sub_overflow.exp +++ b/integration-tests/signed_integer/sub_overflow.exp @@ -4,15 +4,17 @@ task 2 'run'. lines 5-16: { "gas_used": 8453, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "SignedInteger64" - } - }, - "function": 6, - "code_offset": 9 + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "SignedInteger64" + } + }, + "function": 6, + "code_offset": 9 + } } } } diff --git a/integration-tests/signer_capability/create_signer.exp b/integration-tests/signer_capability/create_signer.exp index 845fcdfe..b39e906a 100644 --- a/integration-tests/signer_capability/create_signer.exp +++ b/integration-tests/signer_capability/create_signer.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-16: { "gas_used": 88765, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/signer_capability/destroy_signer.exp b/integration-tests/signer_capability/destroy_signer.exp index 1a318c09..8fda5759 100644 --- a/integration-tests/signer_capability/destroy_signer.exp +++ b/integration-tests/signer_capability/destroy_signer.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-22: { "gas_used": 83335, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/starcoin_dao/starcoin_onchain_config.exp b/integration-tests/starcoin_dao/starcoin_onchain_config.exp deleted file mode 100644 index eb180b72..00000000 --- a/integration-tests/starcoin_dao/starcoin_onchain_config.exp +++ /dev/null @@ -1,113 +0,0 @@ -processed 42 tasks - -task 11 'run'. lines 23-37: -{ - "gas_used": 1096577, - "status": "Executed" -} - -task 12 'run'. lines 39-53: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 13 'run'. lines 55-69: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 14 'run'. lines 71-85: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 18 'run'. lines 93-104: -{ - "gas_used": 101440, - "status": "Executed" -} - -task 21 'run'. lines 111-120: -{ - "gas_used": 575872, - "status": "Executed" -} - -task 22 'run'. lines 123-132: -{ - "gas_used": 485629, - "status": "Executed" -} - -task 24 'call'. lines 136-136: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 26 'run'. lines 140-153: -{ - "gas_used": 6111871, - "status": "Executed" -} - -task 27 'call'. lines 154-156: -"0xb5d577dc9ce59725e29886632e69ecdf/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 29 'run'. lines 159-170: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 30 'call'. lines 171-173: -"0x9255386a0faee0205777b798ba4fc6c4/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 32 'run'. lines 176-188: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 33 'call'. lines 189-191: -"0xb0c32ba18ae392ec1978360105bc3956/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 35 'run'. lines 195-205: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 37 'run'. lines 209-217: -{ - "gas_used": 72156, - "status": "Executed" -} - -task 38 'run'. lines 219-228: -{ - "gas_used": 173612, - "status": "Executed" -} - -task 40 'run'. lines 232-248: -{ - "gas_used": 532724, - "status": "Executed" -} - -task 41 'run'. lines 250-261: -{ - "gas_used": 164212, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOSpace" - } - }, - "abort_code": "103175" - } - } -} diff --git a/integration-tests/starcoin_dao/starcoin_onchain_config.move b/integration-tests/starcoin_dao/starcoin_onchain_config.move deleted file mode 100644 index 444d4b85..00000000 --- a/integration-tests/starcoin_dao/starcoin_onchain_config.move +++ /dev/null @@ -1,261 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis --amount 1000000000000000 - -//# faucet --addr alice --amount 1000000000000000 - -//# faucet --addr bob --amount 1000000000000000 - -//# faucet --addr carol --amount 1000000000000000 - -//# faucet --addr dave --amount 1000000000000000 - -//# var alice={{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var bob={{$.faucet[2].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var carol={{$.faucet[3].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var dave={{$.faucet[4].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers alice -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers carol -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers dave -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86401000 - -//# block --author 0x1 --timestamp 86402000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - assert!(expect_parent_hash == parent_hash, 1001); - - Block::checkpoint(); - } -} -// check: EXECUTED - - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - - fun update(_account: signer, raw_header: vector) { - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - - -//# run --signers alice -script { - use StarcoinFramework::OnChainStarcoinDAOConfig; - use StarcoinFramework::RewardConfig; - - fun propose (sender: signer){ - assert!(RewardConfig::reward_delay() == 1, 101); - OnChainStarcoinDAOConfig::propose_update_reward_config(&sender, b"update",b"update",b"update", 5 , 3600000); - } -} - -//# block --author=0x3 --timestamp 86520000 - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[0].alice}} - -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[2]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - - -// index 1 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[1].bob}} - -// index: 3 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[1]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers bob --args {{$.call-api[3]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // bob vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 2 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[2].carol}} - -// index: 4 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[2]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers carol --args {{$.call-api[4]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 3 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[3].dave}} - -// index: 5 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[3]}}","{{$.call-api[1].header.state_root}}"] - - -//# run --signers dave --args {{$.call-api[5]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 90240000 - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - fun state(_sender: signer){ - assert!(DAOSpace::proposal_state(1) == 5 , 103); - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - fun queue_proposal_action(_sender: signer){ - DAOSpace::queue_proposal_action(1); - assert!(DAOSpace::proposal_state(1) == 6 , 103); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 93860000 - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::ConfigProposalPlugin; - use StarcoinFramework::RewardConfig; - - fun execute_proposal(sender: signer){ - assert!(DAOSpace::proposal_state(1) == 7 , 103); - ConfigProposalPlugin::execute_proposal(&sender, 1); - assert!(DAOSpace::proposal_state(1) == 8 , 104); - - assert!(RewardConfig::reward_delay() == 5, 105); - - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun execute_proposal(sender: signer){ - assert!(DAOSpace::proposal_state(1) == 8 , 104); - DAOSpace::clean_proposal_by_id(&sender, 1); - let _ = DAOSpace::proposal(1); - } -} -// check: ABORT, code 103175, proposal 1 not exist. \ No newline at end of file diff --git a/integration-tests/starcoin_dao/starcoin_treasury_withdraw.exp b/integration-tests/starcoin_dao/starcoin_treasury_withdraw.exp deleted file mode 100644 index a7db4faf..00000000 --- a/integration-tests/starcoin_dao/starcoin_treasury_withdraw.exp +++ /dev/null @@ -1,119 +0,0 @@ -processed 44 tasks - -task 11 'run'. lines 23-37: -{ - "gas_used": 1096577, - "status": "Executed" -} - -task 12 'run'. lines 39-53: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 13 'run'. lines 55-69: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 14 'run'. lines 71-85: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 18 'run'. lines 93-104: -{ - "gas_used": 101440, - "status": "Executed" -} - -task 21 'run'. lines 111-120: -{ - "gas_used": 575872, - "status": "Executed" -} - -task 22 'run'. lines 122-142: -{ - "gas_used": 90735, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "TreasuryPlugin" - } - }, - "abort_code": "26375" - } - } -} - -task 23 'run'. lines 144-155: -{ - "gas_used": 555771, - "status": "Executed" -} - -task 25 'call'. lines 159-161: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 27 'run'. lines 164-176: -{ - "gas_used": 6111871, - "status": "Executed" -} - -task 28 'call'. lines 177-179: -"0xb5d577dc9ce59725e29886632e69ecdf/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 30 'run'. lines 182-194: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 31 'call'. lines 195-197: -"0x9255386a0faee0205777b798ba4fc6c4/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 33 'run'. lines 200-212: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 34 'call'. lines 213-215: -"0xb0c32ba18ae392ec1978360105bc3956/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 36 'run'. lines 219-229: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 38 'run'. lines 233-243: -{ - "gas_used": 72220, - "status": "Executed" -} - -task 39 'run'. lines 245-255: -{ - "gas_used": 173612, - "status": "Executed" -} - -task 41 'run'. lines 259-272: -{ - "gas_used": 473854, - "status": "Executed" -} - -task 43 'run'. lines 276-292: -{ - "gas_used": 124032, - "status": "Executed" -} diff --git a/integration-tests/starcoin_dao/starcoin_treasury_withdraw.move b/integration-tests/starcoin_dao/starcoin_treasury_withdraw.move deleted file mode 100644 index 026794fe..00000000 --- a/integration-tests/starcoin_dao/starcoin_treasury_withdraw.move +++ /dev/null @@ -1,292 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis --amount 1000000000000000 - -//# faucet --addr alice --amount 1000000000000000 - -//# faucet --addr bob --amount 1000000000000000 - -//# faucet --addr carol --amount 1000000000000000 - -//# faucet --addr dave --amount 1000000000000000 - -//# var alice={{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var bob={{$.faucet[2].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var carol={{$.faucet[3].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var dave={{$.faucet[4].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers alice -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers carol -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers dave -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86401000 - -//# block --author 0x1 --timestamp 86402000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - assert!(expect_parent_hash == parent_hash, 1001); - - Block::checkpoint(); - } -} -// check: EXECUTED - - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - - fun update(_account: signer, raw_header: vector) { - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::TreasuryPlugin; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Treasury; - use StarcoinFramework::DAOSpace; - - //alice create proposal - fun create_proposal(sender: signer) { - let market_cap = Token::market_cap(); - let balance_in_treasury = Treasury::balance(); - let supply = market_cap - balance_in_treasury; - let rate = DAOSpace::voting_quorum_rate(); - let rate = (rate as u128); - let amount = supply * rate / 100 + 1; - TreasuryPlugin::create_withdraw_proposal(&sender, b"Withdraw treasury", b"Withdraw treasury", b"Withdraw treasury", @alice, amount, 1000, 3600000); - } -} -// check: ABORT, code: 26375, reason:withdraw amount out of limit. - -//# run --signers alice -script { - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::TreasuryPlugin; - use StarcoinFramework::STC::STC; - - //alice create proposal - fun create_proposal(sender: signer) { - TreasuryPlugin::create_withdraw_proposal(&sender, b"Withdraw treasury", b"Withdraw treasury", b"Withdraw treasury", @alice, 246800, 1000, 3600000); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 86520000 - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[0].alice}} - -// index: 2 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[2]}} -script { - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector) { - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 1 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[1].bob}} - -// index: 3 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[1]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers bob --args {{$.call-api[3]}} -script { - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector) { - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 2 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[2].carol}} - -// index: 4 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[2]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers carol --args {{$.call-api[4]}} -script { - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector) { - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 3 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[3].dave}} - -// index: 5 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[3]}}","{{$.call-api[1].header.state_root}}"] - - -//# run --signers dave --args {{$.call-api[5]}} -script { - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector) { - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 90240000 - -//# run --signers alice -script { - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun state(_sender: signer) { - let state = DAOSpace::proposal_state(1); - assert!(state == 5, 103); - } -} -// check: EXECUTED - -//# run --signers alice -script { - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun queue_proposal_action(_sender: signer) { - DAOSpace::queue_proposal_action(1); - assert!(DAOSpace::proposal_state(1) == 6, 103); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 93860000 - -//# run --signers alice -script { - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::TreasuryPlugin; - use StarcoinFramework::STC::STC; - - fun execute_proposal(sender: signer) { - assert!(DAOSpace::proposal_state(1) == 7, 103); - TreasuryPlugin::execute_withdraw_proposal(&sender, 1); - assert!(DAOSpace::proposal_state(1) == 8, 104); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 94360000 - -//# run --signers alice -script { - use StarcoinFramework::Treasury; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - - fun withdraw_token(sender: signer) { - let token = Treasury::withdraw_by_linear(&sender); - let amount = Token::value(&token); - assert!(amount == 123400, 101); - Account::deposit(Signer::address_of(&sender), token); - } -} - -// check: EXECUTED diff --git a/integration-tests/starcoin_dao/starcoin_upgrade_module.exp b/integration-tests/starcoin_dao/starcoin_upgrade_module.exp deleted file mode 100644 index 322345ca..00000000 --- a/integration-tests/starcoin_dao/starcoin_upgrade_module.exp +++ /dev/null @@ -1,113 +0,0 @@ -processed 45 tasks - -task 11 'run'. lines 23-37: -{ - "gas_used": 1096577, - "status": "Executed" -} - -task 12 'run'. lines 39-53: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 13 'run'. lines 55-69: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 14 'run'. lines 71-85: -{ - "gas_used": 976335, - "status": "Executed" -} - -task 18 'run'. lines 93-104: -{ - "gas_used": 101440, - "status": "Executed" -} - -task 21 'run'. lines 111-120: -{ - "gas_used": 575872, - "status": "Executed" -} - -task 23 'run'. lines 127-137: -{ - "gas_used": 471583, - "status": "Executed" -} - -task 25 'call'. lines 142-144: -"0xa7dcef9aef26202fce82a7c7d6672afb/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 27 'run'. lines 147-159: -{ - "gas_used": 6111871, - "status": "Executed" -} - -task 28 'call'. lines 160-162: -"0xb5d577dc9ce59725e29886632e69ecdf/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 30 'run'. lines 165-177: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 31 'call'. lines 178-180: -"0x9255386a0faee0205777b798ba4fc6c4/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 33 'run'. lines 183-195: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 34 'call'. lines 196-198: -"0xb0c32ba18ae392ec1978360105bc3956/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x00000000000000000000000000000001::DAOSpace::DAOMember<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>,0x00000000000000000000000000000001::DAOSpace::DAOMemberBody<0x00000000000000000000000000000001::StarcoinDAO::StarcoinDAO>>" - -task 36 'run'. lines 202-212: -{ - "gas_used": 5442229, - "status": "Executed" -} - -task 38 'run'. lines 216-225: -{ - "gas_used": 72220, - "status": "Executed" -} - -task 39 'run'. lines 227-236: -{ - "gas_used": 173612, - "status": "Executed" -} - -task 41 'run'. lines 240-252: -{ - "gas_used": 555564, - "status": "Executed" -} - -task 44 'run'. lines 258-269: -{ - "gas_used": 148462, - "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DAOSpace" - } - }, - "abort_code": "103175" - } - } -} diff --git a/integration-tests/starcoin_dao/starcoin_upgrade_module.move b/integration-tests/starcoin_dao/starcoin_upgrade_module.move deleted file mode 100644 index 3a4ef65d..00000000 --- a/integration-tests/starcoin_dao/starcoin_upgrade_module.move +++ /dev/null @@ -1,269 +0,0 @@ -//# init -n dev - -//# faucet --addr Genesis --amount 1000000000000000 - -//# faucet --addr alice --amount 1000000000000000 - -//# faucet --addr bob --amount 1000000000000000 - -//# faucet --addr carol --amount 1000000000000000 - -//# faucet --addr dave --amount 1000000000000000 - -//# var alice={{$.faucet[1].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var bob={{$.faucet[2].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var carol={{$.faucet[3].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# var dave={{$.faucet[4].txn.raw_txn.decoded_payload.ScriptFunction.args[0]}} - -//# block --author 0x1 --timestamp 86400000 - -//# run --signers alice -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers bob -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers carol -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# run --signers dave -script { - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun stake_and_check(sender: signer) { - let token = Account::withdraw( - &sender, 1000 * Token::scaling_factor()); - StakeToSBTPlugin::stake(&sender, token, 60000); - } -} -// check: EXECUTED - -//# block --author 0x1 --timestamp 86401000 - -//# block --author 0x1 --timestamp 86402000 - -//# call-api chain.info - -//# run --signers alice --args {{$.call-api[0].head.parent_hash}} -script { - use StarcoinFramework::Block; - - fun checkpoint(_account: signer, parent_hash: vector) { - let expect_parent_hash = Block::get_parent_hash(); - assert!(expect_parent_hash == parent_hash, 1001); - - Block::checkpoint(); - } -} -// check: EXECUTED - - -//# block --author=0x3 --timestamp 86450000 - -//# call-api chain.get_block_by_hash ["{{$.call-api[0].head.parent_hash}}",{"raw":true}] - -//# run --signers alice --args {{$.call-api[1].raw.header}} - -script { - use StarcoinFramework::Block; - - fun update(_account: signer, raw_header: vector) { - Block::update_state_root(raw_header); - } -} -// check: EXECUTED - -//# package -module Genesis::test { - public fun hello() {} -} - -//# run --signers alice --args {{$.package[0].package_hash}} -script{ - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::UpgradeModulePlugin; - - //alice create proposal - fun create_proposal(sender: signer, package_hash: vector){ - UpgradeModulePlugin::create_proposal(&sender,b"Upgrade module", b"Upgrade module" ,b"Upgrade module", 3600000, package_hash, 1, true); - } -} -// check: EXECUTED - - -//# block --author=0x3 --timestamp 86520000 - -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[0].alice}} - -// index: 2 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[0]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers alice --args {{$.call-api[2]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 1 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[1].bob}} - -// index: 3 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[1]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers bob --args {{$.call-api[3]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 2 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[2].carol}} - -// index: 4 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[2]}}","{{$.call-api[1].header.state_root}}"] - -//# run --signers carol --args {{$.call-api[4]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -// index 3 -//# call 0x1::SnapshotUtil::get_access_path --type-args 0x1::StarcoinDAO::StarcoinDAO --args {{$.var[3].dave}} - -// index: 5 -//# call-api state.get_with_proof_by_root_raw ["{{$.call[3]}}","{{$.call-api[1].header.state_root}}"] - - -//# run --signers dave --args {{$.call-api[5]}} -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - // alice vote - fun cast_vote(sender: signer, snpashot_raw_proofs: vector){ - - DAOSpace::cast_vote_entry(sender, 1, snpashot_raw_proofs, 1); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 90240000 - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - fun state(_sender: signer){ - let state = DAOSpace::proposal_state(1); - assert!(state == 5 , 103); - } -} -// check: EXECUTED - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - fun queue_proposal_action(_sender: signer){ - DAOSpace::queue_proposal_action(1); - assert!(DAOSpace::proposal_state(1) == 6 , 103); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 93860000 - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::UpgradeModulePlugin; - - fun execute_proposal(sender: signer){ - assert!(DAOSpace::proposal_state(1) == 7 , 103); - UpgradeModulePlugin::execute_proposal(&sender, 1); - assert!(DAOSpace::proposal_state(1) == 8 , 104); - } -} -// check: EXECUTED - -//# block --author=0x3 --timestamp 93880000 - -//# deploy {{$.package[0].file}} --signers alice - -//# run --signers alice -script{ - use StarcoinFramework::DAOSpace; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - - fun execute_proposal(sender: signer){ - assert!(DAOSpace::proposal_state(1) == 8 , 104); - DAOSpace::clean_proposals(&sender); - let _ = DAOSpace::proposal(1); - } -} -// check: ABORT, code 103175, proposal 1 not exist. \ No newline at end of file diff --git a/integration-tests/timestamps/timestamps.exp b/integration-tests/timestamps/timestamps.exp index 4f2f58bf..43df4b43 100644 --- a/integration-tests/timestamps/timestamps.exp +++ b/integration-tests/timestamps/timestamps.exp @@ -3,21 +3,25 @@ processed 11 tasks task 3 'run'. lines 7-14: { "gas_used": 14623, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 16-24: { "gas_used": 16116, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Timestamp" - } - }, - "abort_code": "3073" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Timestamp" + } + }, + 3073 + ] } } } @@ -26,14 +30,16 @@ task 5 'run'. lines 26-35: { "gas_used": 21945, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "CoreAddresses" - } - }, - "abort_code": "2818" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "CoreAddresses" + } + }, + 2818 + ] } } } @@ -42,15 +48,17 @@ task 6 'run'. lines 39-48: { "gas_used": 15687, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Timestamp" - } - }, - "function": 1, - "code_offset": 7 + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Timestamp" + } + }, + "function": 1, + "code_offset": 7 + } } } } @@ -59,14 +67,16 @@ task 7 'run'. lines 52-61: { "gas_used": 21945, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "CoreAddresses" - } - }, - "abort_code": "2818" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "CoreAddresses" + } + }, + 2818 + ] } } } @@ -74,21 +84,25 @@ task 7 'run'. lines 52-61: task 8 'run'. lines 64-73: { "gas_used": 27291, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 78-87: { "gas_used": 34856, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Timestamp" - } - }, - "abort_code": "3591" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Timestamp" + } + }, + 3591 + ] } } } @@ -97,14 +111,16 @@ task 10 'run'. lines 90-101: { "gas_used": 34860, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Timestamp" - } - }, - "abort_code": "3591" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Timestamp" + } + }, + 3591 + ] } } } diff --git a/integration-tests/token/burn_and_destroy.exp b/integration-tests/token/burn_and_destroy.exp index 11794adf..20e284b8 100644 --- a/integration-tests/token/burn_and_destroy.exp +++ b/integration-tests/token/burn_and_destroy.exp @@ -3,33 +3,41 @@ processed 11 tasks task 4 'run'. lines 25-40: { "gas_used": 131187, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 42-55: { "gas_used": 116988, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 57-65: { "gas_used": 20271, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 67-82: { "gas_used": 70470, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "abort_code": "26120" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Token" + } + }, + 26120 + ] } } } @@ -37,21 +45,25 @@ task 7 'run'. lines 67-82: task 8 'run'. lines 84-96: { "gas_used": 86577, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 98-109: { "gas_used": 85253, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "abort_code": "4097" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Token" + } + }, + 4097 + ] } } } @@ -59,5 +71,7 @@ task 9 'run'. lines 98-109: task 10 'run'. lines 111-121: { "gas_used": 29999, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/token/create_account_with_token.exp b/integration-tests/token/create_account_with_token.exp index 4d25fa4c..8647f408 100644 --- a/integration-tests/token/create_account_with_token.exp +++ b/integration-tests/token/create_account_with_token.exp @@ -3,11 +3,15 @@ processed 4 tasks task 2 'run'. lines 5-19: { "gas_used": 410589, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 23-37: { "gas_used": 437048, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/token/dummy_token.exp b/integration-tests/token/dummy_token.exp index a20fb419..4721f676 100644 --- a/integration-tests/token/dummy_token.exp +++ b/integration-tests/token/dummy_token.exp @@ -3,27 +3,33 @@ processed 6 tasks task 3 'run'. lines 8-26: { "gas_used": 178842, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 28-46: { "gas_used": 116316, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 48-66: { "gas_used": 25635, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "DummyToken" - } - }, - "abort_code": "25863" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "DummyToken" + } + }, + 25863 + ] } } } diff --git a/integration-tests/token/init_stc.exp b/integration-tests/token/init_stc.exp new file mode 100644 index 00000000..178c5cc0 --- /dev/null +++ b/integration-tests/token/init_stc.exp @@ -0,0 +1,38 @@ +processed 5 tasks + +task 3 'run'. lines 7-16: +{ + "gas_used": 34612, + "status": { + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Token" + } + }, + 25858 + ] + } + } +} + +task 4 'run'. lines 20-30: +{ + "gas_used": 80642, + "status": { + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Token" + } + }, + "function": 21, + "code_offset": 42 + } + } + } +} diff --git a/deprecated/integration-tests/token/init_stc.move b/integration-tests/token/init_stc.move similarity index 100% rename from deprecated/integration-tests/token/init_stc.move rename to integration-tests/token/init_stc.move diff --git a/integration-tests/token/is_same_token.exp b/integration-tests/token/is_same_token.exp index 3ca708d5..b1bac467 100644 --- a/integration-tests/token/is_same_token.exp +++ b/integration-tests/token/is_same_token.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-19: { "gas_used": 81199, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/token/join_and_split.exp b/integration-tests/token/join_and_split.exp index c158fd71..77d30f1e 100644 --- a/integration-tests/token/join_and_split.exp +++ b/integration-tests/token/join_and_split.exp @@ -3,11 +3,15 @@ processed 6 tasks task 4 'run'. lines 28-47: { "gas_used": 131187, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 48-64: { "gas_used": 117102, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/token/mint_stc.exp b/integration-tests/token/mint_stc.exp index 19762952..3b3b5a25 100644 --- a/integration-tests/token/mint_stc.exp +++ b/integration-tests/token/mint_stc.exp @@ -4,15 +4,17 @@ task 3 'run'. lines 7-27: { "gas_used": 17379, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "function": 16, - "code_offset": 2 + "Keep": { + "ExecutionFailure": { + "location": { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Token" + } + }, + "function": 16, + "code_offset": 2 + } } } } @@ -20,5 +22,7 @@ task 3 'run'. lines 7-27: task 4 'run'. lines 31-49: { "gas_used": 114188, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/token/my_token.exp b/integration-tests/token/my_token.exp index cb67c492..5bd04207 100644 --- a/integration-tests/token/my_token.exp +++ b/integration-tests/token/my_token.exp @@ -3,29 +3,39 @@ processed 10 tasks task 5 'run'. lines 41-58: { "gas_used": 131187, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 61-76: { "gas_used": 116988, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 78-86: { - "gas_used": 39208, - "status": "Executed" + "gas_used": 36784, + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 89-97: { "gas_used": 106557, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 99-109: { "gas_used": 61076, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/token/scaling_factor.exp b/integration-tests/token/scaling_factor.exp index 68505bca..50febcbf 100644 --- a/integration-tests/token/scaling_factor.exp +++ b/integration-tests/token/scaling_factor.exp @@ -4,14 +4,16 @@ task 4 'run'. lines 27-36: { "gas_used": 19195, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "Token" - } - }, - "abort_code": "26887" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "Token" + } + }, + 26887 + ] } } } @@ -19,11 +21,15 @@ task 4 'run'. lines 27-36: task 5 'run'. lines 38-47: { "gas_used": 94743, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 49-60: { "gas_used": 17393, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/token/transfer_then_abort.exp b/integration-tests/token/transfer_then_abort.exp index 7fdd82dc..1805622b 100644 --- a/integration-tests/token/transfer_then_abort.exp +++ b/integration-tests/token/transfer_then_abort.exp @@ -4,9 +4,11 @@ task 3 'run'. lines 7-18: { "gas_used": 90482, "status": { - "MoveAbort": { - "location": "Script", - "abort_code": "41" + "Keep": { + "MoveAbort": [ + "Script", + 41 + ] } } } @@ -14,5 +16,7 @@ task 3 'run'. lines 7-18: task 4 'run'. lines 20-30: { "gas_used": 16311, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/transaction_fee/distribute_txn_fee.exp b/integration-tests/transaction_fee/distribute_txn_fee.exp index c8a6c342..35fdca3a 100644 --- a/integration-tests/transaction_fee/distribute_txn_fee.exp +++ b/integration-tests/transaction_fee/distribute_txn_fee.exp @@ -3,27 +3,33 @@ processed 7 tasks task 4 'run'. lines 9-20: { "gas_used": 74502, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 23-36: { "gas_used": 91645, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 40-52: { "gas_used": 23262, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "CoreAddresses" - } - }, - "abort_code": "2818" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "CoreAddresses" + } + }, + 2818 + ] } } } diff --git a/integration-tests/transaction_scripts/accept_token.exp b/integration-tests/transaction_scripts/accept_token.exp index 5c640017..3572bbeb 100644 --- a/integration-tests/transaction_scripts/accept_token.exp +++ b/integration-tests/transaction_scripts/accept_token.exp @@ -2,6 +2,8 @@ processed 3 tasks task 2 'run'. lines 5-13: { - "gas_used": 39622, - "status": "Executed" + "gas_used": 37198, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/transaction_scripts/create_account.exp b/integration-tests/transaction_scripts/create_account.exp index cf1fd3ce..50c0a82a 100644 --- a/integration-tests/transaction_scripts/create_account.exp +++ b/integration-tests/transaction_scripts/create_account.exp @@ -2,6 +2,8 @@ processed 4 tasks task 3 'run'. lines 8-16: { - "gas_used": 367550, - "status": "Executed" + "gas_used": 363896, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/transaction_scripts/empty_script.exp b/integration-tests/transaction_scripts/empty_script.exp index 62c41c63..4bdbd5ab 100644 --- a/integration-tests/transaction_scripts/empty_script.exp +++ b/integration-tests/transaction_scripts/empty_script.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-8: { "gas_used": 8439, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/deprecated/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.exp b/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.exp similarity index 58% rename from deprecated/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.exp rename to integration-tests/transaction_scripts/execute_modify_dao_config_proposal.exp index fe75b088..688ca421 100644 --- a/deprecated/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.exp +++ b/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.exp @@ -3,29 +3,39 @@ processed 12 tasks task 4 'run'. lines 11-24: { "gas_used": 162417, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 28-47: { "gas_used": 153230, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 51-67: { "gas_used": 40133, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 70-86: { "gas_used": 89072, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 89-101: { "gas_used": 113338, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/deprecated/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.move b/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.move similarity index 100% rename from deprecated/integration-tests/transaction_scripts/execute_modify_dao_config_proposal.move rename to integration-tests/transaction_scripts/execute_modify_dao_config_proposal.move diff --git a/integration-tests/transaction_scripts/execute_on_chain_config_proposal.exp b/integration-tests/transaction_scripts/execute_on_chain_config_proposal.exp new file mode 100644 index 00000000..c5ed07bf --- /dev/null +++ b/integration-tests/transaction_scripts/execute_on_chain_config_proposal.exp @@ -0,0 +1,41 @@ +processed 12 tasks + +task 4 'run'. lines 10-20: +{ + "gas_used": 168481, + "status": { + "Keep": "Executed" + } +} + +task 6 'run'. lines 23-43: +{ + "gas_used": 153230, + "status": { + "Keep": "Executed" + } +} + +task 8 'run'. lines 48-64: +{ + "gas_used": 40133, + "status": { + "Keep": "Executed" + } +} + +task 9 'run'. lines 66-83: +{ + "gas_used": 89072, + "status": { + "Keep": "Executed" + } +} + +task 11 'run'. lines 87-99: +{ + "gas_used": 87133, + "status": { + "Keep": "Executed" + } +} diff --git a/deprecated/integration-tests/transaction_scripts/execute_on_chain_config_proposal.move b/integration-tests/transaction_scripts/execute_on_chain_config_proposal.move similarity index 97% rename from deprecated/integration-tests/transaction_scripts/execute_on_chain_config_proposal.move rename to integration-tests/transaction_scripts/execute_on_chain_config_proposal.move index 6b751581..a9b04257 100644 --- a/deprecated/integration-tests/transaction_scripts/execute_on_chain_config_proposal.move +++ b/integration-tests/transaction_scripts/execute_on_chain_config_proposal.move @@ -97,4 +97,3 @@ script { ); } } -// check: ExecutionFailure, WrappedConfigModifyCapability is migrate to StarcoinDAO \ No newline at end of file diff --git a/integration-tests/transaction_scripts/module_upgrade.exp b/integration-tests/transaction_scripts/module_upgrade.exp index 4129506c..b2fb4401 100644 --- a/integration-tests/transaction_scripts/module_upgrade.exp +++ b/integration-tests/transaction_scripts/module_upgrade.exp @@ -3,41 +3,55 @@ processed 15 tasks task 5 'run'. lines 27-39: { "gas_used": 330845, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 41-52: { - "gas_used": 188044, - "status": "Executed" + "gas_used": 161503, + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 54-64: { "gas_used": 44603, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 67-86: { "gas_used": 164029, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 92-109: { "gas_used": 121084, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 12 'run'. lines 113-126: { "gas_used": 32933, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 14 'run'. lines 131-140: { - "gas_used": 99099, - "status": "Executed" + "gas_used": 87497, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/transaction_scripts/peer_to_peer.exp b/integration-tests/transaction_scripts/peer_to_peer.exp index c68a3923..47e13a89 100644 --- a/integration-tests/transaction_scripts/peer_to_peer.exp +++ b/integration-tests/transaction_scripts/peer_to_peer.exp @@ -3,11 +3,15 @@ processed 5 tasks task 3 'run'. lines 9-17: { "gas_used": 116751, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 19-27: { "gas_used": 112512, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/transaction_scripts/peer_to_peer_with_metadata.exp b/integration-tests/transaction_scripts/peer_to_peer_with_metadata.exp index 44007083..fd95c887 100644 --- a/integration-tests/transaction_scripts/peer_to_peer_with_metadata.exp +++ b/integration-tests/transaction_scripts/peer_to_peer_with_metadata.exp @@ -3,11 +3,15 @@ processed 5 tasks task 3 'run'. lines 8-16: { "gas_used": 114287, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 18-26: { "gas_used": 109463, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/transaction_scripts/withdraw_token_from_treasury.exp b/integration-tests/transaction_scripts/withdraw_token_from_treasury.exp index c2b0becb..6735ad0c 100644 --- a/integration-tests/transaction_scripts/withdraw_token_from_treasury.exp +++ b/integration-tests/transaction_scripts/withdraw_token_from_treasury.exp @@ -3,23 +3,31 @@ processed 9 tasks task 2 'run'. lines 5-16: { "gas_used": 25083, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 21-29: { - "gas_used": 198724, - "status": "Executed" + "gas_used": 175833, + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 35-45: { - "gas_used": 94617, - "status": "Executed" + "gas_used": 40838, + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 51-60: { "gas_used": 144078, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/treasury/linear_withdraw_cap.exp b/integration-tests/treasury/linear_withdraw_cap.exp index 3ddcd17c..9265e98d 100644 --- a/integration-tests/treasury/linear_withdraw_cap.exp +++ b/integration-tests/treasury/linear_withdraw_cap.exp @@ -3,23 +3,31 @@ processed 9 tasks task 2 'run'. lines 5-20: { "gas_used": 37247, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 24-40: { "gas_used": 145828, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 45-61: { "gas_used": 145828, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 66-83: { "gas_used": 142528, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/treasury/split_linear_cap.exp b/integration-tests/treasury/split_linear_cap.exp index a4036825..6bc808a7 100644 --- a/integration-tests/treasury/split_linear_cap.exp +++ b/integration-tests/treasury/split_linear_cap.exp @@ -3,17 +3,23 @@ processed 7 tasks task 2 'run'. lines 7-23: { "gas_used": 25083, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 26-45: { - "gas_used": 191897, - "status": "Executed" + "gas_used": 169006, + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 48-59: { - "gas_used": 97125, - "status": "Executed" + "gas_used": 43346, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/u256/test_u256_gas.exp b/integration-tests/u256/test_u256_gas.exp index 53321277..98b44908 100644 --- a/integration-tests/u256/test_u256_gas.exp +++ b/integration-tests/u256/test_u256_gas.exp @@ -3,47 +3,63 @@ processed 10 tasks task 2 'run'. lines 5-11: { "gas_used": 31743, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 13-20: { "gas_used": 31709, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 4 'run'. lines 23-30: { "gas_used": 28804, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 31-38: { "gas_used": 24167, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 39-48: { "gas_used": 62764, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 49-58: { "gas_used": 62764, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 59-68: { "gas_used": 62764, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 69-78: { "gas_used": 62770, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/upgrade_module_dao_proposal/basic.exp b/integration-tests/upgrade_module_dao_proposal/basic.exp index c6360bd2..db10245f 100644 --- a/integration-tests/upgrade_module_dao_proposal/basic.exp +++ b/integration-tests/upgrade_module_dao_proposal/basic.exp @@ -3,39 +3,49 @@ processed 19 tasks task 5 'run'. lines 25-40: { "gas_used": 254270, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 42-57: { "gas_used": 116988, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 58-68: { "gas_used": 25443, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 70-80: { - "gas_used": 188044, - "status": "Executed" + "gas_used": 161503, + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 82-92: { "gas_used": 42542, "status": { - "MoveAbort": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "UpgradeModuleDaoProposal" - } - }, - "abort_code": "102658" + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "UpgradeModuleDaoProposal" + } + }, + 102658 + ] } } } @@ -43,46 +53,57 @@ task 9 'run'. lines 82-92: task 10 'run'. lines 95-108: { "gas_used": 44603, - "status": "Executed" + "status": { + "Keep": "Executed" + } } -task 11 'run'. lines 110-130: +task 11 'run'. lines 110-129: { - "gas_used": 11530, + "gas_used": 21895, "status": { - "ExecutionFailure": { - "location": { - "Module": { - "address": "0x00000000000000000000000000000001", - "name": "UpgradeModuleDaoProposal" - } - }, - "function": 2, - "code_offset": 1 + "Keep": { + "MoveAbort": [ + { + "Module": { + "address": "0x00000000000000000000000000000001", + "name": "UpgradeModuleDaoProposal" + } + }, + 102916 + ] } } } -task 12 'run'. lines 132-151: +task 12 'run'. lines 131-150: { "gas_used": 164029, - "status": "Executed" + "status": { + "Keep": "Executed" + } } -task 14 'run'. lines 156-172: +task 14 'run'. lines 155-171: { "gas_used": 148558, - "status": "Executed" + "status": { + "Keep": "Executed" + } } -task 16 'run'. lines 176-190: +task 16 'run'. lines 175-189: { "gas_used": 62339, - "status": "Executed" + "status": { + "Keep": "Executed" + } } -task 18 'run'. lines 194-207: +task 18 'run'. lines 193-206: { - "gas_used": 120753, - "status": "Executed" + "gas_used": 109151, + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/upgrade_module_dao_proposal/basic.move b/integration-tests/upgrade_module_dao_proposal/basic.move index 7eb5c14e..cd1f983d 100644 --- a/integration-tests/upgrade_module_dao_proposal/basic.move +++ b/integration-tests/upgrade_module_dao_proposal/basic.move @@ -127,7 +127,6 @@ script { ); } } -// check: ExecutionFailure, UpgradeModuleCapability is move to StarcoinDAO //# run --signers alice script { diff --git a/integration-tests/vector/big_vector.exp b/integration-tests/vector/big_vector.exp index d32be2f0..fbaa8b25 100644 --- a/integration-tests/vector/big_vector.exp +++ b/integration-tests/vector/big_vector.exp @@ -3,47 +3,63 @@ processed 12 tasks task 4 'run'. lines 75-82: { "gas_used": 28541993, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 5 'run'. lines 84-91: { "gas_used": 38550, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 6 'run'. lines 93-101: { "gas_used": 23153926, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 7 'run'. lines 103-110: { "gas_used": 38550, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 8 'run'. lines 112-119: { "gas_used": 39082778, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 121-129: { "gas_used": 53570, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 131-137: { "gas_used": 7165731, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 139-146: { "gas_used": 3608947, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/vector/contains.exp b/integration-tests/vector/contains.exp index 0ed326c9..cb8a4196 100644 --- a/integration-tests/vector/contains.exp +++ b/integration-tests/vector/contains.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-22: { "gas_used": 72677, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/vector/index_of.exp b/integration-tests/vector/index_of.exp index ed03d192..507edaeb 100644 --- a/integration-tests/vector/index_of.exp +++ b/integration-tests/vector/index_of.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-30: { "gas_used": 60299, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/vector/remove.exp b/integration-tests/vector/remove.exp index 0dd555e0..379058c1 100644 --- a/integration-tests/vector/remove.exp +++ b/integration-tests/vector/remove.exp @@ -3,11 +3,15 @@ processed 4 tasks task 2 'run'. lines 5-24: { "gas_used": 49219, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 26-41: { "gas_used": 33862, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/vector/reverse.exp b/integration-tests/vector/reverse.exp index c2ce7d61..e589987e 100644 --- a/integration-tests/vector/reverse.exp +++ b/integration-tests/vector/reverse.exp @@ -3,11 +3,15 @@ processed 4 tasks task 2 'run'. lines 5-25: { "gas_used": 49511, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 27-34: { "gas_used": 14442, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/vector/split.exp b/integration-tests/vector/split.exp index f01a11d6..7244404a 100644 --- a/integration-tests/vector/split.exp +++ b/integration-tests/vector/split.exp @@ -3,11 +3,15 @@ processed 4 tasks task 2 'run'. lines 5-28: { "gas_used": 94233, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 30-57: { "gas_used": 124304, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/vector/swap_remove.exp b/integration-tests/vector/swap_remove.exp index 4ad234c0..20ead814 100644 --- a/integration-tests/vector/swap_remove.exp +++ b/integration-tests/vector/swap_remove.exp @@ -3,5 +3,7 @@ processed 3 tasks task 2 'run'. lines 5-24: { "gas_used": 52799, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/version/basic.exp b/integration-tests/version/basic.exp index 466dda32..df805a02 100644 --- a/integration-tests/version/basic.exp +++ b/integration-tests/version/basic.exp @@ -3,11 +3,15 @@ processed 4 tasks task 2 'run'. lines 5-12: { "gas_used": 61661, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 3 'run'. lines 14-23: { "gas_used": 20089, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/yield_farming/basic.exp b/integration-tests/yield_farming/basic.exp index 61ea727b..87d56038 100644 --- a/integration-tests/yield_farming/basic.exp +++ b/integration-tests/yield_farming/basic.exp @@ -3,41 +3,55 @@ processed 18 tasks task 8 'run'. lines 77-107: { "gas_used": 91918, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 110-129: { "gas_used": 207541, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 134-149: { "gas_used": 127098, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 152-171: { "gas_used": 171324, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 175-185: { "gas_used": 105138, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 15 'run'. lines 189-202: { "gas_used": 71846, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 17 'run'. lines 206-226: { "gas_used": 197100, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/integration-tests/yield_farming/cap_local_store.exp b/integration-tests/yield_farming/cap_local_store.exp index d4fba7b5..69d1ae07 100644 --- a/integration-tests/yield_farming/cap_local_store.exp +++ b/integration-tests/yield_farming/cap_local_store.exp @@ -3,47 +3,63 @@ processed 19 tasks task 8 'run'. lines 67-97: { "gas_used": 91918, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 9 'run'. lines 101-120: { "gas_used": 207541, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 10 'run'. lines 122-137: { "gas_used": 127098, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 11 'run'. lines 139-158: { "gas_used": 182485, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 13 'run'. lines 164-174: { "gas_used": 111323, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 15 'run'. lines 177-190: { "gas_used": 71846, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 17 'run'. lines 194-214: { "gas_used": 202076, - "status": "Executed" + "status": { + "Keep": "Executed" + } } task 18 'run'. lines 216-224: { "gas_used": 54189, - "status": "Executed" + "status": { + "Keep": "Executed" + } } diff --git a/release/README.md b/release/README.md index b8f7d18b..3ab5f41c 100644 --- a/release/README.md +++ b/release/README.md @@ -70,16 +70,4 @@ - Upgrade bytecode to v4.(#3109) - Use move pacakge system to organize stdlib source files.(#3109) - Add `phantom` modifier to NFT and Token Module. (#3109) -- [docs](./v11/docs) - -## Version 12 - -- Account::deposit(address, token) auto create account. -- Rename `spectest` to `integrationt-test`. -- Identifier nft add borrow function. (#34) -- Implement bcs function , byte to basic type. (#43) -- Support starcoin snapshot proof and verify. (#45) -- Implement Ring module. (#44) -- Implement Block state root. (#39) (#41) -- Implement DAOSpace, DAOSpace plugins and plugin marketplace. -- [docs](./v12/docs) \ No newline at end of file +- [docs](./v11/docs) \ No newline at end of file diff --git a/release/v12/abis/Account/accept_token.abi b/release/v12/abis/Account/accept_token.abi deleted file mode 100644 index 9d200103..00000000 Binary files a/release/v12/abis/Account/accept_token.abi and /dev/null differ diff --git a/release/v12/abis/Account/accept_token_entry.abi b/release/v12/abis/Account/accept_token_entry.abi deleted file mode 100644 index 2b482dca..00000000 Binary files a/release/v12/abis/Account/accept_token_entry.abi and /dev/null differ diff --git a/release/v12/abis/Account/create_account_with_initial_amount.abi b/release/v12/abis/Account/create_account_with_initial_amount.abi deleted file mode 100644 index 3a0f339c..00000000 Binary files a/release/v12/abis/Account/create_account_with_initial_amount.abi and /dev/null differ diff --git a/release/v12/abis/Account/create_account_with_initial_amount_entry.abi b/release/v12/abis/Account/create_account_with_initial_amount_entry.abi deleted file mode 100644 index 85e0e210..00000000 Binary files a/release/v12/abis/Account/create_account_with_initial_amount_entry.abi and /dev/null differ diff --git a/release/v12/abis/Account/create_account_with_initial_amount_v2.abi b/release/v12/abis/Account/create_account_with_initial_amount_v2.abi deleted file mode 100644 index 4c1f4529..00000000 Binary files a/release/v12/abis/Account/create_account_with_initial_amount_v2.abi and /dev/null differ diff --git a/release/v12/abis/Account/remove_zero_balance_entry.abi b/release/v12/abis/Account/remove_zero_balance_entry.abi deleted file mode 100644 index fbf4971e..00000000 Binary files a/release/v12/abis/Account/remove_zero_balance_entry.abi and /dev/null differ diff --git a/release/v12/abis/Account/rotate_authentication_key.abi b/release/v12/abis/Account/rotate_authentication_key.abi deleted file mode 100644 index d69bd371..00000000 Binary files a/release/v12/abis/Account/rotate_authentication_key.abi and /dev/null differ diff --git a/release/v12/abis/Account/rotate_authentication_key_entry.abi b/release/v12/abis/Account/rotate_authentication_key_entry.abi deleted file mode 100644 index 81a17ade..00000000 Binary files a/release/v12/abis/Account/rotate_authentication_key_entry.abi and /dev/null differ diff --git a/release/v12/abis/Account/set_auto_accept_token_entry.abi b/release/v12/abis/Account/set_auto_accept_token_entry.abi deleted file mode 100644 index 9b5dab25..00000000 Binary files a/release/v12/abis/Account/set_auto_accept_token_entry.abi and /dev/null differ diff --git a/release/v12/abis/AccountScripts/disable_auto_accept_token.abi b/release/v12/abis/AccountScripts/disable_auto_accept_token.abi deleted file mode 100644 index 3661e680..00000000 Binary files a/release/v12/abis/AccountScripts/disable_auto_accept_token.abi and /dev/null differ diff --git a/release/v12/abis/AccountScripts/enable_auto_accept_token.abi b/release/v12/abis/AccountScripts/enable_auto_accept_token.abi deleted file mode 100644 index 2cb1e7b5..00000000 Binary files a/release/v12/abis/AccountScripts/enable_auto_accept_token.abi and /dev/null differ diff --git a/release/v12/abis/AccountScripts/remove_zero_balance.abi b/release/v12/abis/AccountScripts/remove_zero_balance.abi deleted file mode 100644 index f0ffaf79..00000000 Binary files a/release/v12/abis/AccountScripts/remove_zero_balance.abi and /dev/null differ diff --git a/release/v12/abis/AnyMemberPlugin/install_plugin_proposal_entry.abi b/release/v12/abis/AnyMemberPlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index 4b6ed40a..00000000 Binary files a/release/v12/abis/AnyMemberPlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/AnyMemberPlugin/join_entry.abi b/release/v12/abis/AnyMemberPlugin/join_entry.abi deleted file mode 100644 index c3802f84..00000000 Binary files a/release/v12/abis/AnyMemberPlugin/join_entry.abi and /dev/null differ diff --git a/release/v12/abis/Block/checkpoint_entry.abi b/release/v12/abis/Block/checkpoint_entry.abi deleted file mode 100644 index 951dc0d5..00000000 Binary files a/release/v12/abis/Block/checkpoint_entry.abi and /dev/null differ diff --git a/release/v12/abis/Block/update_state_root_entry.abi b/release/v12/abis/Block/update_state_root_entry.abi deleted file mode 100644 index b9e52802..00000000 Binary files a/release/v12/abis/Block/update_state_root_entry.abi and /dev/null differ diff --git a/release/v12/abis/ConfigProposalPlugin/execute_proposal_entry.abi b/release/v12/abis/ConfigProposalPlugin/execute_proposal_entry.abi deleted file mode 100644 index 854b4101..00000000 Binary files a/release/v12/abis/ConfigProposalPlugin/execute_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/ConfigProposalPlugin/install_plugin_proposal_entry.abi b/release/v12/abis/ConfigProposalPlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index ace4ad77..00000000 Binary files a/release/v12/abis/ConfigProposalPlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOAccount/create_account_entry.abi b/release/v12/abis/DAOAccount/create_account_entry.abi deleted file mode 100644 index c4f21451..00000000 Binary files a/release/v12/abis/DAOAccount/create_account_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOAccount/submit_upgrade_plan_entry.abi b/release/v12/abis/DAOAccount/submit_upgrade_plan_entry.abi deleted file mode 100644 index 31b3451c..00000000 Binary files a/release/v12/abis/DAOAccount/submit_upgrade_plan_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOExtensionPoint/publish_version_entry.abi b/release/v12/abis/DAOExtensionPoint/publish_version_entry.abi deleted file mode 100644 index f321f14c..00000000 Binary files a/release/v12/abis/DAOExtensionPoint/publish_version_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOExtensionPoint/register_entry.abi b/release/v12/abis/DAOExtensionPoint/register_entry.abi deleted file mode 100644 index 7efa0c38..00000000 Binary files a/release/v12/abis/DAOExtensionPoint/register_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOExtensionPoint/star_entry.abi b/release/v12/abis/DAOExtensionPoint/star_entry.abi deleted file mode 100644 index 175c7397..00000000 Binary files a/release/v12/abis/DAOExtensionPoint/star_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOExtensionPoint/unstar_entry.abi b/release/v12/abis/DAOExtensionPoint/unstar_entry.abi deleted file mode 100644 index 42a11b17..00000000 Binary files a/release/v12/abis/DAOExtensionPoint/unstar_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOExtensionPoint/update_entry.abi b/release/v12/abis/DAOExtensionPoint/update_entry.abi deleted file mode 100644 index d858e9df..00000000 Binary files a/release/v12/abis/DAOExtensionPoint/update_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOPluginMarketplace/star_plugin_entry.abi b/release/v12/abis/DAOPluginMarketplace/star_plugin_entry.abi deleted file mode 100644 index 2a874b40..00000000 Binary files a/release/v12/abis/DAOPluginMarketplace/star_plugin_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOPluginMarketplace/unstar_plugin_entry.abi b/release/v12/abis/DAOPluginMarketplace/unstar_plugin_entry.abi deleted file mode 100644 index e9514f66..00000000 Binary files a/release/v12/abis/DAOPluginMarketplace/unstar_plugin_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/accept_member_offer_entry.abi b/release/v12/abis/DAOSpace/accept_member_offer_entry.abi deleted file mode 100644 index 757727e5..00000000 Binary files a/release/v12/abis/DAOSpace/accept_member_offer_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/cast_vote_entry.abi b/release/v12/abis/DAOSpace/cast_vote_entry.abi deleted file mode 100644 index 8396d5c5..00000000 Binary files a/release/v12/abis/DAOSpace/cast_vote_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/clean_proposal_by_id_entry.abi b/release/v12/abis/DAOSpace/clean_proposal_by_id_entry.abi deleted file mode 100644 index 1ae36e35..00000000 Binary files a/release/v12/abis/DAOSpace/clean_proposal_by_id_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/clean_proposals_entry.abi b/release/v12/abis/DAOSpace/clean_proposals_entry.abi deleted file mode 100644 index 280d76c5..00000000 Binary files a/release/v12/abis/DAOSpace/clean_proposals_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/grant_accept_offer_entry.abi b/release/v12/abis/DAOSpace/grant_accept_offer_entry.abi deleted file mode 100644 index 7f42b619..00000000 Binary files a/release/v12/abis/DAOSpace/grant_accept_offer_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/grant_offer_refund_entry.abi b/release/v12/abis/DAOSpace/grant_offer_refund_entry.abi deleted file mode 100644 index 4611b551..00000000 Binary files a/release/v12/abis/DAOSpace/grant_offer_refund_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/grant_withdraw_entry.abi b/release/v12/abis/DAOSpace/grant_withdraw_entry.abi deleted file mode 100644 index a610ea7c..00000000 Binary files a/release/v12/abis/DAOSpace/grant_withdraw_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/queue_proposal_action_entry.abi b/release/v12/abis/DAOSpace/queue_proposal_action_entry.abi deleted file mode 100644 index ca7cccbf..00000000 Binary files a/release/v12/abis/DAOSpace/queue_proposal_action_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/quit_member_entry.abi b/release/v12/abis/DAOSpace/quit_member_entry.abi deleted file mode 100644 index ccbd6ee8..00000000 Binary files a/release/v12/abis/DAOSpace/quit_member_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/refund_grant_entry.abi b/release/v12/abis/DAOSpace/refund_grant_entry.abi deleted file mode 100644 index 7dd8b214..00000000 Binary files a/release/v12/abis/DAOSpace/refund_grant_entry.abi and /dev/null differ diff --git a/release/v12/abis/DAOSpace/reject_proposal_entry.abi b/release/v12/abis/DAOSpace/reject_proposal_entry.abi deleted file mode 100644 index f8a429e2..00000000 Binary files a/release/v12/abis/DAOSpace/reject_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/Dao/destroy_terminated_proposal.abi b/release/v12/abis/Dao/destroy_terminated_proposal.abi deleted file mode 100644 index ce2f1889..00000000 Binary files a/release/v12/abis/Dao/destroy_terminated_proposal.abi and /dev/null differ diff --git a/release/v12/abis/Dao/queue_proposal_action.abi b/release/v12/abis/Dao/queue_proposal_action.abi deleted file mode 100644 index afbffcd7..00000000 Binary files a/release/v12/abis/Dao/queue_proposal_action.abi and /dev/null differ diff --git a/release/v12/abis/DaoVoteScripts/cast_vote.abi b/release/v12/abis/DaoVoteScripts/cast_vote.abi deleted file mode 100644 index 4b294bf3..00000000 Binary files a/release/v12/abis/DaoVoteScripts/cast_vote.abi and /dev/null differ diff --git a/release/v12/abis/DaoVoteScripts/flip_vote.abi b/release/v12/abis/DaoVoteScripts/flip_vote.abi deleted file mode 100644 index 5aca87b2..00000000 Binary files a/release/v12/abis/DaoVoteScripts/flip_vote.abi and /dev/null differ diff --git a/release/v12/abis/DaoVoteScripts/revoke_vote.abi b/release/v12/abis/DaoVoteScripts/revoke_vote.abi deleted file mode 100644 index 66a558bb..00000000 Binary files a/release/v12/abis/DaoVoteScripts/revoke_vote.abi and /dev/null differ diff --git a/release/v12/abis/DaoVoteScripts/revoke_vote_of_power.abi b/release/v12/abis/DaoVoteScripts/revoke_vote_of_power.abi deleted file mode 100644 index 23389794..00000000 Binary files a/release/v12/abis/DaoVoteScripts/revoke_vote_of_power.abi and /dev/null differ diff --git a/release/v12/abis/DaoVoteScripts/unstake_vote.abi b/release/v12/abis/DaoVoteScripts/unstake_vote.abi deleted file mode 100644 index 2d215ed5..00000000 Binary files a/release/v12/abis/DaoVoteScripts/unstake_vote.abi and /dev/null differ diff --git a/release/v12/abis/DummyToken/mint.abi b/release/v12/abis/DummyToken/mint.abi deleted file mode 100644 index 0174dc62..00000000 Binary files a/release/v12/abis/DummyToken/mint.abi and /dev/null differ diff --git a/release/v12/abis/EmptyScripts/empty_script.abi b/release/v12/abis/EmptyScripts/empty_script.abi deleted file mode 100644 index 2be29aba..00000000 Binary files a/release/v12/abis/EmptyScripts/empty_script.abi and /dev/null differ diff --git a/release/v12/abis/GasOracleProposalPlugin/create_oracle_add_proposal.abi b/release/v12/abis/GasOracleProposalPlugin/create_oracle_add_proposal.abi deleted file mode 100644 index 1918610c..00000000 Binary files a/release/v12/abis/GasOracleProposalPlugin/create_oracle_add_proposal.abi and /dev/null differ diff --git a/release/v12/abis/GasOracleProposalPlugin/create_oracle_remove_proposal.abi b/release/v12/abis/GasOracleProposalPlugin/create_oracle_remove_proposal.abi deleted file mode 100644 index 910f3cf1..00000000 Binary files a/release/v12/abis/GasOracleProposalPlugin/create_oracle_remove_proposal.abi and /dev/null differ diff --git a/release/v12/abis/GasOracleProposalPlugin/execute_oracle_add_proposal.abi b/release/v12/abis/GasOracleProposalPlugin/execute_oracle_add_proposal.abi deleted file mode 100644 index be59b2d9..00000000 Binary files a/release/v12/abis/GasOracleProposalPlugin/execute_oracle_add_proposal.abi and /dev/null differ diff --git a/release/v12/abis/GasOracleProposalPlugin/execute_oracle_remove_proposal.abi b/release/v12/abis/GasOracleProposalPlugin/execute_oracle_remove_proposal.abi deleted file mode 100644 index ffa5a859..00000000 Binary files a/release/v12/abis/GasOracleProposalPlugin/execute_oracle_remove_proposal.abi and /dev/null differ diff --git a/release/v12/abis/GasOracleProposalPlugin/install_plugin_proposal_entry.abi b/release/v12/abis/GasOracleProposalPlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index 76515082..00000000 Binary files a/release/v12/abis/GasOracleProposalPlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/Genesis/initialize.abi b/release/v12/abis/Genesis/initialize.abi deleted file mode 100644 index 6ec0ef0c..00000000 Binary files a/release/v12/abis/Genesis/initialize.abi and /dev/null differ diff --git a/release/v12/abis/Genesis/initialize_v2.abi b/release/v12/abis/Genesis/initialize_v2.abi deleted file mode 100644 index 3c0fe67b..00000000 Binary files a/release/v12/abis/Genesis/initialize_v2.abi and /dev/null differ diff --git a/release/v12/abis/GenesisNFT/mint.abi b/release/v12/abis/GenesisNFT/mint.abi deleted file mode 100644 index b6a74ac4..00000000 Binary files a/release/v12/abis/GenesisNFT/mint.abi and /dev/null differ diff --git a/release/v12/abis/GenesisNFT/mint_entry.abi b/release/v12/abis/GenesisNFT/mint_entry.abi deleted file mode 100644 index 874e3fa2..00000000 Binary files a/release/v12/abis/GenesisNFT/mint_entry.abi and /dev/null differ diff --git a/release/v12/abis/GrantProposalPlugin/create_grant_proposal_entry.abi b/release/v12/abis/GrantProposalPlugin/create_grant_proposal_entry.abi deleted file mode 100644 index 888f0e89..00000000 Binary files a/release/v12/abis/GrantProposalPlugin/create_grant_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/GrantProposalPlugin/create_grant_revoke_proposal_entry.abi b/release/v12/abis/GrantProposalPlugin/create_grant_revoke_proposal_entry.abi deleted file mode 100644 index cc45a6d5..00000000 Binary files a/release/v12/abis/GrantProposalPlugin/create_grant_revoke_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/GrantProposalPlugin/execute_grant_proposal_entry.abi b/release/v12/abis/GrantProposalPlugin/execute_grant_proposal_entry.abi deleted file mode 100644 index 5dddef77..00000000 Binary files a/release/v12/abis/GrantProposalPlugin/execute_grant_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/GrantProposalPlugin/execute_grant_revoke_proposal_entry.abi b/release/v12/abis/GrantProposalPlugin/execute_grant_revoke_proposal_entry.abi deleted file mode 100644 index a36b9913..00000000 Binary files a/release/v12/abis/GrantProposalPlugin/execute_grant_revoke_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/GrantProposalPlugin/install_plugin_proposal_entry.abi b/release/v12/abis/GrantProposalPlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index 758eb187..00000000 Binary files a/release/v12/abis/GrantProposalPlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/InstallPluginProposalPlugin/execute_proposal_entry.abi b/release/v12/abis/InstallPluginProposalPlugin/execute_proposal_entry.abi deleted file mode 100644 index c8f9f5e7..00000000 Binary files a/release/v12/abis/InstallPluginProposalPlugin/execute_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/MemberProposalPlugin/create_proposal_entry.abi b/release/v12/abis/MemberProposalPlugin/create_proposal_entry.abi deleted file mode 100644 index c91e8d19..00000000 Binary files a/release/v12/abis/MemberProposalPlugin/create_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/MemberProposalPlugin/execute_proposal_entry.abi b/release/v12/abis/MemberProposalPlugin/execute_proposal_entry.abi deleted file mode 100644 index 458d0214..00000000 Binary files a/release/v12/abis/MemberProposalPlugin/execute_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/MemberProposalPlugin/install_plugin_proposal_entry.abi b/release/v12/abis/MemberProposalPlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index 0c8dfa4f..00000000 Binary files a/release/v12/abis/MemberProposalPlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/MintProposalPlugin/create_mint_proposal_entry.abi b/release/v12/abis/MintProposalPlugin/create_mint_proposal_entry.abi deleted file mode 100644 index 14cc604d..00000000 Binary files a/release/v12/abis/MintProposalPlugin/create_mint_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/MintProposalPlugin/delegate_token_mint_cap_entry.abi b/release/v12/abis/MintProposalPlugin/delegate_token_mint_cap_entry.abi deleted file mode 100644 index 3b1e02a9..00000000 Binary files a/release/v12/abis/MintProposalPlugin/delegate_token_mint_cap_entry.abi and /dev/null differ diff --git a/release/v12/abis/MintProposalPlugin/execute_mint_proposal_entry.abi b/release/v12/abis/MintProposalPlugin/execute_mint_proposal_entry.abi deleted file mode 100644 index 1a0220d0..00000000 Binary files a/release/v12/abis/MintProposalPlugin/execute_mint_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/MintProposalPlugin/install_plugin_proposal_entry.abi b/release/v12/abis/MintProposalPlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index dae9f166..00000000 Binary files a/release/v12/abis/MintProposalPlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/ModifyDaoConfigProposal/execute.abi b/release/v12/abis/ModifyDaoConfigProposal/execute.abi deleted file mode 100644 index a32f5574..00000000 Binary files a/release/v12/abis/ModifyDaoConfigProposal/execute.abi and /dev/null differ diff --git a/release/v12/abis/ModifyDaoConfigProposal/propose.abi b/release/v12/abis/ModifyDaoConfigProposal/propose.abi deleted file mode 100644 index 9dea6390..00000000 Binary files a/release/v12/abis/ModifyDaoConfigProposal/propose.abi and /dev/null differ diff --git a/release/v12/abis/ModuleUpgradeScripts/cancel_upgrade_plan.abi b/release/v12/abis/ModuleUpgradeScripts/cancel_upgrade_plan.abi deleted file mode 100644 index f39e40a4..00000000 Binary files a/release/v12/abis/ModuleUpgradeScripts/cancel_upgrade_plan.abi and /dev/null differ diff --git a/release/v12/abis/ModuleUpgradeScripts/execute_module_upgrade_plan_propose.abi b/release/v12/abis/ModuleUpgradeScripts/execute_module_upgrade_plan_propose.abi deleted file mode 100644 index 0f59d6f0..00000000 Binary files a/release/v12/abis/ModuleUpgradeScripts/execute_module_upgrade_plan_propose.abi and /dev/null differ diff --git a/release/v12/abis/ModuleUpgradeScripts/propose_module_upgrade_v2.abi b/release/v12/abis/ModuleUpgradeScripts/propose_module_upgrade_v2.abi deleted file mode 100644 index a949b260..00000000 Binary files a/release/v12/abis/ModuleUpgradeScripts/propose_module_upgrade_v2.abi and /dev/null differ diff --git a/release/v12/abis/ModuleUpgradeScripts/submit_module_upgrade_plan.abi b/release/v12/abis/ModuleUpgradeScripts/submit_module_upgrade_plan.abi deleted file mode 100644 index 6b11cc23..00000000 Binary files a/release/v12/abis/ModuleUpgradeScripts/submit_module_upgrade_plan.abi and /dev/null differ diff --git a/release/v12/abis/ModuleUpgradeScripts/submit_upgrade_plan.abi b/release/v12/abis/ModuleUpgradeScripts/submit_upgrade_plan.abi deleted file mode 100644 index 1198af01..00000000 Binary files a/release/v12/abis/ModuleUpgradeScripts/submit_upgrade_plan.abi and /dev/null differ diff --git a/release/v12/abis/ModuleUpgradeScripts/update_module_upgrade_strategy.abi b/release/v12/abis/ModuleUpgradeScripts/update_module_upgrade_strategy.abi deleted file mode 100644 index a166e001..00000000 Binary files a/release/v12/abis/ModuleUpgradeScripts/update_module_upgrade_strategy.abi and /dev/null differ diff --git a/release/v12/abis/ModuleUpgradeScripts/update_module_upgrade_strategy_with_min_time.abi b/release/v12/abis/ModuleUpgradeScripts/update_module_upgrade_strategy_with_min_time.abi deleted file mode 100644 index f8e8ad1c..00000000 Binary files a/release/v12/abis/ModuleUpgradeScripts/update_module_upgrade_strategy_with_min_time.abi and /dev/null differ diff --git a/release/v12/abis/NFT/accept.abi b/release/v12/abis/NFT/accept.abi deleted file mode 100644 index 8e678ebd..00000000 Binary files a/release/v12/abis/NFT/accept.abi and /dev/null differ diff --git a/release/v12/abis/NFT/accept_entry.abi b/release/v12/abis/NFT/accept_entry.abi deleted file mode 100644 index 23b84386..00000000 Binary files a/release/v12/abis/NFT/accept_entry.abi and /dev/null differ diff --git a/release/v12/abis/NFT/destroy_empty.abi b/release/v12/abis/NFT/destroy_empty.abi deleted file mode 100644 index 456cb71a..00000000 Binary files a/release/v12/abis/NFT/destroy_empty.abi and /dev/null differ diff --git a/release/v12/abis/NFT/destroy_empty_entry.abi b/release/v12/abis/NFT/destroy_empty_entry.abi deleted file mode 100644 index 808b5de8..00000000 Binary files a/release/v12/abis/NFT/destroy_empty_entry.abi and /dev/null differ diff --git a/release/v12/abis/NFT/remove_empty_gallery.abi b/release/v12/abis/NFT/remove_empty_gallery.abi deleted file mode 100644 index 17b89be0..00000000 Binary files a/release/v12/abis/NFT/remove_empty_gallery.abi and /dev/null differ diff --git a/release/v12/abis/NFT/remove_empty_gallery_entry.abi b/release/v12/abis/NFT/remove_empty_gallery_entry.abi deleted file mode 100644 index b1fbfa40..00000000 Binary files a/release/v12/abis/NFT/remove_empty_gallery_entry.abi and /dev/null differ diff --git a/release/v12/abis/NFT/transfer.abi b/release/v12/abis/NFT/transfer.abi deleted file mode 100644 index 492b218d..00000000 Binary files a/release/v12/abis/NFT/transfer.abi and /dev/null differ diff --git a/release/v12/abis/NFT/transfer_entry.abi b/release/v12/abis/NFT/transfer_entry.abi deleted file mode 100644 index 8d60d00a..00000000 Binary files a/release/v12/abis/NFT/transfer_entry.abi and /dev/null differ diff --git a/release/v12/abis/Offer/take_offer.abi b/release/v12/abis/Offer/take_offer.abi deleted file mode 100644 index d601d280..00000000 Binary files a/release/v12/abis/Offer/take_offer.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/execute_on_chain_config_proposal.abi b/release/v12/abis/OnChainConfigScripts/execute_on_chain_config_proposal.abi deleted file mode 100644 index 884f2421..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/execute_on_chain_config_proposal.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/execute_on_chain_config_proposal_v2.abi b/release/v12/abis/OnChainConfigScripts/execute_on_chain_config_proposal_v2.abi deleted file mode 100644 index 4fa4c35a..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/execute_on_chain_config_proposal_v2.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/propose_update_consensus_config.abi b/release/v12/abis/OnChainConfigScripts/propose_update_consensus_config.abi deleted file mode 100644 index 543cd101..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/propose_update_consensus_config.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/propose_update_move_language_version.abi b/release/v12/abis/OnChainConfigScripts/propose_update_move_language_version.abi deleted file mode 100644 index 20cc2fa3..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/propose_update_move_language_version.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/propose_update_reward_config.abi b/release/v12/abis/OnChainConfigScripts/propose_update_reward_config.abi deleted file mode 100644 index 8a2a050d..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/propose_update_reward_config.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/propose_update_txn_publish_option.abi b/release/v12/abis/OnChainConfigScripts/propose_update_txn_publish_option.abi deleted file mode 100644 index 1f80407e..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/propose_update_txn_publish_option.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/propose_update_txn_timeout_config.abi b/release/v12/abis/OnChainConfigScripts/propose_update_txn_timeout_config.abi deleted file mode 100644 index 7dbba62f..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/propose_update_txn_timeout_config.abi and /dev/null differ diff --git a/release/v12/abis/OnChainConfigScripts/propose_update_vm_config.abi b/release/v12/abis/OnChainConfigScripts/propose_update_vm_config.abi deleted file mode 100644 index 2a990bca..00000000 Binary files a/release/v12/abis/OnChainConfigScripts/propose_update_vm_config.abi and /dev/null differ diff --git a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_consensus_config_entry.abi b/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_consensus_config_entry.abi deleted file mode 100644 index 086b125c..00000000 Binary files a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_consensus_config_entry.abi and /dev/null differ diff --git a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_move_language_version_entry.abi b/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_move_language_version_entry.abi deleted file mode 100644 index ca21cb33..00000000 Binary files a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_move_language_version_entry.abi and /dev/null differ diff --git a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_reward_config_entry.abi b/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_reward_config_entry.abi deleted file mode 100644 index 994048ad..00000000 Binary files a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_reward_config_entry.abi and /dev/null differ diff --git a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_txn_publish_option_entry.abi b/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_txn_publish_option_entry.abi deleted file mode 100644 index f5c84ff1..00000000 Binary files a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_txn_publish_option_entry.abi and /dev/null differ diff --git a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_txn_timeout_config_entry.abi b/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_txn_timeout_config_entry.abi deleted file mode 100644 index 5853c243..00000000 Binary files a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_txn_timeout_config_entry.abi and /dev/null differ diff --git a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_vm_config_entry.abi b/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_vm_config_entry.abi deleted file mode 100644 index 3b866ab6..00000000 Binary files a/release/v12/abis/OnChainStarcoinDAOConfig/propose_update_vm_config_entry.abi and /dev/null differ diff --git a/release/v12/abis/Oracle/init_data_source.abi b/release/v12/abis/Oracle/init_data_source.abi deleted file mode 100644 index c5e6b0be..00000000 Binary files a/release/v12/abis/Oracle/init_data_source.abi and /dev/null differ diff --git a/release/v12/abis/Oracle/init_data_source_entry.abi b/release/v12/abis/Oracle/init_data_source_entry.abi deleted file mode 100644 index e925259a..00000000 Binary files a/release/v12/abis/Oracle/init_data_source_entry.abi and /dev/null differ diff --git a/release/v12/abis/Oracle/register_entry.abi b/release/v12/abis/Oracle/register_entry.abi deleted file mode 100644 index 08d280af..00000000 Binary files a/release/v12/abis/Oracle/register_entry.abi and /dev/null differ diff --git a/release/v12/abis/Oracle/register_oracle.abi b/release/v12/abis/Oracle/register_oracle.abi deleted file mode 100644 index b9d93a29..00000000 Binary files a/release/v12/abis/Oracle/register_oracle.abi and /dev/null differ diff --git a/release/v12/abis/Oracle/register_oracle_entry.abi b/release/v12/abis/Oracle/register_oracle_entry.abi deleted file mode 100644 index 14527ed7..00000000 Binary files a/release/v12/abis/Oracle/register_oracle_entry.abi and /dev/null differ diff --git a/release/v12/abis/Oracle/update.abi b/release/v12/abis/Oracle/update.abi deleted file mode 100644 index acbc5310..00000000 Binary files a/release/v12/abis/Oracle/update.abi and /dev/null differ diff --git a/release/v12/abis/Oracle/update_entry.abi b/release/v12/abis/Oracle/update_entry.abi deleted file mode 100644 index ec35f438..00000000 Binary files a/release/v12/abis/Oracle/update_entry.abi and /dev/null differ diff --git a/release/v12/abis/PackageTxnManager/convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2.abi b/release/v12/abis/PackageTxnManager/convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2.abi deleted file mode 100644 index 179a1e05..00000000 Binary files a/release/v12/abis/PackageTxnManager/convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/create_token_accept_proposal_entry.abi b/release/v12/abis/StakeToSBTPlugin/create_token_accept_proposal_entry.abi deleted file mode 100644 index 1681816e..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/create_token_accept_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/create_weight_proposal_entry.abi b/release/v12/abis/StakeToSBTPlugin/create_weight_proposal_entry.abi deleted file mode 100644 index bff74a43..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/create_weight_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/execute_token_accept_proposal_entry.abi b/release/v12/abis/StakeToSBTPlugin/execute_token_accept_proposal_entry.abi deleted file mode 100644 index af507723..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/execute_token_accept_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/execute_weight_proposal_entry.abi b/release/v12/abis/StakeToSBTPlugin/execute_weight_proposal_entry.abi deleted file mode 100644 index dbeb6f0e..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/execute_weight_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/install_plugin_proposal_entry.abi b/release/v12/abis/StakeToSBTPlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index 27336ed5..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/stake_entry.abi b/release/v12/abis/StakeToSBTPlugin/stake_entry.abi deleted file mode 100644 index 1ba9cb2b..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/stake_entry.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/unstake_all_entry.abi b/release/v12/abis/StakeToSBTPlugin/unstake_all_entry.abi deleted file mode 100644 index 1791f37e..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/unstake_all_entry.abi and /dev/null differ diff --git a/release/v12/abis/StakeToSBTPlugin/unstake_by_id_entry.abi b/release/v12/abis/StakeToSBTPlugin/unstake_by_id_entry.abi deleted file mode 100644 index 746114b0..00000000 Binary files a/release/v12/abis/StakeToSBTPlugin/unstake_by_id_entry.abi and /dev/null differ diff --git a/release/v12/abis/StdlibUpgradeScripts/take_linear_withdraw_capability.abi b/release/v12/abis/StdlibUpgradeScripts/take_linear_withdraw_capability.abi deleted file mode 100644 index aa00d595..00000000 Binary files a/release/v12/abis/StdlibUpgradeScripts/take_linear_withdraw_capability.abi and /dev/null differ diff --git a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v11_to_v12.abi b/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v11_to_v12.abi deleted file mode 100644 index 4e6f60b3..00000000 Binary files a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v11_to_v12.abi and /dev/null differ diff --git a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v2_to_v3.abi b/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v2_to_v3.abi deleted file mode 100644 index 824b629f..00000000 Binary files a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v2_to_v3.abi and /dev/null differ diff --git a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v5_to_v6.abi b/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v5_to_v6.abi deleted file mode 100644 index 4556e0de..00000000 Binary files a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v5_to_v6.abi and /dev/null differ diff --git a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v6_to_v7.abi b/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v6_to_v7.abi deleted file mode 100644 index 285bf84a..00000000 Binary files a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v6_to_v7.abi and /dev/null differ diff --git a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v7_to_v8.abi b/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v7_to_v8.abi deleted file mode 100644 index 6795d809..00000000 Binary files a/release/v12/abis/StdlibUpgradeScripts/upgrade_from_v7_to_v8.abi and /dev/null differ diff --git a/release/v12/abis/TransferScripts/batch_peer_to_peer.abi b/release/v12/abis/TransferScripts/batch_peer_to_peer.abi deleted file mode 100644 index f6a196ff..00000000 Binary files a/release/v12/abis/TransferScripts/batch_peer_to_peer.abi and /dev/null differ diff --git a/release/v12/abis/TransferScripts/batch_peer_to_peer_v2.abi b/release/v12/abis/TransferScripts/batch_peer_to_peer_v2.abi deleted file mode 100644 index 77a837ee..00000000 Binary files a/release/v12/abis/TransferScripts/batch_peer_to_peer_v2.abi and /dev/null differ diff --git a/release/v12/abis/TransferScripts/peer_to_peer.abi b/release/v12/abis/TransferScripts/peer_to_peer.abi deleted file mode 100644 index 29e6b70d..00000000 Binary files a/release/v12/abis/TransferScripts/peer_to_peer.abi and /dev/null differ diff --git a/release/v12/abis/TransferScripts/peer_to_peer_batch.abi b/release/v12/abis/TransferScripts/peer_to_peer_batch.abi deleted file mode 100644 index 0e6a00b0..00000000 Binary files a/release/v12/abis/TransferScripts/peer_to_peer_batch.abi and /dev/null differ diff --git a/release/v12/abis/TransferScripts/peer_to_peer_v2.abi b/release/v12/abis/TransferScripts/peer_to_peer_v2.abi deleted file mode 100644 index b3e5683a..00000000 Binary files a/release/v12/abis/TransferScripts/peer_to_peer_v2.abi and /dev/null differ diff --git a/release/v12/abis/TransferScripts/peer_to_peer_with_metadata.abi b/release/v12/abis/TransferScripts/peer_to_peer_with_metadata.abi deleted file mode 100644 index 1520ef4a..00000000 Binary files a/release/v12/abis/TransferScripts/peer_to_peer_with_metadata.abi and /dev/null differ diff --git a/release/v12/abis/TransferScripts/peer_to_peer_with_metadata_v2.abi b/release/v12/abis/TransferScripts/peer_to_peer_with_metadata_v2.abi deleted file mode 100644 index 461b7ede..00000000 Binary files a/release/v12/abis/TransferScripts/peer_to_peer_with_metadata_v2.abi and /dev/null differ diff --git a/release/v12/abis/TreasuryPlugin/create_withdraw_proposal_entry.abi b/release/v12/abis/TreasuryPlugin/create_withdraw_proposal_entry.abi deleted file mode 100644 index a39f0963..00000000 Binary files a/release/v12/abis/TreasuryPlugin/create_withdraw_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/TreasuryPlugin/execute_withdraw_proposal_entry.abi b/release/v12/abis/TreasuryPlugin/execute_withdraw_proposal_entry.abi deleted file mode 100644 index f558575a..00000000 Binary files a/release/v12/abis/TreasuryPlugin/execute_withdraw_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/TreasuryScripts/execute_withdraw_proposal.abi b/release/v12/abis/TreasuryScripts/execute_withdraw_proposal.abi deleted file mode 100644 index c718e096..00000000 Binary files a/release/v12/abis/TreasuryScripts/execute_withdraw_proposal.abi and /dev/null differ diff --git a/release/v12/abis/TreasuryScripts/propose_withdraw.abi b/release/v12/abis/TreasuryScripts/propose_withdraw.abi deleted file mode 100644 index 471d3f1c..00000000 Binary files a/release/v12/abis/TreasuryScripts/propose_withdraw.abi and /dev/null differ diff --git a/release/v12/abis/TreasuryScripts/withdraw_and_split_lt_withdraw_cap.abi b/release/v12/abis/TreasuryScripts/withdraw_and_split_lt_withdraw_cap.abi deleted file mode 100644 index 2aa69118..00000000 Binary files a/release/v12/abis/TreasuryScripts/withdraw_and_split_lt_withdraw_cap.abi and /dev/null differ diff --git a/release/v12/abis/TreasuryScripts/withdraw_token_with_linear_withdraw_capability.abi b/release/v12/abis/TreasuryScripts/withdraw_token_with_linear_withdraw_capability.abi deleted file mode 100644 index 7e0f00e1..00000000 Binary files a/release/v12/abis/TreasuryScripts/withdraw_token_with_linear_withdraw_capability.abi and /dev/null differ diff --git a/release/v12/abis/UpgradeModulePlugin/create_proposal_entry.abi b/release/v12/abis/UpgradeModulePlugin/create_proposal_entry.abi deleted file mode 100644 index 14cc34a3..00000000 Binary files a/release/v12/abis/UpgradeModulePlugin/create_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/UpgradeModulePlugin/execute_proposal_entry.abi b/release/v12/abis/UpgradeModulePlugin/execute_proposal_entry.abi deleted file mode 100644 index 4e89d519..00000000 Binary files a/release/v12/abis/UpgradeModulePlugin/execute_proposal_entry.abi and /dev/null differ diff --git a/release/v12/abis/UpgradeModulePlugin/install_plugin_proposal_entry.abi b/release/v12/abis/UpgradeModulePlugin/install_plugin_proposal_entry.abi deleted file mode 100644 index 4609222c..00000000 Binary files a/release/v12/abis/UpgradeModulePlugin/install_plugin_proposal_entry.abi and /dev/null differ diff --git a/release/v12/bytecode_modules/ASCII.mv b/release/v12/bytecode_modules/ASCII.mv deleted file mode 100644 index 35663a36..00000000 Binary files a/release/v12/bytecode_modules/ASCII.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Account.mv b/release/v12/bytecode_modules/Account.mv deleted file mode 100644 index 4e1d4368..00000000 Binary files a/release/v12/bytecode_modules/Account.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/AccountScripts.mv b/release/v12/bytecode_modules/AccountScripts.mv deleted file mode 100644 index 4f709474..00000000 Binary files a/release/v12/bytecode_modules/AccountScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/AnyMemberPlugin.mv b/release/v12/bytecode_modules/AnyMemberPlugin.mv deleted file mode 100644 index e1f385e9..00000000 Binary files a/release/v12/bytecode_modules/AnyMemberPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Arith.mv b/release/v12/bytecode_modules/Arith.mv deleted file mode 100644 index 1b36c0f7..00000000 Binary files a/release/v12/bytecode_modules/Arith.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Authenticator.mv b/release/v12/bytecode_modules/Authenticator.mv deleted file mode 100644 index 9626d9c1..00000000 Binary files a/release/v12/bytecode_modules/Authenticator.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/BCS.mv b/release/v12/bytecode_modules/BCS.mv deleted file mode 100644 index 83ccc945..00000000 Binary files a/release/v12/bytecode_modules/BCS.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/BitOperators.mv b/release/v12/bytecode_modules/BitOperators.mv deleted file mode 100644 index d22b483a..00000000 Binary files a/release/v12/bytecode_modules/BitOperators.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Block.mv b/release/v12/bytecode_modules/Block.mv deleted file mode 100644 index a7fdecd2..00000000 Binary files a/release/v12/bytecode_modules/Block.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/BlockReward.mv b/release/v12/bytecode_modules/BlockReward.mv deleted file mode 100644 index e7027b75..00000000 Binary files a/release/v12/bytecode_modules/BlockReward.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/ChainId.mv b/release/v12/bytecode_modules/ChainId.mv deleted file mode 100644 index 6ed0508f..00000000 Binary files a/release/v12/bytecode_modules/ChainId.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Collection.mv b/release/v12/bytecode_modules/Collection.mv deleted file mode 100644 index 5235cf8e..00000000 Binary files a/release/v12/bytecode_modules/Collection.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Collection2.mv b/release/v12/bytecode_modules/Collection2.mv deleted file mode 100644 index ddd3600c..00000000 Binary files a/release/v12/bytecode_modules/Collection2.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Compare.mv b/release/v12/bytecode_modules/Compare.mv deleted file mode 100644 index 9fc383b4..00000000 Binary files a/release/v12/bytecode_modules/Compare.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Config.mv b/release/v12/bytecode_modules/Config.mv deleted file mode 100644 index df3c899b..00000000 Binary files a/release/v12/bytecode_modules/Config.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/ConfigProposalPlugin.mv b/release/v12/bytecode_modules/ConfigProposalPlugin.mv deleted file mode 100644 index 28e3a26c..00000000 Binary files a/release/v12/bytecode_modules/ConfigProposalPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/ConsensusConfig.mv b/release/v12/bytecode_modules/ConsensusConfig.mv deleted file mode 100644 index 6861e14b..00000000 Binary files a/release/v12/bytecode_modules/ConsensusConfig.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/ConsensusStrategy.mv b/release/v12/bytecode_modules/ConsensusStrategy.mv deleted file mode 100644 index d389083d..00000000 Binary files a/release/v12/bytecode_modules/ConsensusStrategy.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/CoreAddresses.mv b/release/v12/bytecode_modules/CoreAddresses.mv deleted file mode 100644 index 013b5f11..00000000 Binary files a/release/v12/bytecode_modules/CoreAddresses.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DAOAccount.mv b/release/v12/bytecode_modules/DAOAccount.mv deleted file mode 100644 index 995371a8..00000000 Binary files a/release/v12/bytecode_modules/DAOAccount.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DAOExtensionPoint.mv b/release/v12/bytecode_modules/DAOExtensionPoint.mv deleted file mode 100644 index fa6a673f..00000000 Binary files a/release/v12/bytecode_modules/DAOExtensionPoint.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DAOPluginMarketplace.mv b/release/v12/bytecode_modules/DAOPluginMarketplace.mv deleted file mode 100644 index e7cbb2eb..00000000 Binary files a/release/v12/bytecode_modules/DAOPluginMarketplace.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DAORegistry.mv b/release/v12/bytecode_modules/DAORegistry.mv deleted file mode 100644 index 843b29a4..00000000 Binary files a/release/v12/bytecode_modules/DAORegistry.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DAOSpace.mv b/release/v12/bytecode_modules/DAOSpace.mv deleted file mode 100644 index 90e84b43..00000000 Binary files a/release/v12/bytecode_modules/DAOSpace.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Dao.mv b/release/v12/bytecode_modules/Dao.mv deleted file mode 100644 index 2039ab59..00000000 Binary files a/release/v12/bytecode_modules/Dao.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DaoVoteScripts.mv b/release/v12/bytecode_modules/DaoVoteScripts.mv deleted file mode 100644 index 6c1a2c9f..00000000 Binary files a/release/v12/bytecode_modules/DaoVoteScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Debug.mv b/release/v12/bytecode_modules/Debug.mv deleted file mode 100644 index ceb0961b..00000000 Binary files a/release/v12/bytecode_modules/Debug.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DummyToken.mv b/release/v12/bytecode_modules/DummyToken.mv deleted file mode 100644 index 49ee4840..00000000 Binary files a/release/v12/bytecode_modules/DummyToken.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/DummyTokenScripts.mv b/release/v12/bytecode_modules/DummyTokenScripts.mv deleted file mode 100644 index 87a67c1e..00000000 Binary files a/release/v12/bytecode_modules/DummyTokenScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/EVMAddress.mv b/release/v12/bytecode_modules/EVMAddress.mv deleted file mode 100644 index 5d447d73..00000000 Binary files a/release/v12/bytecode_modules/EVMAddress.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/EmptyScripts.mv b/release/v12/bytecode_modules/EmptyScripts.mv deleted file mode 100644 index 61c71ee4..00000000 Binary files a/release/v12/bytecode_modules/EmptyScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Epoch.mv b/release/v12/bytecode_modules/Epoch.mv deleted file mode 100644 index 5f98d6a9..00000000 Binary files a/release/v12/bytecode_modules/Epoch.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Errors.mv b/release/v12/bytecode_modules/Errors.mv deleted file mode 100644 index 74bc6f4c..00000000 Binary files a/release/v12/bytecode_modules/Errors.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Event.mv b/release/v12/bytecode_modules/Event.mv deleted file mode 100644 index cfcb7069..00000000 Binary files a/release/v12/bytecode_modules/Event.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/EventUtil.mv b/release/v12/bytecode_modules/EventUtil.mv deleted file mode 100644 index bcf5fb84..00000000 Binary files a/release/v12/bytecode_modules/EventUtil.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/FixedPoint32.mv b/release/v12/bytecode_modules/FixedPoint32.mv deleted file mode 100644 index 06b87dd7..00000000 Binary files a/release/v12/bytecode_modules/FixedPoint32.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/GasOracle.mv b/release/v12/bytecode_modules/GasOracle.mv deleted file mode 100644 index ecc2376d..00000000 Binary files a/release/v12/bytecode_modules/GasOracle.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/GasOracleProposalPlugin.mv b/release/v12/bytecode_modules/GasOracleProposalPlugin.mv deleted file mode 100644 index 8d2fc247..00000000 Binary files a/release/v12/bytecode_modules/GasOracleProposalPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Genesis.mv b/release/v12/bytecode_modules/Genesis.mv deleted file mode 100644 index 37dc35bc..00000000 Binary files a/release/v12/bytecode_modules/Genesis.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/GenesisNFT.mv b/release/v12/bytecode_modules/GenesisNFT.mv deleted file mode 100644 index 48c1bbde..00000000 Binary files a/release/v12/bytecode_modules/GenesisNFT.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/GenesisNFTScripts.mv b/release/v12/bytecode_modules/GenesisNFTScripts.mv deleted file mode 100644 index 3aa46b0b..00000000 Binary files a/release/v12/bytecode_modules/GenesisNFTScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/GenesisSignerCapability.mv b/release/v12/bytecode_modules/GenesisSignerCapability.mv deleted file mode 100644 index 8f2da435..00000000 Binary files a/release/v12/bytecode_modules/GenesisSignerCapability.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/GrantProposalPlugin.mv b/release/v12/bytecode_modules/GrantProposalPlugin.mv deleted file mode 100644 index c71344ab..00000000 Binary files a/release/v12/bytecode_modules/GrantProposalPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Hash.mv b/release/v12/bytecode_modules/Hash.mv deleted file mode 100644 index 491ed27e..00000000 Binary files a/release/v12/bytecode_modules/Hash.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/IdentifierNFT.mv b/release/v12/bytecode_modules/IdentifierNFT.mv deleted file mode 100644 index 816454d7..00000000 Binary files a/release/v12/bytecode_modules/IdentifierNFT.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/IdentifierNFTScripts.mv b/release/v12/bytecode_modules/IdentifierNFTScripts.mv deleted file mode 100644 index 23ca97d3..00000000 Binary files a/release/v12/bytecode_modules/IdentifierNFTScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/InstallPluginProposalPlugin.mv b/release/v12/bytecode_modules/InstallPluginProposalPlugin.mv deleted file mode 100644 index cf8793db..00000000 Binary files a/release/v12/bytecode_modules/InstallPluginProposalPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/LanguageVersion.mv b/release/v12/bytecode_modules/LanguageVersion.mv deleted file mode 100644 index 19a36818..00000000 Binary files a/release/v12/bytecode_modules/LanguageVersion.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Math.mv b/release/v12/bytecode_modules/Math.mv deleted file mode 100644 index b46162a5..00000000 Binary files a/release/v12/bytecode_modules/Math.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/MemberProposalPlugin.mv b/release/v12/bytecode_modules/MemberProposalPlugin.mv deleted file mode 100644 index 3e83c189..00000000 Binary files a/release/v12/bytecode_modules/MemberProposalPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/MerkleNFTDistributor.mv b/release/v12/bytecode_modules/MerkleNFTDistributor.mv deleted file mode 100644 index c37a0416..00000000 Binary files a/release/v12/bytecode_modules/MerkleNFTDistributor.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/MerkleProof.mv b/release/v12/bytecode_modules/MerkleProof.mv deleted file mode 100644 index 7d133421..00000000 Binary files a/release/v12/bytecode_modules/MerkleProof.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/MintDaoProposal.mv b/release/v12/bytecode_modules/MintDaoProposal.mv deleted file mode 100644 index 6ace4b21..00000000 Binary files a/release/v12/bytecode_modules/MintDaoProposal.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/MintProposalPlugin.mv b/release/v12/bytecode_modules/MintProposalPlugin.mv deleted file mode 100644 index bb6091f4..00000000 Binary files a/release/v12/bytecode_modules/MintProposalPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/MintScripts.mv b/release/v12/bytecode_modules/MintScripts.mv deleted file mode 100644 index bf26c30f..00000000 Binary files a/release/v12/bytecode_modules/MintScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/ModifyDaoConfigProposal.mv b/release/v12/bytecode_modules/ModifyDaoConfigProposal.mv deleted file mode 100644 index 5c00c614..00000000 Binary files a/release/v12/bytecode_modules/ModifyDaoConfigProposal.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/ModuleUpgradeScripts.mv b/release/v12/bytecode_modules/ModuleUpgradeScripts.mv deleted file mode 100644 index 1bfea8bd..00000000 Binary files a/release/v12/bytecode_modules/ModuleUpgradeScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/NFT.mv b/release/v12/bytecode_modules/NFT.mv deleted file mode 100644 index 70ffe949..00000000 Binary files a/release/v12/bytecode_modules/NFT.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/NFTGallery.mv b/release/v12/bytecode_modules/NFTGallery.mv deleted file mode 100644 index 9f3fb03e..00000000 Binary files a/release/v12/bytecode_modules/NFTGallery.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/NFTGalleryScripts.mv b/release/v12/bytecode_modules/NFTGalleryScripts.mv deleted file mode 100644 index d7954ee6..00000000 Binary files a/release/v12/bytecode_modules/NFTGalleryScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Offer.mv b/release/v12/bytecode_modules/Offer.mv deleted file mode 100644 index c8216dd6..00000000 Binary files a/release/v12/bytecode_modules/Offer.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/OnChainConfigDao.mv b/release/v12/bytecode_modules/OnChainConfigDao.mv deleted file mode 100644 index 5e578fd1..00000000 Binary files a/release/v12/bytecode_modules/OnChainConfigDao.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/OnChainConfigScripts.mv b/release/v12/bytecode_modules/OnChainConfigScripts.mv deleted file mode 100644 index dfb3123e..00000000 Binary files a/release/v12/bytecode_modules/OnChainConfigScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/OnChainStarcoinDAOConfig.mv b/release/v12/bytecode_modules/OnChainStarcoinDAOConfig.mv deleted file mode 100644 index cc510c81..00000000 Binary files a/release/v12/bytecode_modules/OnChainStarcoinDAOConfig.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Option.mv b/release/v12/bytecode_modules/Option.mv deleted file mode 100644 index 47244d70..00000000 Binary files a/release/v12/bytecode_modules/Option.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Oracle.mv b/release/v12/bytecode_modules/Oracle.mv deleted file mode 100644 index b2ef22b9..00000000 Binary files a/release/v12/bytecode_modules/Oracle.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/PackageTxnManager.mv b/release/v12/bytecode_modules/PackageTxnManager.mv deleted file mode 100644 index de91a6bd..00000000 Binary files a/release/v12/bytecode_modules/PackageTxnManager.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/PriceOracle.mv b/release/v12/bytecode_modules/PriceOracle.mv deleted file mode 100644 index 3fca8abf..00000000 Binary files a/release/v12/bytecode_modules/PriceOracle.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/PriceOracleAggregator.mv b/release/v12/bytecode_modules/PriceOracleAggregator.mv deleted file mode 100644 index 2e2440e4..00000000 Binary files a/release/v12/bytecode_modules/PriceOracleAggregator.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/PriceOracleScripts.mv b/release/v12/bytecode_modules/PriceOracleScripts.mv deleted file mode 100644 index c433d2c0..00000000 Binary files a/release/v12/bytecode_modules/PriceOracleScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/RewardConfig.mv b/release/v12/bytecode_modules/RewardConfig.mv deleted file mode 100644 index 83a4162a..00000000 Binary files a/release/v12/bytecode_modules/RewardConfig.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Ring.mv b/release/v12/bytecode_modules/Ring.mv deleted file mode 100644 index d14fabef..00000000 Binary files a/release/v12/bytecode_modules/Ring.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/SBTVoteStrategy.mv b/release/v12/bytecode_modules/SBTVoteStrategy.mv deleted file mode 100644 index e3f6b72b..00000000 Binary files a/release/v12/bytecode_modules/SBTVoteStrategy.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/SIP_2.mv b/release/v12/bytecode_modules/SIP_2.mv deleted file mode 100644 index a3f9e8a6..00000000 Binary files a/release/v12/bytecode_modules/SIP_2.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/SIP_3.mv b/release/v12/bytecode_modules/SIP_3.mv deleted file mode 100644 index a9d0bbdc..00000000 Binary files a/release/v12/bytecode_modules/SIP_3.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/STC.mv b/release/v12/bytecode_modules/STC.mv deleted file mode 100644 index 83f51548..00000000 Binary files a/release/v12/bytecode_modules/STC.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/STCUSDOracle.mv b/release/v12/bytecode_modules/STCUSDOracle.mv deleted file mode 100644 index 26592edc..00000000 Binary files a/release/v12/bytecode_modules/STCUSDOracle.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/SharedEd25519PublicKey.mv b/release/v12/bytecode_modules/SharedEd25519PublicKey.mv deleted file mode 100644 index b3cdc82a..00000000 Binary files a/release/v12/bytecode_modules/SharedEd25519PublicKey.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Signature.mv b/release/v12/bytecode_modules/Signature.mv deleted file mode 100644 index a5743312..00000000 Binary files a/release/v12/bytecode_modules/Signature.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/SignedInteger64.mv b/release/v12/bytecode_modules/SignedInteger64.mv deleted file mode 100644 index 366352d8..00000000 Binary files a/release/v12/bytecode_modules/SignedInteger64.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Signer.mv b/release/v12/bytecode_modules/Signer.mv deleted file mode 100644 index 48fc86fa..00000000 Binary files a/release/v12/bytecode_modules/Signer.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/SimpleMap.mv b/release/v12/bytecode_modules/SimpleMap.mv deleted file mode 100644 index eddad186..00000000 Binary files a/release/v12/bytecode_modules/SimpleMap.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/SnapshotUtil.mv b/release/v12/bytecode_modules/SnapshotUtil.mv deleted file mode 100644 index a119abe6..00000000 Binary files a/release/v12/bytecode_modules/SnapshotUtil.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/StakeToSBTPlugin.mv b/release/v12/bytecode_modules/StakeToSBTPlugin.mv deleted file mode 100644 index 86aa150d..00000000 Binary files a/release/v12/bytecode_modules/StakeToSBTPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/StarcoinDAO.mv b/release/v12/bytecode_modules/StarcoinDAO.mv deleted file mode 100644 index 0ebf0eb8..00000000 Binary files a/release/v12/bytecode_modules/StarcoinDAO.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/StarcoinVerifier.mv b/release/v12/bytecode_modules/StarcoinVerifier.mv deleted file mode 100644 index 2151161e..00000000 Binary files a/release/v12/bytecode_modules/StarcoinVerifier.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/StdlibUpgradeScripts.mv b/release/v12/bytecode_modules/StdlibUpgradeScripts.mv deleted file mode 100644 index 0a2553d4..00000000 Binary files a/release/v12/bytecode_modules/StdlibUpgradeScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/StructuredHash.mv b/release/v12/bytecode_modules/StructuredHash.mv deleted file mode 100644 index 5ff2d183..00000000 Binary files a/release/v12/bytecode_modules/StructuredHash.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Timestamp.mv b/release/v12/bytecode_modules/Timestamp.mv deleted file mode 100644 index 2e1d13a1..00000000 Binary files a/release/v12/bytecode_modules/Timestamp.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Token.mv b/release/v12/bytecode_modules/Token.mv deleted file mode 100644 index 57123b45..00000000 Binary files a/release/v12/bytecode_modules/Token.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TransactionFee.mv b/release/v12/bytecode_modules/TransactionFee.mv deleted file mode 100644 index 0e232147..00000000 Binary files a/release/v12/bytecode_modules/TransactionFee.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TransactionManager.mv b/release/v12/bytecode_modules/TransactionManager.mv deleted file mode 100644 index 7ba1dba8..00000000 Binary files a/release/v12/bytecode_modules/TransactionManager.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TransactionPublishOption.mv b/release/v12/bytecode_modules/TransactionPublishOption.mv deleted file mode 100644 index 751bca37..00000000 Binary files a/release/v12/bytecode_modules/TransactionPublishOption.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TransactionTimeout.mv b/release/v12/bytecode_modules/TransactionTimeout.mv deleted file mode 100644 index a7f1bea0..00000000 Binary files a/release/v12/bytecode_modules/TransactionTimeout.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TransactionTimeoutConfig.mv b/release/v12/bytecode_modules/TransactionTimeoutConfig.mv deleted file mode 100644 index 0a0b3890..00000000 Binary files a/release/v12/bytecode_modules/TransactionTimeoutConfig.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TransferScripts.mv b/release/v12/bytecode_modules/TransferScripts.mv deleted file mode 100644 index f6f727bf..00000000 Binary files a/release/v12/bytecode_modules/TransferScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Treasury.mv b/release/v12/bytecode_modules/Treasury.mv deleted file mode 100644 index 54ca3c47..00000000 Binary files a/release/v12/bytecode_modules/Treasury.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TreasuryPlugin.mv b/release/v12/bytecode_modules/TreasuryPlugin.mv deleted file mode 100644 index fa191ab6..00000000 Binary files a/release/v12/bytecode_modules/TreasuryPlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TreasuryScripts.mv b/release/v12/bytecode_modules/TreasuryScripts.mv deleted file mode 100644 index ac20feb9..00000000 Binary files a/release/v12/bytecode_modules/TreasuryScripts.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TreasuryWithdrawDaoProposal.mv b/release/v12/bytecode_modules/TreasuryWithdrawDaoProposal.mv deleted file mode 100644 index d5e8e732..00000000 Binary files a/release/v12/bytecode_modules/TreasuryWithdrawDaoProposal.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/TypeInfo.mv b/release/v12/bytecode_modules/TypeInfo.mv deleted file mode 100644 index 0b4492da..00000000 Binary files a/release/v12/bytecode_modules/TypeInfo.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/U256.mv b/release/v12/bytecode_modules/U256.mv deleted file mode 100644 index f93df531..00000000 Binary files a/release/v12/bytecode_modules/U256.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/UpgradeModuleDaoProposal.mv b/release/v12/bytecode_modules/UpgradeModuleDaoProposal.mv deleted file mode 100644 index a09eefb5..00000000 Binary files a/release/v12/bytecode_modules/UpgradeModuleDaoProposal.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/UpgradeModulePlugin.mv b/release/v12/bytecode_modules/UpgradeModulePlugin.mv deleted file mode 100644 index 27128983..00000000 Binary files a/release/v12/bytecode_modules/UpgradeModulePlugin.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/VMConfig.mv b/release/v12/bytecode_modules/VMConfig.mv deleted file mode 100644 index 8b923757..00000000 Binary files a/release/v12/bytecode_modules/VMConfig.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Vector.mv b/release/v12/bytecode_modules/Vector.mv deleted file mode 100644 index d8948865..00000000 Binary files a/release/v12/bytecode_modules/Vector.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/Version.mv b/release/v12/bytecode_modules/Version.mv deleted file mode 100644 index ad036a1c..00000000 Binary files a/release/v12/bytecode_modules/Version.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/YieldFarming.mv b/release/v12/bytecode_modules/YieldFarming.mv deleted file mode 100644 index 605da4c9..00000000 Binary files a/release/v12/bytecode_modules/YieldFarming.mv and /dev/null differ diff --git a/release/v12/bytecode_modules/YieldFarmingV2.mv b/release/v12/bytecode_modules/YieldFarmingV2.mv deleted file mode 100644 index 11f4cc65..00000000 Binary files a/release/v12/bytecode_modules/YieldFarmingV2.mv and /dev/null differ diff --git a/release/v12/docs/ASCII.md b/release/v12/docs/ASCII.md deleted file mode 100644 index 25479a52..00000000 --- a/release/v12/docs/ASCII.md +++ /dev/null @@ -1,478 +0,0 @@ - - - -# Module `0x1::ASCII` - - - -- [Struct `String`](#0x1_ASCII_String) -- [Struct `Char`](#0x1_ASCII_Char) -- [Constants](#@Constants_0) -- [Function `char`](#0x1_ASCII_char) -- [Function `string`](#0x1_ASCII_string) -- [Function `try_string`](#0x1_ASCII_try_string) -- [Function `all_characters_printable`](#0x1_ASCII_all_characters_printable) -- [Function `push_char`](#0x1_ASCII_push_char) -- [Function `pop_char`](#0x1_ASCII_pop_char) -- [Function `length`](#0x1_ASCII_length) -- [Function `as_bytes`](#0x1_ASCII_as_bytes) -- [Function `into_bytes`](#0x1_ASCII_into_bytes) -- [Function `byte`](#0x1_ASCII_byte) -- [Function `is_valid_char`](#0x1_ASCII_is_valid_char) -- [Function `is_printable_char`](#0x1_ASCII_is_printable_char) -- [Function `split_by_char`](#0x1_ASCII_split_by_char) - - -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `String` - -The String struct holds a vector of bytes that all represent -valid ASCII characters. Note that these ASCII characters may not all -be printable. To determine if a String contains only "printable" -characters you should use the all_characters_printable predicate -defined in this module. - - -
struct String has copy, drop, store
-
- - - -
-Fields - - -
-
-bytes: vector<u8> -
-
- -
-
- - -
- - - -## Struct `Char` - -An ASCII character. - - -
struct Char has copy, drop, store
-
- - - -
-Fields - - -
-
-byte: u8 -
-
- -
-
- - -
- - - -## Constants - - - - -An invalid ASCII character was encountered when creating an ASCII string. - - -
const EINVALID_ASCII_CHARACTER: u64 = 101;
-
- - - - - -## Function `char` - -Convert a byte into a Char that is checked to make sure it is valid ASCII. - - -
public fun char(byte: u8): ASCII::Char
-
- - - -
-Implementation - - -
public fun char(byte: u8): Char {
-    assert!(is_valid_char(byte), Errors::invalid_argument(EINVALID_ASCII_CHARACTER));
-    Char { byte }
-}
-
- - - -
- - - -## Function `string` - -Convert a vector of bytes bytes into an String. Aborts if -bytes contains non-ASCII characters. - - -
public fun string(bytes: vector<u8>): ASCII::String
-
- - - -
-Implementation - - -
public fun string(bytes: vector<u8>): String {
-    let x = try_string(bytes);
-    assert!(
-        Option::is_some(&x),
-        Errors::invalid_argument(EINVALID_ASCII_CHARACTER)
-    );
-    Option::destroy_some(x)
-}
-
- - - -
- - - -## Function `try_string` - -Convert a vector of bytes bytes into an String. Returns -Some(<ascii_string>) if the bytes contains all valid ASCII -characters. Otherwise returns None. - - -
public fun try_string(bytes: vector<u8>): Option::Option<ASCII::String>
-
- - - -
-Implementation - - -
public fun try_string(bytes: vector<u8>): Option<String> {
-    let len = Vector::length(&bytes);
-    let i = 0;
-    while (  i < len ) {
-        let possible_byte = *Vector::borrow(&bytes, i);
-        if (!is_valid_char(possible_byte)) return Option::none();
-        i = i + 1;
-    };
-    Option::some(String { bytes })
-}
-
- - - -
- - - -## Function `all_characters_printable` - -Returns true if all characters in string are printable characters -Returns false otherwise. Not all Strings are printable strings. - - -
public fun all_characters_printable(string: &ASCII::String): bool
-
- - - -
-Implementation - - -
public fun all_characters_printable(string: &String): bool {
-    let len = Vector::length(&string.bytes);
-    let i = 0;
-    while ( i < len ) {
-        let byte = *Vector::borrow(&string.bytes, i);
-        if (!is_printable_char(byte)) return false;
-        i = i + 1;
-    };
-    true
-}
-
- - - -
- - - -## Function `push_char` - - - -
public fun push_char(string: &mut ASCII::String, char: ASCII::Char)
-
- - - -
-Implementation - - -
public fun push_char(string: &mut String, char: Char) {
-    Vector::push_back(&mut string.bytes, char.byte);
-}
-
- - - -
- - - -## Function `pop_char` - - - -
public fun pop_char(string: &mut ASCII::String): ASCII::Char
-
- - - -
-Implementation - - -
public fun pop_char(string: &mut String): Char {
-    Char { byte: Vector::pop_back(&mut string.bytes) }
-}
-
- - - -
- - - -## Function `length` - - - -
public fun length(string: &ASCII::String): u64
-
- - - -
-Implementation - - -
public fun length(string: &String): u64 {
-    Vector::length(as_bytes(string))
-}
-
- - - -
- - - -## Function `as_bytes` - -Get the inner bytes of the string as a reference - - -
public fun as_bytes(string: &ASCII::String): &vector<u8>
-
- - - -
-Implementation - - -
public fun as_bytes(string: &String): &vector<u8> {
-    &string.bytes
-}
-
- - - -
- - - -## Function `into_bytes` - -Unpack the string to get its backing bytes - - -
public fun into_bytes(string: ASCII::String): vector<u8>
-
- - - -
-Implementation - - -
public fun into_bytes(string: String): vector<u8> {
-    let String { bytes } = string;
-    bytes
-}
-
- - - -
- - - -## Function `byte` - -Unpack the char into its underlying byte. - - -
public fun byte(char: ASCII::Char): u8
-
- - - -
-Implementation - - -
public fun byte(char: Char): u8 {
-    let Char { byte } = char;
-    byte
-}
-
- - - -
- - - -## Function `is_valid_char` - -Returns true if byte is a valid ASCII character. Returns false otherwise. - - -
public fun is_valid_char(byte: u8): bool
-
- - - -
-Implementation - - -
public fun is_valid_char(byte: u8): bool {
-    byte <= 0x7F
-}
-
- - - -
- - - -## Function `is_printable_char` - -Returns true if byte is an printable ASCII character. Returns false otherwise. - - -
public fun is_printable_char(byte: u8): bool
-
- - - -
-Implementation - - -
public fun is_printable_char(byte: u8): bool {
-    byte >= 0x20 && // Disallow metacharacters
-    byte <= 0x7E // Don't allow DEL metacharacter
-}
-
- - - -
- - - -## Function `split_by_char` - -split string by char. Returns vector - - -
public fun split_by_char(string: ASCII::String, char: ASCII::Char): vector<ASCII::String>
-
- - - -
-Implementation - - -
public fun split_by_char(string: String, char: Char): vector<String> {
-    let result = Vector::empty<String>();
-    let len = length(&string);
-    let i = 0;
-    let buffer = Vector::empty<u8>();
-    while ( i < len ) {
-        let byte = *Vector::borrow(&string.bytes, i);
-        if (byte != char.byte) {
-            Vector::push_back(&mut buffer, byte);
-        } else {
-            Vector::push_back(&mut result, string(buffer));
-            buffer = Vector::empty<u8>();
-            if (i != 0 && i == len - 1) {
-                // special
-                Vector::push_back(&mut result, string(copy buffer));
-            };
-        };
-
-        i = i + 1;
-    };
-
-    if (len == 0 || Vector::length(&buffer) != 0) {
-        Vector::push_back(&mut result, string(buffer));
-    };
-    result
-}
-
- - - -
diff --git a/release/v12/docs/Account.md b/release/v12/docs/Account.md deleted file mode 100644 index 50885860..00000000 --- a/release/v12/docs/Account.md +++ /dev/null @@ -1,3637 +0,0 @@ - - - -# Module `0x1::Account` - -The module for the account resource that governs every account - - -- [Resource `Account`](#0x1_Account_Account) -- [Resource `Balance`](#0x1_Account_Balance) -- [Struct `WithdrawCapability`](#0x1_Account_WithdrawCapability) -- [Struct `KeyRotationCapability`](#0x1_Account_KeyRotationCapability) -- [Struct `WithdrawEvent`](#0x1_Account_WithdrawEvent) -- [Struct `DepositEvent`](#0x1_Account_DepositEvent) -- [Struct `AcceptTokenEvent`](#0x1_Account_AcceptTokenEvent) -- [Resource `SignerDelegated`](#0x1_Account_SignerDelegated) -- [Struct `SignerCapability`](#0x1_Account_SignerCapability) -- [Resource `AutoAcceptToken`](#0x1_Account_AutoAcceptToken) -- [Struct `RotateAuthKeyEvent`](#0x1_Account_RotateAuthKeyEvent) -- [Struct `ExtractWithdrawCapEvent`](#0x1_Account_ExtractWithdrawCapEvent) -- [Struct `SignerDelegateEvent`](#0x1_Account_SignerDelegateEvent) -- [Resource `EventStore`](#0x1_Account_EventStore) -- [Constants](#@Constants_0) -- [Function `remove_signer_capability`](#0x1_Account_remove_signer_capability) -- [Function `get_genesis_capability`](#0x1_Account_get_genesis_capability) -- [Function `create_signer_with_cap`](#0x1_Account_create_signer_with_cap) -- [Function `destroy_signer_cap`](#0x1_Account_destroy_signer_cap) -- [Function `signer_address`](#0x1_Account_signer_address) -- [Function `is_signer_delegated`](#0x1_Account_is_signer_delegated) -- [Function `create_genesis_account`](#0x1_Account_create_genesis_account) -- [Function `release_genesis_signer`](#0x1_Account_release_genesis_signer) -- [Function `create_account`](#0x1_Account_create_account) -- [Function `create_account_with_address`](#0x1_Account_create_account_with_address) -- [Function `make_account`](#0x1_Account_make_account) -- [Function `create_signer`](#0x1_Account_create_signer) -- [Function `create_account_with_initial_amount`](#0x1_Account_create_account_with_initial_amount) -- [Function `create_account_with_initial_amount_v2`](#0x1_Account_create_account_with_initial_amount_v2) -- [Function `create_account_with_initial_amount_entry`](#0x1_Account_create_account_with_initial_amount_entry) -- [Function `create_delegate_account`](#0x1_Account_create_delegate_account) -- [Function `generate_fresh_address`](#0x1_Account_generate_fresh_address) -- [Function `deposit_to_self`](#0x1_Account_deposit_to_self) -- [Function `deposit`](#0x1_Account_deposit) -- [Function `deposit_with_metadata`](#0x1_Account_deposit_with_metadata) -- [Function `deposit_to_balance`](#0x1_Account_deposit_to_balance) -- [Function `withdraw_from_balance`](#0x1_Account_withdraw_from_balance) -- [Function `withdraw`](#0x1_Account_withdraw) -- [Function `withdraw_with_metadata`](#0x1_Account_withdraw_with_metadata) -- [Function `withdraw_with_capability`](#0x1_Account_withdraw_with_capability) -- [Function `withdraw_with_capability_and_metadata`](#0x1_Account_withdraw_with_capability_and_metadata) -- [Function `extract_withdraw_capability`](#0x1_Account_extract_withdraw_capability) -- [Function `restore_withdraw_capability`](#0x1_Account_restore_withdraw_capability) -- [Function `emit_account_withdraw_event`](#0x1_Account_emit_account_withdraw_event) -- [Function `emit_account_deposit_event`](#0x1_Account_emit_account_deposit_event) -- [Function `pay_from_capability`](#0x1_Account_pay_from_capability) -- [Function `pay_from_with_metadata`](#0x1_Account_pay_from_with_metadata) -- [Function `pay_from`](#0x1_Account_pay_from) -- [Function `rotate_authentication_key_with_capability`](#0x1_Account_rotate_authentication_key_with_capability) -- [Function `extract_key_rotation_capability`](#0x1_Account_extract_key_rotation_capability) -- [Function `restore_key_rotation_capability`](#0x1_Account_restore_key_rotation_capability) -- [Function `destroy_key_rotation_capability`](#0x1_Account_destroy_key_rotation_capability) -- [Function `rotate_authentication_key`](#0x1_Account_rotate_authentication_key) -- [Function `rotate_authentication_key_entry`](#0x1_Account_rotate_authentication_key_entry) -- [Function `do_rotate_authentication_key`](#0x1_Account_do_rotate_authentication_key) -- [Function `balance_for`](#0x1_Account_balance_for) -- [Function `balance`](#0x1_Account_balance) -- [Function `do_accept_token`](#0x1_Account_do_accept_token) -- [Function `accept_token`](#0x1_Account_accept_token) -- [Function `accept_token_entry`](#0x1_Account_accept_token_entry) -- [Function `is_accepts_token`](#0x1_Account_is_accepts_token) -- [Function `is_accept_token`](#0x1_Account_is_accept_token) -- [Function `can_auto_accept_token`](#0x1_Account_can_auto_accept_token) -- [Function `set_auto_accept_token_entry`](#0x1_Account_set_auto_accept_token_entry) -- [Function `set_auto_accept_token`](#0x1_Account_set_auto_accept_token) -- [Function `try_accept_token`](#0x1_Account_try_accept_token) -- [Function `sequence_number_for_account`](#0x1_Account_sequence_number_for_account) -- [Function `sequence_number`](#0x1_Account_sequence_number) -- [Function `authentication_key`](#0x1_Account_authentication_key) -- [Function `delegated_key_rotation_capability`](#0x1_Account_delegated_key_rotation_capability) -- [Function `delegated_withdraw_capability`](#0x1_Account_delegated_withdraw_capability) -- [Function `withdraw_capability_address`](#0x1_Account_withdraw_capability_address) -- [Function `key_rotation_capability_address`](#0x1_Account_key_rotation_capability_address) -- [Function `exists_at`](#0x1_Account_exists_at) -- [Function `is_dummy_auth_key`](#0x1_Account_is_dummy_auth_key) -- [Function `txn_prologue`](#0x1_Account_txn_prologue) -- [Function `txn_prologue_v2`](#0x1_Account_txn_prologue_v2) -- [Function `txn_epilogue`](#0x1_Account_txn_epilogue) -- [Function `transaction_fee_simulate`](#0x1_Account_transaction_fee_simulate) -- [Function `txn_epilogue_v2`](#0x1_Account_txn_epilogue_v2) -- [Function `txn_epilogue_v3`](#0x1_Account_txn_epilogue_v3) -- [Function `remove_zero_balance_entry`](#0x1_Account_remove_zero_balance_entry) -- [Function `remove_zero_balance`](#0x1_Account_remove_zero_balance) -- [Function `make_event_store_if_not_exist`](#0x1_Account_make_event_store_if_not_exist) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Authenticator;
-use 0x1::BCS;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Hash;
-use 0x1::Math;
-use 0x1::Option;
-use 0x1::STC;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::TransactionFee;
-use 0x1::Vector;
-
- - - - - -## Resource `Account` - -Every account has a Account::Account resource - - -
struct Account has key
-
- - - -
-Fields - - -
-
-authentication_key: vector<u8> -
-
- The current authentication key. - This can be different than the key used to create the account -
-
-withdrawal_capability: Option::Option<Account::WithdrawCapability> -
-
- A withdrawal_capability allows whoever holds this capability - to withdraw from the account. At the time of account creation - this capability is stored in this option. It can later be - "extracted" from this field via extract_withdraw_capability, - and can also be restored via restore_withdraw_capability. -
-
-key_rotation_capability: Option::Option<Account::KeyRotationCapability> -
-
- A key_rotation_capability allows whoever holds this capability - the ability to rotate the authentication key for the account. At - the time of account creation this capability is stored in this - option. It can later be "extracted" from this field via - extract_key_rotation_capability, and can also be restored via - restore_key_rotation_capability. -
-
-withdraw_events: Event::EventHandle<Account::WithdrawEvent> -
-
- event handle for account balance withdraw event -
-
-deposit_events: Event::EventHandle<Account::DepositEvent> -
-
- event handle for account balance deposit event -
-
-accept_token_events: Event::EventHandle<Account::AcceptTokenEvent> -
-
- Event handle for accept_token event -
-
-sequence_number: u64 -
-
- The current sequence number. - Incremented by one each time a transaction is submitted -
-
- - -
- - - -## Resource `Balance` - -A resource that holds the tokens stored in this account - - -
struct Balance<TokenType> has key
-
- - - -
-Fields - - -
-
-token: Token::Token<TokenType> -
-
- -
-
- - -
- - - -## Struct `WithdrawCapability` - -The holder of WithdrawCapability for account_address can withdraw Token from -account_address/Account::Account/balance. -There is at most one WithdrawCapability in existence for a given address. - - -
struct WithdrawCapability has store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
- - -
- - - -## Struct `KeyRotationCapability` - -The holder of KeyRotationCapability for account_address can rotate the authentication key for -account_address (i.e., write to account_address/Account::Account/authentication_key). -There is at most one KeyRotationCapability in existence for a given address. - - -
struct KeyRotationCapability has store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
- - -
- - - -## Struct `WithdrawEvent` - -Message for balance withdraw event. - - -
struct WithdrawEvent has drop, store
-
- - - -
-Fields - - -
-
-amount: u128 -
-
- The amount of Token sent -
-
-token_code: Token::TokenCode -
-
- The code symbol for the token that was sent -
-
-metadata: vector<u8> -
-
- Metadata associated with the withdraw -
-
- - -
- - - -## Struct `DepositEvent` - -Message for balance deposit event. - - -
struct DepositEvent has drop, store
-
- - - -
-Fields - - -
-
-amount: u128 -
-
- The amount of Token sent -
-
-token_code: Token::TokenCode -
-
- The code symbol for the token that was sent -
-
-metadata: vector<u8> -
-
- Metadata associated with the deposit -
-
- - -
- - - -## Struct `AcceptTokenEvent` - -Message for accept token events - - -
struct AcceptTokenEvent has drop, store
-
- - - -
-Fields - - -
-
-token_code: Token::TokenCode -
-
- -
-
- - -
- - - -## Resource `SignerDelegated` - - - -
struct SignerDelegated has key
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `SignerCapability` - - - -
struct SignerCapability has store
-
- - - -
-Fields - - -
-
-addr: address -
-
- -
-
- - -
- - - -## Resource `AutoAcceptToken` - - - -
struct AutoAcceptToken has key
-
- - - -
-Fields - - -
-
-enable: bool -
-
- -
-
- - -
- - - -## Struct `RotateAuthKeyEvent` - -Message for rotate_authentication_key events - - -
struct RotateAuthKeyEvent has drop, store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
-new_auth_key: vector<u8> -
-
- -
-
- - -
- - - -## Struct `ExtractWithdrawCapEvent` - -Message for extract_withdraw_capability events - - -
struct ExtractWithdrawCapEvent has drop, store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
- - -
- - - -## Struct `SignerDelegateEvent` - -Message for SignerDelegate events - - -
struct SignerDelegateEvent has drop, store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
- - -
- - - -## Resource `EventStore` - - - -
struct EventStore has key
-
- - - -
-Fields - - -
-
-rotate_auth_key_events: Event::EventHandle<Account::RotateAuthKeyEvent> -
-
- Event handle for rotate_authentication_key event -
-
-extract_withdraw_cap_events: Event::EventHandle<Account::ExtractWithdrawCapEvent> -
-
- Event handle for extract_withdraw_capability event -
-
-signer_delegate_events: Event::EventHandle<Account::SignerDelegateEvent> -
-
- Event handle for signer delegated event -
-
- - -
- - - -## Constants - - - - - - -
const MAX_U64: u128 = 18446744073709551615;
-
- - - - - - - -
const EDEPRECATED_FUNCTION: u64 = 19;
-
- - - - - -The address bytes length - - -
const ADDRESS_LENGTH: u64 = 16;
-
- - - - - - - -
const CONTRACT_ACCOUNT_AUTH_KEY_PLACEHOLDER: vector<u8> = [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];
-
- - - - - - - -
const DUMMY_AUTH_KEY: vector<u8> = [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, 0];
-
- - - - - - - -
const EADDRESS_AND_AUTH_KEY_MISMATCH: u64 = 105;
-
- - - - - - - -
const EADDRESS_PUBLIC_KEY_INCONSISTENT: u64 = 104;
-
- - - - - - - -
const EBAD_TRANSACTION_FEE_TOKEN: u64 = 18;
-
- - - - - - - -
const ECOIN_DEPOSIT_IS_ZERO: u64 = 15;
-
- - - - - - - -
const EINSUFFICIENT_BALANCE: u64 = 10;
-
- - - - - - - -
const EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED: u64 = 103;
-
- - - - - - - -
const EMALFORMED_AUTHENTICATION_KEY: u64 = 102;
-
- - - - - - - -
const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0;
-
- - - - - - - -
const EPROLOGUE_CANT_PAY_GAS_DEPOSIT: u64 = 4;
-
- - - - - - - -
const EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY: u64 = 1;
-
- - - - - - - -
const EPROLOGUE_SEQUENCE_NUMBER_TOO_BIG: u64 = 9;
-
- - - - - - - -
const EPROLOGUE_SEQUENCE_NUMBER_TOO_NEW: u64 = 3;
-
- - - - - - - -
const EPROLOGUE_SEQUENCE_NUMBER_TOO_OLD: u64 = 2;
-
- - - - - - - -
const EPROLOGUE_SIGNER_ALREADY_DELEGATED: u64 = 200;
-
- - - - - - - -
const ERR_SIGNER_ALREADY_DELEGATED: u64 = 107;
-
- - - - - - - -
const ERR_TOKEN_NOT_ACCEPT: u64 = 106;
-
- - - - - - - -
const EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED: u64 = 101;
-
- - - - - -## Function `remove_signer_capability` - -A one-way action, once SignerCapability is removed from signer, the address cannot send txns anymore. -This function can only called once by signer. - - -
public fun remove_signer_capability(signer: &signer): Account::SignerCapability
-
- - - -
-Implementation - - -
public fun remove_signer_capability(signer: &signer): SignerCapability
-acquires Account, EventStore {
-    let signer_addr = Signer::address_of(signer);
-    assert!(!is_signer_delegated(signer_addr), Errors::invalid_state(ERR_SIGNER_ALREADY_DELEGATED));
-
-    // set to account auth key to noop.
-    {
-        let key_rotation_capability = extract_key_rotation_capability(signer);
-        rotate_authentication_key_with_capability(&key_rotation_capability, CONTRACT_ACCOUNT_AUTH_KEY_PLACEHOLDER);
-        destroy_key_rotation_capability(key_rotation_capability);
-        move_to(signer, SignerDelegated {});
-
-        make_event_store_if_not_exist(signer);
-        let event_store = borrow_global_mut<EventStore>(signer_addr);
-        Event::emit_event<SignerDelegateEvent>(
-            &mut event_store.signer_delegate_events,
-            SignerDelegateEvent {
-                account_address: signer_addr
-            }
-        );
-    };
-
-    let signer_cap = SignerCapability {addr: signer_addr };
-    signer_cap
-}
-
- - - -
- - - -## Function `get_genesis_capability` - - - -
public(friend) fun get_genesis_capability(): Account::SignerCapability
-
- - - -
-Implementation - - -
public (friend) fun get_genesis_capability():SignerCapability{
-    let signer_cap = SignerCapability {addr: Token::token_address<STC>() };
-    signer_cap
-}
-
- - - -
- - - -## Function `create_signer_with_cap` - - - -
public fun create_signer_with_cap(cap: &Account::SignerCapability): signer
-
- - - -
-Implementation - - -
public fun create_signer_with_cap(cap: &SignerCapability): signer {
-    create_signer(cap.addr)
-}
-
- - - -
- - - -## Function `destroy_signer_cap` - - - -
public fun destroy_signer_cap(cap: Account::SignerCapability)
-
- - - -
-Implementation - - -
public fun destroy_signer_cap(cap: SignerCapability) {
-    let SignerCapability {addr: _} = cap;
-}
-
- - - -
- - - -## Function `signer_address` - - - -
public fun signer_address(cap: &Account::SignerCapability): address
-
- - - -
-Implementation - - -
public fun signer_address(cap: &SignerCapability): address {
-    cap.addr
-}
-
- - - -
- - - -## Function `is_signer_delegated` - - - -
public fun is_signer_delegated(addr: address): bool
-
- - - -
-Implementation - - -
public fun is_signer_delegated(addr: address): bool {
-    exists<SignerDelegated>(addr)
-}
-
- - - -
- - - -## Function `create_genesis_account` - -Create an genesis account at new_account_address and return signer. -Genesis authentication_key is zero bytes. - - -
public fun create_genesis_account(new_account_address: address): signer
-
- - - -
-Implementation - - -
public fun create_genesis_account(
-    new_account_address: address,
-) :signer {
-    Timestamp::assert_genesis();
-    let new_account = create_signer(new_account_address);
-    make_account(&new_account, DUMMY_AUTH_KEY);
-    new_account
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if len(DUMMY_AUTH_KEY) != 32;
-aborts_if exists<Account>(new_account_address);
-
- - - -
- - - -## Function `release_genesis_signer` - -Release genesis account signer - - -
public fun release_genesis_signer(_genesis_account: signer)
-
- - - -
-Implementation - - -
public fun release_genesis_signer(_genesis_account: signer){
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `create_account` - -Deprecated since @v5 - - -
public fun create_account<TokenType: store>(_authentication_key: vector<u8>): address
-
- - - -
-Implementation - - -
public fun create_account<TokenType: store>(_authentication_key: vector<u8>): address {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- -
-Specification - - - -
aborts_if true;
-
- - - -
- - - -## Function `create_account_with_address` - -Creates a new account at fresh_address with a balance of zero and empty auth key, the address as init auth key for check transaction. -Creating an account at address StarcoinFramework will cause runtime failure as it is a -reserved address for the MoveVM. - - -
public fun create_account_with_address<TokenType: store>(fresh_address: address)
-
- - - -
-Implementation - - -
public fun create_account_with_address<TokenType: store>(fresh_address: address) acquires Account {
-    let new_account = create_signer(fresh_address);
-    make_account(&new_account, DUMMY_AUTH_KEY);
-    // Make sure all account accept STC.
-    if (!STC::is_stc<TokenType>()){
-        do_accept_token<STC>(&new_account);
-    };
-    do_accept_token<TokenType>(&new_account);
-}
-
- - - -
- -
-Specification - - - -
aborts_if exists<Account>(fresh_address);
-aborts_if Token::spec_token_code<TokenType>() != Token::spec_token_code<STC>() && exists<Balance<STC>>(fresh_address);
-aborts_if exists<Balance<TokenType>>(fresh_address);
-ensures exists_at(fresh_address);
-ensures exists<Balance<TokenType>>(fresh_address);
-
- - - -
- - - -## Function `make_account` - - - -
fun make_account(new_account: &signer, authentication_key: vector<u8>)
-
- - - -
-Implementation - - -
fun make_account(
-    new_account: &signer,
-    authentication_key: vector<u8>,
-) {
-    assert!(Vector::length(&authentication_key) == 32, Errors::invalid_argument(EMALFORMED_AUTHENTICATION_KEY));
-    let new_account_addr = Signer::address_of(new_account);
-    Event::publish_generator(new_account);
-    move_to(new_account, Account {
-          authentication_key,
-          withdrawal_capability: Option::some(
-              WithdrawCapability {
-                  account_address: new_account_addr
-          }),
-          key_rotation_capability: Option::some(
-              KeyRotationCapability {
-                  account_address: new_account_addr
-          }),
-          withdraw_events: Event::new_event_handle<WithdrawEvent>(new_account),
-          deposit_events: Event::new_event_handle<DepositEvent>(new_account),
-          accept_token_events: Event::new_event_handle<AcceptTokenEvent>(new_account),
-          sequence_number: 0,
-    });
-    move_to(new_account, AutoAcceptToken{enable: true});
-    move_to(new_account, EventStore {
-          rotate_auth_key_events: Event::new_event_handle<RotateAuthKeyEvent>(new_account),
-          extract_withdraw_cap_events: Event::new_event_handle<ExtractWithdrawCapEvent>(new_account),
-          signer_delegate_events: Event::new_event_handle<SignerDelegateEvent>(new_account),
-    });
-}
-
- - - -
- -
-Specification - - - -
aborts_if len(authentication_key) != 32;
-aborts_if exists<Account>(Signer::address_of(new_account));
-aborts_if exists<AutoAcceptToken>(Signer::address_of(new_account));
-ensures exists_at(Signer::address_of(new_account));
-
- - - -
- - - -## Function `create_signer` - - - -
fun create_signer(addr: address): signer
-
- - - -
-Implementation - - -
native fun create_signer(addr: address): signer;
-
- - - -
- - - -## Function `create_account_with_initial_amount` - - - -
public(script) fun create_account_with_initial_amount<TokenType: store>(account: signer, fresh_address: address, _auth_key: vector<u8>, initial_amount: u128)
-
- - - -
-Implementation - - -
public(script) fun create_account_with_initial_amount<TokenType: store>(account: signer, fresh_address: address, _auth_key: vector<u8>, initial_amount: u128)
-acquires Account, Balance, AutoAcceptToken {
-    create_account_with_initial_amount_entry<TokenType>(account, fresh_address, initial_amount);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `create_account_with_initial_amount_v2` - - - -
public(script) fun create_account_with_initial_amount_v2<TokenType: store>(account: signer, fresh_address: address, initial_amount: u128)
-
- - - -
-Implementation - - -
public(script) fun create_account_with_initial_amount_v2<TokenType: store>(account: signer, fresh_address: address, initial_amount: u128)
-acquires Account, Balance, AutoAcceptToken {
-    create_account_with_initial_amount_entry<TokenType>(account, fresh_address, initial_amount);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `create_account_with_initial_amount_entry` - - - -
public(script) fun create_account_with_initial_amount_entry<TokenType: store>(account: signer, fresh_address: address, initial_amount: u128)
-
- - - -
-Implementation - - -
public(script) fun create_account_with_initial_amount_entry<TokenType: store>(account: signer, fresh_address: address, initial_amount: u128)
-acquires Account, Balance, AutoAcceptToken {
-    create_account_with_address<TokenType>(fresh_address);
-    if (initial_amount > 0) {
-        pay_from<TokenType>(&account, fresh_address, initial_amount);
-    };
-}
-
- - - -
- - - -## Function `create_delegate_account` - -Generate an new address and create a new account, then delegate the account and return the new account address and SignerCapability - - -
public fun create_delegate_account(sender: &signer): (address, Account::SignerCapability)
-
- - - -
-Implementation - - -
public fun create_delegate_account(sender: &signer) : (address, SignerCapability) acquires Balance, Account, EventStore {
-    let new_address = generate_fresh_address(sender);
-    Self::create_account_with_address<STC>(new_address);
-    let new_signer = Self::create_signer(new_address);
-    (new_address, Self::remove_signer_capability(&new_signer))
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `generate_fresh_address` - -Generate a fresh address from the sender address and the sender's sequence number, and ensure the generated address is not exists onchain. - - -
public fun generate_fresh_address(sender: &signer): address
-
- - - -
-Implementation - - -
public fun generate_fresh_address(sender: &signer) : address acquires Balance, Account {
-    let try_times = 0u64;
-    while(true){
-        let sender_address = Signer::address_of(sender);
-        let sequence_number = Self::sequence_number(sender_address);
-        // use stc balance as part of seed, just for new address more random.
-        let stc_balance = Self::balance<STC>(sender_address);
-
-        let seed_bytes = BCS::to_bytes(&sender_address);
-        Vector::append(&mut seed_bytes, BCS::to_bytes(&sequence_number));
-        Vector::append(&mut seed_bytes, BCS::to_bytes(&stc_balance));
-        Vector::append(&mut seed_bytes, BCS::to_bytes(&try_times));
-
-        let seed_hash = Hash::sha3_256(seed_bytes);
-
-        let i = 0;
-        let address_bytes = Vector::empty();
-        while (i < ADDRESS_LENGTH) {
-            Vector::push_back(&mut address_bytes, *Vector::borrow(&seed_hash,i));
-            i = i + 1;
-        };
-        let new_address = BCS::to_address(address_bytes);
-        if (Self::exists_at(new_address)){
-            try_times = try_times + 1;
-            continue
-        }else{
-            return new_address
-        }
-    };
-    //unreachable
-    abort 0
-}
-
- - - -
- - - -## Function `deposit_to_self` - -Deposits the to_deposit token into the self's account balance - - -
public fun deposit_to_self<TokenType: store>(account: &signer, to_deposit: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun deposit_to_self<TokenType: store>(account: &signer, to_deposit: Token<TokenType>)
-acquires Account, Balance, AutoAcceptToken {
-    let account_address = Signer::address_of(account);
-    if (!is_accepts_token<TokenType>(account_address)){
-        do_accept_token<TokenType>(account);
-    };
-    deposit(account_address, to_deposit);
-}
-
- - - -
- -
-Specification - - - -
aborts_if to_deposit.value == 0;
-let is_accepts_token = exists<Balance<TokenType>>(Signer::address_of(account));
-aborts_if is_accepts_token && global<Balance<TokenType>>(Signer::address_of(account)).token.value + to_deposit.value > max_u128();
-aborts_if !exists<Account>(Signer::address_of(account));
-ensures exists<Balance<TokenType>>(Signer::address_of(account));
-
- - - -
- - - -## Function `deposit` - -Deposits the to_deposit token into the receiver's account balance with the no metadata -It's a reverse operation of withdraw. - - -
public fun deposit<TokenType: store>(receiver: address, to_deposit: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun deposit<TokenType: store>(
-    receiver: address,
-    to_deposit: Token<TokenType>,
-) acquires Account, Balance, AutoAcceptToken {
-    deposit_with_metadata<TokenType>(receiver, to_deposit, x"")
-}
-
- - - -
- -
-Specification - - - -
include DepositWithMetadataAbortsIf<TokenType>;
-
- - - -
- - - -## Function `deposit_with_metadata` - -Deposits the to_deposit token into the receiver's account balance with the attached metadata -It's a reverse operation of withdraw_with_metadata. - - -
public fun deposit_with_metadata<TokenType: store>(receiver: address, to_deposit: Token::Token<TokenType>, metadata: vector<u8>)
-
- - - -
-Implementation - - -
public fun deposit_with_metadata<TokenType: store>(
-    receiver: address,
-    to_deposit: Token<TokenType>,
-    metadata: vector<u8>,
-) acquires Account, Balance, AutoAcceptToken {
-
-    if (!exists_at(receiver)) {
-        create_account_with_address<TokenType>(receiver);
-    };
-
-    try_accept_token<TokenType>(receiver);
-
-    let deposit_value = Token::value(&to_deposit);
-    if (deposit_value > 0u128) {
-        // Deposit the `to_deposit` token
-        deposit_to_balance<TokenType>(borrow_global_mut<Balance<TokenType>>(receiver), to_deposit);
-
-        // emit deposit event
-        emit_account_deposit_event<TokenType>(receiver, deposit_value, metadata);
-    } else {
-        Token::destroy_zero(to_deposit);
-    };
-}
-
- - - -
- -
-Specification - - - -
include DepositWithMetadataAbortsIf<TokenType>;
-ensures exists<Balance<TokenType>>(receiver);
-ensures old(global<Balance<TokenType>>(receiver)).token.value + to_deposit.value == global<Balance<TokenType>>(receiver).token.value;
-
- - - - - - - -
schema DepositWithMetadataAbortsIf<TokenType> {
-    receiver: address;
-    to_deposit: Token<TokenType>;
-    aborts_if to_deposit.value == 0;
-    aborts_if !exists<Account>(receiver);
-    aborts_if !exists<Balance<TokenType>>(receiver);
-    aborts_if global<Balance<TokenType>>(receiver).token.value + to_deposit.value > max_u128();
-}
-
- - - -
- - - -## Function `deposit_to_balance` - -Helper to deposit amount to the given account balance - - -
fun deposit_to_balance<TokenType: store>(balance: &mut Account::Balance<TokenType>, token: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
fun deposit_to_balance<TokenType: store>(balance: &mut Balance<TokenType>, token: Token::Token<TokenType>) {
-    Token::deposit(&mut balance.token, token)
-}
-
- - - -
- -
-Specification - - - -
aborts_if balance.token.value + token.value > MAX_U128;
-
- - - -
- - - -## Function `withdraw_from_balance` - -Helper to withdraw amount from the given account balance and return the withdrawn Token - - -
fun withdraw_from_balance<TokenType: store>(balance: &mut Account::Balance<TokenType>, amount: u128): Token::Token<TokenType>
-
- - - -
-Implementation - - -
fun withdraw_from_balance<TokenType: store>(balance: &mut Balance<TokenType>, amount: u128): Token<TokenType>{
-    Token::withdraw(&mut balance.token, amount)
-}
-
- - - -
- -
-Specification - - - -
aborts_if balance.token.value < amount;
-
- - - -
- - - -## Function `withdraw` - -Withdraw amount Token from the account balance - - -
public fun withdraw<TokenType: store>(account: &signer, amount: u128): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun withdraw<TokenType: store>(account: &signer, amount: u128): Token<TokenType>
-acquires Account, Balance {
-    withdraw_with_metadata<TokenType>(account, amount, x"")
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Balance<TokenType>>(Signer::address_of(account));
-aborts_if !exists<Account>(Signer::address_of(account));
-aborts_if global<Balance<TokenType>>(Signer::address_of(account)).token.value < amount;
-aborts_if Option::is_none(global<Account>(Signer::address_of(account)).withdrawal_capability);
-
- - - -
- - - -## Function `withdraw_with_metadata` - -Withdraw amount tokens from signer with given metadata. - - -
public fun withdraw_with_metadata<TokenType: store>(account: &signer, amount: u128, metadata: vector<u8>): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun withdraw_with_metadata<TokenType: store>(account: &signer, amount: u128, metadata: vector<u8>): Token<TokenType>
-acquires Account, Balance {
-    let sender_addr = Signer::address_of(account);
-    let sender_balance = borrow_global_mut<Balance<TokenType>>(sender_addr);
-    // The sender_addr has delegated the privilege to withdraw from her account elsewhere--abort.
-    assert!(!delegated_withdraw_capability(sender_addr), Errors::invalid_state(EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED));
-    if (amount == 0){
-        return Token::zero()
-    };
-    emit_account_withdraw_event<TokenType>(sender_addr, amount, metadata);
-    // The sender_addr has retained her withdrawal privileges--proceed.
-    withdraw_from_balance<TokenType>(sender_balance, amount)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Balance<TokenType>>(Signer::address_of(account));
-aborts_if !exists<Account>(Signer::address_of(account));
-aborts_if global<Balance<TokenType>>(Signer::address_of(account)).token.value < amount;
-aborts_if Option::is_none(global<Account>(Signer::address_of(account)).withdrawal_capability);
-
- - - - - - - -
fun spec_withdraw<TokenType>(account: signer, amount: u128): Token<TokenType> {
-   Token<TokenType> { value: amount }
-}
-
- - - -
- - - -## Function `withdraw_with_capability` - -Withdraw amount Token from the account under cap.account_address with no metadata - - -
public fun withdraw_with_capability<TokenType: store>(cap: &Account::WithdrawCapability, amount: u128): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun withdraw_with_capability<TokenType: store>(
-    cap: &WithdrawCapability, amount: u128
-): Token<TokenType> acquires Balance, Account {
-    withdraw_with_capability_and_metadata<TokenType>(cap, amount, x"")
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Balance<TokenType>>(cap.account_address);
-aborts_if !exists<Account>(cap.account_address);
-aborts_if global<Balance<TokenType>>(cap.account_address).token.value < amount;
-
- - - -
- - - -## Function `withdraw_with_capability_and_metadata` - -Withdraw amount Token from the account under cap.account_address with metadata - - -
public fun withdraw_with_capability_and_metadata<TokenType: store>(cap: &Account::WithdrawCapability, amount: u128, metadata: vector<u8>): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun withdraw_with_capability_and_metadata<TokenType: store>(
-    cap: &WithdrawCapability, amount: u128, metadata: vector<u8>
-): Token<TokenType> acquires Balance, Account {
-    let balance = borrow_global_mut<Balance<TokenType>>(cap.account_address);
-    emit_account_withdraw_event<TokenType>(cap.account_address, amount, metadata);
-    withdraw_from_balance<TokenType>(balance , amount)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Balance<TokenType>>(cap.account_address);
-aborts_if !exists<Account>(cap.account_address);
-aborts_if global<Balance<TokenType>>(cap.account_address).token.value < amount;
-
- - - -
- - - -## Function `extract_withdraw_capability` - -Return a unique capability granting permission to withdraw from the sender's account balance. - - -
public fun extract_withdraw_capability(sender: &signer): Account::WithdrawCapability
-
- - - -
-Implementation - - -
public fun extract_withdraw_capability(
-    sender: &signer
-): WithdrawCapability acquires Account, EventStore {
-    let sender_addr = Signer::address_of(sender);
-    // Abort if we already extracted the unique withdraw capability for this account.
-    assert!(!delegated_withdraw_capability(sender_addr), Errors::invalid_state(EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED));
-
-    make_event_store_if_not_exist(sender);
-    let event_store = borrow_global_mut<EventStore>(sender_addr);
-    Event::emit_event<ExtractWithdrawCapEvent>(
-        &mut event_store.extract_withdraw_cap_events,
-        ExtractWithdrawCapEvent {
-            account_address: sender_addr,
-        }
-    );
-    let account = borrow_global_mut<Account>(sender_addr);
-    Option::extract(&mut account.withdrawal_capability)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(Signer::address_of(sender));
-aborts_if Option::is_none(global<Account>( Signer::address_of(sender)).withdrawal_capability);
-
- - - -
- - - -## Function `restore_withdraw_capability` - -Return the withdraw capability to the account it originally came from - - -
public fun restore_withdraw_capability(cap: Account::WithdrawCapability)
-
- - - -
-Implementation - - -
public fun restore_withdraw_capability(cap: WithdrawCapability)
-   acquires Account {
-       let account = borrow_global_mut<Account>(cap.account_address);
-       Option::fill(&mut account.withdrawal_capability, cap)
-}
-
- - - -
- -
-Specification - - - -
aborts_if Option::is_some(global<Account>(cap.account_address).withdrawal_capability);
-aborts_if !exists<Account>(cap.account_address);
-
- - - -
- - - -## Function `emit_account_withdraw_event` - - - -
fun emit_account_withdraw_event<TokenType: store>(account: address, amount: u128, metadata: vector<u8>)
-
- - - -
-Implementation - - -
fun emit_account_withdraw_event<TokenType: store>(account: address, amount: u128, metadata: vector<u8>)
-acquires Account {
-    // emit withdraw event
-    let account = borrow_global_mut<Account>(account);
-
-    Event::emit_event<WithdrawEvent>(&mut account.withdraw_events, WithdrawEvent {
-        amount,
-        token_code: Token::token_code<TokenType>(),
-        metadata,
-    });
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(account);
-
- - - -
- - - -## Function `emit_account_deposit_event` - - - -
fun emit_account_deposit_event<TokenType: store>(account: address, amount: u128, metadata: vector<u8>)
-
- - - -
-Implementation - - -
fun emit_account_deposit_event<TokenType: store>(account: address, amount: u128, metadata: vector<u8>)
-acquires Account {
-    // emit withdraw event
-    let account = borrow_global_mut<Account>(account);
-
-    Event::emit_event<DepositEvent>(&mut account.deposit_events, DepositEvent {
-        amount,
-        token_code: Token::token_code<TokenType>(),
-        metadata,
-    });
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(account);
-
- - - -
- - - -## Function `pay_from_capability` - -Withdraws amount Token using the passed in WithdrawCapability, and deposits it -into the payee's account balance. Creates the payee account if it doesn't exist. - - -
public fun pay_from_capability<TokenType: store>(cap: &Account::WithdrawCapability, payee: address, amount: u128, metadata: vector<u8>)
-
- - - -
-Implementation - - -
public fun pay_from_capability<TokenType: store>(
-    cap: &WithdrawCapability,
-    payee: address,
-    amount: u128,
-    metadata: vector<u8>,
-) acquires Account, Balance, AutoAcceptToken {
-    let tokens = withdraw_with_capability_and_metadata<TokenType>(cap, amount, *&metadata);
-    deposit_with_metadata<TokenType>(
-        payee,
-        tokens,
-        metadata,
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Balance<TokenType>>(cap.account_address);
-aborts_if !exists<Account>(cap.account_address);
-aborts_if global<Balance<TokenType>>(cap.account_address).token.value < amount;
-aborts_if amount == 0;
-aborts_if !exists<Account>(payee);
-aborts_if !exists<Balance<TokenType>>(payee);
-aborts_if cap.account_address != payee && global<Balance<TokenType>>(payee).token.value + amount > MAX_U128;
-
- - - -
- - - -## Function `pay_from_with_metadata` - -Withdraw amount Token from the transaction sender's -account balance and send the token to the payee address with the -attached metadata Creates the payee account if it does not exist - - -
public fun pay_from_with_metadata<TokenType: store>(account: &signer, payee: address, amount: u128, metadata: vector<u8>)
-
- - - -
-Implementation - - -
public fun pay_from_with_metadata<TokenType: store>(
-    account: &signer,
-    payee: address,
-    amount: u128,
-    metadata: vector<u8>,
-) acquires Account, Balance, AutoAcceptToken {
-    let tokens = withdraw_with_metadata<TokenType>(account, amount, *&metadata);
-    deposit_with_metadata<TokenType>(
-        payee,
-        tokens,
-        metadata,
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Balance<TokenType>>(Signer::address_of(account));
-aborts_if !exists<Account>(Signer::address_of(account));
-aborts_if global<Balance<TokenType>>(Signer::address_of(account)).token.value < amount;
-aborts_if Option::is_none(global<Account>(Signer::address_of(account)).withdrawal_capability);
-aborts_if amount == 0;
-aborts_if !exists<Account>(payee);
-aborts_if !exists<Balance<TokenType>>(payee);
-aborts_if Signer::address_of(account) != payee && global<Balance<TokenType>>(payee).token.value + amount > max_u128();
-
- - - - - - - -
schema DepositWithPayerAndMetadataAbortsIf<TokenType> {
-    payer: address;
-    payee: address;
-    to_deposit: Token<TokenType>;
-    aborts_if to_deposit.value == 0;
-    aborts_if !exists<Account>(payer);
-    aborts_if !exists<Account>(payee);
-    aborts_if !exists<Balance<TokenType>>(payee);
-    aborts_if global<Balance<TokenType>>(payee).token.value + to_deposit.value > max_u128();
-}
-
- - - -
- - - -## Function `pay_from` - -Withdraw amount Token from the transaction sender's -account balance and send the token to the payee address -Creates the payee account if it does not exist - - -
public fun pay_from<TokenType: store>(account: &signer, payee: address, amount: u128)
-
- - - -
-Implementation - - -
public fun pay_from<TokenType: store>(
-    account: &signer,
-    payee: address,
-    amount: u128
-) acquires Account, Balance, AutoAcceptToken {
-    pay_from_with_metadata<TokenType>(account, payee, amount, x"");
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Balance<TokenType>>(Signer::address_of(account));
-aborts_if !exists<Account>(Signer::address_of(account));
-aborts_if global<Balance<TokenType>>(Signer::address_of(account)).token.value < amount;
-aborts_if Option::is_none(global<Account>(Signer::address_of(account)).withdrawal_capability);
-aborts_if amount == 0;
-aborts_if !exists<Account>(payee);
-aborts_if !exists<Balance<TokenType>>(payee);
-aborts_if Signer::address_of(account) != payee && global<Balance<TokenType>>(payee).token.value + amount > max_u128();
-
- - - -
- - - -## Function `rotate_authentication_key_with_capability` - -Rotate the authentication key for the account under cap.account_address - - -
public fun rotate_authentication_key_with_capability(cap: &Account::KeyRotationCapability, new_authentication_key: vector<u8>)
-
- - - -
-Implementation - - -
public fun rotate_authentication_key_with_capability(
-    cap: &KeyRotationCapability,
-    new_authentication_key: vector<u8>,
-) acquires Account  {
-    let sender_account_resource = borrow_global_mut<Account>(cap.account_address);
-    // Don't allow rotating to clearly invalid key
-    assert!(Vector::length(&new_authentication_key) == 32, Errors::invalid_argument(EMALFORMED_AUTHENTICATION_KEY));
-    sender_account_resource.authentication_key = new_authentication_key;
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(cap.account_address);
-aborts_if len(new_authentication_key) != 32;
-ensures global<Account>(cap.account_address).authentication_key == new_authentication_key;
-
- - - - - - - -
fun spec_rotate_authentication_key_with_capability(addr: address, new_authentication_key: vector<u8>): bool {
-   global<Account>(addr).authentication_key == new_authentication_key
-}
-
- - - -
- - - -## Function `extract_key_rotation_capability` - -Return a unique capability granting permission to rotate the sender's authentication key - - -
public fun extract_key_rotation_capability(account: &signer): Account::KeyRotationCapability
-
- - - -
-Implementation - - -
public fun extract_key_rotation_capability(account: &signer): KeyRotationCapability
-acquires Account {
-    let account_address = Signer::address_of(account);
-    // Abort if we already extracted the unique key rotation capability for this account.
-    assert!(!delegated_key_rotation_capability(account_address), Errors::invalid_state(EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED));
-    let account = borrow_global_mut<Account>(account_address);
-    Option::extract(&mut account.key_rotation_capability)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(Signer::address_of(account));
-aborts_if Option::is_none(global<Account>(Signer::address_of(account)).key_rotation_capability);
-
- - - -
- - - -## Function `restore_key_rotation_capability` - -Return the key rotation capability to the account it originally came from - - -
public fun restore_key_rotation_capability(cap: Account::KeyRotationCapability)
-
- - - -
-Implementation - - -
public fun restore_key_rotation_capability(cap: KeyRotationCapability)
-acquires Account {
-    let account = borrow_global_mut<Account>(cap.account_address);
-    Option::fill(&mut account.key_rotation_capability, cap)
-}
-
- - - -
- -
-Specification - - - -
aborts_if Option::is_some(global<Account>(cap.account_address).key_rotation_capability);
-aborts_if !exists<Account>(cap.account_address);
-
- - - -
- - - -## Function `destroy_key_rotation_capability` - - - -
public fun destroy_key_rotation_capability(cap: Account::KeyRotationCapability)
-
- - - -
-Implementation - - -
public fun destroy_key_rotation_capability(cap: KeyRotationCapability) {
-    let KeyRotationCapability {account_address: _} = cap;
-}
-
- - - -
- - - -## Function `rotate_authentication_key` - - - -
public(script) fun rotate_authentication_key(account: signer, new_key: vector<u8>)
-
- - - -
-Implementation - - -
public(script) fun rotate_authentication_key(account: signer, new_key: vector<u8>) acquires Account, EventStore {
-    rotate_authentication_key_entry(account, new_key);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `rotate_authentication_key_entry` - - - -
public(script) fun rotate_authentication_key_entry(account: signer, new_key: vector<u8>)
-
- - - -
-Implementation - - -
public(script) fun rotate_authentication_key_entry(account: signer, new_key: vector<u8>) acquires Account, EventStore {
-    do_rotate_authentication_key(&account, new_key);
-}
-
- - - -
- - - -## Function `do_rotate_authentication_key` - - - -
public fun do_rotate_authentication_key(account: &signer, new_key: vector<u8>)
-
- - - -
-Implementation - - -
public fun do_rotate_authentication_key(account: &signer, new_key: vector<u8>) acquires Account, EventStore {
-    let key_rotation_capability = extract_key_rotation_capability(account);
-    rotate_authentication_key_with_capability(&key_rotation_capability, copy new_key);
-    restore_key_rotation_capability(key_rotation_capability);
-
-    make_event_store_if_not_exist(account);
-    let signer_addr = Signer::address_of(account);
-    let event_store = borrow_global_mut<EventStore>(signer_addr);
-    Event::emit_event<RotateAuthKeyEvent>(
-        &mut event_store.rotate_auth_key_events,
-        RotateAuthKeyEvent {
-            account_address: signer_addr,
-            new_auth_key: new_key,
-        }
-    );
-}
-
- - - -
- - - -## Function `balance_for` - -Helper to return the u128 value of the balance for account - - -
fun balance_for<TokenType: store>(balance: &Account::Balance<TokenType>): u128
-
- - - -
-Implementation - - -
fun balance_for<TokenType: store>(balance: &Balance<TokenType>): u128 {
-    Token::value<TokenType>(&balance.token)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `balance` - -Return the current TokenType balance of the account at addr. - - -
public fun balance<TokenType: store>(addr: address): u128
-
- - - -
-Implementation - - -
public fun balance<TokenType: store>(addr: address): u128 acquires Balance {
-    if (exists<Balance<TokenType>>(addr)) {
-        balance_for(borrow_global<Balance<TokenType>>(addr))
-    } else {
-        0u128
-    }
-}
-
- - - -
- - - -## Function `do_accept_token` - -Add a balance of Token type to the sending account. - - -
public fun do_accept_token<TokenType: store>(account: &signer)
-
- - - -
-Implementation - - -
public fun do_accept_token<TokenType: store>(account: &signer) acquires Account {
-    move_to(account, Balance<TokenType>{ token: Token::zero<TokenType>() });
-    let token_code = Token::token_code<TokenType>();
-    // Load the sender's account
-    let sender_account_ref = borrow_global_mut<Account>(Signer::address_of(account));
-    // Log a sent event
-    Event::emit_event<AcceptTokenEvent>(
-        &mut sender_account_ref.accept_token_events,
-        AcceptTokenEvent {
-            token_code:  token_code,
-        },
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if exists<Balance<TokenType>>(Signer::address_of(account));
-aborts_if !exists<Account>(Signer::address_of(account));
-
- - - -
- - - -## Function `accept_token` - - - -
public(script) fun accept_token<TokenType: store>(account: signer)
-
- - - -
-Implementation - - -
public(script) fun accept_token<TokenType: store>(account: signer) acquires Account {
-    accept_token_entry<TokenType>(account);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `accept_token_entry` - - - -
public(script) fun accept_token_entry<TokenType: store>(account: signer)
-
- - - -
-Implementation - - -
public(script) fun accept_token_entry<TokenType: store>(account: signer) acquires Account {
-    do_accept_token<TokenType>(&account);
-}
-
- - - -
- - - -## Function `is_accepts_token` - -This is a alias of is_accept_token - - -
public fun is_accepts_token<TokenType: store>(addr: address): bool
-
- - - -
-Implementation - - -
public fun is_accepts_token<TokenType: store>(addr: address): bool acquires AutoAcceptToken {
-    Self::is_accept_token<TokenType>(addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_accept_token` - -Return whether the account at addr accept Token type tokens - - -
public fun is_accept_token<TokenType: store>(addr: address): bool
-
- - - -
-Implementation - - -
public fun is_accept_token<TokenType: store>(addr: address): bool acquires AutoAcceptToken {
-    if (can_auto_accept_token(addr)) {
-        true
-    } else {
-        exists<Balance<TokenType>>(addr)
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `can_auto_accept_token` - -Check whether the address can auto accept token. - - -
public fun can_auto_accept_token(addr: address): bool
-
- - - -
-Implementation - - -
public fun can_auto_accept_token(addr: address): bool acquires AutoAcceptToken {
-    if (exists<AutoAcceptToken>(addr)) {
-        borrow_global<AutoAcceptToken>(addr).enable
-    } else {
-        false
-    }
-}
-
- - - -
- - - -## Function `set_auto_accept_token_entry` - - - -
public(script) fun set_auto_accept_token_entry(account: signer, enable: bool)
-
- - - -
-Implementation - - -
public(script) fun set_auto_accept_token_entry(account: signer, enable: bool) acquires AutoAcceptToken {
-    set_auto_accept_token(&account, enable);
-}
-
- - - -
- - - -## Function `set_auto_accept_token` - -Configure whether auto-accept tokens. - - -
public fun set_auto_accept_token(account: &signer, enable: bool)
-
- - - -
-Implementation - - -
public fun set_auto_accept_token(account: &signer, enable: bool) acquires AutoAcceptToken {
-    let addr = Signer::address_of(account);
-    if (exists<AutoAcceptToken>(addr)) {
-        let config = borrow_global_mut<AutoAcceptToken>(addr);
-        config.enable = enable;
-    } else {
-        move_to(account, AutoAcceptToken{enable});
-    };
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `try_accept_token` - -try to accept token for addr. - - -
fun try_accept_token<TokenType: store>(addr: address)
-
- - - -
-Implementation - - -
fun try_accept_token<TokenType: store>(addr: address) acquires AutoAcceptToken, Account {
-    if (!exists<Balance<TokenType>>(addr)) {
-        if (can_auto_accept_token(addr)) {
-            let signer = create_signer(addr);
-            do_accept_token<TokenType>(&signer);
-        }else{
-            abort Errors::not_published(ERR_TOKEN_NOT_ACCEPT)
-        }
-    };
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `sequence_number_for_account` - -Helper to return the sequence number field for given account - - -
fun sequence_number_for_account(account: &Account::Account): u64
-
- - - -
-Implementation - - -
fun sequence_number_for_account(account: &Account): u64 {
-    account.sequence_number
-}
-
- - - -
- - - -## Function `sequence_number` - -Return the current sequence number at addr - - -
public fun sequence_number(addr: address): u64
-
- - - -
-Implementation - - -
public fun sequence_number(addr: address): u64 acquires Account {
-    sequence_number_for_account(borrow_global<Account>(addr))
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(addr);
-
- - - -
- - - -## Function `authentication_key` - -Return the authentication key for this account - - -
public fun authentication_key(addr: address): vector<u8>
-
- - - -
-Implementation - - -
public fun authentication_key(addr: address): vector<u8> acquires Account {
-    *&borrow_global<Account>(addr).authentication_key
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(addr);
-
- - - -
- - - -## Function `delegated_key_rotation_capability` - -Return true if the account at addr has delegated its key rotation capability - - -
public fun delegated_key_rotation_capability(addr: address): bool
-
- - - -
-Implementation - - -
public fun delegated_key_rotation_capability(addr: address): bool
-acquires Account {
-    Option::is_none(&borrow_global<Account>(addr).key_rotation_capability)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(addr);
-
- - - -
- - - -## Function `delegated_withdraw_capability` - -Return true if the account at addr has delegated its withdraw capability - - -
public fun delegated_withdraw_capability(addr: address): bool
-
- - - -
-Implementation - - -
public fun delegated_withdraw_capability(addr: address): bool
-acquires Account {
-    Option::is_none(&borrow_global<Account>(addr).withdrawal_capability)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account>(addr);
-
- - - -
- - - -## Function `withdraw_capability_address` - -Return a reference to the address associated with the given withdraw capability - - -
public fun withdraw_capability_address(cap: &Account::WithdrawCapability): &address
-
- - - -
-Implementation - - -
public fun withdraw_capability_address(cap: &WithdrawCapability): &address {
-    &cap.account_address
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `key_rotation_capability_address` - -Return a reference to the address associated with the given key rotation capability - - -
public fun key_rotation_capability_address(cap: &Account::KeyRotationCapability): &address
-
- - - -
-Implementation - - -
public fun key_rotation_capability_address(cap: &KeyRotationCapability): &address {
-    &cap.account_address
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `exists_at` - -Checks if an account exists at check_addr - - -
public fun exists_at(check_addr: address): bool
-
- - - -
-Implementation - - -
public fun exists_at(check_addr: address): bool {
-    exists<Account>(check_addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_dummy_auth_key` - - - -
fun is_dummy_auth_key(account: &Account::Account): bool
-
- - - -
-Implementation - - -
fun is_dummy_auth_key(account: &Account): bool {
-    *&account.authentication_key == DUMMY_AUTH_KEY
-}
-
- - - -
- - - -## Function `txn_prologue` - -The prologue is invoked at the beginning of every transaction -It verifies: -- The account's auth key matches the transaction's public key -- That the account has enough balance to pay for all of the gas -- That the sequence number matches the transaction's sequence key - - -
public fun txn_prologue<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64)
-
- - - -
-Implementation - - -
public fun txn_prologue<TokenType: store>(
-    account: &signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-) acquires Account, Balance {
-    txn_prologue_v2<TokenType>(
-        account,
-        txn_sender,
-        txn_sequence_number,
-        txn_authentication_key_preimage,
-        txn_gas_price,
-        txn_max_gas_units,
-        1,
-        1,
-    )
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Account>(txn_sender);
-aborts_if global<Account>(txn_sender).authentication_key == DUMMY_AUTH_KEY && Authenticator::spec_derived_address(Hash::sha3_256(txn_authentication_key_preimage)) != txn_sender;
-aborts_if global<Account>(txn_sender).authentication_key != DUMMY_AUTH_KEY && Hash::sha3_256(txn_authentication_key_preimage) != global<Account>(txn_sender).authentication_key;
-aborts_if txn_sequence_number < global<Account>(txn_sender).sequence_number;
-
- - - -
- - - -## Function `txn_prologue_v2` - - - -
public fun txn_prologue_v2<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, stc_price: u128, stc_price_scaling: u128)
-
- - - -
-Implementation - - -
public fun txn_prologue_v2<TokenType: store>(
-    account: &signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    stc_price: u128,
-    stc_price_scaling: u128
-) acquires Account, Balance {
-    CoreAddresses::assert_genesis_address(account);
-
-    // Verify that the transaction sender's account exists
-    assert!(exists_at(txn_sender), Errors::requires_address(EPROLOGUE_ACCOUNT_DOES_NOT_EXIST));
-    // Verify the account has not delegate its signer cap.
-    assert!(!is_signer_delegated(txn_sender), Errors::invalid_state(EPROLOGUE_SIGNER_ALREADY_DELEGATED));
-
-    // Load the transaction sender's account
-    let sender_account = borrow_global_mut<Account>(txn_sender);
-
-    if (is_dummy_auth_key(sender_account)){
-        // if sender's auth key is empty, use address as auth key for check transaction.
-        assert!(
-            Authenticator::derived_address(Hash::sha3_256(txn_authentication_key_preimage)) == txn_sender,
-            Errors::invalid_argument(EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY)
-        );
-    }else{
-        // Check that the hash of the transaction's public key matches the account's auth key
-        assert!(
-            Hash::sha3_256(txn_authentication_key_preimage) == *&sender_account.authentication_key,
-            Errors::invalid_argument(EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY)
-        );
-    };
-    // Check that the account has enough balance for all of the gas
-    let (max_transaction_fee_stc,max_transaction_fee_token) = transaction_fee_simulate(txn_gas_price,txn_max_gas_units,0, stc_price, stc_price_scaling);
-    assert!(
-        max_transaction_fee_stc <= MAX_U64,
-        Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT),
-    );
-    if (max_transaction_fee_stc > 0) {
-        assert!(
-            (txn_sequence_number as u128) < MAX_U64,
-            Errors::limit_exceeded(EPROLOGUE_SEQUENCE_NUMBER_TOO_BIG)
-        );
-        let balance_amount_token = balance<TokenType>(txn_sender);
-        assert!(balance_amount_token >= max_transaction_fee_token, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT));
-        if (!is_stc<TokenType>()){
-            let balance_amount_stc= balance<STC>(CoreAddresses::GENESIS_ADDRESS());
-            assert!(balance_amount_stc >= max_transaction_fee_stc, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT));
-        }
-    };
-    // Check that the transaction sequence number matches the sequence number of the account
-    assert!(txn_sequence_number >= sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_OLD));
-    assert!(txn_sequence_number == sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_NEW));
-
-}
-
- - - -
- - - -## Function `txn_epilogue` - -The epilogue is invoked at the end of transactions. -It collects gas and bumps the sequence number - - -
public fun txn_epilogue<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64)
-
- - - -
-Implementation - - -
public fun txn_epilogue<TokenType: store>(
-    account: &signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining: u64,
-) acquires Account, Balance {
-    txn_epilogue_v3<TokenType>(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining,1,1)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `transaction_fee_simulate` - - - -
public fun transaction_fee_simulate(txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64, stc_price: u128, stc_price_scaling: u128): (u128, u128)
-
- - - -
-Implementation - - -
public fun transaction_fee_simulate(
-    txn_gas_price:u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining:u64,
-    stc_price: u128,
-    stc_price_scaling: u128,
-): (u128, u128){
-    let transaction_fee_stc =(txn_gas_price * (txn_max_gas_units - gas_units_remaining) as u128);
-    let transaction_fee_token= Math::mul_div((transaction_fee_stc as u128), stc_price, stc_price_scaling);
-    transaction_fee_token = if (transaction_fee_token == 0 && transaction_fee_stc > 0 ) { 1 } else { transaction_fee_token};
-    (transaction_fee_stc, transaction_fee_token)
-}
-
- - - -
- - - -## Function `txn_epilogue_v2` - -The epilogue is invoked at the end of transactions. -It collects gas and bumps the sequence number - - -
public fun txn_epilogue_v2<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64)
-
- - - -
-Implementation - - -
public fun txn_epilogue_v2<TokenType: store>(
-    account: &signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining: u64,
-) acquires Account, Balance {
-    txn_epilogue_v3<TokenType>(
-        account,
-        txn_sender,
-        txn_sequence_number,
-        txn_authentication_key_preimage,
-        txn_gas_price,
-        txn_max_gas_units,
-        gas_units_remaining,1,1)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Account>(txn_sender);
-aborts_if !exists<Balance<TokenType>>(txn_sender);
-aborts_if txn_max_gas_units < gas_units_remaining;
-let transaction_fee_amount = txn_gas_price * (txn_max_gas_units - gas_units_remaining);
-aborts_if transaction_fee_amount > max_u128();
-aborts_if global<Balance<TokenType>>(txn_sender).token.value < transaction_fee_amount;
-aborts_if txn_sequence_number + 1 > max_u64();
-aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
-          global<Balance<TokenType>>(txn_sender).token.value  < txn_gas_price * (txn_max_gas_units - gas_units_remaining);
-aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
-          !exists<TransactionFee::TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 &&
-          global<TransactionFee::TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS()).fee.value + txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u128();
-
- - - - -
pragma verify = false;
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Account>(txn_sender);
-aborts_if !exists<Balance<TokenType>>(txn_sender);
-aborts_if txn_sequence_number + 1 > max_u64();
-aborts_if !exists<Balance<TokenType>>(txn_sender);
-aborts_if txn_max_gas_units < gas_units_remaining;
-
- - - -
- - - -## Function `txn_epilogue_v3` - -The epilogue is invoked at the end of transactions. -It collects gas and bumps the sequence number - - -
public fun txn_epilogue_v3<TokenType: store>(account: &signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64, stc_price: u128, stc_price_scaling: u128)
-
- - - -
-Implementation - - -
public fun txn_epilogue_v3<TokenType: store>(
-    account: &signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining: u64,
-    stc_price: u128,
-    stc_price_scaling: u128,
-) acquires Account, Balance {
-    CoreAddresses::assert_genesis_address(account);
-    // Charge for gas
-    let (transaction_fee_amount_stc,transaction_fee_amount_token) = transaction_fee_simulate(
-        txn_gas_price,
-        txn_max_gas_units,
-        gas_units_remaining,
-        stc_price,
-        stc_price_scaling);
-    assert!(
-        balance<TokenType>(txn_sender) >= transaction_fee_amount_token,
-        Errors::limit_exceeded(EINSUFFICIENT_BALANCE)
-    );
-    if (!is_stc<TokenType>()){
-        let genesis_balance_amount_stc=balance<STC>(CoreAddresses::GENESIS_ADDRESS());
-        assert!(genesis_balance_amount_stc >= transaction_fee_amount_stc,
-            Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT)
-        );
-    };
-    // Load the transaction sender's account and balance resources
-    let sender_account = borrow_global_mut<Account>(txn_sender);
-    // Bump the sequence number
-    sender_account.sequence_number = txn_sequence_number + 1;
-    // Set auth key when user send transaction first.
-    if (is_dummy_auth_key(sender_account) && !Vector::is_empty(&txn_authentication_key_preimage)){
-        sender_account.authentication_key = Hash::sha3_256(txn_authentication_key_preimage);
-    };
-    if (transaction_fee_amount_stc > 0) {
-        let transaction_fee_token = withdraw_from_balance(
-        borrow_global_mut<Balance<TokenType>>(txn_sender),
-            transaction_fee_amount_token
-        );
-        deposit_to_balance(borrow_global_mut<Balance<TokenType>>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_token);
-        let stc_fee_token = withdraw_from_balance(borrow_global_mut<Balance<STC>>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_amount_stc);
-        TransactionFee::pay_fee(stc_fee_token);
-    };
-}
-
- - - -
- - - -## Function `remove_zero_balance_entry` - - - -
public(script) fun remove_zero_balance_entry<TokenType: store>(account: signer)
-
- - - -
-Implementation - - -
public(script) fun remove_zero_balance_entry<TokenType: store>(account: signer) acquires Balance {
-    remove_zero_balance<TokenType>(&account);
-}
-
- - - -
- - - -## Function `remove_zero_balance` - -Remove zero Balance - - -
public fun remove_zero_balance<TokenType: store>(account: &signer)
-
- - - -
-Implementation - - -
public fun remove_zero_balance<TokenType: store>(account: &signer) acquires Balance {
-    let addr: address = Signer::address_of(account);
-    let Balance<TokenType> { token } = move_from<Balance<TokenType>>(addr);
-    Token::destroy_zero<TokenType>(token);
-}
-
- - - -
- -
-Specification - - - -
let addr = Signer::address_of(account);
-aborts_if !exists<Balance<TokenType>>(addr);
-ensures !exists<Balance<TokenType>>(addr);
-
- - - -
- - - -## Function `make_event_store_if_not_exist` - -Make a event store if it's not exist. - - -
fun make_event_store_if_not_exist(account: &signer)
-
- - - -
-Implementation - - -
fun make_event_store_if_not_exist(account: &signer) {
-    if (!exists<EventStore>(Signer::address_of(account))) {
-        move_to(account, EventStore {
-          rotate_auth_key_events: Event::new_event_handle<RotateAuthKeyEvent>(account),
-          extract_withdraw_cap_events: Event::new_event_handle<ExtractWithdrawCapEvent>(account),
-          signer_delegate_events: Event::new_event_handle<SignerDelegateEvent>(account),
-        })
-    };
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/AccountScripts.md b/release/v12/docs/AccountScripts.md deleted file mode 100644 index 0a0a0d74..00000000 --- a/release/v12/docs/AccountScripts.md +++ /dev/null @@ -1,93 +0,0 @@ - - - -# Module `0x1::AccountScripts` - - - -- [Function `enable_auto_accept_token`](#0x1_AccountScripts_enable_auto_accept_token) -- [Function `disable_auto_accept_token`](#0x1_AccountScripts_disable_auto_accept_token) -- [Function `remove_zero_balance`](#0x1_AccountScripts_remove_zero_balance) - - -
use 0x1::Account;
-
- - - - - -## Function `enable_auto_accept_token` - -Enable account's auto-accept-token feature. -The script function is reenterable. - - -
public(script) fun enable_auto_accept_token(account: signer)
-
- - - -
-Implementation - - -
public(script) fun enable_auto_accept_token(account: signer) {
-    Account::set_auto_accept_token_entry(account, true);
-}
-
- - - -
- - - -## Function `disable_auto_accept_token` - -Disable account's auto-accept-token feature. -The script function is reenterable. - - -
public(script) fun disable_auto_accept_token(account: signer)
-
- - - -
-Implementation - - -
public(script) fun disable_auto_accept_token(account: signer) {
-    Account::set_auto_accept_token_entry(account, false);
-}
-
- - - -
- - - -## Function `remove_zero_balance` - -Remove zero Balance - - -
public(script) fun remove_zero_balance<TokenType: store>(account: signer)
-
- - - -
-Implementation - - -
public(script) fun remove_zero_balance<TokenType: store>(account: signer) {
-    Account::remove_zero_balance_entry<TokenType>(account);
-}
-
- - - -
diff --git a/release/v12/docs/AnyMemberPlugin.md b/release/v12/docs/AnyMemberPlugin.md deleted file mode 100644 index 361fffc8..00000000 --- a/release/v12/docs/AnyMemberPlugin.md +++ /dev/null @@ -1,234 +0,0 @@ - - - -# Module `0x1::AnyMemberPlugin` - -This plugin let every can join the DAO, and auto get 1 sbt. - - -- [Struct `AnyMemberPlugin`](#0x1_AnyMemberPlugin_AnyMemberPlugin) -- [Function `required_caps`](#0x1_AnyMemberPlugin_required_caps) -- [Function `initialize`](#0x1_AnyMemberPlugin_initialize) -- [Function `join`](#0x1_AnyMemberPlugin_join) -- [Function `join_entry`](#0x1_AnyMemberPlugin_join_entry) -- [Function `install_plugin_proposal`](#0x1_AnyMemberPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_AnyMemberPlugin_install_plugin_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Vector;
-
- - - - - -## Struct `AnyMemberPlugin` - - - -
struct AnyMemberPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps():vector<CapType>{
-    let caps = Vector::singleton(DAOSpace::member_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = AnyMemberPlugin{};
-
-    DAOPluginMarketplace::register_plugin<AnyMemberPlugin>(
-        &witness,
-        b"0x1::AnyMemberPlugin",
-        b"The member plugin that allow all member to do join.",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<AnyMemberPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://any-member-plugin",
-    );
-}
-
- - - -
- - - -## Function `join` - - - -
public fun join<DAOT: store>(sender: &signer, image_data: vector<u8>, image_url: vector<u8>)
-
- - - -
-Implementation - - -
public fun join<DAOT: store>(sender: &signer, image_data:vector<u8>, image_url:vector<u8>){
-    let witness = AnyMemberPlugin{};
-    let sender_addr = Signer::address_of(sender);
-    if (DAOSpace::is_member<DAOT>(sender_addr) ) {
-        return
-    };
-    let member_cap = DAOSpace::acquire_member_cap<DAOT, AnyMemberPlugin>(&witness);
-    let op_image_data = if(Vector::is_empty(&image_data)){
-        Option::none<vector<u8>>()
-    }else{
-        Option::some(image_data)
-    };
-    let op_image_url = if(Vector::is_empty(&image_url)){
-        Option::none<vector<u8>>()
-    }else{
-        Option::some(image_url)
-    };
-
-    DAOSpace::issue_member_offer<DAOT, AnyMemberPlugin>(&member_cap, sender_addr,  op_image_data, op_image_url, 1);
-    DAOSpace::accept_member_offer<DAOT>(sender);
-}
-
- - - -
- - - -## Function `join_entry` - - - -
public(script) fun join_entry<DAOT: store>(sender: signer, image_data: vector<u8>, image_url: vector<u8>)
-
- - - -
-Implementation - - -
public (script) fun join_entry<DAOT: store>(sender: signer, image_data:vector<u8>, image_url:vector<u8>){
-    join<DAOT>(&sender, image_data, image_url);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT:store>(sender:&signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    InstallPluginProposalPlugin::create_proposal<DAOT, AnyMemberPlugin>(sender, required_caps(), title, introduction, extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun install_plugin_proposal_entry<DAOT:store>(sender:signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/Authenticator.md b/release/v12/docs/Authenticator.md deleted file mode 100644 index baad0a7d..00000000 --- a/release/v12/docs/Authenticator.md +++ /dev/null @@ -1,448 +0,0 @@ - - - -# Module `0x1::Authenticator` - -Move representation of the authenticator types -- Ed25519 (single-sig) -- MultiEd25519 (K-of-N multisig) - - -- [Struct `MultiEd25519PublicKey`](#0x1_Authenticator_MultiEd25519PublicKey) -- [Constants](#@Constants_0) -- [Function `create_multi_ed25519`](#0x1_Authenticator_create_multi_ed25519) -- [Function `ed25519_authentication_key`](#0x1_Authenticator_ed25519_authentication_key) -- [Function `derived_address`](#0x1_Authenticator_derived_address) -- [Function `multi_ed25519_authentication_key`](#0x1_Authenticator_multi_ed25519_authentication_key) -- [Function `public_keys`](#0x1_Authenticator_public_keys) -- [Function `threshold`](#0x1_Authenticator_threshold) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::BCS;
-use 0x1::Errors;
-use 0x1::Hash;
-use 0x1::Vector;
-
- - - - - -## Struct `MultiEd25519PublicKey` - -A multi-ed25519 public key - - -
struct MultiEd25519PublicKey has copy, drop, store
-
- - - -
-Fields - - -
-
-public_keys: vector<vector<u8>> -
-
- vector of ed25519 public keys -
-
-threshold: u8 -
-
- approval threshold -
-
- - -
- - - -## Constants - - - - - - -
const AUTHENTICATION_KEY_LENGTH: u64 = 32;
-
- - - - - - - -
const ED25519_SCHEME_ID: u8 = 0;
-
- - - - - -Not enough keys were provided for the specified threshold when creating an MultiEd25519 key - - -
const ENOT_ENOUGH_KEYS_FOR_THRESHOLD: u64 = 103;
-
- - - - - -Too many keys were provided for the specified threshold when creating an MultiEd25519 key - - -
const ENUM_KEYS_ABOVE_MAX_THRESHOLD: u64 = 104;
-
- - - - - - - -
const EWRONG_AUTHENTICATION_KEY_LENGTH: u64 = 101;
-
- - - - - -Threshold provided was 0 which can't be used to create a MultiEd25519 key - - -
const EZERO_THRESHOLD: u64 = 102;
-
- - - - - -Maximum number of keys allowed in a MultiEd25519 public/private key - - -
const MAX_MULTI_ED25519_KEYS: u64 = 32;
-
- - - - - - - -
const MULTI_ED25519_SCHEME_ID: u8 = 1;
-
- - - - - -## Function `create_multi_ed25519` - -Create a a multisig policy from a vector of ed25519 public keys and a threshold. -Note: this does *not* check uniqueness of keys. Repeated keys are convenient to -encode weighted multisig policies. For example Alice AND 1 of Bob or Carol is -public_key: {alice_key, alice_key, bob_key, carol_key}, threshold: 3 -Aborts if threshold is zero or bigger than the length of public_keys. - - -
public fun create_multi_ed25519(public_keys: vector<vector<u8>>, threshold: u8): Authenticator::MultiEd25519PublicKey
-
- - - -
-Implementation - - -
public fun create_multi_ed25519(
-    public_keys: vector<vector<u8>>,
-    threshold: u8
-): MultiEd25519PublicKey {
-    // check threshold requirements
-    let len = Vector::length(&public_keys);
-    assert!(threshold != 0, Errors::invalid_argument(EZERO_THRESHOLD));
-    assert!(
-        (threshold as u64) <= len,
-        Errors::invalid_argument(ENOT_ENOUGH_KEYS_FOR_THRESHOLD)
-    );
-    // the multied25519 signature scheme allows at most 32 keys
-    assert!(
-        len <= MAX_MULTI_ED25519_KEYS,
-        Errors::invalid_argument(ENUM_KEYS_ABOVE_MAX_THRESHOLD)
-    );
-
-    MultiEd25519PublicKey { public_keys, threshold }
-}
-
- - - -
- -
-Specification - - - -
aborts_if threshold == 0;
-aborts_if threshold > Vector::length(public_keys);
-aborts_if Vector::length(public_keys) > 32;
-
- - - -
- - - -## Function `ed25519_authentication_key` - -Compute an authentication key for the ed25519 public key public_key - - -
public fun ed25519_authentication_key(public_key: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
public fun ed25519_authentication_key(public_key: vector<u8>): vector<u8> {
-    Vector::push_back(&mut public_key, ED25519_SCHEME_ID);
-    Hash::sha3_256(public_key)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures [abstract] result == spec_ed25519_authentication_key(public_key);
-
- - -We use an uninterpreted function to represent the result of key construction. The actual value -does not matter for the verification of callers. - - - - - -
fun spec_ed25519_authentication_key(public_key: vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `derived_address` - -convert authentication key to address - - -
public fun derived_address(authentication_key: vector<u8>): address
-
- - - -
-Implementation - - -
public fun derived_address(authentication_key: vector<u8>): address {
-    assert!(Vector::length(&authentication_key) == AUTHENTICATION_KEY_LENGTH, Errors::invalid_argument(EWRONG_AUTHENTICATION_KEY_LENGTH));
-    let address_bytes = Vector::empty<u8>();
-
-    let i = 16;
-    while (i < 32) {
-        let b = *Vector::borrow(&authentication_key, i);
-        Vector::push_back(&mut address_bytes, b);
-        i = i + 1;
-    };
-
-    BCS::to_address(address_bytes)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if len(authentication_key) != 32;
-ensures [abstract] result == spec_derived_address(authentication_key);
-
- - -We use an uninterpreted function to represent the result of derived address. The actual value -does not matter for the verification of callers. - - - - - -
fun spec_derived_address(authentication_key: vector<u8>): address;
-
- - - -
- - - -## Function `multi_ed25519_authentication_key` - -Compute a multied25519 account authentication key for the policy k - - -
public fun multi_ed25519_authentication_key(k: &Authenticator::MultiEd25519PublicKey): vector<u8>
-
- - - -
-Implementation - - -
public fun multi_ed25519_authentication_key(k: &MultiEd25519PublicKey): vector<u8> {
-    let public_keys = &k.public_keys;
-    let len = Vector::length(public_keys);
-    let authentication_key_preimage = Vector::empty();
-    let i = 0;
-    while (i < len) {
-        let public_key = *Vector::borrow(public_keys, i);
-        Vector::append(
-            &mut authentication_key_preimage,
-            public_key
-        );
-        i = i + 1;
-    };
-    Vector::append(&mut authentication_key_preimage, BCS::to_bytes(&k.threshold));
-    Vector::push_back(&mut authentication_key_preimage, MULTI_ED25519_SCHEME_ID);
-    Hash::sha3_256(authentication_key_preimage)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `public_keys` - -Return the public keys involved in the multisig policy k - - -
public fun public_keys(k: &Authenticator::MultiEd25519PublicKey): &vector<vector<u8>>
-
- - - -
-Implementation - - -
public fun public_keys(k: &MultiEd25519PublicKey): &vector<vector<u8>> {
-    &k.public_keys
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `threshold` - -Return the threshold for the multisig policy k - - -
public fun threshold(k: &Authenticator::MultiEd25519PublicKey): u8
-
- - - -
-Implementation - - -
public fun threshold(k: &MultiEd25519PublicKey): u8 {
-    *&k.threshold
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/BCS.md b/release/v12/docs/BCS.md deleted file mode 100644 index 9af233ec..00000000 --- a/release/v12/docs/BCS.md +++ /dev/null @@ -1,1682 +0,0 @@ - - - -# Module `0x1::BCS` - -Utility for converting a Move value to its binary representation in BCS (Diem Canonical -Serialization). BCS is the binary encoding for Move resources and other non-module values -published on-chain. - - -- [Constants](#@Constants_0) -- [Function `to_bytes`](#0x1_BCS_to_bytes) -- [Function `to_address`](#0x1_BCS_to_address) -- [Function `deserialize_option_bytes_vector`](#0x1_BCS_deserialize_option_bytes_vector) -- [Function `deserialize_option_tuple`](#0x1_BCS_deserialize_option_tuple) -- [Function `deserialize_bytes_vector`](#0x1_BCS_deserialize_bytes_vector) -- [Function `deserialize_u64_vector`](#0x1_BCS_deserialize_u64_vector) -- [Function `deserialize_u128_vector`](#0x1_BCS_deserialize_u128_vector) -- [Function `deserialize_option_bytes`](#0x1_BCS_deserialize_option_bytes) -- [Function `deserialize_address`](#0x1_BCS_deserialize_address) -- [Function `deserialize_16_bytes`](#0x1_BCS_deserialize_16_bytes) -- [Function `deserialize_bytes`](#0x1_BCS_deserialize_bytes) -- [Function `deserialize_u128`](#0x1_BCS_deserialize_u128) -- [Function `deserialize_u64`](#0x1_BCS_deserialize_u64) -- [Function `deserialize_u32`](#0x1_BCS_deserialize_u32) -- [Function `deserialize_u16`](#0x1_BCS_deserialize_u16) -- [Function `deserialize_u8`](#0x1_BCS_deserialize_u8) -- [Function `deserialize_option_tag`](#0x1_BCS_deserialize_option_tag) -- [Function `deserialize_len`](#0x1_BCS_deserialize_len) -- [Function `deserialize_bool`](#0x1_BCS_deserialize_bool) -- [Function `get_byte`](#0x1_BCS_get_byte) -- [Function `get_n_bytes`](#0x1_BCS_get_n_bytes) -- [Function `get_n_bytes_as_u128`](#0x1_BCS_get_n_bytes_as_u128) -- [Function `deserialize_uleb128_as_u32`](#0x1_BCS_deserialize_uleb128_as_u32) -- [Function `serialize_u32_as_uleb128`](#0x1_BCS_serialize_u32_as_uleb128) -- [Function `skip_option_bytes_vector`](#0x1_BCS_skip_option_bytes_vector) -- [Function `skip_option_bytes`](#0x1_BCS_skip_option_bytes) -- [Function `skip_bytes_vector`](#0x1_BCS_skip_bytes_vector) -- [Function `skip_bytes`](#0x1_BCS_skip_bytes) -- [Function `skip_n_bytes`](#0x1_BCS_skip_n_bytes) -- [Function `skip_u64_vector`](#0x1_BCS_skip_u64_vector) -- [Function `skip_u128_vector`](#0x1_BCS_skip_u128_vector) -- [Function `skip_u256`](#0x1_BCS_skip_u256) -- [Function `skip_u128`](#0x1_BCS_skip_u128) -- [Function `skip_u64`](#0x1_BCS_skip_u64) -- [Function `skip_u32`](#0x1_BCS_skip_u32) -- [Function `skip_u16`](#0x1_BCS_skip_u16) -- [Function `skip_u8`](#0x1_BCS_skip_u8) -- [Function `skip_address`](#0x1_BCS_skip_address) -- [Function `skip_bool`](#0x1_BCS_skip_bool) -- [Function `can_skip`](#0x1_BCS_can_skip) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Constants - - - - - - -
const ERR_INPUT_NOT_LARGE_ENOUGH: u64 = 201;
-
- - - - - - - -
const ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT: u64 = 207;
-
- - - - - - - -
const ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32: u64 = 206;
-
- - - - - - - -
const ERR_UNEXPECTED_BOOL_VALUE: u64 = 205;
-
- - - - - - - -
const INTEGER32_MAX_VALUE: u64 = 2147483647;
-
- - - - - -## Function `to_bytes` - -Return the binary representation of v in BCS (Starcoin Canonical Serialization) format - - -
public fun to_bytes<MoveValue>(v: &MoveValue): vector<u8>
-
- - - -
-Implementation - - -
native public fun to_bytes<MoveValue>(v: &MoveValue): vector<u8>;
-
- - - -
- - - -## Function `to_address` - -Return the address of key bytes - - -
public fun to_address(key_bytes: vector<u8>): address
-
- - - -
-Implementation - - -
native public fun to_address(key_bytes: vector<u8>): address;
-
- - - -
- - - -## Function `deserialize_option_bytes_vector` - - - -
public fun deserialize_option_bytes_vector(input: &vector<u8>, offset: u64): (vector<Option::Option<vector<u8>>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_bytes_vector(input: &vector<u8>, offset: u64): (vector<Option::Option<vector<u8>>>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<Option::Option<vector<u8>>>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_option_bytes(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_option_tuple` - - - -
public fun deserialize_option_tuple(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, Option::Option<vector<u8>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_tuple(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, Option::Option<vector<u8>>, u64) {
-    let (tag, new_offset) = deserialize_option_tag(input, offset);
-    if (!tag) {
-        return (Option::none<vector<u8>>(), Option::none<vector<u8>>(), new_offset)
-    } else {
-        let (bs1, new_offset) = deserialize_bytes(input, new_offset);
-        let (bs2, new_offset) = deserialize_bytes(input, new_offset);
-
-        (Option::some<vector<u8>>(bs1), Option::some<vector<u8>>(bs2), new_offset)
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_bytes_vector` - - - -
public fun deserialize_bytes_vector(input: &vector<u8>, offset: u64): (vector<vector<u8>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_bytes_vector(input: &vector<u8>, offset: u64): (vector<vector<u8>>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<vector<u8>>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_bytes(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u64_vector` - - - -
public fun deserialize_u64_vector(input: &vector<u8>, offset: u64): (vector<u64>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u64_vector(input: &vector<u8>, offset: u64): (vector<u64>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<u64>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_u64(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u128_vector` - - - -
public fun deserialize_u128_vector(input: &vector<u8>, offset: u64): (vector<u128>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u128_vector(input: &vector<u8>, offset: u64): (vector<u128>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    let vec = Vector::empty<u128>();
-    while (i < len) {
-        let (opt_bs, o) = deserialize_u128(input, new_offset);
-        Vector::push_back(&mut vec, opt_bs);
-        new_offset = o;
-        i = i + 1;
-    };
-    (vec, new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_option_bytes` - - - -
public fun deserialize_option_bytes(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_bytes(input: &vector<u8>, offset: u64): (Option::Option<vector<u8>>, u64) {
-    let (tag, new_offset) = deserialize_option_tag(input, offset);
-    if (!tag) {
-        return (Option::none<vector<u8>>(), new_offset)
-    } else {
-        let (bs, new_offset) = deserialize_bytes(input, new_offset);
-        return (Option::some<vector<u8>>(bs), new_offset)
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_address` - - - -
public fun deserialize_address(input: &vector<u8>, offset: u64): (address, u64)
-
- - - -
-Implementation - - -
public fun deserialize_address(input: &vector<u8>, offset: u64): (address, u64) {
-    let (content, new_offset) = deserialize_16_bytes(input, offset);
-    (BCS::to_address(content), new_offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_16_bytes` - - - -
public fun deserialize_16_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_16_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64) {
-    let content = get_n_bytes(input, offset, 16);
-    (content, offset + 16)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_bytes` - - - -
public fun deserialize_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64)
-
- - - -
-Implementation - - -
public fun deserialize_bytes(input: &vector<u8>, offset: u64): (vector<u8>, u64) {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let content = get_n_bytes(input, new_offset, len);
-    (content, new_offset + len)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u128` - - - -
public fun deserialize_u128(input: &vector<u8>, offset: u64): (u128, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u128(input: &vector<u8>, offset: u64): (u128, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 16);
-    (u, offset + 16)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u64` - - - -
public fun deserialize_u64(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u64(input: &vector<u8>, offset: u64): (u64, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 8);
-    ((u as u64), offset + 8)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u32` - - - -
public fun deserialize_u32(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u32(input: &vector<u8>, offset: u64): (u64, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 4);
-    ((u as u64), offset + 4)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u16` - - - -
public fun deserialize_u16(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u16(input: &vector<u8>, offset: u64): (u64, u64) {
-    let u = get_n_bytes_as_u128(input, offset, 2);
-    ((u as u64), offset + 2)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_u8` - - - -
public fun deserialize_u8(input: &vector<u8>, offset: u64): (u8, u64)
-
- - - -
-Implementation - - -
public fun deserialize_u8(input: &vector<u8>, offset: u64): (u8, u64) {
-    let u = get_byte(input, offset);
-    (u, offset + 1)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_option_tag` - - - -
public fun deserialize_option_tag(input: &vector<u8>, offset: u64): (bool, u64)
-
- - - -
-Implementation - - -
public fun deserialize_option_tag(input: &vector<u8>, offset: u64): (bool, u64) {
-    deserialize_bool(input, offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_len` - - - -
public fun deserialize_len(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_len(input: &vector<u8>, offset: u64): (u64, u64) {
-    deserialize_uleb128_as_u32(input, offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_bool` - - - -
public fun deserialize_bool(input: &vector<u8>, offset: u64): (bool, u64)
-
- - - -
-Implementation - - -
public fun deserialize_bool(input: &vector<u8>, offset: u64): (bool, u64) {
-    let b = get_byte(input, offset);
-    if (b == 1) {
-        return (true, offset + 1)
-    } else if (b == 0) {
-        return (false, offset + 1)
-    } else {
-        abort ERR_UNEXPECTED_BOOL_VALUE
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_byte` - - - -
fun get_byte(input: &vector<u8>, offset: u64): u8
-
- - - -
-Implementation - - -
fun get_byte(input: &vector<u8>, offset: u64): u8 {
-    assert!(((offset + 1) <= Vector::length(input)) && (offset < offset + 1), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-    *Vector::borrow(input, offset)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_n_bytes` - - - -
fun get_n_bytes(input: &vector<u8>, offset: u64, n: u64): vector<u8>
-
- - - -
-Implementation - - -
fun get_n_bytes(input: &vector<u8>, offset: u64, n: u64): vector<u8> {
-    assert!(((offset + n) <= Vector::length(input)) && (offset <= offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-    let i = 0;
-    let content = Vector::empty<u8>();
-    while (i < n) {
-        let b = *Vector::borrow(input, offset + i);
-        Vector::push_back(&mut content, b);
-        i = i + 1;
-    };
-    content
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_n_bytes_as_u128` - - - -
fun get_n_bytes_as_u128(input: &vector<u8>, offset: u64, n: u64): u128
-
- - - -
-Implementation - - -
fun get_n_bytes_as_u128(input: &vector<u8>, offset: u64, n: u64): u128 {
-    assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-    let number: u128 = 0;
-    let i = 0;
-    while (i < n) {
-        let byte = *Vector::borrow(input, offset + i);
-        let s = (i as u8) * 8;
-        number = number + ((byte as u128) << s);
-        i = i + 1;
-    };
-    number
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `deserialize_uleb128_as_u32` - - - -
public fun deserialize_uleb128_as_u32(input: &vector<u8>, offset: u64): (u64, u64)
-
- - - -
-Implementation - - -
public fun deserialize_uleb128_as_u32(input: &vector<u8>, offset: u64): (u64, u64) {
-    let value: u64 = 0;
-    let shift = 0;
-    let new_offset = offset;
-    while (shift < 32) {
-        let x = get_byte(input, new_offset);
-        new_offset = new_offset + 1;
-        let digit: u8 = x & 0x7F;
-        value = value | (digit as u64) << shift;
-        if ((value < 0) || (value > INTEGER32_MAX_VALUE)) {
-            abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32
-        };
-        if (digit == x) {
-            if (shift > 0 && digit == 0) {
-                abort ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT
-            };
-            return (value, new_offset)
-        };
-        shift = shift + 7
-    };
-    abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `serialize_u32_as_uleb128` - - - -
fun serialize_u32_as_uleb128(value: u64): vector<u8>
-
- - - -
-Implementation - - -
fun serialize_u32_as_uleb128(value: u64): vector<u8> {
-    let output = Vector::empty<u8>();
-    while ((value >> 7) != 0) {
-        Vector::push_back(&mut output, (((value & 0x7f) | 0x80) as u8));
-        value = value >> 7;
-    };
-    Vector::push_back(&mut output, (value as u8));
-    output
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_option_bytes_vector` - - - -
public fun skip_option_bytes_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_option_bytes_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    while (i < len) {
-        new_offset = skip_option_bytes(input, new_offset);
-        i = i + 1;
-    };
-    new_offset
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_option_bytes` - - - -
public fun skip_option_bytes(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_option_bytes(input: &vector<u8>, offset: u64):  u64 {
-    let (tag, new_offset) = deserialize_option_tag(input, offset);
-    if (!tag) {
-        new_offset
-    } else {
-        skip_bytes(input, new_offset)
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_bytes_vector` - - - -
public fun skip_bytes_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_bytes_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    let i = 0;
-    while (i < len) {
-        new_offset = skip_bytes(input, new_offset);
-        i = i + 1;
-    };
-    new_offset
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_bytes` - - - -
public fun skip_bytes(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_bytes(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    new_offset + len
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_n_bytes` - - - -
public fun skip_n_bytes(input: &vector<u8>, offset: u64, n: u64): u64
-
- - - -
-Implementation - - -
public fun skip_n_bytes(input: &vector<u8>, offset: u64, n:u64): u64 {
-    can_skip(input, offset, n );
-    offset + n
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u64_vector` - - - -
public fun skip_u64_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u64_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    can_skip(input, new_offset, len * 8);
-    new_offset + len * 8
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u128_vector` - - - -
public fun skip_u128_vector(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u128_vector(input: &vector<u8>, offset: u64): u64 {
-    let (len, new_offset) = deserialize_len(input, offset);
-    can_skip(input, new_offset, len * 16);
-    new_offset + len * 16
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u256` - - - -
public fun skip_u256(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u256(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 32 );
-    offset + 32
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u128` - - - -
public fun skip_u128(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u128(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 16 );
-    offset + 16
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u64` - - - -
public fun skip_u64(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u64(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 8 );
-    offset + 8
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u32` - - - -
public fun skip_u32(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u32(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 4 );
-    offset + 4
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u16` - - - -
public fun skip_u16(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u16(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 2 );
-    offset + 2
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_u8` - - - -
public fun skip_u8(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_u8(input: &vector<u8>, offset: u64): u64 {
-    can_skip(input, offset, 1 );
-    offset + 1
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_address` - - - -
public fun skip_address(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_address(input: &vector<u8>, offset: u64): u64 {
-    skip_n_bytes(input, offset, 16)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `skip_bool` - - - -
public fun skip_bool(input: &vector<u8>, offset: u64): u64
-
- - - -
-Implementation - - -
public fun skip_bool(input: &vector<u8>, offset: u64):  u64{
-    can_skip(input, offset, 1);
-    offset + 1
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `can_skip` - - - -
fun can_skip(input: &vector<u8>, offset: u64, n: u64)
-
- - - -
-Implementation - - -
fun can_skip(input: &vector<u8>, offset: u64, n: u64){
-    assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH));
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
- - - - - - - -
native fun serialize<MoveValue>(v: &MoveValue): vector<u8>;
-
diff --git a/release/v12/docs/Bitwise.md b/release/v12/docs/Bitwise.md deleted file mode 100644 index 74d8a7ca..00000000 --- a/release/v12/docs/Bitwise.md +++ /dev/null @@ -1,179 +0,0 @@ - - - -# Module `0x1::BitOperators` - -Functions for bit operations. - - -- [Function `and`](#0x1_BitOperators_and) -- [Function `or`](#0x1_BitOperators_or) -- [Function `xor`](#0x1_BitOperators_xor) -- [Function `not`](#0x1_BitOperators_not) -- [Function `lshift`](#0x1_BitOperators_lshift) -- [Function `rshift`](#0x1_BitOperators_rshift) -- [Module Specification](#@Module_Specification_0) - - -
- - - - - -## Function `and` - -bit and: x & y - - -
public fun and(x: u64, y: u64): u64
-
- - - -
-Implementation - - -
public fun and(x: u64, y: u64): u64 {
-    (x & y as u64)
-}
-
- - - -
- - - -## Function `or` - -bit or: x | y - - -
public fun or(x: u64, y: u64): u64
-
- - - -
-Implementation - - -
public fun or(x: u64, y: u64): u64 {
-    (x | y as u64)
-}
-
- - - -
- - - -## Function `xor` - -bit xor: x ^ y - - -
public fun xor(x: u64, y: u64): u64
-
- - - -
-Implementation - - -
public fun xor(x: u64, y: u64): u64 {
-    (x ^ y as u64)
-}
-
- - - -
- - - -## Function `not` - -bit not: !x - - -
public fun not(x: u64): u64
-
- - - -
-Implementation - - -
public fun not(x: u64): u64 {
-   (x ^ 18446744073709551615u64 as u64)
-}
-
- - - -
- - - -## Function `lshift` - -left shift n bits. - - -
public fun lshift(x: u64, n: u8): u64
-
- - - -
-Implementation - - -
public fun lshift(x: u64, n: u8): u64 {
-    (x << n  as u64)
-}
-
- - - -
- - - -## Function `rshift` - -right shift n bits. - - -
public fun rshift(x: u64, n: u8): u64
-
- - - -
-Implementation - - -
public fun rshift(x: u64, n: u8): u64 {
-    (x >> n  as u64)
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-
diff --git a/release/v12/docs/Block.md b/release/v12/docs/Block.md deleted file mode 100644 index 7a24f46d..00000000 --- a/release/v12/docs/Block.md +++ /dev/null @@ -1,953 +0,0 @@ - - - -# Module `0x1::Block` - -Block module provide metadata for generated blocks. - - -- [Resource `BlockMetadata`](#0x1_Block_BlockMetadata) -- [Struct `NewBlockEvent`](#0x1_Block_NewBlockEvent) -- [Struct `Checkpoint`](#0x1_Block_Checkpoint) -- [Resource `Checkpoints`](#0x1_Block_Checkpoints) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_Block_initialize) -- [Function `get_current_block_number`](#0x1_Block_get_current_block_number) -- [Function `get_parent_hash`](#0x1_Block_get_parent_hash) -- [Function `get_current_author`](#0x1_Block_get_current_author) -- [Function `process_block_metadata`](#0x1_Block_process_block_metadata) -- [Function `checkpoints_init`](#0x1_Block_checkpoints_init) -- [Function `checkpoint_entry`](#0x1_Block_checkpoint_entry) -- [Function `checkpoint`](#0x1_Block_checkpoint) -- [Function `base_checkpoint`](#0x1_Block_base_checkpoint) -- [Function `latest_state_root`](#0x1_Block_latest_state_root) -- [Function `base_latest_state_root`](#0x1_Block_base_latest_state_root) -- [Function `update_state_root_entry`](#0x1_Block_update_state_root_entry) -- [Function `update_state_root`](#0x1_Block_update_state_root) -- [Function `base_update_state_root`](#0x1_Block_base_update_state_root) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::BCS;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::GenesisSignerCapability;
-use 0x1::Hash;
-use 0x1::Option;
-use 0x1::Ring;
-use 0x1::Timestamp;
-use 0x1::Vector;
-
- - - - - -## Resource `BlockMetadata` - -Block metadata struct. - - -
struct BlockMetadata has key
-
- - - -
-Fields - - -
-
-number: u64 -
-
- number of the current block -
-
-parent_hash: vector<u8> -
-
- Hash of the parent block. -
-
-author: address -
-
- Author of the current block. -
-
-uncles: u64 -
-
- number of uncles. -
-
-new_block_events: Event::EventHandle<Block::NewBlockEvent> -
-
- Handle of events when new blocks are emitted -
-
- - -
- - - -## Struct `NewBlockEvent` - -Events emitted when new block generated. - - -
struct NewBlockEvent has drop, store
-
- - - -
-Fields - - -
-
-number: u64 -
-
- -
-
-author: address -
-
- -
-
-timestamp: u64 -
-
- -
-
-uncles: u64 -
-
- -
-
- - -
- - - -## Struct `Checkpoint` - - - -
struct Checkpoint has copy, drop, store
-
- - - -
-Fields - - -
-
-block_number: u64 -
-
- -
-
-block_hash: vector<u8> -
-
- -
-
-state_root: Option::Option<vector<u8>> -
-
- -
-
- - -
- - - -## Resource `Checkpoints` - - - -
struct Checkpoints has store, key
-
- - - -
-Fields - - -
-
-checkpoints: Ring::Ring<Block::Checkpoint> -
-
- -
-
-index: u64 -
-
- -
-
-last_number: u64 -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_ALREADY_INITIALIZED: u64 = 21;
-
- - - - - - - -
const BLOCK_HEADER_LENGTH: u64 = 247;
-
- - - - - - - -
const BLOCK_INTERVAL_NUMBER: u64 = 5;
-
- - - - - - - -
const CHECKPOINT_LENGTH: u64 = 60;
-
- - - - - - - -
const EBLOCK_NUMBER_MISMATCH: u64 = 17;
-
- - - - - - - -
const ERROR_INTERVAL_TOO_LITTLE: u64 = 20;
-
- - - - - - - -
const ERROR_NOT_BLOCK_HEADER: u64 = 19;
-
- - - - - - - -
const ERROR_NO_HAVE_CHECKPOINT: u64 = 18;
-
- - - - - -## Function `initialize` - -This can only be invoked by the GENESIS_ACCOUNT at genesis - - -
public fun initialize(account: &signer, parent_hash: vector<u8>)
-
- - - -
-Implementation - - -
public fun initialize(account: &signer, parent_hash: vector<u8>) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-
-    move_to<BlockMetadata>(
-        account,
-        BlockMetadata {
-            number: 0,
-            parent_hash: parent_hash,
-            author: CoreAddresses::GENESIS_ADDRESS(),
-            uncles: 0,
-            new_block_events: Event::new_event_handle<Self::NewBlockEvent>(account),
-        });
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if exists<BlockMetadata>(Signer::address_of(account));
-
- - - -
- - - -## Function `get_current_block_number` - -Get the current block number - - -
public fun get_current_block_number(): u64
-
- - - -
-Implementation - - -
public fun get_current_block_number(): u64 acquires BlockMetadata {
-  borrow_global<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS()).number
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `get_parent_hash` - -Get the hash of the parent block. - - -
public fun get_parent_hash(): vector<u8>
-
- - - -
-Implementation - - -
public fun get_parent_hash(): vector<u8> acquires BlockMetadata {
-  *&borrow_global<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS()).parent_hash
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `get_current_author` - -Gets the address of the author of the current block - - -
public fun get_current_author(): address
-
- - - -
-Implementation - - -
public fun get_current_author(): address acquires BlockMetadata {
-  borrow_global<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS()).author
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `process_block_metadata` - -Call at block prologue - - -
public fun process_block_metadata(account: &signer, parent_hash: vector<u8>, author: address, timestamp: u64, uncles: u64, number: u64)
-
- - - -
-Implementation - - -
public fun process_block_metadata(account: &signer, parent_hash: vector<u8>,author: address, timestamp: u64, uncles:u64, number:u64) acquires BlockMetadata{
-    CoreAddresses::assert_genesis_address(account);
-
-    let block_metadata_ref = borrow_global_mut<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-    assert!(number == (block_metadata_ref.number + 1), Errors::invalid_argument(EBLOCK_NUMBER_MISMATCH));
-    block_metadata_ref.number = number;
-    block_metadata_ref.author= author;
-    block_metadata_ref.parent_hash = parent_hash;
-    block_metadata_ref.uncles = uncles;
-
-    Event::emit_event<NewBlockEvent>(
-      &mut block_metadata_ref.new_block_events,
-      NewBlockEvent {
-          number: number,
-          author: author,
-          timestamp: timestamp,
-          uncles: uncles,
-      }
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if number != global<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS()).number + 1;
-
- - - - - - - -
schema AbortsIfBlockMetadataNotExist {
-    aborts_if !exists<BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-}
-
- - - -
- - - -## Function `checkpoints_init` - - - -
public fun checkpoints_init()
-
- - - -
-Implementation - - -
public fun checkpoints_init(){
-
-    assert!(!exists<Checkpoints>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED));
-    let signer = GenesisSignerCapability::get_genesis_signer();
-
-    let checkpoints = Ring::create_with_capacity<Checkpoint>(CHECKPOINT_LENGTH);
-    move_to<Checkpoints>(
-        &signer,
-        Checkpoints {
-           checkpoints  : checkpoints,
-           index        : 0,
-           last_number  : 0,
-    });
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `checkpoint_entry` - - - -
public(script) fun checkpoint_entry(_account: signer)
-
- - - -
-Implementation - - -
public (script) fun checkpoint_entry(_account: signer) acquires BlockMetadata, Checkpoints {
-    checkpoint();
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `checkpoint` - - - -
public fun checkpoint()
-
- - - -
-Implementation - - -
public fun checkpoint() acquires BlockMetadata, Checkpoints{
-    let parent_block_number = get_current_block_number() - 1;
-    let parent_block_hash   = get_parent_hash();
-
-    let checkpoints = borrow_global_mut<Checkpoints>(CoreAddresses::GENESIS_ADDRESS());
-    base_checkpoint(checkpoints, parent_block_number, parent_block_hash);
-
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `base_checkpoint` - - - -
fun base_checkpoint(checkpoints: &mut Block::Checkpoints, parent_block_number: u64, parent_block_hash: vector<u8>)
-
- - - -
-Implementation - - -
fun base_checkpoint(checkpoints: &mut Checkpoints, parent_block_number: u64, parent_block_hash:vector<u8>){
-    assert!(checkpoints.last_number + BLOCK_INTERVAL_NUMBER <= parent_block_number || checkpoints.last_number == 0, Errors::invalid_argument(ERROR_INTERVAL_TOO_LITTLE));
-
-    checkpoints.index = checkpoints.index + 1;
-    checkpoints.last_number = parent_block_number;
-    let op_checkpoint = Ring::push<Checkpoint>(&mut checkpoints.checkpoints, Checkpoint {
-                                                            block_number: parent_block_number,
-                                                            block_hash: parent_block_hash,
-                                                            state_root: Option::none<vector<u8>>(),
-                                                        } );
-    if(Option::is_some(&op_checkpoint)){
-        Option::destroy_some(op_checkpoint);
-    }else{
-        Option::destroy_none(op_checkpoint);
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `latest_state_root` - - - -
public fun latest_state_root(): (u64, vector<u8>)
-
- - - -
-Implementation - - -
public fun latest_state_root():(u64,vector<u8>) acquires  Checkpoints{
-    let checkpoints = borrow_global<Checkpoints>(CoreAddresses::GENESIS_ADDRESS());
-    base_latest_state_root(checkpoints)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `base_latest_state_root` - - - -
fun base_latest_state_root(checkpoints: &Block::Checkpoints): (u64, vector<u8>)
-
- - - -
-Implementation - - -
fun base_latest_state_root(checkpoints: &Checkpoints):(u64,vector<u8>){
-    let len = Ring::capacity<Checkpoint>(&checkpoints.checkpoints);
-    let j = if(checkpoints.index < len - 1){
-        checkpoints.index
-    }else{
-        len
-    };
-    let i = checkpoints.index;
-    while( j > 0){
-        let op_checkpoint = Ring::borrow(&checkpoints.checkpoints, i - 1 );
-        if( Option::is_some(op_checkpoint) && Option::is_some(&Option::borrow(op_checkpoint).state_root) ) {
-            let state_root = Option::borrow(&Option::borrow(op_checkpoint).state_root);
-            return (Option::borrow(op_checkpoint).block_number, *state_root)
-        };
-        j = j - 1;
-        i = i - 1;
-    };
-
-    abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `update_state_root_entry` - - - -
public(script) fun update_state_root_entry(_account: signer, header: vector<u8>)
-
- - - -
-Implementation - - -
public (script) fun update_state_root_entry(_account: signer , header: vector<u8>)
-acquires Checkpoints {
-    update_state_root(header);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `update_state_root` - - - -
public fun update_state_root(header: vector<u8>)
-
- - - -
-Implementation - - -
public fun update_state_root(header: vector<u8>) acquires  Checkpoints {
-    let checkpoints = borrow_global_mut<Checkpoints>(CoreAddresses::GENESIS_ADDRESS());
-    base_update_state_root(checkpoints, header);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `base_update_state_root` - - - -
fun base_update_state_root(checkpoints: &mut Block::Checkpoints, header: vector<u8>)
-
- - - -
-Implementation - - -
fun base_update_state_root(checkpoints: &mut Checkpoints, header: vector<u8>){
-    let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader");
-
-    //parent_hash
-    let new_offset = BCS::skip_bytes(&header,0);
-    //timestamp
-    let new_offset = BCS::skip_u64(&header,new_offset);
-    //number
-    let (number,new_offset) = BCS::deserialize_u64(&header,new_offset);
-    //author
-    new_offset = BCS::skip_address(&header,new_offset);
-    //author_auth_key
-    new_offset = BCS::skip_option_bytes(&header,new_offset);
-    //txn_accumulator_root
-    new_offset = BCS::skip_bytes(&header,new_offset);
-    //block_accumulator_root
-    new_offset = BCS::skip_bytes(&header,new_offset);
-    //state_root
-    let (state_root,_new_offset) = BCS::deserialize_bytes(&header,new_offset);
-
-    Vector::append(&mut prefix,header);
-    let block_hash = Hash::sha3_256(prefix);
-
-    let len = Ring::capacity<Checkpoint>(&checkpoints.checkpoints);
-    let j = if(checkpoints.index < len - 1){
-        checkpoints.index
-    }else{
-        len
-    };
-    let i = checkpoints.index;
-    while( j > 0){
-        let op_checkpoint = Ring::borrow_mut(&mut checkpoints.checkpoints, i - 1);
-
-        if( Option::is_some(op_checkpoint) && &Option::borrow(op_checkpoint).block_hash == &block_hash && Option::borrow<Checkpoint>(op_checkpoint).block_number == number) {
-
-            let op_state_root = &mut Option::borrow_mut<Checkpoint>(op_checkpoint).state_root;
-            if(Option::is_some(op_state_root)){
-                Option::swap(op_state_root, state_root);
-            }else{
-                Option::fill(op_state_root, state_root);
-            };
-            return
-        };
-        j = j - 1;
-        i = i - 1;
-    };
-
-    abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/BlockReward.md b/release/v12/docs/BlockReward.md deleted file mode 100644 index 4499e64e..00000000 --- a/release/v12/docs/BlockReward.md +++ /dev/null @@ -1,397 +0,0 @@ - - - -# Module `0x1::BlockReward` - -The module provide block rewarding calculation logic. - - -- [Resource `RewardQueue`](#0x1_BlockReward_RewardQueue) -- [Struct `RewardInfo`](#0x1_BlockReward_RewardInfo) -- [Struct `BlockRewardEvent`](#0x1_BlockReward_BlockRewardEvent) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_BlockReward_initialize) -- [Function `process_block_reward`](#0x1_BlockReward_process_block_reward) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Account;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::RewardConfig;
-use 0x1::STC;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::Treasury;
-use 0x1::TreasuryPlugin;
-use 0x1::Vector;
-
- - - - - -## Resource `RewardQueue` - -Queue of rewards distributed to miners. - - -
struct RewardQueue has key
-
- - - -
-Fields - - -
-
-reward_number: u64 -
-
- How many block rewards has been handled. -
-
-infos: vector<BlockReward::RewardInfo> -
-
- informations about the reward distribution. -
-
-reward_events: Event::EventHandle<BlockReward::BlockRewardEvent> -
-
- event handle used to emit block reward event. -
-
- - -
- - - -## Struct `RewardInfo` - -Reward info of miners. - - -
struct RewardInfo has store
-
- - - -
-Fields - - -
-
-number: u64 -
-
- number of the block miner minted. -
-
-reward: u128 -
-
- how many stc rewards. -
-
-miner: address -
-
- miner who mint the block. -
-
-gas_fees: Token::Token<STC::STC> -
-
- store the gas fee that users consumed. -
-
- - -
- - - -## Struct `BlockRewardEvent` - -block reward event - - -
struct BlockRewardEvent has drop, store
-
- - - -
-Fields - - -
-
-block_number: u64 -
-
- block number -
-
-block_reward: u128 -
-
- STC reward. -
-
-gas_fees: u128 -
-
- gas fees in STC. -
-
-miner: address -
-
- block miner -
-
- - -
- - - -## Constants - - - - - - -
const EAUTHOR_ADDRESS_AND_AUTH_KEY_MISMATCH: u64 = 105;
-
- - - - - - - -
const EAUTHOR_AUTH_KEY_IS_EMPTY: u64 = 101;
-
- - - - - - - -
const ECURRENT_NUMBER_IS_WRONG: u64 = 102;
-
- - - - - - - -
const EMINER_EXIST: u64 = 104;
-
- - - - - - - -
const EREWARD_NUMBER_IS_WRONG: u64 = 103;
-
- - - - - -## Function `initialize` - -Initialize the module, should be called in genesis. - - -
public fun initialize(account: &signer, reward_delay: u64)
-
- - - -
-Implementation - - -
public fun initialize(account: &signer, reward_delay: u64) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-
-    RewardConfig::initialize(account, reward_delay);
-    move_to<RewardQueue>(account, RewardQueue {
-        reward_number: 0,
-        infos: Vector::empty(),
-        reward_events: Event::new_event_handle<Self::BlockRewardEvent>(account),
-    });
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-include Config::PublishNewConfigAbortsIf<RewardConfig::RewardConfig>;
-include Config::PublishNewConfigEnsures<RewardConfig::RewardConfig>;
-aborts_if exists<RewardQueue>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<RewardQueue>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `process_block_reward` - -Process the given block rewards. - - -
public fun process_block_reward(account: &signer, current_number: u64, current_reward: u128, current_author: address, _auth_key_vec: vector<u8>, previous_block_gas_fees: Token::Token<STC::STC>)
-
- - - -
-Implementation - - -
public fun process_block_reward(account: &signer, current_number: u64, current_reward: u128,
-                                current_author: address, _auth_key_vec: vector<u8>,
-                                previous_block_gas_fees: Token::Token<STC>) acquires RewardQueue {
-    CoreAddresses::assert_genesis_address(account);
-    if (current_number == 0) {
-        Token::destroy_zero(previous_block_gas_fees);
-        return
-    };
-
-    let rewards = borrow_global_mut<RewardQueue>(CoreAddresses::GENESIS_ADDRESS());
-    let len = Vector::length(&rewards.infos);
-    assert!((current_number == (rewards.reward_number + len + 1)), Errors::invalid_argument(ECURRENT_NUMBER_IS_WRONG));
-
-    // distribute gas fee to last block reward info.
-    // if not last block reward info, the passed in gas fee must be zero.
-    if (len == 0) {
-        Token::destroy_zero(previous_block_gas_fees);
-    } else {
-        let reward_info = Vector::borrow_mut(&mut rewards.infos, len - 1);
-        assert!(current_number == reward_info.number + 1, Errors::invalid_argument(ECURRENT_NUMBER_IS_WRONG));
-        Token::deposit(&mut reward_info.gas_fees, previous_block_gas_fees);
-    };
-
-    let reward_delay = RewardConfig::reward_delay();
-    if (len >= reward_delay) {//pay and remove
-        let i = len;
-        while (i > 0 && i >= reward_delay) {
-            let RewardInfo { number: reward_block_number, reward: block_reward, gas_fees, miner } = Vector::remove(&mut rewards.infos, 0);
-
-            let gas_fee_value = Token::value(&gas_fees);
-            let total_reward = gas_fees;
-            // add block reward to total.
-            if (block_reward > 0) {
-                // if no STC in Treasury, BlockReward will been 0.
-                let treasury_balance = Treasury::balance<STC>();
-                if (treasury_balance < block_reward) {
-                    block_reward = treasury_balance;
-                };
-                if (block_reward > 0) {
-                    let reward = TreasuryPlugin::withdraw_for_block_reward<STC>(account, block_reward);
-                    Token::deposit(&mut total_reward, reward);
-                };
-            };
-            // distribute total.
-            if (Token::value(&total_reward) > 0) {
-                Account::deposit<STC>(miner, total_reward);
-            } else {
-                Token::destroy_zero(total_reward);
-            };
-            // emit reward event.
-            Event::emit_event<BlockRewardEvent>(
-                &mut rewards.reward_events,
-                BlockRewardEvent {
-                    block_number: reward_block_number,
-                    block_reward: block_reward,
-                    gas_fees: gas_fee_value,
-                    miner,
-                }
-            );
-
-            rewards.reward_number = rewards.reward_number + 1;
-            i = i - 1;
-        }
-    };
-
-    if (!Account::exists_at(current_author)) {
-        Account::create_account_with_address<STC>(current_author);
-    };
-    let current_info = RewardInfo {
-        number: current_number,
-        reward: current_reward,
-        miner: current_author,
-        gas_fees: Token::zero<STC>(),
-    };
-    Vector::push_back(&mut rewards.infos, current_info);
-
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if current_number == 0 && Token::value(previous_block_gas_fees) != 0;
-aborts_if current_number > 0 && !exists<RewardQueue>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if current_number > 0 && (global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).reward_number + Vector::length(global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).infos) + 1) != current_number;
-aborts_if current_number > 0 && !exists<Config::Config<RewardConfig::RewardConfig>>(CoreAddresses::GENESIS_ADDRESS());
-let reward_info_length = Vector::length(global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).infos);
-aborts_if current_number > 0 && reward_info_length == 0 && Token::value(previous_block_gas_fees) != 0;
-aborts_if current_number > 0 && reward_info_length != 0 && Vector::borrow(global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).infos, reward_info_length - 1).number != current_number - 1;
-aborts_if current_number > 0 && Vector::length(global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).infos) >= global<Config::Config<RewardConfig::RewardConfig>>(CoreAddresses::GENESIS_ADDRESS()).payload.reward_delay
-&& (global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).reward_number + 1) != Vector::borrow(global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).infos, 0).number;
-aborts_if current_number > 0 && Vector::length(global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).infos) >= global<Config::Config<RewardConfig::RewardConfig>>(CoreAddresses::GENESIS_ADDRESS()).payload.reward_delay
-        && (global<RewardQueue>(CoreAddresses::GENESIS_ADDRESS()).reward_number + 1) > max_u64();
-aborts_if current_number > 0 && !Account::exists_at(current_author) ;
-pragma verify = false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/ChainId.md b/release/v12/docs/ChainId.md deleted file mode 100644 index 89ab9fd3..00000000 --- a/release/v12/docs/ChainId.md +++ /dev/null @@ -1,425 +0,0 @@ - - - -# Module `0x1::ChainId` - -The module provides chain id information. - - -- [Resource `ChainId`](#0x1_ChainId_ChainId) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_ChainId_initialize) -- [Function `get`](#0x1_ChainId_get) -- [Function `is_dev`](#0x1_ChainId_is_dev) -- [Function `is_test`](#0x1_ChainId_is_test) -- [Function `is_halley`](#0x1_ChainId_is_halley) -- [Function `is_proxima`](#0x1_ChainId_is_proxima) -- [Function `is_barnard`](#0x1_ChainId_is_barnard) -- [Function `is_main`](#0x1_ChainId_is_main) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::CoreAddresses;
-use 0x1::Timestamp;
-
- - - - - -## Resource `ChainId` - -chain id data structure. - - -
struct ChainId has key
-
- - - -
-Fields - - -
-
-id: u8 -
-
- real id. -
-
- - -
- - - -## Constants - - - - - - -
const BARNARD_CHAIN_ID: u8 = 251;
-
- - - - - - - -
const DEV_CHAIN_ID: u8 = 254;
-
- - - - - - - -
const HALLEY_CHAIN_ID: u8 = 253;
-
- - - - - - - -
const MAIN_CHAIN_ID: u8 = 1;
-
- - - - - - - -
const PROXIMA_CHAIN_ID: u8 = 252;
-
- - - - - - - -
const TEST_CHAIN_ID: u8 = 255;
-
- - - - - -## Function `initialize` - -Publish the chain ID under the genesis account - - -
public fun initialize(account: &signer, id: u8)
-
- - - -
-Implementation - - -
public fun initialize(account: &signer, id: u8) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-    move_to(account, ChainId { id });
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if exists<ChainId>(Signer::address_of(account));
-ensures exists<ChainId>(Signer::address_of(account));
-
- - - -
- - - -## Function `get` - -Return the chain ID of this chain - - -
public fun get(): u8
-
- - - -
-Implementation - - -
public fun get(): u8 acquires ChainId {
-    borrow_global<ChainId>(CoreAddresses::GENESIS_ADDRESS()).id
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `is_dev` - - - -
public fun is_dev(): bool
-
- - - -
-Implementation - - -
public fun is_dev(): bool acquires ChainId {
-    get() == DEV_CHAIN_ID
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `is_test` - - - -
public fun is_test(): bool
-
- - - -
-Implementation - - -
public fun is_test(): bool acquires ChainId {
-    get() == TEST_CHAIN_ID
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `is_halley` - - - -
public fun is_halley(): bool
-
- - - -
-Implementation - - -
public fun is_halley(): bool acquires ChainId {
-    get() == HALLEY_CHAIN_ID
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `is_proxima` - - - -
public fun is_proxima(): bool
-
- - - -
-Implementation - - -
public fun is_proxima(): bool acquires ChainId {
-    get() == PROXIMA_CHAIN_ID
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `is_barnard` - - - -
public fun is_barnard(): bool
-
- - - -
-Implementation - - -
public fun is_barnard(): bool acquires ChainId {
-    get() == BARNARD_CHAIN_ID
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `is_main` - - - -
public fun is_main(): bool
-
- - - -
-Implementation - - -
public fun is_main(): bool acquires ChainId {
-    get() == MAIN_CHAIN_ID
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-ensures exists<ChainId>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Collection.md b/release/v12/docs/Collection.md deleted file mode 100644 index 6716cbb4..00000000 --- a/release/v12/docs/Collection.md +++ /dev/null @@ -1,430 +0,0 @@ - - - -# Module `0x1::Collection` - -Deprecated since @v3 please use Collection2 -Provide a account based vector for save resource. - - -- [Struct `Collection`](#0x1_Collection_Collection) -- [Resource `CollectionStore`](#0x1_Collection_CollectionStore) -- [Constants](#@Constants_0) -- [Function `borrow`](#0x1_Collection_borrow) -- [Function `pop_back`](#0x1_Collection_pop_back) -- [Function `exists_at`](#0x1_Collection_exists_at) -- [Function `put`](#0x1_Collection_put) -- [Function `take`](#0x1_Collection_take) -- [Function `borrow_collection`](#0x1_Collection_borrow_collection) -- [Function `return_collection`](#0x1_Collection_return_collection) -- [Function `destroy_empty`](#0x1_Collection_destroy_empty) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Vector;
-
- - - - - -## Struct `Collection` - -Collection in memory, can not drop & store. - - -
struct Collection<T>
-
- - - -
-Fields - - -
-
-items: vector<T> -
-
- -
-
-owner: address -
-
- the owner of Collection. -
-
- - -
- - - -## Resource `CollectionStore` - -Collection in global store. - - -
struct CollectionStore<T: store> has key
-
- - - -
-Fields - - -
-
-items: Option::Option<vector<T>> -
-
- items in the CollectionStore. - use Option at here is for temporary take away from store to construct Collection. -
-
- - -
- - - -## Constants - - - - - - -
const EDEPRECATED_FUNCTION: u64 = 19;
-
- - - - - - - -
const ECOLLECTION_NOT_EXIST: u64 = 101;
-
- - - - - -The operator require the collection owner. - - -
const ECOLLECTION_NOT_OWNER: u64 = 102;
-
- - - - - -## Function `borrow` - -Acquire an immutable reference to the ith element of the collection c. -Aborts if i is out of bounds. - - -
public fun borrow<T>(c: &Collection::Collection<T>, i: u64): &T
-
- - - -
-Implementation - - -
public fun borrow<T>(c: &Collection<T>, i: u64): &T{
-    Vector::borrow(&c.items, i)
-}
-
- - - -
- - - -## Function `pop_back` - -Pop an element from the end of vector v. -Aborts if v is empty. - - -
public fun pop_back<T>(account: &signer, c: &mut Collection::Collection<T>): T
-
- - - -
-Implementation - - -
public fun pop_back<T>(account: &signer, c: &mut Collection<T>): T {
-    assert!(Signer::address_of(account) == c.owner, Errors::requires_address(ECOLLECTION_NOT_OWNER));
-    Vector::pop_back<T>(&mut c.items)
-}
-
- - - -
- - - -## Function `exists_at` - -check the Collection exists in addr - - -
fun exists_at<T: store>(addr: address): bool
-
- - - -
-Implementation - - -
fun exists_at<T: store>(addr: address): bool{
-    exists<CollectionStore<T>>(addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `put` - -Deprecated since @v3 -Put items to account's Collection last position. - - -
public fun put<T: store>(_account: &signer, _item: T)
-
- - - -
-Implementation - - -
public fun put<T: store>(_account: &signer, _item: T) {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `take` - -Take last item from account's Collection of T. - - -
public fun take<T: store>(account: &signer): T
-
- - - -
-Implementation - - -
public fun take<T: store>(account: &signer): T acquires CollectionStore{
-    let addr = Signer::address_of(account);
-    let c = borrow_collection<T>(addr);
-    let item = pop_back(account, &mut c);
-    return_collection(c);
-    item
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `borrow_collection` - -Borrow collection of T from addr - - -
public fun borrow_collection<T: store>(addr: address): Collection::Collection<T>
-
- - - -
-Implementation - - -
public fun borrow_collection<T: store>(addr: address): Collection<T> acquires CollectionStore{
-    assert!(exists_at<T>(addr), Errors::invalid_state(ECOLLECTION_NOT_EXIST));
-    let c = borrow_global_mut<CollectionStore<T>>(addr);
-    let items = Option::extract(&mut c.items);
-    Collection{
-        items,
-        owner: addr
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `return_collection` - -Return the Collection of T - - -
public fun return_collection<T: store>(c: Collection::Collection<T>)
-
- - - -
-Implementation - - -
public fun return_collection<T: store>(c: Collection<T>) acquires CollectionStore{
-    let Collection{ items, owner } = c;
-    if (Vector::is_empty(&items)) {
-        let c = move_from<CollectionStore<T>>(owner);
-        destroy_empty(c);
-        Vector::destroy_empty(items);
-    }else{
-        let c = borrow_global_mut<CollectionStore<T>>(owner);
-        Option::fill(&mut c.items, items);
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `destroy_empty` - - - -
fun destroy_empty<T: store>(c: Collection::CollectionStore<T>)
-
- - - -
-Implementation - - -
fun destroy_empty<T: store>(c: CollectionStore<T>){
-    let CollectionStore{ items } = c;
-    Option::destroy_none(items);
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = false;
-
diff --git a/release/v12/docs/Collection2.md b/release/v12/docs/Collection2.md deleted file mode 100644 index 42e6ff21..00000000 --- a/release/v12/docs/Collection2.md +++ /dev/null @@ -1,878 +0,0 @@ - - - -# Module `0x1::Collection2` - -Provide a account based vector for save resource item. -The resource in CollectionStore can borrowed by anyone, anyone can get immutable ref of item. -and the owner of Collection can allow others to add item to Collection or get mut ref from Collection.git - - -- [Struct `Collection`](#0x1_Collection2_Collection) -- [Resource `CollectionStore`](#0x1_Collection2_CollectionStore) -- [Constants](#@Constants_0) -- [Function `length`](#0x1_Collection2_length) -- [Function `borrow`](#0x1_Collection2_borrow) -- [Function `push_back`](#0x1_Collection2_push_back) -- [Function `borrow_mut`](#0x1_Collection2_borrow_mut) -- [Function `pop_back`](#0x1_Collection2_pop_back) -- [Function `remove`](#0x1_Collection2_remove) -- [Function `append`](#0x1_Collection2_append) -- [Function `append_all`](#0x1_Collection2_append_all) -- [Function `exists_at`](#0x1_Collection2_exists_at) -- [Function `is_accept`](#0x1_Collection2_is_accept) -- [Function `accept`](#0x1_Collection2_accept) -- [Function `put`](#0x1_Collection2_put) -- [Function `put_all`](#0x1_Collection2_put_all) -- [Function `take`](#0x1_Collection2_take) -- [Function `create_collection`](#0x1_Collection2_create_collection) -- [Function `length_of`](#0x1_Collection2_length_of) -- [Function `borrow_collection`](#0x1_Collection2_borrow_collection) -- [Function `return_collection`](#0x1_Collection2_return_collection) -- [Function `destroy_collection`](#0x1_Collection2_destroy_collection) -- [Function `destroy_empty`](#0x1_Collection2_destroy_empty) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Vector;
-
- - - - - -## Struct `Collection` - -Collection in memory, can not drop & store. - - -
struct Collection<T>
-
- - - -
-Fields - - -
-
-items: vector<T> -
-
- -
-
-owner: address -
-
- -
-
-can_put: bool -
-
- -
-
-can_mut: bool -
-
- -
-
-can_take: bool -
-
- -
-
- - -
- - - -## Resource `CollectionStore` - -Collection in global store. - - -
struct CollectionStore<T: store> has key
-
- - - -
-Fields - - -
-
-items: Option::Option<vector<T>> -
-
- items in the CollectionStore. - use Option at here is for temporary take away from store to construct Collection. -
-
-anyone_can_put: bool -
-
- -
-
-anyone_can_mut: bool -
-
- -
-
- - -
- - - -## Constants - - - - -The operator require the collection owner or collection set anyone_can_put to true. - - -
const ERR_COLLECTION_CAN_NOT_ADD: u64 = 102;
-
- - - - - -The operator require the collection owner or collection set anyone_can_mut to true. - - -
const ERR_COLLECTION_CAN_NOT_MUT: u64 = 103;
-
- - - - - -The operator require the collection owner - - -
const ERR_COLLECTION_CAN_NOT_TAKE: u64 = 104;
-
- - - - - - - -
const ERR_COLLECTION_INVALID_BORROW_STATE: u64 = 105;
-
- - - - - - - -
const ERR_COLLECTION_IS_NOT_EMPTY: u64 = 106;
-
- - - - - - - -
const ERR_COLLECTION_NOT_EXIST: u64 = 101;
-
- - - - - -## Function `length` - -Return the length of the collection. - - -
public fun length<T>(c: &Collection2::Collection<T>): u64
-
- - - -
-Implementation - - -
public fun length<T>(c: &Collection<T>): u64{
-    Vector::length(&c.items)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `borrow` - -Acquire an immutable reference to the ith element of the collection c. -Aborts if i is out of bounds. - - -
public fun borrow<T>(c: &Collection2::Collection<T>, i: u64): &T
-
- - - -
-Implementation - - -
public fun borrow<T>(c: &Collection<T>, i: u64): &T{
-    Vector::borrow(&c.items, i)
-}
-
- - - -
- - - -## Function `push_back` - -Add item v to the end of the collection c. -require owner of Collection. - - -
public fun push_back<T>(c: &mut Collection2::Collection<T>, t: T)
-
- - - -
-Implementation - - -
public fun push_back<T>(c: &mut Collection<T>, t: T){
-    assert!(c.can_put, Errors::requires_address(ERR_COLLECTION_CAN_NOT_ADD));
-    Vector::push_back<T>(&mut c.items, t);
-}
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the ith item in the Collection c. -Aborts if i is out of bounds. - - -
public fun borrow_mut<T>(c: &mut Collection2::Collection<T>, i: u64): &mut T
-
- - - -
-Implementation - - -
public fun borrow_mut<T>(c: &mut Collection<T>, i: u64): &mut T{
-    assert!(c.can_mut, Errors::requires_address(ERR_COLLECTION_CAN_NOT_MUT));
-    Vector::borrow_mut<T>(&mut c.items, i)
-}
-
- - - -
- - - -## Function `pop_back` - -Pop an element from the end of vector v. -Aborts if v is empty. - - -
public fun pop_back<T>(c: &mut Collection2::Collection<T>): T
-
- - - -
-Implementation - - -
public fun pop_back<T>(c: &mut Collection<T>): T {
-    assert!(c.can_take, Errors::requires_address(ERR_COLLECTION_CAN_NOT_TAKE));
-    Vector::pop_back<T>(&mut c.items)
-}
-
- - - -
- - - -## Function `remove` - - - -
public fun remove<T>(c: &mut Collection2::Collection<T>, i: u64): T
-
- - - -
-Implementation - - -
public fun remove<T>(c: &mut Collection<T>, i: u64): T{
-    assert!(c.can_take, Errors::requires_address(ERR_COLLECTION_CAN_NOT_TAKE));
-    Vector::remove<T>(&mut c.items, i)
-}
-
- - - -
- - - -## Function `append` - - - -
public fun append<T>(c: &mut Collection2::Collection<T>, other: T)
-
- - - -
-Implementation - - -
public fun append<T>(c: &mut Collection<T>, other: T) {
-    assert!(c.can_put, Errors::requires_address(ERR_COLLECTION_CAN_NOT_ADD));
-    Vector::append<T>(&mut c.items, Vector::singleton(other))
-}
-
- - - -
- - - -## Function `append_all` - - - -
public fun append_all<T>(c: &mut Collection2::Collection<T>, other: vector<T>)
-
- - - -
-Implementation - - -
public fun append_all<T>(c: &mut Collection<T>, other: vector<T>) {
-    assert!(c.can_put, Errors::requires_address(ERR_COLLECTION_CAN_NOT_ADD));
-    Vector::append<T>(&mut c.items, other)
-}
-
- - - -
- - - -## Function `exists_at` - -check the Collection exists in addr - - -
public fun exists_at<T: store>(addr: address): bool
-
- - - -
-Implementation - - -
public fun exists_at<T: store>(addr: address): bool{
-    exists<CollectionStore<T>>(addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_accept` - -check addr is accept T and other can send T to addr, -it means exists a Collection of T at addr and anyone_can_put of the Collection is true - - -
public fun is_accept<T: store>(addr: address): bool
-
- - - -
-Implementation - - -
public fun is_accept<T: store>(addr: address): bool acquires CollectionStore {
-    if (!exists<CollectionStore<T>>(addr)){
-        return false
-    };
-    let cs = borrow_global<CollectionStore<T>>(addr);
-    cs.anyone_can_put
-}
-
- - - -
- - - -## Function `accept` - -signer allow other send T to self -create a Collection of T and set anyone_can_put to true -if the Collection exists, just update anyone_can_put to true - - -
public fun accept<T: store>(signer: &signer)
-
- - - -
-Implementation - - -
public fun accept<T: store>(signer: &signer) acquires CollectionStore {
-     let addr = Signer::address_of(signer);
-    if (!exists<CollectionStore<T>>(addr)){
-        Self::create_collection<T>(signer, true, false);
-    };
-    let cs = borrow_global_mut<CollectionStore<T>>(addr);
-    if (!cs.anyone_can_put) {
-        cs.anyone_can_put = true;
-    }
-}
-
- - - -
- - - -## Function `put` - -Put items to to_addr's Collection of T -put = borrow_collection + append + return_collection. - - -
public fun put<T: store>(signer: &signer, owner: address, item: T)
-
- - - -
-Implementation - - -
public fun put<T: store>(signer: &signer, owner: address, item: T) acquires CollectionStore{
-    let c = Self::borrow_collection(signer, owner);
-    Self::append(&mut c, item);
-    Self::return_collection(c);
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `put_all` - -Put all items to owner's collection of T. - - -
public fun put_all<T: store>(signer: &signer, owner: address, items: vector<T>)
-
- - - -
-Implementation - - -
public fun put_all<T: store>(signer: &signer, owner: address, items: vector<T>) acquires CollectionStore{
-    let c = Self::borrow_collection(signer, owner);
-    Self::append_all(&mut c, items);
-    Self::return_collection(c);
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `take` - -Take last item from signer's Collection of T. - - -
public fun take<T: store>(signer: &signer): T
-
- - - -
-Implementation - - -
public fun take<T: store>(signer: &signer): T acquires CollectionStore{
-    let addr = Signer::address_of(signer);
-    let c = borrow_collection<T>(signer, addr);
-    let item = pop_back(&mut c);
-    return_collection(c);
-    item
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `create_collection` - - - -
public fun create_collection<T: store>(signer: &signer, anyone_can_put: bool, anyone_can_mut: bool)
-
- - - -
-Implementation - - -
public fun create_collection<T:store>(signer: &signer, anyone_can_put: bool, anyone_can_mut: bool) {
-    move_to(signer, CollectionStore<T>{items: Option::some(Vector::empty<T>()), anyone_can_put, anyone_can_mut})
-}
-
- - - -
- - - -## Function `length_of` - -Return the length of Collection from owner, if collection do not exist, return 0. - - -
public fun length_of<T: store>(owner: address): u64
-
- - - -
-Implementation - - -
public fun length_of<T: store>(owner: address) : u64 acquires CollectionStore{
-    if (exists_at<T>(owner)){
-        let cs = borrow_global_mut<CollectionStore<T>>(owner);
-        //if items is None, indicate it is borrowed
-        assert!(!Option::is_none(&cs.items), Errors::invalid_state(ERR_COLLECTION_INVALID_BORROW_STATE));
-        let items = Option::borrow(&cs.items);
-        Vector::length(items)
-    }else{
-        0
-    }
-}
-
- - - -
- - - -## Function `borrow_collection` - -Borrow collection of T from owner, auto detected the collection's can_put|can_mut|can_take by the sender and Collection config. - - -
public fun borrow_collection<T: store>(sender: &signer, owner: address): Collection2::Collection<T>
-
- - - -
-Implementation - - -
public fun borrow_collection<T: store>(sender: &signer, owner: address): Collection<T> acquires CollectionStore{
-    assert!(exists_at<T>(owner), Errors::invalid_state(ERR_COLLECTION_NOT_EXIST));
-    let cs = borrow_global_mut<CollectionStore<T>>(owner);
-    //if items is None, indicate it is borrowed
-    assert!(!Option::is_none(&cs.items), Errors::invalid_state(ERR_COLLECTION_INVALID_BORROW_STATE));
-    let items = Option::extract(&mut cs.items);
-    let is_owner = owner == Signer::address_of(sender);
-    let can_put = cs.anyone_can_put || is_owner;
-    let can_mut = cs.anyone_can_mut || is_owner;
-    let can_take = is_owner;
-    Collection{
-        items,
-        owner,
-        can_put,
-        can_mut,
-        can_take,
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `return_collection` - -Return the Collection of T - - -
public fun return_collection<T: store>(c: Collection2::Collection<T>)
-
- - - -
-Implementation - - -
public fun return_collection<T: store>(c: Collection<T>) acquires CollectionStore{
-    let Collection{ items, owner, can_put:_, can_mut:_, can_take:_ } = c;
-    let cs = borrow_global_mut<CollectionStore<T>>(owner);
-    assert!(Option::is_none(&cs.items), Errors::invalid_state(ERR_COLLECTION_INVALID_BORROW_STATE));
-    Option::fill(&mut cs.items, items);
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `destroy_collection` - - - -
public fun destroy_collection<T: store>(signer: &signer)
-
- - - -
-Implementation - - -
public fun destroy_collection<T: store>(signer: &signer) acquires CollectionStore{
-    let c = move_from<CollectionStore<T>>(Signer::address_of(signer));
-    destroy_empty(c);
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `destroy_empty` - - - -
fun destroy_empty<T: store>(c: Collection2::CollectionStore<T>)
-
- - - -
-Implementation - - -
fun destroy_empty<T: store>(c: CollectionStore<T>){
-    let CollectionStore{ items, anyone_can_put:_, anyone_can_mut:_,} = c;
-    if (Option::is_some(&items)) {
-        let item_vec = Option::extract(&mut items);
-        assert!(Vector::is_empty(&item_vec), Errors::invalid_state(ERR_COLLECTION_IS_NOT_EMPTY));
-        Vector::destroy_empty(item_vec);
-        Option::destroy_none(items);
-    }else{
-        Option::destroy_none(items);
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = false;
-
diff --git a/release/v12/docs/Compare.md b/release/v12/docs/Compare.md deleted file mode 100644 index cd7ba32c..00000000 --- a/release/v12/docs/Compare.md +++ /dev/null @@ -1,341 +0,0 @@ - - - -# Module `0x1::Compare` - - - -- [Constants](#@Constants_0) -- [Function `cmp_bcs_bytes`](#0x1_Compare_cmp_bcs_bytes) -- [Function `cmp_bytes`](#0x1_Compare_cmp_bytes) -- [Function `cmp_u64`](#0x1_Compare_cmp_u64) -- [Function `is_equal`](#0x1_Compare_is_equal) -- [Function `is_less_than`](#0x1_Compare_is_less_than) -- [Function `is_greater_than`](#0x1_Compare_is_greater_than) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Vector;
-
- - - - - -## Constants - - - - - - -
const EQUAL: u8 = 0;
-
- - - - - - - -
const GREATER_THAN: u8 = 2;
-
- - - - - - - -
const LESS_THAN: u8 = 1;
-
- - - - - -## Function `cmp_bcs_bytes` - -Compare v1 and v2 using -(1) byte-by-byte comparison from right to left until we reach the end of the shorter vector, -then -(2) vector length to break ties. -Returns either EQUAL (0u8), LESS_THAN (1u8), or GREATER_THAN (2u8). -This function is designed to compare BCS (Starcoin Canonical Serialization)-encoded values -(i.e., vectors produced by BCS::to_bytes). A typical client will call -Compare::cmp_bcs_bytes(BCS::to_bytes(&t1), BCS::to_bytes(&t2)). The comparison provides the -following guarantees w.r.t the original values t1 and t2: -- cmp_bcs_bytes(bcs_ext(t1), bcs_ext(t2)) == LESS_THAN iff cmp_bcs_bytes(t2, t1) == GREATER_THAN -- Compare::cmp<T>(t1, t2) == EQUAL iff t1 == t2 and (similarly) -Compare::cmp<T>(t1, t2) != EQUAL iff t1 != t2, where == and != denote the Move -bytecode operations for polymorphic equality. -- for all primitive types T with < and > comparison operators exposed in Move bytecode -(u8, u64, u128), we have -compare_bcs_bytes(bcs_ext(t1), bcs_ext(t2)) == LESS_THAN iff t1 < t2 and (similarly) -compare_bcs_bytes(bcs_ext(t1), bcs_ext(t2)) == LESS_THAN iff t1 > t2. -For all other types, the order is whatever the BCS encoding of the type and the comparison -strategy above gives you. One case where the order might be surprising is the address type. -CoreAddresses are 16 byte hex values that BCS encodes with the identity function. The right to -left, byte-by-byte comparison means that (for example) -compare_bcs_bytes(bcs_ext(0x01), bcs_ext(0x10)) == LESS_THAN (as you'd expect), but -compare_bcs_bytes(bcs_ext(0x100), bcs_ext(0x001)) == LESS_THAN (as you probably wouldn't expect). -Keep this in mind when using this function to compare addresses. - - -
public fun cmp_bcs_bytes(v1: &vector<u8>, v2: &vector<u8>): u8
-
- - - -
-Implementation - - -
public fun cmp_bcs_bytes(v1: &vector<u8>, v2: &vector<u8>): u8 {
-    let i1 = Vector::length(v1);
-    let i2 = Vector::length(v2);
-    let len_cmp = cmp_u64(i1, i2);
-
-    // BCS uses little endian encoding for all integer types, so we choose to compare from left
-    // to right. Going right to left would make the behavior of Compare.cmp diverge from the
-    // bytecode operators < and > on integer values (which would be confusing).
-    while (i1 > 0 && i2 > 0) {
-        i1 = i1 - 1;
-        i2 = i2 - 1;
-        let v1 = *Vector::borrow(v1, i1);
-        let v2 = *Vector::borrow(v2, i2);
-        let elem_cmp = if (v1 == v2) EQUAL
-            else if (v1 < v2) LESS_THAN
-            else GREATER_THAN;
-        if (elem_cmp != 0) return elem_cmp
-        // else, compare next element
-    };
-    // all compared elements equal; use length comparison to break the tie
-    len_cmp
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `cmp_bytes` - - - -
public fun cmp_bytes(v1: &vector<u8>, v2: &vector<u8>): u8
-
- - - -
-Implementation - - -
public fun cmp_bytes(v1: &vector<u8>, v2: &vector<u8>): u8 {
-    let l1 = Vector::length(v1);
-    let l2 = Vector::length(v2);
-    let len_cmp = cmp_u64(l1, l2);
-    let i = 0;
-    while (i < l1 && i < l2) {
-        let v1 = *Vector::borrow(v1, i);
-        let v2 = *Vector::borrow(v2, i);
-        let elem_cmp = if (v1 == v2) EQUAL
-            else if (v1 < v2) LESS_THAN
-            else GREATER_THAN;
-        if (elem_cmp != 0) {
-            return elem_cmp
-        };
-        // else, compare next element
-        i = i + 1;
-    };
-    // all compared elements equal; use length comparison to break the tie
-    len_cmp
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `cmp_u64` - - - -
fun cmp_u64(i1: u64, i2: u64): u8
-
- - - -
-Implementation - - -
fun cmp_u64(i1: u64, i2: u64): u8 {
-    if (i1 == i2) EQUAL
-    else if (i1 < i2) LESS_THAN
-    else GREATER_THAN
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_equal` - - - -
public fun is_equal(result: u8): bool
-
- - - -
-Implementation - - -
public fun is_equal(result: u8): bool {
-    result == EQUAL
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_less_than` - - - -
public fun is_less_than(result: u8): bool
-
- - - -
-Implementation - - -
public fun is_less_than(result: u8): bool {
-    result == LESS_THAN
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_greater_than` - - - -
public fun is_greater_than(result: u8): bool
-
- - - -
-Implementation - - -
public fun is_greater_than(result: u8): bool {
-    result == GREATER_THAN
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Config.md b/release/v12/docs/Config.md deleted file mode 100644 index cdffd8bb..00000000 --- a/release/v12/docs/Config.md +++ /dev/null @@ -1,773 +0,0 @@ - - - -# Module `0x1::Config` - -The module provides a general implmentation of configuration for onchain contracts. - - -- [Resource `Config`](#0x1_Config_Config) -- [Struct `ModifyConfigCapability`](#0x1_Config_ModifyConfigCapability) -- [Resource `ModifyConfigCapabilityHolder`](#0x1_Config_ModifyConfigCapabilityHolder) -- [Struct `ConfigChangeEvent`](#0x1_Config_ConfigChangeEvent) -- [Constants](#@Constants_0) -- [Function `get_by_address`](#0x1_Config_get_by_address) -- [Function `config_exist_by_address`](#0x1_Config_config_exist_by_address) -- [Function `set`](#0x1_Config_set) -- [Function `set_with_capability`](#0x1_Config_set_with_capability) -- [Function `publish_new_config_with_capability`](#0x1_Config_publish_new_config_with_capability) -- [Function `publish_new_config`](#0x1_Config_publish_new_config) -- [Function `extract_modify_config_capability`](#0x1_Config_extract_modify_config_capability) -- [Function `restore_modify_config_capability`](#0x1_Config_restore_modify_config_capability) -- [Function `destroy_modify_config_capability`](#0x1_Config_destroy_modify_config_capability) -- [Function `account_address`](#0x1_Config_account_address) -- [Function `emit_config_change_event`](#0x1_Config_emit_config_change_event) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Option;
-use 0x1::Signer;
-
- - - - - -## Resource `Config` - -A generic singleton resource that holds a value of a specific type. - - -
struct Config<ConfigValue: copy, drop, store> has key
-
- - - -
-Fields - - -
-
-payload: ConfigValue -
-
- -
-
- - -
- - - -## Struct `ModifyConfigCapability` - -Accounts with this privilege can modify config of type ConfigValue under account_address - - -
struct ModifyConfigCapability<ConfigValue: copy, drop, store> has store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
-events: Event::EventHandle<Config::ConfigChangeEvent<ConfigValue>> -
-
- -
-
- - -
- - - -## Resource `ModifyConfigCapabilityHolder` - -A holder for ModifyConfigCapability, for extraction and restoration of ModifyConfigCapability. - - -
struct ModifyConfigCapabilityHolder<ConfigValue: copy, drop, store> has store, key
-
- - - -
-Fields - - -
-
-cap: Option::Option<Config::ModifyConfigCapability<ConfigValue>> -
-
- -
-
- - -
- - - -## Struct `ConfigChangeEvent` - -Event emitted when config value is changed. - - -
struct ConfigChangeEvent<ConfigValue: copy, drop, store> has drop, store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
-value: ConfigValue -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ECAPABILITY_HOLDER_NOT_EXISTS: u64 = 101;
-
- - - - - - - -
const ECONFIG_VALUE_DOES_NOT_EXIST: u64 = 13;
-
- - - - - -## Function `get_by_address` - -Get a copy of ConfigValue value stored under addr. - - -
public fun get_by_address<ConfigValue: copy, drop, store>(addr: address): ConfigValue
-
- - - -
-Implementation - - -
public fun get_by_address<ConfigValue: copy + drop + store>(addr: address): ConfigValue acquires Config {
-    assert!(exists<Config<ConfigValue>>(addr), Errors::invalid_state(ECONFIG_VALUE_DOES_NOT_EXIST));
-    *&borrow_global<Config<ConfigValue>>(addr).payload
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Config<ConfigValue>>(addr);
-ensures exists<Config<ConfigValue>>(addr);
-ensures result == spec_get<ConfigValue>(addr);
-
- - - -
- - - -## Function `config_exist_by_address` - -Check whether the config of ConfigValue type exists under addr. - - -
public fun config_exist_by_address<ConfigValue: copy, drop, store>(addr: address): bool
-
- - - -
-Implementation - - -
public fun config_exist_by_address<ConfigValue: copy + drop + store>(addr: address): bool {
-    exists<Config<ConfigValue>>(addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == exists<Config<ConfigValue>>(addr);
-
- - - -
- - - -## Function `set` - -Set a config item to a new value with capability stored under signer - - -
public fun set<ConfigValue: copy, drop, store>(account: &signer, payload: ConfigValue)
-
- - - -
-Implementation - - -
public fun set<ConfigValue: copy + drop + store>(
-    account: &signer,
-    payload: ConfigValue,
-) acquires Config, ModifyConfigCapabilityHolder {
-    let signer_address = Signer::address_of(account);
-    assert!(
-        exists<ModifyConfigCapabilityHolder<ConfigValue>>(signer_address),
-        Errors::requires_capability(ECAPABILITY_HOLDER_NOT_EXISTS),
-    );
-    let cap_holder = borrow_global_mut<ModifyConfigCapabilityHolder<ConfigValue>>(signer_address);
-    assert!(Option::is_some(&cap_holder.cap), Errors::requires_capability(ECAPABILITY_HOLDER_NOT_EXISTS));
-    set_with_capability(Option::borrow_mut(&mut cap_holder.cap), payload);
-}
-
- - - -
- -
-Specification - - - -
let addr = Signer::address_of(account);
-let cap_opt = spec_cap<ConfigValue>(addr);
-let cap = Option::borrow(spec_cap<ConfigValue>(Signer::address_of(account)));
-aborts_if !exists<ModifyConfigCapabilityHolder<ConfigValue>>(addr);
-aborts_if Option::is_none<ModifyConfigCapability<ConfigValue>>(cap_opt);
-ensures exists<ModifyConfigCapabilityHolder<ConfigValue>>(addr);
-pragma aborts_if_is_partial;
-ensures exists<Config<ConfigValue>>(
-    Option::borrow(spec_cap<ConfigValue>(Signer::address_of(account))).account_address,
-);
-ensures global<Config<ConfigValue>>(
-    Option::borrow(spec_cap<ConfigValue>(Signer::address_of(account))).account_address,
-).payload == payload;
-
- - - - - - - -
fun spec_cap<ConfigValue>(addr: address): Option<ModifyConfigCapability<ConfigValue>> {
-   global<ModifyConfigCapabilityHolder<ConfigValue>>(addr).cap
-}
-
- - - -
- - - -## Function `set_with_capability` - -Set a config item to a new value with cap. - - -
public fun set_with_capability<ConfigValue: copy, drop, store>(cap: &mut Config::ModifyConfigCapability<ConfigValue>, payload: ConfigValue)
-
- - - -
-Implementation - - -
public fun set_with_capability<ConfigValue: copy + drop + store>(
-    cap: &mut ModifyConfigCapability<ConfigValue>,
-    payload: ConfigValue,
-) acquires Config {
-    let addr = cap.account_address;
-    assert!(exists<Config<ConfigValue>>(addr), Errors::invalid_state(ECONFIG_VALUE_DOES_NOT_EXIST));
-    let config = borrow_global_mut<Config<ConfigValue>>(addr);
-    config.payload = copy payload;
-    emit_config_change_event(cap, payload);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Config<ConfigValue>>(cap.account_address);
-ensures exists<Config<ConfigValue>>(cap.account_address);
-ensures global<Config<ConfigValue>>(cap.account_address).payload == payload;
-
- - - -
- - - -## Function `publish_new_config_with_capability` - -Publish a new config item. The caller will use the returned ModifyConfigCapability to specify the access control -policy for who can modify the config. - - -
public fun publish_new_config_with_capability<ConfigValue: copy, drop, store>(account: &signer, payload: ConfigValue): Config::ModifyConfigCapability<ConfigValue>
-
- - - -
-Implementation - - -
public fun publish_new_config_with_capability<ConfigValue: copy + drop + store>(
-    account: &signer,
-    payload: ConfigValue,
-): ModifyConfigCapability<ConfigValue> acquires ModifyConfigCapabilityHolder{
-    publish_new_config<ConfigValue>(account, payload);
-    extract_modify_config_capability<ConfigValue>(account)
-}
-
- - - -
- -
-Specification - - - -
include PublishNewConfigAbortsIf<ConfigValue>;
-ensures exists<Config<ConfigValue>>(Signer::address_of(account));
-ensures global<Config<ConfigValue>>(Signer::address_of(account)).payload == payload;
-ensures exists<ModifyConfigCapabilityHolder<ConfigValue>>(Signer::address_of(account));
-ensures Option::is_none(global<ModifyConfigCapabilityHolder<ConfigValue>>(Signer::address_of(account)).cap);
-
- - - -
- - - -## Function `publish_new_config` - -Publish a new config item under account address. - - -
public fun publish_new_config<ConfigValue: copy, drop, store>(account: &signer, payload: ConfigValue)
-
- - - -
-Implementation - - -
public fun publish_new_config<ConfigValue: copy + drop + store>(account: &signer, payload: ConfigValue) {
-    move_to(account, Config<ConfigValue>{ payload });
-    let cap = ModifyConfigCapability<ConfigValue> {
-        account_address: Signer::address_of(account),
-        events: Event::new_event_handle<ConfigChangeEvent<ConfigValue>>(account),
-    };
-    move_to(account, ModifyConfigCapabilityHolder{cap: Option::some(cap)});
-}
-
- - - -
- -
-Specification - - - -
include PublishNewConfigAbortsIf<ConfigValue>;
-ensures exists<Config<ConfigValue>>(Signer::address_of(account));
-ensures global<Config<ConfigValue>>(Signer::address_of(account)).payload == payload;
-ensures exists<ModifyConfigCapabilityHolder<ConfigValue>>(Signer::address_of(account));
-ensures Option::is_some(global<ModifyConfigCapabilityHolder<ConfigValue>>(Signer::address_of(account)).cap);
-
- - - - - - - -
schema PublishNewConfigAbortsIf<ConfigValue> {
-    account: signer;
-    aborts_if exists<Config<ConfigValue>>(Signer::address_of(account));
-    aborts_if exists<ModifyConfigCapabilityHolder<ConfigValue>>(Signer::address_of(account));
-}
-
- - - - - - - -
schema AbortsIfConfigNotExist<ConfigValue> {
-    addr: address;
-    aborts_if !exists<Config<ConfigValue>>(addr);
-}
-
- - - - - - - -
schema AbortsIfConfigOrCapabilityNotExist<ConfigValue> {
-    addr: address;
-    aborts_if !exists<Config<ConfigValue>>(addr);
-    aborts_if !exists<ModifyConfigCapabilityHolder<ConfigValue>>(addr);
-}
-
- - - - - - - -
schema PublishNewConfigEnsures<ConfigValue> {
-    account: signer;
-    ensures exists<Config<ConfigValue>>(Signer::address_of(account));
-    ensures exists<ModifyConfigCapabilityHolder<ConfigValue>>(Signer::address_of(account));
-}
-
- - - - - - - -
schema AbortsIfCapNotExist<ConfigValue> {
-    address: address;
-    aborts_if !exists<ModifyConfigCapabilityHolder<ConfigValue>>(address);
-    aborts_if Option::is_none<ModifyConfigCapability<ConfigValue>>(
-        global<ModifyConfigCapabilityHolder<ConfigValue>>(address).cap,
-    );
-}
-
- - - -
- - - -## Function `extract_modify_config_capability` - -Extract account's ModifyConfigCapability for ConfigValue type - - -
public fun extract_modify_config_capability<ConfigValue: copy, drop, store>(account: &signer): Config::ModifyConfigCapability<ConfigValue>
-
- - - -
-Implementation - - -
public fun extract_modify_config_capability<ConfigValue: copy + drop + store>(
-    account: &signer,
-): ModifyConfigCapability<ConfigValue> acquires ModifyConfigCapabilityHolder {
-    let signer_address = Signer::address_of(account);
-    assert!(
-        exists<ModifyConfigCapabilityHolder<ConfigValue>>(signer_address),
-        Errors::requires_capability(ECAPABILITY_HOLDER_NOT_EXISTS)
-    );
-    let cap_holder = borrow_global_mut<ModifyConfigCapabilityHolder<ConfigValue>>(signer_address);
-    Option::extract(&mut cap_holder.cap)
-}
-
- - - -
- -
-Specification - - - -
let address = Signer::address_of(account);
-include AbortsIfCapNotExist<ConfigValue>;
-ensures exists<ModifyConfigCapabilityHolder<ConfigValue>>(address);
-ensures Option::is_none<ModifyConfigCapability<ConfigValue>>(
-    global<ModifyConfigCapabilityHolder<ConfigValue>>(address).cap
-);
-ensures result == old(Option::borrow(global<ModifyConfigCapabilityHolder<ConfigValue>>(address).cap));
-
- - - -
- - - -## Function `restore_modify_config_capability` - -Restore account's ModifyConfigCapability - - -
public fun restore_modify_config_capability<ConfigValue: copy, drop, store>(cap: Config::ModifyConfigCapability<ConfigValue>)
-
- - - -
-Implementation - - -
public fun restore_modify_config_capability<ConfigValue: copy + drop + store>(
-    cap: ModifyConfigCapability<ConfigValue>,
-) acquires ModifyConfigCapabilityHolder {
-    let cap_holder = borrow_global_mut<ModifyConfigCapabilityHolder<ConfigValue>>(cap.account_address);
-    Option::fill(&mut cap_holder.cap, cap);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ModifyConfigCapabilityHolder<ConfigValue>>(cap.account_address);
-aborts_if Option::is_some(global<ModifyConfigCapabilityHolder<ConfigValue>>(cap.account_address).cap);
-ensures exists<ModifyConfigCapabilityHolder<ConfigValue>>(cap.account_address);
-ensures Option::is_some(global<ModifyConfigCapabilityHolder<ConfigValue>>(cap.account_address).cap);
-ensures Option::borrow(global<ModifyConfigCapabilityHolder<ConfigValue>>(cap.account_address).cap) == cap;
-
- - - -
- - - -## Function `destroy_modify_config_capability` - -Destroy the given ModifyConfigCapability - - -
public fun destroy_modify_config_capability<ConfigValue: copy, drop, store>(cap: Config::ModifyConfigCapability<ConfigValue>)
-
- - - -
-Implementation - - -
public fun destroy_modify_config_capability<ConfigValue: copy + drop + store>(
-    cap: ModifyConfigCapability<ConfigValue>,
-) {
-    let ModifyConfigCapability{account_address:_, events} = cap;
-    Event::destroy_handle(events)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `account_address` - -Return the address of the given ModifyConfigCapability - - -
public fun account_address<ConfigValue: copy, drop, store>(cap: &Config::ModifyConfigCapability<ConfigValue>): address
-
- - - -
-Implementation - - -
public fun account_address<ConfigValue: copy + drop + store>(cap: &ModifyConfigCapability<ConfigValue>): address {
-    cap.account_address
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == cap.account_address;
-
- - - -
- - - -## Function `emit_config_change_event` - -Emit a config change event. - - -
fun emit_config_change_event<ConfigValue: copy, drop, store>(cap: &mut Config::ModifyConfigCapability<ConfigValue>, value: ConfigValue)
-
- - - -
-Implementation - - -
fun emit_config_change_event<ConfigValue: copy + drop + store>(
-    cap: &mut ModifyConfigCapability<ConfigValue>,
-    value: ConfigValue,
-) {
-    Event::emit_event<ConfigChangeEvent<ConfigValue>>(
-        &mut cap.events,
-        ConfigChangeEvent {
-            account_address: cap.account_address,
-            value,
-        },
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
- - - - - - - -
fun spec_get<ConfigValue>(addr: address): ConfigValue {
-   global<Config<ConfigValue>>(addr).payload
-}
-
diff --git a/release/v12/docs/ConfigProposalPlugin.md b/release/v12/docs/ConfigProposalPlugin.md deleted file mode 100644 index c4a1c97d..00000000 --- a/release/v12/docs/ConfigProposalPlugin.md +++ /dev/null @@ -1,287 +0,0 @@ - - - -# Module `0x1::ConfigProposalPlugin` - -Called by other contract which need proposal config - - -- [Struct `ConfigProposalPlugin`](#0x1_ConfigProposalPlugin_ConfigProposalPlugin) -- [Struct `ConfigProposalAction`](#0x1_ConfigProposalPlugin_ConfigProposalAction) -- [Function `initialize`](#0x1_ConfigProposalPlugin_initialize) -- [Function `required_caps`](#0x1_ConfigProposalPlugin_required_caps) -- [Function `create_proposal`](#0x1_ConfigProposalPlugin_create_proposal) -- [Function `execute_proposal`](#0x1_ConfigProposalPlugin_execute_proposal) -- [Function `execute_proposal_entry`](#0x1_ConfigProposalPlugin_execute_proposal_entry) -- [Function `install_plugin_proposal`](#0x1_ConfigProposalPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_ConfigProposalPlugin_install_plugin_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `ConfigProposalPlugin` - - - -
struct ConfigProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `ConfigProposalAction` - - - -
struct ConfigProposalAction<ConfigT> has drop, store
-
- - - -
-Fields - - -
-
-config: ConfigT -
-
- -
-
- - -
- - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = ConfigProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<ConfigProposalPlugin>(
-        &witness,
-        b"0x1::ConfigProposalPlugin",
-        b"The config proposal plugin",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<ConfigProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://config-proposal-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps(): vector<CapType> {
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_proposal` - - - -
public fun create_proposal<DAOT: store, ConfigT: drop, store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64, config: ConfigT)
-
- - - -
-Implementation - - -
public fun create_proposal<DAOT: store, ConfigT: store+drop>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>,action_delay: u64, config: ConfigT) {
-    let witness = ConfigProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, ConfigProposalPlugin>(&witness);
-    let action = ConfigProposalAction<ConfigT>{
-        config
-    };
-    DAOSpace::create_proposal<
-        DAOT,
-        ConfigProposalPlugin,
-        ConfigProposalAction<ConfigT>>(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `execute_proposal` - - - -
public fun execute_proposal<DAOT: store, ConfigT: copy, drop, store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_proposal<DAOT: store, ConfigT: copy + drop + store>(sender: &signer, proposal_id: u64) {
-    let witness = ConfigProposalPlugin{};
-    let proposal_cap =
-        DAOSpace::acquire_proposal_cap<DAOT, ConfigProposalPlugin>(&witness);
-    let modify_config_cap =
-        DAOSpace::acquire_modify_config_cap<DAOT, ConfigProposalPlugin>(&witness);
-
-    let ConfigProposalAction<ConfigT>{ config } = DAOSpace::execute_proposal<
-        DAOT,
-        ConfigProposalPlugin,
-        ConfigProposalAction<ConfigT>>(&proposal_cap, sender, proposal_id);
-    DAOSpace::set_custom_config<DAOT, ConfigProposalPlugin, ConfigT>(&mut modify_config_cap, config);
-}
-
- - - -
- - - -## Function `execute_proposal_entry` - - - -
public(script) fun execute_proposal_entry<DAOT: store, ConfigT: copy, drop, store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_proposal_entry<DAOT: store, ConfigT: copy + drop + store>(sender: signer, proposal_id: u64) {
-    execute_proposal<DAOT, ConfigT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT:store>(sender:&signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    InstallPluginProposalPlugin::create_proposal<DAOT, ConfigProposalPlugin>(sender, required_caps(), title, introduction, extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun install_plugin_proposal_entry<DAOT:store>(sender:signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/ConsensusConfig.md b/release/v12/docs/ConsensusConfig.md deleted file mode 100644 index fc33060d..00000000 --- a/release/v12/docs/ConsensusConfig.md +++ /dev/null @@ -1,700 +0,0 @@ - - - -# Module `0x1::ConsensusConfig` - -The module provide configuration of consensus parameters. - - -- [Struct `ConsensusConfig`](#0x1_ConsensusConfig_ConsensusConfig) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_ConsensusConfig_initialize) -- [Function `new_consensus_config`](#0x1_ConsensusConfig_new_consensus_config) -- [Function `get_config`](#0x1_ConsensusConfig_get_config) -- [Function `uncle_rate_target`](#0x1_ConsensusConfig_uncle_rate_target) -- [Function `base_block_time_target`](#0x1_ConsensusConfig_base_block_time_target) -- [Function `base_reward_per_block`](#0x1_ConsensusConfig_base_reward_per_block) -- [Function `epoch_block_count`](#0x1_ConsensusConfig_epoch_block_count) -- [Function `base_block_difficulty_window`](#0x1_ConsensusConfig_base_block_difficulty_window) -- [Function `base_reward_per_uncle_percent`](#0x1_ConsensusConfig_base_reward_per_uncle_percent) -- [Function `min_block_time_target`](#0x1_ConsensusConfig_min_block_time_target) -- [Function `max_block_time_target`](#0x1_ConsensusConfig_max_block_time_target) -- [Function `base_max_uncles_per_block`](#0x1_ConsensusConfig_base_max_uncles_per_block) -- [Function `base_block_gas_limit`](#0x1_ConsensusConfig_base_block_gas_limit) -- [Function `strategy`](#0x1_ConsensusConfig_strategy) -- [Function `compute_reward_per_block`](#0x1_ConsensusConfig_compute_reward_per_block) -- [Function `do_compute_reward_per_block`](#0x1_ConsensusConfig_do_compute_reward_per_block) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Math;
-use 0x1::Timestamp;
-
- - - - - -## Struct `ConsensusConfig` - -consensus configurations. - - -
struct ConsensusConfig has copy, drop, store
-
- - - -
-Fields - - -
-
-uncle_rate_target: u64 -
-
- Uncle block rate per epoch -
-
-base_block_time_target: u64 -
-
- Average target time to calculate a block's difficulty -
-
-base_reward_per_block: u128 -
-
- Rewards per block -
-
-base_reward_per_uncle_percent: u64 -
-
- Percentage of base_reward_per_block to reward a uncle block -
-
-epoch_block_count: u64 -
-
- Blocks each epoch -
-
-base_block_difficulty_window: u64 -
-
- How many ancestor blocks which use to calculate next block's difficulty -
-
-min_block_time_target: u64 -
-
- Minimum target time to calculate a block's difficulty -
-
-max_block_time_target: u64 -
-
- Maximum target time to calculate a block's difficulty -
-
-base_max_uncles_per_block: u64 -
-
- Maximum number of uncle block per block -
-
-base_block_gas_limit: u64 -
-
- Maximum gases per block -
-
-strategy: u8 -
-
- Strategy to calculate difficulty -
-
- - -
- - - -## Constants - - - - - - -
const EINVALID_ARGUMENT: u64 = 18;
-
- - - - - -## Function `initialize` - -Initialization of the module. - - -
public fun initialize(account: &signer, uncle_rate_target: u64, epoch_block_count: u64, base_block_time_target: u64, base_block_difficulty_window: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8)
-
- - - -
-Implementation - - -
public fun initialize(
-    account: &signer,
-    uncle_rate_target: u64,
-    epoch_block_count: u64,
-    base_block_time_target: u64,
-    base_block_difficulty_window: u64,
-    base_reward_per_block: u128,
-    base_reward_per_uncle_percent: u64,
-    min_block_time_target: u64,
-    max_block_time_target: u64,
-    base_max_uncles_per_block: u64,
-    base_block_gas_limit: u64,
-    strategy: u8,
-) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-
-    Config::publish_new_config<Self::ConsensusConfig>(
-        account,
-        new_consensus_config(
-            uncle_rate_target,
-            base_block_time_target,
-            base_reward_per_block,
-            base_reward_per_uncle_percent,
-            epoch_block_count,
-            base_block_difficulty_window,
-            min_block_time_target,
-            max_block_time_target,
-            base_max_uncles_per_block,
-            base_block_gas_limit,
-            strategy,
-        ),
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if uncle_rate_target == 0;
-aborts_if epoch_block_count == 0;
-aborts_if base_reward_per_block == 0;
-aborts_if base_block_time_target == 0;
-aborts_if base_block_difficulty_window == 0;
-aborts_if min_block_time_target == 0;
-aborts_if max_block_time_target < min_block_time_target;
-include Config::PublishNewConfigAbortsIf<ConsensusConfig>;
-include Config::PublishNewConfigEnsures<ConsensusConfig>;
-
- - - -
- - - -## Function `new_consensus_config` - -Create a new consensus config mainly used in DAO. - - -
public fun new_consensus_config(uncle_rate_target: u64, base_block_time_target: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, epoch_block_count: u64, base_block_difficulty_window: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8): ConsensusConfig::ConsensusConfig
-
- - - -
-Implementation - - -
public fun new_consensus_config(uncle_rate_target: u64,
-                                base_block_time_target: u64,
-                                base_reward_per_block: u128,
-                                base_reward_per_uncle_percent: u64,
-                                epoch_block_count: u64,
-                                base_block_difficulty_window: u64,
-                                min_block_time_target: u64,
-                                max_block_time_target: u64,
-                                base_max_uncles_per_block: u64,
-                                base_block_gas_limit: u64,
-                                strategy: u8,): ConsensusConfig {
-    assert!(uncle_rate_target > 0, Errors::invalid_argument(EINVALID_ARGUMENT));
-    assert!(base_block_time_target > 0, Errors::invalid_argument(EINVALID_ARGUMENT));
-    assert!(base_reward_per_block > 0, Errors::invalid_argument(EINVALID_ARGUMENT));
-    assert!(epoch_block_count > 0, Errors::invalid_argument(EINVALID_ARGUMENT));
-    assert!(base_block_difficulty_window > 0, Errors::invalid_argument(EINVALID_ARGUMENT));
-    // base_reward_per_uncle_percent can been zero.
-    assert!(min_block_time_target > 0, Errors::invalid_argument(EINVALID_ARGUMENT));
-    assert!(max_block_time_target >= min_block_time_target, Errors::invalid_argument(EINVALID_ARGUMENT));
-
-    ConsensusConfig {
-        uncle_rate_target,
-        base_block_time_target,
-        base_reward_per_block,
-        epoch_block_count,
-        base_block_difficulty_window,
-        base_reward_per_uncle_percent,
-        min_block_time_target,
-        max_block_time_target,
-        base_max_uncles_per_block,
-        base_block_gas_limit,
-        strategy,
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if uncle_rate_target == 0;
-aborts_if epoch_block_count == 0;
-aborts_if base_reward_per_block == 0;
-aborts_if base_block_time_target == 0;
-aborts_if base_block_difficulty_window == 0;
-aborts_if min_block_time_target == 0;
-aborts_if max_block_time_target < min_block_time_target;
-
- - - -
- - - -## Function `get_config` - -Get config data. - - -
public fun get_config(): ConsensusConfig::ConsensusConfig
-
- - - -
-Implementation - - -
public fun get_config(): ConsensusConfig {
-    Config::get_by_address<ConsensusConfig>(CoreAddresses::GENESIS_ADDRESS())
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Config::Config<ConsensusConfig>>(CoreAddresses::GENESIS_ADDRESS());
-
- - - - - - - -
fun spec_get_config(): ConsensusConfig {
-   global<Config::Config<ConsensusConfig>>(CoreAddresses::GENESIS_ADDRESS()).payload
-}
-
- - - -
- - - -## Function `uncle_rate_target` - -Get uncle_rate_target - - -
public fun uncle_rate_target(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun uncle_rate_target(config: &ConsensusConfig): u64 {
-    config.uncle_rate_target
-}
-
- - - -
- - - -## Function `base_block_time_target` - -Get base_block_time_target - - -
public fun base_block_time_target(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun base_block_time_target(config: &ConsensusConfig): u64 {
-    config.base_block_time_target
-}
-
- - - -
- - - -## Function `base_reward_per_block` - -Get base_reward_per_block - - -
public fun base_reward_per_block(config: &ConsensusConfig::ConsensusConfig): u128
-
- - - -
-Implementation - - -
public fun base_reward_per_block(config: &ConsensusConfig): u128 {
-    config.base_reward_per_block
-}
-
- - - -
- - - -## Function `epoch_block_count` - -Get epoch_block_count - - -
public fun epoch_block_count(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun epoch_block_count(config: &ConsensusConfig): u64 {
-    config.epoch_block_count
-}
-
- - - -
- - - -## Function `base_block_difficulty_window` - -Get base_block_difficulty_window - - -
public fun base_block_difficulty_window(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun base_block_difficulty_window(config: &ConsensusConfig): u64 {
-    config.base_block_difficulty_window
-}
-
- - - -
- - - -## Function `base_reward_per_uncle_percent` - -Get base_reward_per_uncle_percent - - -
public fun base_reward_per_uncle_percent(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun base_reward_per_uncle_percent(config: &ConsensusConfig): u64 {
-    config.base_reward_per_uncle_percent
-}
-
- - - -
- - - -## Function `min_block_time_target` - -Get min_block_time_target - - -
public fun min_block_time_target(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun min_block_time_target(config: &ConsensusConfig): u64 {
-    config.min_block_time_target
-}
-
- - - -
- - - -## Function `max_block_time_target` - -Get max_block_time_target - - -
public fun max_block_time_target(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun max_block_time_target(config: &ConsensusConfig): u64 {
-    config.max_block_time_target
-}
-
- - - -
- - - -## Function `base_max_uncles_per_block` - -Get base_max_uncles_per_block - - -
public fun base_max_uncles_per_block(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun base_max_uncles_per_block(config: &ConsensusConfig): u64 {
-    config.base_max_uncles_per_block
-}
-
- - - -
- - - -## Function `base_block_gas_limit` - -Get base_block_gas_limit - - -
public fun base_block_gas_limit(config: &ConsensusConfig::ConsensusConfig): u64
-
- - - -
-Implementation - - -
public fun base_block_gas_limit(config: &ConsensusConfig): u64 {
-    config.base_block_gas_limit
-}
-
- - - -
- - - -## Function `strategy` - -Get strategy - - -
public fun strategy(config: &ConsensusConfig::ConsensusConfig): u8
-
- - - -
-Implementation - - -
public fun strategy(config: &ConsensusConfig): u8 {
-    config.strategy
-}
-
- - - -
- - - -## Function `compute_reward_per_block` - -Compute block reward given the new_epoch_block_time_target. - - -
public fun compute_reward_per_block(new_epoch_block_time_target: u64): u128
-
- - - -
-Implementation - - -
public fun compute_reward_per_block(new_epoch_block_time_target: u64): u128 {
-    let config = get_config();
-    do_compute_reward_per_block(&config, new_epoch_block_time_target)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Config::Config<ConsensusConfig>>(CoreAddresses::GENESIS_ADDRESS());
-include Math::MulDivAbortsIf{x: spec_get_config().base_reward_per_block, y: new_epoch_block_time_target, z: spec_get_config().base_block_time_target};
-
- - - -
- - - -## Function `do_compute_reward_per_block` - -Compute block reward given the new_epoch_block_time_target, and the consensus config. - - -
public fun do_compute_reward_per_block(config: &ConsensusConfig::ConsensusConfig, new_epoch_block_time_target: u64): u128
-
- - - -
-Implementation - - -
public fun do_compute_reward_per_block(config: &ConsensusConfig, new_epoch_block_time_target: u64): u128 {
-    Math::mul_div(config.base_reward_per_block, (new_epoch_block_time_target as u128), (config.base_block_time_target as u128))
-}
-
- - - -
- -
-Specification - - - -
include Math::MulDivAbortsIf{x: config.base_reward_per_block, y: new_epoch_block_time_target, z: config.base_block_time_target};
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/ConsensusStrategy.md b/release/v12/docs/ConsensusStrategy.md deleted file mode 100644 index f8f72b50..00000000 --- a/release/v12/docs/ConsensusStrategy.md +++ /dev/null @@ -1,143 +0,0 @@ - - - -# Module `0x1::ConsensusStrategy` - -The module provides the information of current consensus strategy. - - -- [Struct `ConsensusStrategy`](#0x1_ConsensusStrategy_ConsensusStrategy) -- [Function `initialize`](#0x1_ConsensusStrategy_initialize) -- [Function `get`](#0x1_ConsensusStrategy_get) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Timestamp;
-
- - - - - -## Struct `ConsensusStrategy` - -ConsensusStrategy data. - - -
struct ConsensusStrategy has copy, drop, store
-
- - - -
-Fields - - -
-
-value: u8 -
-
- Value of strategy -
-
- - -
- - - -## Function `initialize` - -Publish the chain ID under the genesis account - - -
public fun initialize(account: &signer, consensus_strategy: u8)
-
- - - -
-Implementation - - -
public fun initialize(account: &signer, consensus_strategy: u8) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-    let cap = Config::publish_new_config_with_capability<ConsensusStrategy>(
-        account,
-        ConsensusStrategy { value:consensus_strategy }
-    );
-    //destroy the cap, so ConsensusStrategy can not been change.
-    Config::destroy_modify_config_capability(cap);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if exists<Config::Config<ConsensusStrategy>>(Signer::address_of(account));
-aborts_if exists<Config::ModifyConfigCapabilityHolder<ConsensusStrategy>>(Signer::address_of(account));
-ensures exists<Config::Config<ConsensusStrategy>>(Signer::address_of(account));
-
- - - -
- - - -## Function `get` - -Return the consensus strategy type of this chain - - -
public fun get(): u8
-
- - - -
-Implementation - - -
public fun get(): u8 {
-    Config::get_by_address<ConsensusStrategy>(CoreAddresses::GENESIS_ADDRESS()).value
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Config::Config<ConsensusStrategy>>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/CoreAddresses.md b/release/v12/docs/CoreAddresses.md deleted file mode 100644 index 70f433be..00000000 --- a/release/v12/docs/CoreAddresses.md +++ /dev/null @@ -1,178 +0,0 @@ - - - -# Module `0x1::CoreAddresses` - -The module provide addresses used in stdlib. - - -- [Constants](#@Constants_0) -- [Function `GENESIS_ADDRESS`](#0x1_CoreAddresses_GENESIS_ADDRESS) -- [Function `assert_genesis_address`](#0x1_CoreAddresses_assert_genesis_address) -- [Function `ASSOCIATION_ROOT_ADDRESS`](#0x1_CoreAddresses_ASSOCIATION_ROOT_ADDRESS) -- [Function `VM_RESERVED_ADDRESS`](#0x1_CoreAddresses_VM_RESERVED_ADDRESS) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Signer;
-
- - - - - -## Constants - - - - - - -
const ENOT_GENESIS_ACCOUNT: u64 = 11;
-
- - - - - -## Function `GENESIS_ADDRESS` - -The address of the genesis - - -
public fun GENESIS_ADDRESS(): address
-
- - - -
-Implementation - - -
public fun GENESIS_ADDRESS(): address {
-    @0x1
-}
-
- - - -
- - - -## Function `assert_genesis_address` - -Assert signer is genesis. - - -
public fun assert_genesis_address(account: &signer)
-
- - - -
-Implementation - - -
public fun assert_genesis_address(account: &signer) {
-    assert!(Signer::address_of(account) == GENESIS_ADDRESS(),
-            Errors::requires_address(ENOT_GENESIS_ACCOUNT))
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-include AbortsIfNotGenesisAddress;
-
- - -Specifies that a function aborts if the account does not have the Diem root address. - - - - - -
schema AbortsIfNotGenesisAddress {
-    account: signer;
-    aborts_if Signer::address_of(account) != GENESIS_ADDRESS();
-}
-
- - - -
- - - -## Function `ASSOCIATION_ROOT_ADDRESS` - -The address of the root association account. This account is -created in genesis, and cannot be changed. This address has -ultimate authority over the permissions granted (or removed) from -accounts on-chain. - - -
public fun ASSOCIATION_ROOT_ADDRESS(): address
-
- - - -
-Implementation - - -
public fun ASSOCIATION_ROOT_ADDRESS(): address {
-    @0xA550C18
-}
-
- - - -
- - - -## Function `VM_RESERVED_ADDRESS` - -The reserved address for transactions inserted by the VM into blocks (e.g. -block metadata transactions). Because the transaction is sent from -the VM, an account _cannot_ exist at the 0x0 address since there -is no signer for the transaction. - - -
public fun VM_RESERVED_ADDRESS(): address
-
- - - -
-Implementation - - -
public fun VM_RESERVED_ADDRESS(): address {
-    @0x0
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/DAOAccount.md b/release/v12/docs/DAOAccount.md deleted file mode 100644 index e3f02ff0..00000000 --- a/release/v12/docs/DAOAccount.md +++ /dev/null @@ -1,440 +0,0 @@ - - - -# Module `0x1::DAOAccount` - - - -- [Resource `DAOAccount`](#0x1_DAOAccount_DAOAccount) -- [Resource `DAOAccountCap`](#0x1_DAOAccount_DAOAccountCap) -- [Constants](#@Constants_0) -- [Function `create_account`](#0x1_DAOAccount_create_account) -- [Function `create_account_entry`](#0x1_DAOAccount_create_account_entry) -- [Function `extract_dao_account_cap`](#0x1_DAOAccount_extract_dao_account_cap) -- [Function `restore_dao_account_cap`](#0x1_DAOAccount_restore_dao_account_cap) -- [Function `upgrade_to_dao`](#0x1_DAOAccount_upgrade_to_dao) -- [Function `upgrade_to_dao_with_signer_cap`](#0x1_DAOAccount_upgrade_to_dao_with_signer_cap) -- [Function `upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap`](#0x1_DAOAccount_upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap) -- [Function `dao_signer`](#0x1_DAOAccount_dao_signer) -- [Function `submit_upgrade_plan`](#0x1_DAOAccount_submit_upgrade_plan) -- [Function `submit_upgrade_plan_entry`](#0x1_DAOAccount_submit_upgrade_plan_entry) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Account;
-use 0x1::Config;
-use 0x1::Errors;
-use 0x1::Option;
-use 0x1::PackageTxnManager;
-use 0x1::Signer;
-use 0x1::Version;
-
- - - - - -## Resource `DAOAccount` - -DAOAccount - - -
struct DAOAccount has key
-
- - - -
-Fields - - -
-
-dao_address: address -
-
- -
-
-signer_cap: Account::SignerCapability -
-
- -
-
-upgrade_plan_cap: PackageTxnManager::UpgradePlanCapability -
-
- -
-
- - -
- - - -## Resource `DAOAccountCap` - -This capability can control the DAO account - - -
struct DAOAccountCap has store, key
-
- - - -
-Fields - - -
-
-dao_address: address -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_ACCOUNT_CAP_EXISTS: u64 = 101;
-
- - - - - - - -
const ERR_ACCOUNT_CAP_NOT_EXISTS: u64 = 100;
-
- - - - - - - -
const ERR_ACCOUNT_IS_NOT_SAME: u64 = 102;
-
- - - - - - - -
const ERR_UPGARDE_PLAN_CAP_NOT_EXISTS: u64 = 103;
-
- - - - - -## Function `create_account` - -Create a new DAO Account and return DAOAccountCap -DAO Account is a delegate account, the creator has the DAOAccountCap - - -
public fun create_account(creator: &signer): DAOAccount::DAOAccountCap
-
- - - -
-Implementation - - -
public fun create_account(creator: &signer): DAOAccountCap {
-    let (_dao_address, signer_cap) = Account::create_delegate_account(creator);
-    upgrade_to_dao_with_signer_cap(signer_cap)
-}
-
- - - -
- - - -## Function `create_account_entry` - -Entry function for create dao account, the DAOAccountCap save to the creator account - - -
public(script) fun create_account_entry(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun create_account_entry(sender: signer){
-    let cap = create_account(&sender);
-    assert!(!exists<DAOAccountCap>(Signer::address_of(&sender)), Errors::already_published(ERR_ACCOUNT_CAP_EXISTS));
-    move_to(&sender, cap);
-}
-
- - - -
- - - -## Function `extract_dao_account_cap` - -Extract the DAOAccountCap from the sender - - -
public fun extract_dao_account_cap(sender: &signer): DAOAccount::DAOAccountCap
-
- - - -
-Implementation - - -
public fun extract_dao_account_cap(sender: &signer): DAOAccountCap acquires DAOAccountCap {
-    let sender_addr = Signer::address_of(sender);
-    assert!(exists<DAOAccountCap>(sender_addr), Errors::not_published(ERR_ACCOUNT_CAP_NOT_EXISTS));
-    move_from<DAOAccountCap>(sender_addr)
-}
-
- - - -
- - - -## Function `restore_dao_account_cap` - -Restore the DAOAccountCap to the sender - - -
public fun restore_dao_account_cap(sender: &signer, cap: DAOAccount::DAOAccountCap)
-
- - - -
-Implementation - - -
public fun restore_dao_account_cap(sender: &signer, cap: DAOAccountCap) {
-    let sender_addr = Signer::address_of(sender);
-    assert!(!exists<DAOAccountCap>(sender_addr), Errors::already_published(ERR_ACCOUNT_CAP_EXISTS));
-    move_to(sender, cap)
-}
-
- - - -
- - - -## Function `upgrade_to_dao` - -Upgrade sender account to DAO account - - -
public fun upgrade_to_dao(sender: signer): DAOAccount::DAOAccountCap
-
- - - -
-Implementation - - -
public fun upgrade_to_dao(sender: signer): DAOAccountCap {
-    let signer_cap = Account::remove_signer_capability(&sender);
-    upgrade_to_dao_with_signer_cap(signer_cap)
-}
-
- - - -
- - - -## Function `upgrade_to_dao_with_signer_cap` - -Upgrade the account which have the signer_cap to a DAO Account - - -
public fun upgrade_to_dao_with_signer_cap(signer_cap: Account::SignerCapability): DAOAccount::DAOAccountCap
-
- - - -
-Implementation - - -
public fun upgrade_to_dao_with_signer_cap(signer_cap: SignerCapability): DAOAccountCap {
-    let dao_signer = Account::create_signer_with_cap(&signer_cap);
-    let dao_address = Signer::address_of(&dao_signer);
-
-    let upgrade_plan_cap = if(Config::config_exist_by_address<Version::Version>(dao_address)){
-        assert!(PackageTxnManager::exists_upgrade_plan_cap(dao_address), Errors::not_published(ERR_UPGARDE_PLAN_CAP_NOT_EXISTS));
-        PackageTxnManager::extract_submit_upgrade_plan_cap(&dao_signer)
-    }else{
-        Config::publish_new_config<Version::Version>(&dao_signer, Version::new_version(1));
-        PackageTxnManager::update_module_upgrade_strategy(&dao_signer, PackageTxnManager::get_strategy_two_phase(), Option::some(1));
-        PackageTxnManager::extract_submit_upgrade_plan_cap(&dao_signer)
-    };
-    upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap, upgrade_plan_cap)
-}
-
- - - -
- - - -## Function `upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap` - -Upgrade the account which have the signer_cap to a DAO Account - - -
public fun upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap: Account::SignerCapability, upgrade_plan_cap: PackageTxnManager::UpgradePlanCapability): DAOAccount::DAOAccountCap
-
- - - -
-Implementation - - -
public fun upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap: SignerCapability, upgrade_plan_cap:UpgradePlanCapability): DAOAccountCap {
-    let dao_signer = Account::create_signer_with_cap(&signer_cap);
-    let dao_address = Signer::address_of(&dao_signer);
-
-    assert!(Account::signer_address(&signer_cap) == PackageTxnManager::account_address(&upgrade_plan_cap), Errors::already_published(ERR_ACCOUNT_IS_NOT_SAME));
-
-    move_to(&dao_signer, DAOAccount{
-        dao_address,
-        signer_cap,
-        upgrade_plan_cap,
-    });
-
-    DAOAccountCap{
-        dao_address
-    }
-}
-
- - - -
- - - -## Function `dao_signer` - -Provide a function to create signer with DAOAccountCap - - -
public fun dao_signer(cap: &DAOAccount::DAOAccountCap): signer
-
- - - -
-Implementation - - -
public fun dao_signer(cap: &DAOAccountCap): signer acquires DAOAccount {
-    let signer_cap = &borrow_global<DAOAccount>(cap.dao_address).signer_cap;
-    Account::create_signer_with_cap(signer_cap)
-}
-
- - - -
- - - -## Function `submit_upgrade_plan` - -Sumbit upgrade plan for the DAO account -This function is a shortcut for create signer with DAOAccountCap and invoke PackageTxnManager::submit_upgrade_plan_v2 - - -
public fun submit_upgrade_plan(cap: &DAOAccount::DAOAccountCap, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public fun submit_upgrade_plan(cap: &DAOAccountCap, package_hash: vector<u8>, version:u64, enforced: bool) acquires DAOAccount{
-    let upgrade_plan_cap = &borrow_global<DAOAccount>(cap.dao_address).upgrade_plan_cap;
-    PackageTxnManager::submit_upgrade_plan_with_cap_v2(upgrade_plan_cap, package_hash, version, enforced);
-}
-
- - - -
- - - -## Function `submit_upgrade_plan_entry` - -Sumbit upgrade plan for the DAO account, sender must hold the DAOAccountCap - - -
public(script) fun submit_upgrade_plan_entry(sender: signer, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public(script) fun submit_upgrade_plan_entry(sender: signer, package_hash: vector<u8>, version:u64, enforced: bool) acquires DAOAccount, DAOAccountCap{
-    let addr = Signer::address_of(&sender);
-    let cap = borrow_global<DAOAccountCap>(addr);
-    submit_upgrade_plan(cap, package_hash, version, enforced)
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/DAOExtensionPoint.md b/release/v12/docs/DAOExtensionPoint.md deleted file mode 100644 index 68fef6bb..00000000 --- a/release/v12/docs/DAOExtensionPoint.md +++ /dev/null @@ -1,1435 +0,0 @@ - - - -# Module `0x1::DAOExtensionPoint` - - - -- [Struct `Version`](#0x1_DAOExtensionPoint_Version) -- [Resource `Registry`](#0x1_DAOExtensionPoint_Registry) -- [Resource `Entry`](#0x1_DAOExtensionPoint_Entry) -- [Resource `Star`](#0x1_DAOExtensionPoint_Star) -- [Struct `OwnerNFTMeta`](#0x1_DAOExtensionPoint_OwnerNFTMeta) -- [Struct `OwnerNFTBody`](#0x1_DAOExtensionPoint_OwnerNFTBody) -- [Resource `NFTMintCapHolder`](#0x1_DAOExtensionPoint_NFTMintCapHolder) -- [Resource `RegistryEventHandlers`](#0x1_DAOExtensionPoint_RegistryEventHandlers) -- [Struct `ExtensionPointRegisterEvent`](#0x1_DAOExtensionPoint_ExtensionPointRegisterEvent) -- [Resource `ExtensionPointEventHandlers`](#0x1_DAOExtensionPoint_ExtensionPointEventHandlers) -- [Struct `PublishVersionEvent`](#0x1_DAOExtensionPoint_PublishVersionEvent) -- [Struct `StarEvent`](#0x1_DAOExtensionPoint_StarEvent) -- [Struct `UnstarEvent`](#0x1_DAOExtensionPoint_UnstarEvent) -- [Struct `UpdateInfoEvent`](#0x1_DAOExtensionPoint_UpdateInfoEvent) -- [Constants](#@Constants_0) -- [Function `next_extpoint_id`](#0x1_DAOExtensionPoint_next_extpoint_id) -- [Function `next_extpoint_version_number`](#0x1_DAOExtensionPoint_next_extpoint_version_number) -- [Function `has_extpoint_nft`](#0x1_DAOExtensionPoint_has_extpoint_nft) -- [Function `ensure_exists_extpoint_nft`](#0x1_DAOExtensionPoint_ensure_exists_extpoint_nft) -- [Function `assert_tag_no_repeat`](#0x1_DAOExtensionPoint_assert_tag_no_repeat) -- [Function `assert_string_length`](#0x1_DAOExtensionPoint_assert_string_length) -- [Function `assert_string_array_length`](#0x1_DAOExtensionPoint_assert_string_array_length) -- [Function `initialize`](#0x1_DAOExtensionPoint_initialize) -- [Function `register`](#0x1_DAOExtensionPoint_register) -- [Function `publish_version`](#0x1_DAOExtensionPoint_publish_version) -- [Function `update`](#0x1_DAOExtensionPoint_update) -- [Function `has_star_plugin`](#0x1_DAOExtensionPoint_has_star_plugin) -- [Function `star`](#0x1_DAOExtensionPoint_star) -- [Function `unstar`](#0x1_DAOExtensionPoint_unstar) -- [Function `register_entry`](#0x1_DAOExtensionPoint_register_entry) -- [Function `publish_version_entry`](#0x1_DAOExtensionPoint_publish_version_entry) -- [Function `update_entry`](#0x1_DAOExtensionPoint_update_entry) -- [Function `star_entry`](#0x1_DAOExtensionPoint_star_entry) -- [Function `unstar_entry`](#0x1_DAOExtensionPoint_unstar_entry) - - -
use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::GenesisSignerCapability;
-use 0x1::NFT;
-use 0x1::NFTGallery;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::TypeInfo;
-use 0x1::Vector;
-
- - - - - -## Struct `Version` - - - -
struct Version has store
-
- - - -
-Fields - - -
-
-number: u64 -
-
- -
-
-tag: vector<u8> -
-
- -
-
-types_d_ts: vector<u8> -
-
- -
-
-document: vector<u8> -
-
- -
-
-created_at: u64 -
-
- -
-
- - -
- - - -## Resource `Registry` - - - -
struct Registry has store, key
-
- - - -
-Fields - - -
-
-next_id: u64 -
-
- -
-
- - -
- - - -## Resource `Entry` - - - -
struct Entry<ExtPointT> has store, key
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-labels: vector<vector<u8>> -
-
- -
-
-next_version_number: u64 -
-
- -
-
-versions: vector<DAOExtensionPoint::Version> -
-
- -
-
-star_count: u64 -
-
- -
-
-created_at: u64 -
-
- -
-
-updated_at: u64 -
-
- -
-
- - -
- - - -## Resource `Star` - - - -
struct Star<ExtPointT> has store, key
-
- - - -
-Fields - - -
-
-created_at: u64 -
-
- -
-
- - -
- - - -## Struct `OwnerNFTMeta` - - - -
struct OwnerNFTMeta has copy, drop, store
-
- - - -
-Fields - - -
-
-extpoint_id: u64 -
-
- -
-
-registry_address: address -
-
- -
-
- - -
- - - -## Struct `OwnerNFTBody` - - - -
struct OwnerNFTBody has store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `NFTMintCapHolder` - - - -
struct NFTMintCapHolder has key
-
- - - -
-Fields - - -
-
-cap: NFT::MintCapability<DAOExtensionPoint::OwnerNFTMeta> -
-
- -
-
-nft_metadata: NFT::Metadata -
-
- -
-
- - -
- - - -## Resource `RegistryEventHandlers` - -registry event handlers - - -
struct RegistryEventHandlers has store, key
-
- - - -
-Fields - - -
-
-register: Event::EventHandle<DAOExtensionPoint::ExtensionPointRegisterEvent> -
-
- -
-
- - -
- - - -## Struct `ExtensionPointRegisterEvent` - - - -
struct ExtensionPointRegisterEvent has drop, store
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-type: TypeInfo::TypeInfo -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-labels: vector<vector<u8>> -
-
- -
-
- - -
- - - -## Resource `ExtensionPointEventHandlers` - -extension point event handlers - - -
struct ExtensionPointEventHandlers<PluginT> has store, key
-
- - - -
-Fields - - -
-
-publish_version: Event::EventHandle<DAOExtensionPoint::PublishVersionEvent<PluginT>> -
-
- -
-
-star: Event::EventHandle<DAOExtensionPoint::StarEvent<PluginT>> -
-
- -
-
-unstar: Event::EventHandle<DAOExtensionPoint::UnstarEvent<PluginT>> -
-
- -
-
-update: Event::EventHandle<DAOExtensionPoint::UpdateInfoEvent<PluginT>> -
-
- -
-
- - -
- - - -## Struct `PublishVersionEvent` - - - -
struct PublishVersionEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-sender: address -
-
- -
-
-version_number: u64 -
-
- -
-
- - -
- - - -## Struct `StarEvent` - - - -
struct StarEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-sender: address -
-
- -
-
- - -
- - - -## Struct `UnstarEvent` - - - -
struct UnstarEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-sender: address -
-
- -
-
- - -
- - - -## Struct `UpdateInfoEvent` - - - -
struct UpdateInfoEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-sender: address -
-
- -
-
-id: u64 -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-labels: vector<vector<u8>> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_ALREADY_INITIALIZED: u64 = 100;
-
- - - - - - - -
const ERR_ITEMS_COUNT_LIMIT: u64 = 109;
-
- - - - - - - -
const ERR_NOT_CONTRACT_OWNER: u64 = 101;
-
- - - - - - - -
const ERR_STAR_ALREADY_STARED: u64 = 105;
-
- - - - - - - -
const ERR_STAR_NOT_FOUND_STAR: u64 = 106;
-
- - - - - - - -
const ERR_STRING_TOO_LONG: u64 = 110;
-
- - - - - - - -
const ERR_TAG_DUPLICATED: u64 = 107;
-
- - - - - - - -
const ERR_VERSION_COUNT_LIMIT: u64 = 108;
-
- - - - - - - -
const MAX_INPUT_LEN: u64 = 64;
-
- - - - - - - -
const MAX_TEXT_LEN: u64 = 256;
-
- - - - - - - -
const MAX_VERSION_COUNT: u64 = 256;
-
- - - - - - - -
const ERR_ALREADY_REGISTERED: u64 = 104;
-
- - - - - - - -
const ERR_EXPECT_EXT_POINT_NFT: u64 = 102;
-
- - - - - - - -
const ERR_NOT_FOUND_EXT_POINT: u64 = 103;
-
- - - - - - - -
const MAX_LABELS_COUNT: u64 = 20;
-
- - - - - -## Function `next_extpoint_id` - - - -
fun next_extpoint_id(registry: &mut DAOExtensionPoint::Registry): u64
-
- - - -
-Implementation - - -
fun next_extpoint_id(registry: &mut Registry): u64 {
-    let extpoint_id = registry.next_id;
-    registry.next_id = extpoint_id + 1;
-    extpoint_id
-}
-
- - - -
- - - -## Function `next_extpoint_version_number` - - - -
fun next_extpoint_version_number<ExtPointT: store>(extpoint: &mut DAOExtensionPoint::Entry<ExtPointT>): u64
-
- - - -
-Implementation - - -
fun next_extpoint_version_number<ExtPointT: store>(extpoint: &mut Entry<ExtPointT>): u64 {
-    let version_number = extpoint.next_version_number;
-    extpoint.next_version_number = version_number + 1;
-    version_number
-}
-
- - - -
- - - -## Function `has_extpoint_nft` - - - -
fun has_extpoint_nft(sender_addr: address, extpoint_id: u64): bool
-
- - - -
-Implementation - - -
fun has_extpoint_nft(sender_addr: address, extpoint_id: u64): bool {
-    if (!NFTGallery::is_accept<OwnerNFTMeta, OwnerNFTBody>(sender_addr)) {
-        return false
-    };
-
-    let nft_infos = NFTGallery::get_nft_infos<OwnerNFTMeta, OwnerNFTBody>(sender_addr);
-    let len = Vector::length(&nft_infos);
-    if (len == 0) {
-        return false
-    };
-
-    let idx = len - 1;
-    loop {
-        let nft_info = Vector::borrow(&nft_infos, idx);
-        let (_, _, _, type_meta) = NFT::unpack_info<OwnerNFTMeta>(*nft_info);
-        if (type_meta.extpoint_id == extpoint_id) {
-            return true
-        };
-
-        if (idx == 0) {
-            return false
-        };
-
-        idx = idx - 1;
-    }
-}
-
- - - -
- - - -## Function `ensure_exists_extpoint_nft` - - - -
fun ensure_exists_extpoint_nft(sender_addr: address, extpoint_id: u64)
-
- - - -
-Implementation - - -
fun ensure_exists_extpoint_nft(sender_addr: address, extpoint_id: u64) {
-    assert!(has_extpoint_nft(sender_addr, extpoint_id), Errors::invalid_state(ERR_EXPECT_EXT_POINT_NFT));
-}
-
- - - -
- - - -## Function `assert_tag_no_repeat` - - - -
fun assert_tag_no_repeat(v: &vector<DAOExtensionPoint::Version>, tag: vector<u8>)
-
- - - -
-Implementation - - -
fun assert_tag_no_repeat(v: &vector<Version>, tag:vector<u8>) {
-    let i = 0;
-    let len = Vector::length(v);
-    while (i < len) {
-        let e = Vector::borrow(v, i);
-        assert!(*&e.tag != *&tag, Errors::invalid_argument(ERR_TAG_DUPLICATED));
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `assert_string_length` - - - -
fun assert_string_length(s: &vector<u8>, max_len: u64)
-
- - - -
-Implementation - - -
fun assert_string_length(s: &vector<u8>, max_len: u64) {
-    let len = Vector::length(s);
-    assert!(len <= max_len, Errors::invalid_argument(ERR_STRING_TOO_LONG));
-}
-
- - - -
- - - -## Function `assert_string_array_length` - - - -
fun assert_string_array_length(v: &vector<vector<u8>>, max_item_len: u64, max_string_len: u64)
-
- - - -
-Implementation - - -
fun assert_string_array_length(v: &vector<vector<u8>>, max_item_len: u64, max_string_len: u64) {
-    assert!(Vector::length(v) <= max_item_len, Errors::limit_exceeded(ERR_ITEMS_COUNT_LIMIT));
-
-    let i = 0;
-    let len = Vector::length(v);
-    while (i < len) {
-        let e = Vector::borrow(v, i);
-        assert_string_length(e, max_string_len);
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `initialize` - - - -
public fun initialize()
-
- - - -
-Implementation - - -
public fun initialize() {
-    assert!(!exists<Registry>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED));
-    let signer = GenesisSignerCapability::get_genesis_signer();
-
-    let nft_name = b"ExtPointOwnerNFT";
-    let nft_image = b"ipfs://QmdTwdhFi61zhRM3MtPLxuKyaqv3ePECLGsMg9pMrePv4i";
-    let nft_description = b"The extension point owner NFT";
-    let basemeta = NFT::new_meta_with_image_data(nft_name, nft_image, nft_description);
-    let basemeta_bak = *&basemeta;
-    NFT::register_v2<OwnerNFTMeta>(&signer, basemeta);
-
-    let nft_mint_cap = NFT::remove_mint_capability<OwnerNFTMeta>(&signer);
-    move_to(&signer, NFTMintCapHolder{
-        cap: nft_mint_cap,
-        nft_metadata: basemeta_bak,
-    });
-
-    move_to(&signer, Registry{
-        next_id: 1,
-    });
-
-    move_to(&signer, RegistryEventHandlers {
-        register: Event::new_event_handle<ExtensionPointRegisterEvent>(&signer),
-    });
-}
-
- - - -
- - - -## Function `register` - - - -
public fun register<ExtPointT: store>(sender: &signer, name: vector<u8>, description: vector<u8>, types_d_ts: vector<u8>, dts_doc: vector<u8>, option_labels: Option::Option<vector<vector<u8>>>): u64
-
- - - -
-Implementation - - -
public fun register<ExtPointT: store>(sender: &signer, name: vector<u8>, description: vector<u8>, types_d_ts:vector<u8>, dts_doc:vector<u8>,
-    option_labels: Option<vector<vector<u8>>>):u64 acquires Registry, NFTMintCapHolder, RegistryEventHandlers {
-    assert_string_length(&name, MAX_INPUT_LEN);
-    assert_string_length(&description, MAX_TEXT_LEN);
-    assert_string_length(&types_d_ts, MAX_TEXT_LEN);
-    assert_string_length(&dts_doc, MAX_TEXT_LEN);
-
-    assert!(!exists<Entry<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_REGISTERED));
-    let registry = borrow_global_mut<Registry>(CoreAddresses::GENESIS_ADDRESS());
-    let extpoint_id = next_extpoint_id(registry);
-
-    let version = Version {
-        number: 1,
-        tag: b"v0.1.0",
-        types_d_ts: types_d_ts,
-        document: dts_doc,
-        created_at: Timestamp::now_seconds(),
-    };
-
-    let labels = if(Option::is_some(&option_labels)){
-        Option::destroy_some(option_labels)
-    } else {
-        Vector::empty<vector<u8>>()
-    };
-
-    assert_string_array_length(&labels, MAX_LABELS_COUNT, MAX_INPUT_LEN);
-
-    let genesis_account = GenesisSignerCapability::get_genesis_signer();
-    move_to(&genesis_account, Entry<ExtPointT>{
-        id: copy extpoint_id,
-        name: copy name,
-        description: copy description,
-        labels: copy labels,
-        next_version_number: 2,
-        versions: Vector::singleton<Version>(version),
-        star_count: 0,
-        created_at: Timestamp::now_seconds(),
-        updated_at: Timestamp::now_seconds(),
-    });
-
-    move_to(&genesis_account, ExtensionPointEventHandlers<ExtPointT>{
-        publish_version: Event::new_event_handle<PublishVersionEvent<ExtPointT>>(&genesis_account),
-        star: Event::new_event_handle<StarEvent<ExtPointT>>(&genesis_account),
-        unstar: Event::new_event_handle<UnstarEvent<ExtPointT>>(&genesis_account),
-        update: Event::new_event_handle<UpdateInfoEvent<ExtPointT>>(&genesis_account),
-    });
-
-    // grant owner NFT to sender
-    let nft_mint_cap = borrow_global_mut<NFTMintCapHolder>(CoreAddresses::GENESIS_ADDRESS());
-    let meta = OwnerNFTMeta{
-        registry_address: CoreAddresses::GENESIS_ADDRESS(),
-        extpoint_id: extpoint_id,
-    };
-
-    let nft = NFT::mint_with_cap_v2(CoreAddresses::GENESIS_ADDRESS(), &mut nft_mint_cap.cap, *&nft_mint_cap.nft_metadata, meta, OwnerNFTBody{});
-    NFTGallery::deposit(sender, nft);
-
-    // registry register event emit
-    let registry_event_handlers = borrow_global_mut<RegistryEventHandlers>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut registry_event_handlers.register,
-        ExtensionPointRegisterEvent {
-            id: copy extpoint_id,
-            type: TypeInfo::type_of<ExtPointT>(),
-            name: copy name,
-            description: copy description,
-            labels: copy labels,
-        },
-    );
-
-    extpoint_id
-}
-
- - - -
- - - -## Function `publish_version` - - - -
public fun publish_version<ExtPointT: store>(sender: &signer, tag: vector<u8>, types_d_ts: vector<u8>, dts_doc: vector<u8>)
-
- - - -
-Implementation - - -
public fun publish_version<ExtPointT: store>(
-    sender: &signer,
-    tag: vector<u8>,
-    types_d_ts:vector<u8>,
-    dts_doc: vector<u8>,
-) acquires Entry, ExtensionPointEventHandlers {
-    assert_string_length(&tag, MAX_INPUT_LEN);
-    assert_string_length(&types_d_ts, MAX_TEXT_LEN);
-    assert_string_length(&dts_doc, MAX_TEXT_LEN);
-
-    let sender_addr = Signer::address_of(sender);
-    let extp = borrow_global_mut<Entry<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-
-    ensure_exists_extpoint_nft(sender_addr, extp.id);
-    assert!(Vector::length(&extp.versions) <= MAX_VERSION_COUNT, Errors::limit_exceeded(ERR_VERSION_COUNT_LIMIT));
-    assert_tag_no_repeat(&extp.versions, copy tag);
-
-    let number = next_extpoint_version_number(extp);
-    Vector::push_back<Version>(&mut extp.versions, Version{
-        number: number,
-        tag: tag,
-        types_d_ts: types_d_ts,
-        document: dts_doc,
-        created_at: Timestamp::now_seconds(),
-    });
-
-    extp.updated_at = Timestamp::now_seconds();
-
-    // publish version event emit
-    let plugin_event_handlers = borrow_global_mut<ExtensionPointEventHandlers<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut plugin_event_handlers.publish_version,
-        PublishVersionEvent {
-            sender: copy sender_addr,
-            version_number: copy number,
-        },
-    );
-}
-
- - - -
- - - -## Function `update` - - - -
public fun update<ExtPointT>(sender: &signer, name: vector<u8>, description: vector<u8>, option_labels: Option::Option<vector<vector<u8>>>)
-
- - - -
-Implementation - - -
public fun update<ExtPointT>(sender: &signer, name: vector<u8>, description: vector<u8>, option_labels: Option<vector<vector<u8>>>) acquires Entry, ExtensionPointEventHandlers {
-    assert_string_length(&name, MAX_INPUT_LEN);
-    assert_string_length(&description, MAX_TEXT_LEN);
-
-    let sender_addr = Signer::address_of(sender);
-    let extp = borrow_global_mut<Entry<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-    ensure_exists_extpoint_nft(sender_addr, extp.id);
-
-    extp.name = name;
-    extp.description = description;
-
-    if(Option::is_some(&option_labels)){
-        let labels = Option::destroy_some(option_labels);
-        assert_string_array_length(&labels, MAX_LABELS_COUNT, MAX_INPUT_LEN);
-        extp.labels = labels;
-    };
-
-    extp.updated_at = Timestamp::now_seconds();
-
-    // update extpoint entry event emit
-    let plugin_event_handlers = borrow_global_mut<ExtensionPointEventHandlers<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut plugin_event_handlers.update,
-        UpdateInfoEvent {
-            sender: sender_addr,
-            id: *&extp.id,
-            name: *&extp.name,
-            description: *&extp.description,
-            labels: *&extp.labels,
-        },
-    );
-}
-
- - - -
- - - -## Function `has_star_plugin` - - - -
public fun has_star_plugin<ExtPointT>(sender: &signer): bool
-
- - - -
-Implementation - - -
public fun has_star_plugin<ExtPointT>(sender: &signer): bool {
-    let sender_addr = Signer::address_of(sender);
-    return exists<Star<ExtPointT>>(sender_addr)
-}
-
- - - -
- - - -## Function `star` - - - -
public fun star<ExtPointT>(sender: &signer)
-
- - - -
-Implementation - - -
public fun star<ExtPointT>(sender: &signer) acquires Entry, ExtensionPointEventHandlers {
-    let sender_addr = Signer::address_of(sender);
-    assert!(!exists<Star<ExtPointT>>(sender_addr), Errors::invalid_state(ERR_STAR_ALREADY_STARED));
-
-    move_to(sender, Star<ExtPointT>{
-        created_at: Timestamp::now_seconds(),
-    });
-
-    let entry = borrow_global_mut<Entry<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-    entry.star_count = entry.star_count + 1;
-    entry.updated_at = Timestamp::now_seconds();
-
-    // star event emit
-    let extpoint_event_handlers = borrow_global_mut<ExtensionPointEventHandlers<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut extpoint_event_handlers.star,
-        StarEvent {
-            sender: sender_addr,
-        },
-    );
-}
-
- - - -
- - - -## Function `unstar` - - - -
public fun unstar<ExtPointT>(sender: &signer)
-
- - - -
-Implementation - - -
public fun unstar<ExtPointT>(sender: &signer) acquires Star, Entry, ExtensionPointEventHandlers {
-    let sender_addr = Signer::address_of(sender);
-    assert!(exists<Star<ExtPointT>>(sender_addr), Errors::invalid_state(ERR_STAR_NOT_FOUND_STAR));
-
-    let star = move_from<Star<ExtPointT>>(sender_addr);
-    let Star<ExtPointT> {created_at:_} = star;
-
-    let entry = borrow_global_mut<Entry<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-    entry.star_count = entry.star_count - 1;
-    entry.updated_at = Timestamp::now_seconds();
-
-    // unstar event emit
-    let extpoint_event_handlers = borrow_global_mut<ExtensionPointEventHandlers<ExtPointT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut extpoint_event_handlers.unstar,
-        UnstarEvent {
-            sender: sender_addr,
-        },
-    );
-}
-
- - - -
- - - -## Function `register_entry` - - - -
public(script) fun register_entry<ExtPointT: store>(sender: signer, name: vector<u8>, description: vector<u8>, types_d_ts: vector<u8>, dts_doc: vector<u8>, labels: vector<vector<u8>>)
-
- - - -
-Implementation - - -
public(script) fun register_entry<ExtPointT: store>(sender: signer, name: vector<u8>, description: vector<u8>, types_d_ts:vector<u8>, dts_doc:vector<u8>,
-    labels: vector<vector<u8>>) acquires Registry, NFTMintCapHolder, RegistryEventHandlers {
-    let option_labels = if(Vector::length(&labels) == 0){
-        Option::none<vector<vector<u8>>>()
-    } else {
-        Option::some(labels)
-    };
-
-    register<ExtPointT>(&sender, name, description, types_d_ts, dts_doc, option_labels);
-}
-
- - - -
- - - -## Function `publish_version_entry` - - - -
public(script) fun publish_version_entry<ExtPointT: store>(sender: signer, tag: vector<u8>, types_d_ts: vector<u8>, dts_doc: vector<u8>)
-
- - - -
-Implementation - - -
public(script) fun publish_version_entry<ExtPointT: store>(
-    sender: signer,
-    tag: vector<u8>,
-    types_d_ts:vector<u8>,
-    dts_doc: vector<u8>,
-) acquires Entry, ExtensionPointEventHandlers {
-    publish_version<ExtPointT>(&sender, tag, types_d_ts, dts_doc);
-}
-
- - - -
- - - -## Function `update_entry` - - - -
public(script) fun update_entry<ExtPointT>(sender: signer, name: vector<u8>, description: vector<u8>, labels: vector<vector<u8>>)
-
- - - -
-Implementation - - -
public(script) fun update_entry<ExtPointT>(sender: signer, name: vector<u8>, description: vector<u8>, labels: vector<vector<u8>>) acquires Entry, ExtensionPointEventHandlers {
-    let option_labels = if(Vector::length(&labels) == 0){
-        Option::none<vector<vector<u8>>>()
-    } else {
-        Option::some(labels)
-    };
-
-    update<ExtPointT>(&sender, name, description, option_labels);
-}
-
- - - -
- - - -## Function `star_entry` - - - -
public(script) fun star_entry<ExtPointT: store>(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun star_entry<ExtPointT:store>(sender: signer) acquires Entry, ExtensionPointEventHandlers {
-    star<ExtPointT>(&sender);
-}
-
- - - -
- - - -## Function `unstar_entry` - - - -
public(script) fun unstar_entry<ExtPointT: store>(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun unstar_entry<ExtPointT:store>(sender: signer) acquires Star, Entry, ExtensionPointEventHandlers {
-    unstar<ExtPointT>(&sender);
-}
-
- - - -
diff --git a/release/v12/docs/DAOPluginMarketplace.md b/release/v12/docs/DAOPluginMarketplace.md deleted file mode 100644 index c41ea165..00000000 --- a/release/v12/docs/DAOPluginMarketplace.md +++ /dev/null @@ -1,1235 +0,0 @@ - - - -# Module `0x1::DAOPluginMarketplace` - - - -- [Struct `PluginVersion`](#0x1_DAOPluginMarketplace_PluginVersion) -- [Resource `PluginRegistry`](#0x1_DAOPluginMarketplace_PluginRegistry) -- [Resource `PluginEntry`](#0x1_DAOPluginMarketplace_PluginEntry) -- [Resource `Star`](#0x1_DAOPluginMarketplace_Star) -- [Resource `RegistryEventHandlers`](#0x1_DAOPluginMarketplace_RegistryEventHandlers) -- [Struct `PluginRegisterEvent`](#0x1_DAOPluginMarketplace_PluginRegisterEvent) -- [Resource `PluginEventHandlers`](#0x1_DAOPluginMarketplace_PluginEventHandlers) -- [Struct `PluginPublishVersionEvent`](#0x1_DAOPluginMarketplace_PluginPublishVersionEvent) -- [Struct `StarPluginEvent`](#0x1_DAOPluginMarketplace_StarPluginEvent) -- [Struct `UnstarPluginEvent`](#0x1_DAOPluginMarketplace_UnstarPluginEvent) -- [Struct `UpdatePluginInfoEvent`](#0x1_DAOPluginMarketplace_UpdatePluginInfoEvent) -- [Constants](#@Constants_0) -- [Function `next_plugin_id`](#0x1_DAOPluginMarketplace_next_plugin_id) -- [Function `next_plugin_version_number`](#0x1_DAOPluginMarketplace_next_plugin_version_number) -- [Function `assert_tag_no_repeat`](#0x1_DAOPluginMarketplace_assert_tag_no_repeat) -- [Function `assert_string_length`](#0x1_DAOPluginMarketplace_assert_string_length) -- [Function `assert_string_array_length`](#0x1_DAOPluginMarketplace_assert_string_array_length) -- [Function `initialize`](#0x1_DAOPluginMarketplace_initialize) -- [Function `register_plugin`](#0x1_DAOPluginMarketplace_register_plugin) -- [Function `exists_plugin`](#0x1_DAOPluginMarketplace_exists_plugin) -- [Function `take_plugin_id`](#0x1_DAOPluginMarketplace_take_plugin_id) -- [Function `publish_plugin_version`](#0x1_DAOPluginMarketplace_publish_plugin_version) -- [Function `exists_plugin_version`](#0x1_DAOPluginMarketplace_exists_plugin_version) -- [Function `star_plugin`](#0x1_DAOPluginMarketplace_star_plugin) -- [Function `unstar_plugin`](#0x1_DAOPluginMarketplace_unstar_plugin) -- [Function `has_star_plugin`](#0x1_DAOPluginMarketplace_has_star_plugin) -- [Function `update_plugin`](#0x1_DAOPluginMarketplace_update_plugin) -- [Function `star_plugin_entry`](#0x1_DAOPluginMarketplace_star_plugin_entry) -- [Function `unstar_plugin_entry`](#0x1_DAOPluginMarketplace_unstar_plugin_entry) - - -
use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::GenesisSignerCapability;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::TypeInfo;
-use 0x1::Vector;
-
- - - - - -## Struct `PluginVersion` - - - -
struct PluginVersion has store
-
- - - -
-Fields - - -
-
-number: u64 -
-
- -
-
-tag: vector<u8> -
-
- -
-
-implement_extpoints: vector<vector<u8>> -
-
- -
-
-depend_extpoints: vector<vector<u8>> -
-
- -
-
-js_entry_uri: vector<u8> -
-
- -
-
-created_at: u64 -
-
- -
-
- - -
- - - -## Resource `PluginRegistry` - - - -
struct PluginRegistry has store, key
-
- - - -
-Fields - - -
-
-next_plugin_id: u64 -
-
- -
-
- - -
- - - -## Resource `PluginEntry` - - - -
struct PluginEntry<PluginT> has store, key
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-labels: vector<vector<u8>> -
-
- -
-
-next_version_number: u64 -
-
- -
-
-versions: vector<DAOPluginMarketplace::PluginVersion> -
-
- -
-
-star_count: u64 -
-
- -
-
-created_at: u64 -
-
- -
-
-updated_at: u64 -
-
- -
-
- - -
- - - -## Resource `Star` - - - -
struct Star<PluginT> has store, key
-
- - - -
-Fields - - -
-
-created_at: u64 -
-
- -
-
- - -
- - - -## Resource `RegistryEventHandlers` - -registry event handlers - - -
struct RegistryEventHandlers has store, key
-
- - - -
-Fields - - -
-
-register: Event::EventHandle<DAOPluginMarketplace::PluginRegisterEvent> -
-
- -
-
- - -
- - - -## Struct `PluginRegisterEvent` - - - -
struct PluginRegisterEvent has drop, store
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-type: TypeInfo::TypeInfo -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-labels: vector<vector<u8>> -
-
- -
-
- - -
- - - -## Resource `PluginEventHandlers` - -plugin event handlers - - -
struct PluginEventHandlers<PluginT> has store, key
-
- - - -
-Fields - - -
-
-publish_version: Event::EventHandle<DAOPluginMarketplace::PluginPublishVersionEvent<PluginT>> -
-
- -
-
-star: Event::EventHandle<DAOPluginMarketplace::StarPluginEvent<PluginT>> -
-
- -
-
-unstar: Event::EventHandle<DAOPluginMarketplace::UnstarPluginEvent<PluginT>> -
-
- -
-
-update_plugin: Event::EventHandle<DAOPluginMarketplace::UpdatePluginInfoEvent<PluginT>> -
-
- -
-
- - -
- - - -## Struct `PluginPublishVersionEvent` - - - -
struct PluginPublishVersionEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-plugin_type: TypeInfo::TypeInfo -
-
- -
-
-version_number: u64 -
-
- -
-
- - -
- - - -## Struct `StarPluginEvent` - - - -
struct StarPluginEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-sender: address -
-
- -
-
- - -
- - - -## Struct `UnstarPluginEvent` - - - -
struct UnstarPluginEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-sender: address -
-
- -
-
- - -
- - - -## Struct `UpdatePluginInfoEvent` - - - -
struct UpdatePluginInfoEvent<PluginT> has drop, store
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-type: TypeInfo::TypeInfo -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-labels: vector<vector<u8>> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_ALREADY_INITIALIZED: u64 = 100;
-
- - - - - - - -
const ERR_EXPECT_PLUGIN_NFT: u64 = 103;
-
- - - - - - - -
const ERR_ITEMS_COUNT_LIMIT: u64 = 109;
-
- - - - - - - -
const ERR_NOT_CONTRACT_OWNER: u64 = 101;
-
- - - - - - - -
const ERR_NOT_FOUND_PLUGIN: u64 = 102;
-
- - - - - - - -
const ERR_PLUGIN_ALREADY_EXISTS: u64 = 104;
-
- - - - - - - -
const ERR_STAR_ALREADY_STARED: u64 = 105;
-
- - - - - - - -
const ERR_STAR_NOT_FOUND_STAR: u64 = 106;
-
- - - - - - - -
const ERR_STRING_TOO_LONG: u64 = 110;
-
- - - - - - - -
const ERR_TAG_DUPLICATED: u64 = 107;
-
- - - - - - - -
const ERR_VERSION_COUNT_LIMIT: u64 = 108;
-
- - - - - - - -
const MAX_INPUT_LEN: u64 = 64;
-
- - - - - - - -
const MAX_ITEMS_COUNT: u64 = 20;
-
- - - - - - - -
const MAX_TEXT_LEN: u64 = 256;
-
- - - - - - - -
const MAX_VERSION_COUNT: u64 = 5;
-
- - - - - -## Function `next_plugin_id` - - - -
fun next_plugin_id(plugin_registry: &mut DAOPluginMarketplace::PluginRegistry): u64
-
- - - -
-Implementation - - -
fun next_plugin_id(plugin_registry: &mut PluginRegistry): u64 {
-    let plugin_id = plugin_registry.next_plugin_id;
-    plugin_registry.next_plugin_id = plugin_id + 1;
-    plugin_id
-}
-
- - - -
- - - -## Function `next_plugin_version_number` - - - -
fun next_plugin_version_number<PluginT>(plugin: &mut DAOPluginMarketplace::PluginEntry<PluginT>): u64
-
- - - -
-Implementation - - -
fun next_plugin_version_number<PluginT>(plugin: &mut PluginEntry<PluginT>): u64 {
-    let version_number = plugin.next_version_number;
-    plugin.next_version_number = version_number + 1;
-    version_number
-}
-
- - - -
- - - -## Function `assert_tag_no_repeat` - - - -
fun assert_tag_no_repeat(v: &vector<DAOPluginMarketplace::PluginVersion>, tag: vector<u8>)
-
- - - -
-Implementation - - -
fun assert_tag_no_repeat(v: &vector<PluginVersion>, tag:vector<u8>) {
-    let i = 0;
-    let len = Vector::length(v);
-    while (i < len) {
-        let e = Vector::borrow(v, i);
-        assert!(*&e.tag != *&tag, Errors::invalid_argument(ERR_TAG_DUPLICATED));
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `assert_string_length` - - - -
fun assert_string_length(s: &vector<u8>, max_len: u64)
-
- - - -
-Implementation - - -
fun assert_string_length(s: &vector<u8>, max_len: u64) {
-    let len = Vector::length(s);
-    assert!(len <= max_len, Errors::invalid_argument(ERR_STRING_TOO_LONG));
-}
-
- - - -
- - - -## Function `assert_string_array_length` - - - -
fun assert_string_array_length(v: &vector<vector<u8>>, max_item_len: u64, max_string_len: u64)
-
- - - -
-Implementation - - -
fun assert_string_array_length(v: &vector<vector<u8>>, max_item_len: u64, max_string_len: u64) {
-    assert!(Vector::length(v) <= max_item_len, Errors::limit_exceeded(ERR_ITEMS_COUNT_LIMIT));
-
-    let i = 0;
-    let len = Vector::length(v);
-    while (i < len) {
-        let e = Vector::borrow(v, i);
-        assert_string_length(e, max_string_len);
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `initialize` - - - -
public fun initialize()
-
- - - -
-Implementation - - -
public fun initialize() {
-    assert!(!exists<PluginRegistry>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED));
-    let signer = GenesisSignerCapability::get_genesis_signer();
-
-    move_to(&signer, PluginRegistry{
-        next_plugin_id: 1,
-    });
-
-    move_to(&signer, RegistryEventHandlers {
-        register: Event::new_event_handle<PluginRegisterEvent>(&signer),
-    });
-}
-
- - - -
- - - -## Function `register_plugin` - - - -
public fun register_plugin<PluginT: store>(_witness: &PluginT, name: vector<u8>, description: vector<u8>, option_labels: Option::Option<vector<vector<u8>>>): u64
-
- - - -
-Implementation - - -
public fun register_plugin<PluginT: store>(_witness: &PluginT, name: vector<u8>, description: vector<u8>, option_labels: Option<vector<vector<u8>>>): u64
-    acquires PluginRegistry, RegistryEventHandlers {
-    assert_string_length(&name, MAX_INPUT_LEN);
-    assert_string_length(&description, MAX_TEXT_LEN);
-
-    assert!(!exists<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_PLUGIN_ALREADY_EXISTS));
-    let plugin_registry = borrow_global_mut<PluginRegistry>(CoreAddresses::GENESIS_ADDRESS());
-    let plugin_id = next_plugin_id(plugin_registry);
-
-    let genesis_account = GenesisSignerCapability::get_genesis_signer();
-
-    let labels = if(Option::is_some(&option_labels)){
-        Option::destroy_some(option_labels)
-    } else {
-        Vector::empty<vector<u8>>()
-    };
-
-    assert_string_array_length(&labels, MAX_ITEMS_COUNT, MAX_INPUT_LEN);
-
-    move_to(&genesis_account, PluginEntry<PluginT>{
-        id: copy plugin_id,
-        name: copy name,
-        description: copy description,
-        labels: copy labels,
-        next_version_number: 1,
-        versions: Vector::empty<PluginVersion>(),
-        star_count: 0,
-        created_at: Timestamp::now_seconds(),
-        updated_at: Timestamp::now_seconds(),
-    });
-
-    move_to(&genesis_account, PluginEventHandlers<PluginT>{
-        publish_version: Event::new_event_handle<PluginPublishVersionEvent<PluginT>>(&genesis_account),
-        star: Event::new_event_handle<StarPluginEvent<PluginT>>(&genesis_account),
-        unstar: Event::new_event_handle<UnstarPluginEvent<PluginT>>(&genesis_account),
-        update_plugin: Event::new_event_handle<UpdatePluginInfoEvent<PluginT>>(&genesis_account),
-    });
-
-    // registry register event emit
-    let registry_event_handlers = borrow_global_mut<RegistryEventHandlers>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut registry_event_handlers.register,
-        PluginRegisterEvent {
-            id: copy plugin_id,
-            type: TypeInfo::type_of<PluginT>(),
-            name: copy name,
-            description: copy description,
-            labels: copy labels,
-        },
-    );
-
-    plugin_id
-}
-
- - - -
- - - -## Function `exists_plugin` - - - -
public fun exists_plugin<PluginT>(): bool
-
- - - -
-Implementation - - -
public fun exists_plugin<PluginT>(): bool {
-    return exists<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS())
-}
-
- - - -
- - - -## Function `take_plugin_id` - - - -
public fun take_plugin_id<PluginT>(): u64
-
- - - -
-Implementation - - -
public fun take_plugin_id<PluginT>(): u64 acquires PluginEntry {
-    let plugin = borrow_global<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    return plugin.id
-}
-
- - - -
- - - -## Function `publish_plugin_version` - - - -
public fun publish_plugin_version<PluginT>(_witness: &PluginT, tag: vector<u8>, implement_extpoints: vector<vector<u8>>, depend_extpoints: vector<vector<u8>>, js_entry_uri: vector<u8>)
-
- - - -
-Implementation - - -
public fun publish_plugin_version<PluginT>(
-    _witness: &PluginT,
-    tag: vector<u8>,
-    implement_extpoints: vector<vector<u8>>,
-    depend_extpoints: vector<vector<u8>>,
-    js_entry_uri: vector<u8>,
-) acquires PluginEntry, PluginEventHandlers {
-    assert_string_length(&tag, MAX_INPUT_LEN);
-    assert_string_array_length(&implement_extpoints, MAX_ITEMS_COUNT, MAX_INPUT_LEN);
-    assert_string_array_length(&depend_extpoints, MAX_ITEMS_COUNT, MAX_INPUT_LEN);
-    assert_string_length(&js_entry_uri, MAX_TEXT_LEN);
-
-    let plugin = borrow_global_mut<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-
-    assert_tag_no_repeat(&plugin.versions, copy tag);
-
-    // Remove the old version when the number of versions is greater than MAX_VERSION_COUNT
-    if (Vector::length(&plugin.versions) >= MAX_VERSION_COUNT) {
-        let oldest_version = Vector::remove(&mut plugin.versions, 0);
-        let PluginVersion {
-            number: _,
-            tag: _,
-            implement_extpoints: _,
-            depend_extpoints: _,
-            js_entry_uri: _,
-            created_at: _,
-        } = oldest_version;
-    };
-
-    let version_number = next_plugin_version_number(plugin);
-    Vector::push_back<PluginVersion>(&mut plugin.versions, PluginVersion{
-        number: copy version_number,
-        tag: tag,
-        implement_extpoints: implement_extpoints,
-        depend_extpoints: depend_extpoints,
-        js_entry_uri: js_entry_uri,
-        created_at: Timestamp::now_seconds(),
-    });
-
-    plugin.updated_at = Timestamp::now_seconds();
-
-    // plugin register event emit
-    let plugin_event_handlers = borrow_global_mut<PluginEventHandlers<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut plugin_event_handlers.publish_version,
-        PluginPublishVersionEvent {
-            plugin_type: TypeInfo::type_of<PluginT>(),
-            version_number: copy version_number,
-        },
-    );
-}
-
- - - -
- - - -## Function `exists_plugin_version` - - - -
public fun exists_plugin_version<PluginT>(version_number: u64): bool
-
- - - -
-Implementation - - -
public fun exists_plugin_version<PluginT>(
-    version_number: u64,
-): bool acquires PluginEntry {
-    let plugin = borrow_global_mut<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    return version_number > 0 && version_number < plugin.next_version_number
-}
-
- - - -
- - - -## Function `star_plugin` - - - -
public fun star_plugin<PluginT>(sender: &signer)
-
- - - -
-Implementation - - -
public fun star_plugin<PluginT>(sender: &signer) acquires PluginEntry, PluginEventHandlers {
-    let sender_addr = Signer::address_of(sender);
-    assert!(!exists<Star<PluginT>>(sender_addr), Errors::invalid_state(ERR_STAR_ALREADY_STARED));
-
-    move_to(sender, Star<PluginT>{
-        created_at: Timestamp::now_seconds(),
-    });
-
-    let plugin = borrow_global_mut<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    plugin.star_count = plugin.star_count + 1;
-    plugin.updated_at = Timestamp::now_seconds();
-
-    // star plugin event emit
-    let plugin_event_handlers = borrow_global_mut<PluginEventHandlers<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut plugin_event_handlers.star,
-        StarPluginEvent {
-            sender: sender_addr,
-        },
-    );
-}
-
- - - -
- - - -## Function `unstar_plugin` - - - -
public fun unstar_plugin<PluginT>(sender: &signer)
-
- - - -
-Implementation - - -
public fun unstar_plugin<PluginT>(sender: &signer) acquires PluginEntry, Star, PluginEventHandlers {
-    let sender_addr = Signer::address_of(sender);
-    assert!(exists<Star<PluginT>>(sender_addr), Errors::invalid_state(ERR_STAR_NOT_FOUND_STAR));
-
-    let star = move_from<Star<PluginT>>(sender_addr);
-    let Star<PluginT> { created_at:_} = star;
-
-    let plugin = borrow_global_mut<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    plugin.star_count = plugin.star_count - 1;
-    plugin.updated_at = Timestamp::now_seconds();
-
-    // unstar plugin event emit
-    let plugin_event_handlers = borrow_global_mut<PluginEventHandlers<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut plugin_event_handlers.unstar,
-        UnstarPluginEvent {
-            sender: sender_addr,
-        },
-    );
-}
-
- - - -
- - - -## Function `has_star_plugin` - - - -
public fun has_star_plugin<PluginT>(sender: &signer): bool
-
- - - -
-Implementation - - -
public fun has_star_plugin<PluginT>(sender: &signer): bool {
-    let sender_addr = Signer::address_of(sender);
-    return exists<Star<PluginT>>(sender_addr)
-}
-
- - - -
- - - -## Function `update_plugin` - - - -
public fun update_plugin<PluginT>(_witness: &PluginT, name: vector<u8>, description: vector<u8>, option_labels: Option::Option<vector<vector<u8>>>)
-
- - - -
-Implementation - - -
public fun update_plugin<PluginT>(_witness: &PluginT, name: vector<u8>, description: vector<u8>, option_labels: Option<vector<vector<u8>>>) acquires PluginEntry, PluginEventHandlers {
-    assert_string_length(&name, MAX_INPUT_LEN);
-    assert_string_length(&description, MAX_TEXT_LEN);
-
-    let plugin = borrow_global_mut<PluginEntry<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-
-    plugin.name = name;
-    plugin.description = description;
-
-    if(Option::is_some(&option_labels)){
-        let labels = Option::destroy_some(option_labels);
-        assert_string_array_length(&labels, MAX_ITEMS_COUNT, MAX_INPUT_LEN);
-        plugin.labels = labels;
-    };
-
-    plugin.updated_at = Timestamp::now_seconds();
-
-    // update plugin event emit
-    let plugin_event_handlers = borrow_global_mut<PluginEventHandlers<PluginT>>(CoreAddresses::GENESIS_ADDRESS());
-    Event::emit_event(&mut plugin_event_handlers.update_plugin,
-        UpdatePluginInfoEvent {
-            id: *&plugin.id,
-            type: TypeInfo::type_of<PluginT>(),
-            name: *&plugin.name,
-            description: *&plugin.description,
-            labels: *&plugin.labels,
-        },
-    );
-}
-
- - - -
- - - -## Function `star_plugin_entry` - - - -
public(script) fun star_plugin_entry<PluginT>(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun star_plugin_entry<PluginT>(sender: signer) acquires PluginEntry, PluginEventHandlers {
-    star_plugin<PluginT>(&sender);
-}
-
- - - -
- - - -## Function `unstar_plugin_entry` - - - -
public(script) fun unstar_plugin_entry<PluginT>(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun unstar_plugin_entry<PluginT>(sender: signer) acquires PluginEntry, Star, PluginEventHandlers {
-    unstar_plugin<PluginT>(&sender);
-}
-
- - - -
diff --git a/release/v12/docs/DAORegistry.md b/release/v12/docs/DAORegistry.md deleted file mode 100644 index 91c35eff..00000000 --- a/release/v12/docs/DAORegistry.md +++ /dev/null @@ -1,217 +0,0 @@ - - - -# Module `0x1::DAORegistry` - - - -- [Resource `DAORegistry`](#0x1_DAORegistry_DAORegistry) -- [Resource `DAORegistryEntry`](#0x1_DAORegistry_DAORegistryEntry) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_DAORegistry_initialize) -- [Function `register`](#0x1_DAORegistry_register) -- [Function `next_dao_id`](#0x1_DAORegistry_next_dao_id) -- [Function `dao_address`](#0x1_DAORegistry_dao_address) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::GenesisSignerCapability;
-
- - - - - -## Resource `DAORegistry` - -Global DAO registry info - - -
struct DAORegistry has key
-
- - - -
-Fields - - -
-
-next_dao_id: u64 -
-
- -
-
- - -
- - - -## Resource `DAORegistryEntry` - -Registry Entry for record the mapping between DAOT and dao_address - - -
struct DAORegistryEntry<DAOT> has key
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-dao_address: address -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_ALREADY_INITIALIZED: u64 = 100;
-
- - - - - -## Function `initialize` - - - -
public(friend) fun initialize()
-
- - - -
-Implementation - - -
public(friend) fun initialize(){
-    assert!(!exists<DAORegistry>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED));
-    let signer = GenesisSignerCapability::get_genesis_signer();
-    move_to(&signer, DAORegistry{next_dao_id: 1})
-}
-
- - - -
- - - -## Function `register` - - - -
public(friend) fun register<DAOT>(dao_address: address): u64
-
- - - -
-Implementation - - -
public(friend) fun register<DAOT>(dao_address: address): u64 acquires DAORegistry{
-    let genesis_account = GenesisSignerCapability::get_genesis_signer();
-    let dao_id = next_dao_id();
-    move_to(&genesis_account, DAORegistryEntry<DAOT>{
-        dao_id,
-        dao_address,
-    });
-    dao_id
-}
-
- - - -
- - - -## Function `next_dao_id` - - - -
fun next_dao_id(): u64
-
- - - -
-Implementation - - -
fun next_dao_id(): u64 acquires DAORegistry {
-    let dao_registry = borrow_global_mut<DAORegistry>(CoreAddresses::GENESIS_ADDRESS());
-    let dao_id = dao_registry.next_dao_id;
-    dao_registry.next_dao_id = dao_id + 1;
-    dao_id
-
-}
-
- - - -
- - - -## Function `dao_address` - - - -
public fun dao_address<DAOT>(): address
-
- - - -
-Implementation - - -
public fun dao_address<DAOT>():address acquires DAORegistryEntry{
-    *&borrow_global<DAORegistryEntry<DAOT>>(CoreAddresses::GENESIS_ADDRESS()).dao_address
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/DAOSpace.md b/release/v12/docs/DAOSpace.md deleted file mode 100644 index 6fb137b7..00000000 --- a/release/v12/docs/DAOSpace.md +++ /dev/null @@ -1,8184 +0,0 @@ - - - -# Module `0x1::DAOSpace` - - - -- [Resource `DAO`](#0x1_DAOSpace_DAO) -- [Struct `DAOConfig`](#0x1_DAOSpace_DAOConfig) -- [Struct `DAOCustomConfig`](#0x1_DAOSpace_DAOCustomConfig) -- [Resource `DAOAccountCapHolder`](#0x1_DAOSpace_DAOAccountCapHolder) -- [Resource `DAOSBTMintCapHolder`](#0x1_DAOSpace_DAOSBTMintCapHolder) -- [Resource `DAOSBTBurnCapHolder`](#0x1_DAOSpace_DAOSBTBurnCapHolder) -- [Resource `DAOTokenMintCapHolder`](#0x1_DAOSpace_DAOTokenMintCapHolder) -- [Resource `DAOTokenBurnCapHolder`](#0x1_DAOSpace_DAOTokenBurnCapHolder) -- [Resource `DAONFTMintCapHolder`](#0x1_DAOSpace_DAONFTMintCapHolder) -- [Resource `DAONFTBurnCapHolder`](#0x1_DAOSpace_DAONFTBurnCapHolder) -- [Resource `DAONFTUpdateCapHolder`](#0x1_DAOSpace_DAONFTUpdateCapHolder) -- [Resource `DAOConfigModifyCapHolder`](#0x1_DAOSpace_DAOConfigModifyCapHolder) -- [Resource `DAOCustomConfigModifyCapHolder`](#0x1_DAOSpace_DAOCustomConfigModifyCapHolder) -- [Struct `CapType`](#0x1_DAOSpace_CapType) -- [Struct `DAOInstallPluginCap`](#0x1_DAOSpace_DAOInstallPluginCap) -- [Struct `DAOUpgradeModuleCap`](#0x1_DAOSpace_DAOUpgradeModuleCap) -- [Struct `DAOModifyConfigCap`](#0x1_DAOSpace_DAOModifyConfigCap) -- [Struct `DAOWithdrawTokenCap`](#0x1_DAOSpace_DAOWithdrawTokenCap) -- [Struct `DAOWithdrawNFTCap`](#0x1_DAOSpace_DAOWithdrawNFTCap) -- [Struct `DAOStorageCap`](#0x1_DAOSpace_DAOStorageCap) -- [Struct `DAOMemberCap`](#0x1_DAOSpace_DAOMemberCap) -- [Struct `DAOProposalCap`](#0x1_DAOSpace_DAOProposalCap) -- [Struct `DAOGrantCap`](#0x1_DAOSpace_DAOGrantCap) -- [Struct `DAOPluginEventCap`](#0x1_DAOSpace_DAOPluginEventCap) -- [Resource `DAOGrantWithdrawTokenKey`](#0x1_DAOSpace_DAOGrantWithdrawTokenKey) -- [Resource `InstalledPluginInfo`](#0x1_DAOSpace_InstalledPluginInfo) -- [Struct `DAOMember`](#0x1_DAOSpace_DAOMember) -- [Struct `DAOMemberBody`](#0x1_DAOSpace_DAOMemberBody) -- [Resource `DAOEvent`](#0x1_DAOSpace_DAOEvent) -- [Struct `DAOCreatedEvent`](#0x1_DAOSpace_DAOCreatedEvent) -- [Resource `MemberEvent`](#0x1_DAOSpace_MemberEvent) -- [Struct `MemberOfferEvent`](#0x1_DAOSpace_MemberOfferEvent) -- [Struct `MemberJoinEvent`](#0x1_DAOSpace_MemberJoinEvent) -- [Struct `MemberRevokeEvent`](#0x1_DAOSpace_MemberRevokeEvent) -- [Struct `MemberQuitEvent`](#0x1_DAOSpace_MemberQuitEvent) -- [Struct `MemberIncreaseSBTEvent`](#0x1_DAOSpace_MemberIncreaseSBTEvent) -- [Struct `MemberDecreaseSBTEvent`](#0x1_DAOSpace_MemberDecreaseSBTEvent) -- [Resource `StorageItem`](#0x1_DAOSpace_StorageItem) -- [Struct `MemeberOffer`](#0x1_DAOSpace_MemeberOffer) -- [Resource `PluginEvent`](#0x1_DAOSpace_PluginEvent) -- [Resource `GrantEvent`](#0x1_DAOSpace_GrantEvent) -- [Struct `GrantCreateEvent`](#0x1_DAOSpace_GrantCreateEvent) -- [Struct `GrantRevokeEvent`](#0x1_DAOSpace_GrantRevokeEvent) -- [Struct `GrantRefundEvent`](#0x1_DAOSpace_GrantRefundEvent) -- [Struct `GrantConfigEvent`](#0x1_DAOSpace_GrantConfigEvent) -- [Struct `GrantWithdrawEvent`](#0x1_DAOSpace_GrantWithdrawEvent) -- [Struct `GrantInfo`](#0x1_DAOSpace_GrantInfo) -- [Struct `ProposalState`](#0x1_DAOSpace_ProposalState) -- [Struct `VotingChoice`](#0x1_DAOSpace_VotingChoice) -- [Struct `Proposal`](#0x1_DAOSpace_Proposal) -- [Struct `ProposalAction`](#0x1_DAOSpace_ProposalAction) -- [Struct `ProposalActionIndex`](#0x1_DAOSpace_ProposalActionIndex) -- [Resource `GlobalProposals`](#0x1_DAOSpace_GlobalProposals) -- [Resource `ProposalActions`](#0x1_DAOSpace_ProposalActions) -- [Resource `GlobalProposalActions`](#0x1_DAOSpace_GlobalProposalActions) -- [Struct `Vote`](#0x1_DAOSpace_Vote) -- [Struct `VoteInfo`](#0x1_DAOSpace_VoteInfo) -- [Resource `MyVotes`](#0x1_DAOSpace_MyVotes) -- [Struct `SnapshotProof`](#0x1_DAOSpace_SnapshotProof) -- [Struct `HashNode`](#0x1_DAOSpace_HashNode) -- [Resource `ProposalEvent`](#0x1_DAOSpace_ProposalEvent) -- [Struct `ProposalCreatedEvent`](#0x1_DAOSpace_ProposalCreatedEvent) -- [Struct `VotedEvent`](#0x1_DAOSpace_VotedEvent) -- [Struct `ProposalActionEvent`](#0x1_DAOSpace_ProposalActionEvent) -- [Constants](#@Constants_0) -- [Function `install_plugin_cap_type`](#0x1_DAOSpace_install_plugin_cap_type) -- [Function `upgrade_module_cap_type`](#0x1_DAOSpace_upgrade_module_cap_type) -- [Function `modify_config_cap_type`](#0x1_DAOSpace_modify_config_cap_type) -- [Function `withdraw_token_cap_type`](#0x1_DAOSpace_withdraw_token_cap_type) -- [Function `withdraw_nft_cap_type`](#0x1_DAOSpace_withdraw_nft_cap_type) -- [Function `storage_cap_type`](#0x1_DAOSpace_storage_cap_type) -- [Function `member_cap_type`](#0x1_DAOSpace_member_cap_type) -- [Function `proposal_cap_type`](#0x1_DAOSpace_proposal_cap_type) -- [Function `grant_cap_type`](#0x1_DAOSpace_grant_cap_type) -- [Function `token_mint_cap_type`](#0x1_DAOSpace_token_mint_cap_type) -- [Function `token_burn_cap_type`](#0x1_DAOSpace_token_burn_cap_type) -- [Function `plugin_event_cap_type`](#0x1_DAOSpace_plugin_event_cap_type) -- [Function `all_caps`](#0x1_DAOSpace_all_caps) -- [Function `create_dao`](#0x1_DAOSpace_create_dao) -- [Function `upgrade_to_dao`](#0x1_DAOSpace_upgrade_to_dao) -- [Function `install_plugin`](#0x1_DAOSpace_install_plugin) -- [Function `do_install_plugin`](#0x1_DAOSpace_do_install_plugin) -- [Function `uninstall_plugin`](#0x1_DAOSpace_uninstall_plugin) -- [Function `do_uninstall_plugin`](#0x1_DAOSpace_do_uninstall_plugin) -- [Function `submit_upgrade_plan`](#0x1_DAOSpace_submit_upgrade_plan) -- [Function `save_to_storage`](#0x1_DAOSpace_save_to_storage) -- [Function `take_from_storage`](#0x1_DAOSpace_take_from_storage) -- [Function `exists_in_storage`](#0x1_DAOSpace_exists_in_storage) -- [Function `copy_from_storage`](#0x1_DAOSpace_copy_from_storage) -- [Function `withdraw_token`](#0x1_DAOSpace_withdraw_token) -- [Function `withdraw_nft`](#0x1_DAOSpace_withdraw_nft) -- [Function `issue_member_offer`](#0x1_DAOSpace_issue_member_offer) -- [Function `revoke_member_offer`](#0x1_DAOSpace_revoke_member_offer) -- [Function `accept_member_offer`](#0x1_DAOSpace_accept_member_offer) -- [Function `accept_member_offer_entry`](#0x1_DAOSpace_accept_member_offer_entry) -- [Function `do_join_member`](#0x1_DAOSpace_do_join_member) -- [Function `quit_member_entry`](#0x1_DAOSpace_quit_member_entry) -- [Function `quit_member`](#0x1_DAOSpace_quit_member) -- [Function `revoke_member`](#0x1_DAOSpace_revoke_member) -- [Function `ensure_member`](#0x1_DAOSpace_ensure_member) -- [Function `ensure_not_member`](#0x1_DAOSpace_ensure_not_member) -- [Function `do_remove_member`](#0x1_DAOSpace_do_remove_member) -- [Function `join_member_with_member_cap`](#0x1_DAOSpace_join_member_with_member_cap) -- [Function `increase_member_sbt`](#0x1_DAOSpace_increase_member_sbt) -- [Function `decrease_member_sbt`](#0x1_DAOSpace_decrease_member_sbt) -- [Function `set_member_image`](#0x1_DAOSpace_set_member_image) -- [Function `query_sbt`](#0x1_DAOSpace_query_sbt) -- [Function `query_member_id`](#0x1_DAOSpace_query_member_id) -- [Function `is_member`](#0x1_DAOSpace_is_member) -- [Function `is_exist_member_offer`](#0x1_DAOSpace_is_exist_member_offer) -- [Function `init_plugin_event`](#0x1_DAOSpace_init_plugin_event) -- [Function `emit_plugin_event`](#0x1_DAOSpace_emit_plugin_event) -- [Function `grant_accept_offer`](#0x1_DAOSpace_grant_accept_offer) -- [Function `grant_accept_offer_entry`](#0x1_DAOSpace_grant_accept_offer_entry) -- [Function `grant_offer`](#0x1_DAOSpace_grant_offer) -- [Function `grant_offer_refund`](#0x1_DAOSpace_grant_offer_refund) -- [Function `grant_offer_refund_entry`](#0x1_DAOSpace_grant_offer_refund_entry) -- [Function `grant_withdraw_entry`](#0x1_DAOSpace_grant_withdraw_entry) -- [Function `grant_withdraw`](#0x1_DAOSpace_grant_withdraw) -- [Function `query_grant_withdrawable_amount`](#0x1_DAOSpace_query_grant_withdrawable_amount) -- [Function `is_exist_grant`](#0x1_DAOSpace_is_exist_grant) -- [Function `grant_revoke`](#0x1_DAOSpace_grant_revoke) -- [Function `grant_offer_revoke`](#0x1_DAOSpace_grant_offer_revoke) -- [Function `refund_grant`](#0x1_DAOSpace_refund_grant) -- [Function `refund_grant_entry`](#0x1_DAOSpace_refund_grant_entry) -- [Function `query_grant`](#0x1_DAOSpace_query_grant) -- [Function `query_grant_info_total`](#0x1_DAOSpace_query_grant_info_total) -- [Function `query_grant_info_withdraw`](#0x1_DAOSpace_query_grant_info_withdraw) -- [Function `query_grant_info_start_time`](#0x1_DAOSpace_query_grant_info_start_time) -- [Function `query_grant_info_period`](#0x1_DAOSpace_query_grant_info_period) -- [Function `validate_cap`](#0x1_DAOSpace_validate_cap) -- [Function `acquire_install_plugin_cap`](#0x1_DAOSpace_acquire_install_plugin_cap) -- [Function `acquire_upgrade_module_cap`](#0x1_DAOSpace_acquire_upgrade_module_cap) -- [Function `acquire_modify_config_cap`](#0x1_DAOSpace_acquire_modify_config_cap) -- [Function `acquire_withdraw_token_cap`](#0x1_DAOSpace_acquire_withdraw_token_cap) -- [Function `acquire_withdraw_nft_cap`](#0x1_DAOSpace_acquire_withdraw_nft_cap) -- [Function `acquire_storage_cap`](#0x1_DAOSpace_acquire_storage_cap) -- [Function `acquire_member_cap`](#0x1_DAOSpace_acquire_member_cap) -- [Function `acquire_proposal_cap`](#0x1_DAOSpace_acquire_proposal_cap) -- [Function `acquire_grant_cap`](#0x1_DAOSpace_acquire_grant_cap) -- [Function `acquire_plugin_event_cap`](#0x1_DAOSpace_acquire_plugin_event_cap) -- [Function `delegate_token_mint_cap`](#0x1_DAOSpace_delegate_token_mint_cap) -- [Function `delegate_token_burn_cap`](#0x1_DAOSpace_delegate_token_burn_cap) -- [Function `mint_token`](#0x1_DAOSpace_mint_token) -- [Function `burn_token`](#0x1_DAOSpace_burn_token) -- [Function `choice_yes`](#0x1_DAOSpace_choice_yes) -- [Function `choice_no`](#0x1_DAOSpace_choice_no) -- [Function `choice_no_with_veto`](#0x1_DAOSpace_choice_no_with_veto) -- [Function `choice_abstain`](#0x1_DAOSpace_choice_abstain) -- [Function `create_proposal`](#0x1_DAOSpace_create_proposal) -- [Function `block_number_and_state_root`](#0x1_DAOSpace_block_number_and_state_root) -- [Function `cast_vote`](#0x1_DAOSpace_cast_vote) -- [Function `deserialize_snapshot_proofs`](#0x1_DAOSpace_deserialize_snapshot_proofs) -- [Function `new_state_proof_from_proofs`](#0x1_DAOSpace_new_state_proof_from_proofs) -- [Function `execute_proposal`](#0x1_DAOSpace_execute_proposal) -- [Function `clean_proposals`](#0x1_DAOSpace_clean_proposals) -- [Function `clean_proposals_entry`](#0x1_DAOSpace_clean_proposals_entry) -- [Function `clean_proposal_by_id`](#0x1_DAOSpace_clean_proposal_by_id) -- [Function `clean_proposal_by_id_entry`](#0x1_DAOSpace_clean_proposal_by_id_entry) -- [Function `take_proposal_action`](#0x1_DAOSpace_take_proposal_action) -- [Function `remove_proposal`](#0x1_DAOSpace_remove_proposal) -- [Function `find_action`](#0x1_DAOSpace_find_action) -- [Function `do_cast_vote`](#0x1_DAOSpace_do_cast_vote) -- [Function `has_voted`](#0x1_DAOSpace_has_voted) -- [Function `vote_info`](#0x1_DAOSpace_vote_info) -- [Function `reject_proposal`](#0x1_DAOSpace_reject_proposal) -- [Function `reject_proposal_entry`](#0x1_DAOSpace_reject_proposal_entry) -- [Function `get_vote_info`](#0x1_DAOSpace_get_vote_info) -- [Function `proposal_state`](#0x1_DAOSpace_proposal_state) -- [Function `proposal_state_with_proposal`](#0x1_DAOSpace_proposal_state_with_proposal) -- [Function `do_proposal_state`](#0x1_DAOSpace_do_proposal_state) -- [Function `borrow_proposal_mut`](#0x1_DAOSpace_borrow_proposal_mut) -- [Function `borrow_proposal`](#0x1_DAOSpace_borrow_proposal) -- [Function `find_proposal_action_index`](#0x1_DAOSpace_find_proposal_action_index) -- [Function `proposal`](#0x1_DAOSpace_proposal) -- [Function `proposal_id`](#0x1_DAOSpace_proposal_id) -- [Function `proposal_proposer`](#0x1_DAOSpace_proposal_proposer) -- [Function `proposal_time`](#0x1_DAOSpace_proposal_time) -- [Function `proposal_votes`](#0x1_DAOSpace_proposal_votes) -- [Function `proposal_block_number`](#0x1_DAOSpace_proposal_block_number) -- [Function `proposal_state_root`](#0x1_DAOSpace_proposal_state_root) -- [Function `queue_proposal_action_entry`](#0x1_DAOSpace_queue_proposal_action_entry) -- [Function `queue_proposal_action`](#0x1_DAOSpace_queue_proposal_action) -- [Function `cast_vote_entry`](#0x1_DAOSpace_cast_vote_entry) -- [Function `new_dao_config`](#0x1_DAOSpace_new_dao_config) -- [Function `get_custom_config`](#0x1_DAOSpace_get_custom_config) -- [Function `exists_custom_config`](#0x1_DAOSpace_exists_custom_config) -- [Function `set_custom_config`](#0x1_DAOSpace_set_custom_config) -- [Function `set_custom_config_cap`](#0x1_DAOSpace_set_custom_config_cap) -- [Function `set_dao_description`](#0x1_DAOSpace_set_dao_description) -- [Function `set_dao_image`](#0x1_DAOSpace_set_dao_image) -- [Function `voting_delay`](#0x1_DAOSpace_voting_delay) -- [Function `voting_period`](#0x1_DAOSpace_voting_period) -- [Function `quorum_votes`](#0x1_DAOSpace_quorum_votes) -- [Function `voting_quorum_rate`](#0x1_DAOSpace_voting_quorum_rate) -- [Function `min_action_delay`](#0x1_DAOSpace_min_action_delay) -- [Function `min_proposal_deposit`](#0x1_DAOSpace_min_proposal_deposit) -- [Function `get_config`](#0x1_DAOSpace_get_config) -- [Function `modify_dao_config`](#0x1_DAOSpace_modify_dao_config) -- [Function `set_voting_delay`](#0x1_DAOSpace_set_voting_delay) -- [Function `set_voting_period`](#0x1_DAOSpace_set_voting_period) -- [Function `set_voting_quorum_rate`](#0x1_DAOSpace_set_voting_quorum_rate) -- [Function `set_min_action_delay`](#0x1_DAOSpace_set_min_action_delay) -- [Function `set_min_proposal_deposit`](#0x1_DAOSpace_set_min_proposal_deposit) -- [Function `next_member_id`](#0x1_DAOSpace_next_member_id) -- [Function `next_proposal_id`](#0x1_DAOSpace_next_proposal_id) -- [Function `assert_no_repeat`](#0x1_DAOSpace_assert_no_repeat) -- [Function `remove_element`](#0x1_DAOSpace_remove_element) -- [Function `add_element`](#0x1_DAOSpace_add_element) -- [Function `convert_option_bytes_vector`](#0x1_DAOSpace_convert_option_bytes_vector) -- [Function `dao_signer`](#0x1_DAOSpace_dao_signer) -- [Function `dao_address`](#0x1_DAOSpace_dao_address) -- [Function `dao_id`](#0x1_DAOSpace_dao_id) - - -
use 0x1::ASCII;
-use 0x1::Account;
-use 0x1::BCS;
-use 0x1::Block;
-use 0x1::Config;
-use 0x1::DAOAccount;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAORegistry;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::EventUtil;
-use 0x1::IdentifierNFT;
-use 0x1::Math;
-use 0x1::NFT;
-use 0x1::NFTGallery;
-use 0x1::Offer;
-use 0x1::Option;
-use 0x1::SBTVoteStrategy;
-use 0x1::STC;
-use 0x1::Signer;
-use 0x1::SnapshotUtil;
-use 0x1::StarcoinVerifier;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::TypeInfo;
-use 0x1::Vector;
-
- - - - - -## Resource `DAO` - -DAO resource, every DAO has this resource at it's DAO account - - -
struct DAO has key
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-dao_address: address -
-
- -
-
-next_member_id: u64 -
-
- -
-
-next_proposal_id: u64 -
-
- -
-
- - -
- - - -## Struct `DAOConfig` - -Configuration of the DAO. - - -
struct DAOConfig has copy, drop, store
-
- - - -
-Fields - - -
-
-voting_delay: u64 -
-
- after proposal created, how long use should wait before he can vote (in milliseconds) -
-
-voting_period: u64 -
-
- how long the voting window is (in milliseconds). -
-
-voting_quorum_rate: u8 -
-
- the quorum rate to agree on the proposal. - if 50% votes needed, then the voting_quorum_rate should be 50. - it should between (0, 100]. -
-
-min_action_delay: u64 -
-
- how long the proposal should wait before it can be executed (in milliseconds). -
-
-min_proposal_deposit: u128 -
-
- how many STC should be deposited to create a proposal. -
-
- - -
- - - -## Struct `DAOCustomConfig` - - - -
struct DAOCustomConfig<ConfigT> has copy, drop, store
-
- - - -
-Fields - - -
-
-config: ConfigT -
-
- -
-
- - -
- - - -## Resource `DAOAccountCapHolder` - - - -
struct DAOAccountCapHolder has key
-
- - - -
-Fields - - -
-
-cap: DAOAccount::DAOAccountCap -
-
- -
-
- - -
- - - -## Resource `DAOSBTMintCapHolder` - -Capability for minting SBT. - - -
struct DAOSBTMintCapHolder<DAOT> has key
-
- - - -
-Fields - - -
-
-cap: Token::MintCapability<DAOT> -
-
- -
-
- - -
- - - -## Resource `DAOSBTBurnCapHolder` - -Capability for burning SBT. - - -
struct DAOSBTBurnCapHolder<DAOT> has key
-
- - - -
-Fields - - -
-
-cap: Token::BurnCapability<DAOT> -
-
- -
-
- - -
- - - -## Resource `DAOTokenMintCapHolder` - -Capability for minting any tokens. - - -
struct DAOTokenMintCapHolder<DAOT, TokenT> has key
-
- - - -
-Fields - - -
-
-cap: Token::MintCapability<TokenT> -
-
- -
-
- - -
- - - -## Resource `DAOTokenBurnCapHolder` - -Capability for burning any tokens. - - -
struct DAOTokenBurnCapHolder<DAOT, TokenT> has key
-
- - - -
-Fields - - -
-
-cap: Token::BurnCapability<TokenT> -
-
- -
-
- - -
- - - -## Resource `DAONFTMintCapHolder` - - - -
struct DAONFTMintCapHolder<DAOT> has key
-
- - - -
-Fields - - -
-
-cap: NFT::MintCapability<DAOSpace::DAOMember<DAOT>> -
-
- -
-
- - -
- - - -## Resource `DAONFTBurnCapHolder` - - - -
struct DAONFTBurnCapHolder<DAOT> has key
-
- - - -
-Fields - - -
-
-cap: NFT::BurnCapability<DAOSpace::DAOMember<DAOT>> -
-
- -
-
- - -
- - - -## Resource `DAONFTUpdateCapHolder` - - - -
struct DAONFTUpdateCapHolder<DAOT> has key
-
- - - -
-Fields - - -
-
-cap: NFT::UpdateCapability<DAOSpace::DAOMember<DAOT>> -
-
- -
-
- - -
- - - -## Resource `DAOConfigModifyCapHolder` - - - -
struct DAOConfigModifyCapHolder has key
-
- - - -
-Fields - - -
-
-cap: Config::ModifyConfigCapability<DAOSpace::DAOConfig> -
-
- -
-
- - -
- - - -## Resource `DAOCustomConfigModifyCapHolder` - - - -
struct DAOCustomConfigModifyCapHolder<DAOT, ConfigT: copy, drop, store> has key
-
- - - -
-Fields - - -
-
-cap: Config::ModifyConfigCapability<ConfigT> -
-
- -
-
- - -
- - - -## Struct `CapType` - -A type describing a capability. - - -
struct CapType has copy, drop, store
-
- - - -
-Fields - - -
-
-code: u8 -
-
- -
-
- - -
- - - -## Struct `DAOInstallPluginCap` - - - -
struct DAOInstallPluginCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOUpgradeModuleCap` - - - -
struct DAOUpgradeModuleCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOModifyConfigCap` - - - -
struct DAOModifyConfigCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOWithdrawTokenCap` - - - -
struct DAOWithdrawTokenCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOWithdrawNFTCap` - - - -
struct DAOWithdrawNFTCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOStorageCap` - - - -
struct DAOStorageCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOMemberCap` - - - -
struct DAOMemberCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOProposalCap` - - - -
struct DAOProposalCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOGrantCap` - - - -
struct DAOGrantCap<DAOT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `DAOPluginEventCap` - - - -
struct DAOPluginEventCap<DAOT, PluginT> has drop
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `DAOGrantWithdrawTokenKey` - - - -
struct DAOGrantWithdrawTokenKey<DAOT, PluginT, TokenT> has store, key
-
- - - -
-Fields - - -
-
-total: u128 -
-
- The total amount of tokens that can be withdrawn by this capability -
-
-withdraw: u128 -
-
- The amount of tokens that have been withdrawn by this capability -
-
-start_time: u64 -
-
- The time-based linear release start time, timestamp in seconds. -
-
-period: u64 -
-
- The time-based linear release period in seconds -
-
- - -
- - - -## Resource `InstalledPluginInfo` - -The info for DAO installed Plugin - - -
struct InstalledPluginInfo<PluginT> has key
-
- - - -
-Fields - - -
-
-plugin_id: u64 -
-
- -
-
-granted_caps: vector<DAOSpace::CapType> -
-
- -
-
- - -
- - - -## Struct `DAOMember` - -The DAO member NFT metadata - - -
struct DAOMember<DAOT> has copy, drop, store
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
- - -
- - - -## Struct `DAOMemberBody` - -The DAO member NFT Body, hold the SBT token - - -
struct DAOMemberBody<DAOT> has store
-
- - - -
-Fields - - -
-
-sbt: Token::Token<DAOT> -
-
- -
-
- - -
- - - -## Resource `DAOEvent` - -dao event - - -
struct DAOEvent<DAOT> has store, key
-
- - - -
-Fields - - -
-
-dao_create_event: Event::EventHandle<DAOSpace::DAOCreatedEvent> -
-
- -
-
- - -
- - - -## Struct `DAOCreatedEvent` - - - -
struct DAOCreatedEvent has drop, store
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-name: vector<u8> -
-
- -
-
-description: vector<u8> -
-
- -
-
-dao_address: address -
-
- -
-
- - -
- - - -## Resource `MemberEvent` - -member event - - -
struct MemberEvent has store, key
-
- - - -
-Fields - - -
-
-member_offer_event_handler: Event::EventHandle<DAOSpace::MemberOfferEvent> -
-
- -
-
-member_join_event_handler: Event::EventHandle<DAOSpace::MemberJoinEvent> -
-
- -
-
-member_quit_event_handler: Event::EventHandle<DAOSpace::MemberQuitEvent> -
-
- -
-
-member_revoke_event_handler: Event::EventHandle<DAOSpace::MemberRevokeEvent> -
-
- -
-
-member_increase_sbt_event_handler: Event::EventHandle<DAOSpace::MemberIncreaseSBTEvent> -
-
- -
-
-member_decrease_sbt_event_handler: Event::EventHandle<DAOSpace::MemberDecreaseSBTEvent> -
-
- -
-
- - -
- - - -## Struct `MemberOfferEvent` - - - -
struct MemberOfferEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- dao id -
-
-type: u8 -
-
- -
-
-addr: address -
-
- -
-
-image_data: Option::Option<vector<u8>> -
-
- -
-
-image_url: Option::Option<vector<u8>> -
-
- -
-
-sbt: u128 -
-
- -
-
- - -
- - - -## Struct `MemberJoinEvent` - - - -
struct MemberJoinEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- dao id -
-
-type: u8 -
-
- -
-
-member_id: u64 -
-
- -
-
-addr: address -
-
- -
-
-sbt: u128 -
-
- -
-
- - -
- - - -## Struct `MemberRevokeEvent` - - - -
struct MemberRevokeEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- dao id -
-
-member_id: u64 -
-
- -
-
-addr: address -
-
- -
-
-sbt: u128 -
-
- -
-
- - -
- - - -## Struct `MemberQuitEvent` - - - -
struct MemberQuitEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- dao id -
-
-member_id: u64 -
-
- -
-
-addr: address -
-
- -
-
-sbt: u128 -
-
- -
-
- - -
- - - -## Struct `MemberIncreaseSBTEvent` - - - -
struct MemberIncreaseSBTEvent has drop, store
-
- - - -
-Fields - - -
-
-member_id: u64 -
-
- -
-
-addr: address -
-
- -
-
-increase_sbt: u128 -
-
- -
-
-sbt: u128 -
-
- -
-
- - -
- - - -## Struct `MemberDecreaseSBTEvent` - - - -
struct MemberDecreaseSBTEvent has drop, store
-
- - - -
-Fields - - -
-
-member_id: u64 -
-
- -
-
-addr: address -
-
- -
-
-decrease_sbt: u128 -
-
- -
-
-sbt: u128 -
-
- -
-
- - -
- - - -## Resource `StorageItem` - - - -
struct StorageItem<PluginT, V: store> has key
-
- - - -
-Fields - - -
-
-item: V -
-
- -
-
- - -
- - - -## Struct `MemeberOffer` - - - -
struct MemeberOffer<DAOT> has drop, store
-
- - - -
-Fields - - -
-
-to_address: address -
-
- -
-
-image_data: Option::Option<vector<u8>> -
-
- -
-
-image_url: Option::Option<vector<u8>> -
-
- -
-
-init_sbt: u128 -
-
- -
-
- - -
- - - -## Resource `PluginEvent` - - - -
struct PluginEvent<DAOT: store, PluginT: store, EventT: drop, store> has store, key
-
- - - -
-Fields - - -
-
-event_handle: Event::EventHandle<EventT> -
-
- -
-
- - -
- - - -## Resource `GrantEvent` - -Grant Event - - -
struct GrantEvent has store, key
-
- - - -
-Fields - - -
-
-create_grant_event_handler: Event::EventHandle<DAOSpace::GrantCreateEvent> -
-
- -
-
-revoke_grant_event_handler: Event::EventHandle<DAOSpace::GrantRevokeEvent> -
-
- -
-
-withdraw_grant_event_handler: Event::EventHandle<DAOSpace::GrantWithdrawEvent> -
-
- -
-
-refund_grant_event_handler: Event::EventHandle<DAOSpace::GrantRefundEvent> -
-
- -
-
- - -
- - - -## Struct `GrantCreateEvent` - - - -
struct GrantCreateEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-grantee: address -
-
- -
-
-total: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
-now_time: u64 -
-
- -
-
-plugin: TypeInfo::TypeInfo -
-
- -
-
-token: Token::TokenCode -
-
- -
-
- - -
- - - -## Struct `GrantRevokeEvent` - - - -
struct GrantRevokeEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-grantee: address -
-
- -
-
-total: u128 -
-
- -
-
-withdraw: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
-plugin: TypeInfo::TypeInfo -
-
- -
-
-token: Token::TokenCode -
-
- -
-
- - -
- - - -## Struct `GrantRefundEvent` - - - -
struct GrantRefundEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-grantee: address -
-
- -
-
-total: u128 -
-
- -
-
-withdraw: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
-plugin: TypeInfo::TypeInfo -
-
- -
-
-token: Token::TokenCode -
-
- -
-
- - -
- - - -## Struct `GrantConfigEvent` - - - -
struct GrantConfigEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-old_grantee: address -
-
- -
-
-new_grantee: address -
-
- -
-
-total: u128 -
-
- -
-
-withdraw: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
-plugin: TypeInfo::TypeInfo -
-
- -
-
-token: Token::TokenCode -
-
- -
-
- - -
- - - -## Struct `GrantWithdrawEvent` - - - -
struct GrantWithdrawEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-grantee: address -
-
- -
-
-total: u128 -
-
- -
-
-withdraw: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
-withdraw_value: u128 -
-
- -
-
-plugin: TypeInfo::TypeInfo -
-
- -
-
-token: Token::TokenCode -
-
- -
-
- - -
- - - -## Struct `GrantInfo` - - - -
struct GrantInfo has copy, drop, store
-
- - - -
-Fields - - -
-
-total: u128 -
-
- -
-
-grantee: address -
-
- -
-
-withdraw: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
- - -
- - - -## Struct `ProposalState` - - - -
struct ProposalState has copy, drop, store
-
- - - -
-Fields - - -
-
-state: u8 -
-
- -
-
- - -
- - - -## Struct `VotingChoice` - - - -
struct VotingChoice has copy, drop, store
-
- - - -
-Fields - - -
-
-choice: u8 -
-
- -
-
- - -
- - - -## Struct `Proposal` - -Proposal data struct. -review: it is safe to has copy and drop? - - -
struct Proposal has copy, drop, store
-
- - - -
-Fields - - -
-
-id: u64 -
-
- id of the proposal -
-
-proposer: address -
-
- creator of the proposal -
-
-title: vector<u8> -
-
- title of proposal -
-
-introduction: vector<u8> -
-
- introduction of proposal , short introduction -
-
-extend: vector<u8> -
-
- extend of proposal , ipfs:// | { "title":"xxxxx",........ } -
-
-start_time: u64 -
-
- when voting begins. -
-
-end_time: u64 -
-
- when voting ends. -
-
-yes_votes: u128 -
-
- count of voters who yes|no|abstain with the proposal -
-
-no_votes: u128 -
-
- -
-
-abstain_votes: u128 -
-
- -
-
-no_with_veto_votes: u128 -
-
- no_with_veto counts as no but also adds a veto vote -
-
-eta: u64 -
-
- executable after this time. -
-
-action_delay: u64 -
-
- after how long, the agreed proposal can be executed. -
-
-quorum_votes: u128 -
-
- how many votes to reach to make the proposal valid. -
-
-block_number: u64 -
-
- the block number when submit proposal -
-
-state_root: vector<u8> -
-
- the state root of the block which has the block_number -
-
- - -
- - - -## Struct `ProposalAction` - - - -
struct ProposalAction<Action: store> has store
-
- - - -
-Fields - - -
-
-proposal_id: u64 -
-
- id of the proposal -
-
-deposit: Token::Token<STC::STC> -
-
- -
-
-action: Action -
-
- proposal action. -
-
- - -
- - - -## Struct `ProposalActionIndex` - - - -
struct ProposalActionIndex has drop, store
-
- - - -
-Fields - - -
-
-proposal_id: u64 -
-
- id of the proposal -
-
- - -
- - - -## Resource `GlobalProposals` - -Keep a global proposal record for query proposal by id. -Replace with Table when support Table. - - -
struct GlobalProposals has key
-
- - - -
-Fields - - -
-
-proposals: vector<DAOSpace::Proposal> -
-
- -
-
- - -
- - - -## Resource `ProposalActions` - -Every ActionT keep a vector in the DAO account - - -
struct ProposalActions<ActionT: drop, store> has key
-
- - - -
-Fields - - -
-
-actions: vector<DAOSpace::ProposalAction<ActionT>> -
-
- -
-
- - -
- - - -## Resource `GlobalProposalActions` - -Keep a global proposal action record for query action by proposal_id. -Replace with Table when support Table. - - -
struct GlobalProposalActions has key
-
- - - -
-Fields - - -
-
-proposal_action_indexs: vector<DAOSpace::ProposalActionIndex> -
-
- -
-
- - -
- - - -## Struct `Vote` - -User vote. - - -
struct Vote has store
-
- - - -
-Fields - - -
-
-proposal_id: u64 -
-
- proposal id. -
-
-vote_weight: u128 -
-
- vote weight -
-
-choice: u8 -
-
- vote choise -
-
- - -
- - - -## Struct `VoteInfo` - -User vote info. has drop cap - - -
struct VoteInfo has drop, store
-
- - - -
-Fields - - -
-
-proposal_id: u64 -
-
- proposal id. -
-
-vote_weight: u128 -
-
- vote weight -
-
-choice: u8 -
-
- vote choise -
-
- - -
- - - -## Resource `MyVotes` - -Every voter keep a vector Vote for per DAO - - -
struct MyVotes<DAOT> has key
-
- - - -
-Fields - - -
-
-votes: vector<DAOSpace::Vote> -
-
- -
-
- - -
- - - -## Struct `SnapshotProof` - -use bcs se/de for Snapshot proofs - - -
struct SnapshotProof has copy, drop, store
-
- - - -
-Fields - - -
-
-state: vector<u8> -
-
- -
-
-account_state: vector<u8> -
-
- -
-
-account_proof_leaf: DAOSpace::HashNode -
-
- -
-
-account_proof_siblings: vector<vector<u8>> -
-
- -
-
-account_state_proof_leaf: DAOSpace::HashNode -
-
- -
-
-account_state_proof_siblings: vector<vector<u8>> -
-
- -
-
- - -
- - - -## Struct `HashNode` - - - -
struct HashNode has copy, drop, store
-
- - - -
-Fields - - -
-
-hash1: vector<u8> -
-
- -
-
-hash2: vector<u8> -
-
- -
-
- - -
- - - -## Resource `ProposalEvent` - -proposal event - - -
struct ProposalEvent<DAOT: store> has store, key
-
- - - -
-Fields - - -
-
-proposal_create_event: Event::EventHandle<DAOSpace::ProposalCreatedEvent> -
-
- proposal creating event. -
-
-vote_event: Event::EventHandle<DAOSpace::VotedEvent> -
-
- voting event. -
-
-proposal_action_event: Event::EventHandle<DAOSpace::ProposalActionEvent> -
-
- proposal action event. -
-
- - -
- - - -## Struct `ProposalCreatedEvent` - -emitted when proposal created. - - -
struct ProposalCreatedEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- dao id -
-
-title: vector<u8> -
-
- title -
-
-proposal_id: u64 -
-
- the proposal id. -
-
-introduction: vector<u8> -
-
- introduction of proposal , short introduction -
-
-extend: vector<u8> -
-
- extend of proposal , ipfs:// | { "title":"xxxxx",........ } -
-
-proposer: address -
-
- proposer is the user who create the proposal. -
-
- - -
- - - -## Struct `VotedEvent` - -emitted when user vote/revoke_vote. - - -
struct VotedEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- dao id -
-
-proposal_id: u64 -
-
- the proposal id. -
-
-voter: address -
-
- the voter. -
-
-choice: u8 -
-
- 1:yes, 2:no, 3:no_with_veto, 4:abstain -
-
-vote_weight: u128 -
-
- latest vote count of the voter. -
-
- - -
- - - -## Struct `ProposalActionEvent` - -emitted when proposal executed. - - -
struct ProposalActionEvent has drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- dao id -
-
-proposal_id: u64 -
-
- the proposal id. -
-
-sender: address -
-
- the sender. -
-
-state: u8 -
-
- proposal state after the action: EXTRACTED or REJECTED -
-
- - -
- - - -## Constants - - - - - - -
const ACTIVE: u8 = 2;
-
- - - - - - - -
const AGREED: u8 = 5;
-
- - - - - - - -
const DEFEATED: u8 = 4;
-
- - - - - -config or arguments - - -
const ERR_ACTION_DELAY_TOO_SMALL: u64 = 300;
-
- - - - - - - -
const ERR_ACTION_INDEX_INVALID: u64 = 501;
-
- - - - - -action - - -
const ERR_ACTION_MUST_EXIST: u64 = 500;
-
- - - - - - - -
const ERR_ALREADY_INIT: u64 = 104;
-
- - - - - - - -
const ERR_CONFIG_PARAM_INVALID: u64 = 301;
-
- - - - - - - -
const ERR_DAO_EXT: u64 = 106;
-
- - - - - -member - - -
const ERR_EXPECT_MEMBER: u64 = 200;
-
- - - - - - - -
const ERR_EXPECT_NOT_MEMBER: u64 = 201;
-
- - - - - - - -
const ERR_HAVE_SAME_GRANT: u64 = 304;
-
- - - - - - - -
const ERR_INVALID_AMOUNT: u64 = 302;
-
- - - - - - - -
const ERR_NFT_ERROR: u64 = 103;
-
- - - - - - - -
const ERR_NOT_HAVE_GRANT: u64 = 305;
-
- - - - - - - -
const ERR_NO_GRANTED: u64 = 100;
-
- - - - - -grant - - -
const ERR_OFFER_NOT_EXIST: u64 = 800;
-
- - - - - - - -
const ERR_OFFER_NOT_RECEIPTOR: u64 = 801;
-
- - - - - - - -
const ERR_PLUGIN_HAS_INSTALLED: u64 = 702;
-
- - - - - -plugin - - -
const ERR_PLUGIN_NOT_EXIST: u64 = 700;
-
- - - - - - - -
const ERR_PLUGIN_NOT_INSTALLED: u64 = 703;
-
- - - - - - - -
const ERR_PLUGIN_VERSION_NOT_EXIST: u64 = 701;
-
- - - - - - - -
const ERR_PROPOSAL_ACTIONS_NOT_EXIST: u64 = 502;
-
- - - - - - - -
const ERR_PROPOSAL_ACTION_INDEX_NOT_EXIST: u64 = 405;
-
- - - - - - - -
const ERR_PROPOSAL_ID_MISMATCH: u64 = 401;
-
- - - - - - - -
const ERR_PROPOSAL_NOT_EXIST: u64 = 403;
-
- - - - - - - -
const ERR_PROPOSAL_OUT_OF_LIMIT: u64 = 406;
-
- - - - - -proposal - - -
const ERR_PROPOSAL_STATE_INVALID: u64 = 400;
-
- - - - - - - -
const ERR_PROPOSER_MISMATCH: u64 = 402;
-
- - - - - - - -
const ERR_QUORUM_RATE_INVALID: u64 = 404;
-
- - - - - - - -
const ERR_REPEAT_ELEMENT: u64 = 101;
-
- - - - - - - -
const ERR_SNAPSHOT_PROOF_PARAM_INVALID: u64 = 604;
-
- - - - - - - -
const ERR_STATE_PROOF_VERIFY_INVALID: u64 = 605;
-
- - - - - - - -
const ERR_STORAGE_ERROR: u64 = 102;
-
- - - - - - - -
const ERR_TOKEN_ERROR: u64 = 105;
-
- - - - - - - -
const ERR_TOO_SMALL_TOTAL: u64 = 303;
-
- - - - - - - -
const ERR_VOTED_ALREADY: u64 = 602;
-
- - - - - - - -
const ERR_VOTED_OTHERS_ALREADY: u64 = 601;
-
- - - - - - - -
const ERR_VOTE_PARAM_INVALID: u64 = 603;
-
- - - - - -vote - - -
const ERR_VOTE_STATE_MISMATCH: u64 = 600;
-
- - - - - - - -
const EXECUTABLE: u8 = 7;
-
- - - - - - - -
const EXTRACTED: u8 = 8;
-
- - - - - - - -
const MAX_PROPOSALS: u64 = 1000;
-
- - - - - - - -
const MEMBERJOIN_DIRECT: u8 = 0;
-
- - - - - - - -
const MEMBERJOIN_OFFER: u8 = 1;
-
- - - - - - - -
const MEMBER_OFFER_CREATE: u8 = 0;
-
- - - - - - - -
const MEMBER_OFFER_REBACK: u8 = 1;
-
- - - - - - - -
const MEMBER_OFFER_USE: u8 = 2;
-
- - - - - -Proposal --------------------------------------------------- -Proposal state - - -
const PENDING: u8 = 1;
-
- - - - - - - -
const QUEUED: u8 = 6;
-
- - - - - - - -
const REJECTED: u8 = 3;
-
- - - - - - - -
const VOTING_CHOICE_ABSTAIN: u8 = 4;
-
- - - - - - - -
const VOTING_CHOICE_NO: u8 = 2;
-
- - - - - - - -
const VOTING_CHOICE_NO_WITH_VETO: u8 = 3;
-
- - - - - -voting choice: 1:yes, 2:no, 3: no_with_veto, 4:abstain - - -
const VOTING_CHOICE_YES: u8 = 1;
-
- - - - - -## Function `install_plugin_cap_type` - -Create a install plugin capability type. - - -
public fun install_plugin_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun install_plugin_cap_type(): CapType { CapType{ code: 0 } }
-
- - - -
- - - -## Function `upgrade_module_cap_type` - -Create a upgrade module capability type. - - -
public fun upgrade_module_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun upgrade_module_cap_type(): CapType { CapType{ code: 1 } }
-
- - - -
- - - -## Function `modify_config_cap_type` - -Create a modify dao config capability type. - - -
public fun modify_config_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun modify_config_cap_type(): CapType { CapType{ code: 2 } }
-
- - - -
- - - -## Function `withdraw_token_cap_type` - -Create a withdraw Token capability type. - - -
public fun withdraw_token_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun withdraw_token_cap_type(): CapType { CapType{ code: 3 } }
-
- - - -
- - - -## Function `withdraw_nft_cap_type` - -Create a withdraw NFT capability type. - - -
public fun withdraw_nft_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun withdraw_nft_cap_type(): CapType { CapType{ code: 4 } }
-
- - - -
- - - -## Function `storage_cap_type` - -Create a write data to DAO account capability type. - - -
public fun storage_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun storage_cap_type(): CapType { CapType{ code: 5 } }
-
- - - -
- - - -## Function `member_cap_type` - -Create a member capability type. -This cap can issue DAO member NFT or update member's SBT - - -
public fun member_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun member_cap_type(): CapType { CapType{ code: 6 } }
-
- - - -
- - - -## Function `proposal_cap_type` - -Create a vote capability type. - - -
public fun proposal_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun proposal_cap_type(): CapType { CapType{ code: 7 } }
-
- - - -
- - - -## Function `grant_cap_type` - -Create a grant capability type. - - -
public fun grant_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun grant_cap_type(): CapType { CapType{ code: 8 } }
-
- - - -
- - - -## Function `token_mint_cap_type` - -Create a token minting capability type. - - -
public fun token_mint_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun token_mint_cap_type(): CapType { CapType{code: 9 } }
-
- - - -
- - - -## Function `token_burn_cap_type` - -Create a token burning capability type. - - -
public fun token_burn_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun token_burn_cap_type(): CapType { CapType{code: 10 } }
-
- - - -
- - - -## Function `plugin_event_cap_type` - -Creates a grant capability type. - - -
public fun plugin_event_cap_type(): DAOSpace::CapType
-
- - - -
-Implementation - - -
public fun plugin_event_cap_type(): CapType { CapType{ code: 11 } }
-
- - - -
- - - -## Function `all_caps` - -Create all capability types. - - -
public fun all_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun all_caps(): vector<CapType> {
-    let caps = Vector::singleton(install_plugin_cap_type());
-    Vector::push_back(&mut caps, upgrade_module_cap_type());
-    Vector::push_back(&mut caps, modify_config_cap_type());
-    Vector::push_back(&mut caps, withdraw_token_cap_type());
-    Vector::push_back(&mut caps, withdraw_nft_cap_type());
-    Vector::push_back(&mut caps, storage_cap_type());
-    Vector::push_back(&mut caps, member_cap_type());
-    Vector::push_back(&mut caps, proposal_cap_type());
-    Vector::push_back(&mut caps, grant_cap_type());
-    Vector::push_back(&mut caps, token_mint_cap_type());
-    Vector::push_back(&mut caps, token_burn_cap_type());
-    Vector::push_back(&mut caps, plugin_event_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_dao` - -Create a dao with a exists DAO account - - -
public fun create_dao<DAOT: store>(cap: DAOAccount::DAOAccountCap, name: vector<u8>, image_data: Option::Option<vector<u8>>, image_url: Option::Option<vector<u8>>, description: vector<u8>, config: DAOSpace::DAOConfig)
-
- - - -
-Implementation - - -
public fun create_dao<DAOT: store>(
-    cap: DAOAccountCap,
-    name: vector<u8>,
-    image_data:Option::Option<vector<u8>>,
-    image_url:Option::Option<vector<u8>>,
-    description: vector<u8>,
-    config: DAOConfig
-) acquires DAOEvent {
-    let dao_signer = DAOAccount::dao_signer(&cap);
-
-    let dao_address = Signer::address_of(&dao_signer);
-    let id = DAORegistry::register<DAOT>(dao_address);
-    ASCII::string(copy name);
-    let dao = DAO{
-        id,
-        name: copy name,
-        description: copy description,
-        dao_address,
-        next_member_id: 1,
-        next_proposal_id: 1,
-    };
-
-    move_to(&dao_signer, dao);
-    move_to(&dao_signer, DAOAccountCapHolder{
-        cap
-    });
-
-    Token::register_token<DAOT>(&dao_signer, 1);
-    let token_mint_cap = Token::remove_mint_capability<DAOT>(&dao_signer);
-    let token_burn_cap = Token::remove_burn_capability<DAOT>(&dao_signer);
-
-    move_to(&dao_signer, DAOSBTMintCapHolder{
-        cap: token_mint_cap,
-    });
-    move_to(&dao_signer, DAOSBTBurnCapHolder{
-        cap: token_burn_cap,
-    });
-
-    let nft_name = copy name;
-    let nft_description = copy name;
-    let basemeta = if(Option::is_some(&image_data)){
-        NFT::new_meta_with_image_data(nft_name, Option::destroy_some(image_data), nft_description)
-    }else if(Option::is_some(&image_url)){
-        NFT::new_meta_with_image(nft_name, Option::destroy_some(image_url), nft_description)
-    }else{
-        NFT::new_meta(nft_name, nft_description)
-    };
-
-
-    NFT::register_v2<DAOMember<DAOT>>(&dao_signer, basemeta);
-    let nft_mint_cap = NFT::remove_mint_capability<DAOMember<DAOT>>(&dao_signer);
-    move_to(&dao_signer, DAONFTMintCapHolder{
-        cap: nft_mint_cap,
-    });
-
-    let nft_burn_cap = NFT::remove_burn_capability<DAOMember<DAOT>>(&dao_signer);
-    move_to(&dao_signer, DAONFTBurnCapHolder{
-        cap: nft_burn_cap,
-    });
-
-    let nft_update_cap = NFT::remove_update_capability<DAOMember<DAOT>>(&dao_signer);
-    move_to(&dao_signer, DAONFTUpdateCapHolder{
-        cap: nft_update_cap,
-    });
-
-    let config_modify_cap = Config::publish_new_config_with_capability(&dao_signer, config);
-    move_to(&dao_signer, DAOConfigModifyCapHolder{
-        cap: config_modify_cap,
-    });
-
-    move_to(&dao_signer, DAOEvent<DAOT>  {
-        dao_create_event: Event::new_event_handle<DAOCreatedEvent>(&dao_signer),
-    });
-    move_to(&dao_signer ,MemberEvent{
-        member_offer_event_handler: Event::new_event_handle<MemberOfferEvent>(&dao_signer),
-        member_join_event_handler:Event::new_event_handle<MemberJoinEvent>(&dao_signer),
-        member_quit_event_handler:Event::new_event_handle<MemberQuitEvent>(&dao_signer),
-        member_revoke_event_handler:Event::new_event_handle<MemberRevokeEvent>(&dao_signer),
-        member_increase_sbt_event_handler:Event::new_event_handle<MemberIncreaseSBTEvent>(&dao_signer),
-        member_decrease_sbt_event_handler:Event::new_event_handle<MemberDecreaseSBTEvent>(&dao_signer),
-    });
-    move_to(&dao_signer, ProposalEvent<DAOT>  {
-        proposal_create_event: Event::new_event_handle<ProposalCreatedEvent>(&dao_signer),
-        vote_event: Event::new_event_handle<VotedEvent>(&dao_signer),
-        proposal_action_event: Event::new_event_handle<ProposalActionEvent>(&dao_signer),
-    });
-
-    // dao event emit
-    let dao_event = borrow_global_mut<DAOEvent<DAOT> >(dao_address);
-    Event::emit_event(&mut dao_event.dao_create_event,
-        DAOCreatedEvent {
-            id,
-            name: copy name,
-            description:copy description,
-            dao_address,
-        },
-    );
-}
-
- - - -
- - - -## Function `upgrade_to_dao` - -Upgrade account to DAO account and create DAO - - -
public fun upgrade_to_dao<DAOT: store>(sender: signer, name: vector<u8>, image_data: Option::Option<vector<u8>>, image_url: Option::Option<vector<u8>>, description: vector<u8>, config: DAOSpace::DAOConfig)
-
- - - -
-Implementation - - -
public fun upgrade_to_dao<DAOT: store>(
-    sender: signer,
-    name: vector<u8>,
-    image_data:Option::Option<vector<u8>>,
-    image_url:Option::Option<vector<u8>>,
-    description:vector<u8>,
-    config: DAOConfig
-) acquires DAOEvent{
-    let cap = DAOAccount::upgrade_to_dao(sender);
-    create_dao<DAOT>(cap, name, image_data, image_url, description, config)
-}
-
- - - -
- - - -## Function `install_plugin` - -Install plugin with DAOInstallPluginCap - - -
public fun install_plugin<DAOT: store, PluginT: store, ToInstallPluginT: store>(_cap: &DAOSpace::DAOInstallPluginCap<DAOT, PluginT>, granted_caps: vector<DAOSpace::CapType>)
-
- - - -
-Implementation - - -
public fun install_plugin<DAOT: store, PluginT:store, ToInstallPluginT:store>(_cap: &DAOInstallPluginCap<DAOT, PluginT>, granted_caps: vector<CapType>) acquires DAOAccountCapHolder {
-    do_install_plugin<DAOT, ToInstallPluginT>(granted_caps);
-}
-
- - - -
- - - -## Function `do_install_plugin` - - - -
fun do_install_plugin<DAOT: store, ToInstallPluginT: store>(granted_caps: vector<DAOSpace::CapType>)
-
- - - -
-Implementation - - -
fun do_install_plugin<DAOT: store, ToInstallPluginT:store>(granted_caps: vector<CapType>) acquires DAOAccountCapHolder {
-    assert!(DAOPluginMarketplace::exists_plugin<ToInstallPluginT>(), Errors::invalid_state(ERR_PLUGIN_NOT_EXIST));
-    assert_no_repeat(&granted_caps);
-    let dao_signer = dao_signer<DAOT>();
-    let plugin_id = DAOPluginMarketplace::take_plugin_id<ToInstallPluginT>();
-
-    assert!(!exists<InstalledPluginInfo<ToInstallPluginT>>(Signer::address_of(&dao_signer)), Errors::already_published(ERR_PLUGIN_HAS_INSTALLED));
-    move_to(&dao_signer, InstalledPluginInfo<ToInstallPluginT>{
-        plugin_id: plugin_id,
-        granted_caps,
-    });
-}
-
- - - -
- - - -## Function `uninstall_plugin` - -Uninstall plugin with DAOInstallPluginCap - - -
public fun uninstall_plugin<DAOT: store, PluginT: store, ToInstallPluginT: store>(_cap: &DAOSpace::DAOInstallPluginCap<DAOT, PluginT>)
-
- - - -
-Implementation - - -
public fun uninstall_plugin<DAOT: store, PluginT:store, ToInstallPluginT:store>(_cap: &DAOInstallPluginCap<DAOT, PluginT>) acquires DAOAccountCapHolder, InstalledPluginInfo {
-    do_uninstall_plugin<DAOT, ToInstallPluginT>();
-}
-
- - - -
- - - -## Function `do_uninstall_plugin` - - - -
fun do_uninstall_plugin<DAOT: store, ToInstallPluginT: store>()
-
- - - -
-Implementation - - -
fun do_uninstall_plugin<DAOT: store, ToInstallPluginT:store>() acquires DAOAccountCapHolder, InstalledPluginInfo {
-    assert!(DAOPluginMarketplace::exists_plugin<ToInstallPluginT>(), Errors::invalid_state(ERR_PLUGIN_NOT_EXIST));
-
-    let dao_signer = dao_signer<DAOT>();
-    let dao_address = Signer::address_of(&dao_signer);
-
-    assert!(exists<InstalledPluginInfo<ToInstallPluginT>>(dao_address), Errors::already_published(ERR_PLUGIN_NOT_INSTALLED));
-    let installed_plugin = move_from<InstalledPluginInfo<ToInstallPluginT>>(dao_address);
-
-    let InstalledPluginInfo<ToInstallPluginT> {
-        plugin_id:_,
-        granted_caps:_,
-    } = installed_plugin;
-}
-
- - - -
- - - -## Function `submit_upgrade_plan` - -Submit upgrade module plan - - -
public fun submit_upgrade_plan<DAOT: store, PluginT>(_cap: &DAOSpace::DAOUpgradeModuleCap<DAOT, PluginT>, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public fun submit_upgrade_plan<DAOT: store, PluginT>(_cap: &DAOUpgradeModuleCap<DAOT, PluginT>, package_hash: vector<u8>, version: u64, enforced: bool) acquires DAOAccountCapHolder {
-    let dao_account_cap = &mut borrow_global_mut<DAOAccountCapHolder>(dao_address<DAOT>()).cap;
-    DAOAccount::submit_upgrade_plan(dao_account_cap, package_hash, version, enforced);
-}
-
- - - -
- - - -## Function `save_to_storage` - -Save the item to the storage - - -
public fun save_to_storage<DAOT: store, PluginT, V: store>(_cap: &DAOSpace::DAOStorageCap<DAOT, PluginT>, item: V)
-
- - - -
-Implementation - - -
public fun save_to_storage<DAOT: store, PluginT, V: store>(_cap: &DAOStorageCap<DAOT, PluginT>, item: V) acquires DAOAccountCapHolder {
-    let dao_signer = dao_signer<DAOT>();
-    assert!(!exists<StorageItem<PluginT, V>>(Signer::address_of(&dao_signer)), Errors::already_published(ERR_STORAGE_ERROR));
-    move_to(&dao_signer, StorageItem<PluginT, V>{
-        item
-    });
-}
-
- - - -
- - - -## Function `take_from_storage` - -Get the item from the storage - - -
public fun take_from_storage<DAOT: store, PluginT, V: store>(_cap: &DAOSpace::DAOStorageCap<DAOT, PluginT>): V
-
- - - -
-Implementation - - -
public fun take_from_storage<DAOT: store, PluginT, V: store>(_cap: &DAOStorageCap<DAOT, PluginT>): V acquires StorageItem {
-    let dao_address = dao_address<DAOT>();
-    assert!(exists<StorageItem<PluginT, V>>(dao_address), Errors::not_published(ERR_STORAGE_ERROR));
-    let StorageItem{ item } = move_from<StorageItem<PluginT, V>>(dao_address);
-    item
-}
-
- - - -
- - - -## Function `exists_in_storage` - -Check the item has exists in storage - - -
public fun exists_in_storage<DAOT: store, PluginT, V: store>(): bool
-
- - - -
-Implementation - - -
public fun exists_in_storage<DAOT: store, PluginT, V: store>(): bool {
-    exists<StorageItem<PluginT, V>>(dao_address<DAOT>())
-}
-
- - - -
- - - -## Function `copy_from_storage` - -Copy the item from the storage - - -
public fun copy_from_storage<DAOT: store, PluginT, V: copy, store>(_cap: &DAOSpace::DAOStorageCap<DAOT, PluginT>): V
-
- - - -
-Implementation - - -
public fun copy_from_storage<DAOT: store, PluginT, V: store+copy>(_cap: &DAOStorageCap<DAOT, PluginT>): V acquires StorageItem {
-    let dao_address = dao_address<DAOT>();
-    assert!(exists<StorageItem<PluginT, V>>(dao_address), Errors::not_published(ERR_STORAGE_ERROR));
-    let storage_item  = borrow_global<StorageItem<PluginT, V>>(dao_address);
-    *&storage_item.item
-}
-
- - - -
- - - -## Function `withdraw_token` - -Withdraw the token from the DAO account - - -
public fun withdraw_token<DAOT: store, PluginT, TokenT: store>(_cap: &DAOSpace::DAOWithdrawTokenCap<DAOT, PluginT>, amount: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun withdraw_token<DAOT: store, PluginT, TokenT: store>(_cap: &DAOWithdrawTokenCap<DAOT, PluginT>, amount: u128): Token<TokenT> acquires DAOAccountCapHolder {
-    let dao_signer = dao_signer<DAOT>();
-    //we should extract the WithdrawCapability from account, and invoke the withdraw_with_cap ?
-    Account::withdraw<TokenT>(&dao_signer, amount)
-}
-
- - - -
- - - -## Function `withdraw_nft` - -Withdraw the NFT from the DAO account - - -
public fun withdraw_nft<DAOT: store, PluginT, NFTMeta: copy, drop, store, NFTBody: store>(_cap: &DAOSpace::DAOWithdrawNFTCap<DAOT, PluginT>, id: u64): NFT::NFT<NFTMeta, NFTBody>
-
- - - -
-Implementation - - -
public fun withdraw_nft<DAOT: store, PluginT, NFTMeta: store + copy + drop, NFTBody: store>(_cap: &DAOWithdrawNFTCap<DAOT, PluginT>, id: u64): NFT<NFTMeta, NFTBody> acquires DAOAccountCapHolder {
-    let dao_signer = dao_signer<DAOT>();
-    let nft = NFTGallery::withdraw<NFTMeta, NFTBody>(&dao_signer, id);
-    assert!(Option::is_some(&nft), Errors::not_published(ERR_NFT_ERROR));
-    Option::destroy_some(nft)
-}
-
- - - -
- - - -## Function `issue_member_offer` - -invite a new member to the DAO - - -
public fun issue_member_offer<DAOT: store, PluginT>(_cap: &DAOSpace::DAOMemberCap<DAOT, PluginT>, to_address: address, image_data: Option::Option<vector<u8>>, image_url: Option::Option<vector<u8>>, init_sbt: u128)
-
- - - -
-Implementation - - -
public fun issue_member_offer<DAOT: store, PluginT>(_cap: &DAOMemberCap<DAOT, PluginT>, to_address: address, image_data:Option::Option<vector<u8>>, image_url:Option::Option<vector<u8>>, init_sbt: u128) acquires DAOAccountCapHolder, MemberEvent, DAO {
-    let dao_address = dao_address<DAOT>();
-    let dao_signer = dao_signer<DAOT>();
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    if(is_member<DAOT>(to_address)){
-        Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent {
-            dao_id: dao_id(dao_address),
-            addr:to_address,
-            type:MEMBER_OFFER_REBACK,
-            image_data,
-            image_url,
-            sbt: init_sbt,
-        });
-        return
-    };
-
-    let op_index = Offer::find_offer<MemeberOffer<DAOT>>(dao_address, to_address);
-    if(Option::is_some(&op_index)){
-        let MemeberOffer<DAOT>{
-            to_address,
-            image_data,
-            image_url,
-            init_sbt
-        } = Offer::retake<MemeberOffer<DAOT>>(&dao_signer, Option::destroy_some(op_index));
-        Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent {
-            dao_id: dao_id(dao_address),
-            addr:to_address,
-            type:MEMBER_OFFER_REBACK,
-            image_data,
-            image_url,
-            sbt: init_sbt,
-        });
-        return
-    };
-
-    let offered = MemeberOffer<DAOT> {
-        to_address,
-        image_data: copy image_data,
-        image_url: copy image_url,
-        init_sbt
-    };
-    Offer::create_v2<MemeberOffer<DAOT>>(&dao_signer, offered, to_address, 0);
-
-    Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent {
-        dao_id: dao_id(dao_address),
-        addr:to_address,
-        type:MEMBER_OFFER_CREATE,
-        image_data,
-        image_url,
-        sbt: init_sbt,
-    });
-}
-
- - - -
- - - -## Function `revoke_member_offer` - -Review the member offer - - -
public fun revoke_member_offer<DAOT: store, PluginT>(_cap: &DAOSpace::DAOMemberCap<DAOT, PluginT>, to_address: address)
-
- - - -
-Implementation - - -
public fun revoke_member_offer<DAOT: store, PluginT>(_cap: &DAOMemberCap<DAOT, PluginT>, to_address: address) acquires DAOAccountCapHolder, MemberEvent, DAO {
-    let dao_address = dao_address<DAOT>();
-    let dao_signer = dao_signer<DAOT>();
-    let op_index = Offer::find_offer<MemeberOffer<DAOT>>(dao_address, to_address);
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    if(Option::is_some(&op_index)){
-        let MemeberOffer<DAOT>{
-            to_address,
-            image_data,
-            image_url,
-            init_sbt
-        } = Offer::retake<MemeberOffer<DAOT>>(&dao_signer, Option::destroy_some(op_index));
-        Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent {
-            dao_id: dao_id(dao_address),
-            addr:to_address,
-            type:MEMBER_OFFER_REBACK,
-            image_data,
-            image_url,
-            sbt: init_sbt,
-        });
-    }
-}
-
- - - -
- - - -## Function `accept_member_offer` - -Accept the MemberOffer and become a member - - -
public fun accept_member_offer<DAOT: store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun accept_member_offer<DAOT: store>(sender: &signer) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent, DAONFTUpdateCapHolder {
-    let dao_address = dao_address<DAOT>();
-    let op_index = Offer::find_offer<MemeberOffer<DAOT>>(dao_address, Signer::address_of(sender));
-    assert!(Option::is_some(&op_index),1003);
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    let MemeberOffer<DAOT> {
-        to_address,
-        image_data,
-        image_url,
-        init_sbt
-    }= Offer::redeem_v2<MemeberOffer<DAOT>>(sender, dao_address, Option::destroy_some(op_index));
-    assert!(to_address == Signer::address_of(sender), Errors::invalid_argument(ERR_OFFER_NOT_RECEIPTOR));
-    Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent {
-        dao_id: dao_id(dao_address),
-        addr:to_address,
-        type:MEMBER_OFFER_USE,
-        image_data: copy image_data,
-        image_url: copy image_url,
-        sbt: init_sbt,
-    });
-    if(is_member<DAOT>(to_address)){
-        increase_member_sbt<DAOT, DAOT>(&DAOMemberCap<DAOT, DAOT>{}, to_address, init_sbt);
-    }else{
-        do_join_member<DAOT>(sender, image_data, image_url, init_sbt);
-        Event::emit_event(&mut memeber_event.member_join_event_handler, MemberJoinEvent {
-            dao_id: dao_id(dao_address),
-            type:MEMBERJOIN_OFFER,
-            member_id:Option::destroy_some(query_member_id<DAOT>(to_address)),
-            addr:to_address,
-            sbt: init_sbt,
-        });
-    }
-}
-
- - - -
- - - -## Function `accept_member_offer_entry` - - - -
public(script) fun accept_member_offer_entry<DAOT: store>(sender: signer)
-
- - - -
-Implementation - - -
public (script) fun accept_member_offer_entry<DAOT: store>(sender: signer) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent , DAONFTUpdateCapHolder {
-    accept_member_offer<DAOT>(&sender)
-}
-
- - - -
- - - -## Function `do_join_member` - - - -
fun do_join_member<DAOT: store>(sender: &signer, image_data: Option::Option<vector<u8>>, image_url: Option::Option<vector<u8>>, init_sbt: u128)
-
- - - -
-Implementation - - -
fun do_join_member<DAOT: store>(sender: &signer, image_data:Option::Option<vector<u8>>, image_url:Option::Option<vector<u8>>, init_sbt: u128) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO {
-    let to_address = Signer::address_of(sender);
-    ensure_not_member<DAOT>(to_address);
-    IdentifierNFT::accept<DAOMember<DAOT>, DAOMemberBody<DAOT>>(sender);
-    let member_id = next_member_id<DAOT>();
-
-    let meta = DAOMember<DAOT>{
-        id: member_id,
-    };
-
-    let dao_address = dao_address<DAOT>();
-
-    let token_mint_cap = &borrow_global_mut<DAOSBTMintCapHolder<DAOT>>(dao_address).cap;
-    let sbt = Token::mint_with_capability<DAOT>(token_mint_cap, init_sbt);
-
-    let body = DAOMemberBody<DAOT>{
-        sbt,
-    };
-
-    let dao = borrow_global<DAO>(dao_address);
-    let nft_name = *&dao.name;
-    let nft_description = *&dao.name;
-
-    let basemeta = if(Option::is_some(&image_data)){
-        NFT::new_meta_with_image_data(nft_name, Option::destroy_some(image_data), nft_description)
-    }else if(Option::is_some(&image_url)){
-        NFT::new_meta_with_image(nft_name, Option::destroy_some(image_url), nft_description)
-    }else{
-        NFT::new_meta(nft_name, nft_description)
-    };
-    let nft_mint_cap = &mut borrow_global_mut<DAONFTMintCapHolder<DAOT>>(dao_address).cap;
-
-    let nft = NFT::mint_with_cap_v2(dao_address, nft_mint_cap, basemeta, meta, body);
-    IdentifierNFT::grant_to(nft_mint_cap, to_address, nft);
-}
-
- - - -
- - - -## Function `quit_member_entry` - -Member quit DAO by self - - -
public(script) fun quit_member_entry<DAOT: store>(sender: signer)
-
- - - -
-Implementation - - -
public (script) fun quit_member_entry<DAOT: store>(sender: signer) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO, DAOAccountCapHolder {
-    quit_member<DAOT>(&sender);
-}
-
- - - -
- - - -## Function `quit_member` - -Member quit DAO by self - - -
public fun quit_member<DAOT: store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun quit_member<DAOT: store>(sender: &signer) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO, DAOAccountCapHolder {
-    let member_addr = Signer::address_of(sender);
-    if(!is_member<DAOT>(member_addr)){
-        let dao_address = dao_address<DAOT>();
-        let dao_signer = dao_signer<DAOT>();
-        let op_index = Offer::find_offer<MemeberOffer<DAOT>>(dao_address, member_addr);
-        if(Option::is_some(&op_index)){
-            Offer::retake<MemeberOffer<DAOT>>(&dao_signer, Option::destroy_some(op_index));
-        };
-        return
-    };
-
-    let (member_id , sbt) = do_remove_member<DAOT>(member_addr);
-    let dao_address = dao_address<DAOT>();
-
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    Event::emit_event(&mut memeber_event.member_quit_event_handler, MemberQuitEvent {
-        dao_id: dao_id(dao_address),
-        member_id,
-        addr:member_addr,
-        sbt,
-    });
-}
-
- - - -
- - - -## Function `revoke_member` - -Revoke membership with cap - - -
public fun revoke_member<DAOT: store, PluginT>(_cap: &DAOSpace::DAOMemberCap<DAOT, PluginT>, member_addr: address)
-
- - - -
-Implementation - - -
public fun revoke_member<DAOT: store, PluginT>(_cap: &DAOMemberCap<DAOT, PluginT>, member_addr: address) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO {
-    let (member_id , sbt) = do_remove_member<DAOT>(member_addr);
-    let dao_address = dao_address<DAOT>();
-
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    Event::emit_event(&mut memeber_event.member_revoke_event_handler, MemberRevokeEvent {
-        dao_id: dao_id(dao_address),
-        member_id,
-        addr:member_addr,
-        sbt: sbt,
-    });
-}
-
- - - -
- - - -## Function `ensure_member` - - - -
public fun ensure_member<DAOT: store>(member_addr: address)
-
- - - -
-Implementation - - -
public fun ensure_member<DAOT: store>(member_addr:address){
-    assert!(is_member<DAOT>(member_addr), Errors::invalid_state(ERR_EXPECT_MEMBER));
-}
-
- - - -
- - - -## Function `ensure_not_member` - - - -
public fun ensure_not_member<DAOT: store>(member_addr: address)
-
- - - -
-Implementation - - -
public fun ensure_not_member<DAOT: store>(member_addr:address){
-    assert!(!is_member<DAOT>(member_addr), Errors::invalid_state(ERR_EXPECT_NOT_MEMBER));
-}
-
- - - -
- - - -## Function `do_remove_member` - - - -
fun do_remove_member<DAOT: store>(member_addr: address): (u64, u128)
-
- - - -
-Implementation - - -
fun do_remove_member<DAOT: store>(member_addr: address):(u64,u128) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder {
-    ensure_member<DAOT>(member_addr);
-    let dao_address = dao_address<DAOT>();
-
-    let nft_burn_cap = &mut borrow_global_mut<DAONFTBurnCapHolder<DAOT>>(dao_address).cap;
-    let nft = IdentifierNFT::revoke<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft_burn_cap, member_addr);
-    let member_id = NFT::get_type_meta<DAOMember<DAOT>, DAOMemberBody<DAOT>>(&nft).id;
-    let DAOMemberBody<DAOT>{ sbt } = NFT::burn_with_cap(nft_burn_cap, nft);
-    let sbt_amount = Token::value<DAOT>(&sbt);
-    let token_burn_cap = &mut borrow_global_mut<DAOSBTBurnCapHolder<DAOT>>(dao_address).cap;
-    Token::burn_with_capability(token_burn_cap, sbt);
-    (member_id, sbt_amount)
-}
-
- - - -
- - - -## Function `join_member_with_member_cap` - - - -
public fun join_member_with_member_cap<DAOT: store, Plugin>(_cap: &DAOSpace::DAOMemberCap<DAOT, Plugin>, sender: &signer, image_data: Option::Option<vector<u8>>, image_url: Option::Option<vector<u8>>, init_sbt: u128)
-
- - - -
-Implementation - - -
public fun join_member_with_member_cap<DAOT: store, Plugin>(
-    _cap: &DAOMemberCap<DAOT, Plugin>,
-    sender: &signer,
-    image_data:Option::Option<vector<u8>>,
-    image_url:Option::Option<vector<u8>>,
-    init_sbt: u128
-) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent {
-    let dao_address = dao_address<DAOT>();
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    do_join_member<DAOT>(sender, image_data, image_url, init_sbt);
-    let to_address = Signer::address_of(sender);
-    Event::emit_event(&mut memeber_event.member_join_event_handler, MemberJoinEvent {
-        dao_id: dao_id(dao_address),
-        type:MEMBERJOIN_DIRECT,
-        member_id:Option::destroy_some(query_member_id<DAOT>(to_address)),
-        addr:to_address,
-        sbt: init_sbt,
-    });
-}
-
- - - -
- - - -## Function `increase_member_sbt` - -Increment the member SBT - - -
public fun increase_member_sbt<DAOT: store, PluginT>(_cap: &DAOSpace::DAOMemberCap<DAOT, PluginT>, member_addr: address, amount: u128)
-
- - - -
-Implementation - - -
public fun increase_member_sbt<DAOT: store, PluginT>(_cap: &DAOMemberCap<DAOT, PluginT>, member_addr: address, amount: u128) acquires DAONFTUpdateCapHolder, DAOSBTMintCapHolder, MemberEvent {
-    ensure_member<DAOT>(member_addr);
-    let dao_address = dao_address<DAOT>();
-
-    let nft_update_cap = &mut borrow_global_mut<DAONFTUpdateCapHolder<DAOT>>(dao_address).cap;
-    let borrow_nft = IdentifierNFT::borrow_out<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft_update_cap, member_addr);
-    let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft);
-    let member_id = NFT::get_type_meta<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft).id;
-
-    let body = NFT::borrow_body_mut_with_cap(nft_update_cap, nft);
-
-    let token_mint_cap = &mut borrow_global_mut<DAOSBTMintCapHolder<DAOT>>(dao_address).cap;
-    let increase_sbt = Token::mint_with_capability<DAOT>(token_mint_cap, amount);
-    Token::deposit(&mut body.sbt, increase_sbt);
-
-    let sbt_amount = Token::value<DAOT>(&body.sbt);
-    IdentifierNFT::return_back(borrow_nft);
-
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    Event::emit_event(&mut memeber_event.member_increase_sbt_event_handler, MemberIncreaseSBTEvent {
-        member_id,
-        addr:member_addr,
-        increase_sbt:amount,
-        sbt: sbt_amount,
-    });
-}
-
- - - -
- - - -## Function `decrease_member_sbt` - -Decrement the member SBT - - -
public fun decrease_member_sbt<DAOT: store, PluginT>(_cap: &DAOSpace::DAOMemberCap<DAOT, PluginT>, member_addr: address, amount: u128)
-
- - - -
-Implementation - - -
public fun decrease_member_sbt<DAOT: store, PluginT>(_cap: &DAOMemberCap<DAOT, PluginT>, member_addr: address, amount: u128) acquires DAONFTUpdateCapHolder, DAOSBTBurnCapHolder, MemberEvent {
-    ensure_member<DAOT>(member_addr);
-    let dao_address = dao_address<DAOT>();
-
-    let nft_update_cap = &mut borrow_global_mut<DAONFTUpdateCapHolder<DAOT>>(dao_address).cap;
-    let borrow_nft = IdentifierNFT::borrow_out<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft_update_cap, member_addr);
-    let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft);
-    let member_id = NFT::get_type_meta<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft).id;
-
-    let body = NFT::borrow_body_mut_with_cap(nft_update_cap, nft);
-
-    let token_burn_cap = &mut borrow_global_mut<DAOSBTBurnCapHolder<DAOT>>(dao_address).cap;
-    let decrease_sbt = Token::withdraw(&mut body.sbt, amount);
-    let sbt_amount = Token::value<DAOT>(&body.sbt);
-
-    Token::burn_with_capability(token_burn_cap, decrease_sbt);
-    IdentifierNFT::return_back(borrow_nft);
-
-    let memeber_event = borrow_global_mut<MemberEvent>(dao_address);
-    Event::emit_event(&mut memeber_event.member_decrease_sbt_event_handler, MemberDecreaseSBTEvent {
-        member_id,
-        addr:member_addr,
-        decrease_sbt:amount,
-        sbt: sbt_amount,
-    });
-}
-
- - - -
- - - -## Function `set_member_image` - - - -
public fun set_member_image<DAOT: store, PluginT>(_cap: &DAOSpace::DAOMemberCap<DAOT, PluginT>, member_addr: address, image_data: Option::Option<vector<u8>>, image_url: Option::Option<vector<u8>>)
-
- - - -
-Implementation - - -
public fun set_member_image<DAOT: store, PluginT>(
-    _cap: &DAOMemberCap<DAOT, PluginT>,
-    member_addr: address,
-    image_data: Option::Option<vector<u8>>,
-    image_url: Option::Option<vector<u8>>
-) acquires DAONFTUpdateCapHolder {
-    ensure_member<DAOT>(member_addr);
-
-    let dao_address = dao_address<DAOT>();
-
-    let nft_update_cap = &mut borrow_global_mut<DAONFTUpdateCapHolder<DAOT>>(dao_address).cap;
-    let borrow_nft = IdentifierNFT::borrow_out<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft_update_cap, member_addr);
-    let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft);
-    let metadata = *NFT::get_type_meta<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft);
-    let old_basemeta = NFT::get_base_meta<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft);
-    let new_basemeta = if(Option::is_some(&image_data)){
-        NFT::new_meta_with_image_data(NFT::meta_name(old_basemeta), Option::destroy_some(image_data), NFT::meta_description(old_basemeta))
-    }else if(Option::is_some(&image_url)){
-        NFT::new_meta_with_image(NFT::meta_name(old_basemeta), Option::destroy_some(image_url), NFT::meta_description(old_basemeta))
-    }else{
-        NFT::new_meta(NFT::meta_name(old_basemeta), NFT::meta_description(old_basemeta))
-    };
-    NFT::update_meta_with_cap(nft_update_cap, nft, new_basemeta, metadata);
-
-    IdentifierNFT::return_back(borrow_nft);
-}
-
- - - -
- - - -## Function `query_sbt` - -Query amount of the member SBT - - -
public fun query_sbt<DAOT: store>(member_addr: address): u128
-
- - - -
-Implementation - - -
public fun query_sbt<DAOT: store>(member_addr: address)
-: u128 acquires DAONFTUpdateCapHolder {
-    if (!is_member<DAOT>(member_addr)) {
-        return 0
-    };
-    let dao_address = dao_address<DAOT>();
-
-    let nft_update_cap =
-        &mut borrow_global_mut<DAONFTUpdateCapHolder<DAOT>>(dao_address).cap;
-    let borrow_nft =
-        IdentifierNFT::borrow_out<DAOMember<DAOT>, DAOMemberBody<DAOT>>(nft_update_cap, member_addr);
-    let nft = IdentifierNFT::borrow_nft(&mut borrow_nft);
-    let body = NFT::borrow_body(nft);
-
-    let result = Token::value(&body.sbt);
-    IdentifierNFT::return_back(borrow_nft);
-    result
-}
-
- - - -
- - - -## Function `query_member_id` - -Query member id of the member - - -
public fun query_member_id<DAOT: store>(member_addr: address): Option::Option<u64>
-
- - - -
-Implementation - - -
public fun query_member_id<DAOT: store>(member_addr: address): Option::Option<u64>{
-    if(!is_member<DAOT>(member_addr)){
-        return Option::none<u64>()
-    };
-    let nft_info = Option::destroy_some(IdentifierNFT::get_nft_info<DAOMember<DAOT>, DAOMemberBody<DAOT>>(member_addr));
-    let (_, _, _, type_meta) = NFT::unpack_info(nft_info);
-    Option::some(type_meta.id)
-}
-
- - - -
- - - -## Function `is_member` - -Check the member_addr account is a member of DAOT - - -
public fun is_member<DAOT: store>(member_addr: address): bool
-
- - - -
-Implementation - - -
public fun is_member<DAOT: store>(member_addr: address): bool {
-    IdentifierNFT::owns<DAOMember<DAOT>, DAOMemberBody<DAOT>>(member_addr)
-}
-
- - - -
- - - -## Function `is_exist_member_offer` - - - -
public fun is_exist_member_offer<DAOT>(member_addr: address): bool
-
- - - -
-Implementation - - -
public fun is_exist_member_offer<DAOT>(member_addr: address):bool{
-    let dao_address = dao_address<DAOT>();
-    Option::is_some(&Offer::find_offer<MemeberOffer<DAOT>>(dao_address, member_addr))
-}
-
- - - -
- - - -## Function `init_plugin_event` - -Plugin event - - -
public fun init_plugin_event<DAOT: store, PluginT: store, EventT: drop, store>(_cap: &DAOSpace::DAOPluginEventCap<DAOT, PluginT>)
-
- - - -
-Implementation - - -
public fun init_plugin_event<
-    DAOT: store,
-    PluginT: store,
-    EventT: store + drop
->(_cap: &DAOPluginEventCap<DAOT, PluginT>) acquires DAOAccountCapHolder {
-    let dao_signer = dao_signer<DAOT>();
-    EventUtil::init_event<EventT>(&dao_signer);
-}
-
- - - -
- - - -## Function `emit_plugin_event` - - - -
public fun emit_plugin_event<DAOT: store, PluginT: store, EventT: drop, store>(_cap: &DAOSpace::DAOPluginEventCap<DAOT, PluginT>, event: EventT)
-
- - - -
-Implementation - - -
public fun emit_plugin_event<
-    DAOT: store,
-    PluginT: store,
-    EventT: store + drop
->(
-    _cap: &DAOPluginEventCap<DAOT, PluginT>,
-    event: EventT
-) {
-    EventUtil::emit_event(dao_address<DAOT>(), event);
-}
-
- - - -
- - - -## Function `grant_accept_offer` - -Grant function -Accept grant offer by self - - -
public fun grant_accept_offer<DAOT, Plugin, TokenT: store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun grant_accept_offer<DAOT, Plugin, TokenT:store>(sender: &signer) {
-    let dao_address = dao_address<DAOT>();
-    let op_index = Offer::find_offer<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(dao_address, Signer::address_of(sender));
-    assert!(Option::is_some(&op_index),1003);
-    let grant_key = Offer::redeem_v2<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(sender, dao_address, Option::destroy_some(op_index));
-    move_to(sender, grant_key)
-}
-
- - - -
- - - -## Function `grant_accept_offer_entry` - -Accept grant offer by self entry - - -
public(script) fun grant_accept_offer_entry<DAOT, Plugin, TokenT: store>(sender: signer)
-
- - - -
-Implementation - - -
public (script) fun grant_accept_offer_entry<DAOT, Plugin, TokenT:store>(sender: signer) {
-    grant_accept_offer<DAOT, Plugin, TokenT>(&sender)
-}
-
- - - -
- - - -## Function `grant_offer` - -Grant offer and init/emit a event - - -
public fun grant_offer<DAOT, Plugin, TokenT: store>(_cap: &DAOSpace::DAOGrantCap<DAOT>, grantee: address, total: u128, start_time: u64, period: u64)
-
- - - -
-Implementation - - -
public fun grant_offer<DAOT, Plugin, TokenT:store>(_cap:&DAOGrantCap<DAOT>, grantee: address, total:u128, start_time:u64, period:u64) acquires DAOAccountCapHolder, GrantEvent, DAO {
-    let dao_signer = dao_signer<DAOT>();
-    let dao_address = dao_address<DAOT>();
-
-    if (!exists<GrantEvent>(dao_address)){
-        move_to(&dao_signer, GrantEvent{
-            create_grant_event_handler:Event::new_event_handle<GrantCreateEvent>(&dao_signer),
-            revoke_grant_event_handler:Event::new_event_handle<GrantRevokeEvent>(&dao_signer),
-            withdraw_grant_event_handler:Event::new_event_handle<GrantWithdrawEvent>(&dao_signer),
-            refund_grant_event_handler:Event::new_event_handle<GrantRefundEvent>(&dao_signer),
-        });
-    };
-    let grant_event = borrow_global_mut<GrantEvent>(dao_address);
-
-    Event::emit_event(&mut grant_event.create_grant_event_handler, GrantCreateEvent {
-        dao_id:dao_id(dao_address),
-        grantee,
-        total,
-        start_time,
-        period,
-        now_time:Timestamp::now_seconds(),
-        plugin: TypeInfo::type_of<Plugin>(),
-        token: Token::token_code<TokenT>()
-    });
-
-    Offer::create_v2<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(
-        &dao_signer,
-        DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>{
-            total,
-            withdraw: 0 ,
-            start_time,
-            period
-        },
-        grantee,
-        0
-    );
-}
-
- - - -
- - - -## Function `grant_offer_refund` - -Grant offer refund - - -
public fun grant_offer_refund<DAOT, Plugin, TokenT: store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun grant_offer_refund<DAOT, Plugin, TokenT:store>(sender: &signer)acquires DAOAccountCapHolder, GrantEvent, DAO {
-    let dao_address = dao_address<DAOT>();
-    let dao_signer = dao_signer<DAOT>();
-    let grantee = Signer::address_of(sender);
-    let op_index = Offer::find_offer<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(dao_address, grantee);
-    assert!(Option::is_some(&op_index), Errors::not_published(ERR_OFFER_NOT_EXIST));
-    let grant_event = borrow_global_mut<GrantEvent>(dao_address);
-    let DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>{
-        total,
-        withdraw,
-        start_time,
-        period
-    } = Offer::retake<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(&dao_signer, Option::destroy_some(op_index));
-    Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent {
-        dao_id:dao_id(dao_address),
-        grantee,
-        total,
-        withdraw,
-        start_time,
-        period,
-        plugin: TypeInfo::type_of<Plugin>(),
-        token: Token::token_code<TokenT>()
-    });
-}
-
- - - -
- - - -## Function `grant_offer_refund_entry` - -Grant offer refund entry - - -
public(script) fun grant_offer_refund_entry<DAOT, Plugin, TokenT: store>(sender: signer)
-
- - - -
-Implementation - - -
public (script) fun grant_offer_refund_entry<DAOT, Plugin, TokenT:store>(sender: signer)acquires DAOAccountCapHolder, GrantEvent, DAO{
-    grant_offer_refund<DAOT, Plugin, TokenT>(&sender);
-}
-
- - - -
- - - -## Function `grant_withdraw_entry` - -Withdraw token with grant - - -
public(script) fun grant_withdraw_entry<DAOT, Plugin, TokenT: store>(sender: signer, amount: u128)
-
- - - -
-Implementation - - -
public (script) fun grant_withdraw_entry<DAOT, Plugin, TokenT:store>(sender: signer, amount:u128) acquires DAOAccountCapHolder, DAOGrantWithdrawTokenKey, GrantEvent, DAO{
-    grant_withdraw<DAO, Plugin, TokenT>(&sender, amount);
-}
-
- - - -
- - - -## Function `grant_withdraw` - -Withdraw token with grant - - -
public fun grant_withdraw<DAOT, Plugin, TokenT: store>(sender: &signer, amount: u128)
-
- - - -
-Implementation - - -
public fun grant_withdraw<DAOT, Plugin, TokenT:store>(sender: &signer, amount:u128) acquires DAOAccountCapHolder, DAOGrantWithdrawTokenKey, GrantEvent, DAO{
-    let account_address = Signer::address_of(sender);
-    assert!(exists<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(account_address) , Errors::invalid_state(ERR_NOT_HAVE_GRANT));
-
-    let cap = borrow_global_mut<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(account_address);
-    let now = Timestamp::now_seconds();
-    let elapsed_time = now - cap.start_time;
-    let can_amount =  if (elapsed_time >= cap.period) {
-        cap.total - cap.withdraw
-    } else {
-        Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw
-    };
-
-    assert!(can_amount > 0, Errors::invalid_argument(ERR_INVALID_AMOUNT));
-    assert!(can_amount >= amount, Errors::invalid_argument(ERR_INVALID_AMOUNT));
-
-    let dao_signer = dao_signer<DAOT>();
-    let dao_address = dao_address<DAOT>();
-
-    assert!(amount <= Account::balance<TokenT>(dao_address) , Errors::invalid_argument(ERR_INVALID_AMOUNT));
-    cap.withdraw = cap.withdraw + amount;
-
-    let grant_event = borrow_global_mut<GrantEvent>(dao_address);
-    Event::emit_event(&mut grant_event.withdraw_grant_event_handler, GrantWithdrawEvent {
-        dao_id:dao_id(dao_address),
-        grantee: account_address,
-        total:cap.total,
-        withdraw:cap.withdraw,
-        start_time:cap.start_time,
-        period:cap.period,
-        withdraw_value:amount,
-        plugin: TypeInfo::type_of<Plugin>(),
-        token: Token::token_code<TokenT>()
-    });
-    let token = Account::withdraw<TokenT>(&dao_signer, amount);
-    Account::deposit<TokenT>(account_address, token);
-}
-
- - - -
- - - -## Function `query_grant_withdrawable_amount` - - - -
public fun query_grant_withdrawable_amount<DAOT, Plugin, TokenT: store>(addr: address): u128
-
- - - -
-Implementation - - -
public fun query_grant_withdrawable_amount<DAOT, Plugin, TokenT:store>(addr: address):u128 acquires DAOGrantWithdrawTokenKey{
-    assert!(exists<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(addr) , Errors::invalid_state(ERR_NOT_HAVE_GRANT));
-    let cap = borrow_global<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(addr);
-    let now = Timestamp::now_seconds();
-    let elapsed_time = now - cap.start_time;
-    if (elapsed_time >= cap.period) {
-        cap.total - cap.withdraw
-    } else {
-        Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw
-    }
-}
-
- - - -
- - - -## Function `is_exist_grant` - -Is exist DAOGrantWithdrawTokenKey - - -
public fun is_exist_grant<DAOT, Plugin, TokenT: store>(addr: address): bool
-
- - - -
-Implementation - - -
public fun is_exist_grant<DAOT, Plugin, TokenT:store>(addr:address):bool{
-    exists<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(addr)
-}
-
- - - -
- - - -## Function `grant_revoke` - -Revoke grant - - -
public fun grant_revoke<DAOT, Plugin, TokenT: store>(_cap: &DAOSpace::DAOGrantCap<DAOT>, grantee: address)
-
- - - -
-Implementation - - -
public fun grant_revoke<DAOT, Plugin, TokenT:store>(_cap:&DAOGrantCap<DAOT>, grantee: address ) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO {
-    let dao_address = dao_address<DAOT>();
-    let grant_event = borrow_global_mut<GrantEvent>(dao_address);
-    if(exists<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(grantee)){
-        let DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>{
-            total,
-            withdraw,
-            start_time,
-            period
-        } = move_from<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(grantee);
-
-        Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent {
-            dao_id:dao_id(dao_address),
-            grantee,
-            total,
-            withdraw,
-            start_time,
-            period,
-            plugin: TypeInfo::type_of<Plugin>(),
-            token: Token::token_code<TokenT>()
-        });
-    };
-}
-
- - - -
- - - -## Function `grant_offer_revoke` - -Revoke grant offer - - -
public fun grant_offer_revoke<DAOT, Plugin, TokenT: store>(_cap: &DAOSpace::DAOGrantCap<DAOT>, grantee: address)
-
- - - -
-Implementation - - -
public fun grant_offer_revoke<DAOT, Plugin, TokenT:store>(_cap:&DAOGrantCap<DAOT>, grantee: address ) acquires GrantEvent, DAO, DAOAccountCapHolder {
-    let dao_signer = dao_signer<DAOT>();
-    let dao_address = dao_address<DAOT>();
-    let grant_event = borrow_global_mut<GrantEvent>(dao_address);
-    let op_index = Offer::find_offer<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(dao_address, grantee);
-    if(Option::is_some(&op_index)) {
-        let DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT> {
-            total,
-            withdraw,
-            start_time,
-            period
-        } = Offer::retake<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(&dao_signer, Option::destroy_some(op_index));
-        Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent {
-            dao_id: dao_id(dao_address),
-            grantee,
-            total,
-            withdraw,
-            start_time,
-            period,
-            plugin: TypeInfo::type_of<Plugin>(),
-            token: Token::token_code<TokenT>()
-        });
-    };
-}
-
- - - -
- - - -## Function `refund_grant` - -Refund the grant - - -
public fun refund_grant<DAOT, Plugin, TokenT: store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun refund_grant<DAOT, Plugin, TokenT:store>(sender: &signer) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO {
-    let dao_address = dao_address<DAOT>();
-    let grantee = Signer::address_of(sender);
-    assert!(exists<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(grantee) , Errors::invalid_state(ERR_NOT_HAVE_GRANT));
-    let DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>{
-        total:total,
-        withdraw:withdraw,
-        start_time:start_time,
-        period:period
-    } = move_from<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(grantee);
-
-    let grant_event = borrow_global_mut<GrantEvent>(dao_address);
-    Event::emit_event(&mut grant_event.refund_grant_event_handler, GrantRefundEvent {
-        dao_id:dao_id(dao_address),
-        grantee,
-        total:total,
-        withdraw:withdraw,
-        start_time:start_time,
-        period:period,
-        plugin: TypeInfo::type_of<Plugin>(),
-        token: Token::token_code<TokenT>()
-    });
-}
-
- - - -
- - - -## Function `refund_grant_entry` - -Refund the grant entry - - -
public(script) fun refund_grant_entry<DAOT, Plugin, TokenT: store>(sender: signer)
-
- - - -
-Implementation - - -
public (script) fun refund_grant_entry<DAOT, Plugin, TokenT:store>(sender: signer) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO {
-    refund_grant<DAOT, Plugin, TokenT>(&sender);
-}
-
- - - -
- - - -## Function `query_grant` - -Query address grant - - -
public fun query_grant<DAOT, Plugin, TokenT: store>(addr: address): DAOSpace::GrantInfo
-
- - - -
-Implementation - - -
public fun query_grant<DAOT, Plugin, TokenT:store>(addr: address): GrantInfo acquires DAOGrantWithdrawTokenKey{
-    assert!(exists<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(addr) , Errors::invalid_state(ERR_NOT_HAVE_GRANT));
-    let cap = borrow_global<DAOGrantWithdrawTokenKey<DAOT, Plugin, TokenT>>(addr);
-    GrantInfo{
-        total        :   cap.total,
-        grantee      :   addr,
-        withdraw     :   cap.withdraw,
-        start_time   :   cap.start_time,
-        period       :   cap.period
-    }
-}
-
- - - -
- - - -## Function `query_grant_info_total` - -Query grant info total - - -
public fun query_grant_info_total(grant_info: &DAOSpace::GrantInfo): u128
-
- - - -
-Implementation - - -
public fun query_grant_info_total(grant_info: &GrantInfo):u128{
-    grant_info.total
-}
-
- - - -
- - - -## Function `query_grant_info_withdraw` - -Query grant info withdraw - - -
public fun query_grant_info_withdraw(grant_info: &DAOSpace::GrantInfo): u128
-
- - - -
-Implementation - - -
public fun query_grant_info_withdraw(grant_info: &GrantInfo):u128{
-    grant_info.withdraw
-}
-
- - - -
- - - -## Function `query_grant_info_start_time` - -Query grant info start_time - - -
public fun query_grant_info_start_time(grant_info: &DAOSpace::GrantInfo): u64
-
- - - -
-Implementation - - -
public fun query_grant_info_start_time(grant_info: &GrantInfo):u64{
-    grant_info.start_time
-}
-
- - - -
- - - -## Function `query_grant_info_period` - -Query grant info period - - -
public fun query_grant_info_period(grant_info: &DAOSpace::GrantInfo): u64
-
- - - -
-Implementation - - -
public fun query_grant_info_period(grant_info: &GrantInfo):u64{
-    grant_info.period
-}
-
- - - -
- - - -## Function `validate_cap` - -Acquiring Capabilities - - -
fun validate_cap<DAOT: store, PluginT>(cap: DAOSpace::CapType)
-
- - - -
-Implementation - - -
fun validate_cap<DAOT: store, PluginT>(cap: CapType) acquires InstalledPluginInfo {
-    let addr = dao_address<DAOT>();
-    // When create a new DAO, one can pass a `DAOT` type as the `PluginT` type,
-    // in this case, the signer is equal to have the root cap.
-    if (TypeInfo::type_of<DAOT>() != TypeInfo::type_of<PluginT>()) {
-        if (exists<InstalledPluginInfo<PluginT>>(addr)) {
-            let plugin_info = borrow_global<InstalledPluginInfo<PluginT>>(addr);
-            assert!(Vector::contains(&plugin_info.granted_caps, &cap), Errors::requires_capability(ERR_NO_GRANTED));
-        } else {
-            abort (Errors::requires_capability(ERR_NO_GRANTED))
-        }
-    }
-}
-
- - - -
- - - -## Function `acquire_install_plugin_cap` - -Acquire the installed plugin capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_install_plugin_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOInstallPluginCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_install_plugin_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOInstallPluginCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(install_plugin_cap_type());
-    DAOInstallPluginCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_upgrade_module_cap` - -Acquire the upgrade module capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_upgrade_module_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOUpgradeModuleCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_upgrade_module_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOUpgradeModuleCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(upgrade_module_cap_type());
-    DAOUpgradeModuleCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_modify_config_cap` - -Acquire the modify config capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_modify_config_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOModifyConfigCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_modify_config_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOModifyConfigCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(modify_config_cap_type());
-    DAOModifyConfigCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_withdraw_token_cap` - -Acquires the withdraw Token capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_withdraw_token_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOWithdrawTokenCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_withdraw_token_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOWithdrawTokenCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(withdraw_token_cap_type());
-    DAOWithdrawTokenCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_withdraw_nft_cap` - -Acquires the withdraw NFT capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_withdraw_nft_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOWithdrawNFTCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_withdraw_nft_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOWithdrawNFTCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(withdraw_nft_cap_type());
-    DAOWithdrawNFTCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_storage_cap` - -Acquires the storage capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_storage_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOStorageCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_storage_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOStorageCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(storage_cap_type());
-    DAOStorageCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_member_cap` - -Acquires the membership capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_member_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOMemberCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_member_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOMemberCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(member_cap_type());
-    DAOMemberCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_proposal_cap` - -Acquire the proposql capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_proposal_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOProposalCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_proposal_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOProposalCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(proposal_cap_type());
-    DAOProposalCap<DAOT, PluginT>{}
-}
-
- - - -
- - - -## Function `acquire_grant_cap` - -Acquire the grant capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_grant_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOGrantCap<DAOT>
-
- - - -
-Implementation - - -
public fun acquire_grant_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOGrantCap<DAOT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(grant_cap_type());
-    DAOGrantCap<DAOT>{}
-}
-
- - - -
- - - -## Function `acquire_plugin_event_cap` - -Acquire the plugin event capability -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun acquire_plugin_event_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOSpace::DAOPluginEventCap<DAOT, PluginT>
-
- - - -
-Implementation - - -
public fun acquire_plugin_event_cap<DAOT: store, PluginT>(_witness: &PluginT): DAOPluginEventCap<DAOT, PluginT> acquires InstalledPluginInfo {
-    validate_cap<DAOT, PluginT>(plugin_event_cap_type());
-    DAOPluginEventCap<DAOT, PluginT> {}
-}
-
- - - -
- - - -## Function `delegate_token_mint_cap` - -Delegate the token mint capability to DAO -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun delegate_token_mint_cap<DAOT: store, PluginT, TokenT: store>(cap: Token::MintCapability<TokenT>, _witness: &PluginT)
-
- - - -
-Implementation - - -
public fun delegate_token_mint_cap<DAOT: store, PluginT, TokenT: store>(cap: Token::MintCapability<TokenT>, _witness: &PluginT)
-acquires DAOAccountCapHolder {
-    let dao_signer = dao_signer<DAOT>();
-    move_to<DAOTokenMintCapHolder<DAOT, TokenT>>(
-        &dao_signer,
-        DAOTokenMintCapHolder<DAOT, TokenT> { cap },
-    );
-}
-
- - - -
- - - -## Function `delegate_token_burn_cap` - -Delegate the token burn capability to DAO -_witness parameter ensures that the caller is the module which define PluginT - - -
public fun delegate_token_burn_cap<DAOT: store, PluginT, TokenT: store>(cap: Token::BurnCapability<TokenT>, _witness: &PluginT)
-
- - - -
-Implementation - - -
public fun delegate_token_burn_cap<DAOT: store, PluginT, TokenT: store>(cap: Token::BurnCapability<TokenT>, _witness: &PluginT)
-acquires DAOAccountCapHolder {
-    let dao_signer = dao_signer<DAOT>();
-    move_to<DAOTokenBurnCapHolder<DAOT, TokenT>>(
-        &dao_signer,
-        DAOTokenBurnCapHolder<DAOT, TokenT> { cap },
-    );
-}
-
- - - -
- - - -## Function `mint_token` - -Mint token - - -
public fun mint_token<DAOT: store, PluginT, TokenT: store>(amount: u128, _witness: &PluginT): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun mint_token<DAOT: store, PluginT, TokenT: store>(amount: u128, _witness: &PluginT): Token<TokenT>
-acquires InstalledPluginInfo, DAOTokenMintCapHolder {
-    validate_cap<DAOT, PluginT>(token_mint_cap_type());
-    let dao_addr = dao_address<DAOT>();
-    assert!(exists<DAOTokenMintCapHolder<DAOT, TokenT>>(dao_addr), Errors::not_published(ERR_TOKEN_ERROR));
-    let DAOTokenMintCapHolder<DAOT, TokenT> { cap } =
-        borrow_global<DAOTokenMintCapHolder<DAOT, TokenT>>(dao_addr);
-    let tokens = Token::mint_with_capability<TokenT>(cap, amount);
-    tokens
-}
-
- - - -
- - - -## Function `burn_token` - -Burn token - - -
public fun burn_token<DAOT: store, PluginT, TokenT: store>(tokens: Token::Token<TokenT>, _witness: &PluginT)
-
- - - -
-Implementation - - -
public fun burn_token<DAOT: store, PluginT, TokenT: store>(tokens: Token<TokenT>, _witness: &PluginT)
-acquires InstalledPluginInfo, DAOTokenBurnCapHolder {
-    validate_cap<DAOT, PluginT>(token_burn_cap_type());
-    let dao_addr = dao_address<DAOT>();
-    assert!(exists<DAOTokenBurnCapHolder<DAOT, TokenT>>(dao_addr), Errors::not_published(ERR_TOKEN_ERROR));
-    let DAOTokenBurnCapHolder<DAOT, TokenT> { cap } =
-        borrow_global<DAOTokenBurnCapHolder<DAOT, TokenT>>(dao_addr);
-    Token::burn_with_capability<TokenT>(cap, tokens);
-}
-
- - - -
- - - -## Function `choice_yes` - - - -
public fun choice_yes(): DAOSpace::VotingChoice
-
- - - -
-Implementation - - -
public fun choice_yes(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_YES } }
-
- - - -
- - - -## Function `choice_no` - - - -
public fun choice_no(): DAOSpace::VotingChoice
-
- - - -
-Implementation - - -
public fun choice_no(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_NO } }
-
- - - -
- - - -## Function `choice_no_with_veto` - -no_with_veto counts as no but also adds a veto vote - - -
public fun choice_no_with_veto(): DAOSpace::VotingChoice
-
- - - -
-Implementation - - -
public fun choice_no_with_veto(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_NO_WITH_VETO } }
-
- - - -
- - - -## Function `choice_abstain` - - - -
public fun choice_abstain(): DAOSpace::VotingChoice
-
- - - -
-Implementation - - -
public fun choice_abstain(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_ABSTAIN } }
-
- - - -
- - - -## Function `create_proposal` - -propose a proposal. -title: title of the proposal -introduction: short introduction of the proposal -extend: extend of proposal , ipfs:// | { "title":"xxxxx",........ } -action: the actual action to execute. -action_delay: the delay to execute after the proposal is agreed -quorum_scale_factor: used to scale up the base quorum_votes_rate. -The final quorum_votes_rate = (1.0 + scale / 100) * quorum_votes_rate - - -
public fun create_proposal<DAOT: store, PluginT, ActionT: drop, store>(_cap: &DAOSpace::DAOProposalCap<DAOT, PluginT>, sender: &signer, action: ActionT, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64, quorum_scale_factor: Option::Option<u8>): u64
-
- - - -
-Implementation - - -
public fun create_proposal<DAOT: store, PluginT, ActionT: store+drop>(
-    _cap: &DAOProposalCap<DAOT, PluginT>,
-    sender: &signer,
-    action: ActionT,
-    title: vector<u8>,
-    introduction: vector<u8>,
-    extend: vector<u8>,
-    action_delay: u64,
-    quorum_scale_factor: Option::Option<u8>,
-): u64 acquires DAO, GlobalProposals, DAOAccountCapHolder, ProposalActions, ProposalEvent, GlobalProposalActions {
-    // check DAO member
-    let sender_addr = Signer::address_of(sender);
-    ensure_member<DAOT>(sender_addr);
-
-    if (action_delay == 0) {
-        action_delay = min_action_delay<DAOT>();
-    } else {
-        assert!(action_delay >= min_action_delay<DAOT>(), Errors::invalid_argument(ERR_ACTION_DELAY_TOO_SMALL));
-    };
-
-    let min_proposal_deposit = min_proposal_deposit<DAOT>();
-    let deposit = Account::withdraw<STC>(sender, min_proposal_deposit);
-
-    let proposal_id = next_proposal_id<DAOT>();
-    let proposer = Signer::address_of(sender);
-    let start_time = Timestamp::now_milliseconds() + voting_delay<DAOT>();
-    let quorum_votes = quorum_votes<DAOT>(quorum_scale_factor);
-    let voting_period = voting_period<DAOT>();
-
-    let (block_number,state_root) = block_number_and_state_root();
-
-    let proposal = Proposal {
-        id: proposal_id,
-        proposer,
-        title: copy title,
-        introduction: copy introduction,
-        extend: copy extend,
-        start_time,
-        end_time: start_time + voting_period,
-        yes_votes: 0,
-        no_votes: 0,
-        abstain_votes: 0,
-        no_with_veto_votes: 0,
-        eta: 0,
-        action_delay,
-        quorum_votes,
-        block_number,
-        state_root,
-    };
-    let proposal_action = ProposalAction{
-        proposal_id,
-        deposit,
-        action,
-    };
-    let proposal_action_index = ProposalActionIndex{
-        proposal_id,
-    };
-
-    let dao_signer = dao_signer<DAOT>();
-    let dao_address = dao_address<DAOT>();
-
-    let actions = Vector::singleton(proposal_action);
-    // check ProposalActions is exists
-    if(exists<ProposalActions<ActionT>>(dao_address)){
-        let current_actions = borrow_global_mut<ProposalActions<ActionT>>(dao_address);
-        assert!(Vector::length(¤t_actions.actions) < MAX_PROPOSALS, Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT));
-        Vector::append(&mut current_actions.actions, actions);
-    }else{
-        move_to(&dao_signer, ProposalActions<ActionT>{
-            actions,
-        });
-    };
-
-    let proposal_action_indexs = Vector::singleton(proposal_action_index);
-    // check GlobalProposalActions is exists
-    if(exists<GlobalProposalActions>(dao_address)){
-        let current_global_proposal_actions = borrow_global_mut<GlobalProposalActions>(dao_address);
-        assert!(Vector::length(¤t_global_proposal_actions.proposal_action_indexs) < MAX_PROPOSALS,
-            Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT));
-        Vector::append(&mut current_global_proposal_actions.proposal_action_indexs, proposal_action_indexs);
-    }else{
-        move_to(&dao_signer, GlobalProposalActions{
-            proposal_action_indexs,
-        });
-    };
-
-    let proposals = Vector::singleton(proposal);
-    // check GlobalProposals is exists
-    if(exists<GlobalProposals>(dao_address)){
-        let current_global_proposals = borrow_global_mut<GlobalProposals>(dao_address);
-        assert!(Vector::length(¤t_global_proposals.proposals) < MAX_PROPOSALS,
-            Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT));
-        Vector::append(&mut current_global_proposals.proposals, proposals);
-    }else{
-        move_to(&dao_signer, GlobalProposals{
-            proposals,
-        });
-    };
-
-    // emit event
-    let dao_id = dao_id(dao_address);
-    let proposal_event = borrow_global_mut<ProposalEvent<DAOT>>(dao_address);
-    Event::emit_event(&mut proposal_event.proposal_create_event,
-        ProposalCreatedEvent { dao_id, proposal_id, title,  introduction: copy introduction, extend: copy extend, proposer },
-    );
-
-    proposal_id
-}
-
- - - -
- - - -## Function `block_number_and_state_root` - -get lastest block number and state root - - -
fun block_number_and_state_root(): (u64, vector<u8>)
-
- - - -
-Implementation - - -
fun block_number_and_state_root(): (u64, vector<u8>) {
-    Block::latest_state_root()
-}
-
- - - -
- - - -## Function `cast_vote` - -votes for a proposal. -User can only vote once, then the stake is locked, -The voting power depends on the strategy of the proposal configuration and the user's token amount at the time of the snapshot - - -
public fun cast_vote<DAOT: store>(sender: &signer, proposal_id: u64, snpashot_raw_proofs: vector<u8>, choice: DAOSpace::VotingChoice)
-
- - - -
-Implementation - - -
public fun cast_vote<DAOT: store>(
-    sender: &signer,
-    proposal_id: u64,
-    snpashot_raw_proofs: vector<u8>,
-    choice: VotingChoice,
-)  acquires GlobalProposals, MyVotes, ProposalEvent, GlobalProposalActions, DAO {
-    let sender_addr = Signer::address_of(sender);
-    ensure_member<DAOT>(sender_addr);
-
-    let dao_address = dao_address<DAOT>();
-    let proposals = borrow_global_mut<GlobalProposals>(dao_address);
-    let proposal = borrow_proposal_mut(proposals, proposal_id);
-
-    {
-        let state = proposal_state_with_proposal<DAOT>(proposal);
-        // only when proposal is active, use can cast vote.
-        assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    };
-
-    // verify snapshot state proof
-    let snapshot_proof = deserialize_snapshot_proofs(&snpashot_raw_proofs);
-    let state_proof = new_state_proof_from_proofs(&snapshot_proof);
-    let resource_struct_tag = SnapshotUtil::get_sturct_tag<DAOT>();
-    // verify state_proof according to proposal snapshot proofs, and state root
-    let verify = StarcoinVerifier::verify_state_proof(&state_proof, &proposal.state_root, sender_addr, &resource_struct_tag, &snapshot_proof.state);
-    assert!(verify, Errors::invalid_state(ERR_STATE_PROOF_VERIFY_INVALID));
-
-    // decode sbt value from snapshot state
-    let vote_weight = SBTVoteStrategy::get_voting_power(&snapshot_proof.state);
-
-    assert!(!has_voted<DAOT>(sender_addr, proposal_id), Errors::invalid_state(ERR_VOTED_ALREADY));
-
-    let vote = Vote{
-        proposal_id,
-        vote_weight,
-        choice: choice.choice,
-    };
-
-    do_cast_vote(proposal, &mut vote);
-
-    if (exists<MyVotes<DAOT>>(sender_addr)) {
-        assert!(vote.proposal_id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY));
-        let my_votes = borrow_global_mut<MyVotes<DAOT>>(sender_addr);
-        Vector::push_back(&mut my_votes.votes, vote);
-    } else {
-        move_to(sender, MyVotes<DAOT>{
-            votes: Vector::singleton(vote),
-        });
-    };
-
-    // emit event
-    let dao_id = dao_id(dao_address);
-    let proposal_event = borrow_global_mut<ProposalEvent<DAOT> >(DAORegistry::dao_address<DAOT>());
-    Event::emit_event(&mut proposal_event.vote_event,
-        VotedEvent {
-            dao_id,
-            proposal_id,
-            voter: sender_addr,
-            choice: choice.choice,
-            vote_weight,
-        },
-    );
-}
-
- - - -
- - - -## Function `deserialize_snapshot_proofs` - - - -
fun deserialize_snapshot_proofs(snpashot_raw_proofs: &vector<u8>): DAOSpace::SnapshotProof
-
- - - -
-Implementation - - -
fun deserialize_snapshot_proofs(snpashot_raw_proofs: &vector<u8>): SnapshotProof{
-    assert!(Vector::length(snpashot_raw_proofs) > 0, Errors::invalid_argument(ERR_SNAPSHOT_PROOF_PARAM_INVALID));
-    let offset= 0;
-    let (state_option, offset) = BCS::deserialize_option_bytes(snpashot_raw_proofs, offset);
-    let (account_state_option, offset) = BCS::deserialize_option_bytes(snpashot_raw_proofs, offset);
-
-    let (account_proof_leaf1_option, account_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(snpashot_raw_proofs, offset);
-    let account_proof_leaf1 = Option::get_with_default(&mut account_proof_leaf1_option, Vector::empty());
-    let account_proof_leaf2 = Option::get_with_default(&mut account_proof_leaf2_option, Vector::empty());
-    let (account_proof_siblings, offset) = BCS::deserialize_bytes_vector(snpashot_raw_proofs, offset);
-
-    let (account_state_proof_leaf1_option, account_state_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(snpashot_raw_proofs, offset);
-    let account_state_proof_leaf1 = Option::get_with_default(&mut account_state_proof_leaf1_option, Vector::empty());
-    let account_state_proof_leaf2 = Option::get_with_default(&mut account_state_proof_leaf2_option, Vector::empty());
-    let (account_state_proof_siblings, _offset) = BCS::deserialize_bytes_vector(snpashot_raw_proofs, offset);
-
-    SnapshotProof {
-        state: Option::get_with_default(&mut state_option, Vector::empty()),
-        account_state: Option::get_with_default(&mut account_state_option, Vector::empty()),
-        account_proof_leaf: HashNode {
-            hash1: account_proof_leaf1,
-            hash2: account_proof_leaf2,
-        },
-        account_proof_siblings,
-        account_state_proof_leaf: HashNode {
-            hash1: account_state_proof_leaf1,
-            hash2: account_state_proof_leaf2,
-        },
-        account_state_proof_siblings,
-    }
-}
-
- - - -
- - - -## Function `new_state_proof_from_proofs` - - - -
fun new_state_proof_from_proofs(snpashot_proofs: &DAOSpace::SnapshotProof): StarcoinVerifier::StateProof
-
- - - -
-Implementation - - -
fun new_state_proof_from_proofs(snpashot_proofs: &SnapshotProof): StateProof{
-    let state_proof = StarcoinVerifier::new_state_proof(
-        StarcoinVerifier::new_sparse_merkle_proof(
-            *&snpashot_proofs.account_proof_siblings,
-            StarcoinVerifier::new_smt_node(
-                *&snpashot_proofs.account_proof_leaf.hash1,
-                *&snpashot_proofs.account_proof_leaf.hash2,
-            ),
-        ),
-        *&snpashot_proofs.account_state,
-        StarcoinVerifier::new_sparse_merkle_proof(
-            *&snpashot_proofs.account_state_proof_siblings,
-            StarcoinVerifier::new_smt_node(
-                *&snpashot_proofs.account_state_proof_leaf.hash1,
-                *&snpashot_proofs.account_state_proof_leaf.hash2,
-            ),
-        ),
-    );
-    state_proof
-}
-
- - - -
- - - -## Function `execute_proposal` - - - -
public fun execute_proposal<DAOT: store, PluginT, ActionT: drop, store>(_cap: &DAOSpace::DAOProposalCap<DAOT, PluginT>, sender: &signer, proposal_id: u64): ActionT
-
- - - -
-Implementation - - -
public fun execute_proposal<DAOT: store, PluginT, ActionT: store+drop>(
-    _cap: &DAOProposalCap<DAOT, PluginT>,
-    sender: &signer,
-    proposal_id: u64,
-): ActionT acquires ProposalActions, GlobalProposals, GlobalProposalActions, ProposalEvent, DAO {
-    // Only executable proposal's action can be extracted.
-    assert!(proposal_state<DAOT>(proposal_id) == EXECUTABLE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    let dao_address = dao_address<DAOT>();
-    let sender_addr = Signer::address_of(sender);
-    assert!(exists<ProposalActions<ActionT>>(dao_address), Errors::invalid_state(ERR_PROPOSAL_ACTIONS_NOT_EXIST));
-
-    let (actionT, deposit) = take_proposal_action(dao_address, proposal_id);
-
-    let global_proposals = borrow_global_mut<GlobalProposals>(dao_address);
-    let proposal = borrow_proposal(global_proposals, proposal_id);
-
-    Account::deposit(proposal.proposer, deposit);
-
-    // emit event
-    let dao_id = dao_id(dao_address);
-    let proposal_event = borrow_global_mut<ProposalEvent<DAOT>>(dao_address);
-    Event::emit_event(&mut proposal_event.proposal_action_event,
-        ProposalActionEvent { dao_id, proposal_id, sender: sender_addr, state: EXTRACTED }
-    );
-
-    actionT
-}
-
- - - -
- - - -## Function `clean_proposals` - - - -
public fun clean_proposals<DAOT: store>(_sender: &signer)
-
- - - -
-Implementation - - -
public fun clean_proposals<DAOT: store>(_sender: &signer)
-acquires GlobalProposals, GlobalProposalActions {
-    let dao_address = dao_address<DAOT>();
-    let global_proposals = borrow_global_mut<GlobalProposals>(dao_address);
-
-    let i = 0;
-    let len = Vector::length(&global_proposals.proposals);
-    while(i < len){
-        let proposal = Vector::borrow(&global_proposals.proposals, i);
-        let state = proposal_state_with_proposal<DAOT>(proposal);
-        if (state == EXTRACTED || state == REJECTED) {
-            let _ = Vector::remove(&mut global_proposals.proposals, i);
-            len = len - 1;
-        } else {
-            i = i + 1;
-        }
-    };
-}
-
- - - -
- - - -## Function `clean_proposals_entry` - - - -
public(script) fun clean_proposals_entry<DAOT: store>(sender: signer)
-
- - - -
-Implementation - - -
public (script) fun clean_proposals_entry<DAOT: store>(sender: signer)
-acquires GlobalProposals, GlobalProposalActions {
-    clean_proposals<DAOT>(&sender);
-}
-
- - - -
- - - -## Function `clean_proposal_by_id` - - - -
public fun clean_proposal_by_id<DAOT: store>(_sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun clean_proposal_by_id<DAOT: store>(_sender: &signer, proposal_id: u64)
-acquires GlobalProposals, GlobalProposalActions {
-    let dao_address = dao_address<DAOT>();
-    let global_proposals = borrow_global_mut<GlobalProposals>(dao_address);
-    let proposal = borrow_proposal(global_proposals, proposal_id);
-    let state = proposal_state_with_proposal<DAOT>(proposal);
-    assert!(state == EXTRACTED || state == REJECTED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-
-    let _ = remove_proposal(global_proposals, proposal_id);
-}
-
- - - -
- - - -## Function `clean_proposal_by_id_entry` - - - -
public(script) fun clean_proposal_by_id_entry<DAOT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun clean_proposal_by_id_entry<DAOT: store>(sender: signer, proposal_id: u64)
-acquires GlobalProposals, GlobalProposalActions {
-    clean_proposal_by_id<DAOT>(&sender, proposal_id)
-}
-
- - - -
- - - -## Function `take_proposal_action` - - - -
fun take_proposal_action<ActionT: drop, store>(dao_address: address, proposal_id: u64): (ActionT, Token::Token<STC::STC>)
-
- - - -
-Implementation - - -
fun take_proposal_action<ActionT: store+drop>(dao_address: address, proposal_id: u64): (ActionT, Token<STC>)
-acquires ProposalActions, GlobalProposalActions {
-    let actions = borrow_global_mut<ProposalActions<ActionT>>(dao_address);
-    let index_opt = find_action(&actions.actions, proposal_id);
-    assert!(Option::is_some(&index_opt), Errors::invalid_argument(ERR_ACTION_INDEX_INVALID));
-
-    let index = Option::extract(&mut index_opt);
-    let ProposalAction{ proposal_id:_, deposit, action} = Vector::remove(&mut actions.actions, index);
-
-    // remove proposal action index
-    let global_proposal_actions = borrow_global_mut<GlobalProposalActions>(dao_address);
-    let proposal_action_index_opt = find_proposal_action_index(global_proposal_actions, proposal_id);
-    assert!(Option::is_some(&proposal_action_index_opt), Errors::invalid_argument(ERR_PROPOSAL_ACTION_INDEX_NOT_EXIST));
-    let propopsal_action_index = Option::extract(&mut proposal_action_index_opt);
-    let ProposalActionIndex{ proposal_id:_,} = Vector::remove(&mut global_proposal_actions.proposal_action_indexs, propopsal_action_index);
-
-    (action, deposit)
-}
-
- - - -
- - - -## Function `remove_proposal` - - - -
fun remove_proposal(proposals: &mut DAOSpace::GlobalProposals, proposal_id: u64): DAOSpace::Proposal
-
- - - -
-Implementation - - -
fun remove_proposal(proposals: &mut GlobalProposals, proposal_id: u64): Proposal {
-    let i = 0;
-    let len = Vector::length(&proposals.proposals);
-    while(i < len){
-        let proposal = Vector::borrow(&proposals.proposals, i);
-        if(proposal.id == proposal_id){
-            let proposal = Vector::remove(&mut proposals.proposals, i);
-            return proposal
-        };
-        i = i + 1;
-    };
-    abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST)
-}
-
- - - -
- - - -## Function `find_action` - - - -
fun find_action<ActionT: drop, store>(actions: &vector<DAOSpace::ProposalAction<ActionT>>, proposal_id: u64): Option::Option<u64>
-
- - - -
-Implementation - - -
fun find_action<ActionT: store+drop>(actions: &vector<ProposalAction<ActionT>>, proposal_id: u64): Option<u64>{
-    let i = 0;
-    let len = Vector::length(actions);
-    while(i < len){
-        let action = Vector::borrow(actions, i);
-        if(action.proposal_id == proposal_id){
-            return Option::some(i)
-        };
-        i = i + 1;
-    };
-    Option::none<u64>()
-}
-
- - - -
- - - -## Function `do_cast_vote` - - - -
fun do_cast_vote(proposal: &mut DAOSpace::Proposal, vote: &mut DAOSpace::Vote)
-
- - - -
-Implementation - - -
fun do_cast_vote(proposal: &mut Proposal, vote: &mut Vote){
-    if (choice_yes().choice == vote.choice) {
-        proposal.yes_votes = proposal.yes_votes + vote.vote_weight;
-    } else if (choice_no().choice == vote.choice) {
-        proposal.no_votes = proposal.no_votes + vote.vote_weight;
-    } else if ( choice_no_with_veto().choice == vote.choice) {
-        proposal.no_with_veto_votes = proposal.no_with_veto_votes + vote.vote_weight;
-    } else if (choice_abstain().choice == vote.choice) {
-        proposal.abstain_votes = proposal.abstain_votes + vote.vote_weight;
-    } else {
-        abort Errors::invalid_argument(ERR_VOTE_PARAM_INVALID)
-    };
-}
-
- - - -
- - - -## Function `has_voted` - - - -
fun has_voted<DAOT>(sender: address, proposal_id: u64): bool
-
- - - -
-Implementation - - -
fun has_voted<DAOT>(sender: address, proposal_id: u64): bool acquires MyVotes{
-    if(exists<MyVotes<DAOT>>(sender)){
-        let my_votes = borrow_global<MyVotes<DAOT>>(sender);
-        let vote = vote_info<DAOT>(my_votes, proposal_id);
-        Option::is_some(&vote)
-    }else{
-        false
-    }
-}
-
- - - -
- - - -## Function `vote_info` - -vote info by proposal_id - - -
fun vote_info<DAOT>(my_votes: &DAOSpace::MyVotes<DAOT>, proposal_id: u64): Option::Option<DAOSpace::VoteInfo>
-
- - - -
-Implementation - - -
fun vote_info<DAOT>(my_votes: &MyVotes<DAOT>, proposal_id: u64): Option<VoteInfo>{
-    let len = Vector::length(&my_votes.votes);
-    let idx = 0;
-    loop {
-        if (idx >= len) {
-            break
-        };
-        let vote = Vector::borrow(&my_votes.votes, idx);
-        if (proposal_id == vote.proposal_id) {
-            let vote_info = VoteInfo {
-                proposal_id: vote.proposal_id,
-                vote_weight: vote.vote_weight,
-                choice: vote.choice,
-            };
-            return Option::some(vote_info)
-        };
-        idx = idx + 1;
-    };
-    Option::none<VoteInfo>()
-}
-
- - - -
- - - -## Function `reject_proposal` - -Proposals are rejected when their nowithveto option reaches a certain threshold -A portion of the pledged tokens will be rewarded to the executor who executes the proposal - - -
public fun reject_proposal<DAOT: store, ActionT: drop, store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun reject_proposal<DAOT: store, ActionT: store+drop>(sender: &signer, proposal_id: u64)
-acquires DAO, ProposalEvent, ProposalActions, GlobalProposals, GlobalProposalActions{
-    // Only  REJECTED proposal's action can be burn token.
-    assert!(proposal_state<DAOT>(proposal_id) == REJECTED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    let dao_address = dao_address<DAOT>();
-    assert!(exists<ProposalActions<ActionT>>(dao_address), Errors::invalid_state(ERR_PROPOSAL_ACTIONS_NOT_EXIST));
-    let (_, token) = take_proposal_action<ActionT>(dao_address, proposal_id);
-    // Part of the token is awarded to whoever executes this method , current: 10 %
-    let award_amount = Token::value(&token) / 10;
-    let (burn_token , award_token) = Token::split(token, award_amount);
-    Account::deposit(Signer::address_of(sender), award_token);
-    STC::burn(burn_token);
-
-    // emit event
-    let dao_id = dao_id(dao_address);
-    let proposal_event = borrow_global_mut<ProposalEvent<DAOT>>(dao_address);
-    Event::emit_event(&mut proposal_event.proposal_action_event,
-        ProposalActionEvent { dao_id, proposal_id, sender: Signer::address_of(sender), state: REJECTED }
-    );
-}
-
- - - -
- - - -## Function `reject_proposal_entry` - - - -
public(script) fun reject_proposal_entry<DAOT: store, ActionT: drop, store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun reject_proposal_entry<DAOT: store, ActionT: store+drop>(sender: signer, proposal_id: u64)
-acquires DAO, ProposalEvent, ProposalActions, GlobalProposals, GlobalProposalActions{
-    reject_proposal<DAOT, ActionT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `get_vote_info` - -get vote info by proposal_id - - -
public fun get_vote_info<DAOT>(voter: address, proposal_id: u64): (u64, u8, u128)
-
- - - -
-Implementation - - -
public fun get_vote_info<DAOT>(voter: address, proposal_id: u64): (u64, u8, u128)acquires MyVotes {
-    if(exists<MyVotes<DAOT>>(voter)){
-        let my_votes = borrow_global<MyVotes<DAOT>>(voter);
-        let vote_option = vote_info<DAOT>(my_votes, proposal_id);
-        if(!Option::is_some(&vote_option)){
-            return (0, 0, 0)
-        };
-        let vote = Option::extract(&mut vote_option);
-        (vote.proposal_id, vote.choice, vote.vote_weight)
-    }else{
-        (0, 0, 0)
-    }
-}
-
- - - -
- - - -## Function `proposal_state` - - - -
public fun proposal_state<DAOT: store>(proposal_id: u64): u8
-
- - - -
-Implementation - - -
public fun proposal_state<DAOT: store>(proposal_id: u64) : u8 acquires GlobalProposalActions, GlobalProposals {
-    let dao_address = dao_address<DAOT>();
-    let proposals = borrow_global<GlobalProposals>(dao_address);
-    let proposal = borrow_proposal(proposals, proposal_id);
-
-    proposal_state_with_proposal<DAOT>(proposal)
-}
-
- - - -
- - - -## Function `proposal_state_with_proposal` - - - -
fun proposal_state_with_proposal<DAOT: store>(proposal: &DAOSpace::Proposal): u8
-
- - - -
-Implementation - - -
fun proposal_state_with_proposal<DAOT: store>(proposal: &Proposal) : u8 acquires GlobalProposalActions {
-    let dao_address = dao_address<DAOT>();
-    let current_time = Timestamp::now_milliseconds();
-
-    let global_proposal_actions = borrow_global<GlobalProposalActions>(dao_address);
-    let action_index_opt = find_proposal_action_index(global_proposal_actions, proposal.id);
-
-    do_proposal_state(proposal, current_time, action_index_opt)
-}
-
- - - -
- - - -## Function `do_proposal_state` - - - -
fun do_proposal_state(proposal: &DAOSpace::Proposal, current_time: u64, action_index_opt: Option::Option<u64>): u8
-
- - - -
-Implementation - - -
fun do_proposal_state(proposal: &Proposal, current_time: u64, action_index_opt: Option<u64>): u8 {
-    if (current_time < proposal.start_time) {
-        // Pending
-        PENDING
-    } else if (current_time <= proposal.end_time) {
-        // Active
-        ACTIVE
-    } else if (proposal.no_with_veto_votes >= (proposal.no_votes + proposal.yes_votes) ){
-        // rejected
-        REJECTED
-    } else if (proposal.yes_votes <=  (proposal.no_votes + proposal.no_with_veto_votes) ||
-               ( proposal.yes_votes + proposal.no_votes + proposal.abstain_votes + proposal.no_with_veto_votes ) < proposal.quorum_votes) {
-        // Defeated
-        DEFEATED
-    } else if (proposal.eta == 0) {
-        // Agreed.
-        AGREED
-    } else if (current_time < proposal.eta) {
-        // Queued, waiting to execute
-        QUEUED
-    } else if (Option::is_some(&action_index_opt)) {
-        EXECUTABLE
-    } else {
-        EXTRACTED
-    }
-}
-
- - - -
- - - -## Function `borrow_proposal_mut` - - - -
fun borrow_proposal_mut(proposals: &mut DAOSpace::GlobalProposals, proposal_id: u64): &mut DAOSpace::Proposal
-
- - - -
-Implementation - - -
fun borrow_proposal_mut(proposals: &mut GlobalProposals, proposal_id: u64): &mut Proposal{
-    let i = 0;
-    let len = Vector::length(&proposals.proposals);
-    while(i < len){
-        let proposal = Vector::borrow(&proposals.proposals, i);
-        if(proposal.id == proposal_id){
-            return Vector::borrow_mut(&mut proposals.proposals, i)
-        };
-        i = i + 1;
-    };
-    abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST)
-}
-
- - - -
- - - -## Function `borrow_proposal` - - - -
fun borrow_proposal(proposals: &DAOSpace::GlobalProposals, proposal_id: u64): &DAOSpace::Proposal
-
- - - -
-Implementation - - -
fun borrow_proposal(proposals: &GlobalProposals, proposal_id: u64): &Proposal {
-    let i = 0;
-    let len = Vector::length(&proposals.proposals);
-    while(i < len){
-        let proposal = Vector::borrow(&proposals.proposals, i);
-        if(proposal.id == proposal_id){
-            return proposal
-        };
-        i = i + 1;
-    };
-    abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST)
-}
-
- - - -
- - - -## Function `find_proposal_action_index` - - - -
fun find_proposal_action_index(global_proposal_action: &DAOSpace::GlobalProposalActions, proposal_id: u64): Option::Option<u64>
-
- - - -
-Implementation - - -
fun find_proposal_action_index(global_proposal_action: &GlobalProposalActions, proposal_id: u64): Option<u64> {
-    let i = 0;
-    let len = Vector::length(&global_proposal_action.proposal_action_indexs);
-    while(i < len){
-        let proposal_action_index = Vector::borrow(&global_proposal_action.proposal_action_indexs, i);
-        if(proposal_action_index.proposal_id == proposal_id){
-            return Option::some(i)
-        };
-        i = i + 1;
-    };
-    Option::none<u64>()
-}
-
- - - -
- - - -## Function `proposal` - -Return a copy of Proposal of proposal_id - - -
public fun proposal<DAOT>(proposal_id: u64): DAOSpace::Proposal
-
- - - -
-Implementation - - -
public fun proposal<DAOT>(proposal_id: u64): Proposal acquires GlobalProposals{
-    let dao_address = dao_address<DAOT>();
-    let global_proposals = borrow_global<GlobalProposals>(dao_address);
-    *borrow_proposal(global_proposals, proposal_id)
-}
-
- - - -
- - - -## Function `proposal_id` - -get proposal's id. - - -
public fun proposal_id(proposal: &DAOSpace::Proposal): u64
-
- - - -
-Implementation - - -
public fun proposal_id(proposal: &Proposal): u64 {
-    proposal.id
-}
-
- - - -
- - - -## Function `proposal_proposer` - -get proposal's proposer. - - -
public fun proposal_proposer(proposal: &DAOSpace::Proposal): address
-
- - - -
-Implementation - - -
public fun proposal_proposer(proposal: &Proposal): address {
-    proposal.proposer
-}
-
- - - -
- - - -## Function `proposal_time` - -get proposal's time(start_time/end_time). - - -
public fun proposal_time(proposal: &DAOSpace::Proposal): (u64, u64)
-
- - - -
-Implementation - - -
public fun proposal_time(proposal: &Proposal): (u64, u64) {
-    (proposal.start_time,proposal.end_time)
-}
-
- - - -
- - - -## Function `proposal_votes` - -get proposal's votes(Yes/No/Abstain/Veto). - - -
public fun proposal_votes(proposal: &DAOSpace::Proposal): (u128, u128, u128, u128)
-
- - - -
-Implementation - - -
public fun proposal_votes(proposal: &Proposal): (u128, u128, u128, u128) {
-    (proposal.yes_votes, proposal.no_votes, proposal.abstain_votes, proposal.no_with_veto_votes)
-}
-
- - - -
- - - -## Function `proposal_block_number` - -get proposal's block number. - - -
public fun proposal_block_number(proposal: &DAOSpace::Proposal): u64
-
- - - -
-Implementation - - -
public fun proposal_block_number(proposal: &Proposal): u64 {
-    proposal.block_number
-}
-
- - - -
- - - -## Function `proposal_state_root` - -get proposal's state root. - - -
public fun proposal_state_root(proposal: &DAOSpace::Proposal): vector<u8>
-
- - - -
-Implementation - - -
public fun proposal_state_root(proposal: &Proposal): vector<u8> {
-    *&proposal.state_root
-}
-
- - - -
- - - -## Function `queue_proposal_action_entry` - -queue agreed proposal to execute. - - -
public(script) fun queue_proposal_action_entry<DAOT: store>(_signer: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun queue_proposal_action_entry<DAOT:store>(
-    _signer: signer,
-    proposal_id: u64,
-) acquires GlobalProposalActions, GlobalProposals {
-    queue_proposal_action<DAOT>(proposal_id)
-}
-
- - - -
- - - -## Function `queue_proposal_action` - -queue agreed proposal to execute. - - -
public fun queue_proposal_action<DAOT: store>(proposal_id: u64)
-
- - - -
-Implementation - - -
public fun queue_proposal_action<DAOT:store>(
-    proposal_id: u64,
-) acquires GlobalProposalActions, GlobalProposals {
-    // Only agreed proposal can be submitted.
-    assert!(proposal_state<DAOT>(proposal_id) == AGREED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    let dao_address = dao_address<DAOT>();
-    let proposals = borrow_global_mut<GlobalProposals>(dao_address);
-    let proposal = borrow_proposal_mut(proposals, proposal_id);
-    proposal.eta = Timestamp::now_milliseconds() + proposal.action_delay;
-}
-
- - - -
- - - -## Function `cast_vote_entry` - - - -
public(script) fun cast_vote_entry<DAOT: store>(sender: signer, proposal_id: u64, snpashot_raw_proofs: vector<u8>, choice: u8)
-
- - - -
-Implementation - - -
public(script) fun cast_vote_entry<DAOT:store>(
-    sender: signer,
-    proposal_id: u64,
-    snpashot_raw_proofs: vector<u8>,
-    choice: u8,
-) acquires MyVotes, GlobalProposals, ProposalEvent, GlobalProposalActions, DAO {
-    let sender_addr = Signer::address_of(&sender);
-    if (has_voted<DAOT>(sender_addr, proposal_id)) {
-        abort Errors::invalid_state(ERR_VOTED_ALREADY)
-    };
-
-    let vote_choice = VotingChoice {
-        choice,
-    };
-    cast_vote<DAOT>(&sender, proposal_id, snpashot_raw_proofs, vote_choice)
-}
-
- - - -
- - - -## Function `new_dao_config` - -DAOConfig ---------------------------------------------------- -create a dao config - - -
public fun new_dao_config(voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, min_proposal_deposit: u128): DAOSpace::DAOConfig
-
- - - -
-Implementation - - -
public fun new_dao_config(
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-    min_proposal_deposit: u128,
-): DAOConfig{
-    assert!(voting_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    assert!(voting_period > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    assert!(
-        voting_quorum_rate > 0 && voting_quorum_rate <= 100,
-        Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID),
-    );
-    assert!(min_action_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    DAOConfig { voting_delay, voting_period, voting_quorum_rate, min_action_delay, min_proposal_deposit }
-}
-
- - - -
- - - -## Function `get_custom_config` - - - -
public fun get_custom_config<DAOT: store, ConfigT: copy, drop, store>(): ConfigT
-
- - - -
-Implementation - - -
public fun get_custom_config<DAOT: store,
-                             ConfigT: copy + store + drop>(): ConfigT {
-    let dao_address = dao_address<DAOT>();
-    Config::get_by_address<ConfigT>(dao_address)
-}
-
- - - -
- - - -## Function `exists_custom_config` - - - -
public fun exists_custom_config<DAOT: store, ConfigT: copy, drop, store>(): bool
-
- - - -
-Implementation - - -
public fun exists_custom_config<DAOT: store,
-                                ConfigT: copy + store + drop>(): bool {
-    let dao_address = dao_address<DAOT>();
-    Config::config_exist_by_address<ConfigT>(dao_address)
-}
-
- - - -
- - - -## Function `set_custom_config` - -Update, save function of custom plugin configuration - - -
public fun set_custom_config<DAOT: store, PluginT: drop, ConfigT: copy, drop, store>(_cap: &mut DAOSpace::DAOModifyConfigCap<DAOT, PluginT>, config: ConfigT)
-
- - - -
-Implementation - - -
public fun set_custom_config<DAOT: store,
-                             PluginT: drop,
-                             ConfigT: copy + store + drop>(
-    _cap: &mut DAOModifyConfigCap<DAOT, PluginT>,
-    config: ConfigT)
-acquires DAOCustomConfigModifyCapHolder, DAOAccountCapHolder {
-    let dao_address = dao_address<DAOT>();
-    if (Config::config_exist_by_address<ConfigT>(dao_address)) {
-        let cap_holder =
-            borrow_global_mut<DAOCustomConfigModifyCapHolder<DAOT, ConfigT>>(dao_address);
-        let modify_config_cap = &mut cap_holder.cap;
-        Config::set_with_capability(modify_config_cap, config);
-    } else {
-        let signer = dao_signer<DAOT>();
-        move_to(&signer, DAOCustomConfigModifyCapHolder<DAOT, ConfigT> {
-            cap: Config::publish_new_config_with_capability<ConfigT>(&signer, config)
-        });
-    }
-}
-
- - - -
- - - -## Function `set_custom_config_cap` - - - -
public(friend) fun set_custom_config_cap<DAOT: store, ConfigT: copy, drop, store>(config_cap: Config::ModifyConfigCapability<ConfigT>)
-
- - - -
-Implementation - - -
public (friend) fun set_custom_config_cap<DAOT: store,
-                                ConfigT:copy + store + drop>(
-    config_cap: Config::ModifyConfigCapability<ConfigT>)
-    acquires DAOAccountCapHolder{
-        let signer = dao_signer<DAOT>();
-        move_to(&signer, DAOCustomConfigModifyCapHolder<DAOT, ConfigT> {
-            cap: config_cap
-    });
-}
-
- - - -
- - - -## Function `set_dao_description` - -Update DAO description - - -
public fun set_dao_description<DAOT: store, PluginT: drop, ConfigT: copy, drop, store>(_cap: &mut DAOSpace::DAOModifyConfigCap<DAOT, PluginT>, description: vector<u8>)
-
- - - -
-Implementation - - -
public fun set_dao_description<DAOT: store,
-                             PluginT: drop,
-                             ConfigT: copy + store + drop>(
-    _cap: &mut DAOModifyConfigCap<DAOT, PluginT>,
-    description: vector<u8>)
-acquires DAO{
-    let dao_address = dao_address<DAOT>();
-    let dao = borrow_global_mut<DAO>(dao_address);
-    dao.description = description;
-}
-
- - - -
- - - -## Function `set_dao_image` - -Update DAO NFT image - - -
public fun set_dao_image<DAOT: store, PluginT: drop, ConfigT: copy, drop, store>(_cap: &mut DAOSpace::DAOModifyConfigCap<DAOT, PluginT>, image_data: Option::Option<vector<u8>>, image_url: Option::Option<vector<u8>>)
-
- - - -
-Implementation - - -
public fun set_dao_image<DAOT: store,
-                             PluginT: drop,
-                             ConfigT: copy + store + drop>(
-    _cap: &mut DAOModifyConfigCap<DAOT, PluginT>,
-    image_data:Option::Option<vector<u8>>,
-    image_url:Option::Option<vector<u8>>)
-acquires DAONFTUpdateCapHolder{
-    let dao_address = dao_address<DAOT>();
-    let nft_update_cap = &mut borrow_global_mut<DAONFTUpdateCapHolder<DAOT>>(dao_address).cap;
-    let old_meta = NFT::nft_type_info_meta<DAOMember<DAOT>>();
-    let new_meta = if(Option::is_some(&image_data)){
-        NFT::new_meta_with_image_data(NFT::meta_name(&old_meta), Option::destroy_some(image_data), NFT::meta_description(&old_meta))
-    }else if(Option::is_some(&image_url)){
-        NFT::new_meta_with_image(NFT::meta_name(&old_meta), Option::destroy_some(image_url), NFT::meta_description(&old_meta))
-    }else{
-        NFT::new_meta(NFT::meta_name(&old_meta), NFT::meta_description(&old_meta))
-    };
-    NFT::update_nft_type_info_meta_with_cap<DAOMember<DAOT>>(nft_update_cap, new_meta);
-}
-
- - - -
- - - -## Function `voting_delay` - -get default voting delay of the DAO. - - -
public fun voting_delay<DAOT: store>(): u64
-
- - - -
-Implementation - - -
public fun voting_delay<DAOT: store>(): u64 {
-    get_config<DAOT>().voting_delay
-}
-
- - - -
- - - -## Function `voting_period` - -get the default voting period of the DAO. - - -
public fun voting_period<DAOT: store>(): u64
-
- - - -
-Implementation - - -
public fun voting_period<DAOT: store>(): u64 {
-    get_config<DAOT>().voting_period
-}
-
- - - -
- - - -## Function `quorum_votes` - -Quorum votes to make proposal valid. - - -
public fun quorum_votes<DAOT: store>(scale_factor: Option::Option<u8>): u128
-
- - - -
-Implementation - - -
public fun quorum_votes<DAOT: store>(scale_factor: Option::Option<u8>): u128 {
-    let scale_factor = if (Option::is_none(&scale_factor)) {
-        0u8
-    } else {
-        Option::extract(&mut scale_factor)
-    };
-    assert!(
-        scale_factor >= 0 && scale_factor <= 100,
-        Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID),
-    );
-
-    let market_cap = Token::market_cap<DAOT>();
-    let rate = (voting_quorum_rate<DAOT>() as u128);
-    let rate = rate + rate * (scale_factor as u128) / 100;
-    assert!(
-        rate > 0 && rate <= 100,
-        Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID),
-    );
-    market_cap * rate / 100
-}
-
- - - -
- - - -## Function `voting_quorum_rate` - -Get the quorum rate in percent. - - -
public fun voting_quorum_rate<DAOT: store>(): u8
-
- - - -
-Implementation - - -
public fun voting_quorum_rate<DAOT: store>(): u8 {
-    get_config<DAOT>().voting_quorum_rate
-}
-
- - - -
- - - -## Function `min_action_delay` - -Get the min action delay of the DAO. - - -
public fun min_action_delay<DAOT: store>(): u64
-
- - - -
-Implementation - - -
public fun min_action_delay<DAOT: store>(): u64 {
-    get_config<DAOT>().min_action_delay
-}
-
- - - -
- - - -## Function `min_proposal_deposit` - -Get the min proposal deposit of the DAO. - - -
public fun min_proposal_deposit<DAOT: store>(): u128
-
- - - -
-Implementation - - -
public fun min_proposal_deposit<DAOT: store>(): u128{
-    get_config<DAOT>().min_proposal_deposit
-}
-
- - - -
- - - -## Function `get_config` - - - -
fun get_config<DAOT: store>(): DAOSpace::DAOConfig
-
- - - -
-Implementation - - -
fun get_config<DAOT: store>(): DAOConfig {
-    let dao_address= dao_address<DAOT>();
-    Config::get_by_address<DAOConfig>(dao_address)
-}
-
- - - -
- - - -## Function `modify_dao_config` - -Update function, modify dao config. - - -
public fun modify_dao_config<DAOT: store, PluginT>(_cap: &mut DAOSpace::DAOModifyConfigCap<DAOT, PluginT>, new_config: DAOSpace::DAOConfig)
-
- - - -
-Implementation - - -
public fun modify_dao_config<DAOT: store, PluginT>(
-    _cap: &mut DAOModifyConfigCap<DAOT, PluginT>,
-    new_config: DAOConfig,
-) acquires DAOConfigModifyCapHolder {
-    let modify_config_cap = &mut borrow_global_mut<DAOConfigModifyCapHolder>(
-        dao_address<DAOT>(),
-    ).cap;
-    Config::set_with_capability<DAOConfig>(modify_config_cap, new_config);
-}
-
- - - -
- - - -## Function `set_voting_delay` - -set voting delay - - -
public fun set_voting_delay(config: &mut DAOSpace::DAOConfig, value: u64)
-
- - - -
-Implementation - - -
public fun set_voting_delay(
-    config: &mut DAOConfig,
-    value: u64,
-) {
-    assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    config.voting_delay = value;
-}
-
- - - -
- - - -## Function `set_voting_period` - -set voting period - - -
public fun set_voting_period<DAOT: store>(config: &mut DAOSpace::DAOConfig, value: u64)
-
- - - -
-Implementation - - -
public fun set_voting_period<DAOT: store>(
-    config: &mut DAOConfig,
-    value: u64,
-) {
-    assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    config.voting_period = value;
-}
-
- - - -
- - - -## Function `set_voting_quorum_rate` - -set voting quorum rate - - -
public fun set_voting_quorum_rate<DAOT: store>(config: &mut DAOSpace::DAOConfig, value: u8)
-
- - - -
-Implementation - - -
public fun set_voting_quorum_rate<DAOT: store>(
-    config: &mut DAOConfig,
-    value: u8,
-) {
-    assert!(value <= 100 && value > 0, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID));
-    config.voting_quorum_rate = value;
-}
-
- - - -
- - - -## Function `set_min_action_delay` - -set min action delay - - -
public fun set_min_action_delay<DAOT: store>(config: &mut DAOSpace::DAOConfig, value: u64)
-
- - - -
-Implementation - - -
public fun set_min_action_delay<DAOT: store>(
-    config: &mut DAOConfig,
-    value: u64,
-) {
-    assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    config.min_action_delay = value;
-}
-
- - - -
- - - -## Function `set_min_proposal_deposit` - -set min action delay - - -
public fun set_min_proposal_deposit<DAOT: store>(config: &mut DAOSpace::DAOConfig, value: u128)
-
- - - -
-Implementation - - -
public fun set_min_proposal_deposit<DAOT: store>(
-    config: &mut DAOConfig,
-    value: u128,
-) {
-    config.min_proposal_deposit = value;
-}
-
- - - -
- - - -## Function `next_member_id` - -Helpers ---------------------------------------------------- - - -
fun next_member_id<DAOT>(): u64
-
- - - -
-Implementation - - -
fun next_member_id<DAOT>(): u64 acquires DAO {
-    let dao_address = dao_address<DAOT>();
-    let dao = borrow_global_mut<DAO>(dao_address);
-    let member_id = dao.next_member_id;
-    dao.next_member_id = member_id + 1;
-    member_id
-}
-
- - - -
- - - -## Function `next_proposal_id` - - - -
fun next_proposal_id<DAOT>(): u64
-
- - - -
-Implementation - - -
fun next_proposal_id<DAOT>(): u64 acquires DAO {
-    let dao_address = dao_address<DAOT>();
-    let dao = borrow_global_mut<DAO>(dao_address);
-    let proposal_id = dao.next_proposal_id;
-    dao.next_proposal_id = proposal_id + 1;
-    proposal_id
-}
-
- - - -
- - - -## Function `assert_no_repeat` - - - -
fun assert_no_repeat<E>(v: &vector<E>)
-
- - - -
-Implementation - - -
fun assert_no_repeat<E>(v: &vector<E>) {
-    let i = 1;
-    let len = Vector::length(v);
-    while (i < len) {
-        let e = Vector::borrow(v, i);
-        let j = 0;
-        while (j < i) {
-            let f = Vector::borrow(v, j);
-            assert!(e != f, Errors::invalid_argument(ERR_REPEAT_ELEMENT));
-            j = j + 1;
-        };
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `remove_element` - -Helper to remove an element from a vector. - - -
fun remove_element<E: drop>(v: &mut vector<E>, x: &E)
-
- - - -
-Implementation - - -
fun remove_element<E: drop>(v: &mut vector<E>, x: &E) {
-    let (found, index) = Vector::index_of(v, x);
-    if (found) {
-        Vector::remove(v, index);
-    }
-}
-
- - - -
- - - -## Function `add_element` - -Helper to add an element to a vector. - - -
fun add_element<E: drop>(v: &mut vector<E>, x: E)
-
- - - -
-Implementation - - -
fun add_element<E: drop>(v: &mut vector<E>, x: E) {
-    if (!Vector::contains(v, &x)) {
-        Vector::push_back(v, x)
-    }
-}
-
- - - -
- - - -## Function `convert_option_bytes_vector` - - - -
fun convert_option_bytes_vector(input: &vector<Option::Option<vector<u8>>>): vector<vector<u8>>
-
- - - -
-Implementation - - -
fun convert_option_bytes_vector(input: &vector<Option::Option<vector<u8>>>): vector<vector<u8>> {
-    let len = Vector::length(input);
-    let i = 0;
-    let output = Vector::empty<vector<u8>>();
-    while (i < len) {
-        let option = Vector::borrow(input, i);
-        if (Option::is_some(option)){
-            Vector::push_back(&mut output, Option::extract(&mut *option));
-        };
-        i = i + 1;
-    };
-    output
-}
-
- - - -
- - - -## Function `dao_signer` - - - -
fun dao_signer<DAOT>(): signer
-
- - - -
-Implementation - - -
fun dao_signer<DAOT>(): signer acquires DAOAccountCapHolder {
-    let cap = &borrow_global<DAOAccountCapHolder>(dao_address<DAOT>()).cap;
-    DAOAccount::dao_signer(cap)
-}
-
- - - -
- - - -## Function `dao_address` - - - -
public fun dao_address<DAOT>(): address
-
- - - -
-Implementation - - -
public fun dao_address<DAOT>(): address {
-    DAORegistry::dao_address<DAOT>()
-}
-
- - - -
- - - -## Function `dao_id` - - - -
public fun dao_id(dao_address: address): u64
-
- - - -
-Implementation - - -
public fun dao_id(dao_address: address): u64 acquires DAO {
-    if (exists<DAO>(dao_address)){
-        let dao = borrow_global<DAO>(dao_address);
-        dao.id
-    }else{
-        0
-    }
-}
-
- - - -
diff --git a/release/v12/docs/Dao.md b/release/v12/docs/Dao.md deleted file mode 100644 index 453b0e50..00000000 --- a/release/v12/docs/Dao.md +++ /dev/null @@ -1,2330 +0,0 @@ - - - -# Module `0x1::Dao` - - - -- [Resource `DaoGlobalInfo`](#0x1_Dao_DaoGlobalInfo) -- [Struct `DaoConfig`](#0x1_Dao_DaoConfig) -- [Struct `ProposalCreatedEvent`](#0x1_Dao_ProposalCreatedEvent) -- [Struct `VoteChangedEvent`](#0x1_Dao_VoteChangedEvent) -- [Resource `Proposal`](#0x1_Dao_Proposal) -- [Resource `Vote`](#0x1_Dao_Vote) -- [Constants](#@Constants_0) -- [Function `plugin`](#0x1_Dao_plugin) -- [Function `new_dao_config`](#0x1_Dao_new_dao_config) -- [Function `propose`](#0x1_Dao_propose) -- [Function `cast_vote`](#0x1_Dao_cast_vote) -- [Function `do_cast_vote`](#0x1_Dao_do_cast_vote) -- [Function `change_vote`](#0x1_Dao_change_vote) -- [Function `do_flip_vote`](#0x1_Dao_do_flip_vote) -- [Function `revoke_vote`](#0x1_Dao_revoke_vote) -- [Function `do_revoke_vote`](#0x1_Dao_do_revoke_vote) -- [Function `unstake_votes`](#0x1_Dao_unstake_votes) -- [Function `queue_proposal_action`](#0x1_Dao_queue_proposal_action) -- [Function `extract_proposal_action`](#0x1_Dao_extract_proposal_action) -- [Function `destroy_terminated_proposal`](#0x1_Dao_destroy_terminated_proposal) -- [Function `proposal_exists`](#0x1_Dao_proposal_exists) -- [Function `proposal_state`](#0x1_Dao_proposal_state) -- [Function `do_proposal_state`](#0x1_Dao_do_proposal_state) -- [Function `proposal_info`](#0x1_Dao_proposal_info) -- [Function `vote_of`](#0x1_Dao_vote_of) -- [Function `has_vote`](#0x1_Dao_has_vote) -- [Function `generate_next_proposal_id`](#0x1_Dao_generate_next_proposal_id) -- [Function `voting_delay`](#0x1_Dao_voting_delay) -- [Function `voting_period`](#0x1_Dao_voting_period) -- [Function `quorum_votes`](#0x1_Dao_quorum_votes) -- [Function `voting_quorum_rate`](#0x1_Dao_voting_quorum_rate) -- [Function `min_action_delay`](#0x1_Dao_min_action_delay) -- [Function `get_config`](#0x1_Dao_get_config) -- [Function `modify_dao_config`](#0x1_Dao_modify_dao_config) -- [Function `set_voting_delay`](#0x1_Dao_set_voting_delay) -- [Function `set_voting_period`](#0x1_Dao_set_voting_period) -- [Function `set_voting_quorum_rate`](#0x1_Dao_set_voting_quorum_rate) -- [Function `set_min_action_delay`](#0x1_Dao_set_min_action_delay) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::Treasury;
-
- - - - - -## Resource `DaoGlobalInfo` - -global DAO info of the specified token type Token. - - -
struct DaoGlobalInfo<Token: store> has key
-
- - - -
-Fields - - -
-
-next_proposal_id: u64 -
-
- next proposal id. -
-
-proposal_create_event: Event::EventHandle<Dao::ProposalCreatedEvent> -
-
- proposal creating event. -
-
-vote_changed_event: Event::EventHandle<Dao::VoteChangedEvent> -
-
- voting event. -
-
- - -
- - - -## Struct `DaoConfig` - -Configuration of the Token's DAO. - - -
struct DaoConfig<TokenT: copy, drop, store> has copy, drop, store
-
- - - -
-Fields - - -
-
-voting_delay: u64 -
-
- after proposal created, how long use should wait before he can vote (in milliseconds) -
-
-voting_period: u64 -
-
- how long the voting window is (in milliseconds). -
-
-voting_quorum_rate: u8 -
-
- the quorum rate to agree on the proposal. - if 50% votes needed, then the voting_quorum_rate should be 50. - it should between (0, 100]. -
-
-min_action_delay: u64 -
-
- how long the proposal should wait before it can be executed (in milliseconds). -
-
- - -
- -
-Specification - - - -
invariant voting_quorum_rate > 0 && voting_quorum_rate <= 100;
-invariant voting_delay > 0;
-invariant voting_period > 0;
-invariant min_action_delay > 0;
-
- - - -
- - - -## Struct `ProposalCreatedEvent` - -emitted when proposal created. - - -
struct ProposalCreatedEvent has drop, store
-
- - - -
-Fields - - -
-
-proposal_id: u64 -
-
- the proposal id. -
-
-proposer: address -
-
- proposer is the user who create the proposal. -
-
- - -
- - - -## Struct `VoteChangedEvent` - -emitted when user vote/revoke_vote. - - -
struct VoteChangedEvent has drop, store
-
- - - -
-Fields - - -
-
-proposal_id: u64 -
-
- the proposal id. -
-
-voter: address -
-
- the voter. -
-
-proposer: address -
-
- creator of the proposal. -
-
-agree: bool -
-
- agree with the proposal or not -
-
-vote: u128 -
-
- latest vote count of the voter. -
-
- - -
- - - -## Resource `Proposal` - -Proposal data struct. - - -
struct Proposal<Token: store, Action: store> has key
-
- - - -
-Fields - - -
-
-id: u64 -
-
- id of the proposal -
-
-proposer: address -
-
- creator of the proposal -
-
-start_time: u64 -
-
- when voting begins. -
-
-end_time: u64 -
-
- when voting ends. -
-
-for_votes: u128 -
-
- count of voters who agree with the proposal -
-
-against_votes: u128 -
-
- count of voters who're against the proposal -
-
-eta: u64 -
-
- executable after this time. -
-
-action_delay: u64 -
-
- after how long, the agreed proposal can be executed. -
-
-quorum_votes: u128 -
-
- how many votes to reach to make the proposal pass. -
-
-action: Option::Option<Action> -
-
- proposal action. -
-
- - -
- - - -## Resource `Vote` - -User vote info. - - -
struct Vote<TokenT: store> has key
-
- - - -
-Fields - - -
-
-proposer: address -
-
- vote for the proposal under the proposer. -
-
-id: u64 -
-
- proposal id. -
-
-stake: Token::Token<TokenT> -
-
- how many tokens to stake. -
-
-agree: bool -
-
- vote for or vote against. -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 1401;
-
- - - - - - - -
const ACTIVE: u8 = 2;
-
- - - - - - - -
const AGREED: u8 = 4;
-
- - - - - - - -
const DEFEATED: u8 = 3;
-
- - - - - - - -
const ERR_ACTION_DELAY_TOO_SMALL: u64 = 1402;
-
- - - - - - - -
const ERR_ACTION_MUST_EXIST: u64 = 1409;
-
- - - - - - - -
const ERR_CONFIG_PARAM_INVALID: u64 = 1407;
-
- - - - - - - -
const ERR_PROPOSAL_ID_MISMATCH: u64 = 1404;
-
- - - - - - - -
const ERR_PROPOSAL_STATE_INVALID: u64 = 1403;
-
- - - - - - - -
const ERR_PROPOSER_MISMATCH: u64 = 1405;
-
- - - - - - - -
const ERR_QUORUM_RATE_INVALID: u64 = 1406;
-
- - - - - - - -
const ERR_VOTED_OTHERS_ALREADY: u64 = 1410;
-
- - - - - - - -
const ERR_VOTE_STATE_MISMATCH: u64 = 1408;
-
- - - - - - - -
const EXECUTABLE: u8 = 6;
-
- - - - - - - -
const EXTRACTED: u8 = 7;
-
- - - - - -Proposal state - - -
const PENDING: u8 = 1;
-
- - - - - - - -
const QUEUED: u8 = 5;
-
- - - - - -## Function `plugin` - -plugin function, can only be called by token issuer. -Any token who wants to have gov functionality -can optin this module by call this register function. - - -
public fun plugin<TokenT: copy, drop, store>(signer: &signer, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64)
-
- - - -
-Implementation - - -
public fun plugin<TokenT: copy + drop + store>(
-    signer: &signer,
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-) {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    // let proposal_id = ProposalId {next: 0};
-    let gov_info = DaoGlobalInfo<TokenT> {
-        next_proposal_id: 0,
-        proposal_create_event: Event::new_event_handle<ProposalCreatedEvent>(signer),
-        vote_changed_event: Event::new_event_handle<VoteChangedEvent>(signer),
-    };
-    move_to(signer, gov_info);
-    let config = new_dao_config<TokenT>(
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-    );
-    Config::publish_new_config(signer, config);
-}
-
- - - -
- -
-Specification - - - -
let sender = Signer::address_of(signer);
-aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS();
-include NewDaoConfigParamSchema<TokenT>;
-include Config::PublishNewConfigAbortsIf<DaoConfig<TokenT>>{account: signer};
-aborts_if exists<DaoGlobalInfo<TokenT>>(sender);
-
- - - - - - - -
schema RequirePluginDao<TokenT> {
-    let token_addr = Token::SPEC_TOKEN_TEST_ADDRESS();
-    aborts_if !exists<DaoGlobalInfo<TokenT>>(token_addr);
-    aborts_if !exists<Config::Config<DaoConfig<TokenT>>>(token_addr);
-}
-
- - - - - - - -
schema AbortIfDaoInfoNotExist<TokenT> {
-    let token_addr = Token::SPEC_TOKEN_TEST_ADDRESS();
-    aborts_if !exists<DaoGlobalInfo<TokenT>>(token_addr);
-}
-
- - - - - - - -
schema AbortIfDaoConfigNotExist<TokenT> {
-    let token_addr = Token::SPEC_TOKEN_TEST_ADDRESS();
-    aborts_if !exists<Config::Config<DaoConfig<TokenT>>>(token_addr);
-}
-
- - - - - - - -
schema AbortIfTimestampNotExist {
-    aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-}
-
- - - - -
apply
-    AbortIfDaoInfoNotExist<TokenT>
-to
-    generate_next_proposal_id<TokenT>;
-apply
-    AbortIfDaoConfigNotExist<TokenT>
-to
-    get_config<TokenT>,
-    voting_delay<TokenT>,
-    voting_period<TokenT>,
-    voting_quorum_rate<TokenT>,
-    min_action_delay<TokenT>,
-    quorum_votes<TokenT>;
-
- - - -
- - - -## Function `new_dao_config` - -create a dao config - - -
public fun new_dao_config<TokenT: copy, drop, store>(voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64): Dao::DaoConfig<TokenT>
-
- - - -
-Implementation - - -
public fun new_dao_config<TokenT: copy + drop + store>(
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-): DaoConfig<TokenT> {
-    assert!(voting_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    assert!(voting_period > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    assert!(
-        voting_quorum_rate > 0 && voting_quorum_rate <= 100,
-        Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID),
-    );
-    assert!(min_action_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    DaoConfig { voting_delay, voting_period, voting_quorum_rate, min_action_delay }
-}
-
- - - -
- -
-Specification - - - -
include NewDaoConfigParamSchema<TokenT>;
-
- - - - - - - -
schema NewDaoConfigParamSchema<TokenT> {
-    voting_delay: u64;
-    voting_period: u64;
-    voting_quorum_rate: u8;
-    min_action_delay: u64;
-    aborts_if voting_delay == 0;
-    aborts_if voting_period == 0;
-    aborts_if voting_quorum_rate == 0 || voting_quorum_rate > 100;
-    aborts_if min_action_delay == 0;
-}
-
- - - -
- - - -## Function `propose` - -propose a proposal. -action: the actual action to execute. -action_delay: the delay to execute after the proposal is agreed - - -
public fun propose<TokenT: copy, drop, store, ActionT: copy, drop, store>(signer: &signer, action: ActionT, action_delay: u64)
-
- - - -
-Implementation - - -
public fun propose<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    signer: &signer,
-    action: ActionT,
-    action_delay: u64,
-) acquires DaoGlobalInfo {
-    if (action_delay == 0) {
-        action_delay = min_action_delay<TokenT>();
-    } else {
-        assert!(action_delay >= min_action_delay<TokenT>(), Errors::invalid_argument(ERR_ACTION_DELAY_TOO_SMALL));
-    };
-    let proposal_id = generate_next_proposal_id<TokenT>();
-    let proposer = Signer::address_of(signer);
-    let start_time = Timestamp::now_milliseconds() + voting_delay<TokenT>();
-    let quorum_votes = quorum_votes<TokenT>();
-    let proposal = Proposal<TokenT, ActionT> {
-        id: proposal_id,
-        proposer,
-        start_time,
-        end_time: start_time + voting_period<TokenT>(),
-        for_votes: 0,
-        against_votes: 0,
-        eta: 0,
-        action_delay,
-        quorum_votes,
-        action: Option::some(action),
-    };
-    move_to(signer, proposal);
-    // emit event
-    let gov_info = borrow_global_mut<DaoGlobalInfo<TokenT>>(Token::token_address<TokenT>());
-    Event::emit_event(
-        &mut gov_info.proposal_create_event,
-        ProposalCreatedEvent { proposal_id, proposer },
-    );
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-let proposer = Signer::address_of(signer);
-include GenerateNextProposalIdSchema<TokenT>;
-pragma addition_overflow_unchecked = true;
-include AbortIfDaoConfigNotExist<TokenT>;
-include AbortIfDaoInfoNotExist<TokenT>;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if action_delay > 0 && action_delay < spec_dao_config<TokenT>().min_action_delay;
-include CheckQuorumVotes<TokenT>;
-let sender = Signer::address_of(signer);
-aborts_if exists<Proposal<TokenT, ActionT>>(sender);
-modifies global<DaoGlobalInfo<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-ensures exists<Proposal<TokenT, ActionT>>(sender);
-
- - - -
- - - -## Function `cast_vote` - -votes for a proposal. -User can only vote once, then the stake is locked, -which can only be unstaked by user after the proposal is expired, or cancelled, or executed. -So think twice before casting vote. - - -
public fun cast_vote<TokenT: copy, drop, store, ActionT: copy, drop, store>(signer: &signer, proposer_address: address, proposal_id: u64, stake: Token::Token<TokenT>, agree: bool)
-
- - - -
-Implementation - - -
public fun cast_vote<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    signer: &signer,
-    proposer_address: address,
-    proposal_id: u64,
-    stake: Token::Token<TokenT>,
-    agree: bool,
-) acquires Proposal, DaoGlobalInfo, Vote {
-    {
-        let state = proposal_state<TokenT, ActionT>(proposer_address, proposal_id);
-        // only when proposal is active, use can cast vote.
-        assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    };
-    let proposal = borrow_global_mut<Proposal<TokenT, ActionT>>(proposer_address);
-    assert!(proposal.id == proposal_id, Errors::invalid_argument(ERR_PROPOSAL_ID_MISMATCH));
-    let sender = Signer::address_of(signer);
-    let total_voted = if (exists<Vote<TokenT>>(sender)) {
-        let my_vote = borrow_global_mut<Vote<TokenT>>(sender);
-        assert!(my_vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY));
-        assert!(my_vote.agree == agree, Errors::invalid_state(ERR_VOTE_STATE_MISMATCH));
-
-        do_cast_vote(proposal, my_vote, stake);
-        Token::value(&my_vote.stake)
-    } else {
-        let my_vote = Vote<TokenT> {
-            proposer: proposer_address,
-            id: proposal_id,
-            stake: Token::zero(),
-            agree,
-        };
-        do_cast_vote(proposal, &mut my_vote, stake);
-        let total_voted = Token::value(&my_vote.stake);
-        move_to(signer, my_vote);
-        total_voted
-    };
-
-    // emit event
-    let gov_info = borrow_global_mut<DaoGlobalInfo<TokenT>>(Token::token_address<TokenT>());
-    Event::emit_event(
-        &mut gov_info.vote_changed_event,
-        VoteChangedEvent {
-            proposal_id,
-            proposer: proposer_address,
-            voter: sender,
-            agree,
-            vote: total_voted,
-        },
-    );
-}
-
- - - -
- -
-Specification - - - -
pragma addition_overflow_unchecked = true;
-include AbortIfDaoInfoNotExist<TokenT>;
-let expected_states = vec(ACTIVE);
-include CheckProposalStates<TokenT, ActionT> {expected_states};
-let sender = Signer::address_of(signer);
-let vote_exists = exists<Vote<TokenT>>(sender);
-include vote_exists ==> CheckVoteOnCast<TokenT, ActionT> {
-    voter: sender,
-    proposal_id: proposal_id,
-    agree: agree,
-    stake_value: stake.value,
-};
-modifies global<Proposal<TokenT, ActionT>>(proposer_address);
-ensures !vote_exists ==> global<Vote<TokenT>>(sender).stake.value == stake.value;
-
- - - -
- - - -## Function `do_cast_vote` - - - -
fun do_cast_vote<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposal: &mut Dao::Proposal<TokenT, ActionT>, vote: &mut Dao::Vote<TokenT>, stake: Token::Token<TokenT>)
-
- - - -
-Implementation - - -
fun do_cast_vote<TokenT: copy + drop + store, ActionT: copy + drop + store>(proposal: &mut Proposal<TokenT, ActionT>, vote: &mut Vote<TokenT>, stake: Token::Token<TokenT>) {
-    let stake_value = Token::value(&stake);
-    Token::deposit(&mut vote.stake, stake);
-    if (vote.agree) {
-        proposal.for_votes = proposal.for_votes + stake_value;
-    } else {
-        proposal.against_votes = proposal.against_votes + stake_value;
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma addition_overflow_unchecked = true;
-aborts_if vote.stake.value + stake.value > MAX_U128;
-ensures vote.stake.value == old(vote).stake.value + stake.value;
-ensures vote.agree ==> old(proposal).for_votes + stake.value == proposal.for_votes;
-ensures vote.agree ==> old(proposal).against_votes == proposal.against_votes;
-ensures !vote.agree ==> old(proposal).against_votes + stake.value == proposal.against_votes;
-ensures !vote.agree ==> old(proposal).for_votes == proposal.for_votes;
-
- - - -
- - - -## Function `change_vote` - -Let user change their vote during the voting time. - - -
public fun change_vote<TokenT: copy, drop, store, ActionT: copy, drop, store>(signer: &signer, proposer_address: address, proposal_id: u64, agree: bool)
-
- - - -
-Implementation - - -
public fun change_vote<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    signer: &signer,
-    proposer_address: address,
-    proposal_id: u64,
-    agree: bool,
-) acquires Proposal, DaoGlobalInfo, Vote {
-    {
-        let state = proposal_state<TokenT, ActionT>(proposer_address, proposal_id);
-        // only when proposal is active, user can change vote.
-        assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    };
-    let proposal = borrow_global_mut<Proposal<TokenT, ActionT>>(proposer_address);
-    assert!(proposal.id == proposal_id, Errors::invalid_argument(ERR_PROPOSAL_ID_MISMATCH));
-    let my_vote = borrow_global_mut<Vote<TokenT>>(Signer::address_of(signer));
-    {
-        assert!(my_vote.proposer == proposer_address, Errors::invalid_argument(ERR_PROPOSER_MISMATCH));
-        assert!(my_vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY));
-    };
-
-    // flip the vote
-    if (my_vote.agree != agree) {
-        let total_voted = do_flip_vote(my_vote, proposal);
-        // emit event
-        let gov_info = borrow_global_mut<DaoGlobalInfo<TokenT>>(Token::token_address<TokenT>());
-        Event::emit_event(
-            &mut gov_info.vote_changed_event,
-            VoteChangedEvent {
-                proposal_id,
-                proposer: proposer_address,
-                voter: Signer::address_of(signer),
-                agree,
-                vote: total_voted,
-            },
-        );
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-let expected_states = vec(ACTIVE);
-include CheckProposalStates<TokenT, ActionT>{expected_states};
-let sender = Signer::address_of(signer);
-aborts_if !exists<Vote<TokenT>>(sender);
-let vote = global<Vote<TokenT>>(sender);
-include CheckVoteOnProposal<TokenT>{vote, proposer_address, proposal_id};
-include vote.agree != agree ==> CheckChangeVote<TokenT, ActionT>{vote, proposer_address};
-ensures vote.agree != agree ==> vote.agree == agree;
-
- - - -
- - - -## Function `do_flip_vote` - - - -
fun do_flip_vote<TokenT: copy, drop, store, ActionT: copy, drop, store>(my_vote: &mut Dao::Vote<TokenT>, proposal: &mut Dao::Proposal<TokenT, ActionT>): u128
-
- - - -
-Implementation - - -
fun do_flip_vote<TokenT: copy + drop + store, ActionT: copy + drop + store>(my_vote: &mut Vote<TokenT>, proposal: &mut Proposal<TokenT, ActionT>): u128 {
-    my_vote.agree = !my_vote.agree;
-    let total_voted = Token::value(&my_vote.stake);
-    if (my_vote.agree) {
-        proposal.for_votes = proposal.for_votes + total_voted;
-        proposal.against_votes = proposal.against_votes - total_voted;
-    } else {
-        proposal.for_votes = proposal.for_votes - total_voted;
-        proposal.against_votes = proposal.against_votes + total_voted;
-    };
-    total_voted
-}
-
- - - -
- -
-Specification - - - -
include CheckFlipVote<TokenT, ActionT>;
-ensures my_vote.agree == !old(my_vote).agree;
-
- - - -
- - - -## Function `revoke_vote` - -Revoke some voting powers from vote on proposal_id of proposer_address. - - -
public fun revoke_vote<TokenT: copy, drop, store, ActionT: copy, drop, store>(signer: &signer, proposer_address: address, proposal_id: u64, voting_power: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun revoke_vote<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    signer: &signer,
-    proposer_address: address,
-    proposal_id: u64,
-    voting_power: u128,
-): Token::Token<TokenT> acquires Proposal, Vote, DaoGlobalInfo {
-    {
-        let state = proposal_state<TokenT, ActionT>(proposer_address, proposal_id);
-        // only when proposal is active, user can revoke vote.
-        assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    };
-    // get proposal
-    let proposal = borrow_global_mut<Proposal<TokenT, ActionT>>(proposer_address);
-
-    // get vote
-    let my_vote = move_from<Vote<TokenT>>(Signer::address_of(signer));
-    {
-        assert!(my_vote.proposer == proposer_address, Errors::invalid_argument(ERR_PROPOSER_MISMATCH));
-        assert!(my_vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY));
-    };
-    // revoke vote on proposal
-    let reverted_stake =do_revoke_vote(proposal, &mut my_vote, voting_power);
-    // emit vote changed event
-    let gov_info = borrow_global_mut<DaoGlobalInfo<TokenT>>(Token::token_address<TokenT>());
-    Event::emit_event(
-        &mut gov_info.vote_changed_event,
-        VoteChangedEvent {
-            proposal_id,
-            proposer: proposer_address,
-            voter: Signer::address_of(signer),
-            agree: my_vote.agree,
-            vote: Token::value(&my_vote.stake),
-        },
-    );
-
-    // if user has no stake, destroy his vote. resolve https://github.com/starcoinorg/starcoin/issues/2925.
-    if (Token::value(&my_vote.stake) == 0u128) {
-        let Vote {stake, proposer: _, id: _, agree: _} = my_vote;
-        Token::destroy_zero(stake);
-    } else {
-        move_to(signer, my_vote);
-    };
-
-    reverted_stake
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-include AbortIfDaoInfoNotExist<TokenT>;
-let expected_states = vec(ACTIVE);
-include CheckProposalStates<TokenT, ActionT> {expected_states};
-let sender = Signer::address_of(signer);
-aborts_if !exists<Vote<TokenT>>(sender);
-let vote = global<Vote<TokenT>>(sender);
-include CheckVoteOnProposal<TokenT> {vote, proposer_address, proposal_id};
-include CheckRevokeVote<TokenT, ActionT> {
-    vote,
-    proposal: global<Proposal<TokenT, ActionT>>(proposer_address),
-    to_revoke: voting_power,
-};
-modifies global<Vote<TokenT>>(sender);
-modifies global<Proposal<TokenT, ActionT>>(proposer_address);
-modifies global<DaoGlobalInfo<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-ensures global<Vote<TokenT>>(sender).stake.value + result.value == old(global<Vote<TokenT>>(sender)).stake.value;
-ensures result.value == voting_power;
-
- - - -
- - - -## Function `do_revoke_vote` - - - -
fun do_revoke_vote<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposal: &mut Dao::Proposal<TokenT, ActionT>, vote: &mut Dao::Vote<TokenT>, to_revoke: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
fun do_revoke_vote<TokenT: copy + drop + store, ActionT: copy + drop + store>(proposal: &mut Proposal<TokenT, ActionT>, vote: &mut Vote<TokenT>, to_revoke: u128): Token::Token<TokenT> {
-    spec {
-        assume vote.stake.value >= to_revoke;
-    };
-    let reverted_stake = Token::withdraw(&mut vote.stake, to_revoke);
-    if (vote.agree) {
-        proposal.for_votes = proposal.for_votes - to_revoke;
-    } else {
-        proposal.against_votes = proposal.against_votes - to_revoke;
-    };
-    spec {
-        assert Token::value(reverted_stake) == to_revoke;
-    };
-    reverted_stake
-}
-
- - - -
- -
-Specification - - - -
include CheckRevokeVote<TokenT, ActionT>;
-ensures vote.agree ==> old(proposal).for_votes == proposal.for_votes + to_revoke;
-ensures !vote.agree ==> old(proposal).against_votes == proposal.against_votes + to_revoke;
-ensures result.value == to_revoke;
-
- - - -
- - - -## Function `unstake_votes` - -Retrieve back my staked token voted for a proposal. - - -
public fun unstake_votes<TokenT: copy, drop, store, ActionT: copy, drop, store>(signer: &signer, proposer_address: address, proposal_id: u64): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun unstake_votes<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    signer: &signer,
-    proposer_address: address,
-    proposal_id: u64,
-): Token::Token<TokenT> acquires Proposal, Vote {
-    // only check state when proposal exists.
-    // because proposal can be destroyed after it ends in DEFEATED or EXTRACTED state.
-    if (proposal_exists<TokenT, ActionT>(proposer_address, proposal_id)) {
-        let state = proposal_state<TokenT, ActionT>(proposer_address, proposal_id);
-        // Only after vote period end, user can unstake his votes.
-        assert!(state > ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID));
-    };
-    let Vote { proposer, id, stake, agree: _ } = move_from<Vote<TokenT>>(
-        Signer::address_of(signer),
-    );
-    // these checks are still required.
-    assert!(proposer == proposer_address, Errors::requires_address(ERR_PROPOSER_MISMATCH));
-    assert!(id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY));
-    stake
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-let expected_states = vec(DEFEATED);
-let expected_states1 = concat(expected_states,vec(AGREED));
-let expected_states2 = concat(expected_states1,vec(QUEUED));
-let expected_states3 = concat(expected_states2,vec(EXECUTABLE));
-let expected_states4 = concat(expected_states3,vec(EXTRACTED));
-aborts_if expected_states4[0] != DEFEATED;
-aborts_if expected_states4[1] != AGREED;
-aborts_if expected_states4[2] != QUEUED;
-aborts_if expected_states4[3] != EXECUTABLE;
-aborts_if expected_states4[4] != EXTRACTED;
-include spec_proposal_exists<TokenT, ActionT>(proposer_address, proposal_id) ==>
-            CheckProposalStates<TokenT, ActionT>{expected_states: expected_states4};
-let sender = Signer::address_of(signer);
-aborts_if !exists<Vote<TokenT>>(sender);
-let vote = global<Vote<TokenT>>(sender);
-include CheckVoteOnProposal<TokenT>{vote, proposer_address, proposal_id};
-ensures !exists<Vote<TokenT>>(sender);
-ensures result.value == old(vote).stake.value;
-
- - - -
- - - -## Function `queue_proposal_action` - -queue agreed proposal to execute. - - -
public(script) fun queue_proposal_action<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun queue_proposal_action<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-) acquires Proposal {
-    // Only agreed proposal can be submitted.
-    assert!(
-        proposal_state<TokenT, ActionT>(proposer_address, proposal_id) == AGREED,
-        Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)
-    );
-    let proposal = borrow_global_mut<Proposal<TokenT, ActionT>>(proposer_address);
-    proposal.eta = Timestamp::now_milliseconds() + proposal.action_delay;
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-let expected_states = vec(AGREED);
-include CheckProposalStates<TokenT, ActionT>{expected_states};
-let proposal = global<Proposal<TokenT, ActionT>>(proposer_address);
-aborts_if Timestamp::spec_now_millseconds() + proposal.action_delay > MAX_U64;
-ensures proposal.eta >= Timestamp::spec_now_millseconds();
-
- - - -
- - - -## Function `extract_proposal_action` - -extract proposal action to execute. - - -
public fun extract_proposal_action<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposer_address: address, proposal_id: u64): ActionT
-
- - - -
-Implementation - - -
public fun extract_proposal_action<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-): ActionT acquires Proposal {
-    // Only executable proposal's action can be extracted.
-    assert!(
-        proposal_state<TokenT, ActionT>(proposer_address, proposal_id) == EXECUTABLE,
-        Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID),
-    );
-    let proposal = borrow_global_mut<Proposal<TokenT, ActionT>>(proposer_address);
-    let action: ActionT = Option::extract(&mut proposal.action);
-    action
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-let expected_states = vec(EXECUTABLE);
-include CheckProposalStates<TokenT, ActionT>{expected_states};
-modifies global<Proposal<TokenT, ActionT>>(proposer_address);
-ensures Option::is_none(global<Proposal<TokenT, ActionT>>(proposer_address).action);
-
- - - -
- - - -## Function `destroy_terminated_proposal` - -remove terminated proposal from proposer - - -
public(script) fun destroy_terminated_proposal<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun destroy_terminated_proposal<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-) acquires Proposal {
-    let proposal_state = proposal_state<TokenT, ActionT>(proposer_address, proposal_id);
-    assert!(
-        proposal_state == DEFEATED || proposal_state == EXTRACTED,
-        Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID),
-    );
-    let Proposal {
-        id: _,
-        proposer: _,
-        start_time: _,
-        end_time: _,
-        for_votes: _,
-        against_votes: _,
-        eta: _,
-        action_delay: _,
-        quorum_votes: _,
-        action,
-    } = move_from<Proposal<TokenT, ActionT>>(proposer_address);
-    if (proposal_state == DEFEATED) {
-        let _ = Option::extract(&mut action);
-    };
-    Option::destroy_none(action);
-}
-
- - - -
- -
-Specification - - - -
let expected_states = concat(vec(DEFEATED), vec(EXTRACTED));
-aborts_if len(expected_states) != 2;
-aborts_if expected_states[0] != DEFEATED;
-aborts_if expected_states[1] != EXTRACTED;
-aborts_if !exists<Proposal<TokenT, ActionT>>(proposer_address);
-let proposal = global<Proposal<TokenT, ActionT>>(proposer_address);
-aborts_if proposal.id != proposal_id;
-include AbortIfTimestampNotExist;
-let current_time = Timestamp::spec_now_millseconds();
-let state = do_proposal_state(proposal, current_time);
-aborts_if (forall s in expected_states : s != state);
-aborts_if state == DEFEATED && Option::is_none(global<Proposal<TokenT, ActionT>>(proposer_address).action);
-aborts_if state == EXTRACTED && Option::is_some(global<Proposal<TokenT, ActionT>>(proposer_address).action);
-modifies global<Proposal<TokenT, ActionT>>(proposer_address);
-
- - - -
- - - -## Function `proposal_exists` - -check whether a proposal exists in proposer_address with id proposal_id. - - -
public fun proposal_exists<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposer_address: address, proposal_id: u64): bool
-
- - - -
-Implementation - - -
public fun proposal_exists<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-): bool acquires Proposal {
-    if (exists<Proposal<TokenT, ActionT>>(proposer_address)) {
-        let proposal = borrow_global<Proposal<TokenT, ActionT>>(proposer_address);
-        return proposal.id == proposal_id
-    };
-    false
-}
-
- - - -
- -
-Specification - - - -
ensures exists<Proposal<TokenT, ActionT>>(proposer_address) &&
-            borrow_global<Proposal<TokenT, ActionT>>(proposer_address).id == proposal_id ==>
-            result;
-
- - - - - - - -
fun spec_proposal_exists<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-   proposer_address: address,
-   proposal_id: u64,
-): bool {
-   if (exists<Proposal<TokenT, ActionT>>(proposer_address)) {
-       let proposal = global<Proposal<TokenT, ActionT>>(proposer_address);
-       proposal.id == proposal_id
-   } else {
-       false
-   }
-}
-
- - - -
- - - -## Function `proposal_state` - -Get the proposal state. - - -
public fun proposal_state<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposer_address: address, proposal_id: u64): u8
-
- - - -
-Implementation - - -
public fun proposal_state<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-): u8 acquires Proposal {
-    let proposal = borrow_global<Proposal<TokenT, ActionT>>(proposer_address);
-    assert!(proposal.id == proposal_id, Errors::invalid_argument(ERR_PROPOSAL_ID_MISMATCH));
-    let current_time = Timestamp::now_milliseconds();
-    do_proposal_state(proposal, current_time)
-}
-
- - - -
- -
-Specification - - - -
include AbortIfTimestampNotExist;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if !exists<Proposal<TokenT, ActionT>>(proposer_address);
-let proposal = global<Proposal<TokenT, ActionT>>(proposer_address);
-aborts_if proposal.id != proposal_id;
-
- - - -
- - - -## Function `do_proposal_state` - - - -
fun do_proposal_state<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposal: &Dao::Proposal<TokenT, ActionT>, current_time: u64): u8
-
- - - -
-Implementation - - -
fun do_proposal_state<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    proposal: &Proposal<TokenT, ActionT>,
-    current_time: u64,
-): u8 {
-    if (current_time < proposal.start_time) {
-        // Pending
-        PENDING
-    } else if (current_time <= proposal.end_time) {
-        // Active
-        ACTIVE
-    } else if (proposal.for_votes <= proposal.against_votes ||
-        proposal.for_votes < proposal.quorum_votes) {
-        // Defeated
-        DEFEATED
-    } else if (proposal.eta == 0) {
-        // Agreed.
-        AGREED
-    } else if (current_time < proposal.eta) {
-        // Queued, waiting to execute
-        QUEUED
-    } else if (Option::is_some(&proposal.action)) {
-        EXECUTABLE
-    } else {
-        EXTRACTED
-    }
-}
-
- - - -
- - - -## Function `proposal_info` - -get proposal's information. -return: (id, start_time, end_time, for_votes, against_votes). - - -
public fun proposal_info<TokenT: copy, drop, store, ActionT: copy, drop, store>(proposer_address: address): (u64, u64, u64, u128, u128)
-
- - - -
-Implementation - - -
public fun proposal_info<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    proposer_address: address,
-): (u64, u64, u64, u128, u128) acquires Proposal {
-    let proposal = borrow_global<Proposal<TokenT, ActionT>>(proposer_address);
-    (proposal.id, proposal.start_time, proposal.end_time, proposal.for_votes, proposal.against_votes)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Proposal<TokenT, ActionT>>(proposer_address);
-
- - - -
- - - -## Function `vote_of` - -Get voter's vote info on proposal with proposal_id of proposer_address. - - -
public fun vote_of<TokenT: copy, drop, store>(voter: address, proposer_address: address, proposal_id: u64): (bool, u128)
-
- - - -
-Implementation - - -
public fun vote_of<TokenT: copy + drop + store>(
-    voter: address,
-    proposer_address: address,
-    proposal_id: u64,
-): (bool, u128) acquires Vote {
-    let vote = borrow_global<Vote<TokenT>>(voter);
-    assert!(vote.proposer == proposer_address, Errors::requires_address(ERR_PROPOSER_MISMATCH));
-    assert!(vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY));
-    (vote.agree, Token::value(&vote.stake))
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Vote<TokenT>>(voter);
-let vote = global<Vote<TokenT>>(voter);
-include CheckVoteOnProposal<TokenT>{vote, proposer_address, proposal_id};
-
- - - -
- - - -## Function `has_vote` - -Check whether voter has voted on proposal with proposal_id of proposer_address. - - -
public fun has_vote<TokenT: copy, drop, store>(voter: address, proposer_address: address, proposal_id: u64): bool
-
- - - -
-Implementation - - -
public fun has_vote<TokenT: copy + drop + store>(
-    voter: address,
-    proposer_address: address,
-    proposal_id: u64,
-): bool acquires Vote {
-    if (!exists<Vote<TokenT>>(voter)) {
-        return false
-    };
-
-    let vote = borrow_global<Vote<TokenT>>(voter);
-    vote.proposer == proposer_address && vote.id == proposal_id
-}
-
- - - -
- - - -## Function `generate_next_proposal_id` - - - -
fun generate_next_proposal_id<TokenT: store>(): u64
-
- - - -
-Implementation - - -
fun generate_next_proposal_id<TokenT: store>(): u64 acquires DaoGlobalInfo {
-    let gov_info = borrow_global_mut<DaoGlobalInfo<TokenT>>(Token::token_address<TokenT>());
-    let proposal_id = gov_info.next_proposal_id;
-    gov_info.next_proposal_id = proposal_id + 1;
-    proposal_id
-}
-
- - - -
- -
-Specification - - - -
include GenerateNextProposalIdSchema<TokenT>;
-ensures result == old(global<DaoGlobalInfo<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id);
-
- - - - - - - -
schema GenerateNextProposalIdSchema<TokenT> {
-    aborts_if global<DaoGlobalInfo<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id >= MAX_U64;
-    modifies global<DaoGlobalInfo<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-    ensures
-        global<DaoGlobalInfo<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id ==
-        old(global<DaoGlobalInfo<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id) + 1;
-}
-
- - - -
- - - -## Function `voting_delay` - -get default voting delay of the DAO. - - -
public fun voting_delay<TokenT: copy, drop, store>(): u64
-
- - - -
-Implementation - - -
public fun voting_delay<TokenT: copy + drop + store>(): u64 {
-    get_config<TokenT>().voting_delay
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `voting_period` - -get the default voting period of the DAO. - - -
public fun voting_period<TokenT: copy, drop, store>(): u64
-
- - - -
-Implementation - - -
public fun voting_period<TokenT: copy + drop + store>(): u64 {
-    get_config<TokenT>().voting_period
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `quorum_votes` - -Quorum votes to make proposal pass. - - -
public fun quorum_votes<TokenT: copy, drop, store>(): u128
-
- - - -
-Implementation - - -
public fun quorum_votes<TokenT: copy + drop + store>(): u128 {
-    let market_cap = Token::market_cap<TokenT>();
-    let balance_in_treasury = Treasury::balance<TokenT>();
-    let supply = market_cap - balance_in_treasury;
-    let rate = voting_quorum_rate<TokenT>();
-    let rate = (rate as u128);
-    supply * rate / 100
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-include CheckQuorumVotes<TokenT>;
-
- - - - - - - -
fun spec_quorum_votes<TokenT: copy + drop + store>(): u128 {
-   let supply = Token::spec_abstract_total_value<TokenT>() - Treasury::spec_balance<TokenT>();
-   supply * spec_dao_config<TokenT>().voting_quorum_rate / 100
-}
-
- - - -
- - - -## Function `voting_quorum_rate` - -Get the quorum rate in percent. - - -
public fun voting_quorum_rate<TokenT: copy, drop, store>(): u8
-
- - - -
-Implementation - - -
public fun voting_quorum_rate<TokenT: copy + drop + store>(): u8 {
-    get_config<TokenT>().voting_quorum_rate
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == global<Config::Config<DaoConfig<TokenT>>>((Token::SPEC_TOKEN_TEST_ADDRESS())).payload.voting_quorum_rate;
-
- - - -
- - - -## Function `min_action_delay` - -Get the min_action_delay of the DAO. - - -
public fun min_action_delay<TokenT: copy, drop, store>(): u64
-
- - - -
-Implementation - - -
public fun min_action_delay<TokenT: copy + drop + store>(): u64 {
-    get_config<TokenT>().min_action_delay
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == spec_dao_config<TokenT>().min_action_delay;
-
- - - -
- - - -## Function `get_config` - - - -
fun get_config<TokenT: copy, drop, store>(): Dao::DaoConfig<TokenT>
-
- - - -
-Implementation - - -
fun get_config<TokenT: copy + drop + store>(): DaoConfig<TokenT> {
-    let token_issuer = Token::token_address<TokenT>();
-    Config::get_by_address<DaoConfig<TokenT>>(token_issuer)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == global<Config::Config<DaoConfig<TokenT>>>(Token::SPEC_TOKEN_TEST_ADDRESS()).payload;
-
- - - - - - - -
fun spec_dao_config<TokenT: copy + drop + store>(): DaoConfig<TokenT> {
-   global<Config::Config<DaoConfig<TokenT>>>((Token::SPEC_TOKEN_TEST_ADDRESS())).payload
-}
-
- - - - - - - -
schema CheckModifyConfigWithCap<TokenT> {
-    cap: Config::ModifyConfigCapability<DaoConfig<TokenT>>;
-    aborts_if cap.account_address != Token::SPEC_TOKEN_TEST_ADDRESS();
-    aborts_if !exists<Config::Config<DaoConfig<TokenT>>>(cap.account_address);
-}
-
- - - -
- - - -## Function `modify_dao_config` - -update function, modify dao config. -if any param is 0, it means no change to that param. - - -
public fun modify_dao_config<TokenT: copy, drop, store>(cap: &mut Config::ModifyConfigCapability<Dao::DaoConfig<TokenT>>, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64)
-
- - - -
-Implementation - - -
public fun modify_dao_config<TokenT: copy + drop + store>(
-    cap: &mut Config::ModifyConfigCapability<DaoConfig<TokenT>>,
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-) {
-    assert!(Config::account_address(cap) == Token::token_address<TokenT>(), Errors::invalid_argument(ERR_NOT_AUTHORIZED));
-    let config = get_config<TokenT>();
-    if (voting_period > 0) {
-        config.voting_period = voting_period;
-    };
-    if (voting_delay > 0) {
-        config.voting_delay = voting_delay;
-    };
-    if (voting_quorum_rate > 0) {
-        assert!(voting_quorum_rate <= 100, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID));
-        config.voting_quorum_rate = voting_quorum_rate;
-    };
-    if (min_action_delay > 0) {
-        config.min_action_delay = min_action_delay;
-    };
-    Config::set_with_capability<DaoConfig<TokenT>>(cap, config);
-}
-
- - - -
- -
-Specification - - - -
include CheckModifyConfigWithCap<TokenT>;
-aborts_if voting_quorum_rate > 0 && voting_quorum_rate > 100;
-
- - - -
- - - -## Function `set_voting_delay` - -set voting delay - - -
public fun set_voting_delay<TokenT: copy, drop, store>(cap: &mut Config::ModifyConfigCapability<Dao::DaoConfig<TokenT>>, value: u64)
-
- - - -
-Implementation - - -
public fun set_voting_delay<TokenT: copy + drop + store>(
-    cap: &mut Config::ModifyConfigCapability<DaoConfig<TokenT>>,
-    value: u64,
-) {
-    assert!(Config::account_address(cap) == Token::token_address<TokenT>(), Errors::invalid_argument(ERR_NOT_AUTHORIZED));
-    assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    let config = get_config<TokenT>();
-    config.voting_delay = value;
-    Config::set_with_capability<DaoConfig<TokenT>>(cap, config);
-}
-
- - - -
- -
-Specification - - - -
include CheckModifyConfigWithCap<TokenT>;
-aborts_if value == 0;
-
- - - -
- - - -## Function `set_voting_period` - -set voting period - - -
public fun set_voting_period<TokenT: copy, drop, store>(cap: &mut Config::ModifyConfigCapability<Dao::DaoConfig<TokenT>>, value: u64)
-
- - - -
-Implementation - - -
public fun set_voting_period<TokenT: copy + drop + store>(
-    cap: &mut Config::ModifyConfigCapability<DaoConfig<TokenT>>,
-    value: u64,
-) {
-    assert!(Config::account_address(cap) == Token::token_address<TokenT>(), Errors::invalid_argument(ERR_NOT_AUTHORIZED));
-    assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    let config = get_config<TokenT>();
-    config.voting_period = value;
-    Config::set_with_capability<DaoConfig<TokenT>>(cap, config);
-}
-
- - - -
- -
-Specification - - - -
include CheckModifyConfigWithCap<TokenT>;
-aborts_if value == 0;
-
- - - -
- - - -## Function `set_voting_quorum_rate` - -set voting quorum rate - - -
public fun set_voting_quorum_rate<TokenT: copy, drop, store>(cap: &mut Config::ModifyConfigCapability<Dao::DaoConfig<TokenT>>, value: u8)
-
- - - -
-Implementation - - -
public fun set_voting_quorum_rate<TokenT: copy + drop + store>(
-    cap: &mut Config::ModifyConfigCapability<DaoConfig<TokenT>>,
-    value: u8,
-) {
-    assert!(Config::account_address(cap) == Token::token_address<TokenT>(), Errors::invalid_argument(ERR_NOT_AUTHORIZED));
-    assert!(value <= 100 && value > 0, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID));
-    let config = get_config<TokenT>();
-    config.voting_quorum_rate = value;
-    Config::set_with_capability<DaoConfig<TokenT>>(cap, config);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !(value > 0 && value <= 100);
-include CheckModifyConfigWithCap<TokenT>;
-
- - - -
- - - -## Function `set_min_action_delay` - -set min action delay - - -
public fun set_min_action_delay<TokenT: copy, drop, store>(cap: &mut Config::ModifyConfigCapability<Dao::DaoConfig<TokenT>>, value: u64)
-
- - - -
-Implementation - - -
public fun set_min_action_delay<TokenT: copy + drop + store>(
-    cap: &mut Config::ModifyConfigCapability<DaoConfig<TokenT>>,
-    value: u64,
-) {
-    assert!(Config::account_address(cap) == Token::token_address<TokenT>(), Errors::invalid_argument(ERR_NOT_AUTHORIZED));
-    assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID));
-    let config = get_config<TokenT>();
-    config.min_action_delay = value;
-    Config::set_with_capability<DaoConfig<TokenT>>(cap, config);
-}
-
- - - -
- -
-Specification - - - -
aborts_if value == 0;
-include CheckModifyConfigWithCap<TokenT>;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/DaoVoteScripts.md b/release/v12/docs/DaoVoteScripts.md deleted file mode 100644 index 7c79ae3c..00000000 --- a/release/v12/docs/DaoVoteScripts.md +++ /dev/null @@ -1,197 +0,0 @@ - - - -# Module `0x1::DaoVoteScripts` - - - -- [Function `cast_vote`](#0x1_DaoVoteScripts_cast_vote) -- [Function `revoke_vote`](#0x1_DaoVoteScripts_revoke_vote) -- [Function `flip_vote`](#0x1_DaoVoteScripts_flip_vote) -- [Function `revoke_vote_of_power`](#0x1_DaoVoteScripts_revoke_vote_of_power) -- [Function `unstake_vote`](#0x1_DaoVoteScripts_unstake_vote) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::Account;
-use 0x1::Dao;
-use 0x1::Signer;
-use 0x1::Token;
-
- - - - - -## Function `cast_vote` - - - -
public(script) fun cast_vote<Token: copy, drop, store, ActionT: copy, drop, store>(signer: signer, proposer_address: address, proposal_id: u64, agree: bool, votes: u128)
-
- - - -
-Implementation - - -
public ( script ) fun cast_vote<Token: copy + drop + store, ActionT: copy + drop + store>(
-    signer: signer,
-    proposer_address: address,
-    proposal_id: u64,
-    agree: bool,
-    votes: u128,
-) {
-    let sender = Signer::address_of(&signer);
-    if (Dao::has_vote<Token>(sender, proposer_address, proposal_id)) {
-        // if already voted, and vote is not same as the current cast, change the existing vote.
-        // resolve https://github.com/starcoinorg/starcoin/issues/2925.
-        let (agree_voted, _) = Dao::vote_of<Token>(sender, proposer_address, proposal_id);
-        if (agree_voted != agree) {
-            Dao::change_vote<Token, ActionT>(&signer, proposer_address, proposal_id, agree);
-        }
-    };
-
-    let votes = Account::withdraw<Token>(&signer, votes);
-    Dao::cast_vote<Token, ActionT>(&signer, proposer_address, proposal_id, votes, agree);
-}
-
- - - -
- - - -## Function `revoke_vote` - -revoke all votes on a proposal - - -
public(script) fun revoke_vote<Token: copy, drop, store, Action: copy, drop, store>(signer: signer, proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public ( script ) fun revoke_vote<Token: copy + drop + store, Action: copy + drop + store>(
-    signer: signer,
-    proposer_address: address,
-    proposal_id: u64,
-) {
-    let sender = Signer::address_of(&signer);
-    let (_, power) = Dao::vote_of<Token>(sender, proposer_address, proposal_id);
-    let my_token = Dao::revoke_vote<Token, Action>(&signer, proposer_address, proposal_id, power);
-    Account::deposit(sender, my_token);
-}
-
- - - -
- - - -## Function `flip_vote` - -Let user change their vote during the voting time. - - -
public(script) fun flip_vote<TokenT: copy, drop, store, ActionT: copy, drop, store>(signer: signer, proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun flip_vote<TokenT: copy + drop + store, ActionT: copy + drop + store>(
-    signer: signer,
-    proposer_address: address,
-    proposal_id: u64,
-) {
-    let (agree, _) = Dao::vote_of<TokenT>(Signer::address_of(&signer), proposer_address, proposal_id);
-    Dao::change_vote<TokenT, ActionT>(&signer, proposer_address, proposal_id, !agree);
-}
-
- - - -
- - - -## Function `revoke_vote_of_power` - -revoke some votes on a proposal - - -
public(script) fun revoke_vote_of_power<Token: copy, drop, store, Action: copy, drop, store>(signer: signer, proposer_address: address, proposal_id: u64, power: u128)
-
- - - -
-Implementation - - -
public ( script ) fun revoke_vote_of_power<Token: copy + drop + store, Action: copy + drop + store>(
-    signer: signer,
-    proposer_address: address,
-    proposal_id: u64,
-    power: u128,
-) {
-    let sender = Signer::address_of(&signer);
-    let my_token = Dao::revoke_vote<Token, Action>(&signer, proposer_address, proposal_id, power);
-    Account::deposit(sender, my_token);
-}
-
- - - -
- - - -## Function `unstake_vote` - - - -
public(script) fun unstake_vote<Token: copy, drop, store, Action: copy, drop, store>(signer: signer, proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public ( script ) fun unstake_vote<Token: copy + drop + store, Action: copy + drop + store>(
-    signer: signer,
-    proposer_address: address,
-    proposal_id: u64,
-) {
-    let my_token = Dao::unstake_votes<Token, Action>(&signer, proposer_address, proposal_id);
-    Account::deposit(Signer::address_of(&signer), my_token);
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_partial = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/Debug.md b/release/v12/docs/Debug.md deleted file mode 100644 index 9d714ba9..00000000 --- a/release/v12/docs/Debug.md +++ /dev/null @@ -1,72 +0,0 @@ - - - -# Module `0x1::Debug` - -The module provide debug print for Move. - - -- [Function `print`](#0x1_Debug_print) -- [Function `print_stack_trace`](#0x1_Debug_print_stack_trace) -- [Module Specification](#@Module_Specification_0) - - -
- - - - - -## Function `print` - -Print data of Type T. - - -
public fun print<T: store>(x: &T)
-
- - - -
-Implementation - - -
native public fun print<T: store>(x: &T);
-
- - - -
- - - -## Function `print_stack_trace` - -Print current stack. - - -
public fun print_stack_trace()
-
- - - -
-Implementation - - -
native public fun print_stack_trace();
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/DummyToken.md b/release/v12/docs/DummyToken.md deleted file mode 100644 index 3582759c..00000000 --- a/release/v12/docs/DummyToken.md +++ /dev/null @@ -1,46 +0,0 @@ - - - -# Module `0x1::DummyTokenScripts` - - - -- [Function `mint`](#0x1_DummyTokenScripts_mint) - - -
use 0x1::Account;
-use 0x1::DummyToken;
-use 0x1::Signer;
-use 0x1::Token;
-
- - - - - -## Function `mint` - - - -
public(script) fun mint(sender: signer, amount: u128)
-
- - - -
-Implementation - - -
public(script) fun mint(sender: signer, amount: u128){
-    let token = DummyToken::mint(&sender, amount);
-    let sender_addr = Signer::address_of(&sender);
-    if(Account::is_accept_token<DummyToken>(sender_addr)){
-        Account::do_accept_token<DummyToken>(&sender);
-    };
-    Account::deposit(sender_addr, token);
-}
-
- - - -
diff --git a/release/v12/docs/EmptyScripts.md b/release/v12/docs/EmptyScripts.md deleted file mode 100644 index 0ea89aca..00000000 --- a/release/v12/docs/EmptyScripts.md +++ /dev/null @@ -1,48 +0,0 @@ - - - -# Module `0x1::EmptyScripts` - - - -- [Function `empty_script`](#0x1_EmptyScripts_empty_script) -- [Module Specification](#@Module_Specification_0) - - -
- - - - - -## Function `empty_script` - - - -
public(script) fun empty_script()
-
- - - -
-Implementation - - -
public(script) fun empty_script() {
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_partial = false;
-pragma aborts_if_is_strict = false;
-
diff --git a/release/v12/docs/Epoch.md b/release/v12/docs/Epoch.md deleted file mode 100644 index 17ac2e3c..00000000 --- a/release/v12/docs/Epoch.md +++ /dev/null @@ -1,1041 +0,0 @@ - - - -# Module `0x1::Epoch` - -The module provide epoch functionality for starcoin. - - -- [Resource `Epoch`](#0x1_Epoch_Epoch) -- [Struct `NewEpochEvent`](#0x1_Epoch_NewEpochEvent) -- [Resource `EpochData`](#0x1_Epoch_EpochData) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_Epoch_initialize) -- [Function `compute_next_block_time_target`](#0x1_Epoch_compute_next_block_time_target) -- [Function `adjust_epoch`](#0x1_Epoch_adjust_epoch) -- [Function `adjust_gas_limit`](#0x1_Epoch_adjust_gas_limit) -- [Function `compute_gas_limit`](#0x1_Epoch_compute_gas_limit) -- [Function `in_or_decrease_gas_limit`](#0x1_Epoch_in_or_decrease_gas_limit) -- [Function `update_epoch_data`](#0x1_Epoch_update_epoch_data) -- [Function `emit_epoch_event`](#0x1_Epoch_emit_epoch_event) -- [Function `start_time`](#0x1_Epoch_start_time) -- [Function `uncles`](#0x1_Epoch_uncles) -- [Function `total_gas`](#0x1_Epoch_total_gas) -- [Function `block_gas_limit`](#0x1_Epoch_block_gas_limit) -- [Function `start_block_number`](#0x1_Epoch_start_block_number) -- [Function `end_block_number`](#0x1_Epoch_end_block_number) -- [Function `number`](#0x1_Epoch_number) -- [Function `block_time_target`](#0x1_Epoch_block_time_target) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::ConsensusConfig;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Math;
-use 0x1::Option;
-use 0x1::Timestamp;
-
- - - - - -## Resource `Epoch` - -Current epoch info. - - -
struct Epoch has key
-
- - - -
-Fields - - -
-
-number: u64 -
-
- Number of current epoch -
-
-start_time: u64 -
-
- Start time of current epoch -
-
-start_block_number: u64 -
-
- Start block's number of current epoch -
-
-end_block_number: u64 -
-
- End block's number of current epoch -
-
-block_time_target: u64 -
-
- Average target time to calculate a block's difficulty in current epoch -
-
-reward_per_block: u128 -
-
- Rewards per block in current epoch -
-
-reward_per_uncle_percent: u64 -
-
- Percentage of reward_per_block to reward a uncle block in current epoch -
-
-block_difficulty_window: u64 -
-
- How many ancestor blocks which use to calculate next block's difficulty in current epoch -
-
-max_uncles_per_block: u64 -
-
- Maximum number of uncle block per block in current epoch -
-
-block_gas_limit: u64 -
-
- Maximum gases per block in current epoch -
-
-strategy: u8 -
-
- Strategy to calculate difficulty in current epoch -
-
-new_epoch_events: Event::EventHandle<Epoch::NewEpochEvent> -
-
- Switch Epoch Event -
-
- - -
- - - -## Struct `NewEpochEvent` - -New epoch event. - - -
struct NewEpochEvent has drop, store
-
- - - -
-Fields - - -
-
-number: u64 -
-
- Epoch::number -
-
-start_time: u64 -
-
- Epoch::start_time -
-
-start_block_number: u64 -
-
- Epoch::start_block_number -
-
-end_block_number: u64 -
-
- Epoch::end_block_number -
-
-block_time_target: u64 -
-
- Epoch::block_time_target -
-
-reward_per_block: u128 -
-
- Epoch::reward_per_block -
-
-previous_epoch_total_reward: u128 -
-
- Total rewards during previous epoch -
-
- - -
- - - -## Resource `EpochData` - -Epoch data. - - -
struct EpochData has key
-
- - - -
-Fields - - -
-
-uncles: u64 -
-
- Up to now, Number of uncle block during current epoch -
-
-total_reward: u128 -
-
- Up to now, Total rewards during current epoch -
-
-total_gas: u128 -
-
- Up to now, Total gases during current epoch -
-
- - -
- - - -## Constants - - - - - - -
const EINVALID_UNCLES_COUNT: u64 = 101;
-
- - - - - - - -
const EUNREACHABLE: u64 = 19;
-
- - - - - - - -
const HUNDRED: u64 = 100;
-
- - - - - - - -
const THOUSAND: u64 = 1000;
-
- - - - - - - -
const THOUSAND_U128: u128 = 1000;
-
- - - - - -## Function `initialize` - -Initialization of the module. - - -
public fun initialize(account: &signer)
-
- - - -
-Implementation - - -
public fun initialize(
-    account: &signer,
-) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-
-    let config = ConsensusConfig::get_config();
-    move_to<Epoch>(
-        account,
-        Epoch {
-            number: 0,
-            start_time: Timestamp::now_milliseconds(),
-            start_block_number: 0,
-            end_block_number: ConsensusConfig::epoch_block_count(&config),
-            block_time_target: ConsensusConfig::base_block_time_target(&config),
-            reward_per_block: ConsensusConfig::base_reward_per_block(&config),
-            reward_per_uncle_percent: ConsensusConfig::base_reward_per_uncle_percent(&config),
-            block_difficulty_window: ConsensusConfig::base_block_difficulty_window(&config),
-            max_uncles_per_block: ConsensusConfig::base_max_uncles_per_block(&config),
-            block_gas_limit: ConsensusConfig::base_block_gas_limit(&config),
-            strategy: ConsensusConfig::strategy(&config),
-            new_epoch_events: Event::new_event_handle<NewEpochEvent>(account),
-        },
-    );
-    move_to<EpochData>(account, EpochData { uncles: 0, total_reward: 0, total_gas: 0 });
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if !exists<Config::Config<ConsensusConfig>>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if exists<Epoch>(Signer::address_of(account));
-aborts_if exists<EpochData>(Signer::address_of(account));
-
- - - -
- - - -## Function `compute_next_block_time_target` - -compute next block time_target. - - -
public fun compute_next_block_time_target(config: &ConsensusConfig::ConsensusConfig, last_epoch_time_target: u64, epoch_start_time: u64, now_milli_second: u64, start_block_number: u64, end_block_number: u64, total_uncles: u64): u64
-
- - - -
-Implementation - - -
public fun compute_next_block_time_target(config: &ConsensusConfig, last_epoch_time_target: u64, epoch_start_time: u64, now_milli_second: u64, start_block_number: u64, end_block_number: u64, total_uncles: u64): u64 {
-    let total_time = now_milli_second - epoch_start_time;
-    let blocks = end_block_number - start_block_number;
-    let avg_block_time = total_time / blocks;
-    let uncles_rate = total_uncles * THOUSAND / blocks;
-    let new_epoch_block_time_target = (THOUSAND + uncles_rate) * avg_block_time /
-            (ConsensusConfig::uncle_rate_target(config) + THOUSAND);
-    if (new_epoch_block_time_target > last_epoch_time_target * 2) {
-        new_epoch_block_time_target = last_epoch_time_target * 2;
-    };
-    if (new_epoch_block_time_target < last_epoch_time_target / 2) {
-        new_epoch_block_time_target = last_epoch_time_target / 2;
-    };
-    let min_block_time_target = ConsensusConfig::min_block_time_target(config);
-    let max_block_time_target = ConsensusConfig::max_block_time_target(config);
-    if (new_epoch_block_time_target < min_block_time_target) {
-        new_epoch_block_time_target = min_block_time_target;
-    };
-    if (new_epoch_block_time_target > max_block_time_target) {
-        new_epoch_block_time_target = max_block_time_target;
-    };
-    new_epoch_block_time_target
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `adjust_epoch` - -adjust_epoch try to advance to next epoch if current epoch ends. - - -
public fun adjust_epoch(account: &signer, block_number: u64, timestamp: u64, uncles: u64, parent_gas_used: u64): u128
-
- - - -
-Implementation - - -
public fun adjust_epoch(account: &signer, block_number: u64, timestamp: u64, uncles: u64, parent_gas_used:u64): u128
-acquires Epoch, EpochData {
-    CoreAddresses::assert_genesis_address(account);
-
-    let epoch_ref = borrow_global_mut<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-    assert!(epoch_ref.max_uncles_per_block >= uncles, Errors::invalid_argument(EINVALID_UNCLES_COUNT));
-
-    let epoch_data = borrow_global_mut<EpochData>(CoreAddresses::GENESIS_ADDRESS());
-    let (new_epoch, reward_per_block) = if (block_number < epoch_ref.end_block_number) {
-        (false, epoch_ref.reward_per_block)
-    } else if (block_number == epoch_ref.end_block_number) {
-        //start a new epoch
-        assert!(uncles == 0, Errors::invalid_argument(EINVALID_UNCLES_COUNT));
-        // block time target unit is milli_seconds.
-        let now_milli_seconds = timestamp;
-
-        let config = ConsensusConfig::get_config();
-        let last_epoch_time_target = epoch_ref.block_time_target;
-        let new_epoch_block_time_target = compute_next_block_time_target(&config, last_epoch_time_target, epoch_ref.start_time, now_milli_seconds, epoch_ref.start_block_number, epoch_ref.end_block_number, epoch_data.uncles);
-        let new_reward_per_block = ConsensusConfig::do_compute_reward_per_block(&config, new_epoch_block_time_target);
-
-        //update epoch by adjust result or config, because ConsensusConfig may be updated.
-        epoch_ref.number = epoch_ref.number + 1;
-        epoch_ref.start_time = now_milli_seconds;
-        epoch_ref.start_block_number = block_number;
-        epoch_ref.end_block_number = block_number + ConsensusConfig::epoch_block_count(&config);
-        epoch_ref.block_time_target = new_epoch_block_time_target;
-        epoch_ref.reward_per_block = new_reward_per_block;
-        epoch_ref.reward_per_uncle_percent = ConsensusConfig::base_reward_per_uncle_percent(&config);
-        epoch_ref.block_difficulty_window = ConsensusConfig::base_block_difficulty_window(&config);
-        epoch_ref.max_uncles_per_block = ConsensusConfig::base_max_uncles_per_block(&config);
-        epoch_ref.strategy = ConsensusConfig::strategy(&config);
-
-        epoch_data.uncles = 0;
-        let last_epoch_total_gas = epoch_data.total_gas + (parent_gas_used as u128);
-        adjust_gas_limit(&config, epoch_ref, last_epoch_time_target, new_epoch_block_time_target, last_epoch_total_gas);
-        emit_epoch_event(epoch_ref, epoch_data.total_reward);
-        (true, new_reward_per_block)
-    } else {
-        //This should never happened.
-        abort EUNREACHABLE
-    };
-    let reward = reward_per_block +
-            reward_per_block * (epoch_ref.reward_per_uncle_percent as u128) * (uncles as u128) / (HUNDRED as u128);
-    update_epoch_data(epoch_data, new_epoch, reward, uncles, parent_gas_used);
-    reward
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Epoch>(Signer::address_of(account));
-aborts_if global<Epoch>(Signer::address_of(account)).max_uncles_per_block < uncles;
-aborts_if exists<EpochData>(Signer::address_of(account));
-aborts_if block_number == global<Epoch>(Signer::address_of(account)).end_block_number && uncles != 0;
-
- - - -
- - - -## Function `adjust_gas_limit` - - - -
fun adjust_gas_limit(config: &ConsensusConfig::ConsensusConfig, epoch_ref: &mut Epoch::Epoch, last_epoch_time_target: u64, new_epoch_time_target: u64, last_epoch_total_gas: u128)
-
- - - -
-Implementation - - -
fun adjust_gas_limit(config: &ConsensusConfig, epoch_ref: &mut Epoch, last_epoch_time_target: u64, new_epoch_time_target: u64, last_epoch_total_gas:u128) {
-    let new_gas_limit = compute_gas_limit(config, last_epoch_time_target, new_epoch_time_target, epoch_ref.block_gas_limit, last_epoch_total_gas);
-    if (Option::is_some(&new_gas_limit)) {
-        epoch_ref.block_gas_limit = Option::destroy_some(new_gas_limit);
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `compute_gas_limit` - -Compute block's gas limit of next epoch. - - -
public fun compute_gas_limit(config: &ConsensusConfig::ConsensusConfig, last_epoch_time_target: u64, new_epoch_time_target: u64, last_epoch_block_gas_limit: u64, last_epoch_total_gas: u128): Option::Option<u64>
-
- - - -
-Implementation - - -
public fun compute_gas_limit(config: &ConsensusConfig, last_epoch_time_target: u64, new_epoch_time_target: u64, last_epoch_block_gas_limit: u64, last_epoch_total_gas: u128) : Option::Option<u64> {
-    let epoch_block_count = (ConsensusConfig::epoch_block_count(config) as u128);
-    let gas_limit_threshold = (last_epoch_total_gas >= Math::mul_div((last_epoch_block_gas_limit as u128) * epoch_block_count, (80 as u128), (HUNDRED as u128)));
-    let new_gas_limit = Option::none<u64>();
-
-    let min_block_time_target = ConsensusConfig::min_block_time_target(config);
-    let max_block_time_target = ConsensusConfig::max_block_time_target(config);
-    let base_block_gas_limit =  ConsensusConfig::base_block_gas_limit(config);
-    if (last_epoch_time_target == new_epoch_time_target) {
-        if (new_epoch_time_target == min_block_time_target && gas_limit_threshold) {
-            let increase_gas_limit = in_or_decrease_gas_limit(last_epoch_block_gas_limit, 110, base_block_gas_limit);
-            new_gas_limit = Option::some(increase_gas_limit);
-        } else if (new_epoch_time_target == max_block_time_target && !gas_limit_threshold) {
-            let decrease_gas_limit = in_or_decrease_gas_limit(last_epoch_block_gas_limit, 90, base_block_gas_limit);
-            new_gas_limit = Option::some(decrease_gas_limit);
-        }
-    };
-
-    new_gas_limit
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `in_or_decrease_gas_limit` - - - -
fun in_or_decrease_gas_limit(last_epoch_block_gas_limit: u64, percent: u64, min_block_gas_limit: u64): u64
-
- - - -
-Implementation - - -
fun in_or_decrease_gas_limit(last_epoch_block_gas_limit: u64, percent: u64, min_block_gas_limit: u64): u64 {
-    let tmp_gas_limit = Math::mul_div((last_epoch_block_gas_limit as u128), (percent as u128), (HUNDRED as u128));
-    let new_gas_limit = if (tmp_gas_limit > (min_block_gas_limit  as u128)) {
-        (tmp_gas_limit as u64)
-    } else {
-        min_block_gas_limit
-    };
-
-    new_gas_limit
-}
-
- - - -
- -
-Specification - - - -
include Math::MulDivAbortsIf{x: last_epoch_block_gas_limit, y: percent, z: HUNDRED};
-aborts_if Math::spec_mul_div() > MAX_U64;
-
- - - -
- - - -## Function `update_epoch_data` - - - -
fun update_epoch_data(epoch_data: &mut Epoch::EpochData, new_epoch: bool, reward: u128, uncles: u64, parent_gas_used: u64)
-
- - - -
-Implementation - - -
fun update_epoch_data(epoch_data: &mut EpochData, new_epoch: bool, reward: u128, uncles: u64, parent_gas_used:u64) {
-    if (new_epoch) {
-        epoch_data.total_reward = reward;
-        epoch_data.uncles = uncles;
-        epoch_data.total_gas = 0;
-    } else {
-        epoch_data.total_reward = epoch_data.total_reward + reward;
-        epoch_data.uncles = epoch_data.uncles + uncles;
-        epoch_data.total_gas = epoch_data.total_gas + (parent_gas_used as u128);
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if !new_epoch && epoch_data.total_reward + reward > MAX_U128;
-aborts_if !new_epoch && epoch_data.uncles + uncles > MAX_U64;
-aborts_if !new_epoch && epoch_data.total_gas + parent_gas_used > MAX_U128;
-
- - - -
- - - -## Function `emit_epoch_event` - - - -
fun emit_epoch_event(epoch_ref: &mut Epoch::Epoch, previous_epoch_total_reward: u128)
-
- - - -
-Implementation - - -
fun emit_epoch_event(epoch_ref: &mut Epoch, previous_epoch_total_reward: u128) {
-    Event::emit_event(
-        &mut epoch_ref.new_epoch_events,
-        NewEpochEvent {
-            number: epoch_ref.number,
-            start_time: epoch_ref.start_time,
-            start_block_number: epoch_ref.start_block_number,
-            end_block_number: epoch_ref.end_block_number,
-            block_time_target: epoch_ref.block_time_target,
-            reward_per_block: epoch_ref.reward_per_block,
-            previous_epoch_total_reward,
-        },
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `start_time` - -Get start time of current epoch - - -
public fun start_time(): u64
-
- - - -
-Implementation - - -
public fun start_time(): u64 acquires Epoch {
-    let epoch_ref = borrow_global<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_ref.start_time
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `uncles` - -Get uncles number of current epoch - - -
public fun uncles(): u64
-
- - - -
-Implementation - - -
public fun uncles(): u64 acquires EpochData {
-    let epoch_data = borrow_global<EpochData>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_data.uncles
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<EpochData>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `total_gas` - -Get total gas of current epoch - - -
public fun total_gas(): u128
-
- - - -
-Implementation - - -
public fun total_gas(): u128 acquires EpochData {
-    let epoch_data = borrow_global<EpochData>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_data.total_gas
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<EpochData>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `block_gas_limit` - -Get block's gas_limit of current epoch - - -
public fun block_gas_limit(): u64
-
- - - -
-Implementation - - -
public fun block_gas_limit(): u64 acquires Epoch {
-    let epoch_ref = borrow_global<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_ref.block_gas_limit
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `start_block_number` - -Get start block's number of current epoch - - -
public fun start_block_number(): u64
-
- - - -
-Implementation - - -
public fun start_block_number(): u64 acquires Epoch {
-    let epoch_ref = borrow_global<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_ref.start_block_number
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `end_block_number` - -Get end block's number of current epoch - - -
public fun end_block_number(): u64
-
- - - -
-Implementation - - -
public fun end_block_number(): u64 acquires Epoch {
-    let epoch_ref = borrow_global<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_ref.end_block_number
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `number` - -Get current epoch number - - -
public fun number(): u64
-
- - - -
-Implementation - - -
public fun number(): u64 acquires Epoch {
-    let epoch_ref = borrow_global<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_ref.number
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `block_time_target` - -Get current block time target - - -
public fun block_time_target(): u64
-
- - - -
-Implementation - - -
public fun block_time_target(): u64 acquires Epoch {
-    let epoch_ref = borrow_global<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-    epoch_ref.block_time_target
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Epoch>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Errors.md b/release/v12/docs/Errors.md deleted file mode 100644 index 75b214eb..00000000 --- a/release/v12/docs/Errors.md +++ /dev/null @@ -1,623 +0,0 @@ - - - -# Module `0x1::Errors` - -Module defining error codes used in Move aborts throughout the framework. - -A u64 error code is constructed from two values: - -1. The *error category* which is encoded in the lower 8 bits of the code. Error categories are -declared in this module and are globally unique across the Diem framework. There is a limited -fixed set of predefined categories, and the framework is guaranteed to use those consistently. - -2. The *error reason* which is encoded in the remaining 56 bits of the code. The reason is a unique -number relative to the module which raised the error and can be used to obtain more information about -the error at hand. It is mostly used for diagnosis purposes. Error reasons may change over time as the -framework evolves. - -Rules to declare or use *error reason*: -1. error reason is declared as const in the user module -2. error reason name must start with "E", for example, const EACCOUNT_DOES_NOT_EXIST = ... -3. value less than 100 is reserved for general purpose and shared by all modules -4. don't change general purpose error reason value, it's co-related with error code in starcoin vm -5. self-defined error reason value must be large than 100 -6. error reason must be used together with error category - - -- [Constants](#@Constants_0) -- [Function `make`](#0x1_Errors_make) -- [Function `invalid_state`](#0x1_Errors_invalid_state) -- [Function `requires_address`](#0x1_Errors_requires_address) -- [Function `requires_role`](#0x1_Errors_requires_role) -- [Function `requires_capability`](#0x1_Errors_requires_capability) -- [Function `not_published`](#0x1_Errors_not_published) -- [Function `already_published`](#0x1_Errors_already_published) -- [Function `invalid_argument`](#0x1_Errors_invalid_argument) -- [Function `limit_exceeded`](#0x1_Errors_limit_exceeded) -- [Function `internal`](#0x1_Errors_internal) -- [Function `deprecated`](#0x1_Errors_deprecated) -- [Function `custom`](#0x1_Errors_custom) -- [Module Specification](#@Module_Specification_1) - - -
- - - - - -## Constants - - - - -Attempting to publish a resource that is already published. Example: calling an initialization function -twice. - - -
const ALREADY_PUBLISHED: u8 = 6;
-
- - - - - -A custom error category for extension points. - - -
const CUSTOM: u8 = 255;
-
- - - - - -deprecated code - - -
const DEPRECATED: u8 = 11;
-
- - - - - -An internal error (bug) has occurred. - - -
const INTERNAL: u8 = 10;
-
- - - - - -An argument provided to an operation is invalid. Example: a signing key has the wrong format. - - -
const INVALID_ARGUMENT: u8 = 7;
-
- - - - - -The system is in a state where the performed operation is not allowed. Example: call to a function only allowed -in genesis - - -
const INVALID_STATE: u8 = 1;
-
- - - - - -A limit on an amount, e.g. a currency, is exceeded. Example: withdrawal of money after account limits window -is exhausted. - - -
const LIMIT_EXCEEDED: u8 = 8;
-
- - - - - -A resource is required but not published. Example: access to non-existing resource. - - -
const NOT_PUBLISHED: u8 = 5;
-
- - - - - -The signer of a transaction does not have the expected address for this operation. Example: a call to a function -which publishes a resource under a particular address. - - -
const REQUIRES_ADDRESS: u8 = 2;
-
- - - - - -The signer of a transaction does not have a required capability. - - -
const REQUIRES_CAPABILITY: u8 = 4;
-
- - - - - -The signer of a transaction does not have the expected role for this operation. Example: a call to a function -which requires the signer to have the role of treasury compliance. - - -
const REQUIRES_ROLE: u8 = 3;
-
- - - - - -## Function `make` - -A function to create an error from from a category and a reason. - - -
fun make(category: u8, reason: u64): u64
-
- - - -
-Implementation - - -
fun make(category: u8, reason: u64): u64 {
-    (category as u64) + (reason << 8)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-pragma verify = false;
-aborts_if [abstract] false;
-ensures [abstract] result == category;
-
- - - -
- - - -## Function `invalid_state` - -Create an error of invalid_state - - -
public fun invalid_state(reason: u64): u64
-
- - - -
-Implementation - - -
public fun invalid_state(reason: u64): u64 { make(INVALID_STATE, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == INVALID_STATE;
-
- - - -
- - - -## Function `requires_address` - -Create an error of requires_address. - - -
public fun requires_address(reason: u64): u64
-
- - - -
-Implementation - - -
public fun requires_address(reason: u64): u64 { make(REQUIRES_ADDRESS, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == REQUIRES_ADDRESS;
-
- - - -
- - - -## Function `requires_role` - -Create an error of requires_role. - - -
public fun requires_role(reason: u64): u64
-
- - - -
-Implementation - - -
public fun requires_role(reason: u64): u64 { make(REQUIRES_ROLE, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == REQUIRES_ROLE;
-
- - - -
- - - -## Function `requires_capability` - -Create an error of requires_capability. - - -
public fun requires_capability(reason: u64): u64
-
- - - -
-Implementation - - -
public fun requires_capability(reason: u64): u64 { make(REQUIRES_CAPABILITY, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == REQUIRES_CAPABILITY;
-
- - - -
- - - -## Function `not_published` - -Create an error of not_published. - - -
public fun not_published(reason: u64): u64
-
- - - -
-Implementation - - -
public fun not_published(reason: u64): u64 { make(NOT_PUBLISHED, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == NOT_PUBLISHED;
-
- - - -
- - - -## Function `already_published` - -Create an error of already_published. - - -
public fun already_published(reason: u64): u64
-
- - - -
-Implementation - - -
public fun already_published(reason: u64): u64 { make(ALREADY_PUBLISHED, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == ALREADY_PUBLISHED;
-
- - - -
- - - -## Function `invalid_argument` - -Create an error of invalid_argument. - - -
public fun invalid_argument(reason: u64): u64
-
- - - -
-Implementation - - -
public fun invalid_argument(reason: u64): u64 { make(INVALID_ARGUMENT, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == INVALID_ARGUMENT;
-
- - - -
- - - -## Function `limit_exceeded` - -Create an error of limit_exceeded. - - -
public fun limit_exceeded(reason: u64): u64
-
- - - -
-Implementation - - -
public fun limit_exceeded(reason: u64): u64 { make(LIMIT_EXCEEDED, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == LIMIT_EXCEEDED;
-
- - - -
- - - -## Function `internal` - -Create an error of internal. - - -
public fun internal(reason: u64): u64
-
- - - -
-Implementation - - -
public fun internal(reason: u64): u64 { make(INTERNAL, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == INTERNAL;
-
- - - -
- - - -## Function `deprecated` - -Create an error of deprecated. - - -
public fun deprecated(reason: u64): u64
-
- - - -
-Implementation - - -
public fun deprecated(reason: u64): u64 { make(DEPRECATED, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == DEPRECATED;
-
- - - -
- - - -## Function `custom` - -Create an error of custom. - - -
public fun custom(reason: u64): u64
-
- - - -
-Implementation - - -
public fun custom(reason: u64): u64 { make(CUSTOM, reason) }
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == CUSTOM;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Event.md b/release/v12/docs/Event.md deleted file mode 100644 index aed6dda1..00000000 --- a/release/v12/docs/Event.md +++ /dev/null @@ -1,300 +0,0 @@ - - - -# Module `0x1::Event` - -The Event module defines an EventHandleGenerator that is used to create -EventHandles with unique GUIDs. It contains a counter for the number -of EventHandles it generates. An EventHandle is used to count the number of -events emitted to a handle and emit events to the event store. - - -- [Resource `EventHandleGenerator`](#0x1_Event_EventHandleGenerator) -- [Struct `EventHandle`](#0x1_Event_EventHandle) -- [Constants](#@Constants_0) -- [Function `publish_generator`](#0x1_Event_publish_generator) -- [Function `fresh_guid`](#0x1_Event_fresh_guid) -- [Function `new_event_handle`](#0x1_Event_new_event_handle) -- [Function `emit_event`](#0x1_Event_emit_event) -- [Function `write_to_event_store`](#0x1_Event_write_to_event_store) -- [Function `destroy_handle`](#0x1_Event_destroy_handle) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::BCS;
-use 0x1::Errors;
-use 0x1::Signer;
-use 0x1::Vector;
-
- - - - - -## Resource `EventHandleGenerator` - -A resource representing the counter used to generate uniqueness under each account. There won't be destructor for -this resource to guarantee the uniqueness of the generated handle. - - -
struct EventHandleGenerator has key
-
- - - -
-Fields - - -
-
-counter: u64 -
-
- -
-
-addr: address -
-
- -
-
- - -
- - - -## Struct `EventHandle` - -A handle for an event such that: -1. Other modules can emit events to this handle. -2. Storage can use this handle to prove the total number of events that happened in the past. - - -
struct EventHandle<T: drop, store> has store
-
- - - -
-Fields - - -
-
-counter: u64 -
-
- Total number of events emitted to this event stream. -
-
-guid: vector<u8> -
-
- A globally unique ID for this event stream. -
-
- - -
- - - -## Constants - - - - -The event generator resource was in an invalid state - - -
const EEVENT_GENERATOR: u64 = 0;
-
- - - - - -## Function `publish_generator` - -Publishs a new event handle generator. - - -
public fun publish_generator(account: &signer)
-
- - - -
-Implementation - - -
public fun publish_generator(account: &signer) {
-    let addr = Signer::address_of(account);
-    assert!(!exists<EventHandleGenerator>(addr), Errors::already_published(EEVENT_GENERATOR));
-    move_to(account, EventHandleGenerator{ counter: 0, addr })
-}
-
- - - -
- - - -## Function `fresh_guid` - -Derive a fresh unique id by using sender's EventHandleGenerator. The generated vector is indeed unique because it -was derived from the hash(sender's EventHandleGenerator || sender_address). This module guarantees that the -EventHandleGenerator is only going to be monotonically increased and there's no way to revert it or destroy it. Thus -such counter is going to give distinct value for each of the new event stream under each sender. And since we -hash it with the sender's address, the result is guaranteed to be globally unique. - - -
fun fresh_guid(counter: &mut Event::EventHandleGenerator): vector<u8>
-
- - - -
-Implementation - - -
fun fresh_guid(counter: &mut EventHandleGenerator): vector<u8> {
-    let sender_bytes = BCS::to_bytes(&counter.addr);
-    let count_bytes = BCS::to_bytes(&counter.counter);
-    counter.counter = counter.counter + 1;
-
-    // EventHandleGenerator goes first just in case we want to extend address in the future.
-    Vector::append(&mut count_bytes, sender_bytes);
-
-    count_bytes
-}
-
- - - -
- - - -## Function `new_event_handle` - -Use EventHandleGenerator to generate a unique event handle for sig - - -
public fun new_event_handle<T: drop, store>(account: &signer): Event::EventHandle<T>
-
- - - -
-Implementation - - -
public fun new_event_handle<T: drop + store>(account: &signer): EventHandle<T>
-acquires EventHandleGenerator {
-    let addr = Signer::address_of(account);
-    assert!(exists<EventHandleGenerator>(addr), Errors::not_published(EEVENT_GENERATOR));
-    EventHandle<T> {
-        counter: 0,
-        guid: fresh_guid(borrow_global_mut<EventHandleGenerator>(addr))
-    }
-}
-
- - - -
- - - -## Function `emit_event` - -Emit an event with payload msg by using handle_ref's key and counter. - - -
public fun emit_event<T: drop, store>(handle_ref: &mut Event::EventHandle<T>, msg: T)
-
- - - -
-Implementation - - -
public fun emit_event<T: drop + store>(handle_ref: &mut EventHandle<T>, msg: T) {
-    let guid = *&handle_ref.guid;
-
-    write_to_event_store<T>(guid, handle_ref.counter, msg);
-    handle_ref.counter = handle_ref.counter + 1;
-}
-
- - - -
- - - -## Function `write_to_event_store` - -Native procedure that writes to the actual event stream in Event store -This will replace the "native" portion of EmitEvent bytecode - - -
fun write_to_event_store<T: drop, store>(guid: vector<u8>, count: u64, msg: T)
-
- - - -
-Implementation - - -
native fun write_to_event_store<T: drop + store>(guid: vector<u8>, count: u64, msg: T);
-
- - - -
- - - -## Function `destroy_handle` - -Destroy a unique handle. - - -
public fun destroy_handle<T: drop, store>(handle: Event::EventHandle<T>)
-
- - - -
-Implementation - - -
public fun destroy_handle<T: drop + store>(handle: EventHandle<T>) {
-    EventHandle<T> { counter: _, guid: _ } = handle;
-}
-
- - - -
- - - -## Module Specification - - - -Functions of the event module are mocked out using the intrinsic -pragma. They are implemented in the prover's prelude. - - -
pragma intrinsic = true;
-
diff --git a/release/v12/docs/EventUtil.md b/release/v12/docs/EventUtil.md deleted file mode 100644 index 420e3c6f..00000000 --- a/release/v12/docs/EventUtil.md +++ /dev/null @@ -1,175 +0,0 @@ - - - -# Module `0x1::EventUtil` - - - -- [Resource `EventHandleWrapper`](#0x1_EventUtil_EventHandleWrapper) -- [Constants](#@Constants_0) -- [Function `init_event`](#0x1_EventUtil_init_event) -- [Function `uninit_event`](#0x1_EventUtil_uninit_event) -- [Function `emit_event`](#0x1_EventUtil_emit_event) -- [Function `exist_event`](#0x1_EventUtil_exist_event) - - -
use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Signer;
-
- - - - - -## Resource `EventHandleWrapper` - - - -
struct EventHandleWrapper<EventT: drop, store> has key
-
- - - -
-Fields - - -
-
-handle: Event::EventHandle<EventT> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_INIT_REPEATE: u64 = 101;
-
- - - - - - - -
const ERR_RESOURCE_NOT_EXISTS: u64 = 102;
-
- - - - - -## Function `init_event` - - - -
public fun init_event<EventT: drop, store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun init_event<EventT: store + drop>(sender: &signer) {
-    let broker = Signer::address_of(sender);
-    assert!(!exists<EventHandleWrapper<EventT>>(broker), Errors::invalid_state(ERR_INIT_REPEATE));
-    move_to(sender, EventHandleWrapper<EventT> {
-        handle: Event::new_event_handle<EventT>(sender)
-    });
-}
-
- - - -
- - - -## Function `uninit_event` - - - -
public fun uninit_event<EventT: drop, store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun uninit_event<EventT: store + drop>(sender: &signer) acquires EventHandleWrapper {
-    let broker = Signer::address_of(sender);
-    assert!(exists<EventHandleWrapper<EventT>>(broker), Errors::invalid_state(ERR_RESOURCE_NOT_EXISTS));
-    let EventHandleWrapper<EventT> { handle } = move_from<EventHandleWrapper<EventT>>(broker);
-    Event::destroy_handle<EventT>(handle);
-}
-
- - - -
- - - -## Function `emit_event` - - - -
public fun emit_event<EventT: drop, store>(broker: address, event: EventT)
-
- - - -
-Implementation - - -
public fun emit_event<EventT: store + drop>(broker: address, event: EventT) acquires EventHandleWrapper {
-    let event_handle = borrow_global_mut<EventHandleWrapper<EventT>>(broker);
-    Event::emit_event(&mut event_handle.handle, event);
-}
-
- - - -
- - - -## Function `exist_event` - - - -
public fun exist_event<EventT: drop, store>(broker: address): bool
-
- - - -
-Implementation - - -
public fun exist_event<EventT: store + drop>(broker: address): bool {
-    exists<EventHandleWrapper<EventT>>(broker)
-}
-
- - - -
diff --git a/release/v12/docs/FixedPoint32.md b/release/v12/docs/FixedPoint32.md deleted file mode 100644 index 70a6d2fa..00000000 --- a/release/v12/docs/FixedPoint32.md +++ /dev/null @@ -1,438 +0,0 @@ - - - -# Module `0x1::FixedPoint32` - -The module provide operations for FixedPoint32. - - -- [Struct `FixedPoint32`](#0x1_FixedPoint32_FixedPoint32) -- [Constants](#@Constants_0) -- [Function `multiply_u64`](#0x1_FixedPoint32_multiply_u64) -- [Function `divide_u64`](#0x1_FixedPoint32_divide_u64) -- [Function `create_from_rational`](#0x1_FixedPoint32_create_from_rational) -- [Function `create_from_raw_value`](#0x1_FixedPoint32_create_from_raw_value) -- [Function `get_raw_value`](#0x1_FixedPoint32_get_raw_value) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-
- - - - - -## Struct `FixedPoint32` - -Define a fixed-point numeric type with 32 fractional bits. -This is just a u64 integer but it is wrapped in a struct to -make a unique type. - - -
struct FixedPoint32 has copy, drop, store
-
- - - -
-Fields - - -
-
-value: u64 -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const MAX_U64: u128 = 18446744073709551615;
-
- - - - - -The denominator provided was zero - - -
const EDENOMINATOR: u64 = 101;
-
- - - - - -The quotient value would be too large to be held in a u64 - - -
const EDIVISION: u64 = 102;
-
- - - - - -A division by zero was encountered - - -
const EDIVISION_BY_ZERO: u64 = 104;
-
- - - - - -The multiplied value would be too large to be held in a u64 - - -
const EMULTIPLICATION: u64 = 103;
-
- - - - - -The computed ratio when converting to a FixedPoint32 would be unrepresentable - - -
const ERATIO_OUT_OF_RANGE: u64 = 105;
-
- - - - - -## Function `multiply_u64` - -Multiply a u64 integer by a fixed-point number, truncating any -fractional part of the product. This will abort if the product -overflows. - - -
public fun multiply_u64(val: u64, multiplier: FixedPoint32::FixedPoint32): u64
-
- - - -
-Implementation - - -
public fun multiply_u64(val: u64, multiplier: FixedPoint32): u64 {
-    // 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);
-    // The unscaled product has 32 fractional bits (from the multiplier)
-    // so rescale it by shifting away the low bits.
-    let product = unscaled_product >> 32;
-    // Check whether the value is too large.
-    assert!(product <= MAX_U64, Errors::limit_exceeded(EMULTIPLICATION));
-    (product as u64)
-}
-
- - - -
- -
-Specification - - -Currently, we ignore the actual implementation of this function in verification -and treat it as uninterpreted, which simplifies the verification problem significantly. -This way we avoid the non-linear arithmetic problem presented by this function. - -Abstracting this and related functions is possible because the correctness of currency -conversion (where FixedPoint32 is used for) is not relevant for the rest of the contract -control flow, so we can assume some arbitrary (but fixed) behavior here. - - -
pragma opaque = true;
-include MultiplyAbortsIf;
-ensures result == spec_multiply_u64(val, multiplier);
-
- - - - - - - -
schema MultiplyAbortsIf {
-    val: num;
-    multiplier: FixedPoint32;
-    aborts_if spec_multiply_u64(val, multiplier) > MAX_U64 with Errors::LIMIT_EXCEEDED;
-}
-
- - - - - - - -
fun spec_multiply_u64(val: num, multiplier: FixedPoint32): num {
-   (val * multiplier.value) >> 32
-}
-
- - - -
- - - -## Function `divide_u64` - -Divide a u64 integer by a fixed-point number, truncating any -fractional part of the quotient. This will abort if the divisor -is zero or if the quotient overflows. - - -
public fun divide_u64(val: u64, divisor: FixedPoint32::FixedPoint32): u64
-
- - - -
-Implementation - - -
public fun divide_u64(val: u64, divisor: FixedPoint32): u64 {
-    // Check for division by zero.
-    assert!(divisor.value != 0, Errors::invalid_argument(EDIVISION_BY_ZERO));
-    // First convert to 128 bits and then shift left to
-    // add 32 fractional zero bits to the dividend.
-    let scaled_value = (val as u128) << 32;
-    let quotient = scaled_value / (divisor.value as u128);
-    // Check whether the value is too large.
-    assert!(quotient <= MAX_U64, Errors::limit_exceeded(EDIVISION));
-    // the value may be too large, which will cause the cast to fail
-    // with an arithmetic error.
-    (quotient as u64)
-}
-
- - - -
- -
-Specification - - -See comment at Self::multiply_64. - - -
pragma opaque = true;
-include DivideAbortsIf;
-ensures result == spec_divide_u64(val, divisor);
-
- - - - - - - -
schema DivideAbortsIf {
-    val: num;
-    divisor: FixedPoint32;
-    aborts_if divisor.value == 0 with Errors::INVALID_ARGUMENT;
-    aborts_if spec_divide_u64(val, divisor) > MAX_U64 with Errors::LIMIT_EXCEEDED;
-}
-
- - - - - - - -
fun spec_divide_u64(val: num, divisor: FixedPoint32): num {
-   (val << 32) / divisor.value
-}
-
- - - -
- - - -## Function `create_from_rational` - -Create a fixed-point value from a rational number specified by its -numerator and denominator. This function is for convenience; it is also -perfectly fine to create a fixed-point value by directly specifying the -raw value. This will abort if the denominator is zero or if the ratio is -not in the range 2^-32 .. 2^32-1. - - -
public fun create_from_rational(numerator: u64, denominator: u64): FixedPoint32::FixedPoint32
-
- - - -
-Implementation - - -
public fun create_from_rational(numerator: u64, denominator: u64): FixedPoint32 {
-    // If the denominator is zero, this will abort.
-    // Scale the numerator to have 64 fractional bits and the denominator
-    // to have 32 fractional bits, so that the quotient will have 32
-    // fractional bits.
-    let scaled_numerator = (numerator as u128) << 64;
-    let scaled_denominator = (denominator as u128) << 32;
-    assert!(scaled_denominator != 0, Errors::invalid_argument(EDENOMINATOR));
-    let quotient = scaled_numerator / scaled_denominator;
-    assert!(quotient != 0 || numerator == 0, Errors::invalid_argument(ERATIO_OUT_OF_RANGE));
-    // Return the quotient as a fixed-point number. We first need to check whether the cast
-    // can succeed.
-    assert!(quotient <= MAX_U64, Errors::limit_exceeded(ERATIO_OUT_OF_RANGE));
-    FixedPoint32 { value: (quotient as u64) }
-}
-
- - - -
- -
-Specification - - -See comment at Self::multiply_64. - - -
pragma opaque = true;
-include CreateFromRationalAbortsIf;
-ensures result == spec_create_from_rational(numerator, denominator);
-
- - - - - - - -
schema CreateFromRationalAbortsIf {
-    numerator: u64;
-    denominator: u64;
-    let scaled_numerator = numerator << 64;
-    let scaled_denominator = denominator << 32;
-    let quotient = scaled_numerator / scaled_denominator;
-    aborts_if scaled_denominator == 0 with Errors::INVALID_ARGUMENT;
-    aborts_if quotient == 0 && scaled_numerator != 0 with Errors::INVALID_ARGUMENT;
-    aborts_if quotient > MAX_U64 with Errors::LIMIT_EXCEEDED;
-}
-
- - - - - - - -
fun spec_create_from_rational(numerator: num, denominator: num): FixedPoint32 {
-   FixedPoint32{value: (numerator << 64) / (denominator << 32)}
-}
-
- - - -
- - - -## Function `create_from_raw_value` - -create a fixedpoint 32 from u64. - - -
public fun create_from_raw_value(value: u64): FixedPoint32::FixedPoint32
-
- - - -
-Implementation - - -
public fun create_from_raw_value(value: u64): FixedPoint32 {
-    FixedPoint32 { value }
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result.value == value;
-
- - - -
- - - -## Function `get_raw_value` - -Accessor for the raw u64 value. Other less common operations, such as -adding or subtracting FixedPoint32 values, can be done using the raw -values directly. - - -
public fun get_raw_value(num: FixedPoint32::FixedPoint32): u64
-
- - - -
-Implementation - - -
public fun get_raw_value(num: FixedPoint32): u64 {
-    num.value
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/GasOracleProposalPlugin.md b/release/v12/docs/GasOracleProposalPlugin.md deleted file mode 100644 index ac8efbf8..00000000 --- a/release/v12/docs/GasOracleProposalPlugin.md +++ /dev/null @@ -1,477 +0,0 @@ - - - -# Module `0x1::GasOracleProposalPlugin` - - - -- [Struct `GasOracleProposalPlugin`](#0x1_GasOracleProposalPlugin_GasOracleProposalPlugin) -- [Struct `OracleCreateAction`](#0x1_GasOracleProposalPlugin_OracleCreateAction) -- [Struct `OracleSourceAddAction`](#0x1_GasOracleProposalPlugin_OracleSourceAddAction) -- [Struct `OracleSourceRemoveAction`](#0x1_GasOracleProposalPlugin_OracleSourceRemoveAction) -- [Struct `OracleSources`](#0x1_GasOracleProposalPlugin_OracleSources) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_GasOracleProposalPlugin_initialize) -- [Function `required_caps`](#0x1_GasOracleProposalPlugin_required_caps) -- [Function `create_oracle_add_proposal`](#0x1_GasOracleProposalPlugin_create_oracle_add_proposal) -- [Function `execute_oracle_add_proposal`](#0x1_GasOracleProposalPlugin_execute_oracle_add_proposal) -- [Function `create_oracle_remove_proposal`](#0x1_GasOracleProposalPlugin_create_oracle_remove_proposal) -- [Function `execute_oracle_remove_proposal`](#0x1_GasOracleProposalPlugin_execute_oracle_remove_proposal) -- [Function `gas_oracle_read`](#0x1_GasOracleProposalPlugin_gas_oracle_read) -- [Function `install_plugin_proposal`](#0x1_GasOracleProposalPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_GasOracleProposalPlugin_install_plugin_proposal_entry) - - -
use 0x1::Account;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Errors;
-use 0x1::GasOracle;
-use 0x1::GenesisSignerCapability;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::PriceOracleAggregator;
-use 0x1::Vector;
-
- - - - - -## Struct `GasOracleProposalPlugin` - - - -
struct GasOracleProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `OracleCreateAction` - - - -
struct OracleCreateAction<TokenType: store> has store
-
- - - -
-Fields - - -
-
-precision: u8 -
-
- -
-
- - -
- - - -## Struct `OracleSourceAddAction` - - - -
struct OracleSourceAddAction<TokenType: store> has drop, store
-
- - - -
-Fields - - -
-
-source_address: address -
-
- -
-
- - -
- - - -## Struct `OracleSourceRemoveAction` - - - -
struct OracleSourceRemoveAction<TokenType: store> has drop, store
-
- - - -
-Fields - - -
-
-source_address: address -
-
- -
-
- - -
- - - -## Struct `OracleSources` - - - -
struct OracleSources<TokenType: store> has copy, store
-
- - - -
-Fields - - -
-
-source_addresses: vector<address> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_PLUGIN_ORACLE_EXIST: u64 = 1001;
-
- - - - - - - -
const ERR_PLUGIN_ORACLE_NOT_EXIST: u64 = 1002;
-
- - - - - - - -
const ORACLE_UPDATED_IN: u64 = 600000;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = GasOracleProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<GasOracleProposalPlugin>(
-        &witness,
-        b"0x1::GasOraclePlugin",
-        b"The plugin for gas oracle.",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<GasOracleProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://gas-oracle-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps(): vector<CapType> {
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::storage_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_oracle_add_proposal` - - - -
public(script) fun create_oracle_add_proposal<DAOT: store, TokenType: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64, source_address: address)
-
- - - -
-Implementation - - -
public(script) fun create_oracle_add_proposal<DAOT: store, TokenType: store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay: u64, source_address: address) {
-    let witness = GasOracleProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, GasOracleProposalPlugin>(&witness);
-    let action = OracleSourceAddAction<TokenType>{
-        source_address
-    };
-    DAOSpace::create_proposal(&cap, &sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `execute_oracle_add_proposal` - - - -
public(script) fun execute_oracle_add_proposal<DAOT: store, TokenType: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_oracle_add_proposal<DAOT: store, TokenType: store>(sender: signer, proposal_id: u64) {
-    let witness = GasOracleProposalPlugin{};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, GasOracleProposalPlugin>(&witness);
-    let OracleSourceAddAction<TokenType>{ source_address } = DAOSpace::execute_proposal<DAOT, GasOracleProposalPlugin, OracleSourceAddAction<TokenType>>(&proposal_cap, &sender, proposal_id);
-    let storage_cap = DAOSpace::acquire_storage_cap<DAOT, GasOracleProposalPlugin>(&witness);
-    let source_addresses = if (!DAOSpace::exists_in_storage<DAOT, GasOracleProposalPlugin, OracleSources<TokenType>>()) {
-        let genesis_singer= GenesisSignerCapability::get_genesis_signer();
-        Account::accept_token<TokenType>(genesis_singer);
-        Vector::singleton(source_address)
-    }else {
-        let OracleSources<TokenType>{ source_addresses } = DAOSpace::take_from_storage<DAOT, GasOracleProposalPlugin, OracleSources<TokenType>>(&storage_cap);
-        assert!(Vector::contains(&source_addresses, &source_address) == false, Errors::invalid_state(ERR_PLUGIN_ORACLE_EXIST));
-        Vector::push_back(&mut source_addresses, source_address);
-        source_addresses
-    };
-
-    DAOSpace::save_to_storage(&storage_cap, OracleSources<TokenType>{ source_addresses });
-}
-
- - - -
- - - -## Function `create_oracle_remove_proposal` - - - -
public(script) fun create_oracle_remove_proposal<DAOT: store, TokenType: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64, source_address: address)
-
- - - -
-Implementation - - -
public(script) fun create_oracle_remove_proposal<DAOT: store, TokenType: store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay: u64, source_address: address) {
-    let witness = GasOracleProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, GasOracleProposalPlugin>(&witness);
-    let action = OracleSourceRemoveAction<TokenType>{
-        source_address
-    };
-    DAOSpace::create_proposal(&cap, &sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `execute_oracle_remove_proposal` - - - -
public(script) fun execute_oracle_remove_proposal<DAOT: store, TokenType: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_oracle_remove_proposal<DAOT: store, TokenType: store>(sender: signer, proposal_id: u64) {
-    let witness = GasOracleProposalPlugin{};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, GasOracleProposalPlugin>(&witness);
-    let OracleSourceRemoveAction<TokenType>{ source_address } = DAOSpace::execute_proposal<DAOT, GasOracleProposalPlugin, OracleSourceRemoveAction<TokenType>>(&proposal_cap, &sender, proposal_id);
-    let storage_cap = DAOSpace::acquire_storage_cap<DAOT, GasOracleProposalPlugin>(&witness);
-    assert!(DAOSpace::exists_in_storage<DAOT, GasOracleProposalPlugin, OracleSources<TokenType>>(), ERR_PLUGIN_ORACLE_NOT_EXIST);
-    let OracleSources<TokenType>{ source_addresses } = DAOSpace::take_from_storage<DAOT, GasOracleProposalPlugin, OracleSources<TokenType>>(&storage_cap);
-    let (exist,index)= Vector::index_of(&source_addresses, &source_address);
-    assert!(exist, Errors::invalid_state(ERR_PLUGIN_ORACLE_NOT_EXIST));
-    Vector::remove(&mut source_addresses,index);
-    DAOSpace::save_to_storage(&storage_cap, OracleSources<TokenType>{ source_addresses });
-}
-
- - - -
- - - -## Function `gas_oracle_read` - - - -
public fun gas_oracle_read<DAOT: store, TokenType: store>(): u128
-
- - - -
-Implementation - - -
public fun gas_oracle_read<DAOT: store, TokenType: store>(): u128 {
-    let witness = GasOracleProposalPlugin{};
-    let storage_cap = DAOSpace::acquire_storage_cap<DAOT, GasOracleProposalPlugin>(&witness);
-    let OracleSources{ source_addresses } = DAOSpace::copy_from_storage<DAOT, GasOracleProposalPlugin, OracleSources<TokenType>>(&storage_cap);
-    PriceOracleAggregator::latest_price_average_aggregator<STCToken<TokenType>>(&source_addresses, ORACLE_UPDATED_IN)
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay: u64) {
-    InstallPluginProposalPlugin::create_proposal<DAOT, GasOracleProposalPlugin>(sender, required_caps(), title, introduction, extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay: u64) {
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/Genesis.md b/release/v12/docs/Genesis.md deleted file mode 100644 index 638f9277..00000000 --- a/release/v12/docs/Genesis.md +++ /dev/null @@ -1,597 +0,0 @@ - - - -# Module `0x1::Genesis` - -The module for init Genesis - - -- [Function `initialize`](#0x1_Genesis_initialize) -- [Function `initialize_v2`](#0x1_Genesis_initialize_v2) -- [Function `do_initialize`](#0x1_Genesis_do_initialize) -- [Function `initialize_for_unit_tests`](#0x1_Genesis_initialize_for_unit_tests) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::Account;
-use 0x1::AnyMemberPlugin;
-use 0x1::Block;
-use 0x1::BlockReward;
-use 0x1::ChainId;
-use 0x1::Config;
-use 0x1::ConfigProposalPlugin;
-use 0x1::ConsensusConfig;
-use 0x1::ConsensusStrategy;
-use 0x1::CoreAddresses;
-use 0x1::DAOExtensionPoint;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAORegistry;
-use 0x1::DummyToken;
-use 0x1::Epoch;
-use 0x1::Errors;
-use 0x1::GasOracleProposalPlugin;
-use 0x1::GenesisNFT;
-use 0x1::GenesisSignerCapability;
-use 0x1::GrantProposalPlugin;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::LanguageVersion;
-use 0x1::MemberProposalPlugin;
-use 0x1::MintProposalPlugin;
-use 0x1::Option;
-use 0x1::PackageTxnManager;
-use 0x1::RewardConfig;
-use 0x1::STC;
-use 0x1::STCUSDOracle;
-use 0x1::Signer;
-use 0x1::StakeToSBTPlugin;
-use 0x1::StarcoinDAO;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::TransactionFee;
-use 0x1::TransactionPublishOption;
-use 0x1::TransactionTimeoutConfig;
-use 0x1::Treasury;
-use 0x1::TreasuryPlugin;
-use 0x1::UpgradeModulePlugin;
-use 0x1::VMConfig;
-use 0x1::Vector;
-use 0x1::Version;
-
- - - - - -## Function `initialize` - - - -
public(script) fun initialize(_stdlib_version: u64, _reward_delay: u64, _pre_mine_stc_amount: u128, _time_mint_stc_amount: u128, _time_mint_stc_period: u64, _parent_hash: vector<u8>, _association_auth_key: vector<u8>, _genesis_auth_key: vector<u8>, _chain_id: u8, _genesis_timestamp: u64, _uncle_rate_target: u64, _epoch_block_count: u64, _base_block_time_target: u64, _base_block_difficulty_window: u64, _base_reward_per_block: u128, _base_reward_per_uncle_percent: u64, _min_block_time_target: u64, _max_block_time_target: u64, _base_max_uncles_per_block: u64, _base_block_gas_limit: u64, _strategy: u8, _script_allowed: bool, _module_publishing_allowed: bool, _instruction_schedule: vector<u8>, _native_schedule: vector<u8>, _global_memory_per_byte_cost: u64, _global_memory_per_byte_write_cost: u64, _min_transaction_gas_units: u64, _large_transaction_cutoff: u64, _instrinsic_gas_per_byte: u64, _maximum_number_of_gas_units: u64, _min_price_per_gas_unit: u64, _max_price_per_gas_unit: u64, _max_transaction_size_in_bytes: u64, _gas_unit_scaling_factor: u64, _default_account_size: u64, _voting_delay: u64, _voting_period: u64, _voting_quorum_rate: u8, _min_action_delay: u64, _transaction_timeout: u64)
-
- - - -
-Implementation - - -
public(script) fun initialize(
-    _stdlib_version: u64,
-    // block reward config
-    _reward_delay: u64,
-    _pre_mine_stc_amount: u128,
-    _time_mint_stc_amount: u128,
-    _time_mint_stc_period: u64,
-    _parent_hash: vector<u8>,
-    _association_auth_key: vector<u8>,
-    _genesis_auth_key: vector<u8>,
-    _chain_id: u8,
-    _genesis_timestamp: u64,
-    //consensus config
-    _uncle_rate_target: u64,
-    _epoch_block_count: u64,
-    _base_block_time_target: u64,
-    _base_block_difficulty_window: u64,
-    _base_reward_per_block: u128,
-    _base_reward_per_uncle_percent: u64,
-    _min_block_time_target: u64,
-    _max_block_time_target: u64,
-    _base_max_uncles_per_block: u64,
-    _base_block_gas_limit: u64,
-    _strategy: u8,
-    //vm config
-    _script_allowed: bool,
-    _module_publishing_allowed: bool,
-    _instruction_schedule: vector<u8>,
-    _native_schedule: vector<u8>,
-    //gas constants
-    _global_memory_per_byte_cost: u64,
-    _global_memory_per_byte_write_cost: u64,
-    _min_transaction_gas_units: u64,
-    _large_transaction_cutoff: u64,
-    _instrinsic_gas_per_byte: u64,
-    _maximum_number_of_gas_units: u64,
-    _min_price_per_gas_unit: u64,
-    _max_price_per_gas_unit: u64,
-    _max_transaction_size_in_bytes: u64,
-    _gas_unit_scaling_factor: u64,
-    _default_account_size: u64,
-    // dao config
-    _voting_delay: u64,
-    _voting_period: u64,
-    _voting_quorum_rate: u8,
-    _min_action_delay: u64,
-    // transaction timeout config
-    _transaction_timeout: u64,
-) {
-    abort Errors::deprecated(1)
-}
-
- - - -
- - - -## Function `initialize_v2` - - - -
public(script) fun initialize_v2(stdlib_version: u64, reward_delay: u64, total_stc_amount: u128, pre_mine_stc_amount: u128, time_mint_stc_amount: u128, time_mint_stc_period: u64, parent_hash: vector<u8>, association_auth_key: vector<u8>, genesis_auth_key: vector<u8>, chain_id: u8, genesis_timestamp: u64, uncle_rate_target: u64, epoch_block_count: u64, base_block_time_target: u64, base_block_difficulty_window: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, script_allowed: bool, module_publishing_allowed: bool, instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, transaction_timeout: u64)
-
- - - -
-Implementation - - -
public(script) fun initialize_v2(
-    stdlib_version: u64,
-    // block reward and stc config
-    reward_delay: u64,
-    total_stc_amount: u128,
-    pre_mine_stc_amount: u128,
-    time_mint_stc_amount: u128,
-    time_mint_stc_period: u64,
-    parent_hash: vector<u8>,
-    association_auth_key: vector<u8>,
-    genesis_auth_key: vector<u8>,
-    chain_id: u8,
-    genesis_timestamp: u64,
-    //consensus config
-    uncle_rate_target: u64,
-    epoch_block_count: u64,
-    base_block_time_target: u64,
-    base_block_difficulty_window: u64,
-    base_reward_per_block: u128,
-    base_reward_per_uncle_percent: u64,
-    min_block_time_target: u64,
-    max_block_time_target: u64,
-    base_max_uncles_per_block: u64,
-    base_block_gas_limit: u64,
-    strategy: u8,
-    //vm config
-    script_allowed: bool,
-    module_publishing_allowed: bool,
-    instruction_schedule: vector<u8>,
-    native_schedule: vector<u8>,
-    //gas constants
-    global_memory_per_byte_cost: u64,
-    global_memory_per_byte_write_cost: u64,
-    min_transaction_gas_units: u64,
-    large_transaction_cutoff: u64,
-    instrinsic_gas_per_byte: u64,
-    maximum_number_of_gas_units: u64,
-    min_price_per_gas_unit: u64,
-    max_price_per_gas_unit: u64,
-    max_transaction_size_in_bytes: u64,
-    gas_unit_scaling_factor: u64,
-    default_account_size: u64,
-    // dao config
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-    // transaction timeout config
-    transaction_timeout: u64,
-) {
-    Self::do_initialize(
-        stdlib_version,
-        reward_delay,
-        total_stc_amount,
-        pre_mine_stc_amount,
-        time_mint_stc_amount,
-        time_mint_stc_period,
-        parent_hash,
-        association_auth_key,
-        genesis_auth_key,
-        chain_id,
-        genesis_timestamp,
-        uncle_rate_target,
-        epoch_block_count,
-        base_block_time_target,
-        base_block_difficulty_window,
-        base_reward_per_block,
-        base_reward_per_uncle_percent,
-        min_block_time_target,
-        max_block_time_target,
-        base_max_uncles_per_block,
-        base_block_gas_limit,
-        strategy,
-        script_allowed,
-        module_publishing_allowed,
-        instruction_schedule,
-        native_schedule,
-        global_memory_per_byte_cost,
-        global_memory_per_byte_write_cost,
-        min_transaction_gas_units,
-        large_transaction_cutoff,
-        instrinsic_gas_per_byte,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit,
-        max_transaction_size_in_bytes,
-        gas_unit_scaling_factor,
-        default_account_size,
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-        transaction_timeout,
-    );
-}
-
- - - -
- - - -## Function `do_initialize` - - - -
fun do_initialize(stdlib_version: u64, reward_delay: u64, total_stc_amount: u128, pre_mine_stc_amount: u128, time_mint_stc_amount: u128, time_mint_stc_period: u64, parent_hash: vector<u8>, association_auth_key: vector<u8>, genesis_auth_key: vector<u8>, chain_id: u8, genesis_timestamp: u64, uncle_rate_target: u64, epoch_block_count: u64, base_block_time_target: u64, base_block_difficulty_window: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, script_allowed: bool, module_publishing_allowed: bool, instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, transaction_timeout: u64)
-
- - - -
-Implementation - - -
fun do_initialize(
-    stdlib_version: u64,
-    // block reward and stc config
-    reward_delay: u64,
-    total_stc_amount: u128,
-    pre_mine_stc_amount: u128,
-    time_mint_stc_amount: u128,
-    time_mint_stc_period: u64,
-    parent_hash: vector<u8>,
-    association_auth_key: vector<u8>,
-    genesis_auth_key: vector<u8>,
-    chain_id: u8,
-    genesis_timestamp: u64,
-    //consensus config
-    uncle_rate_target: u64,
-    epoch_block_count: u64,
-    base_block_time_target: u64,
-    base_block_difficulty_window: u64,
-    base_reward_per_block: u128,
-    base_reward_per_uncle_percent: u64,
-    min_block_time_target: u64,
-    max_block_time_target: u64,
-    base_max_uncles_per_block: u64,
-    base_block_gas_limit: u64,
-    strategy: u8,
-    //vm config
-    script_allowed: bool,
-    module_publishing_allowed: bool,
-    instruction_schedule: vector<u8>,
-    native_schedule: vector<u8>,
-    //gas constants
-    global_memory_per_byte_cost: u64,
-    global_memory_per_byte_write_cost: u64,
-    min_transaction_gas_units: u64,
-    large_transaction_cutoff: u64,
-    instrinsic_gas_per_byte: u64,
-    maximum_number_of_gas_units: u64,
-    min_price_per_gas_unit: u64,
-    max_price_per_gas_unit: u64,
-    max_transaction_size_in_bytes: u64,
-    gas_unit_scaling_factor: u64,
-    default_account_size: u64,
-    // dao config
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-    // transaction timeout config
-    transaction_timeout: u64,
-) {
-    Timestamp::assert_genesis();
-    // create genesis account
-    let genesis_account = Account::create_genesis_account(CoreAddresses::GENESIS_ADDRESS());
-    //Init global time
-    Timestamp::initialize(&genesis_account, genesis_timestamp);
-    ChainId::initialize(&genesis_account, chain_id);
-    ConsensusStrategy::initialize(&genesis_account, strategy);
-    Block::initialize(&genesis_account, parent_hash);
-    TransactionPublishOption::initialize(
-        &genesis_account,
-        script_allowed,
-        module_publishing_allowed,
-    );
-    // init config
-    VMConfig::initialize(
-        &genesis_account,
-        instruction_schedule,
-        native_schedule,
-        global_memory_per_byte_cost,
-        global_memory_per_byte_write_cost,
-        min_transaction_gas_units,
-        large_transaction_cutoff,
-        instrinsic_gas_per_byte,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit,
-        max_transaction_size_in_bytes,
-        gas_unit_scaling_factor,
-        default_account_size,
-    );
-    TransactionTimeoutConfig::initialize(&genesis_account, transaction_timeout);
-    ConsensusConfig::initialize(
-        &genesis_account,
-        uncle_rate_target,
-        epoch_block_count,
-        base_block_time_target,
-        base_block_difficulty_window,
-        base_reward_per_block,
-        base_reward_per_uncle_percent,
-        min_block_time_target,
-        max_block_time_target,
-        base_max_uncles_per_block,
-        base_block_gas_limit,
-        strategy,
-    );
-    Epoch::initialize(&genesis_account);
-    let association = Account::create_genesis_account(
-        CoreAddresses::ASSOCIATION_ROOT_ADDRESS(),
-    );
-    Config::publish_new_config<Version::Version>(&genesis_account, Version::new_version(stdlib_version));
-    // stdlib use two phase upgrade strategy.
-    PackageTxnManager::update_module_upgrade_strategy(
-        &genesis_account,
-        PackageTxnManager::get_strategy_two_phase(),
-        Option::some(0u64),
-    );
-    BlockReward::initialize(&genesis_account, reward_delay);
-
-    // stc should be initialized after genesis_account's module upgrade strategy set and all on chain config init.
-    let withdraw_cap = STC::initialize_v3(&genesis_account, total_stc_amount);
-    Account::do_accept_token<STC>(&genesis_account);
-    Account::do_accept_token<STC>(&association);
-
-    DummyToken::initialize(&genesis_account);
-
-    if (pre_mine_stc_amount > 0) {
-        let stc = Treasury::withdraw_with_capability<STC>(&mut withdraw_cap, pre_mine_stc_amount);
-        Account::deposit(Signer::address_of(&association), stc);
-    };
-    if (time_mint_stc_amount > 0) {
-        let liner_withdraw_cap = Treasury::issue_linear_withdraw_capability<STC>(&mut withdraw_cap, time_mint_stc_amount, time_mint_stc_period);
-        Treasury::add_linear_withdraw_capability(&association, liner_withdraw_cap);
-    };
-
-    // Lock the TreasuryWithdrawCapability to Dao
-    TreasuryPlugin::delegate_capability<STC>(&genesis_account, withdraw_cap);
-
-    TransactionFee::initialize(&genesis_account);
-
-    // only test/dev network set genesis auth key.
-    if (!Vector::is_empty(&genesis_auth_key)) {
-        let genesis_rotate_key_cap = Account::extract_key_rotation_capability(&genesis_account);
-        Account::rotate_authentication_key_with_capability(&genesis_rotate_key_cap, genesis_auth_key);
-        Account::restore_key_rotation_capability(genesis_rotate_key_cap);
-    };
-
-    let assoc_rotate_key_cap = Account::extract_key_rotation_capability(&association);
-    Account::rotate_authentication_key_with_capability(&assoc_rotate_key_cap, association_auth_key);
-    Account::restore_key_rotation_capability(assoc_rotate_key_cap);
-
-    // v5 -> v6
-    {
-        let cap = Account::remove_signer_capability(&genesis_account);
-        GenesisSignerCapability::initialize(&genesis_account, cap);
-        //register oracle
-        STCUSDOracle::register(&genesis_account);
-        let merkle_root = x"5969f0e8e19f8769276fb638e6060d5c02e40088f5fde70a6778dd69d659ee6d";
-        let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY";
-        GenesisNFT::initialize(&genesis_account, merkle_root, 1639u64, image);
-    };
-    Config::publish_new_config(&genesis_account, LanguageVersion::new(4));
-
-    //v11 -> v12
-    Block::checkpoints_init();
-    DAORegistry::initialize();
-
-    DAOExtensionPoint::initialize();
-    DAOPluginMarketplace::initialize();
-
-    AnyMemberPlugin::initialize(&genesis_account);
-    ConfigProposalPlugin::initialize(&genesis_account);
-    GrantProposalPlugin::initialize(&genesis_account);
-    InstallPluginProposalPlugin::initialize(&genesis_account);
-    MemberProposalPlugin::initialize(&genesis_account);
-    MintProposalPlugin::initialize(&genesis_account);
-    StakeToSBTPlugin::initialize(&genesis_account);
-    UpgradeModulePlugin::initialize(&genesis_account);
-    GasOracleProposalPlugin::initialize(&genesis_account);
-    TreasuryPlugin::initialize(&genesis_account);
-
-    let signer_cap = Account::get_genesis_capability();
-    let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(&genesis_account);
-    StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, voting_delay, voting_period, voting_quorum_rate, min_action_delay, 1000 * 1000 * 1000 * 1000);
-
-    StarcoinDAO::delegate_config_capability<STC, TransactionPublishOption::TransactionPublishOption>(
-        Config::extract_modify_config_capability<TransactionPublishOption::TransactionPublishOption>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, VMConfig::VMConfig>(
-        Config::extract_modify_config_capability<VMConfig::VMConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, ConsensusConfig::ConsensusConfig>(
-        Config::extract_modify_config_capability<ConsensusConfig::ConsensusConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, RewardConfig::RewardConfig>(
-        Config::extract_modify_config_capability<RewardConfig::RewardConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>(
-        Config::extract_modify_config_capability<TransactionTimeoutConfig::TransactionTimeoutConfig>(&genesis_account));
-    StarcoinDAO::delegate_config_capability<STC, LanguageVersion::LanguageVersion>(
-        Config::extract_modify_config_capability<LanguageVersion::LanguageVersion>(&genesis_account));
-    StarcoinDAO::set_treasury_withdraw_proposal_scale(100);
-
-    //Start time, Timestamp::is_genesis() will return false. this call should at the end of genesis init.
-    Timestamp::set_time_has_started(&genesis_account);
-    Account::release_genesis_signer(genesis_account);
-    Account::release_genesis_signer(association);
-}
-
- - - -
- - - -## Function `initialize_for_unit_tests` - -Init the genesis for unit tests - - -
public fun initialize_for_unit_tests()
-
- - - -
-Implementation - - -
public fun initialize_for_unit_tests() {
-    let stdlib_version: u64 = 6;
-    let reward_delay: u64 = 7;
-    let total_stc_amount: u128 = 3185136000000000000u128;
-    let pre_mine_stc_amount: u128 = 159256800000000000u128;
-    let time_mint_stc_amount: u128 = (85043130u128 * 3u128 + 74213670u128 * 3u128) * 1000000000u128;
-    let time_mint_stc_period: u64 = 1000000000;
-
-    let parent_hash: vector<u8> = x"0000000000000000000000000000000000000000000000000000000000000000";
-    let association_auth_key: vector<u8> = x"0000000000000000000000000000000000000000000000000000000000000000";
-    let genesis_auth_key: vector<u8> = x"0000000000000000000000000000000000000000000000000000000000000000";
-    let chain_id: u8 = 255;
-    let genesis_timestamp: u64 = 0;
-
-    //consensus config
-    let uncle_rate_target: u64 = 80;
-    let epoch_block_count: u64 = 240;
-    let base_block_time_target: u64 = 10000;
-    let base_block_difficulty_window: u64 = 24;
-    let base_reward_per_block: u128 = 1000000000;
-    let base_reward_per_uncle_percent: u64 = 10;
-    let min_block_time_target: u64 = 1000;
-    let max_block_time_target: u64 = 20000;
-    let base_max_uncles_per_block: u64 = 2;
-    let base_block_gas_limit: u64 = 500000000;
-    let strategy: u8 = 0;
-
-    //vm config
-    let script_allowed: bool = true;
-    let module_publishing_allowed: bool = true;
-    //TODO init the gas table.
-    let instruction_schedule: vector<u8> = Vector::empty();
-    let native_schedule: vector<u8> = Vector::empty();
-
-    //gas constants
-    let global_memory_per_byte_cost: u64 = 1;
-    let global_memory_per_byte_write_cost: u64 = 1;
-    let min_transaction_gas_units: u64 = 1;
-    let large_transaction_cutoff: u64 = 1;
-    let instrinsic_gas_per_byte: u64 = 1;
-    let maximum_number_of_gas_units: u64 = 1;
-    let min_price_per_gas_unit: u64 = 1;
-    let max_price_per_gas_unit: u64 = 10000;
-    let max_transaction_size_in_bytes: u64 = 1024 * 1024;
-    let gas_unit_scaling_factor: u64 = 1;
-    let default_account_size: u64 = 600;
-
-    // dao config
-    let voting_delay: u64 = 1000;
-    let voting_period: u64 = 6000;
-    let voting_quorum_rate: u8 = 4;
-    let min_action_delay: u64 = 1000;
-
-    // transaction timeout config
-    let transaction_timeout: u64 = 10000;
-
-    Self::do_initialize(
-        stdlib_version,
-        reward_delay,
-        total_stc_amount,
-        pre_mine_stc_amount,
-        time_mint_stc_amount,
-        time_mint_stc_period,
-        parent_hash,
-        association_auth_key,
-        genesis_auth_key,
-        chain_id,
-        genesis_timestamp,
-        uncle_rate_target,
-        epoch_block_count,
-        base_block_time_target,
-        base_block_difficulty_window,
-        base_reward_per_block,
-        base_reward_per_uncle_percent,
-        min_block_time_target,
-        max_block_time_target,
-        base_max_uncles_per_block,
-        base_block_gas_limit,
-        strategy,
-        script_allowed,
-        module_publishing_allowed,
-        instruction_schedule,
-        native_schedule,
-        global_memory_per_byte_cost,
-        global_memory_per_byte_write_cost,
-        min_transaction_gas_units,
-        large_transaction_cutoff,
-        instrinsic_gas_per_byte,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit,
-        max_transaction_size_in_bytes,
-        gas_unit_scaling_factor,
-        default_account_size,
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-        transaction_timeout,
-    );
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_partial = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/GenesisNFT.md b/release/v12/docs/GenesisNFT.md deleted file mode 100644 index b25f6504..00000000 --- a/release/v12/docs/GenesisNFT.md +++ /dev/null @@ -1,49 +0,0 @@ - - - -# Module `0x1::GenesisNFTScripts` - - - -- [Function `mint`](#0x1_GenesisNFTScripts_mint) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::GenesisNFT;
-
- - - - - -## Function `mint` - -Mint a GenesisNFT - - -
public(script) fun mint(sender: signer, index: u64, merkle_proof: vector<vector<u8>>)
-
- - - -
-Implementation - - -
public(script) fun mint(sender: signer, index: u64, merkle_proof:vector<vector<u8>>) {
-    GenesisNFT::mint_entry(sender, index, merkle_proof);
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-
diff --git a/release/v12/docs/GenesisSignerCapability.md b/release/v12/docs/GenesisSignerCapability.md deleted file mode 100644 index 5ffea8c8..00000000 --- a/release/v12/docs/GenesisSignerCapability.md +++ /dev/null @@ -1,114 +0,0 @@ - - - -# Module `0x1::GenesisSignerCapability` - - - -- [Resource `GenesisSignerCapability`](#0x1_GenesisSignerCapability_GenesisSignerCapability) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_GenesisSignerCapability_initialize) -- [Function `get_genesis_signer`](#0x1_GenesisSignerCapability_get_genesis_signer) - - -
use 0x1::Account;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-
- - - - - -## Resource `GenesisSignerCapability` - - - -
struct GenesisSignerCapability has key
-
- - - -
-Fields - - -
-
-cap: Account::SignerCapability -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ENOT_GENESIS_ACCOUNT: u64 = 11;
-
- - - - - -## Function `initialize` - - - -
public(friend) fun initialize(signer: &signer, cap: Account::SignerCapability)
-
- - - -
-Implementation - - -
public(friend) fun initialize(signer: &signer, cap: Account::SignerCapability) {
-    CoreAddresses::assert_genesis_address(signer);
-    assert!(
-        Account::signer_address(&cap) == CoreAddresses::GENESIS_ADDRESS(),
-        Errors::invalid_argument(ENOT_GENESIS_ACCOUNT)
-    );
-    move_to(signer, GenesisSignerCapability{cap});
-}
-
- - - -
- - - -## Function `get_genesis_signer` - - - -
public(friend) fun get_genesis_signer(): signer
-
- - - -
-Implementation - - -
public(friend) fun get_genesis_signer(): signer acquires GenesisSignerCapability {
-    let cap = borrow_global<GenesisSignerCapability>(CoreAddresses::GENESIS_ADDRESS());
-    Account::create_signer_with_cap(&cap.cap)
-}
-
- - - -
diff --git a/release/v12/docs/GrantProposalPlugin.md b/release/v12/docs/GrantProposalPlugin.md deleted file mode 100644 index fa054d8d..00000000 --- a/release/v12/docs/GrantProposalPlugin.md +++ /dev/null @@ -1,546 +0,0 @@ - - - -# Module `0x1::GrantProposalPlugin` - - - -- [Struct `GrantProposalPlugin`](#0x1_GrantProposalPlugin_GrantProposalPlugin) -- [Struct `GrantCreateAction`](#0x1_GrantProposalPlugin_GrantCreateAction) -- [Struct `GrantConfigAction`](#0x1_GrantProposalPlugin_GrantConfigAction) -- [Struct `GrantRevokeAction`](#0x1_GrantProposalPlugin_GrantRevokeAction) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_GrantProposalPlugin_initialize) -- [Function `required_caps`](#0x1_GrantProposalPlugin_required_caps) -- [Function `create_grant_proposal`](#0x1_GrantProposalPlugin_create_grant_proposal) -- [Function `create_grant_proposal_entry`](#0x1_GrantProposalPlugin_create_grant_proposal_entry) -- [Function `execute_grant_proposal`](#0x1_GrantProposalPlugin_execute_grant_proposal) -- [Function `execute_grant_proposal_entry`](#0x1_GrantProposalPlugin_execute_grant_proposal_entry) -- [Function `create_grant_revoke_proposal`](#0x1_GrantProposalPlugin_create_grant_revoke_proposal) -- [Function `create_grant_revoke_proposal_entry`](#0x1_GrantProposalPlugin_create_grant_revoke_proposal_entry) -- [Function `execute_grant_revoke_proposal`](#0x1_GrantProposalPlugin_execute_grant_revoke_proposal) -- [Function `execute_grant_revoke_proposal_entry`](#0x1_GrantProposalPlugin_execute_grant_revoke_proposal_entry) -- [Function `install_plugin_proposal`](#0x1_GrantProposalPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_GrantProposalPlugin_install_plugin_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Errors;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Vector;
-
- - - - - -## Struct `GrantProposalPlugin` - - - -
struct GrantProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `GrantCreateAction` - - - -
struct GrantCreateAction<TokenT: store> has drop, store
-
- - - -
-Fields - - -
-
-grantee: address -
-
- -
-
-total: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
- - -
- - - -## Struct `GrantConfigAction` - - - -
struct GrantConfigAction<TokenT: store> has drop, store
-
- - - -
-Fields - - -
-
-old_grantee: address -
-
- -
-
-new_grantee: address -
-
- -
-
-total: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
- - -
- - - -## Struct `GrantRevokeAction` - - - -
struct GrantRevokeAction<TokenT: store> has drop, store
-
- - - -
-Fields - - -
-
-grantee: address -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_GRANTTREASURY_WITHDRAW_NOT_GRANTEE: u64 = 101;
-
- - - - - - - -
const ERR_GRANTTREASURY_WITHDRAW_TOO_MORE: u64 = 102;
-
- - - - - - - -
const ERR_SENDER_NOT_SAME: u64 = 103;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = GrantProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<GrantProposalPlugin>(
-        &witness,
-        b"0x1::GrantProposalPlugin",
-        b"The plugin for grant proposal",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<GrantProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://grant-proposal-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps():vector<CapType>{
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::grant_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_grant_proposal` - - - -
public fun create_grant_proposal<DAOT: store, TokenT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, grantee: address, total: u128, start_time: u64, period: u64, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_grant_proposal<DAOT: store, TokenT:store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>,grantee: address, total: u128, start_time:u64, period: u64, action_delay:u64){
-    let witness = GrantProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, GrantProposalPlugin>(&witness);
-    let action = GrantCreateAction<TokenT>{
-        grantee:grantee,
-        total:total,
-        start_time:start_time,
-        period:period
-    };
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `create_grant_proposal_entry` - - - -
public(script) fun create_grant_proposal_entry<DAOT: store, TokenT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, grantee: address, total: u128, start_time: u64, period: u64, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun create_grant_proposal_entry<DAOT: store, TokenT:store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>,grantee: address, total: u128, start_time:u64, period: u64, action_delay:u64){
-    create_grant_proposal<DAOT, TokenT>(&sender, title, introduction, extend, grantee, total, start_time, period, action_delay);
-}
-
- - - -
- - - -## Function `execute_grant_proposal` - - - -
public fun execute_grant_proposal<DAOT: store, TokenT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_grant_proposal<DAOT: store, TokenT:store>(sender: &signer, proposal_id: u64){
-    let witness = GrantProposalPlugin{};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, GrantProposalPlugin>(&witness);
-    let GrantCreateAction{grantee, total, start_time, period} = DAOSpace::execute_proposal<DAOT, GrantProposalPlugin, GrantCreateAction<TokenT>>(&proposal_cap, sender, proposal_id);
-    assert!(grantee == Signer::address_of(sender),Errors::not_published(ERR_SENDER_NOT_SAME));
-    let grant_cap = DAOSpace::acquire_grant_cap<DAOT, GrantProposalPlugin>(&witness);
-    DAOSpace::grant_offer<DAOT, GrantProposalPlugin, TokenT>(&grant_cap, Signer::address_of(sender), total, start_time, period);
-}
-
- - - -
- - - -## Function `execute_grant_proposal_entry` - - - -
public(script) fun execute_grant_proposal_entry<DAOT: store, TokenT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_grant_proposal_entry<DAOT: store, TokenT:store>(sender: signer, proposal_id: u64){
-    execute_grant_proposal<DAOT, TokenT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `create_grant_revoke_proposal` - - - -
public fun create_grant_revoke_proposal<DAOT: store, TokenT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, grantee: address, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_grant_revoke_proposal<DAOT: store, TokenT:store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, grantee:address, action_delay:u64){
-    let witness = GrantProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, GrantProposalPlugin>(&witness);
-    let action = GrantRevokeAction<TokenT>{ grantee };
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `create_grant_revoke_proposal_entry` - - - -
public(script) fun create_grant_revoke_proposal_entry<DAOT: store, TokenT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, grantee: address, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun create_grant_revoke_proposal_entry<DAOT: store, TokenT:store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, grantee:address, action_delay:u64){
-    create_grant_revoke_proposal<DAOT, TokenT>(&sender, title, introduction, extend, grantee, action_delay);
-}
-
- - - -
- - - -## Function `execute_grant_revoke_proposal` - - - -
public fun execute_grant_revoke_proposal<DAOT: store, TokenT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_grant_revoke_proposal<DAOT: store, TokenT:store>(sender: &signer, proposal_id: u64){
-    let witness = GrantProposalPlugin{};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, GrantProposalPlugin>(&witness);
-    let GrantRevokeAction{ grantee } = DAOSpace::execute_proposal<DAOT, GrantProposalPlugin, GrantRevokeAction<TokenT>>(&proposal_cap, sender, proposal_id);
-    let grant_cap = DAOSpace::acquire_grant_cap<DAOT, GrantProposalPlugin>(&witness);
-    DAOSpace::grant_revoke<DAOT, GrantProposalPlugin, TokenT>(&grant_cap , grantee);
-}
-
- - - -
- - - -## Function `execute_grant_revoke_proposal_entry` - - - -
public(script) fun execute_grant_revoke_proposal_entry<DAOT: store, TokenT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_grant_revoke_proposal_entry<DAOT: store, TokenT:store>(sender: signer, proposal_id: u64){
-    execute_grant_revoke_proposal<DAOT, TokenT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT:store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    InstallPluginProposalPlugin::create_proposal<DAOT, GrantProposalPlugin>(sender, required_caps(), title, introduction, extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun install_plugin_proposal_entry<DAOT: store>(sender:signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/Hash.md b/release/v12/docs/Hash.md deleted file mode 100644 index 47f83022..00000000 --- a/release/v12/docs/Hash.md +++ /dev/null @@ -1,116 +0,0 @@ - - - -# Module `0x1::Hash` - -The module provide sha-hash functionality for Move. - - -- [Function `sha2_256`](#0x1_Hash_sha2_256) -- [Function `sha3_256`](#0x1_Hash_sha3_256) -- [Function `keccak_256`](#0x1_Hash_keccak_256) -- [Function `ripemd160`](#0x1_Hash_ripemd160) -- [Module Specification](#@Module_Specification_0) - - -
- - - - - -## Function `sha2_256` - - - -
public fun sha2_256(data: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
native public fun sha2_256(data: vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `sha3_256` - - - -
public fun sha3_256(data: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
native public fun sha3_256(data: vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `keccak_256` - - - -
public fun keccak_256(data: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
native public fun keccak_256(data: vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `ripemd160` - - - -
public fun ripemd160(data: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
native public fun ripemd160(data: vector<u8>): vector<u8>;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/InstallPluginProposalPlugin.md b/release/v12/docs/InstallPluginProposalPlugin.md deleted file mode 100644 index f42b9fb4..00000000 --- a/release/v12/docs/InstallPluginProposalPlugin.md +++ /dev/null @@ -1,233 +0,0 @@ - - - -# Module `0x1::InstallPluginProposalPlugin` - - - -- [Struct `InstallPluginProposalPlugin`](#0x1_InstallPluginProposalPlugin_InstallPluginProposalPlugin) -- [Struct `InstallPluginAction`](#0x1_InstallPluginProposalPlugin_InstallPluginAction) -- [Function `initialize`](#0x1_InstallPluginProposalPlugin_initialize) -- [Function `required_caps`](#0x1_InstallPluginProposalPlugin_required_caps) -- [Function `create_proposal`](#0x1_InstallPluginProposalPlugin_create_proposal) -- [Function `execute_proposal`](#0x1_InstallPluginProposalPlugin_execute_proposal) -- [Function `execute_proposal_entry`](#0x1_InstallPluginProposalPlugin_execute_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `InstallPluginProposalPlugin` - - - -
struct InstallPluginProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `InstallPluginAction` - - - -
struct InstallPluginAction<ToInstallPluginT> has drop, store
-
- - - -
-Fields - - -
-
-required_caps: vector<DAOSpace::CapType> -
-
- -
-
- - -
- - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = InstallPluginProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<InstallPluginProposalPlugin>(
-        &witness,
-        b"0x1::InstallPluginProposalPlugin",
-        b"The plugin for install plugin proposal",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<InstallPluginProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://install-plugin-proposal-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps():vector<CapType>{
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_proposal` - -Create a proposal to install a plugin. -We do not provide a entry function for create_proposal, because we can not use CapType as an entry function parameter, -every plugin should provide a entry function to create proposal to install self. - - -
public fun create_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, required_caps: vector<DAOSpace::CapType>, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, required_caps: vector<CapType>, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay: u64){
-    let witness = InstallPluginProposalPlugin{};
-
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, InstallPluginProposalPlugin>(&witness);
-    let action = InstallPluginAction<ToInstallPluginT>{
-        required_caps,
-    };
-
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `execute_proposal` - - - -
public fun execute_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_proposal<DAOT: store, ToInstallPluginT: store>(sender: &signer, proposal_id: u64){
-    let witness = InstallPluginProposalPlugin{};
-
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, InstallPluginProposalPlugin>(&witness);
-    let InstallPluginAction{required_caps} = DAOSpace::execute_proposal<DAOT, InstallPluginProposalPlugin, InstallPluginAction<ToInstallPluginT>>(&proposal_cap, sender, proposal_id);
-
-    let install_plugin_cap = DAOSpace::acquire_install_plugin_cap<DAOT, InstallPluginProposalPlugin>(&witness);
-    DAOSpace::install_plugin<DAOT, InstallPluginProposalPlugin, ToInstallPluginT>(&install_plugin_cap, required_caps);
-}
-
- - - -
- - - -## Function `execute_proposal_entry` - - - -
public(script) fun execute_proposal_entry<DAOT: store, ToInstallPluginT: copy, drop, store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_proposal_entry<DAOT: store, ToInstallPluginT: copy + drop + store>(sender: signer, proposal_id: u64) {
-    execute_proposal<DAOT, ToInstallPluginT>(&sender, proposal_id);
-}
-
- - - -
diff --git a/release/v12/docs/LanguageVersion.md b/release/v12/docs/LanguageVersion.md deleted file mode 100644 index 1c8bb89d..00000000 --- a/release/v12/docs/LanguageVersion.md +++ /dev/null @@ -1,114 +0,0 @@ - - - -# Module `0x1::LanguageVersion` - - - -- [Struct `LanguageVersion`](#0x1_LanguageVersion_LanguageVersion) -- [Function `new`](#0x1_LanguageVersion_new) -- [Function `version`](#0x1_LanguageVersion_version) - - -
- - - - - -## Struct `LanguageVersion` - - - -
struct LanguageVersion has copy, drop, store
-
- - - -
-Fields - - -
-
-major: u64 -
-
- -
-
- - -
- - - -## Function `new` - - - -
public fun new(version: u64): LanguageVersion::LanguageVersion
-
- - - -
-Implementation - - -
public fun new(version: u64): LanguageVersion {
-    LanguageVersion {major: version}
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `version` - - - -
public fun version(version: &LanguageVersion::LanguageVersion): u64
-
- - - -
-Implementation - - -
public fun version(version: &LanguageVersion): u64 {
-    version.major
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
diff --git a/release/v12/docs/Math.md b/release/v12/docs/Math.md deleted file mode 100644 index 605ab641..00000000 --- a/release/v12/docs/Math.md +++ /dev/null @@ -1,378 +0,0 @@ - - - -# Module `0x1::Math` - -The module provide some improved math calculations. - - -- [Constants](#@Constants_0) -- [Function `u64_max`](#0x1_Math_u64_max) -- [Function `u128_max`](#0x1_Math_u128_max) -- [Function `sqrt`](#0x1_Math_sqrt) -- [Function `pow`](#0x1_Math_pow) -- [Function `mul_div`](#0x1_Math_mul_div) -- [Function `sum`](#0x1_Math_sum) -- [Function `avg`](#0x1_Math_avg) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Vector;
-
- - - - - -## Constants - - - - - - -
const U128_MAX: u128 = 340282366920938463463374607431768211455;
-
- - - - - - - -
const U64_MAX: u64 = 18446744073709551615;
-
- - - - - -## Function `u64_max` - -u64::MAX - - -
public fun u64_max(): u64
-
- - - -
-Implementation - - -
public fun u64_max(): u64 {
-    U64_MAX
-}
-
- - - -
- - - -## Function `u128_max` - -u128::MAX - - -
public fun u128_max(): u128
-
- - - -
-Implementation - - -
public fun u128_max(): u128 {
-    U128_MAX
-}
-
- - - -
- - - -## Function `sqrt` - -babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) - - -
public fun sqrt(y: u128): u64
-
- - - -
-Implementation - - -
public fun sqrt(y: u128): u64 {
-    if (y < 4) {
-        if (y == 0) {
-            0u64
-        } else {
-            1u64
-        }
-    } else {
-        let z = y;
-        let x = y / 2 + 1;
-        while (x < z) {
-            z = x;
-            x = (y / x + x) / 2;
-        };
-        (z as u64)
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-pragma verify = false;
-aborts_if [abstract] false;
-ensures [abstract] result == spec_sqrt();
-
- - -We use an uninterpreted function to represent the result of sqrt. The actual value -does not matter for the verification of callers. - - - - - -
fun spec_sqrt(): u128;
-
- - - -
- - - -## Function `pow` - -calculate the y pow of x. - - -
public fun pow(x: u64, y: u64): u128
-
- - - -
-Implementation - - -
public fun pow(x: u64, y: u64): u128 {
-    let result = 1u128;
-    let z = y;
-    let u = (x as u128);
-    while (z > 0) {
-        if (z % 2 == 1) {
-            result = (u * result as u128);
-        };
-        u = (u * u as u128);
-        z = z / 2;
-    };
-    result
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-pragma verify = false;
-aborts_if [abstract] false;
-ensures [abstract] result == spec_pow();
-
- - -We use an uninterpreted function to represent the result of pow. The actual value -does not matter for the verification of callers. - - - - - -
fun spec_pow(): u128;
-
- - - -
- - - -## Function `mul_div` - -https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 -calculate x * y /z with as little loss of precision as possible and avoid overflow - - -
public fun mul_div(x: u128, y: u128, z: u128): u128
-
- - - -
-Implementation - - -
public fun mul_div(x: u128, y: u128, z: u128): u128 {
-    if (y == z) {
-        return x
-    };
-    if (x == z) {
-        return y
-    };
-    let a = x / z;
-    let b = x % z;
-    //x = a * z + b;
-    let c = y / z;
-    let d = y % z;
-    //y = c * z + d;
-    a * c * z + a * d + b * c + b * d / z
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-include MulDivAbortsIf;
-aborts_if [abstract] false;
-ensures [abstract] result == spec_mul_div();
-
- - - - - - - -
schema MulDivAbortsIf {
-    x: u128;
-    y: u128;
-    z: u128;
-    aborts_if y != z && x > z && z == 0;
-    aborts_if y != z && x > z && z!=0 && x/z*y > MAX_U128;
-    aborts_if y != z && x <= z && z == 0;
-    aborts_if y != z && x <= z && x / z * (x % z) > MAX_U128;
-    aborts_if y != z && x <= z && x / z * (x % z) * z > MAX_U128;
-    aborts_if y != z && x <= z && x / z * (y % z) > MAX_U128;
-    aborts_if y != z && x <= z && x / z * (x % z) * z + x / z * (y % z) > MAX_U128;
-    aborts_if y != z && x <= z && x % z * (y / z) > MAX_U128;
-    aborts_if y != z && x <= z && x % z * (y % z) > MAX_U128;
-    aborts_if y != z && x <= z && x % z * (y % z) / z > MAX_U128;
-    aborts_if y != z && x <= z && x / z * (x % z) * z + x / z * (y % z) + x % z * (y / z) > MAX_U128;
-    aborts_if y != z && x <= z && x / z * (x % z) * z + x / z * (y % z) + x % z * (y / z) + x % z * (y % z) / z > MAX_U128;
-}
-
- - - - - - - -
fun spec_mul_div(): u128;
-
- - - -
- - - -## Function `sum` - -calculate sum of nums - - -
public fun sum(nums: &vector<u128>): u128
-
- - - -
-Implementation - - -
public fun sum(nums: &vector<u128>): u128 {
-    let len = Vector::length(nums);
-    let i = 0;
-    let sum = 0;
-    while (i < len){
-        sum = sum + *Vector::borrow(nums, i);
-        i = i + 1;
-    };
-    sum
-}
-
- - - -
- - - -## Function `avg` - -calculate average of nums - - -
public fun avg(nums: &vector<u128>): u128
-
- - - -
-Implementation - - -
public fun avg(nums: &vector<u128>): u128{
-    let len = Vector::length(nums);
-    let sum = sum(nums);
-    sum/(len as u128)
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/MemberProposalPlugin.md b/release/v12/docs/MemberProposalPlugin.md deleted file mode 100644 index 818e6e9c..00000000 --- a/release/v12/docs/MemberProposalPlugin.md +++ /dev/null @@ -1,360 +0,0 @@ - - - -# Module `0x1::MemberProposalPlugin` - - - -- [Struct `MemberProposalPlugin`](#0x1_MemberProposalPlugin_MemberProposalPlugin) -- [Struct `MemberJoinAction`](#0x1_MemberProposalPlugin_MemberJoinAction) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_MemberProposalPlugin_initialize) -- [Function `required_caps`](#0x1_MemberProposalPlugin_required_caps) -- [Function `create_proposal`](#0x1_MemberProposalPlugin_create_proposal) -- [Function `create_proposal_entry`](#0x1_MemberProposalPlugin_create_proposal_entry) -- [Function `execute_proposal`](#0x1_MemberProposalPlugin_execute_proposal) -- [Function `execute_proposal_entry`](#0x1_MemberProposalPlugin_execute_proposal_entry) -- [Function `install_plugin_proposal`](#0x1_MemberProposalPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_MemberProposalPlugin_install_plugin_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Errors;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `MemberProposalPlugin` - - - -
struct MemberProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `MemberJoinAction` - - - -
struct MemberJoinAction has drop, store
-
- - - -
-Fields - - -
-
-member: address -
-
- -
-
-init_sbt: u128 -
-
- -
-
-image_url: vector<u8> -
-
- -
-
-image_data: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_MEMBER_EXIST: u64 = 101;
-
- - - - - - - -
const ERR_MEMBER_OFFER_EXIST: u64 = 102;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = MemberProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<MemberProposalPlugin>(
-        &witness,
-        b"0x1::MemberProposalPlugin",
-        b"The plugin for member proposal",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<MemberProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://member-proposal-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps():vector<CapType>{
-    let caps = Vector::singleton(DAOSpace::member_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::proposal_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_proposal` - - - -
public fun create_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, member: address, image_data: vector<u8>, image_url: vector<u8>, init_sbt: u128, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_proposal<DAOT: store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, member: address, image_data:vector<u8>, image_url:vector<u8>, init_sbt: u128, action_delay: u64){
-    let witness = MemberProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, MemberProposalPlugin>(&witness);
-    let action = MemberJoinAction{
-        member,
-        init_sbt,
-        image_data,
-        image_url
-    };
-    assert!(!DAOSpace::is_exist_member_offer<DAOT>(member), Errors::already_published(ERR_MEMBER_OFFER_EXIST));
-    assert!(!DAOSpace::is_member<DAOT>(member), Errors::already_published(ERR_MEMBER_EXIST));
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `create_proposal_entry` - - - -
public(script) fun create_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, member: address, image_data: vector<u8>, image_url: vector<u8>, init_sbt: u128, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun create_proposal_entry<DAOT: store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, member: address, image_data:vector<u8>, image_url:vector<u8>, init_sbt: u128, action_delay: u64){
-    create_proposal<DAOT>(&sender, title, introduction, extend, member, image_data, image_url, init_sbt, action_delay);
-}
-
- - - -
- - - -## Function `execute_proposal` - - - -
public fun execute_proposal<DAOT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_proposal<DAOT: store>(sender: &signer, proposal_id: u64){
-    let witness = MemberProposalPlugin{};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, MemberProposalPlugin>(&witness);
-    let MemberJoinAction{member, init_sbt, image_data, image_url} = DAOSpace::execute_proposal<DAOT, MemberProposalPlugin, MemberJoinAction>(&proposal_cap, sender, proposal_id);
-    let member_cap = DAOSpace::acquire_member_cap<DAOT, MemberProposalPlugin>(&witness);
-    let op_image_data = if(Vector::length(&image_data) == 0){
-        Option::none<vector<u8>>()
-    }else{
-        Option::some(image_data)
-    };
-    let op_image_url = if(Vector::length(&image_url) == 0){
-        Option::none<vector<u8>>()
-    }else{
-        Option::some(image_url)
-    };
-    DAOSpace::issue_member_offer(&member_cap, member,op_image_data , op_image_url , init_sbt);
-}
-
- - - -
- - - -## Function `execute_proposal_entry` - - - -
public(script) fun execute_proposal_entry<DAOT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_proposal_entry<DAOT: store>(sender: signer, proposal_id: u64){
-    execute_proposal<DAOT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT:store>(sender:&signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>,action_delay:u64){
-    InstallPluginProposalPlugin::create_proposal<DAOT, MemberProposalPlugin>(sender, required_caps(), title, introduction, extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun install_plugin_proposal_entry<DAOT:store>(sender:signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/MerkleNFT.md b/release/v12/docs/MerkleNFT.md deleted file mode 100644 index 93a2088b..00000000 --- a/release/v12/docs/MerkleNFT.md +++ /dev/null @@ -1,352 +0,0 @@ - - - -# Module `0x1::MerkleNFTDistributor` - - - -- [Resource `MerkleNFTDistribution`](#0x1_MerkleNFTDistributor_MerkleNFTDistribution) -- [Constants](#@Constants_0) -- [Function `register`](#0x1_MerkleNFTDistributor_register) -- [Function `register_v2`](#0x1_MerkleNFTDistributor_register_v2) -- [Function `mint_with_cap`](#0x1_MerkleNFTDistributor_mint_with_cap) -- [Function `encode_leaf`](#0x1_MerkleNFTDistributor_encode_leaf) -- [Function `set_minted_`](#0x1_MerkleNFTDistributor_set_minted_) -- [Function `verify_proof`](#0x1_MerkleNFTDistributor_verify_proof) -- [Function `is_minted`](#0x1_MerkleNFTDistributor_is_minted) -- [Function `is_minted_`](#0x1_MerkleNFTDistributor_is_minted_) - - -
use 0x1::BCS;
-use 0x1::Errors;
-use 0x1::Hash;
-use 0x1::MerkleProof;
-use 0x1::NFT;
-use 0x1::Signer;
-use 0x1::Vector;
-
- - - - - -## Resource `MerkleNFTDistribution` - - - -
struct MerkleNFTDistribution<NFTMeta: copy, drop, store> has key
-
- - - -
-Fields - - -
-
-merkle_root: vector<u8> -
-
- -
-
-claimed_bitmap: vector<u128> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NO_MINT_CAPABILITY: u64 = 1002;
-
- - - - - - - -
const ALREADY_MINTED: u64 = 1000;
-
- - - - - - - -
const INVALID_PROOF: u64 = 1001;
-
- - - - - -## Function `register` - -Deprecated, use register_v2 instead. - - -
public fun register<NFTMeta: copy, drop, store, Info: copy, drop, store>(signer: &signer, merkle_root: vector<u8>, leafs: u64, info: Info, meta: NFT::Metadata): NFT::MintCapability<NFTMeta>
-
- - - -
-Implementation - - -
public fun register<NFTMeta: copy + store + drop, Info: copy + store + drop>(
-    signer: &signer,
-    merkle_root: vector<u8>,
-    leafs: u64,
-    info: Info,
-    meta: Metadata
-): MintCapability<NFTMeta> {
-    let bitmap_count = leafs / 128;
-    if (bitmap_count * 128 < leafs) {
-        bitmap_count = bitmap_count + 1;
-    };
-    let claimed_bitmap = Vector::empty();
-    let j = 0;
-    while (j < bitmap_count) {
-        Vector::push_back( &mut claimed_bitmap, 0u128);
-        j = j + 1;
-    };
-    let distribution = MerkleNFTDistribution<NFTMeta>{
-        merkle_root,
-        claimed_bitmap
-    };
-    NFT::register<NFTMeta, Info>(signer, info, meta);
-    move_to(signer, distribution);
-    NFT::remove_mint_capability<NFTMeta>(signer)
-}
-
- - - -
- - - -## Function `register_v2` - - - -
public fun register_v2<NFTMeta: copy, drop, store>(signer: &signer, merkle_root: vector<u8>, leafs: u64, meta: NFT::Metadata): NFT::MintCapability<NFTMeta>
-
- - - -
-Implementation - - -
public fun register_v2<NFTMeta: copy + store + drop>(signer: &signer, merkle_root: vector<u8>, leafs: u64, meta: Metadata): MintCapability<NFTMeta> {
-    let bitmap_count = leafs / 128;
-    if (bitmap_count * 128 < leafs) {
-        bitmap_count = bitmap_count + 1;
-    };
-    let claimed_bitmap = Vector::empty();
-    let j = 0;
-    while (j < bitmap_count) {
-        Vector::push_back( &mut claimed_bitmap, 0u128);
-        j = j + 1;
-    };
-    let distribution = MerkleNFTDistribution<NFTMeta>{
-        merkle_root,
-        claimed_bitmap
-    };
-    NFT::register_v2<NFTMeta>(signer, meta);
-    move_to(signer, distribution);
-    NFT::remove_mint_capability<NFTMeta>(signer)
-}
-
- - - -
- - - -## Function `mint_with_cap` - - - -
public fun mint_with_cap<NFTMeta: copy, drop, store, NFTBody: store, Info: copy, drop, store>(sender: &signer, cap: &mut NFT::MintCapability<NFTMeta>, creator: address, index: u64, base_meta: NFT::Metadata, type_meta: NFTMeta, body: NFTBody, merkle_proof: vector<vector<u8>>): NFT::NFT<NFTMeta, NFTBody>
-
- - - -
-Implementation - - -
public fun mint_with_cap<NFTMeta: copy + store + drop, NFTBody: store, Info: copy + store + drop>(sender: &signer, cap:&mut MintCapability<NFTMeta>, creator: address, index: u64, base_meta: Metadata, type_meta: NFTMeta, body: NFTBody, merkle_proof:vector<vector<u8>>): NFT<NFTMeta, NFTBody>
-    acquires MerkleNFTDistribution {
-        let addr = Signer::address_of(sender);
-        let distribution = borrow_global_mut<MerkleNFTDistribution<NFTMeta>>(creator);
-        let minted = is_minted_<NFTMeta>(distribution, index);
-        assert!(!minted, Errors::custom(ALREADY_MINTED));
-        let leaf_data = encode_leaf(&index, &addr);
-        let verified = MerkleProof::verify(&merkle_proof, &distribution.merkle_root, Hash::sha3_256(leaf_data));
-        assert!(verified, Errors::custom(INVALID_PROOF));
-        set_minted_(distribution, index);
-        let nft = NFT::mint_with_cap<NFTMeta, NFTBody, Info>(creator, cap, base_meta, type_meta, body);
-        return nft
-    }
-
- - - -
- - - -## Function `encode_leaf` - - - -
fun encode_leaf(index: &u64, account: &address): vector<u8>
-
- - - -
-Implementation - - -
fun encode_leaf(index: &u64, account: &address): vector<u8> {
-    let leaf = Vector::empty();
-    Vector::append(&mut leaf, BCS::to_bytes(index));
-    Vector::append(&mut leaf, BCS::to_bytes(account));
-    leaf
-}
-
- - - -
- - - -## Function `set_minted_` - - - -
fun set_minted_<NFTMeta: copy, drop, store>(distribution: &mut MerkleNFTDistributor::MerkleNFTDistribution<NFTMeta>, index: u64)
-
- - - -
-Implementation - - -
fun set_minted_<NFTMeta: copy + store + drop>(distribution: &mut MerkleNFTDistribution<NFTMeta>, index: u64) {
-    let claimed_word_index = index / 128;
-    let claimed_bit_index = ((index % 128) as u8);
-    let word = Vector::borrow_mut(&mut distribution.claimed_bitmap, claimed_word_index);
-    // word | (1 << bit_index)
-    let mask = 1u128 << claimed_bit_index;
-    *word = (*word | mask);
-}
-
- - - -
- - - -## Function `verify_proof` - - - -
public fun verify_proof<NFTMeta: copy, drop, store>(account: address, creator: address, index: u64, merkle_proof: vector<vector<u8>>): bool
-
- - - -
-Implementation - - -
public fun verify_proof<NFTMeta: copy + store + drop>(account: address, creator: address, index: u64, merkle_proof:vector<vector<u8>>): bool
-    acquires MerkleNFTDistribution {
-        let distribution = borrow_global_mut<MerkleNFTDistribution<NFTMeta>>(creator);
-        let leaf_data = encode_leaf(&index, &account);
-        MerkleProof::verify(&merkle_proof, &distribution.merkle_root, Hash::sha3_256(leaf_data))
-    }
-
- - - -
- - - -## Function `is_minted` - - - -
public fun is_minted<NFTMeta: copy, drop, store>(creator: address, index: u64): bool
-
- - - -
-Implementation - - -
public fun is_minted<NFTMeta: copy + store + drop>(creator: address, index: u64): bool
-    acquires MerkleNFTDistribution {
-        let distribution = borrow_global_mut<MerkleNFTDistribution<NFTMeta>>(creator);
-        is_minted_<NFTMeta>(distribution, index)
-    }
-
- - - -
- - - -## Function `is_minted_` - - - -
fun is_minted_<NFTMeta: copy, drop, store>(distribution: &MerkleNFTDistributor::MerkleNFTDistribution<NFTMeta>, index: u64): bool
-
- - - -
-Implementation - - -
fun is_minted_<NFTMeta: copy + store + drop>(distribution: &MerkleNFTDistribution<NFTMeta>, index: u64): bool {
-    let claimed_word_index = index / 128;
-    let claimed_bit_index = ((index % 128) as u8);
-    let word = Vector::borrow( &distribution.claimed_bitmap, claimed_word_index);
-    let mask = 1u128 << claimed_bit_index;
-    (*word & mask) == mask
-}
-
- - - -
diff --git a/release/v12/docs/MintDaoProposal.md b/release/v12/docs/MintDaoProposal.md deleted file mode 100644 index 7bf5a984..00000000 --- a/release/v12/docs/MintDaoProposal.md +++ /dev/null @@ -1,258 +0,0 @@ - - - -# Module `0x1::MintDaoProposal` - -MintDaoProposal is a dao proposal for mint extra tokens. - - -- [Resource `WrappedMintCapability`](#0x1_MintDaoProposal_WrappedMintCapability) -- [Struct `MintToken`](#0x1_MintDaoProposal_MintToken) -- [Constants](#@Constants_0) -- [Function `plugin`](#0x1_MintDaoProposal_plugin) -- [Function `propose_mint_to`](#0x1_MintDaoProposal_propose_mint_to) -- [Function `execute_mint_proposal`](#0x1_MintDaoProposal_execute_mint_proposal) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Account;
-use 0x1::Dao;
-use 0x1::Errors;
-use 0x1::Signer;
-use 0x1::Token;
-
- - - - - -## Resource `WrappedMintCapability` - -A wrapper of Token MintCapability. - - -
struct WrappedMintCapability<TokenType> has key
-
- - - -
-Fields - - -
-
-cap: Token::MintCapability<TokenType> -
-
- -
-
- - -
- - - -## Struct `MintToken` - -MintToken request. - - -
struct MintToken has copy, drop, store
-
- - - -
-Fields - - -
-
-receiver: address -
-
- the receiver of minted tokens. -
-
-amount: u128 -
-
- how many tokens to mint. -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 401;
-
- - - - - -## Function `plugin` - -Plugin method of the module. -Should be called by token issuer. - - -
public fun plugin<TokenT: store>(signer: &signer)
-
- - - -
-Implementation - - -
public fun plugin<TokenT: store>(signer: &signer) {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    let mint_cap = Token::remove_mint_capability<TokenT>(signer);
-    move_to(signer, WrappedMintCapability { cap: mint_cap });
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-let sender = Signer::address_of(signer);
-aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS();
-aborts_if !exists<Token::MintCapability<TokenT>>(sender);
-aborts_if exists<WrappedMintCapability<TokenT>>(sender);
-ensures !exists<Token::MintCapability<TokenT>>(sender);
-ensures exists<WrappedMintCapability<TokenT>>(sender);
-
- - - -
- - - -## Function `propose_mint_to` - -Entrypoint for the proposal. - - -
public fun propose_mint_to<TokenT: copy, drop, store>(signer: &signer, receiver: address, amount: u128, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_mint_to<TokenT: copy + drop + store>(signer: &signer, receiver: address, amount: u128, exec_delay: u64) {
-    Dao::propose<TokenT, MintToken>(
-        signer,
-        MintToken { receiver, amount },
-        exec_delay,
-    );
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-include Dao::AbortIfDaoConfigNotExist<TokenT>;
-include Dao::AbortIfDaoInfoNotExist<TokenT>;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config<TokenT>().min_action_delay;
-include Dao::CheckQuorumVotes<TokenT>;
-let sender = Signer::address_of(signer);
-aborts_if exists<Dao::Proposal<TokenT, MintToken>>(sender);
-
- - - -
- - - -## Function `execute_mint_proposal` - -Once the proposal is agreed, anyone can call the method to make the proposal happen. - - -
public fun execute_mint_proposal<TokenT: copy, drop, store>(proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_mint_proposal<TokenT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-) acquires WrappedMintCapability {
-    let MintToken { receiver, amount } = Dao::extract_proposal_action<TokenT, MintToken>(
-        proposer_address,
-        proposal_id,
-    );
-    let cap = borrow_global<WrappedMintCapability<TokenT>>(Token::token_address<TokenT>());
-    let tokens = Token::mint_with_capability<TokenT>(&cap.cap, amount);
-    Account::deposit(receiver, tokens);
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = true;
-let expected_states = vec<u8>(6);
-include Dao::CheckProposalStates<TokenT, MintToken>{expected_states};
-let proposal = global<Dao::Proposal<TokenT, MintToken>>(proposer_address);
-aborts_if Option::is_none(proposal.action);
-aborts_if !exists<WrappedMintCapability<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-pragma aborts_if_is_partial;
-
diff --git a/release/v12/docs/MintProposalPlugin.md b/release/v12/docs/MintProposalPlugin.md deleted file mode 100644 index e9db71ee..00000000 --- a/release/v12/docs/MintProposalPlugin.md +++ /dev/null @@ -1,391 +0,0 @@ - - - -# Module `0x1::MintProposalPlugin` - - - -- [Struct `MintProposalPlugin`](#0x1_MintProposalPlugin_MintProposalPlugin) -- [Struct `MintTokenAction`](#0x1_MintProposalPlugin_MintTokenAction) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_MintProposalPlugin_initialize) -- [Function `required_caps`](#0x1_MintProposalPlugin_required_caps) -- [Function `delegate_token_mint_cap`](#0x1_MintProposalPlugin_delegate_token_mint_cap) -- [Function `delegate_token_mint_cap_entry`](#0x1_MintProposalPlugin_delegate_token_mint_cap_entry) -- [Function `create_mint_proposal`](#0x1_MintProposalPlugin_create_mint_proposal) -- [Function `create_mint_proposal_entry`](#0x1_MintProposalPlugin_create_mint_proposal_entry) -- [Function `execute_mint_proposal`](#0x1_MintProposalPlugin_execute_mint_proposal) -- [Function `execute_mint_proposal_entry`](#0x1_MintProposalPlugin_execute_mint_proposal_entry) -- [Function `install_plugin_proposal`](#0x1_MintProposalPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_MintProposalPlugin_install_plugin_proposal_entry) - - -
use 0x1::Account;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Errors;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Token;
-use 0x1::Vector;
-
- - - - - -## Struct `MintProposalPlugin` - - - -
struct MintProposalPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `MintTokenAction` - -MintToken request. - - -
struct MintTokenAction<TokenT: store> has copy, drop, store
-
- - - -
-Fields - - -
-
-receiver: address -
-
- the receiver of minted tokens. -
-
-amount: u128 -
-
- how many tokens to mint. -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_RECEIVER: u64 = 101;
-
- - - - - - - -
const ERR_NO_MINT_CAP: u64 = 102;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = MintProposalPlugin{};
-
-    DAOPluginMarketplace::register_plugin<MintProposalPlugin>(
-        &witness,
-        b"0x1::MintProposalPlugin",
-        b"The plugin for minting tokens.",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<MintProposalPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://mint-proposal-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps():vector<CapType>{
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::token_mint_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `delegate_token_mint_cap` - - - -
public fun delegate_token_mint_cap<DAOT: store, TokenT: store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun delegate_token_mint_cap<DAOT: store, TokenT: store>(sender: &signer) {
-    let witness = MintProposalPlugin {};
-    let mint_cap = Token::remove_mint_capability<TokenT>(sender);
-    DAOSpace::delegate_token_mint_cap<DAOT, MintProposalPlugin, TokenT>(mint_cap, &witness);
-}
-
- - - -
- - - -## Function `delegate_token_mint_cap_entry` - - - -
public(script) fun delegate_token_mint_cap_entry<DAOT: store, TokenT: store>(sender: signer)
-
- - - -
-Implementation - - -
public (script) fun delegate_token_mint_cap_entry<DAOT: store, TokenT: store>(sender: signer) {
-    delegate_token_mint_cap<DAOT, TokenT>(&sender);
-}
-
- - - -
- - - -## Function `create_mint_proposal` - - - -
public fun create_mint_proposal<DAOT: store, TokenT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, receiver: address, amount: u128, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_mint_proposal<DAOT: store, TokenT:store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, receiver: address, amount: u128, action_delay: u64){
-    let witness = MintProposalPlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, MintProposalPlugin>(&witness);
-    let action = MintTokenAction<TokenT>{
-        receiver,
-        amount,
-    };
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `create_mint_proposal_entry` - - - -
public(script) fun create_mint_proposal_entry<DAOT: store, TokenT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, receiver: address, amount: u128, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun create_mint_proposal_entry<DAOT: store, TokenT:store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, receiver: address, amount: u128, action_delay: u64){
-    create_mint_proposal<DAOT, TokenT>(&sender, extend, title, introduction, receiver, amount, action_delay);
-}
-
- - - -
- - - -## Function `execute_mint_proposal` - - - -
public fun execute_mint_proposal<DAOT: store, TokenT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_mint_proposal<DAOT: store, TokenT:store>(sender: &signer, proposal_id: u64){
-    let witness = MintProposalPlugin{};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, MintProposalPlugin>(&witness);
-    let MintTokenAction<TokenT>{receiver, amount} = DAOSpace::execute_proposal<DAOT, MintProposalPlugin, MintTokenAction<TokenT>>(&proposal_cap, sender, proposal_id);
-    assert!(receiver == Signer::address_of(sender),Errors::not_published(ERR_NOT_RECEIVER));
-    let tokens = DAOSpace::mint_token<DAOT, MintProposalPlugin, TokenT>(amount, &witness);
-    Account::deposit<TokenT>(receiver, tokens);
-}
-
- - - -
- - - -## Function `execute_mint_proposal_entry` - - - -
public(script) fun execute_mint_proposal_entry<DAOT: store, TokenT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_mint_proposal_entry<DAOT: store, TokenT:store>(sender: signer, proposal_id: u64){
-    execute_mint_proposal<DAOT, TokenT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT:store>(sender:&signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    InstallPluginProposalPlugin::create_proposal<DAOT, MintProposalPlugin>(sender,required_caps(), title, introduction,  extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun install_plugin_proposal_entry<DAOT:store>(sender:signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/MintScripts.md b/release/v12/docs/MintScripts.md deleted file mode 100644 index dbbdd845..00000000 --- a/release/v12/docs/MintScripts.md +++ /dev/null @@ -1,10 +0,0 @@ - - - -# Module `0x1::MintScripts` - - - - - -
diff --git a/release/v12/docs/ModifyDaoConfigProposal.md b/release/v12/docs/ModifyDaoConfigProposal.md deleted file mode 100644 index c602b98d..00000000 --- a/release/v12/docs/ModifyDaoConfigProposal.md +++ /dev/null @@ -1,343 +0,0 @@ - - - -# Module `0x1::ModifyDaoConfigProposal` - -A proposal module which is used to modify Token's DAO configuration. - - -- [Resource `DaoConfigModifyCapability`](#0x1_ModifyDaoConfigProposal_DaoConfigModifyCapability) -- [Struct `DaoConfigUpdate`](#0x1_ModifyDaoConfigProposal_DaoConfigUpdate) -- [Constants](#@Constants_0) -- [Function `plugin`](#0x1_ModifyDaoConfigProposal_plugin) -- [Function `destroy_modify_config_capability`](#0x1_ModifyDaoConfigProposal_destroy_modify_config_capability) -- [Function `propose`](#0x1_ModifyDaoConfigProposal_propose) -- [Function `execute`](#0x1_ModifyDaoConfigProposal_execute) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::Dao;
-use 0x1::Errors;
-use 0x1::Signer;
-use 0x1::Token;
-
- - - - - -## Resource `DaoConfigModifyCapability` - -A wrapper of Config::ModifyConfigCapability<Dao::DaoConfig<TokenT>>. - - -
struct DaoConfigModifyCapability<TokenT: copy, drop, store> has key
-
- - - -
-Fields - - -
-
-cap: Config::ModifyConfigCapability<Dao::DaoConfig<TokenT>> -
-
- -
-
- - -
- - - -## Struct `DaoConfigUpdate` - -a proposal action to update dao config. -if any field is 0, that means the proposal want to update. - - -
struct DaoConfigUpdate has copy, drop, store
-
- - - -
-Fields - - -
-
-voting_delay: u64 -
-
- new voting delay setting. -
-
-voting_period: u64 -
-
- new voting period setting. -
-
-voting_quorum_rate: u8 -
-
- new voting quorum rate setting. -
-
-min_action_delay: u64 -
-
- new min action delay setting. -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 401;
-
- - - - - - - -
const ERR_QUORUM_RATE_INVALID: u64 = 402;
-
- - - - - -## Function `plugin` - -Plugin method of the module. -Should be called by token issuer. - - -
public fun plugin<TokenT: copy, drop, store>(signer: &signer)
-
- - - -
-Implementation - - -
public fun plugin<TokenT: copy + drop + store>(signer: &signer) {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    let dao_config_modify_cap = Config::extract_modify_config_capability<
-        Dao::DaoConfig<TokenT>,
-    >(signer);
-    assert!(Config::account_address(&dao_config_modify_cap) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    let cap = DaoConfigModifyCapability { cap: dao_config_modify_cap };
-    move_to(signer, cap);
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-let sender = Signer::address_of(signer);
-aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS();
-include Config::AbortsIfCapNotExist<Dao::DaoConfig<TokenT>>{address: sender};
-let config_cap = Config::spec_cap<Dao::DaoConfig<TokenT>>(sender);
-aborts_if Option::is_none(config_cap);
-aborts_if Option::borrow(config_cap).account_address != sender;
-aborts_if exists<DaoConfigModifyCapability<TokenT>>(sender);
-ensures exists<DaoConfigModifyCapability<TokenT>>(sender);
-
- - - -
- - - -## Function `destroy_modify_config_capability` - -Destroy ModifyConfigCapability - - -
public fun destroy_modify_config_capability<TokenT: copy, drop, store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun destroy_modify_config_capability<TokenT: copy + drop + store>(sender: &signer)
-acquires DaoConfigModifyCapability {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-
-    let DaoConfigModifyCapability {cap} = move_from<DaoConfigModifyCapability<TokenT>>(token_issuer);
-    Config::destroy_modify_config_capability<DaoConfig<TokenT>>(cap);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose` - -Entrypoint for the proposal. - - -
public(script) fun propose<TokenT: copy, drop, store>(signer: signer, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun propose<TokenT: copy + drop + store>(
-    signer: signer,
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-    exec_delay: u64,
-) {
-    assert!(voting_quorum_rate <= 100, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID));
-    let action = DaoConfigUpdate {
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-    };
-    Dao::propose<TokenT, DaoConfigUpdate>(&signer, action, exec_delay);
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-aborts_if voting_quorum_rate > 100;
-include Dao::AbortIfDaoConfigNotExist<TokenT>;
-include Dao::AbortIfDaoInfoNotExist<TokenT>;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config<TokenT>().min_action_delay;
-include Dao::CheckQuorumVotes<TokenT>;
-let sender = Signer::address_of(signer);
-aborts_if exists<Dao::Proposal<TokenT, DaoConfigUpdate>>(sender);
-
- - - -
- - - -## Function `execute` - -Once the proposal is agreed, anyone can call the method to make the proposal happen. - - -
public(script) fun execute<TokenT: copy, drop, store>(proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute<TokenT: copy + drop + store>(proposer_address: address, proposal_id: u64)
-acquires DaoConfigModifyCapability {
-    let DaoConfigUpdate {
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-    } = Dao::extract_proposal_action<TokenT, DaoConfigUpdate>(proposer_address, proposal_id);
-    let cap = borrow_global_mut<DaoConfigModifyCapability<TokenT>>(
-        Token::token_address<TokenT>(),
-    );
-    Dao::modify_dao_config(
-        &mut cap.cap,
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-    );
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = true;
-aborts_if !exists<DaoConfigModifyCapability<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-pragma aborts_if_is_partial;
-
diff --git a/release/v12/docs/ModuleUpgradeScripts.md b/release/v12/docs/ModuleUpgradeScripts.md deleted file mode 100644 index cbca2aef..00000000 --- a/release/v12/docs/ModuleUpgradeScripts.md +++ /dev/null @@ -1,314 +0,0 @@ - - - -# Module `0x1::ModuleUpgradeScripts` - - - -- [Constants](#@Constants_0) -- [Function `propose_module_upgrade_v2`](#0x1_ModuleUpgradeScripts_propose_module_upgrade_v2) -- [Function `update_module_upgrade_strategy`](#0x1_ModuleUpgradeScripts_update_module_upgrade_strategy) -- [Function `update_module_upgrade_strategy_with_min_time`](#0x1_ModuleUpgradeScripts_update_module_upgrade_strategy_with_min_time) -- [Function `submit_module_upgrade_plan`](#0x1_ModuleUpgradeScripts_submit_module_upgrade_plan) -- [Function `execute_module_upgrade_plan_propose`](#0x1_ModuleUpgradeScripts_execute_module_upgrade_plan_propose) -- [Function `submit_upgrade_plan`](#0x1_ModuleUpgradeScripts_submit_upgrade_plan) -- [Function `cancel_upgrade_plan`](#0x1_ModuleUpgradeScripts_cancel_upgrade_plan) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::Errors;
-use 0x1::Option;
-use 0x1::PackageTxnManager;
-use 0x1::Signer;
-use 0x1::UpgradeModuleDaoProposal;
-use 0x1::Version;
-
- - - - - -## Constants - - - - - - -
const ERR_WRONG_UPGRADE_STRATEGY: u64 = 100;
-
- - - - - -## Function `propose_module_upgrade_v2` - - - -
public(script) fun propose_module_upgrade_v2<Token: copy, drop, store>(signer: signer, module_address: address, package_hash: vector<u8>, version: u64, exec_delay: u64, enforced: bool)
-
- - - -
-Implementation - - -
public(script) fun propose_module_upgrade_v2<Token: copy + drop + store>(
-    signer: signer,
-    module_address: address,
-    package_hash: vector<u8>,
-    version: u64,
-    exec_delay: u64,
-    enforced: bool,
-) {
-    UpgradeModuleDaoProposal::propose_module_upgrade_v2<Token>(
-        &signer,
-        module_address,
-        package_hash,
-        version,
-        exec_delay,
-        enforced
-    );
-}
-
- - - -
- - - -## Function `update_module_upgrade_strategy` - -Update sender's module upgrade strategy to strategy - - -
public(script) fun update_module_upgrade_strategy(sender: signer, strategy: u8)
-
- - - -
-Implementation - - -
public(script) fun update_module_upgrade_strategy(
-    sender: signer,
-    strategy: u8,
-) {
-    // 1. check version
-    if (strategy == PackageTxnManager::get_strategy_two_phase()) {
-        if (!Config::config_exist_by_address<Version::Version>(Signer::address_of(&sender))) {
-            Config::publish_new_config<Version::Version>(&sender, Version::new_version(1));
-        }
-    };
-
-    // 2. update strategy
-    PackageTxnManager::update_module_upgrade_strategy(
-        &sender,
-        strategy,
-        Option::none<u64>(),
-    );
-}
-
- - - -
- - - -## Function `update_module_upgrade_strategy_with_min_time` - -Update sender's module upgrade strategy to strategy with min_time_limit. -This can only be invoked when strategy is STRATEGY_TWO_PHASE. - - -
public(script) fun update_module_upgrade_strategy_with_min_time(sender: signer, strategy: u8, min_time_limit: u64)
-
- - - -
-Implementation - - -
public(script) fun update_module_upgrade_strategy_with_min_time(
-    sender: signer,
-    strategy: u8,
-    min_time_limit: u64,
-){
-    // 1. check version
-    assert!(strategy == PackageTxnManager::get_strategy_two_phase(), Errors::invalid_argument(ERR_WRONG_UPGRADE_STRATEGY));
-    // 2. update strategy
-    PackageTxnManager::update_module_upgrade_strategy(
-        &sender,
-        strategy,
-        Option::some<u64>(min_time_limit),
-    );
-}
-
- - - -
- - - -## Function `submit_module_upgrade_plan` - -a alias of execute_module_upgrade_plan_propose, will deprecated in the future. - - -
public(script) fun submit_module_upgrade_plan<Token: copy, drop, store>(sender: signer, proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun submit_module_upgrade_plan<Token: copy + drop + store>(
-    sender: signer,
-    proposer_address: address,
-    proposal_id: u64,
-) {
-    Self::execute_module_upgrade_plan_propose<Token>(sender, proposer_address, proposal_id);
-}
-
- - - -
- - - -## Function `execute_module_upgrade_plan_propose` - -Execute module upgrade plan propose by submit module upgrade plan, the propose must been agreed, and anyone can execute this function. - - -
public(script) fun execute_module_upgrade_plan_propose<Token: copy, drop, store>(_sender: signer, proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_module_upgrade_plan_propose<Token: copy + drop + store>(
-    _sender: signer,
-    proposer_address: address,
-    proposal_id: u64,
-) {
-    UpgradeModuleDaoProposal::submit_module_upgrade_plan<Token>(proposer_address, proposal_id);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `submit_upgrade_plan` - -Directly submit a upgrade plan, the sender's module upgrade plan must been PackageTxnManager::STRATEGY_TWO_PHASE and have UpgradePlanCapability - - -
public(script) fun submit_upgrade_plan(sender: signer, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public(script) fun submit_upgrade_plan(sender: signer, package_hash: vector<u8>, version:u64, enforced: bool) {
-    PackageTxnManager::submit_upgrade_plan_v2(&sender, package_hash, version, enforced);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `cancel_upgrade_plan` - -Cancel current upgrade plan, the sender must have UpgradePlanCapability. - - -
public(script) fun cancel_upgrade_plan(signer: signer)
-
- - - -
-Implementation - - -
public(script) fun cancel_upgrade_plan(
-    signer: signer,
-) {
-    PackageTxnManager::cancel_upgrade_plan(&signer);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_partial = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/NFT.md b/release/v12/docs/NFT.md deleted file mode 100644 index 3cca6422..00000000 --- a/release/v12/docs/NFT.md +++ /dev/null @@ -1,104 +0,0 @@ - - - -# Module `0x1::NFTGalleryScripts` - - - -- [Function `accept`](#0x1_NFTGalleryScripts_accept) -- [Function `transfer`](#0x1_NFTGalleryScripts_transfer) -- [Function `remove_empty_gallery`](#0x1_NFTGalleryScripts_remove_empty_gallery) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::NFTGallery;
-
- - - - - -## Function `accept` - -Init a NFTGallery for accept NFT - - -
public(script) fun accept<NFTMeta: copy, drop, store, NFTBody: store>(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun accept<NFTMeta: copy + store + drop, NFTBody: store>(sender: signer) {
-    NFTGallery::accept_entry<NFTMeta, NFTBody>(sender);
-}
-
- - - -
- - - -## Function `transfer` - -Transfer NFT with id from sender to receiver - - -
public(script) fun transfer<NFTMeta: copy, drop, store, NFTBody: store>(sender: signer, id: u64, receiver: address)
-
- - - -
-Implementation - - -
public(script) fun transfer<NFTMeta: copy + store + drop, NFTBody: store>(
-    sender: signer,
-    id: u64, receiver: address
-) {
-    NFTGallery::transfer_entry<NFTMeta, NFTBody>(sender, id, receiver);
-}
-
- - - -
- - - -## Function `remove_empty_gallery` - -Remove empty NFTGallery. - - -
public(script) fun remove_empty_gallery<NFTMeta: copy, drop, store, NFTBody: store>(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun remove_empty_gallery<NFTMeta: copy + store + drop, NFTBody: store>(sender: signer) {
-    NFTGallery::remove_empty_gallery_entry<NFTMeta, NFTBody>(sender);
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-
diff --git a/release/v12/docs/Offer.md b/release/v12/docs/Offer.md deleted file mode 100644 index 4540012a..00000000 --- a/release/v12/docs/Offer.md +++ /dev/null @@ -1,1052 +0,0 @@ - - - -# Module `0x1::Offer` - - - -- [Resource `Offer`](#0x1_Offer_Offer) -- [Resource `Offers`](#0x1_Offer_Offers) -- [Struct `OfferInfo`](#0x1_Offer_OfferInfo) -- [Constants](#@Constants_0) -- [Function `create`](#0x1_Offer_create) -- [Function `create_v2`](#0x1_Offer_create_v2) -- [Function `create_offers`](#0x1_Offer_create_offers) -- [Function `push`](#0x1_Offer_push) -- [Function `redeem`](#0x1_Offer_redeem) -- [Function `redeem_v2`](#0x1_Offer_redeem_v2) -- [Function `exists_at`](#0x1_Offer_exists_at) -- [Function `exists_at_v2`](#0x1_Offer_exists_at_v2) -- [Function `address_of`](#0x1_Offer_address_of) -- [Function `address_of_v2`](#0x1_Offer_address_of_v2) -- [Function `retake`](#0x1_Offer_retake) -- [Function `get_offers_infos`](#0x1_Offer_get_offers_infos) -- [Function `get_offers_info`](#0x1_Offer_get_offers_info) -- [Function `unpack_offer_info`](#0x1_Offer_unpack_offer_info) -- [Function `get_offers_length`](#0x1_Offer_get_offers_length) -- [Function `is_offers_empty`](#0x1_Offer_is_offers_empty) -- [Function `take_offer`](#0x1_Offer_take_offer) -- [Function `find_offer`](#0x1_Offer_find_offer) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::Vector;
-
- - - - - -## Resource `Offer` - -A wrapper around value offered that can be claimed by the address stored in for when after lock time. - - -
struct Offer<Offered> has store, key
-
- - - -
-Fields - - -
-
-offered: Offered -
-
- -
-
-for: address -
-
- -
-
-time_lock: u64 -
-
- -
-
- - -
- - - -## Resource `Offers` - - - -
struct Offers<Offered: store> has key
-
- - - -
-Fields - - -
-
-offers: vector<Offer::Offer<Offered>> -
-
- -
-
- - -
- - - -## Struct `OfferInfo` - - - -
struct OfferInfo has copy, drop, store
-
- - - -
-Fields - - -
-
-for: address -
-
- -
-
-time_lock: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -An offer of the specified type for the account does not match - - -
const EOFFER_DNE_FOR_ACCOUNT: u64 = 101;
-
- - - - - - - -
const EOFFER_HAVE_OFFER: u64 = 106;
-
- - - - - - - -
const EOFFER_NOT_HAVE_OFFER: u64 = 105;
-
- - - - - -Offer is not unlocked yet. - - -
const EOFFER_NOT_UNLOCKED: u64 = 102;
-
- - - - - - - -
const EOFFER_OFFERS_ARG_LEN_NOT_SAME: u64 = 104;
-
- - - - - - - -
const EOFFER_OFFERS_EMPTY: u64 = 107;
-
- - - - - - - -
const EOFFER_OFFERS_ZERO: u64 = 103;
-
- - - - - - - -
const ERR_DEPRECATED: u64 = 1;
-
- - - - - -## Function `create` - -Publish a value of type Offered under the sender's account. The value can be claimed by -either the for address or the transaction sender. - - -
public fun create<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64)
-
- - - -
-Implementation - - -
public fun create<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offer, Offers{
-    let time_lock = Timestamp::now_seconds() + lock_period;
-    let account_address = Signer::address_of(account);
-    if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        Vector::push_back(offers, Offer<Offered> { offered, for, time_lock });
-    }else {
-        let offers = Vector::empty<Offer<Offered>>();
-        if(exists<Offer<Offered>>(account_address)){
-            Vector::push_back(&mut offers, move_from<Offer<Offered>>(account_address));
-        };
-        Vector::push_back(&mut offers, Offer<Offered> { offered, for, time_lock });
-        move_to(account, Offers<Offered> { offers });
-    }
-}
-
- - - -
- -
-Specification - - - -
include Timestamp::AbortsIfTimestampNotExists;
-aborts_if Timestamp::now_seconds() + lock_period > max_u64();
-aborts_if exists<Offer<Offered>>(Signer::address_of(account));
-
- - - -
- - - -## Function `create_v2` - - - -
public fun create_v2<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64)
-
- - - -
-Implementation - - -
public fun create_v2<Offered: store>(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offers, Offer{
-    let account_address = Signer::address_of(account);
-    let time_lock = Timestamp::now_seconds() + lock_period;
-
-    if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        Vector::push_back(offers, Offer<Offered> { offered, for, time_lock });
-    }else {
-        let offers = Vector::empty<Offer<Offered>>();
-        if(exists<Offer<Offered>>(account_address)){
-            Vector::push_back(&mut offers, move_from<Offer<Offered>>(account_address));
-        };
-        Vector::push_back(&mut offers, Offer<Offered> { offered, for, time_lock });
-        move_to(account, Offers<Offered> { offers });
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `create_offers` - - - -
public fun create_offers<Offered: store>(account: &signer, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>)
-
- - - -
-Implementation - - -
public fun create_offers<Offered: store>(account: &signer, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>) acquires Offers, Offer {
-    let offer_length = Vector::length(&offereds);
-    assert!(offer_length > 0, Errors::invalid_argument(EOFFER_OFFERS_ZERO));
-    assert!(offer_length == Vector::length(&for) && offer_length == Vector::length(&lock_periods), Errors::invalid_argument(EOFFER_OFFERS_ARG_LEN_NOT_SAME));
-    let account_address = Signer::address_of(account);
-
-    if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        push(offers, offereds, for, lock_periods);
-    }else {
-        let offers = Vector::empty<Offer<Offered>>();
-        if(exists<Offer<Offered>>(account_address)){
-            Vector::push_back(&mut offers, move_from<Offer<Offered>>(account_address));
-        };
-        push(&mut offers, offereds, for, lock_periods);
-        move_to(account, Offers<Offered> { offers });
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `push` - - - -
fun push<Offered: store>(offers: &mut vector<Offer::Offer<Offered>>, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>)
-
- - - -
-Implementation - - -
fun push<Offered: store>(offers: &mut vector<Offer<Offered>>, offereds: vector<Offered>, for: vector<address>, lock_periods: vector<u64>){
-    let now = Timestamp::now_seconds();
-    let offer_length = Vector::length(&offereds);
-
-    let i = offer_length - 1;
-    loop{
-        Vector::push_back(offers, Offer<Offered> {
-            offered: Vector::remove(&mut offereds, i),
-            for: Vector::remove(&mut for, i),
-            time_lock: now + Vector::remove(&mut lock_periods, i)
-        });
-        if(i == 0){
-            break
-        };
-        i = i - 1;
-    };
-    Vector::destroy_empty(offereds);
-    Vector::destroy_empty(for);
-    Vector::destroy_empty(lock_periods);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `redeem` - -Claim the value of type Offered published at offer_address. -Only succeeds if the sender is the intended recipient stored in for or the original -publisher offer_address, and now >= time_lock -Also fails if no such value exists. - - -
public fun redeem<Offered: store>(account: &signer, offer_address: address): Offered
-
- - - -
-Implementation - - -
public fun redeem<Offered: store>(account: &signer, offer_address: address): Offered acquires Offer, Offers {
-    let account_address = Signer::address_of(account);
-    let Offer<Offered> { offered, for, time_lock } = if(exists<Offers<Offered>>(offer_address)){
-        let op_index = find_offer<Offered>(offer_address, account_address);
-        assert!(Option::is_some(&op_index),Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT));
-        let offers = &mut borrow_global_mut<Offers<Offered>>(offer_address).offers;
-        let index = Option::destroy_some(op_index);
-        let offer = Vector::remove(offers , index);
-        if(Vector::length(offers) == 0){
-            let Offers { offers } = move_from<Offers<Offered>>(offer_address);
-            Vector::destroy_empty(offers);
-        };
-        offer
-    }else if(exists<Offer<Offered>>(offer_address)){
-        move_from<Offer<Offered>>(offer_address)
-    }else{
-        abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)
-    };
-
-    let now = Timestamp::now_seconds();
-    assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT));
-    assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED));
-    offered
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Offer<Offered>>(offer_address);
-aborts_if Signer::address_of(account) != global<Offer<Offered>>(offer_address).for && Signer::address_of(account) != offer_address;
-aborts_if Timestamp::now_seconds() < global<Offer<Offered>>(offer_address).time_lock;
-include Timestamp::AbortsIfTimestampNotExists;
-
- - - -
- - - -## Function `redeem_v2` - - - -
public fun redeem_v2<Offered: store>(account: &signer, offer_address: address, idx: u64): Offered
-
- - - -
-Implementation - - -
public fun redeem_v2<Offered: store>(account: &signer, offer_address: address, idx: u64): Offered acquires Offer, Offers {
-    let account_address = Signer::address_of(account);
-    let Offer<Offered> { offered, for, time_lock } = if(exists<Offers<Offered>>(offer_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(offer_address).offers;
-        assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-        let offer = Vector::remove(offers, idx);
-        if(Vector::length(offers) == 0){
-            let Offers { offers } = move_from<Offers<Offered>>(offer_address);
-            Vector::destroy_empty(offers);
-        };
-        offer
-    }else if(exists<Offer<Offered>>(offer_address)){
-        move_from<Offer<Offered>>(offer_address)
-    }else{
-        abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)
-    };
-
-    let now = Timestamp::now_seconds();
-    assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT));
-    assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED));
-    offered
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `exists_at` - -Returns true if an offer of type Offered exists at offer_address. - - -
public fun exists_at<Offered: store>(offer_address: address): bool
-
- - - -
-Implementation - - -
public fun exists_at<Offered: store>(offer_address: address): bool {
-    exists<Offer<Offered>>(offer_address) || exists<Offers<Offered>>(offer_address)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `exists_at_v2` - - - -
public fun exists_at_v2<Offered: store>(offer_address: address): bool
-
- - - -
-Implementation - - -
public fun exists_at_v2<Offered: store>(offer_address: address): bool{
-    exists<Offers<Offered>>(offer_address)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `address_of` - -Returns the address of the Offered type stored at offer_address. -Fails if no such Offer exists. - - -
public fun address_of<Offered: store>(offer_address: address): address
-
- - - -
-Implementation - - -
public fun address_of<Offered: store>(offer_address: address): address acquires Offer, Offers {
-    if(exists<Offer<Offered>>(offer_address)){
-        borrow_global<Offer<Offered>>(offer_address).for
-    }else{
-        assert!(!is_offers_empty<Offered>(offer_address), Errors::invalid_argument(EOFFER_OFFERS_EMPTY));
-        address_of_v2<Offered>(offer_address, get_offers_length<Offered>(offer_address) - 1)
-    }
-
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Offer<Offered>>(offer_address);
-aborts_if !exists<Offers<Offered>>(offer_address);
-
- - - -
- - - -## Function `address_of_v2` - - - -
public fun address_of_v2<Offered: store>(offer_address: address, idx: u64): address
-
- - - -
-Implementation - - -
public fun address_of_v2<Offered: store>(offer_address: address, idx: u64): address acquires Offers {
-    assert!(exists<Offers<Offered>>(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    Vector::borrow(offers, idx).for
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `retake` - - - -
public fun retake<Offered: store>(account: &signer, idx: u64): Offered
-
- - - -
-Implementation - - -
public fun retake<Offered: store>(account: &signer, idx: u64): Offered acquires Offer, Offers {
-    let account_address = Signer::address_of(account);
-    let Offer<Offered> { offered: offered, for: _, time_lock: time_lock } = if(exists<Offers<Offered>>(account_address)){
-        let offers = &mut borrow_global_mut<Offers<Offered>>(account_address).offers;
-        assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-        let offer = Vector::remove(offers, idx);
-        if(Vector::length(offers) == 0){
-            let Offers { offers } = move_from<Offers<Offered>>(account_address);
-            Vector::destroy_empty(offers);
-        };
-        offer
-    }else if(exists<Offer<Offered>>(account_address)){
-        move_from<Offer<Offered>>(account_address)
-    }else{
-        abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)
-    };
-    let now = Timestamp::now_seconds();
-    assert!(now >= time_lock + ( 3600 * 24 * 30 * 3 ), Errors::not_published(EOFFER_NOT_UNLOCKED));
-    offered
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_offers_infos` - - - -
public fun get_offers_infos<Offered: store>(offer_address: address): Option::Option<vector<Offer::OfferInfo>>
-
- - - -
-Implementation - - -
public fun get_offers_infos<Offered: store>(offer_address: address): Option::Option<vector<OfferInfo>> acquires Offers{
-    if(!exists_at_v2<Offered>(offer_address)){
-        return Option::none<vector<OfferInfo>>()
-    };
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    let offer_infos = Vector::empty<OfferInfo>();
-    let i = 0;
-    let length = Vector::length(offers);
-    while(i < length){
-        Vector::push_back(&mut offer_infos, OfferInfo { for: Vector::borrow(offers, i).for, time_lock: Vector::borrow(offers, i).time_lock });
-        i = i + 1;
-    };
-    Option::some(offer_infos)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_offers_info` - - - -
public fun get_offers_info<Offered: store>(offer_address: address, idx: u64): Option::Option<Offer::OfferInfo>
-
- - - -
-Implementation - - -
public fun get_offers_info<Offered: store>(offer_address: address, idx: u64): Option::Option<OfferInfo> acquires Offers{
-    if(!exists_at_v2<Offered>(offer_address)){
-        return Option::none<OfferInfo>()
-    };
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    assert!(Vector::length(offers) >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    Option::some(OfferInfo { for: Vector::borrow(offers, idx).for, time_lock: Vector::borrow(offers, idx).time_lock })
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `unpack_offer_info` - - - -
public fun unpack_offer_info(offer_info: Offer::OfferInfo): (address, u64)
-
- - - -
-Implementation - - -
public fun unpack_offer_info(offer_info: OfferInfo):(address, u64){
-    let OfferInfo{ for, time_lock } = offer_info;
-    ( for, time_lock )
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `get_offers_length` - - - -
public fun get_offers_length<Offered: store>(offer_address: address): u64
-
- - - -
-Implementation - - -
public fun get_offers_length<Offered: store>(offer_address: address): u64 acquires Offers{
-    assert!(exists_at_v2<Offered>(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER));
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    Vector::length(offers)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `is_offers_empty` - - - -
public fun is_offers_empty<Offered: store>(offer_address: address): bool
-
- - - -
-Implementation - - -
public fun is_offers_empty<Offered: store>(offer_address: address): bool acquires Offers{
-    if( get_offers_length<Offered>(offer_address) == 0){
-        true
-    }else{
-        false
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `take_offer` - -Take Offer and put to signer's Collection. - - -
public(script) fun take_offer<Offered: store>(_signer: signer, _offer_address: address)
-
- - - -
-Implementation - - -
public(script) fun take_offer<Offered: store>(_signer: signer, _offer_address: address){
-    abort Errors::invalid_state(ERR_DEPRECATED)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `find_offer` - - - -
public fun find_offer<Offered: store>(offer_address: address, for: address): Option::Option<u64>
-
- - - -
-Implementation - - -
public fun find_offer<Offered: store>(offer_address: address, for: address):Option::Option<u64> acquires Offers {
-    if(!exists_at_v2<Offered>(offer_address)){
-        return Option::none<u64>()
-    };
-    let offers = & borrow_global<Offers<Offered>>(offer_address).offers;
-    let length = Vector::length(offers);
-    let i = 0;
-    while(i < length){
-        let offer = Vector::borrow(offers, i);
-        if( offer.for == for ){
-            return Option::some(i)
-        };
-        i = i + 1;
-    };
-    Option::none<u64>()
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/OnChainConfigDao.md b/release/v12/docs/OnChainConfigDao.md deleted file mode 100644 index 90a98f79..00000000 --- a/release/v12/docs/OnChainConfigDao.md +++ /dev/null @@ -1,284 +0,0 @@ - - - -# Module `0x1::OnChainConfigDao` - -OnChainConfigDao is a DAO proposal for modify onchain configuration. - - -- [Resource `WrappedConfigModifyCapability`](#0x1_OnChainConfigDao_WrappedConfigModifyCapability) -- [Struct `OnChainConfigUpdate`](#0x1_OnChainConfigDao_OnChainConfigUpdate) -- [Constants](#@Constants_0) -- [Function `plugin`](#0x1_OnChainConfigDao_plugin) -- [Function `propose_update`](#0x1_OnChainConfigDao_propose_update) -- [Function `execute`](#0x1_OnChainConfigDao_execute) -- [Function `config_cap`](#0x1_OnChainConfigDao_config_cap) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Dao;
-use 0x1::Errors;
-use 0x1::Signer;
-use 0x1::Token;
-
- - - - - -## Resource `WrappedConfigModifyCapability` - -A wrapper of Config::ModifyConfigCapability<ConfigT>. - - -
struct WrappedConfigModifyCapability<TokenT, ConfigT: copy, drop, store> has key
-
- - - -
-Fields - - -
-
-cap: Config::ModifyConfigCapability<ConfigT> -
-
- -
-
- - -
- - - -## Struct `OnChainConfigUpdate` - -request of updating configuration. - - -
struct OnChainConfigUpdate<ConfigT: copy, drop, store> has copy, drop, store
-
- - - -
-Fields - - -
-
-value: ConfigT -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 401;
-
- - - - - -## Function `plugin` - -Plugin method of the module. -Should be called by token issuer. - - -
public fun plugin<TokenT: copy, drop, store, ConfigT: copy, drop, store>(signer: &signer)
-
- - - -
-Implementation - - -
public fun plugin<TokenT: copy + drop + store, ConfigT: copy + drop + store>(signer: &signer) {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    let config_modify_cap = Config::extract_modify_config_capability<ConfigT>(signer);
-    let cap = WrappedConfigModifyCapability<TokenT, ConfigT> { cap: config_modify_cap };
-    move_to(signer, cap);
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-let sender = Signer::address_of(signer);
-aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS();
-include Config::AbortsIfCapNotExist<ConfigT>{address: sender};
-aborts_if exists<WrappedConfigModifyCapability<TokenT, ConfigT>>(sender);
-ensures exists<WrappedConfigModifyCapability<TokenT, ConfigT>>(sender);
-
- - - -
- - - -## Function `propose_update` - -issue a proposal to update config of ConfigT goved by TokenT - - -
public fun propose_update<TokenT: copy, drop, store, ConfigT: copy, drop, store>(signer: &signer, new_config: ConfigT, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_update<TokenT: copy + drop + store, ConfigT: copy + drop + store>(
-    signer: &signer,
-    new_config: ConfigT,
-    exec_delay: u64,
-) {
-    Dao::propose<TokenT, OnChainConfigUpdate<ConfigT>>(
-        signer,
-        OnChainConfigUpdate { value: new_config },
-        exec_delay,
-    );
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-include Dao::AbortIfDaoConfigNotExist<TokenT>;
-include Dao::AbortIfDaoInfoNotExist<TokenT>;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config<TokenT>().min_action_delay;
-include Dao::CheckQuorumVotes<TokenT>;
-let sender = Signer::address_of(signer);
-aborts_if exists<Dao::Proposal<TokenT, OnChainConfigUpdate<ConfigT>>>(sender);
-
- - - -
- - - -## Function `execute` - -Once the proposal is agreed, anyone can call the method to make the proposal happen. -Caller need to make sure that the proposal of proposal_id under proposal_address is -the kind of this proposal module. - - -
public fun execute<TokenT: copy, drop, store, ConfigT: copy, drop, store>(proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute<TokenT: copy + drop + store, ConfigT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-) acquires WrappedConfigModifyCapability {
-    let OnChainConfigUpdate { value } = Dao::extract_proposal_action<
-        TokenT,
-        OnChainConfigUpdate<ConfigT>,
-    >(proposer_address, proposal_id);
-    let cap = borrow_global_mut<WrappedConfigModifyCapability<TokenT, ConfigT>>(
-        Token::token_address<TokenT>(),
-    );
-    Config::set_with_capability(&mut cap.cap, value);
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = true;
-let expected_states = vec<u8>(6);
-include Dao::CheckProposalStates<TokenT, OnChainConfigUpdate<ConfigT>>{expected_states};
-aborts_if !exists<WrappedConfigModifyCapability<TokenT, ConfigT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-
- - - -
- - - -## Function `config_cap` - - - -
public(friend) fun config_cap<TokenT: store, ConfigT: copy, drop, store>(): Config::ModifyConfigCapability<ConfigT>
-
- - - -
-Implementation - - -
public (friend) fun config_cap<TokenT: store, ConfigT: copy + drop + store>():Config::ModifyConfigCapability<ConfigT>acquires WrappedConfigModifyCapability{
-    let WrappedConfigModifyCapability <TokenT, ConfigT>{cap} = move_from<WrappedConfigModifyCapability<TokenT, ConfigT>>(CoreAddresses::GENESIS_ADDRESS());
-    cap
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-pragma aborts_if_is_partial;
-
diff --git a/release/v12/docs/OnChainConfigScripts.md b/release/v12/docs/OnChainConfigScripts.md deleted file mode 100644 index ac5b8334..00000000 --- a/release/v12/docs/OnChainConfigScripts.md +++ /dev/null @@ -1,378 +0,0 @@ - - - -# Module `0x1::OnChainConfigScripts` - - - -- [Function `propose_update_consensus_config`](#0x1_OnChainConfigScripts_propose_update_consensus_config) -- [Function `propose_update_reward_config`](#0x1_OnChainConfigScripts_propose_update_reward_config) -- [Function `propose_update_txn_publish_option`](#0x1_OnChainConfigScripts_propose_update_txn_publish_option) -- [Function `propose_update_txn_timeout_config`](#0x1_OnChainConfigScripts_propose_update_txn_timeout_config) -- [Function `propose_update_vm_config`](#0x1_OnChainConfigScripts_propose_update_vm_config) -- [Function `propose_update_move_language_version`](#0x1_OnChainConfigScripts_propose_update_move_language_version) -- [Function `execute_on_chain_config_proposal`](#0x1_OnChainConfigScripts_execute_on_chain_config_proposal) -- [Function `execute_on_chain_config_proposal_v2`](#0x1_OnChainConfigScripts_execute_on_chain_config_proposal_v2) - - -
use 0x1::ConsensusConfig;
-use 0x1::LanguageVersion;
-use 0x1::OnChainConfigDao;
-use 0x1::RewardConfig;
-use 0x1::STC;
-use 0x1::Signer;
-use 0x1::TransactionPublishOption;
-use 0x1::TransactionTimeoutConfig;
-use 0x1::VMConfig;
-
- - - - - -## Function `propose_update_consensus_config` - - - -
public(script) fun propose_update_consensus_config(account: signer, uncle_rate_target: u64, base_block_time_target: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, epoch_block_count: u64, base_block_difficulty_window: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_consensus_config(account: signer,
-                                                      uncle_rate_target: u64,
-                                                      base_block_time_target: u64,
-                                                      base_reward_per_block: u128,
-                                                      base_reward_per_uncle_percent: u64,
-                                                      epoch_block_count: u64,
-                                                      base_block_difficulty_window: u64,
-                                                      min_block_time_target: u64,
-                                                      max_block_time_target: u64,
-                                                      base_max_uncles_per_block: u64,
-                                                      base_block_gas_limit: u64,
-                                                      strategy: u8,
-                                                      exec_delay: u64) {
-    let consensus_config = ConsensusConfig::new_consensus_config(uncle_rate_target,
-        base_block_time_target,
-        base_reward_per_block,
-        base_reward_per_uncle_percent,
-        epoch_block_count,
-        base_block_difficulty_window,
-        min_block_time_target,
-        max_block_time_target,
-        base_max_uncles_per_block,
-        base_block_gas_limit,
-        strategy);
-    OnChainConfigDao::propose_update<STC::STC, ConsensusConfig::ConsensusConfig>(&account, consensus_config, exec_delay);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_reward_config` - - - -
public(script) fun propose_update_reward_config(account: signer, reward_delay: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_reward_config(account: signer,
-                                                   reward_delay: u64,
-                                                   exec_delay: u64) {
-    let reward_config = RewardConfig::new_reward_config(reward_delay);
-    OnChainConfigDao::propose_update<STC::STC, RewardConfig::RewardConfig>(&account, reward_config, exec_delay);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_txn_publish_option` - - - -
public(script) fun propose_update_txn_publish_option(account: signer, script_allowed: bool, module_publishing_allowed: bool, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_txn_publish_option(account: signer,
-                                                        script_allowed: bool,
-                                                        module_publishing_allowed: bool,
-                                                        exec_delay: u64) {
-    let txn_publish_option = TransactionPublishOption::new_transaction_publish_option(script_allowed, module_publishing_allowed);
-    OnChainConfigDao::propose_update<STC::STC, TransactionPublishOption::TransactionPublishOption>(&account, txn_publish_option, exec_delay);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_txn_timeout_config` - - - -
public(script) fun propose_update_txn_timeout_config(account: signer, duration_seconds: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_txn_timeout_config(account: signer,
-                                                        duration_seconds: u64,
-                                                        exec_delay: u64) {
-    let txn_timeout_config = TransactionTimeoutConfig::new_transaction_timeout_config(duration_seconds);
-    OnChainConfigDao::propose_update<STC::STC, TransactionTimeoutConfig::TransactionTimeoutConfig>(&account, txn_timeout_config, exec_delay);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_vm_config` - - - -
public(script) fun propose_update_vm_config(account: signer, instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_vm_config(account: signer,
-                                               instruction_schedule: vector<u8>,
-                                               native_schedule: vector<u8>,
-                                               global_memory_per_byte_cost: u64,
-                                               global_memory_per_byte_write_cost: u64,
-                                               min_transaction_gas_units: u64,
-                                               large_transaction_cutoff: u64,
-                                               instrinsic_gas_per_byte: u64,
-                                               maximum_number_of_gas_units: u64,
-                                               min_price_per_gas_unit: u64,
-                                               max_price_per_gas_unit: u64,
-                                               max_transaction_size_in_bytes: u64,
-                                               gas_unit_scaling_factor: u64,
-                                               default_account_size: u64,
-                                               exec_delay: u64, ) {
-    let vm_config = VMConfig::new_vm_config(instruction_schedule,
-        native_schedule,
-        global_memory_per_byte_cost,
-        global_memory_per_byte_write_cost,
-        min_transaction_gas_units,
-        large_transaction_cutoff,
-        instrinsic_gas_per_byte,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit,
-        max_transaction_size_in_bytes,
-        gas_unit_scaling_factor,
-        default_account_size);
-    OnChainConfigDao::propose_update<STC::STC, VMConfig::VMConfig>(&account, vm_config, exec_delay);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_move_language_version` - - - -
public(script) fun propose_update_move_language_version(account: signer, new_version: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun propose_update_move_language_version(account: signer, new_version: u64, exec_delay: u64) {
-    let lang_version = LanguageVersion::new(new_version);
-    OnChainConfigDao::propose_update<STC::STC, LanguageVersion::LanguageVersion>(&account, lang_version, exec_delay);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `execute_on_chain_config_proposal` - - - -
public(script) fun execute_on_chain_config_proposal<ConfigT: copy, drop, store>(account: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public ( script ) fun execute_on_chain_config_proposal<ConfigT: copy + drop + store>(account: signer, proposal_id: u64) {
-    OnChainConfigDao::execute<STC::STC, ConfigT>(Signer::address_of(&account), proposal_id);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `execute_on_chain_config_proposal_v2` - - - -
public(script) fun execute_on_chain_config_proposal_v2<TokenType: copy, drop, store, ConfigT: copy, drop, store>(proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_on_chain_config_proposal_v2<TokenType: copy + drop + store, ConfigT: copy + drop + store>(proposer_address: address, proposal_id: u64) {
-    OnChainConfigDao::execute<TokenType, ConfigT>(proposer_address, proposal_id);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
diff --git a/release/v12/docs/OnChainStarcoinDAOConfig.md b/release/v12/docs/OnChainStarcoinDAOConfig.md deleted file mode 100644 index 42eca9db..00000000 --- a/release/v12/docs/OnChainStarcoinDAOConfig.md +++ /dev/null @@ -1,536 +0,0 @@ - - - -# Module `0x1::OnChainStarcoinDAOConfig` - - - -- [Function `propose_update_consensus_config`](#0x1_OnChainStarcoinDAOConfig_propose_update_consensus_config) -- [Function `propose_update_consensus_config_entry`](#0x1_OnChainStarcoinDAOConfig_propose_update_consensus_config_entry) -- [Function `propose_update_reward_config`](#0x1_OnChainStarcoinDAOConfig_propose_update_reward_config) -- [Function `propose_update_reward_config_entry`](#0x1_OnChainStarcoinDAOConfig_propose_update_reward_config_entry) -- [Function `propose_update_txn_publish_option`](#0x1_OnChainStarcoinDAOConfig_propose_update_txn_publish_option) -- [Function `propose_update_txn_publish_option_entry`](#0x1_OnChainStarcoinDAOConfig_propose_update_txn_publish_option_entry) -- [Function `propose_update_txn_timeout_config`](#0x1_OnChainStarcoinDAOConfig_propose_update_txn_timeout_config) -- [Function `propose_update_txn_timeout_config_entry`](#0x1_OnChainStarcoinDAOConfig_propose_update_txn_timeout_config_entry) -- [Function `propose_update_vm_config`](#0x1_OnChainStarcoinDAOConfig_propose_update_vm_config) -- [Function `propose_update_vm_config_entry`](#0x1_OnChainStarcoinDAOConfig_propose_update_vm_config_entry) -- [Function `propose_update_move_language_version`](#0x1_OnChainStarcoinDAOConfig_propose_update_move_language_version) -- [Function `propose_update_move_language_version_entry`](#0x1_OnChainStarcoinDAOConfig_propose_update_move_language_version_entry) - - -
use 0x1::ConfigProposalPlugin;
-use 0x1::ConsensusConfig;
-use 0x1::LanguageVersion;
-use 0x1::RewardConfig;
-use 0x1::StarcoinDAO;
-use 0x1::TransactionPublishOption;
-use 0x1::TransactionTimeoutConfig;
-use 0x1::VMConfig;
-
- - - - - -## Function `propose_update_consensus_config` - - - -
public fun propose_update_consensus_config(account: &signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, uncle_rate_target: u64, base_block_time_target: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, epoch_block_count: u64, base_block_difficulty_window: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_update_consensus_config(account: &signer,
-                                            title:vector<u8>,
-                                            introduction:vector<u8>,
-                                            description: vector<u8>,
-                                            uncle_rate_target: u64,
-                                            base_block_time_target: u64,
-                                            base_reward_per_block: u128,
-                                            base_reward_per_uncle_percent: u64,
-                                            epoch_block_count: u64,
-                                            base_block_difficulty_window: u64,
-                                            min_block_time_target: u64,
-                                            max_block_time_target: u64,
-                                            base_max_uncles_per_block: u64,
-                                            base_block_gas_limit: u64,
-                                            strategy: u8,
-                                            exec_delay: u64) {
-    let consensus_config = ConsensusConfig::new_consensus_config(uncle_rate_target,
-        base_block_time_target,
-        base_reward_per_block,
-        base_reward_per_uncle_percent,
-        epoch_block_count,
-        base_block_difficulty_window,
-        min_block_time_target,
-        max_block_time_target,
-        base_max_uncles_per_block,
-        base_block_gas_limit,
-        strategy);
-    ConfigProposalPlugin::create_proposal<StarcoinDAO, ConsensusConfig::ConsensusConfig>(account, title, introduction, description, exec_delay, consensus_config);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_consensus_config_entry` - - - -
public(script) fun propose_update_consensus_config_entry(account: signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, uncle_rate_target: u64, base_block_time_target: u64, base_reward_per_block: u128, base_reward_per_uncle_percent: u64, epoch_block_count: u64, base_block_difficulty_window: u64, min_block_time_target: u64, max_block_time_target: u64, base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_consensus_config_entry(account: signer,
-                                                        title:vector<u8>,
-                                                        introduction:vector<u8>,
-                                                        description: vector<u8>,
-                                                        uncle_rate_target: u64,
-                                                        base_block_time_target: u64,
-                                                        base_reward_per_block: u128,
-                                                        base_reward_per_uncle_percent: u64,
-                                                        epoch_block_count: u64,
-                                                        base_block_difficulty_window: u64,
-                                                        min_block_time_target: u64,
-                                                        max_block_time_target: u64,
-                                                        base_max_uncles_per_block: u64,
-                                                        base_block_gas_limit: u64,
-                                                        strategy: u8,
-                                                        exec_delay: u64) {
-    propose_update_consensus_config(&account,
-                                    title,
-                                    introduction,
-                                    description,
-                                    uncle_rate_target,
-                                    base_block_time_target,
-                                    base_reward_per_block,
-                                    base_reward_per_uncle_percent,
-                                    epoch_block_count,
-                                    base_block_difficulty_window,
-                                    min_block_time_target,
-                                    max_block_time_target,
-                                    base_max_uncles_per_block,
-                                    base_block_gas_limit,
-                                    strategy,
-                                    exec_delay);
-}
-
- - - -
- - - -## Function `propose_update_reward_config` - - - -
public fun propose_update_reward_config(account: &signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, reward_delay: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_update_reward_config(account: &signer,
-                                            title:vector<u8>,
-                                            introduction:vector<u8>,
-                                            description: vector<u8>,
-                                            reward_delay: u64,
-                                            exec_delay: u64) {
-    let reward_config = RewardConfig::new_reward_config(reward_delay);
-    ConfigProposalPlugin::create_proposal<StarcoinDAO, RewardConfig::RewardConfig>(account, title, introduction, description, exec_delay, reward_config);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_reward_config_entry` - - - -
public(script) fun propose_update_reward_config_entry(account: signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, reward_delay: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_reward_config_entry(account: signer,
-                                                            title:vector<u8>,
-                                                            introduction:vector<u8>,
-                                                            description: vector<u8>,
-                                                            reward_delay: u64,
-                                                            exec_delay: u64) {
-    propose_update_reward_config(&account, title, introduction, description, reward_delay, exec_delay);
-}
-
- - - -
- - - -## Function `propose_update_txn_publish_option` - - - -
public fun propose_update_txn_publish_option(account: &signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, script_allowed: bool, module_publishing_allowed: bool, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_update_txn_publish_option(account: &signer,
-                                                title:vector<u8>,
-                                                introduction:vector<u8>,
-                                                description: vector<u8>,
-                                                script_allowed: bool,
-                                                module_publishing_allowed: bool,
-                                                exec_delay: u64) {
-    let txn_publish_option = TransactionPublishOption::new_transaction_publish_option(script_allowed, module_publishing_allowed);
-    ConfigProposalPlugin::create_proposal<StarcoinDAO, TransactionPublishOption::TransactionPublishOption>(account, title, introduction, description, exec_delay, txn_publish_option);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_txn_publish_option_entry` - - - -
public(script) fun propose_update_txn_publish_option_entry(account: signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, script_allowed: bool, module_publishing_allowed: bool, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_txn_publish_option_entry(account: signer,
-                                                                title:vector<u8>,
-                                                                introduction:vector<u8>,
-                                                                description: vector<u8>,
-                                                                script_allowed: bool,
-                                                                module_publishing_allowed: bool,
-                                                                exec_delay: u64) {
-    propose_update_txn_publish_option(&account, title, introduction, description, script_allowed, module_publishing_allowed, exec_delay);
-}
-
- - - -
- - - -## Function `propose_update_txn_timeout_config` - - - -
public fun propose_update_txn_timeout_config(account: &signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, duration_seconds: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_update_txn_timeout_config(account: &signer,
-                                                title:vector<u8>,
-                                                introduction:vector<u8>,
-                                                description: vector<u8>,
-                                                duration_seconds: u64,
-                                                exec_delay: u64) {
-    let txn_timeout_config = TransactionTimeoutConfig::new_transaction_timeout_config(duration_seconds);
-    ConfigProposalPlugin::create_proposal<StarcoinDAO, TransactionTimeoutConfig::TransactionTimeoutConfig>(account, title, introduction, description, exec_delay, txn_timeout_config);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_txn_timeout_config_entry` - - - -
public(script) fun propose_update_txn_timeout_config_entry(account: signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, duration_seconds: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public ( script ) fun propose_update_txn_timeout_config_entry(account: signer,
-                                                                title:vector<u8>,
-                                                                introduction:vector<u8>,
-                                                                description: vector<u8>,
-                                                                duration_seconds: u64,
-                                                                exec_delay: u64) {
-    propose_update_txn_timeout_config(&account, title, introduction,description,duration_seconds,exec_delay);
-}
-
- - - -
- - - -## Function `propose_update_vm_config` - - - -
public fun propose_update_vm_config(account: &signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_update_vm_config(account: &signer,
-                                        title:vector<u8>,
-                                        introduction:vector<u8>,
-                                        description: vector<u8>,
-                                        instruction_schedule: vector<u8>,
-                                        native_schedule: vector<u8>,
-                                        global_memory_per_byte_cost: u64,
-                                        global_memory_per_byte_write_cost: u64,
-                                        min_transaction_gas_units: u64,
-                                        large_transaction_cutoff: u64,
-                                        instrinsic_gas_per_byte: u64,
-                                        maximum_number_of_gas_units: u64,
-                                        min_price_per_gas_unit: u64,
-                                        max_price_per_gas_unit: u64,
-                                        max_transaction_size_in_bytes: u64,
-                                        gas_unit_scaling_factor: u64,
-                                        default_account_size: u64,
-                                        exec_delay: u64, ) {
-    let vm_config = VMConfig::new_vm_config(instruction_schedule,
-        native_schedule,
-        global_memory_per_byte_cost,
-        global_memory_per_byte_write_cost,
-        min_transaction_gas_units,
-        large_transaction_cutoff,
-        instrinsic_gas_per_byte,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit,
-        max_transaction_size_in_bytes,
-        gas_unit_scaling_factor,
-        default_account_size);
-    ConfigProposalPlugin::create_proposal<StarcoinDAO, VMConfig::VMConfig>(account, title, introduction, description, exec_delay, vm_config);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_update_vm_config_entry` - - - -
public(script) fun propose_update_vm_config_entry(account: signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun propose_update_vm_config_entry(account: signer,
-                                                        title:vector<u8>,
-                                                        introduction:vector<u8>,
-                                                        description: vector<u8>,
-                                                        instruction_schedule: vector<u8>,
-                                                        native_schedule: vector<u8>,
-                                                        global_memory_per_byte_cost: u64,
-                                                        global_memory_per_byte_write_cost: u64,
-                                                        min_transaction_gas_units: u64,
-                                                        large_transaction_cutoff: u64,
-                                                        instrinsic_gas_per_byte: u64,
-                                                        maximum_number_of_gas_units: u64,
-                                                        min_price_per_gas_unit: u64,
-                                                        max_price_per_gas_unit: u64,
-                                                        max_transaction_size_in_bytes: u64,
-                                                        gas_unit_scaling_factor: u64,
-                                                        default_account_size: u64,
-                                                        exec_delay: u64, ) {
-    propose_update_vm_config(&account,
-                            title,
-                            introduction,
-                            description,
-                            instruction_schedule,
-                            native_schedule,
-                            global_memory_per_byte_cost,
-                            global_memory_per_byte_write_cost,
-                            min_transaction_gas_units,
-                            large_transaction_cutoff,
-                            instrinsic_gas_per_byte,
-                            maximum_number_of_gas_units,
-                            min_price_per_gas_unit,
-                            max_price_per_gas_unit,
-                            max_transaction_size_in_bytes,
-                            gas_unit_scaling_factor,
-                            default_account_size,
-                            exec_delay) ;
-}
-
- - - -
- - - -## Function `propose_update_move_language_version` - - - -
public fun propose_update_move_language_version(account: &signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, new_version: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_update_move_language_version(account: &signer, title:vector<u8>, introduction:vector<u8>, description: vector<u8>, new_version: u64, exec_delay: u64) {
-    let lang_version = LanguageVersion::new(new_version);
-    ConfigProposalPlugin::create_proposal<StarcoinDAO, LanguageVersion::LanguageVersion>(account, title, introduction, description, exec_delay, lang_version);
-}
-
- - - -
- - - -## Function `propose_update_move_language_version_entry` - - - -
public(script) fun propose_update_move_language_version_entry(account: signer, title: vector<u8>, introduction: vector<u8>, description: vector<u8>, new_version: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun propose_update_move_language_version_entry(account: signer, title:vector<u8>, introduction:vector<u8>, description: vector<u8>, new_version: u64, exec_delay: u64) {
-    propose_update_move_language_version(&account, title, introduction, description, new_version, exec_delay);
-}
-
- - - -
diff --git a/release/v12/docs/Option.md b/release/v12/docs/Option.md deleted file mode 100644 index 4f518c53..00000000 --- a/release/v12/docs/Option.md +++ /dev/null @@ -1,787 +0,0 @@ - - - -# Module `0x1::Option` - -This module defines the Option type and its methods to represent and handle an optional value. - - -- [Struct `Option`](#0x1_Option_Option) -- [Constants](#@Constants_0) -- [Function `none`](#0x1_Option_none) -- [Function `some`](#0x1_Option_some) -- [Function `is_none`](#0x1_Option_is_none) -- [Function `is_some`](#0x1_Option_is_some) -- [Function `contains`](#0x1_Option_contains) -- [Function `borrow`](#0x1_Option_borrow) -- [Function `borrow_with_default`](#0x1_Option_borrow_with_default) -- [Function `get_with_default`](#0x1_Option_get_with_default) -- [Function `fill`](#0x1_Option_fill) -- [Function `extract`](#0x1_Option_extract) -- [Function `borrow_mut`](#0x1_Option_borrow_mut) -- [Function `swap`](#0x1_Option_swap) -- [Function `destroy_with_default`](#0x1_Option_destroy_with_default) -- [Function `destroy_some`](#0x1_Option_destroy_some) -- [Function `destroy_none`](#0x1_Option_destroy_none) -- [Module Specification](#@Module_Specification_1) - - [Helper Schema](#@Helper_Schema_2) - - -
use 0x1::Errors;
-use 0x1::Vector;
-
- - - - - -## Struct `Option` - -Abstraction of a value that may or may not be present. Implemented with a vector of size -zero or one because Move bytecode does not have ADTs. - - -
struct Option<Element> has copy, drop, store
-
- - - -
-Fields - - -
-
-vec: vector<Element> -
-
- -
-
- - -
- -
-Specification - - -The size of vector is always less than equal to 1 -because it's 0 for "none" or 1 for "some". - - -
invariant len(vec) <= 1;
-
- - - -
- - - -## Constants - - - - -The Option is in an invalid state for the operation attempted. -The Option is Some while it should be None. - - -
const EOPTION_IS_SET: u64 = 0;
-
- - - - - -The Option is in an invalid state for the operation attempted. -The Option is None while it should be Some. - - -
const EOPTION_NOT_SET: u64 = 1;
-
- - - - - -## Function `none` - -Return an empty Option - - -
public fun none<Element>(): Option::Option<Element>
-
- - - -
-Implementation - - -
public fun none<Element>(): Option<Element> {
-    Option { vec: Vector::empty() }
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == spec_none<Element>();
-
- - - - - - - -
fun spec_none<Element>(): Option<Element> {
-   Option{ vec: vec() }
-}
-
- - - -
- - - -## Function `some` - -Return an Option containing e - - -
public fun some<Element>(e: Element): Option::Option<Element>
-
- - - -
-Implementation - - -
public fun some<Element>(e: Element): Option<Element> {
-    Option { vec: Vector::singleton(e) }
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == spec_some(e);
-
- - - - - - - -
fun spec_some<Element>(e: Element): Option<Element> {
-   Option{ vec: vec(e) }
-}
-
- - - -
- - - -## Function `is_none` - -Return true if t does not hold a value - - -
public fun is_none<Element>(t: &Option::Option<Element>): bool
-
- - - -
-Implementation - - -
public fun is_none<Element>(t: &Option<Element>): bool {
-    Vector::is_empty(&t.vec)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == is_none(t);
-
- - - -
- - - -## Function `is_some` - -Return true if t holds a value - - -
public fun is_some<Element>(t: &Option::Option<Element>): bool
-
- - - -
-Implementation - - -
public fun is_some<Element>(t: &Option<Element>): bool {
-    !Vector::is_empty(&t.vec)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == is_some(t);
-
- - - -
- - - -## Function `contains` - -Return true if the value in t is equal to e_ref -Always returns false if t does not hold a value - - -
public fun contains<Element>(t: &Option::Option<Element>, e_ref: &Element): bool
-
- - - -
-Implementation - - -
public fun contains<Element>(t: &Option<Element>, e_ref: &Element): bool {
-    Vector::contains(&t.vec, e_ref)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == spec_contains(t, e_ref);
-
- - - - - - - -
fun spec_contains<Element>(t: Option<Element>, e: Element): bool {
-   is_some(t) && borrow(t) == e
-}
-
- - - -
- - - -## Function `borrow` - -Return an immutable reference to the value inside t -Aborts if t does not hold a value - - -
public fun borrow<Element>(t: &Option::Option<Element>): &Element
-
- - - -
-Implementation - - -
public fun borrow<Element>(t: &Option<Element>): &Element {
-    assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET));
-    Vector::borrow(&t.vec, 0)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-include AbortsIfNone<Element>;
-ensures result == borrow(t);
-
- - - -
- - - -## Function `borrow_with_default` - -Return a reference to the value inside t if it holds one -Return default_ref if t does not hold a value - - -
public fun borrow_with_default<Element>(t: &Option::Option<Element>, default_ref: &Element): &Element
-
- - - -
-Implementation - - -
public fun borrow_with_default<Element>(t: &Option<Element>, default_ref: &Element): &Element {
-    let vec_ref = &t.vec;
-    if (Vector::is_empty(vec_ref)) default_ref
-    else Vector::borrow(vec_ref, 0)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == (if (is_some(t)) borrow(t) else default_ref);
-
- - - -
- - - -## Function `get_with_default` - -Return the value inside t if it holds one -Return default if t does not hold a value - - -
public fun get_with_default<Element: copy, drop>(t: &Option::Option<Element>, default: Element): Element
-
- - - -
-Implementation - - -
public fun get_with_default<Element: copy + drop>(
-    t: &Option<Element>,
-    default: Element,
-): Element {
-    let vec_ref = &t.vec;
-    if (Vector::is_empty(vec_ref)) default
-    else *Vector::borrow(vec_ref, 0)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == (if (is_some(t)) borrow(t) else default);
-
- - - -
- - - -## Function `fill` - -Convert the none option t to a some option by adding e. -Aborts if t already holds a value - - -
public fun fill<Element>(t: &mut Option::Option<Element>, e: Element)
-
- - - -
-Implementation - - -
public fun fill<Element>(t: &mut Option<Element>, e: Element) {
-    let vec_ref = &mut t.vec;
-    if (Vector::is_empty(vec_ref)) Vector::push_back(vec_ref, e)
-    else abort Errors::invalid_argument(EOPTION_IS_SET)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if is_some(t) with Errors::INVALID_ARGUMENT;
-ensures is_some(t);
-ensures borrow(t) == e;
-
- - - -
- - - -## Function `extract` - -Convert a some option to a none by removing and returning the value stored inside t -Aborts if t does not hold a value - - -
public fun extract<Element>(t: &mut Option::Option<Element>): Element
-
- - - -
-Implementation - - -
public fun extract<Element>(t: &mut Option<Element>): Element {
-    assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET));
-    Vector::pop_back(&mut t.vec)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-include AbortsIfNone<Element>;
-ensures result == borrow(old(t));
-ensures is_none(t);
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the value inside t -Aborts if t does not hold a value - - -
public fun borrow_mut<Element>(t: &mut Option::Option<Element>): &mut Element
-
- - - -
-Implementation - - -
public fun borrow_mut<Element>(t: &mut Option<Element>): &mut Element {
-    assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET));
-    Vector::borrow_mut(&mut t.vec, 0)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-include AbortsIfNone<Element>;
-ensures result == borrow(t);
-
- - - -
- - - -## Function `swap` - -Swap the old value inside t with e and return the old value -Aborts if t does not hold a value - - -
public fun swap<Element>(t: &mut Option::Option<Element>, e: Element): Element
-
- - - -
-Implementation - - -
public fun swap<Element>(t: &mut Option<Element>, e: Element): Element {
-    assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET));
-    let vec_ref = &mut t.vec;
-    let old_value = Vector::pop_back(vec_ref);
-    Vector::push_back(vec_ref, e);
-    old_value
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-include AbortsIfNone<Element>;
-ensures result == borrow(old(t));
-ensures is_some(t);
-ensures borrow(t) == e;
-
- - - -
- - - -## Function `destroy_with_default` - -Destroys t. If t holds a value, return it. Returns default otherwise - - -
public fun destroy_with_default<Element: drop>(t: Option::Option<Element>, default: Element): Element
-
- - - -
-Implementation - - -
public fun destroy_with_default<Element: drop>(t: Option<Element>, default: Element): Element {
-    let Option { vec } = t;
-    if (Vector::is_empty(&mut vec)) default
-    else Vector::pop_back(&mut vec)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if false;
-ensures result == (if (is_some(t)) borrow(t) else default);
-
- - - -
- - - -## Function `destroy_some` - -Unpack t and return its contents -Aborts if t does not hold a value - - -
public fun destroy_some<Element>(t: Option::Option<Element>): Element
-
- - - -
-Implementation - - -
public fun destroy_some<Element>(t: Option<Element>): Element {
-    assert!(is_some(&t), Errors::invalid_argument(EOPTION_NOT_SET));
-    let Option { vec } = t;
-    let elem = Vector::pop_back(&mut vec);
-    Vector::destroy_empty(vec);
-    elem
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-include AbortsIfNone<Element>;
-ensures result == borrow(t);
-
- - - -
- - - -## Function `destroy_none` - -Unpack t -Aborts if t holds a value - - -
public fun destroy_none<Element>(t: Option::Option<Element>)
-
- - - -
-Implementation - - -
public fun destroy_none<Element>(t: Option<Element>) {
-    assert!(is_none(&t), Errors::invalid_argument(EOPTION_IS_SET));
-    let Option { vec } = t;
-    Vector::destroy_empty(vec)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if is_some(t) with Errors::INVALID_ARGUMENT;
-
- - - -
- - - -## Module Specification - - - - -
pragma aborts_if_is_strict;
-
- - - - - -### Helper Schema - - - - - - -
schema AbortsIfNone<Element> {
-    t: Option<Element>;
-    aborts_if is_none(t) with Errors::INVALID_ARGUMENT;
-}
-
diff --git a/release/v12/docs/Oracle.md b/release/v12/docs/Oracle.md deleted file mode 100644 index f0066760..00000000 --- a/release/v12/docs/Oracle.md +++ /dev/null @@ -1,88 +0,0 @@ - - - -# Module `0x1::PriceOracleScripts` - - - -- [Function `register_oracle`](#0x1_PriceOracleScripts_register_oracle) -- [Function `init_data_source`](#0x1_PriceOracleScripts_init_data_source) -- [Function `update`](#0x1_PriceOracleScripts_update) - - -
use 0x1::PriceOracle;
-
- - - - - -## Function `register_oracle` - - - -
public(script) fun register_oracle<OracleT: copy, drop, store>(sender: signer, precision: u8)
-
- - - -
-Implementation - - -
public(script) fun register_oracle<OracleT: copy+store+drop>(sender: signer, precision: u8){
-    PriceOracle::register_oracle_entry<OracleT>(sender, precision);
-}
-
- - - -
- - - -## Function `init_data_source` - - - -
public(script) fun init_data_source<OracleT: copy, drop, store>(sender: signer, init_value: u128)
-
- - - -
-Implementation - - -
public(script) fun init_data_source<OracleT: copy+store+drop>(sender: signer, init_value: u128){
-    PriceOracle::init_data_source_entry<OracleT>(sender, init_value);
-}
-
- - - -
- - - -## Function `update` - - - -
public(script) fun update<OracleT: copy, drop, store>(sender: signer, value: u128)
-
- - - -
-Implementation - - -
public(script) fun update<OracleT: copy+store+drop>(sender: signer, value: u128){
-    PriceOracle::update_entry<OracleT>(sender, value);
-}
-
- - - -
diff --git a/release/v12/docs/PackageTxnManager.md b/release/v12/docs/PackageTxnManager.md deleted file mode 100644 index 2e9bafae..00000000 --- a/release/v12/docs/PackageTxnManager.md +++ /dev/null @@ -1,1590 +0,0 @@ - - - -# Module `0x1::PackageTxnManager` - -The module provides strategies for module upgrading. - - -- [Struct `UpgradePlan`](#0x1_PackageTxnManager_UpgradePlan) -- [Resource `UpgradePlanCapability`](#0x1_PackageTxnManager_UpgradePlanCapability) -- [Struct `UpgradePlanV2`](#0x1_PackageTxnManager_UpgradePlanV2) -- [Resource `ModuleUpgradeStrategy`](#0x1_PackageTxnManager_ModuleUpgradeStrategy) -- [Resource `TwoPhaseUpgrade`](#0x1_PackageTxnManager_TwoPhaseUpgrade) -- [Struct `TwoPhaseUpgradeConfig`](#0x1_PackageTxnManager_TwoPhaseUpgradeConfig) -- [Resource `TwoPhaseUpgradeV2`](#0x1_PackageTxnManager_TwoPhaseUpgradeV2) -- [Struct `UpgradeEvent`](#0x1_PackageTxnManager_UpgradeEvent) -- [Resource `UpgradePlanEventHolder`](#0x1_PackageTxnManager_UpgradePlanEventHolder) -- [Struct `UpgradePlanEvent`](#0x1_PackageTxnManager_UpgradePlanEvent) -- [Constants](#@Constants_0) -- [Function `get_strategy_arbitrary`](#0x1_PackageTxnManager_get_strategy_arbitrary) -- [Function `get_strategy_two_phase`](#0x1_PackageTxnManager_get_strategy_two_phase) -- [Function `get_strategy_new_module`](#0x1_PackageTxnManager_get_strategy_new_module) -- [Function `get_strategy_freeze`](#0x1_PackageTxnManager_get_strategy_freeze) -- [Function `get_default_min_time_limit`](#0x1_PackageTxnManager_get_default_min_time_limit) -- [Function `update_module_upgrade_strategy`](#0x1_PackageTxnManager_update_module_upgrade_strategy) -- [Function `account_address`](#0x1_PackageTxnManager_account_address) -- [Function `destroy_upgrade_plan_cap`](#0x1_PackageTxnManager_destroy_upgrade_plan_cap) -- [Function `extract_submit_upgrade_plan_cap`](#0x1_PackageTxnManager_extract_submit_upgrade_plan_cap) -- [Function `convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2`](#0x1_PackageTxnManager_convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2) -- [Function `submit_upgrade_plan_v2`](#0x1_PackageTxnManager_submit_upgrade_plan_v2) -- [Function `submit_upgrade_plan_with_cap_v2`](#0x1_PackageTxnManager_submit_upgrade_plan_with_cap_v2) -- [Function `cancel_upgrade_plan`](#0x1_PackageTxnManager_cancel_upgrade_plan) -- [Function `cancel_upgrade_plan_with_cap`](#0x1_PackageTxnManager_cancel_upgrade_plan_with_cap) -- [Function `get_module_upgrade_strategy`](#0x1_PackageTxnManager_get_module_upgrade_strategy) -- [Function `get_upgrade_plan`](#0x1_PackageTxnManager_get_upgrade_plan) -- [Function `get_upgrade_plan_v2`](#0x1_PackageTxnManager_get_upgrade_plan_v2) -- [Function `check_package_txn`](#0x1_PackageTxnManager_check_package_txn) -- [Function `check_package_txn_v2`](#0x1_PackageTxnManager_check_package_txn_v2) -- [Function `finish_upgrade_plan`](#0x1_PackageTxnManager_finish_upgrade_plan) -- [Function `package_txn_prologue`](#0x1_PackageTxnManager_package_txn_prologue) -- [Function `package_txn_prologue_v2`](#0x1_PackageTxnManager_package_txn_prologue_v2) -- [Function `package_txn_epilogue`](#0x1_PackageTxnManager_package_txn_epilogue) -- [Function `exists_upgrade_plan_cap`](#0x1_PackageTxnManager_exists_upgrade_plan_cap) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::Version;
-
- - - - - -## Struct `UpgradePlan` - -module upgrade plan - - -
struct UpgradePlan has copy, drop, store
-
- - - -
-Fields - - -
-
-package_hash: vector<u8> -
-
- -
-
-active_after_time: u64 -
-
- -
-
-version: u64 -
-
- -
-
- - -
- - - -## Resource `UpgradePlanCapability` - -The holder of UpgradePlanCapability for account_address can submit UpgradePlan for account_address. - - -
struct UpgradePlanCapability has store, key
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
- - -
- - - -## Struct `UpgradePlanV2` - - - -
struct UpgradePlanV2 has copy, drop, store
-
- - - -
-Fields - - -
-
-package_hash: vector<u8> -
-
- -
-
-active_after_time: u64 -
-
- -
-
-version: u64 -
-
- -
-
-enforced: bool -
-
- -
-
- - -
- - - -## Resource `ModuleUpgradeStrategy` - -module upgrade strategy - - -
struct ModuleUpgradeStrategy has store, key
-
- - - -
-Fields - - -
-
-strategy: u8 -
-
- 0 arbitrary - 1 two phase upgrade - 2 only new module - 3 freeze -
-
- - -
- - - -## Resource `TwoPhaseUpgrade` - -data of two phase upgrade strategy. - - -
struct TwoPhaseUpgrade has key
-
- - - -
-Fields - - -
-
-config: PackageTxnManager::TwoPhaseUpgradeConfig -
-
- -
-
-plan: Option::Option<PackageTxnManager::UpgradePlan> -
-
- -
-
-version_cap: Config::ModifyConfigCapability<Version::Version> -
-
- -
-
-upgrade_event: Event::EventHandle<PackageTxnManager::UpgradeEvent> -
-
- -
-
- - -
- - - -## Struct `TwoPhaseUpgradeConfig` - -config of two phase upgrade strategy. - - -
struct TwoPhaseUpgradeConfig has copy, drop, store
-
- - - -
-Fields - - -
-
-min_time_limit: u64 -
-
- -
-
- - -
- - - -## Resource `TwoPhaseUpgradeV2` - -data of two phase upgrade strategy. - - -
struct TwoPhaseUpgradeV2 has key
-
- - - -
-Fields - - -
-
-config: PackageTxnManager::TwoPhaseUpgradeConfig -
-
- -
-
-plan: Option::Option<PackageTxnManager::UpgradePlanV2> -
-
- -
-
-version_cap: Config::ModifyConfigCapability<Version::Version> -
-
- -
-
-upgrade_event: Event::EventHandle<PackageTxnManager::UpgradeEvent> -
-
- -
-
- - -
- - - -## Struct `UpgradeEvent` - -module upgrade event. - - -
struct UpgradeEvent has drop, store
-
- - - -
-Fields - - -
-
-package_address: address -
-
- -
-
-package_hash: vector<u8> -
-
- -
-
-version: u64 -
-
- -
-
- - -
- - - -## Resource `UpgradePlanEventHolder` - - - -
struct UpgradePlanEventHolder has key
-
- - - -
-Fields - - -
-
-upgrade_plan_event: Event::EventHandle<PackageTxnManager::UpgradePlanEvent> -
-
- -
-
- - -
- - - -## Struct `UpgradePlanEvent` - -module upgrade plan event when submitting a module upgrade plan - - -
struct UpgradePlanEvent has drop, store
-
- - - -
-Fields - - -
-
-package_address: address -
-
- -
-
-plan: PackageTxnManager::UpgradePlanV2 -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const DEFAULT_MIN_TIME_LIMIT: u64 = 86400000;
-
- - - - - - - -
const EACTIVE_TIME_INCORRECT: u64 = 104;
-
- - - - - - - -
const EPACKAGE_HASH_INCORRECT: u64 = 103;
-
- - - - - - - -
const ESENDER_AND_PACKAGE_ADDRESS_MISMATCH: u64 = 109;
-
- - - - - - - -
const ESTRATEGY_FREEZED: u64 = 105;
-
- - - - - - - -
const ESTRATEGY_INCORRECT: u64 = 106;
-
- - - - - - - -
const ESTRATEGY_NOT_TWO_PHASE: u64 = 107;
-
- - - - - - - -
const EUNKNOWN_STRATEGY: u64 = 108;
-
- - - - - - - -
const EUPGRADE_PLAN_IS_NONE: u64 = 102;
-
- - - - - - - -
const STRATEGY_ARBITRARY: u8 = 0;
-
- - - - - - - -
const STRATEGY_FREEZE: u8 = 3;
-
- - - - - - - -
const STRATEGY_NEW_MODULE: u8 = 2;
-
- - - - - - - -
const STRATEGY_TWO_PHASE: u8 = 1;
-
- - - - - -## Function `get_strategy_arbitrary` - -arbitary stragegy - - -
public fun get_strategy_arbitrary(): u8
-
- - - -
-Implementation - - -
public fun get_strategy_arbitrary(): u8 { STRATEGY_ARBITRARY }
-
- - - -
- - - -## Function `get_strategy_two_phase` - -two phase stragegy - - -
public fun get_strategy_two_phase(): u8
-
- - - -
-Implementation - - -
public fun get_strategy_two_phase(): u8 { STRATEGY_TWO_PHASE }
-
- - - -
- - - -## Function `get_strategy_new_module` - -new module strategy - - -
public fun get_strategy_new_module(): u8
-
- - - -
-Implementation - - -
public fun get_strategy_new_module(): u8 { STRATEGY_NEW_MODULE }
-
- - - -
- - - -## Function `get_strategy_freeze` - -freezed strategy - - -
public fun get_strategy_freeze(): u8
-
- - - -
-Implementation - - -
public fun get_strategy_freeze(): u8 { STRATEGY_FREEZE }
-
- - - -
- - - -## Function `get_default_min_time_limit` - -default min time limit - - -
public fun get_default_min_time_limit(): u64
-
- - - -
-Implementation - - -
public fun get_default_min_time_limit(): u64 { DEFAULT_MIN_TIME_LIMIT }
-
- - - -
- - - -## Function `update_module_upgrade_strategy` - -Update account's ModuleUpgradeStrategy - - -
public fun update_module_upgrade_strategy(account: &signer, strategy: u8, min_time: Option::Option<u64>)
-
- - - -
-Implementation - - -
public fun update_module_upgrade_strategy(account: &signer, strategy: u8, min_time: Option<u64>)
-acquires ModuleUpgradeStrategy, TwoPhaseUpgrade, TwoPhaseUpgradeV2, UpgradePlanCapability, UpgradePlanEventHolder{
-    assert!(strategy == STRATEGY_ARBITRARY || strategy == STRATEGY_TWO_PHASE || strategy == STRATEGY_NEW_MODULE || strategy == STRATEGY_FREEZE, Errors::invalid_argument(EUNKNOWN_STRATEGY));
-    let account_address = Signer::address_of(account);
-    let previous_strategy = get_module_upgrade_strategy(account_address);
-    assert!(strategy > previous_strategy, Errors::invalid_argument(ESTRATEGY_INCORRECT));
-    if (exists<ModuleUpgradeStrategy>(account_address)) {
-        borrow_global_mut<ModuleUpgradeStrategy>(account_address).strategy = strategy;
-    }else{
-        move_to(account, ModuleUpgradeStrategy{ strategy: strategy});
-    };
-    if (strategy == STRATEGY_TWO_PHASE){
-        let version_cap = Config::extract_modify_config_capability<Version::Version>(account);
-        let min_time_limit = Option::get_with_default(&min_time, DEFAULT_MIN_TIME_LIMIT);
-        move_to(account, UpgradePlanCapability{ account_address});
-        move_to(account, TwoPhaseUpgradeV2 {
-            config: TwoPhaseUpgradeConfig { min_time_limit },
-            plan: Option::none<UpgradePlanV2>(),
-            version_cap,
-            upgrade_event: Event::new_event_handle<UpgradeEvent>(account)
-        });
-        move_to(account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(account)
-        });
-    };
-    //clean two phase upgrade resource
-    if (previous_strategy == STRATEGY_TWO_PHASE){
-        if (exists<TwoPhaseUpgrade>(account_address)) {
-            let tpu = move_from<TwoPhaseUpgrade>(account_address);
-            let TwoPhaseUpgrade{plan:_, version_cap, upgrade_event, config: _} = tpu;
-            Event::destroy_handle<Self::UpgradeEvent>(upgrade_event);
-            Config::destroy_modify_config_capability<Version::Version>(version_cap);
-        };
-        if (exists<TwoPhaseUpgradeV2>(account_address)) {
-            let tpu = move_from<TwoPhaseUpgradeV2>(account_address);
-            let TwoPhaseUpgradeV2{config: _, plan: _, version_cap, upgrade_event } = tpu;
-            Event::destroy_handle<UpgradeEvent>(upgrade_event);
-            if (exists<UpgradePlanEventHolder>(account_address)) {
-                let UpgradePlanEventHolder{ upgrade_plan_event } = move_from<UpgradePlanEventHolder>(account_address);
-                Event::destroy_handle<UpgradePlanEvent>(upgrade_plan_event);
-            };
-            Config::destroy_modify_config_capability<Version::Version>(version_cap);
-        };
-        // UpgradePlanCapability may be extracted
-        if (exists<UpgradePlanCapability>(account_address)) {
-            let cap = move_from<UpgradePlanCapability>(account_address);
-            destroy_upgrade_plan_cap(cap);
-        };
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-aborts_if strategy != 0 && strategy != 1 && strategy != 2 && strategy != 3;
-aborts_if exists<ModuleUpgradeStrategy>(Signer::address_of(account)) && strategy <= global<ModuleUpgradeStrategy>(Signer::address_of(account)).strategy;
-aborts_if !exists<ModuleUpgradeStrategy>(Signer::address_of(account)) && strategy == 0;
-aborts_if strategy == 1 && exists<UpgradePlanCapability>(Signer::address_of(account));
-aborts_if strategy == 1 && !exists<Config::ModifyConfigCapabilityHolder<Version::Version>>(Signer::address_of(account));
-let holder = global<Config::ModifyConfigCapabilityHolder<Version::Version>>(Signer::address_of(account));
-aborts_if strategy == 1 && Option::is_none<Config::ModifyConfigCapability<Version::Version>>(holder.cap);
-aborts_if strategy == 1 && exists<TwoPhaseUpgrade>(Signer::address_of(account));
-aborts_if exists<ModuleUpgradeStrategy>(Signer::address_of(account)) && global<ModuleUpgradeStrategy>(Signer::address_of(account)).strategy == 1
-    && !exists<TwoPhaseUpgrade>(Signer::address_of(account));
-
- - - -
- - - -## Function `account_address` - -Get account address of UpgradePlanCapability - - -
public fun account_address(cap: &PackageTxnManager::UpgradePlanCapability): address
-
- - - -
-Implementation - - -
public fun account_address(cap: &UpgradePlanCapability): address {
-    cap.account_address
-}
-
- - - -
- - - -## Function `destroy_upgrade_plan_cap` - -destroy the given UpgradePlanCapability - - -
public fun destroy_upgrade_plan_cap(cap: PackageTxnManager::UpgradePlanCapability)
-
- - - -
-Implementation - - -
public fun destroy_upgrade_plan_cap(cap: UpgradePlanCapability){
-    let UpgradePlanCapability{account_address:_} = cap;
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `extract_submit_upgrade_plan_cap` - -extract out UpgradePlanCapability from signer. - - -
public fun extract_submit_upgrade_plan_cap(account: &signer): PackageTxnManager::UpgradePlanCapability
-
- - - -
-Implementation - - -
public fun extract_submit_upgrade_plan_cap(account: &signer): UpgradePlanCapability acquires ModuleUpgradeStrategy, UpgradePlanCapability{
-    let account_address = Signer::address_of(account);
-    assert!(get_module_upgrade_strategy(account_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE));
-    move_from<UpgradePlanCapability>(account_address)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<ModuleUpgradeStrategy>(Signer::address_of(account));
-aborts_if global<ModuleUpgradeStrategy>(Signer::address_of(account)).strategy != 1;
-aborts_if !exists<UpgradePlanCapability>(Signer::address_of(account));
-
- - - -
- - - -## Function `convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2` - - - -
public(script) fun convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2(account: signer, package_address: address)
-
- - - -
-Implementation - - -
public(script) fun convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2(account: signer, package_address: address) acquires TwoPhaseUpgrade {
-    let account_address = Signer::address_of(&account);
-    // sender should be package owner
-    assert!(account_address == package_address, Errors::requires_address(ESENDER_AND_PACKAGE_ADDRESS_MISMATCH));
-    let tpu = move_from<TwoPhaseUpgrade>(account_address);
-    let TwoPhaseUpgrade{config, plan, version_cap, upgrade_event} = tpu;
-    if (Option::is_some(&plan)) {
-        let old_plan = Option::borrow(&plan);
-        move_to(&account, TwoPhaseUpgradeV2{
-            config,
-            plan: Option::some(UpgradePlanV2 {
-                package_hash: *&old_plan.package_hash,
-                active_after_time: old_plan.active_after_time,
-                version: old_plan.version,
-                enforced: false }),
-            version_cap,
-            upgrade_event
-        });
-        move_to(&account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(&account)
-        });
-    } else {
-        move_to(&account, TwoPhaseUpgradeV2 {
-            config,
-            plan: Option::none<UpgradePlanV2>(),
-            version_cap,
-            upgrade_event
-        });
-        move_to(&account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(&account)
-        });
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `submit_upgrade_plan_v2` - - - -
public fun submit_upgrade_plan_v2(account: &signer, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public fun submit_upgrade_plan_v2(account: &signer, package_hash: vector<u8>, version:u64, enforced: bool)
-acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy,UpgradePlanEventHolder{
-    let account_address = Signer::address_of(account);
-    let cap = borrow_global<UpgradePlanCapability>(account_address);
-    assert!(get_module_upgrade_strategy(cap.account_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE));
-    if (!exists<UpgradePlanEventHolder>(account_address)) {
-        move_to(account, UpgradePlanEventHolder {
-            upgrade_plan_event: Event::new_event_handle<UpgradePlanEvent>(account)
-        })
-    };
-    submit_upgrade_plan_with_cap_v2(cap, package_hash, version, enforced);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-aborts_if !exists<UpgradePlanCapability>(Signer::address_of(account));
-include SubmitUpgradePlanWithCapAbortsIf{account: global<UpgradePlanCapability>(Signer::address_of(account)).account_address};
-ensures Option::is_some(global<TwoPhaseUpgrade>(global<UpgradePlanCapability>(Signer::address_of(account)).account_address).plan);
-
- - - -
- - - -## Function `submit_upgrade_plan_with_cap_v2` - - - -
public fun submit_upgrade_plan_with_cap_v2(cap: &PackageTxnManager::UpgradePlanCapability, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public fun submit_upgrade_plan_with_cap_v2(cap: &UpgradePlanCapability, package_hash: vector<u8>, version: u64, enforced: bool)
-acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy, UpgradePlanEventHolder{
-    let package_address = cap.account_address;
-    assert!(get_module_upgrade_strategy(package_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE));
-
-    let tpu = borrow_global_mut<TwoPhaseUpgradeV2>(package_address);
-    let active_after_time = Timestamp::now_milliseconds() + tpu.config.min_time_limit;
-    let plan = UpgradePlanV2 { package_hash, active_after_time, version, enforced };
-    tpu.plan = Option::some(copy plan);
-
-    // TODO
-    // if UpgradePlanCapability was delegated to DAO or contract,
-    // it's hard to upgrade the address to claim an UpgradePlanEventHolder.
-    // Try to fix this!
-    if (exists<UpgradePlanEventHolder>(package_address)) {
-        let event_holder = borrow_global_mut<UpgradePlanEventHolder>(package_address);
-        Event::emit_event<UpgradePlanEvent>(&mut event_holder.upgrade_plan_event, UpgradePlanEvent {
-            package_address,
-            plan
-        });
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-include SubmitUpgradePlanWithCapAbortsIf{account: cap.account_address};
-ensures Option::is_some(global<TwoPhaseUpgrade>(cap.account_address).plan);
-
- - - - - - - -
schema SubmitUpgradePlanWithCapAbortsIf {
-    account: address;
-    aborts_if !exists<ModuleUpgradeStrategy>(account);
-    aborts_if global<ModuleUpgradeStrategy>(account).strategy != 1;
-    aborts_if !exists<TwoPhaseUpgrade>(account);
-    aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-    aborts_if Timestamp::now_milliseconds() + global<TwoPhaseUpgrade>(account).config.min_time_limit > max_u64();
-}
-
- - - -
- - - -## Function `cancel_upgrade_plan` - -Cancel a module upgrade plan. - - -
public fun cancel_upgrade_plan(account: &signer)
-
- - - -
-Implementation - - -
public fun cancel_upgrade_plan(account: &signer) acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy{
-    let account_address = Signer::address_of(account);
-    let cap = borrow_global<UpgradePlanCapability>(account_address);
-    cancel_upgrade_plan_with_cap(cap);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<UpgradePlanCapability>(Signer::address_of(account));
-include CancelUpgradePlanWithCapAbortsIf{account: global<UpgradePlanCapability>(Signer::address_of(account)).account_address};
-ensures Option::is_none(global<TwoPhaseUpgrade>(global<UpgradePlanCapability>(Signer::address_of(account)).account_address).plan);
-
- - - -
- - - -## Function `cancel_upgrade_plan_with_cap` - -Cancel a module upgrade plan with given cap. - - -
public fun cancel_upgrade_plan_with_cap(cap: &PackageTxnManager::UpgradePlanCapability)
-
- - - -
-Implementation - - -
public fun cancel_upgrade_plan_with_cap(cap: &UpgradePlanCapability) acquires TwoPhaseUpgradeV2,ModuleUpgradeStrategy{
-    let package_address = cap.account_address;
-    assert!(get_module_upgrade_strategy(package_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE));
-    let tpu = borrow_global_mut<TwoPhaseUpgradeV2>(package_address);
-    assert!(Option::is_some(&tpu.plan), Errors::invalid_state(EUPGRADE_PLAN_IS_NONE));
-    tpu.plan = Option::none<UpgradePlanV2>();
-}
-
- - - -
- -
-Specification - - - -
include CancelUpgradePlanWithCapAbortsIf{account: cap.account_address};
-ensures Option::is_none(global<TwoPhaseUpgrade>(cap.account_address).plan);
-
- - - - - - - -
schema CancelUpgradePlanWithCapAbortsIf {
-    account: address;
-    aborts_if !exists<ModuleUpgradeStrategy>(account);
-    aborts_if global<ModuleUpgradeStrategy>(account).strategy != 1;
-    aborts_if !exists<TwoPhaseUpgrade>(account);
-    aborts_if !Option::is_some(global<TwoPhaseUpgrade>(account).plan);
-}
-
- - - -
- - - -## Function `get_module_upgrade_strategy` - -Get module upgrade strategy of an module address. - - -
public fun get_module_upgrade_strategy(module_address: address): u8
-
- - - -
-Implementation - - -
public fun get_module_upgrade_strategy(module_address: address): u8 acquires ModuleUpgradeStrategy {
-    if (exists<ModuleUpgradeStrategy>(module_address)) {
-        borrow_global<ModuleUpgradeStrategy>(module_address).strategy
-    }else{
-        0
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - - - - - -
fun spec_get_module_upgrade_strategy(module_address: address): u8 {
-   if (exists<ModuleUpgradeStrategy>(module_address)) {
-       global<ModuleUpgradeStrategy>(module_address).strategy
-   }else{
-       0
-   }
-}
-
- - - -
- - - -## Function `get_upgrade_plan` - -Get module upgrade plan of an address. - - -
public fun get_upgrade_plan(_module_address: address): Option::Option<PackageTxnManager::UpgradePlan>
-
- - - -
-Implementation - - -
public fun get_upgrade_plan(_module_address: address): Option<UpgradePlan> {
-    // DEPRECATED_CODE
-    Option::none<UpgradePlan>()
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `get_upgrade_plan_v2` - -Get module upgrade plan of an address. - - -
public fun get_upgrade_plan_v2(module_address: address): Option::Option<PackageTxnManager::UpgradePlanV2>
-
- - - -
-Implementation - - -
public fun get_upgrade_plan_v2(module_address: address): Option<UpgradePlanV2> acquires TwoPhaseUpgradeV2 {
-    if (exists<TwoPhaseUpgradeV2>(module_address)) {
-        *&borrow_global<TwoPhaseUpgradeV2>(module_address).plan
-    } else {
-        Option::none<UpgradePlanV2>()
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-aborts_if false;
-
- - - - - - - -
fun spec_get_upgrade_plan_v2(module_address: address): Option<UpgradePlan> {
-   if (exists<TwoPhaseUpgrade>(module_address)) {
-       global<TwoPhaseUpgrade>(module_address).plan
-   }else{
-       Option::spec_none<UpgradePlan>()
-   }
-}
-
- - - -
- - - -## Function `check_package_txn` - -Check againest on the given package data. - - -
public fun check_package_txn(package_address: address, package_hash: vector<u8>)
-
- - - -
-Implementation - - -
public fun check_package_txn(package_address: address, package_hash: vector<u8>) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy{
-    let strategy = get_module_upgrade_strategy(package_address);
-    if (strategy == STRATEGY_ARBITRARY){
-        //do nothing
-    }else if(strategy == STRATEGY_TWO_PHASE){
-        let plan_opt = get_upgrade_plan_v2(package_address);
-        assert!(Option::is_some(&plan_opt), Errors::invalid_argument(EUPGRADE_PLAN_IS_NONE));
-        let plan = Option::borrow(&plan_opt);
-        assert!(*&plan.package_hash == package_hash, Errors::invalid_argument(EPACKAGE_HASH_INCORRECT));
-        assert!(plan.active_after_time <= Timestamp::now_milliseconds(), Errors::invalid_argument(EACTIVE_TIME_INCORRECT));
-    }else if(strategy == STRATEGY_NEW_MODULE){
-        //do check at VM runtime.
-    }else if(strategy == STRATEGY_FREEZE){
-        Errors::invalid_argument(ESTRATEGY_FREEZED);
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-include CheckPackageTxnAbortsIf;
-
- - - -
- - - -## Function `check_package_txn_v2` - - - -
public fun check_package_txn_v2(txn_sender: address, package_address: address, package_hash: vector<u8>)
-
- - - -
-Implementation - - -
public fun check_package_txn_v2(txn_sender: address, package_address: address, package_hash: vector<u8>) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy{
-    let strategy = get_module_upgrade_strategy(package_address);
-    if (strategy == STRATEGY_ARBITRARY){
-        assert!(txn_sender == package_address, Errors::requires_address(ESENDER_AND_PACKAGE_ADDRESS_MISMATCH));
-    }else if(strategy == STRATEGY_TWO_PHASE){
-        let plan_opt = get_upgrade_plan_v2(package_address);
-        assert!(Option::is_some(&plan_opt), Errors::invalid_argument(EUPGRADE_PLAN_IS_NONE));
-        let plan = Option::borrow(&plan_opt);
-        assert!(*&plan.package_hash == package_hash, Errors::invalid_argument(EPACKAGE_HASH_INCORRECT));
-        assert!(plan.active_after_time <= Timestamp::now_milliseconds(), Errors::invalid_argument(EACTIVE_TIME_INCORRECT));
-    }else if(strategy == STRATEGY_NEW_MODULE){
-        //do check at VM runtime.
-        assert!(txn_sender == package_address, Errors::requires_address(ESENDER_AND_PACKAGE_ADDRESS_MISMATCH));
-    }else if(strategy == STRATEGY_FREEZE){
-        Errors::invalid_argument(ESTRATEGY_FREEZED);
-    };
-}
-
- - - -
- - - -## Function `finish_upgrade_plan` - - - -
fun finish_upgrade_plan(package_address: address)
-
- - - -
-Implementation - - -
fun finish_upgrade_plan(package_address: address) acquires TwoPhaseUpgradeV2 {
-    let tpu = borrow_global_mut<TwoPhaseUpgradeV2>(package_address);
-    if (Option::is_some(&tpu.plan)) {
-        let plan = Option::borrow(&tpu.plan);
-        Config::set_with_capability<Version::Version>(&mut tpu.version_cap, Version::new_version(plan.version));
-        Event::emit_event<Self::UpgradeEvent>(&mut tpu.upgrade_event, UpgradeEvent {
-            package_address,
-            package_hash: *&plan.package_hash,
-            version: plan.version});
-    };
-    tpu.plan = Option::none<UpgradePlanV2>();
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-aborts_if !exists<TwoPhaseUpgrade>(package_address);
-let tpu = global<TwoPhaseUpgrade>(package_address);
-aborts_if Option::is_some(tpu.plan) && !exists<Config::Config<Version::Version>>(tpu.version_cap.account_address);
-
- - - -
- - - -## Function `package_txn_prologue` - -Prologue of package transaction. - - -
public fun package_txn_prologue(account: &signer, package_address: address, package_hash: vector<u8>)
-
- - - -
-Implementation - - -
public fun package_txn_prologue(account: &signer, package_address: address, package_hash: vector<u8>) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy {
-    // Can only be invoked by genesis account
-    CoreAddresses::assert_genesis_address(account);
-    check_package_txn(package_address, package_hash);
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-include CheckPackageTxnAbortsIf{};
-
- - - -
- - - -## Function `package_txn_prologue_v2` - - - -
public fun package_txn_prologue_v2(account: &signer, txn_sender: address, package_address: address, package_hash: vector<u8>)
-
- - - -
-Implementation - - -
public fun package_txn_prologue_v2(account: &signer, txn_sender: address, package_address: address, package_hash: vector<u8>) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy {
-    // Can only be invoked by genesis account
-    CoreAddresses::assert_genesis_address(account);
-    check_package_txn_v2(txn_sender, package_address, package_hash);
-}
-
- - - -
- - - -## Function `package_txn_epilogue` - -Package txn finished, and clean UpgradePlan - - -
public fun package_txn_epilogue(account: &signer, _txn_sender: address, package_address: address, success: bool)
-
- - - -
-Implementation - - -
public fun package_txn_epilogue(account: &signer, _txn_sender: address, package_address: address, success: bool) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy {
-    // Can only be invoked by genesis account
-    CoreAddresses::assert_genesis_address(account);
-    let strategy = get_module_upgrade_strategy(package_address);
-    if(strategy == STRATEGY_TWO_PHASE){
-        if (success) {
-            finish_upgrade_plan(package_address);
-        };
-    };
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if spec_get_module_upgrade_strategy(package_address) == 1
-    && success && !exists<TwoPhaseUpgrade>(package_address);
-aborts_if spec_get_module_upgrade_strategy(package_address) == 1
-    && success && Option::is_some(global<TwoPhaseUpgrade>(package_address).plan)
-    && !exists<Config::Config<Version::Version>>(global<TwoPhaseUpgrade>(package_address).version_cap.account_address);
-
- - - -
- - - -## Function `exists_upgrade_plan_cap` - - - -
public fun exists_upgrade_plan_cap(addr: address): bool
-
- - - -
-Implementation - - -
public fun exists_upgrade_plan_cap(addr :address):bool{
-    exists<UpgradePlanCapability>(addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/README.md b/release/v12/docs/README.md deleted file mode 100644 index 30df7bc4..00000000 --- a/release/v12/docs/README.md +++ /dev/null @@ -1,123 +0,0 @@ - - - -# Move StarcoinFramework Modules - - -This is the root document for the Move StarcoinFramework module documentation. The Move StarcoinFramework provides modules that can be used to access or interact with Starcoin blockchain. - - - - -## Index - - -- [`0x1::ASCII`](ASCII.md#0x1_ASCII) -- [`0x1::Account`](Account.md#0x1_Account) -- [`0x1::AccountScripts`](AccountScripts.md#0x1_AccountScripts) -- [`0x1::AnyMemberPlugin`](AnyMemberPlugin.md#0x1_AnyMemberPlugin) -- [`0x1::Arith`](U256.md#0x1_Arith) -- [`0x1::Authenticator`](Authenticator.md#0x1_Authenticator) -- [`0x1::BCS`](BCS.md#0x1_BCS) -- [`0x1::BitOperators`](Bitwise.md#0x1_BitOperators) -- [`0x1::Block`](Block.md#0x1_Block) -- [`0x1::BlockReward`](BlockReward.md#0x1_BlockReward) -- [`0x1::ChainId`](ChainId.md#0x1_ChainId) -- [`0x1::Collection`](Collection.md#0x1_Collection) -- [`0x1::Collection2`](Collection2.md#0x1_Collection2) -- [`0x1::Compare`](Compare.md#0x1_Compare) -- [`0x1::Config`](Config.md#0x1_Config) -- [`0x1::ConfigProposalPlugin`](ConfigProposalPlugin.md#0x1_ConfigProposalPlugin) -- [`0x1::ConsensusConfig`](ConsensusConfig.md#0x1_ConsensusConfig) -- [`0x1::ConsensusStrategy`](ConsensusStrategy.md#0x1_ConsensusStrategy) -- [`0x1::CoreAddresses`](CoreAddresses.md#0x1_CoreAddresses) -- [`0x1::DAOAccount`](DAOAccount.md#0x1_DAOAccount) -- [`0x1::DAOExtensionPoint`](DAOExtensionPoint.md#0x1_DAOExtensionPoint) -- [`0x1::DAOPluginMarketplace`](DAOPluginMarketplace.md#0x1_DAOPluginMarketplace) -- [`0x1::DAORegistry`](DAORegistry.md#0x1_DAORegistry) -- [`0x1::DAOSpace`](DAOSpace.md#0x1_DAOSpace) -- [`0x1::Dao`](Dao.md#0x1_Dao) -- [`0x1::DaoVoteScripts`](DaoVoteScripts.md#0x1_DaoVoteScripts) -- [`0x1::Debug`](Debug.md#0x1_Debug) -- [`0x1::DummyToken`](DummyToken.md#0x1_DummyToken) -- [`0x1::DummyTokenScripts`](DummyToken.md#0x1_DummyTokenScripts) -- [`0x1::EVMAddress`](Signature.md#0x1_EVMAddress) -- [`0x1::EmptyScripts`](EmptyScripts.md#0x1_EmptyScripts) -- [`0x1::Epoch`](Epoch.md#0x1_Epoch) -- [`0x1::Errors`](Errors.md#0x1_Errors) -- [`0x1::Event`](Event.md#0x1_Event) -- [`0x1::EventUtil`](EventUtil.md#0x1_EventUtil) -- [`0x1::FixedPoint32`](FixedPoint32.md#0x1_FixedPoint32) -- [`0x1::GasOracle`](Oracle.md#0x1_GasOracle) -- [`0x1::GasOracleProposalPlugin`](GasOracleProposalPlugin.md#0x1_GasOracleProposalPlugin) -- [`0x1::Genesis`](Genesis.md#0x1_Genesis) -- [`0x1::GenesisNFT`](GenesisNFT.md#0x1_GenesisNFT) -- [`0x1::GenesisNFTScripts`](GenesisNFT.md#0x1_GenesisNFTScripts) -- [`0x1::GenesisSignerCapability`](GenesisSignerCapability.md#0x1_GenesisSignerCapability) -- [`0x1::GrantProposalPlugin`](GrantProposalPlugin.md#0x1_GrantProposalPlugin) -- [`0x1::Hash`](Hash.md#0x1_Hash) -- [`0x1::IdentifierNFT`](NFT.md#0x1_IdentifierNFT) -- [`0x1::IdentifierNFTScripts`](NFT.md#0x1_IdentifierNFTScripts) -- [`0x1::InstallPluginProposalPlugin`](InstallPluginProposalPlugin.md#0x1_InstallPluginProposalPlugin) -- [`0x1::LanguageVersion`](LanguageVersion.md#0x1_LanguageVersion) -- [`0x1::Math`](Math.md#0x1_Math) -- [`0x1::MemberProposalPlugin`](MemberProposalPlugin.md#0x1_MemberProposalPlugin) -- [`0x1::MerkleNFTDistributor`](MerkleNFT.md#0x1_MerkleNFTDistributor) -- [`0x1::MerkleProof`](MerkleNFT.md#0x1_MerkleProof) -- [`0x1::MintDaoProposal`](MintDaoProposal.md#0x1_MintDaoProposal) -- [`0x1::MintProposalPlugin`](MintProposalPlugin.md#0x1_MintProposalPlugin) -- [`0x1::MintScripts`](MintScripts.md#0x1_MintScripts) -- [`0x1::ModifyDaoConfigProposal`](ModifyDaoConfigProposal.md#0x1_ModifyDaoConfigProposal) -- [`0x1::ModuleUpgradeScripts`](ModuleUpgradeScripts.md#0x1_ModuleUpgradeScripts) -- [`0x1::NFT`](NFT.md#0x1_NFT) -- [`0x1::NFTGallery`](NFT.md#0x1_NFTGallery) -- [`0x1::NFTGalleryScripts`](NFT.md#0x1_NFTGalleryScripts) -- [`0x1::Offer`](Offer.md#0x1_Offer) -- [`0x1::OnChainConfigDao`](OnChainConfigDao.md#0x1_OnChainConfigDao) -- [`0x1::OnChainConfigScripts`](OnChainConfigScripts.md#0x1_OnChainConfigScripts) -- [`0x1::OnChainStarcoinDAOConfig`](OnChainStarcoinDAOConfig.md#0x1_OnChainStarcoinDAOConfig) -- [`0x1::Option`](Option.md#0x1_Option) -- [`0x1::Oracle`](Oracle.md#0x1_Oracle) -- [`0x1::PackageTxnManager`](PackageTxnManager.md#0x1_PackageTxnManager) -- [`0x1::PriceOracle`](Oracle.md#0x1_PriceOracle) -- [`0x1::PriceOracleAggregator`](Oracle.md#0x1_PriceOracleAggregator) -- [`0x1::PriceOracleScripts`](Oracle.md#0x1_PriceOracleScripts) -- [`0x1::RewardConfig`](RewardConfig.md#0x1_RewardConfig) -- [`0x1::Ring`](Ring.md#0x1_Ring) -- [`0x1::SBTVoteStrategy`](SBTVoteStrategy.md#0x1_SBTVoteStrategy) -- [`0x1::SIP_2`](SIPs.md#0x1_SIP_2) -- [`0x1::SIP_3`](SIPs.md#0x1_SIP_3) -- [`0x1::STC`](STC.md#0x1_STC) -- [`0x1::STCUSDOracle`](Oracle.md#0x1_STCUSDOracle) -- [`0x1::SharedEd25519PublicKey`](SharedEd25519PublicKey.md#0x1_SharedEd25519PublicKey) -- [`0x1::Signature`](Signature.md#0x1_Signature) -- [`0x1::SignedInteger64`](SignedInteger64.md#0x1_SignedInteger64) -- [`0x1::Signer`](Signer.md#0x1_Signer) -- [`0x1::SimpleMap`](SimpleMap.md#0x1_SimpleMap) -- [`0x1::SnapshotUtil`](SnapshotUtil.md#0x1_SnapshotUtil) -- [`0x1::StakeToSBTPlugin`](StakeToSBTPlugin.md#0x1_StakeToSBTPlugin) -- [`0x1::StarcoinDAO`](StarcoinDAO.md#0x1_StarcoinDAO) -- [`0x1::StarcoinVerifier`](StarcoinVerifier.md#0x1_StarcoinVerifier) -- [`0x1::StdlibUpgradeScripts`](StdlibUpgradeScripts.md#0x1_StdlibUpgradeScripts) -- [`0x1::StructuredHash`](StarcoinVerifier.md#0x1_StructuredHash) -- [`0x1::Timestamp`](Timestamp.md#0x1_Timestamp) -- [`0x1::Token`](Token.md#0x1_Token) -- [`0x1::TransactionFee`](TransactionFee.md#0x1_TransactionFee) -- [`0x1::TransactionManager`](TransactionManager.md#0x1_TransactionManager) -- [`0x1::TransactionPublishOption`](TransactionPublishOption.md#0x1_TransactionPublishOption) -- [`0x1::TransactionTimeout`](TransactionTimeout.md#0x1_TransactionTimeout) -- [`0x1::TransactionTimeoutConfig`](TransactionTimeoutConfig.md#0x1_TransactionTimeoutConfig) -- [`0x1::TransferScripts`](TransferScripts.md#0x1_TransferScripts) -- [`0x1::Treasury`](Treasury.md#0x1_Treasury) -- [`0x1::TreasuryPlugin`](TreasuryPlugin.md#0x1_TreasuryPlugin) -- [`0x1::TreasuryScripts`](TreasuryScripts.md#0x1_TreasuryScripts) -- [`0x1::TreasuryWithdrawDaoProposal`](TreasuryWithdrawDaoProposal.md#0x1_TreasuryWithdrawDaoProposal) -- [`0x1::TypeInfo`](TypeInfo.md#0x1_TypeInfo) -- [`0x1::U256`](U256.md#0x1_U256) -- [`0x1::UpgradeModuleDaoProposal`](UpgradeModuleDaoProposal.md#0x1_UpgradeModuleDaoProposal) -- [`0x1::UpgradeModulePlugin`](UpgradeModulePlugin.md#0x1_UpgradeModulePlugin) -- [`0x1::VMConfig`](VMConfig.md#0x1_VMConfig) -- [`0x1::Vector`](Vector.md#0x1_Vector) -- [`0x1::Version`](Version.md#0x1_Version) -- [`0x1::YieldFarming`](YieldFarming.md#0x1_YieldFarming) -- [`0x1::YieldFarmingV2`](YieldFarmingV2.md#0x1_YieldFarmingV2) diff --git a/release/v12/docs/RewardConfig.md b/release/v12/docs/RewardConfig.md deleted file mode 100644 index 4c300f5d..00000000 --- a/release/v12/docs/RewardConfig.md +++ /dev/null @@ -1,240 +0,0 @@ - - - -# Module `0x1::RewardConfig` - -The module provide configuration for block reward. - - -- [Struct `RewardConfig`](#0x1_RewardConfig_RewardConfig) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_RewardConfig_initialize) -- [Function `new_reward_config`](#0x1_RewardConfig_new_reward_config) -- [Function `get_reward_config`](#0x1_RewardConfig_get_reward_config) -- [Function `reward_delay`](#0x1_RewardConfig_reward_delay) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Timestamp;
-
- - - - - -## Struct `RewardConfig` - -Reward configuration - - -
struct RewardConfig has copy, drop, store
-
- - - -
-Fields - - -
-
-reward_delay: u64 -
-
- how many blocks delay reward distribution. -
-
- - -
- - - -## Constants - - - - - - -
const EINVALID_ARGUMENT: u64 = 18;
-
- - - - - -## Function `initialize` - -Module initialization. - - -
public fun initialize(account: &signer, reward_delay: u64)
-
- - - -
-Implementation - - -
public fun initialize(account: &signer, reward_delay: u64) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-
-    Config::publish_new_config<Self::RewardConfig>(
-        account,
-        new_reward_config(reward_delay)
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if exists<Config::Config<RewardConfig>>(Signer::address_of(account));
-include Config::PublishNewConfigAbortsIf<RewardConfig>;
-include Config::PublishNewConfigEnsures<RewardConfig>;
-
- - - -
- - - -## Function `new_reward_config` - -Create a new reward config mainly used in DAO. - - -
public fun new_reward_config(reward_delay: u64): RewardConfig::RewardConfig
-
- - - -
-Implementation - - -
public fun new_reward_config(reward_delay: u64) : RewardConfig {
-    RewardConfig {reward_delay: reward_delay}
-}
-
- - - -
- -
-Specification - - - -
- - - -## Function `get_reward_config` - -Get reward configuration. - - -
public fun get_reward_config(): RewardConfig::RewardConfig
-
- - - -
-Implementation - - -
public fun get_reward_config(): RewardConfig {
-    Config::get_by_address<RewardConfig>(CoreAddresses::GENESIS_ADDRESS())
-}
-
- - - -
- -
-Specification - - - -
include GetRewardConfigAbortsIf;
-
- - - - - - - -
schema GetRewardConfigAbortsIf {
-    aborts_if !exists<Config::Config<RewardConfig>>(CoreAddresses::GENESIS_ADDRESS());
-}
-
- - - -
- - - -## Function `reward_delay` - -Get reward delay. - - -
public fun reward_delay(): u64
-
- - - -
-Implementation - - -
public fun reward_delay() :u64 {
-    let reward_config = get_reward_config();
-    reward_config.reward_delay
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Config::Config<RewardConfig>>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/Ring.md b/release/v12/docs/Ring.md deleted file mode 100644 index 9fa1f7ef..00000000 --- a/release/v12/docs/Ring.md +++ /dev/null @@ -1,437 +0,0 @@ - - - -# Module `0x1::Ring` - -A ring-shaped container that can hold any type, indexed from 0 -The capacity is fixed at creation time, and the accessible index is constantly growing - - -- [Struct `Ring`](#0x1_Ring_Ring) -- [Constants](#@Constants_0) -- [Function `create_with_capacity`](#0x1_Ring_create_with_capacity) -- [Function `is_full`](#0x1_Ring_is_full) -- [Function `capacity`](#0x1_Ring_capacity) -- [Function `push`](#0x1_Ring_push) -- [Function `borrow`](#0x1_Ring_borrow) -- [Function `borrow_mut`](#0x1_Ring_borrow_mut) -- [Function `index_of`](#0x1_Ring_index_of) -- [Function `destroy`](#0x1_Ring_destroy) - - -
use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `Ring` - - - -
struct Ring<Element> has store
-
- - - -
-Fields - - -
-
-data: vector<Option::Option<Element>> -
-
- -
-
-insertion_index: u64 -
-
- -
-
-external_index: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -The index into the vector is out of bounds - - -
const ERROR_RING_INDEX_OUT_OF_BOUNDS: u64 = 101;
-
- - - - - -## Function `create_with_capacity` - -Create a Ring with capacity. - - -
public fun create_with_capacity<Element>(len: u64): Ring::Ring<Element>
-
- - - -
-Implementation - - -
public fun create_with_capacity<Element>( len: u64 ):Ring<Element>{
-    let data = Vector::empty<Option::Option<Element>>();
-    let i = 0;
-    while(i < len){
-        Vector::push_back(&mut data , Option::none<Element>());
-        i = i + 1;
-    };
-    Ring {
-        data             : data,
-        insertion_index  : 0,
-        external_index   : 0,
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `is_full` - -is Ring full - - -
public fun is_full<Element>(r: &Ring::Ring<Element>): bool
-
- - - -
-Implementation - - -
public fun is_full<Element>(r: &Ring<Element>):bool{
-    Option::is_some(Vector::borrow(&r.data, r.insertion_index))
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `capacity` - -Return the capacity of the Ring. - - -
public fun capacity<Element>(r: &Ring::Ring<Element>): u64
-
- - - -
-Implementation - - -
public fun capacity<Element>(r: &Ring<Element>): u64{
-    Vector::length( &r.data )
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `push` - -Add element e to the insertion_index of the Ring r. - - -
public fun push<Element>(r: &mut Ring::Ring<Element>, e: Element): Option::Option<Element>
-
- - - -
-Implementation - - -
public fun push<Element> (r: &mut Ring<Element> , e: Element):Option::Option<Element>{
-    let op_e = Vector::borrow_mut<Option::Option<Element>>(&mut r.data, r.insertion_index);
-    let res = if(  Option::is_none<Element>(op_e) ){
-        Option::fill( op_e, e);
-        Option::none<Element>()
-    }else{
-       Option::some<Element>( Option::swap( op_e, e) )
-    };
-    r.insertion_index = ( r.insertion_index + 1 ) % Vector::length(&r.data);
-    r.external_index = r.external_index + 1;
-    res
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `borrow` - -Return a reference to the ith element in the Ring r. - - -
public fun borrow<Element>(r: &Ring::Ring<Element>, i: u64): &Option::Option<Element>
-
- - - -
-Implementation - - -
public fun borrow<Element>(r:& Ring<Element>, i: u64):&Option::Option<Element>{
-    let len = capacity<Element>(r);
-    if( r.external_index > len - 1) {
-        assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow(&r.data, i % len)
-    }else {
-        assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow(&r.data, i )
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the ith element in the Ring r. - - -
public fun borrow_mut<Element>(r: &mut Ring::Ring<Element>, i: u64): &mut Option::Option<Element>
-
- - - -
-Implementation - - -
public fun borrow_mut<Element>(r: &mut Ring<Element>, i: u64):&mut Option::Option<Element>{
-    let len = capacity<Element>(r);
-    if( r.external_index > len - 1) {
-        assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow_mut(&mut r.data, i % len)
-    }else {
-        assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS));
-        Vector::borrow_mut(&mut r.data, i )
-    }
-
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `index_of` - -Return Option::Option<u64> if e is in the Ring r at index i. -Otherwise, returns Option::none<u64>. - - -
public fun index_of<Element>(r: &Ring::Ring<Element>, e: &Element): Option::Option<u64>
-
- - - -
-Implementation - - -
public fun index_of<Element>(r: &Ring<Element>, e: &Element):Option::Option<u64>{
-    let i = 0;
-    let len = capacity<Element>(r);
-    while ( i < len ) {
-        if ( Option::borrow(Vector::borrow( &r.data, i )) == e) return Option::some(i + r.external_index - len);
-        i = i + 1;
-    };
-    Option::none<u64>()
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `destroy` - -Destroy the Ring r. -Returns the vector saved by ring - - -
public fun destroy<Element>(r: Ring::Ring<Element>): vector<Element>
-
- - - -
-Implementation - - -
public fun destroy<Element>(r: Ring<Element>):vector<Element>{
-    let Ring {
-        data            : data ,
-        insertion_index : _,
-        external_index  : _,
-    } = r ;
-    let len = Vector::length(&data);
-    let i = 0;
-    let vec = Vector::empty<Element>();
-    while ( i < len ) {
-        let op_e = Vector::pop_back( &mut data );
-        if ( Option::is_some(&op_e) ) {
-            Vector::push_back(&mut vec, Option::destroy_some(op_e))
-        }else {
-           Option::destroy_none(op_e)
-        };
-        i = i + 1;
-    };
-    Vector::destroy_empty(data);
-    vec
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
diff --git a/release/v12/docs/SBTVoteStrategy.md b/release/v12/docs/SBTVoteStrategy.md deleted file mode 100644 index 58523ec1..00000000 --- a/release/v12/docs/SBTVoteStrategy.md +++ /dev/null @@ -1,104 +0,0 @@ - - - -# Module `0x1::SBTVoteStrategy` - - - -- [Constants](#@Constants_0) -- [Function `get_voting_power`](#0x1_SBTVoteStrategy_get_voting_power) -- [Function `deserialize_sbt_value_from_bcs_state`](#0x1_SBTVoteStrategy_deserialize_sbt_value_from_bcs_state) - - -
use 0x1::BCS;
-use 0x1::Vector;
-
- - - - - -## Constants - - - - - - -
const ERR_BCS_STATE_NTFS_LENGHT_TYPE_INVALID: u64 = 1413;
-
- - - - - -## Function `get_voting_power` - -deserialize snapshot vote value from state - - -
public fun get_voting_power(state: &vector<u8>): u128
-
- - - -
-Implementation - - -
public fun get_voting_power(state: &vector<u8>) : u128 {
-    let sbt_value = deserialize_sbt_value_from_bcs_state(state);
-    sbt_value
-}
-
- - - -
- - - -## Function `deserialize_sbt_value_from_bcs_state` - -deserialize sbt value from bcs state - - -
public fun deserialize_sbt_value_from_bcs_state(state: &vector<u8>): u128
-
- - - -
-Implementation - - -
public fun deserialize_sbt_value_from_bcs_state(state: &vector<u8>) : u128{
-    let len = Vector::length(state);
-    if (len == 0) {
-        return 0u128
-    };
-
-    // nfts array length
-    let offset = 0;
-    let (nfts_len, offset) = BCS::deserialize_u8(state, offset);
-    // user has no sbt yet
-    if (nfts_len == 0) {
-        return 0u128
-    };
-
-    offset = BCS::skip_address(state, offset);
-    offset = BCS::skip_u64(state, offset);
-    offset = BCS::skip_bytes(state, offset);
-    offset = BCS::skip_bytes(state, offset);
-    offset = BCS::skip_bytes(state, offset);
-    offset = BCS::skip_bytes(state, offset);
-    offset = BCS::skip_u64(state, offset);
-    let (value, _offset) = BCS::deserialize_u128(state, offset);
-
-    value
-}
-
- - - -
diff --git a/release/v12/docs/SIPs.md b/release/v12/docs/SIPs.md deleted file mode 100644 index b466bfe7..00000000 --- a/release/v12/docs/SIPs.md +++ /dev/null @@ -1,11 +0,0 @@ - - - -# Module `0x1::SIP_3` - -https://github.com/starcoinorg/SIPs/tree/master/sip-3 - - - - -
diff --git a/release/v12/docs/STC.md b/release/v12/docs/STC.md deleted file mode 100644 index 74bed864..00000000 --- a/release/v12/docs/STC.md +++ /dev/null @@ -1,395 +0,0 @@ - - - -# Module `0x1::STC` - -STC is the token of Starcoin blockchain. -It uses apis defined in the Token module. - - -- [Struct `STC`](#0x1_STC_STC) -- [Resource `SharedBurnCapability`](#0x1_STC_SharedBurnCapability) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_STC_initialize) -- [Function `upgrade_from_v1_to_v2`](#0x1_STC_upgrade_from_v1_to_v2) -- [Function `initialize_v2`](#0x1_STC_initialize_v2) -- [Function `initialize_v3`](#0x1_STC_initialize_v3) -- [Function `is_stc`](#0x1_STC_is_stc) -- [Function `burn`](#0x1_STC_burn) -- [Function `token_address`](#0x1_STC_token_address) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Token;
-use 0x1::Treasury;
-
- - - - - -## Struct `STC` - -STC token marker. - - -
struct STC has copy, drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `SharedBurnCapability` - -Burn capability of STC. - - -
struct SharedBurnCapability has store, key
-
- - - -
-Fields - - -
-
-cap: Token::BurnCapability<STC::STC> -
-
- -
-
- - -
- - - -## Constants - - - - -precision of STC token. - - -
const PRECISION: u8 = 9;
-
- - - - - -## Function `initialize` - -STC initialization. - - -
public fun initialize(_account: &signer, _voting_delay: u64, _voting_period: u64, _voting_quorum_rate: u8, _min_action_delay: u64)
-
- - - -
-Implementation - - -
public fun initialize(
-    _account: &signer,
-    _voting_delay: u64,
-    _voting_period: u64,
-    _voting_quorum_rate: u8,
-    _min_action_delay: u64,
-) {
-    abort Errors::deprecated(1)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `upgrade_from_v1_to_v2` - - - -
public fun upgrade_from_v1_to_v2(account: &signer, total_amount: u128): Treasury::WithdrawCapability<STC::STC>
-
- - - -
-Implementation - - -
public fun upgrade_from_v1_to_v2(account: &signer, total_amount: u128, ): Treasury::WithdrawCapability<STC> {
-    CoreAddresses::assert_genesis_address(account);
-
-    // Mint all stc, and destroy mint capability
-    let total_stc = Token::mint<STC>(account, total_amount - Token::market_cap<STC>());
-    let withdraw_cap = Treasury::initialize(account, total_stc);
-    let mint_cap = Token::remove_mint_capability<STC>(account);
-    Token::destroy_mint_capability(mint_cap);
-    withdraw_cap
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `initialize_v2` - -STC initialization. - - -
public fun initialize_v2(_account: &signer, _total_amount: u128, _voting_delay: u64, _voting_period: u64, _voting_quorum_rate: u8, _min_action_delay: u64): Treasury::WithdrawCapability<STC::STC>
-
- - - -
-Implementation - - -
public fun initialize_v2(
-    _account: &signer,
-    _total_amount: u128,
-    _voting_delay: u64,
-    _voting_period: u64,
-    _voting_quorum_rate: u8,
-    _min_action_delay: u64,
-): Treasury::WithdrawCapability<STC> {
-    abort Errors::deprecated(1)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `initialize_v3` - -STC initialization. - - -
public fun initialize_v3(account: &signer, total_amount: u128): Treasury::WithdrawCapability<STC::STC>
-
- - - -
-Implementation - - -
public fun initialize_v3(
-    account: &signer,
-    total_amount: u128,
-): Treasury::WithdrawCapability<STC> {
-    Token::register_token<STC>(account, PRECISION);
-
-    // Mint all stc, and destroy mint capability
-
-    let total_stc = Token::mint<STC>(account, total_amount);
-    let withdraw_cap = Treasury::initialize(account, total_stc);
-    let mint_cap = Token::remove_mint_capability<STC>(account);
-    Token::destroy_mint_capability(mint_cap);
-
-    let burn_cap = Token::remove_burn_capability<STC>(account);
-    move_to(account, SharedBurnCapability { cap: burn_cap });
-    withdraw_cap
-}
-
- - - -
- -
-Specification - - - -
include Token::RegisterTokenAbortsIf<STC> { precision: PRECISION };
-
- - - -
- - - -## Function `is_stc` - -Returns true if TokenType is STC::STC - - -
public fun is_stc<TokenType: store>(): bool
-
- - - -
-Implementation - - -
public fun is_stc<TokenType: store>(): bool {
-    Token::is_same_token<STC, TokenType>()
-}
-
- - - -
- -
-Specification - - - -
- - - -## Function `burn` - -Burn STC tokens. -It can be called by anyone. - - -
public fun burn(token: Token::Token<STC::STC>)
-
- - - -
-Implementation - - -
public fun burn(token: Token<STC>) acquires SharedBurnCapability {
-    let cap = borrow_global<SharedBurnCapability>(token_address());
-    Token::burn_with_capability(&cap.cap, token);
-}
-
- - - -
- -
-Specification - - - -
aborts_if Token::spec_abstract_total_value<STC>() - token.value < 0;
-aborts_if !exists<SharedBurnCapability>(Token::SPEC_TOKEN_TEST_ADDRESS());
-
- - - -
- - - -## Function `token_address` - -Return STC token address. - - -
public fun token_address(): address
-
- - - -
-Implementation - - -
public fun token_address(): address {
-    Token::token_address<STC>()
-}
-
- - - -
- -
-Specification - - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/SharedEd25519PublicKey.md b/release/v12/docs/SharedEd25519PublicKey.md deleted file mode 100644 index f19c8fb2..00000000 --- a/release/v12/docs/SharedEd25519PublicKey.md +++ /dev/null @@ -1,309 +0,0 @@ - - - -# Module `0x1::SharedEd25519PublicKey` - -Each address that holds a SharedEd25519PublicKey resource can rotate the public key stored in -this resource, but the account's authentication key will be updated in lockstep. This ensures -that the two keys always stay in sync. - - -- [Resource `SharedEd25519PublicKey`](#0x1_SharedEd25519PublicKey_SharedEd25519PublicKey) -- [Constants](#@Constants_0) -- [Function `publish`](#0x1_SharedEd25519PublicKey_publish) -- [Function `rotate_key_`](#0x1_SharedEd25519PublicKey_rotate_key_) -- [Function `rotate_key`](#0x1_SharedEd25519PublicKey_rotate_key) -- [Function `key`](#0x1_SharedEd25519PublicKey_key) -- [Function `exists_at`](#0x1_SharedEd25519PublicKey_exists_at) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Account;
-use 0x1::Authenticator;
-use 0x1::Errors;
-use 0x1::Signature;
-use 0x1::Signer;
-
- - - - - -## Resource `SharedEd25519PublicKey` - -A resource that forces the account associated with rotation_cap to use a ed25519 -authentication key derived from key - - -
struct SharedEd25519PublicKey has key
-
- - - -
-Fields - - -
-
-key: vector<u8> -
-
- 32 byte ed25519 public key -
-
-rotation_cap: Account::KeyRotationCapability -
-
- rotation capability for an account whose authentication key is always derived from key -
-
- - -
- - - -## Constants - - - - - - -
const EMALFORMED_PUBLIC_KEY: u64 = 101;
-
- - - - - -## Function `publish` - -(1) Rotate the authentication key of the sender to key -(2) Publish a resource containing a 32-byte ed25519 public key and the rotation capability -of the sender under the account's address. -Aborts if the sender already has a SharedEd25519PublicKey resource. -Aborts if the length of new_public_key is not 32. - - -
public fun publish(account: &signer, key: vector<u8>)
-
- - - -
-Implementation - - -
public fun publish(account: &signer, key: vector<u8>) {
-    let t = SharedEd25519PublicKey {
-        key: x"",
-        rotation_cap: Account::extract_key_rotation_capability(account)
-    };
-    rotate_key_(&mut t, key);
-    move_to(account, t);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account::Account>(Signer::address_of(account));
-aborts_if StarcoinFramework::Option::is_none(global<Account::Account>(Signer::address_of(account)).key_rotation_capability);
-aborts_if !exists<Account::Account>(
-          StarcoinFramework::Option::borrow<Account::KeyRotationCapability>(
-              global<Account::Account>(Signer::address_of(account))
-              .key_rotation_capability
-          ).account_address);
-aborts_if !Signature::ed25519_validate_pubkey(key);
-aborts_if exists<SharedEd25519PublicKey>(Signer::address_of(account));
-aborts_if len(Authenticator::spec_ed25519_authentication_key(key)) != 32;
-
- - - -
- - - -## Function `rotate_key_` - - - -
fun rotate_key_(shared_key: &mut SharedEd25519PublicKey::SharedEd25519PublicKey, new_public_key: vector<u8>)
-
- - - -
-Implementation - - -
fun rotate_key_(shared_key: &mut SharedEd25519PublicKey, new_public_key: vector<u8>) {
-    // Cryptographic check of public key validity
-    assert!(
-        Signature::ed25519_validate_pubkey(copy new_public_key),
-        Errors::invalid_argument(EMALFORMED_PUBLIC_KEY)
-    );
-    Account::rotate_authentication_key_with_capability(
-        &shared_key.rotation_cap,
-        Authenticator::ed25519_authentication_key(copy new_public_key)
-    );
-    shared_key.key = new_public_key;
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Account::Account>(shared_key.rotation_cap.account_address);
-aborts_if !Signature::ed25519_validate_pubkey(new_public_key);
-aborts_if len(Authenticator::spec_ed25519_authentication_key(new_public_key)) != 32;
-
- - - -
- - - -## Function `rotate_key` - -(1) rotate the public key stored account's SharedEd25519PublicKey resource to -new_public_key -(2) rotate the authentication key using the capability stored in the account's -SharedEd25519PublicKey to a new value derived from new_public_key -Aborts if the sender does not have a SharedEd25519PublicKey resource. -Aborts if the length of new_public_key is not 32. - - -
public fun rotate_key(account: &signer, new_public_key: vector<u8>)
-
- - - -
-Implementation - - -
public fun rotate_key(account: &signer, new_public_key: vector<u8>) acquires SharedEd25519PublicKey {
-    rotate_key_(borrow_global_mut<SharedEd25519PublicKey>(Signer::address_of(account)), new_public_key);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<SharedEd25519PublicKey>(Signer::address_of(account));
-aborts_if !exists<Account::Account>(global<SharedEd25519PublicKey>(Signer::address_of(account)).rotation_cap.account_address);
-aborts_if !Signature::ed25519_validate_pubkey(new_public_key);
-aborts_if len(Authenticator::spec_ed25519_authentication_key(new_public_key)) != 32;
-
- - - -
- - - -## Function `key` - -Return the public key stored under addr. -Aborts if addr does not hold a SharedEd25519PublicKey resource. - - -
public fun key(addr: address): vector<u8>
-
- - - -
-Implementation - - -
public fun key(addr: address): vector<u8> acquires SharedEd25519PublicKey {
-    *&borrow_global<SharedEd25519PublicKey>(addr).key
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<SharedEd25519PublicKey>(addr);
-
- - - -
- - - -## Function `exists_at` - -Returns true if addr holds a SharedEd25519PublicKey resource. - - -
public fun exists_at(addr: address): bool
-
- - - -
-Implementation - - -
public fun exists_at(addr: address): bool {
-    exists<SharedEd25519PublicKey>(addr)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Signature.md b/release/v12/docs/Signature.md deleted file mode 100644 index e819d8cf..00000000 --- a/release/v12/docs/Signature.md +++ /dev/null @@ -1,154 +0,0 @@ - - - -# Module `0x1::Signature` - -Contains functions for [ed25519](https://en.wikipedia.org/wiki/EdDSA) digital signatures. - - -- [Function `ed25519_validate_pubkey`](#0x1_Signature_ed25519_validate_pubkey) -- [Function `ed25519_verify`](#0x1_Signature_ed25519_verify) -- [Function `native_ecrecover`](#0x1_Signature_native_ecrecover) -- [Function `ecrecover`](#0x1_Signature_ecrecover) -- [Function `secp256k1_verify`](#0x1_Signature_secp256k1_verify) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::EVMAddress;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Function `ed25519_validate_pubkey` - - - -
public fun ed25519_validate_pubkey(public_key: vector<u8>): bool
-
- - - -
-Implementation - - -
native public fun ed25519_validate_pubkey(public_key: vector<u8>): bool;
-
- - - -
- - - -## Function `ed25519_verify` - - - -
public fun ed25519_verify(signature: vector<u8>, public_key: vector<u8>, message: vector<u8>): bool
-
- - - -
-Implementation - - -
native public fun ed25519_verify(signature: vector<u8>, public_key: vector<u8>, message: vector<u8>): bool;
-
- - - -
- - - -## Function `native_ecrecover` - -recover address from ECDSA signature, if recover fail, return an empty vector - - -
fun native_ecrecover(hash: vector<u8>, signature: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
native fun native_ecrecover(hash: vector<u8>, signature: vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `ecrecover` - -recover address from ECDSA signature, if recover fail, return None - - -
public fun ecrecover(hash: vector<u8>, signature: vector<u8>): Option::Option<EVMAddress::EVMAddress>
-
- - - -
-Implementation - - -
public fun ecrecover(hash: vector<u8>, signature: vector<u8>):Option<EVMAddress>{
-    let bytes = native_ecrecover(hash, signature);
-    if (Vector::is_empty(&bytes)){
-        Option::none<EVMAddress>()
-    }else{
-        Option::some(EVMAddress::new(bytes))
-    }
-}
-
- - - -
- - - -## Function `secp256k1_verify` - - - -
public fun secp256k1_verify(signature: vector<u8>, addr: vector<u8>, message: vector<u8>): bool
-
- - - -
-Implementation - - -
public fun secp256k1_verify(signature: vector<u8>, addr: vector<u8>, message: vector<u8>) : bool{
-  let receover_address_opt:Option<EVMAddress>  = ecrecover(message, signature);
-  let expect_address =  EVMAddress::new(addr);
-  &Option::destroy_some<EVMAddress>(receover_address_opt) == &expect_address
-}
-
- - - -
- - - -## Module Specification - - - -
pragma intrinsic = true;
-
diff --git a/release/v12/docs/SignedInteger64.md b/release/v12/docs/SignedInteger64.md deleted file mode 100644 index 5d4c8fc2..00000000 --- a/release/v12/docs/SignedInteger64.md +++ /dev/null @@ -1,352 +0,0 @@ - - - -# Module `0x1::SignedInteger64` - -Implementation of i64. - - -- [Struct `SignedInteger64`](#0x1_SignedInteger64_SignedInteger64) -- [Function `multiply_u64`](#0x1_SignedInteger64_multiply_u64) -- [Function `divide_u64`](#0x1_SignedInteger64_divide_u64) -- [Function `sub_u64`](#0x1_SignedInteger64_sub_u64) -- [Function `add_u64`](#0x1_SignedInteger64_add_u64) -- [Function `create_from_raw_value`](#0x1_SignedInteger64_create_from_raw_value) -- [Function `get_value`](#0x1_SignedInteger64_get_value) -- [Function `is_negative`](#0x1_SignedInteger64_is_negative) -- [Module Specification](#@Module_Specification_0) - - -
- - - - - -## Struct `SignedInteger64` - -Define a signed integer type with two 32 bits. - - -
struct SignedInteger64 has copy, drop, store
-
- - - -
-Fields - - -
-
-value: u64 -
-
- -
-
-is_negative: bool -
-
- -
-
- - -
- - - -## Function `multiply_u64` - -Multiply a u64 integer by a signed integer number. - - -
public fun multiply_u64(num: u64, multiplier: SignedInteger64::SignedInteger64): SignedInteger64::SignedInteger64
-
- - - -
-Implementation - - -
public fun multiply_u64(num: u64, multiplier: SignedInteger64): SignedInteger64 {
-    let product = multiplier.value * num;
-    SignedInteger64 { value: product, is_negative: multiplier.is_negative }
-}
-
- - - -
- -
-Specification - - - -
aborts_if multiplier.value * num > max_u64();
-
- - - -
- - - -## Function `divide_u64` - -Divide a u64 integer by a signed integer number. - - -
public fun divide_u64(num: u64, divisor: SignedInteger64::SignedInteger64): SignedInteger64::SignedInteger64
-
- - - -
-Implementation - - -
public fun divide_u64(num: u64, divisor: SignedInteger64): SignedInteger64 {
-    let quotient = num / divisor.value;
-    SignedInteger64 { value: quotient, is_negative: divisor.is_negative }
-}
-
- - - -
- -
-Specification - - - -
aborts_if divisor.value == 0;
-
- - - -
- - - -## Function `sub_u64` - -Sub: num - minus - - -
public fun sub_u64(num: u64, minus: SignedInteger64::SignedInteger64): SignedInteger64::SignedInteger64
-
- - - -
-Implementation - - -
public fun sub_u64(num: u64, minus: SignedInteger64): SignedInteger64 {
-    if (minus.is_negative) {
-        let result = num + minus.value;
-        SignedInteger64 { value: result, is_negative: false }
-    } else {
-        if (num >= minus.value) {
-            let result = num - minus.value;
-            SignedInteger64 { value: result, is_negative: false }
-        }else {
-            let result = minus.value - num;
-            SignedInteger64 { value: result, is_negative: true }
-        }
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if minus.is_negative && num + minus.value > max_u64();
-
- - - -
- - - -## Function `add_u64` - -Add: num + addend - - -
public fun add_u64(num: u64, addend: SignedInteger64::SignedInteger64): SignedInteger64::SignedInteger64
-
- - - -
-Implementation - - -
public fun add_u64(num: u64, addend: SignedInteger64): SignedInteger64 {
-    if (addend.is_negative) {
-        if (num >= addend.value) {
-            let result = num - addend.value;
-            SignedInteger64 { value: result, is_negative: false }
-        }else {
-            let result = addend.value - num;
-            SignedInteger64 { value: result, is_negative: true }
-        }
-    } else {
-        let result = num + addend.value;
-        SignedInteger64 { value: result, is_negative: false }
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if !addend.is_negative && num + addend.value > max_u64();
-
- - - -
- - - -## Function `create_from_raw_value` - -Create a signed integer value from a unsigned integer - - -
public fun create_from_raw_value(value: u64, is_negative: bool): SignedInteger64::SignedInteger64
-
- - - -
-Implementation - - -
public fun create_from_raw_value(value: u64, is_negative: bool): SignedInteger64 {
-    SignedInteger64 { value, is_negative }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == SignedInteger64 { value, is_negative };
-
- - - -
- - - -## Function `get_value` - -Get value part of i64 ignore sign part. - - -
public fun get_value(num: SignedInteger64::SignedInteger64): u64
-
- - - -
-Implementation - - -
public fun get_value(num: SignedInteger64): u64 {
-    num.value
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == num.value;
-
- - - -
- - - -## Function `is_negative` - -Check if the given num is negative. - - -
public fun is_negative(num: SignedInteger64::SignedInteger64): bool
-
- - - -
-Implementation - - -
public fun is_negative(num: SignedInteger64): bool {
-    num.is_negative
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == num.is_negative;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Signer.md b/release/v12/docs/Signer.md deleted file mode 100644 index 8f0f1d8c..00000000 --- a/release/v12/docs/Signer.md +++ /dev/null @@ -1,94 +0,0 @@ - - - -# Module `0x1::Signer` - -Provide access methods for Signer. - - -- [Function `borrow_address`](#0x1_Signer_borrow_address) -- [Function `address_of`](#0x1_Signer_address_of) -- [Module Specification](#@Module_Specification_0) - - -
- - - - - -## Function `borrow_address` - -Borrows the address of the signer -Conceptually, you can think of the signer as being a resource struct wrapper around an -address -``` -resource struct Signer has key, store { addr: address } -``` -borrow_address borrows this inner field - - -
public fun borrow_address(s: &signer): &address
-
- - - -
-Implementation - - -
native public fun borrow_address(s: &signer): &address;
-
- - - -
- - - -## Function `address_of` - -Copies the address of the signer - - -
public fun address_of(s: &signer): address
-
- - - -
-Implementation - - -
public fun address_of(s: &signer): address {
-    *borrow_address(s)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures result == address_of(s);
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/SimpleMap.md b/release/v12/docs/SimpleMap.md deleted file mode 100644 index c6977084..00000000 --- a/release/v12/docs/SimpleMap.md +++ /dev/null @@ -1,422 +0,0 @@ - - - -# Module `0x1::SimpleMap` - -This module provides a solution for sorted maps, that is it has the properties that -1) Keys point to Values -2) Each Key must be unique -3) A Key can be found within O(Log N) time -4) The data is stored as sorted by Key -5) Adds and removals take O(N) time - - -- [Struct `SimpleMap`](#0x1_SimpleMap_SimpleMap) -- [Struct `Element`](#0x1_SimpleMap_Element) -- [Constants](#@Constants_0) -- [Function `length`](#0x1_SimpleMap_length) -- [Function `create`](#0x1_SimpleMap_create) -- [Function `borrow`](#0x1_SimpleMap_borrow) -- [Function `borrow_mut`](#0x1_SimpleMap_borrow_mut) -- [Function `contains_key`](#0x1_SimpleMap_contains_key) -- [Function `destroy_empty`](#0x1_SimpleMap_destroy_empty) -- [Function `add`](#0x1_SimpleMap_add) -- [Function `remove`](#0x1_SimpleMap_remove) -- [Function `find`](#0x1_SimpleMap_find) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::BCS;
-use 0x1::Compare;
-use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `SimpleMap` - - - -
struct SimpleMap<Key, Value> has copy, drop, store
-
- - - -
-Fields - - -
-
-data: vector<SimpleMap::Element<Key, Value>> -
-
- -
-
- - -
- - - -## Struct `Element` - - - -
struct Element<Key, Value> has copy, drop, store
-
- - - -
-Fields - - -
-
-key: Key -
-
- -
-
-value: Value -
-
- -
-
- - -
- - - -## Constants - - - - -Map key already exists - - -
const EKEY_ALREADY_EXISTS: u64 = 1;
-
- - - - - -Map key is not found - - -
const EKEY_NOT_FOUND: u64 = 2;
-
- - - - - -## Function `length` - - - -
public fun length<Key: store, Value: store>(map: &SimpleMap::SimpleMap<Key, Value>): u64
-
- - - -
-Implementation - - -
public fun length<Key: store, Value: store>(map: &SimpleMap<Key, Value>): u64 {
-    Vector::length(&map.data)
-}
-
- - - -
- - - -## Function `create` - - - -
public fun create<Key: store, Value: store>(): SimpleMap::SimpleMap<Key, Value>
-
- - - -
-Implementation - - -
public fun create<Key: store, Value: store>(): SimpleMap<Key, Value> {
-    SimpleMap {
-        data: Vector::empty(),
-    }
-}
-
- - - -
- - - -## Function `borrow` - - - -
public fun borrow<Key: store, Value: store>(map: &SimpleMap::SimpleMap<Key, Value>, key: &Key): &Value
-
- - - -
-Implementation - - -
public fun borrow<Key: store, Value: store>(
-    map: &SimpleMap<Key, Value>,
-    key: &Key,
-): &Value {
-    let (maybe_idx, _) = find(map, key);
-    assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND));
-    let idx = Option::extract(&mut maybe_idx);
-    &Vector::borrow(&map.data, idx).value
-}
-
- - - -
- - - -## Function `borrow_mut` - - - -
public fun borrow_mut<Key: store, Value: store>(map: &mut SimpleMap::SimpleMap<Key, Value>, key: &Key): &mut Value
-
- - - -
-Implementation - - -
public fun borrow_mut<Key: store, Value: store>(
-    map: &mut SimpleMap<Key, Value>,
-    key: &Key,
-): &mut Value {
-    let (maybe_idx, _) = find(map, key);
-    assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND));
-    let idx = Option::extract(&mut maybe_idx);
-    &mut Vector::borrow_mut(&mut map.data, idx).value
-}
-
- - - -
- - - -## Function `contains_key` - - - -
public fun contains_key<Key: store, Value: store>(map: &SimpleMap::SimpleMap<Key, Value>, key: &Key): bool
-
- - - -
-Implementation - - -
public fun contains_key<Key: store, Value: store>(
-    map: &SimpleMap<Key, Value>,
-    key: &Key,
-): bool {
-    let (maybe_idx, _) = find(map, key);
-    Option::is_some(&maybe_idx)
-}
-
- - - -
- - - -## Function `destroy_empty` - - - -
public fun destroy_empty<Key: store, Value: store>(map: SimpleMap::SimpleMap<Key, Value>)
-
- - - -
-Implementation - - -
public fun destroy_empty<Key: store, Value: store>(map: SimpleMap<Key, Value>) {
-    let SimpleMap { data } = map;
-    Vector::destroy_empty(data);
-}
-
- - - -
- - - -## Function `add` - - - -
public fun add<Key: store, Value: store>(map: &mut SimpleMap::SimpleMap<Key, Value>, key: Key, value: Value)
-
- - - -
-Implementation - - -
public fun add<Key: store, Value: store>(
-    map: &mut SimpleMap<Key, Value>,
-    key: Key,
-    value: Value,
-) {
-    let (maybe_idx, maybe_placement) = find(map, &key);
-    assert!(Option::is_none(&maybe_idx), Errors::invalid_argument(EKEY_ALREADY_EXISTS));
-
-    // Append to the end and then swap elements until the list is ordered again
-    Vector::push_back(&mut map.data, Element { key, value });
-
-    let placement = Option::extract(&mut maybe_placement);
-    let end = Vector::length(&map.data) - 1;
-    while (placement < end) {
-        Vector::swap(&mut map.data, placement, end);
-        placement = placement + 1;
-    };
-}
-
- - - -
- - - -## Function `remove` - - - -
public fun remove<Key: store, Value: store>(map: &mut SimpleMap::SimpleMap<Key, Value>, key: &Key): (Key, Value)
-
- - - -
-Implementation - - -
public fun remove<Key: store, Value: store>(
-    map: &mut SimpleMap<Key, Value>,
-    key: &Key,
-): (Key, Value) {
-    let (maybe_idx, _) = find(map, key);
-    assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND));
-
-    let placement = Option::extract(&mut maybe_idx);
-    let end = Vector::length(&map.data) - 1;
-
-    while (placement < end) {
-        Vector::swap(&mut map.data, placement, placement + 1);
-        placement = placement + 1;
-    };
-
-    let Element { key, value } = Vector::pop_back(&mut map.data);
-    (key, value)
-}
-
- - - -
- - - -## Function `find` - - - -
fun find<Key: store, Value: store>(map: &SimpleMap::SimpleMap<Key, Value>, key: &Key): (Option::Option<u64>, Option::Option<u64>)
-
- - - -
-Implementation - - -
fun find<Key: store, Value: store>(
-    map: &SimpleMap<Key, Value>,
-    key: &Key,
-): (Option::Option<u64>, Option::Option<u64>) {
-    let length = Vector::length(&map.data);
-
-    if (length == 0) {
-        return (Option::none(), Option::some(0))
-    };
-
-    let left = 0;
-    let right = length;
-
-    while (left != right) {
-        let mid = left + (right - left) / 2;
-        let potential_key = &Vector::borrow(&map.data, mid).key;
-        if (Compare::is_less_than(Compare::cmp_bytes(&BCS::to_bytes(potential_key), &BCS::to_bytes(key)))) {
-            left = mid + 1;
-        } else {
-            right = mid;
-        };
-    };
-
-    if (left != length && key == &Vector::borrow(&map.data, left).key) {
-        (Option::some(left), Option::none())
-    } else {
-        (Option::none(), Option::some(left))
-    }
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/SnapshotUtil.md b/release/v12/docs/SnapshotUtil.md deleted file mode 100644 index 15c3b73e..00000000 --- a/release/v12/docs/SnapshotUtil.md +++ /dev/null @@ -1,583 +0,0 @@ - - - -# Module `0x1::SnapshotUtil` - - - -- [Struct `StructTag0`](#0x1_SnapshotUtil_StructTag0) -- [Struct `TypeTag0`](#0x1_SnapshotUtil_TypeTag0) -- [Struct `StructTag1`](#0x1_SnapshotUtil_StructTag1) -- [Struct `TypeTag1`](#0x1_SnapshotUtil_TypeTag1) -- [Struct `StructTag2`](#0x1_SnapshotUtil_StructTag2) -- [Constants](#@Constants_0) -- [Function `get_sturct_tag`](#0x1_SnapshotUtil_get_sturct_tag) -- [Function `generate_struct_tag`](#0x1_SnapshotUtil_generate_struct_tag) -- [Function `get_dao_struct_tag`](#0x1_SnapshotUtil_get_dao_struct_tag) -- [Function `get_access_path`](#0x1_SnapshotUtil_get_access_path) -- [Function `get_access_path_dao_member_slice`](#0x1_SnapshotUtil_get_access_path_dao_member_slice) -- [Function `get_access_path_dao_member_body_slice`](#0x1_SnapshotUtil_get_access_path_dao_member_body_slice) -- [Function `struct_tag_to_string`](#0x1_SnapshotUtil_struct_tag_to_string) -- [Function `to_hex_string_without_prefix`](#0x1_SnapshotUtil_to_hex_string_without_prefix) -- [Function `address_to_hex_string`](#0x1_SnapshotUtil_address_to_hex_string) - - -
use 0x1::BCS;
-use 0x1::Token;
-use 0x1::Vector;
-
- - - - - -## Struct `StructTag0` - -Struct Tag which identify a unique Struct. - - -
struct StructTag0 has copy, drop, store
-
- - - -
-Fields - - -
-
-addr: address -
-
- -
-
-module_name: vector<u8> -
-
- -
-
-name: vector<u8> -
-
- -
-
-types: vector<u8> -
-
- -
-
- - -
- - - -## Struct `TypeTag0` - - - -
struct TypeTag0 has copy, drop, store
-
- - - -
-Fields - - -
-
-variant_index: u8 -
-
- -
-
-struct_tag: SnapshotUtil::StructTag0 -
-
- -
-
- - -
- - - -## Struct `StructTag1` - - - -
struct StructTag1 has copy, drop, store
-
- - - -
-Fields - - -
-
-addr: address -
-
- -
-
-module_name: vector<u8> -
-
- -
-
-name: vector<u8> -
-
- -
-
-types: vector<SnapshotUtil::TypeTag0> -
-
- -
-
- - -
- - - -## Struct `TypeTag1` - - - -
struct TypeTag1 has copy, drop, store
-
- - - -
-Fields - - -
-
-variant_index: u8 -
-
- -
-
-struct_tag: SnapshotUtil::StructTag1 -
-
- -
-
- - -
- - - -## Struct `StructTag2` - - - -
struct StructTag2 has copy, drop, store
-
- - - -
-Fields - - -
-
-addr: address -
-
- -
-
-module_name: vector<u8> -
-
- -
-
-name: vector<u8> -
-
- -
-
-types: vector<SnapshotUtil::TypeTag1> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const HEX_SYMBOLS: vector<u8> = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102];
-
- - - - - -## Function `get_sturct_tag` - - - -
public fun get_sturct_tag<DAOT: store>(): vector<u8>
-
- - - -
-Implementation - - -
public fun get_sturct_tag<DAOT: store>(): vector<u8> {
-    let struct_tags = generate_struct_tag<DAOT>();
-    BCS::to_bytes(&struct_tags)
-}
-
- - - -
- - - -## Function `generate_struct_tag` - - - -
fun generate_struct_tag<DAOT: store>(): SnapshotUtil::StructTag2
-
- - - -
-Implementation - - -
fun generate_struct_tag<DAOT: store>(): StructTag2{
-    let dao_struct_tag = get_dao_struct_tag<DAOT>();
-    let dao_type_tag = TypeTag0 {
-        variant_index: 7,
-        struct_tag: dao_struct_tag,
-    };
-    let dao_type_tags = Vector::empty<TypeTag0>();
-    Vector::push_back(&mut dao_type_tags, dao_type_tag);
-
-    // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember
-    let dao_member_struct_tag = StructTag1 {
-        addr: @0x00000000000000000000000000000001,
-        module_name: b"DAOSpace",
-        name: b"DAOMember",
-        types: *&dao_type_tags
-    };
-
-    // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody
-    let dao_member_body_struct_tag = StructTag1 {
-        addr: @0x00000000000000000000000000000001,
-        module_name: b"DAOSpace",
-        name: b"DAOMemberBody",
-        types: *&dao_type_tags
-    };
-
-    let dao_member_type_tag = TypeTag1 {
-        variant_index: 7,
-        struct_tag: dao_member_struct_tag,
-    };
-    let dao_member_body_type_tag = TypeTag1 {
-        variant_index: 7,
-        struct_tag: dao_member_body_struct_tag,
-    };
-    let type_tags = Vector::empty<TypeTag1>();
-    Vector::push_back(&mut type_tags, dao_member_type_tag);
-    Vector::push_back(&mut type_tags, dao_member_body_type_tag);
-
-    StructTag2 {
-        addr: @0x00000000000000000000000000000001,
-        module_name: b"IdentifierNFT",
-        name: b"IdentifierNFT",
-        types: type_tags,
-    }
-}
-
- - - -
- - - -## Function `get_dao_struct_tag` - - - -
fun get_dao_struct_tag<DAOT: store>(): SnapshotUtil::StructTag0
-
- - - -
-Implementation - - -
fun get_dao_struct_tag<DAOT: store>(): StructTag0{
-    // DAOT is also TokenT
-    let token_code = Token::token_code<DAOT>();
-    let token_code_bcs = BCS::to_bytes(&token_code);
-
-    let offset = 0;
-    let (address, offset) = BCS::deserialize_address(&token_code_bcs, offset);
-    let (module_name, offset) = BCS::deserialize_bytes(&token_code_bcs, offset);
-    let (name, _offset) = BCS::deserialize_bytes(&token_code_bcs, offset);
-
-    StructTag0 {
-        addr: address,
-        module_name,
-        name,
-        types: Vector::empty<u8>(),
-    }
-}
-
- - - -
- - - -## Function `get_access_path` - - - -
public fun get_access_path<DaoT: store>(user_addr: address): vector<u8>
-
- - - -
-Implementation - - -
public fun get_access_path<DaoT: store>(user_addr: address): vector<u8> {
-
-    //    0x6bfb460477adf9dd0455d3de2fc7f211/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<
-    //        0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>
-    //        ,0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>>
-
-    let access_path_slice_0 = b"/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT";
-    let access_path_bytes = Vector::empty();
-    Vector::append(&mut access_path_bytes, address_to_hex_string(*&user_addr));
-    Vector::append(&mut access_path_bytes, access_path_slice_0);
-    Vector::append(&mut access_path_bytes, b"<");
-    Vector::append(&mut access_path_bytes, get_access_path_dao_member_slice<DaoT>());
-    Vector::append(&mut access_path_bytes, b",");
-    Vector::append(&mut access_path_bytes, get_access_path_dao_member_body_slice<DaoT>());
-    Vector::append(&mut access_path_bytes, b">");
-
-    access_path_bytes
-}
-
- - - -
- - - -## Function `get_access_path_dao_member_slice` - - - -
fun get_access_path_dao_member_slice<DaoT: store>(): vector<u8>
-
- - - -
-Implementation - - -
fun get_access_path_dao_member_slice<DaoT:store>(): vector<u8>{
-    let dao_member_slice_0 = b"0x00000000000000000000000000000001::DAOSpace::DAOMember";
-    let slice = Vector::empty();
-    Vector::append(&mut slice, dao_member_slice_0);
-    Vector::append(&mut slice, b"<");
-    Vector::append(&mut slice, struct_tag_to_string<DaoT>());
-    Vector::append(&mut slice, b">");
-
-    slice
-}
-
- - - -
- - - -## Function `get_access_path_dao_member_body_slice` - - - -
fun get_access_path_dao_member_body_slice<DaoT: store>(): vector<u8>
-
- - - -
-Implementation - - -
fun get_access_path_dao_member_body_slice<DaoT:store>(): vector<u8>{
-    let dao_member_body_slice_0 = b"0x00000000000000000000000000000001::DAOSpace::DAOMemberBody";
-    let slice = Vector::empty();
-    Vector::append(&mut slice, dao_member_body_slice_0);
-    Vector::append(&mut slice, b"<");
-    Vector::append(&mut slice, struct_tag_to_string<DaoT>());
-    Vector::append(&mut slice, b">");
-
-    slice
-}
-
- - - -
- - - -## Function `struct_tag_to_string` - - - -
fun struct_tag_to_string<DaoT: store>(): vector<u8>
-
- - - -
-Implementation - - -
fun struct_tag_to_string<DaoT:store>(): vector<u8> {
-    let struct_tag = get_dao_struct_tag<DaoT>();
-    let struct_tag_slice = Vector::empty();
-    Vector::append(&mut struct_tag_slice, address_to_hex_string(*&struct_tag.addr));
-    Vector::append(&mut struct_tag_slice, b"::");
-    Vector::append(&mut struct_tag_slice, *&struct_tag.module_name);
-    Vector::append(&mut struct_tag_slice, b"::");
-    Vector::append(&mut struct_tag_slice, *&struct_tag.name);
-
-    struct_tag_slice
-}
-
- - - -
- - - -## Function `to_hex_string_without_prefix` - -Converts a u8 to its hexadecimal representation with fixed length (in whole bytes). -so the returned String is 2 * length in size - - -
public fun to_hex_string_without_prefix(value: u8): vector<u8>
-
- - - -
-Implementation - - -
public fun to_hex_string_without_prefix(value: u8): vector<u8> {
-    if (value == 0) {
-        return b"00"
-    };
-
-    let buffer = Vector::empty<u8>();
-    let len = 1;
-    let i: u64 = 0;
-    while (i < len * 2) {
-        Vector::push_back(&mut buffer, *Vector::borrow(&HEX_SYMBOLS, (value & 0xf as u64)));
-        value = value >> 4;
-        i = i + 1;
-    };
-    assert!(value == 0, 1);
-    Vector::reverse(&mut buffer);
-    buffer
-}
-
- - - -
- - - -## Function `address_to_hex_string` - -Converts a address to its hexadecimal representation with fixed length (in whole bytes). -so the returned String is 2 * length + 2(with '0x') in size - - -
fun address_to_hex_string(addr: address): vector<u8>
-
- - - -
-Implementation - - -
fun address_to_hex_string(addr: address): vector<u8>{
-    let hex_string = Vector::empty<u8>();
-    Vector::append(&mut hex_string, b"0x");
-    let addr_bytes = BCS::to_bytes<address>(&addr);
-    let i = 0;
-    let len = Vector::length(&addr_bytes);
-    while (i < len) {
-        let hex_slice = to_hex_string_without_prefix(*Vector::borrow(&addr_bytes, i));
-        Vector::append(&mut hex_string, hex_slice);
-        i = i + 1;
-    };
-    hex_string
-}
-
- - - -
diff --git a/release/v12/docs/StakeToSBTPlugin.md b/release/v12/docs/StakeToSBTPlugin.md deleted file mode 100644 index c2b828fd..00000000 --- a/release/v12/docs/StakeToSBTPlugin.md +++ /dev/null @@ -1,1648 +0,0 @@ - - - -# Module `0x1::StakeToSBTPlugin` - - - -- [Struct `StakeToSBTPlugin`](#0x1_StakeToSBTPlugin_StakeToSBTPlugin) -- [Resource `Stake`](#0x1_StakeToSBTPlugin_Stake) -- [Resource `StakeList`](#0x1_StakeToSBTPlugin_StakeList) -- [Struct `LockWeightConfig`](#0x1_StakeToSBTPlugin_LockWeightConfig) -- [Struct `LockWeight`](#0x1_StakeToSBTPlugin_LockWeight) -- [Struct `AcceptTokenCap`](#0x1_StakeToSBTPlugin_AcceptTokenCap) -- [Struct `SBTTokenAcceptedEvent`](#0x1_StakeToSBTPlugin_SBTTokenAcceptedEvent) -- [Struct `SBTWeightChangedEvent`](#0x1_StakeToSBTPlugin_SBTWeightChangedEvent) -- [Struct `SBTStakeEvent`](#0x1_StakeToSBTPlugin_SBTStakeEvent) -- [Struct `SBTUnstakeEvent`](#0x1_StakeToSBTPlugin_SBTUnstakeEvent) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_StakeToSBTPlugin_initialize) -- [Function `required_caps`](#0x1_StakeToSBTPlugin_required_caps) -- [Function `accept_token_by_dao`](#0x1_StakeToSBTPlugin_accept_token_by_dao) -- [Function `install_event`](#0x1_StakeToSBTPlugin_install_event) -- [Function `set_sbt_weight_by_dao`](#0x1_StakeToSBTPlugin_set_sbt_weight_by_dao) -- [Function `accept_token`](#0x1_StakeToSBTPlugin_accept_token) -- [Function `stake`](#0x1_StakeToSBTPlugin_stake) -- [Function `stake_entry`](#0x1_StakeToSBTPlugin_stake_entry) -- [Function `query_stake`](#0x1_StakeToSBTPlugin_query_stake) -- [Function `query_stake_count`](#0x1_StakeToSBTPlugin_query_stake_count) -- [Function `unstake_by_id`](#0x1_StakeToSBTPlugin_unstake_by_id) -- [Function `unstake_by_id_entry`](#0x1_StakeToSBTPlugin_unstake_by_id_entry) -- [Function `unstake_all`](#0x1_StakeToSBTPlugin_unstake_all) -- [Function `unstake_all_entry`](#0x1_StakeToSBTPlugin_unstake_all_entry) -- [Function `unstake_item`](#0x1_StakeToSBTPlugin_unstake_item) -- [Function `get_sbt_weight`](#0x1_StakeToSBTPlugin_get_sbt_weight) -- [Function `set_sbt_weight`](#0x1_StakeToSBTPlugin_set_sbt_weight) -- [Function `find_item`](#0x1_StakeToSBTPlugin_find_item) -- [Function `compute_token_to_sbt`](#0x1_StakeToSBTPlugin_compute_token_to_sbt) -- [Function `create_weight_proposal`](#0x1_StakeToSBTPlugin_create_weight_proposal) -- [Function `create_weight_proposal_entry`](#0x1_StakeToSBTPlugin_create_weight_proposal_entry) -- [Function `execute_weight_proposal`](#0x1_StakeToSBTPlugin_execute_weight_proposal) -- [Function `execute_weight_proposal_entry`](#0x1_StakeToSBTPlugin_execute_weight_proposal_entry) -- [Function `create_token_accept_proposal`](#0x1_StakeToSBTPlugin_create_token_accept_proposal) -- [Function `create_token_accept_proposal_entry`](#0x1_StakeToSBTPlugin_create_token_accept_proposal_entry) -- [Function `execute_token_accept_proposal`](#0x1_StakeToSBTPlugin_execute_token_accept_proposal) -- [Function `execute_token_accept_proposal_entry`](#0x1_StakeToSBTPlugin_execute_token_accept_proposal_entry) -- [Function `install_plugin_proposal`](#0x1_StakeToSBTPlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_StakeToSBTPlugin_install_plugin_proposal_entry) - - -
use 0x1::Account;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Errors;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::Vector;
-
- - - - - -## Struct `StakeToSBTPlugin` - - - -
struct StakeToSBTPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `Stake` - - - -
struct Stake<DAOT, TokenT> has store, key
-
- - - -
-Fields - - -
-
-id: u64 -
-
- -
-
-token: Token::Token<TokenT> -
-
- -
-
-stake_time: u64 -
-
- -
-
-lock_time: u64 -
-
- -
-
-weight: u64 -
-
- -
-
-sbt_amount: u128 -
-
- -
-
- - -
- - - -## Resource `StakeList` - - - -
struct StakeList<DAOT, TokenT> has store, key
-
- - - -
-Fields - - -
-
-items: vector<StakeToSBTPlugin::Stake<DAOT, TokenT>> -
-
- -
-
-next_id: u64 -
-
- -
-
- - -
- - - -## Struct `LockWeightConfig` - - - -
struct LockWeightConfig<DAOT, TokenT> has copy, drop, store
-
- - - -
-Fields - - -
-
-weight_vec: vector<StakeToSBTPlugin::LockWeight<DAOT, TokenT>> -
-
- -
-
- - -
- - - -## Struct `LockWeight` - - - -
struct LockWeight<DAOT, TokenT> has copy, drop, store
-
- - - -
-Fields - - -
-
-lock_time: u64 -
-
- -
-
-weight: u64 -
-
- -
-
- - -
- - - -## Struct `AcceptTokenCap` - - - -
struct AcceptTokenCap<DAOT, TokenT> has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `SBTTokenAcceptedEvent` - -Events - - -
struct SBTTokenAcceptedEvent has copy, drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-token_code: Token::TokenCode -
-
- -
-
- - -
- - - -## Struct `SBTWeightChangedEvent` - - - -
struct SBTWeightChangedEvent has copy, drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-token_code: Token::TokenCode -
-
- -
-
-lock_time: u64 -
-
- -
-
-weight: u64 -
-
- -
-
- - -
- - - -## Struct `SBTStakeEvent` - - - -
struct SBTStakeEvent has copy, drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-stake_id: u64 -
-
- -
-
-token_code: Token::TokenCode -
-
- -
-
-amount: u128 -
-
- -
-
-lock_time: u64 -
-
- -
-
-weight: u64 -
-
- -
-
-sbt_amount: u128 -
-
- -
-
-member: address -
-
- -
-
- - -
- - - -## Struct `SBTUnstakeEvent` - - - -
struct SBTUnstakeEvent has copy, drop, store
-
- - - -
-Fields - - -
-
-dao_id: u64 -
-
- -
-
-stake_id: u64 -
-
- -
-
-token_code: Token::TokenCode -
-
- -
-
-amount: u128 -
-
- -
-
-lock_time: u64 -
-
- -
-
-weight: u64 -
-
- -
-
-sbt_amount: u128 -
-
- -
-
-member: address -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_PLUGIN_CONFIG_INIT_REPEATE: u64 = 1005;
-
- - - - - - - -
const ERR_PLUGIN_HAS_STAKED: u64 = 1002;
-
- - - - - - - -
const ERR_PLUGIN_ITEM_CANT_FOUND: u64 = 1006;
-
- - - - - - - -
const ERR_PLUGIN_NOT_STAKE: u64 = 1003;
-
- - - - - - - -
const ERR_PLUGIN_NO_MATCH_LOCKTIME: u64 = 1007;
-
- - - - - - - -
const ERR_PLUGIN_STILL_LOCKED: u64 = 1004;
-
- - - - - - - -
const ERR_PLUGIN_USER_IS_MEMBER: u64 = 1001;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = StakeToSBTPlugin {};
-
-    DAOPluginMarketplace::register_plugin<StakeToSBTPlugin>(
-        &witness,
-        b"0x1::StakeToSBTPlugin",
-        b"The plugin for stake to SBT",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<StakeToSBTPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://stake-to-sbt-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps(): vector<DAOSpace::CapType> {
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::member_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::plugin_event_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `accept_token_by_dao` - -Accept token with token type by given DAO - - -
public fun accept_token_by_dao<DAOT: store, TokenT: store>(_witness: &DAOT)
-
- - - -
-Implementation - - -
public fun accept_token_by_dao<DAOT: store, TokenT: store>(_witness: &DAOT) {
-    install_event<DAOT>();
-    accept_token(AcceptTokenCap<DAOT, TokenT> {});
-}
-
- - - -
- - - -## Function `install_event` - - - -
public fun install_event<DAOT: store>()
-
- - - -
-Implementation - - -
public fun install_event<DAOT: store>() {
-    let witness = StakeToSBTPlugin {};
-    let plugin_event_cap =
-        DAOSpace::acquire_plugin_event_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-    DAOSpace::init_plugin_event<DAOT, StakeToSBTPlugin, SBTTokenAcceptedEvent>(&plugin_event_cap);
-    DAOSpace::init_plugin_event<DAOT, StakeToSBTPlugin, SBTWeightChangedEvent>(&plugin_event_cap);
-    DAOSpace::init_plugin_event<DAOT, StakeToSBTPlugin, SBTStakeEvent>(&plugin_event_cap);
-    DAOSpace::init_plugin_event<DAOT, StakeToSBTPlugin, SBTUnstakeEvent>(&plugin_event_cap);
-}
-
- - - -
- - - -## Function `set_sbt_weight_by_dao` - -Set sbt weight by given DAO - - -
public fun set_sbt_weight_by_dao<DAOT: store, TokenT: store>(_witness: &DAOT, lock_time: u64, weight: u64)
-
- - - -
-Implementation - - -
public fun set_sbt_weight_by_dao<DAOT: store, TokenT: store>(
-    _witness: &DAOT,
-    lock_time: u64,
-    weight: u64
-) {
-    set_sbt_weight<DAOT, TokenT>(lock_time, weight);
-}
-
- - - -
- - - -## Function `accept_token` - -Accept token with token type - - -
public fun accept_token<DAOT: store, TokenT: store>(cap: StakeToSBTPlugin::AcceptTokenCap<DAOT, TokenT>)
-
- - - -
-Implementation - - -
public fun accept_token<DAOT: store, TokenT: store>(cap: AcceptTokenCap<DAOT, TokenT>) {
-    let AcceptTokenCap<DAOT, TokenT> {} = cap;
-    assert!(
-        !DAOSpace::exists_custom_config<DAOT, LockWeightConfig<DAOT, TokenT>>(),
-        Errors::invalid_state(ERR_PLUGIN_CONFIG_INIT_REPEATE)
-    );
-
-    let witness = StakeToSBTPlugin {};
-    let modify_config_cap =
-        DAOSpace::acquire_modify_config_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-    DAOSpace::set_custom_config<
-        DAOT,
-        StakeToSBTPlugin,
-        LockWeightConfig<DAOT, TokenT>
-    >(&mut modify_config_cap, LockWeightConfig<DAOT, TokenT> {
-        weight_vec: Vector::empty<LockWeight<DAOT, TokenT>>()
-    });
-
-    let witness = StakeToSBTPlugin {};
-    let plugin_event_cap =
-        DAOSpace::acquire_plugin_event_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-    DAOSpace::emit_plugin_event<DAOT, StakeToSBTPlugin, SBTTokenAcceptedEvent>(
-        &plugin_event_cap,
-        SBTTokenAcceptedEvent {
-            dao_id: DAOSpace::dao_id(DAOSpace::dao_address<DAOT>()),
-            token_code: Token::token_code<TokenT>(),
-        }
-    );
-}
-
- - - -
- - - -## Function `stake` - - - -
public fun stake<DAOT: store, TokenT: store>(sender: &signer, token: Token::Token<TokenT>, lock_time: u64): u64
-
- - - -
-Implementation - - -
public fun stake<DAOT: store, TokenT: store>(
-    sender: &signer,
-    token: Token::Token<TokenT>,
-    lock_time: u64
-): u64 acquires StakeList {
-    let sender_addr = Signer::address_of(sender);
-    // Increase SBT
-    let witness = StakeToSBTPlugin {};
-    let member_cap =
-        DAOSpace::acquire_member_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-    if (!DAOSpace::is_member<DAOT>(sender_addr) ) {
-        DAOSpace::issue_member_offer<DAOT, StakeToSBTPlugin>(
-            &member_cap,
-            sender_addr,
-            Option::none<vector<u8>>(),
-            Option::none<vector<u8>>(),
-            0
-        );
-        DAOSpace::accept_member_offer<DAOT>(sender);
-    };
-
-    if (!exists<StakeList<DAOT, TokenT>>(sender_addr)) {
-        move_to(sender, StakeList<DAOT, TokenT> {
-            items: Vector::empty(),
-            next_id: 0
-        });
-    };
-
-    let weight_opt = get_sbt_weight<DAOT, TokenT>(lock_time);
-    assert!(Option::is_some(&weight_opt), Errors::invalid_state(ERR_PLUGIN_NO_MATCH_LOCKTIME));
-
-    let weight = Option::destroy_some(weight_opt);
-    let sbt_amount = compute_token_to_sbt(weight, &token);
-    DAOSpace::increase_member_sbt(&member_cap, sender_addr, sbt_amount);
-
-    let stake_list = borrow_global_mut<StakeList<DAOT, TokenT>>(sender_addr);
-    let id = stake_list.next_id + 1;
-    Vector::push_back(
-        &mut stake_list.items,
-        Stake<DAOT, TokenT> {
-            id,
-            token,
-            lock_time,
-            stake_time: Timestamp::now_seconds(),
-            weight,
-            sbt_amount
-        });
-    stake_list.next_id = id;
-
-    let witness = StakeToSBTPlugin {};
-    let plugin_event_cap =
-        DAOSpace::acquire_plugin_event_cap<DAOT, StakeToSBTPlugin>(&witness);
-    DAOSpace::emit_plugin_event<DAOT, StakeToSBTPlugin, SBTStakeEvent>(
-        &plugin_event_cap,
-        SBTStakeEvent {
-            dao_id: DAOSpace::dao_id(DAOSpace::dao_address<DAOT>()),
-            stake_id: id,
-            token_code: Token::token_code<TokenT>(),
-            amount: sbt_amount,
-            lock_time,
-            weight,
-            sbt_amount,
-            member: sender_addr,
-        }
-    );
-    id
-}
-
- - - -
- - - -## Function `stake_entry` - - - -
public(script) fun stake_entry<DAOT: store, TokenT: store>(sender: signer, amount: u128, lock_time: u64)
-
- - - -
-Implementation - - -
public(script) fun stake_entry<DAOT: store, TokenT: store>(
-    sender: signer,
-    amount: u128,
-    lock_time: u64
-) acquires StakeList {
-    let token = Account::withdraw<TokenT>(&sender, amount);
-    stake<DAOT, TokenT>(&sender, token, lock_time);
-}
-
- - - -
- - - -## Function `query_stake` - - - -
public fun query_stake<DAOT: store, TokenT: store>(member: address, id: u64): (u64, u64, u64, u128, u128)
-
- - - -
-Implementation - - -
public fun query_stake<DAOT: store, TokenT: store>(
-    member: address,
-    id: u64
-): (u64, u64, u64, u128, u128) acquires StakeList {
-    assert!(exists<StakeList<DAOT, TokenT>>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE));
-    let stake_list = borrow_global_mut<StakeList<DAOT, TokenT>>(member);
-    let item_index = find_item(id, &stake_list.items);
-
-    // Check item in item container
-    assert!(Option::is_some(&item_index), Errors::invalid_state(ERR_PLUGIN_ITEM_CANT_FOUND));
-
-    let stake =
-        Vector::borrow(&mut stake_list.items, Option::destroy_some(item_index));
-    (
-        stake.stake_time,
-        stake.lock_time,
-        stake.weight,
-        stake.sbt_amount,
-        Token::value(&stake.token),
-    )
-}
-
- - - -
- - - -## Function `query_stake_count` - -Query stake count from stake list - - -
public fun query_stake_count<DAOT: store, TokenT: store>(member: address): u64
-
- - - -
-Implementation - - -
public fun query_stake_count<DAOT: store, TokenT: store>(member: address): u64 acquires StakeList {
-    assert!(exists<StakeList<DAOT, TokenT>>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE));
-    let stake_list = borrow_global<StakeList<DAOT, TokenT>>(member);
-    Vector::length(&stake_list.items)
-}
-
- - - -
- - - -## Function `unstake_by_id` - -Unstake from staking - - -
public fun unstake_by_id<DAOT: store, TokenT: store>(sender: &signer, id: u64)
-
- - - -
-Implementation - - -
public fun unstake_by_id<DAOT: store, TokenT: store>(sender: &signer, id: u64) acquires StakeList {
-    let member = Signer::address_of(sender);
-    assert!(exists<StakeList<DAOT, TokenT>>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE));
-    let stake_list = borrow_global_mut<StakeList<DAOT, TokenT>>(member);
-    let item_index = find_item(id, &stake_list.items);
-
-    // Check item in item container
-    assert!(Option::is_some(&item_index), Errors::invalid_state(ERR_PLUGIN_ITEM_CANT_FOUND));
-
-    let poped_item =
-        Vector::remove(&mut stake_list.items, Option::destroy_some(item_index));
-
-    let amount = Token::value<TokenT>(&poped_item.token);
-    let lock_time = poped_item.lock_time;
-    let weight = poped_item.weight;
-    let sbt_amount = poped_item.sbt_amount;
-
-    Account::deposit<TokenT>(member, unstake_item(member, poped_item));
-
-    let witness = StakeToSBTPlugin {};
-    let plugin_event_cap =
-        DAOSpace::acquire_plugin_event_cap<DAOT, StakeToSBTPlugin>(&witness);
-    DAOSpace::emit_plugin_event<DAOT, StakeToSBTPlugin, SBTUnstakeEvent>(
-        &plugin_event_cap,
-        SBTUnstakeEvent {
-            dao_id: DAOSpace::dao_id(DAOSpace::dao_address<DAOT>()),
-            stake_id: id,
-            token_code: Token::token_code<TokenT>(),
-            amount,
-            lock_time,
-            weight,
-            sbt_amount,
-            member,
-        }
-    );
-}
-
- - - -
- - - -## Function `unstake_by_id_entry` - - - -
public(script) fun unstake_by_id_entry<DAOT: store, TokenT: store>(sender: signer, id: u64)
-
- - - -
-Implementation - - -
public(script) fun unstake_by_id_entry<DAOT: store, TokenT: store>(
-    sender: signer,
-    id: u64
-) acquires StakeList {
-    unstake_by_id<DAOT, TokenT>(&sender, id);
-}
-
- - - -
- - - -## Function `unstake_all` - -Unstake all staking items from sender, -No care whether the sender is member or not - - -
public fun unstake_all<DAOT: store, TokenT: store>(sender: &signer)
-
- - - -
-Implementation - - -
public fun unstake_all<DAOT: store, TokenT: store>(sender: &signer) acquires StakeList {
-    let sender_addr = Signer::address_of(sender);
-    assert!(exists<StakeList<DAOT, TokenT>>(sender_addr), Errors::not_published(ERR_PLUGIN_NOT_STAKE));
-    let stake_list = borrow_global_mut<StakeList<DAOT, TokenT>>(sender_addr);
-    let len = Vector::length(&mut stake_list.items);
-
-    let idx = 0;
-    while (idx < len) {
-        let item = Vector::remove(&mut stake_list.items, idx);
-        Account::deposit(sender_addr, unstake_item<DAOT, TokenT>(sender_addr, item));
-        idx = idx + 1;
-    };
-}
-
- - - -
- - - -## Function `unstake_all_entry` - - - -
public(script) fun unstake_all_entry<DAOT: store, TokenT: store>(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun unstake_all_entry<DAOT: store, TokenT: store>(sender: signer) acquires StakeList {
-    unstake_all<DAOT, TokenT>(&sender);
-}
-
- - - -
- - - -## Function `unstake_item` - -Unstake a item from a item object - - -
fun unstake_item<DAOT: store, TokenT: store>(member: address, item: StakeToSBTPlugin::Stake<DAOT, TokenT>): Token::Token<TokenT>
-
- - - -
-Implementation - - -
fun unstake_item<DAOT: store, TokenT: store>(
-    member: address,
-    item: Stake<DAOT, TokenT>
-): Token::Token<TokenT> {
-    let Stake<DAOT, TokenT> {
-        id: _,
-        token,
-        lock_time,
-        stake_time,
-        weight: _,
-        sbt_amount,
-    } = item;
-
-    assert!((Timestamp::now_seconds() - stake_time) > lock_time, Errors::invalid_state(ERR_PLUGIN_STILL_LOCKED));
-
-    // Deduct the corresponding SBT amount if the signer account is a DAO member while unstake
-    if (DAOSpace::is_member<DAOT>(member)) {
-        let witness = StakeToSBTPlugin {};
-        let member_cap =
-            DAOSpace::acquire_member_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-        // Decrease the SBT using `sbt_amount` which from unwrapped Stake data,
-        // rather than the value that calculate a SBT amount from lock time and weight,
-        // because of the `weight` could change at any time
-        DAOSpace::decrease_member_sbt(&member_cap, member, sbt_amount);
-    };
-
-    token
-}
-
- - - -
- - - -## Function `get_sbt_weight` - - - -
fun get_sbt_weight<DAOT: store, TokenT: store>(lock_time: u64): Option::Option<u64>
-
- - - -
-Implementation - - -
fun get_sbt_weight<DAOT: store, TokenT: store>(lock_time: u64): Option::Option<u64> {
-    let config =
-        DAOSpace::get_custom_config<DAOT, LockWeightConfig<DAOT, TokenT>>();
-    let c =
-        &mut config.weight_vec;
-    let len = Vector::length(c);
-    let idx = 0;
-
-    while (idx < len) {
-        let e = Vector::borrow(c, idx);
-        if (e.lock_time == lock_time) {
-            return Option::some(e.weight)
-        };
-        idx = idx + 1;
-    };
-
-    Option::none<u64>()
-}
-
- - - -
- - - -## Function `set_sbt_weight` - - - -
fun set_sbt_weight<DAOT: store, TokenT: store>(lock_time: u64, weight: u64)
-
- - - -
-Implementation - - -
fun set_sbt_weight<DAOT: store, TokenT: store>(lock_time: u64, weight: u64) {
-    let config =
-        DAOSpace::get_custom_config<DAOT, LockWeightConfig<DAOT, TokenT>>();
-    let c = &mut config.weight_vec;
-    let len = Vector::length(c);
-    let idx = 0;
-    let new_el = true;
-    while (idx < len) {
-        let lock_weight = Vector::borrow_mut(c, idx);
-        if (lock_weight.lock_time == lock_time) {
-            lock_weight.weight = weight;
-            new_el = false;
-            break
-        };
-        idx = idx + 1;
-    };
-
-    if (new_el) {
-        Vector::push_back(c, LockWeight<DAOT, TokenT> {
-            lock_time,
-            weight,
-        });
-    };
-
-    let witness = StakeToSBTPlugin {};
-    let modify_config_cap =
-        DAOSpace::acquire_modify_config_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-    DAOSpace::set_custom_config<
-        DAOT,
-        StakeToSBTPlugin,
-        LockWeightConfig<DAOT, TokenT>
-    >(&mut modify_config_cap, LockWeightConfig<DAOT, TokenT> {
-        weight_vec: *&config.weight_vec
-    });
-}
-
- - - -
- - - -## Function `find_item` - - - -
fun find_item<DAOT: store, TokenT: store>(id: u64, c: &vector<StakeToSBTPlugin::Stake<DAOT, TokenT>>): Option::Option<u64>
-
- - - -
-Implementation - - -
fun find_item<DAOT: store, TokenT: store>(
-    id: u64,
-    c: &vector<Stake<DAOT, TokenT>>
-): Option::Option<u64> {
-    let len = Vector::length(c);
-    let idx = 0;
-    while (idx < len) {
-        let item = Vector::borrow(c, idx);
-        if (item.id == id) {
-            return Option::some(idx)
-        };
-        idx = idx + 1;
-    };
-    Option::none()
-}
-
- - - -
- - - -## Function `compute_token_to_sbt` - - - -
fun compute_token_to_sbt<TokenT: store>(weight: u64, token: &Token::Token<TokenT>): u128
-
- - - -
-Implementation - - -
fun compute_token_to_sbt<TokenT: store>(weight: u64, token: &Token::Token<TokenT>): u128 {
-    (weight as u128) * Token::value<TokenT>(token) / Token::scaling_factor<TokenT>()
-}
-
- - - -
- - - -## Function `create_weight_proposal` - -Create proposal that to specific a weight for a locktime - - -
public fun create_weight_proposal<DAOT: store, TokenT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, lock_time: u64, weight: u64, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_weight_proposal<DAOT: store, TokenT: store>(
-    sender: &signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    lock_time: u64,
-    weight: u64,
-    action_delay: u64
-) {
-    let witness = StakeToSBTPlugin {};
-
-    let cap =
-        DAOSpace::acquire_proposal_cap<DAOT, StakeToSBTPlugin>(&witness);
-    DAOSpace::create_proposal(&cap, sender, LockWeight<DAOT, TokenT> {
-            lock_time,
-            weight,
-        },
-        title,
-        introduction,
-        extend,
-        action_delay,
-        Option::none<u8>());
-}
-
- - - -
- - - -## Function `create_weight_proposal_entry` - - - -
public(script) fun create_weight_proposal_entry<DAOT: store, TokenT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, lock_time: u64, weight: u64, action_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun create_weight_proposal_entry<DAOT: store, TokenT: store>(
-    sender: signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    lock_time: u64,
-    weight: u64,
-    action_delay: u64
-) {
-    create_weight_proposal<DAOT, TokenT>(&sender,title, introduction, extend, lock_time, weight, action_delay);
-}
-
- - - -
- - - -## Function `execute_weight_proposal` - - - -
public fun execute_weight_proposal<DAOT: store, TokenT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_weight_proposal<DAOT: store, TokenT: store>(
-    sender: &signer,
-    proposal_id: u64
-) {
-    let witness = StakeToSBTPlugin {};
-    let proposal_cap =
-        DAOSpace::acquire_proposal_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-    let LockWeight<DAOT, TokenT> {
-        lock_time,
-        weight
-    } = DAOSpace::execute_proposal<
-        DAOT,
-        StakeToSBTPlugin,
-        LockWeight<DAOT, TokenT>
-    >(&proposal_cap, sender, proposal_id);
-
-    set_sbt_weight<DAOT, TokenT>(lock_time, weight);
-}
-
- - - -
- - - -## Function `execute_weight_proposal_entry` - - - -
public(script) fun execute_weight_proposal_entry<DAOT: store, TokenT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_weight_proposal_entry<DAOT: store, TokenT: store>(
-    sender: signer,
-    proposal_id: u64
-) {
-    execute_weight_proposal<DAOT, TokenT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `create_token_accept_proposal` - -Create proposal that to accept a token type, which allow user to convert amount of token to SBT - - -
public fun create_token_accept_proposal<DAOT: store, TokenT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_token_accept_proposal<DAOT: store, TokenT: store>(
-    sender: &signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    action_delay: u64
-) {
-    let witness = StakeToSBTPlugin {};
-
-    let cap =
-        DAOSpace::acquire_proposal_cap<DAOT, StakeToSBTPlugin>(&witness);
-    DAOSpace::create_proposal(
-        &cap,
-        sender,
-        AcceptTokenCap<DAOT, TokenT> {},
-        title,
-        introduction,
-        extend,
-        action_delay,
-        Option::none<u8>()
-    );
-}
-
- - - -
- - - -## Function `create_token_accept_proposal_entry` - - - -
public(script) fun create_token_accept_proposal_entry<DAOT: store, TokenT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun create_token_accept_proposal_entry<DAOT: store, TokenT: store>(
-    sender: signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    action_delay: u64
-) {
-    create_token_accept_proposal<DAOT, TokenT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
- - - -## Function `execute_token_accept_proposal` - - - -
public fun execute_token_accept_proposal<DAOT: store, TokenT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_token_accept_proposal<DAOT: store, TokenT: store>(
-    sender: &signer,
-    proposal_id: u64
-) {
-    let witness = StakeToSBTPlugin {};
-    let proposal_cap =
-        DAOSpace::acquire_proposal_cap<DAOT, StakeToSBTPlugin>(&witness);
-
-    let cap = DAOSpace::execute_proposal<
-        DAOT,
-        StakeToSBTPlugin,
-        AcceptTokenCap<DAOT, TokenT>
-    >(&proposal_cap, sender, proposal_id);
-
-    accept_token(cap);
-}
-
- - - -
- - - -## Function `execute_token_accept_proposal_entry` - - - -
public(script) fun execute_token_accept_proposal_entry<DAOT: store, TokenT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_token_accept_proposal_entry<DAOT: store, TokenT: store>(
-    sender: signer,
-    proposal_id: u64
-) {
-    execute_token_accept_proposal<DAOT, TokenT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT: store>(
-    sender: &signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    action_delay: u64
-) {
-    InstallPluginProposalPlugin::create_proposal<DAOT, StakeToSBTPlugin>(
-        sender,
-        required_caps(),
-        title,
-        introduction,
-        extend,
-        action_delay
-    );
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(
-    sender: signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    action_delay: u64
-) {
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/StarcoinDAO.md b/release/v12/docs/StarcoinDAO.md deleted file mode 100644 index 33d0150f..00000000 --- a/release/v12/docs/StarcoinDAO.md +++ /dev/null @@ -1,175 +0,0 @@ - - - -# Module `0x1::StarcoinDAO` - - - -- [Struct `StarcoinDAO`](#0x1_StarcoinDAO_StarcoinDAO) -- [Constants](#@Constants_0) -- [Function `create_dao`](#0x1_StarcoinDAO_create_dao) -- [Function `delegate_config_capability`](#0x1_StarcoinDAO_delegate_config_capability) -- [Function `set_treasury_withdraw_proposal_scale`](#0x1_StarcoinDAO_set_treasury_withdraw_proposal_scale) - - -
use 0x1::Account;
-use 0x1::Config;
-use 0x1::ConfigProposalPlugin;
-use 0x1::DAOAccount;
-use 0x1::DAOSpace;
-use 0x1::GasOracleProposalPlugin;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::PackageTxnManager;
-use 0x1::STC;
-use 0x1::StakeToSBTPlugin;
-use 0x1::TreasuryPlugin;
-use 0x1::UpgradeModulePlugin;
-
- - - - - -## Struct `StarcoinDAO` - - - -
struct StarcoinDAO has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const NAME: vector<u8> = [83, 116, 97, 114, 99, 111, 105, 110, 68, 65, 79];
-
- - - - - -## Function `create_dao` - - - -
public(friend) fun create_dao(signer_cap: Account::SignerCapability, upgrade_plan_cap: PackageTxnManager::UpgradePlanCapability, voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, min_proposal_deposit: u128)
-
- - - -
-Implementation - - -
public(friend) fun create_dao(
-    signer_cap: Account::SignerCapability,
-    upgrade_plan_cap: PackageTxnManager::UpgradePlanCapability,
-    voting_delay: u64,
-    voting_period: u64,
-    voting_quorum_rate: u8,
-    min_action_delay: u64,
-    min_proposal_deposit: u128
-) {
-    let dao_account_cap = DAOAccount::upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap, upgrade_plan_cap);
-
-    let config = DAOSpace::new_dao_config(
-        voting_delay,
-        voting_period,
-        voting_quorum_rate,
-        min_action_delay,
-        min_proposal_deposit,
-    );
-
-
-    DAOSpace::create_dao<StarcoinDAO>(dao_account_cap, *&NAME, Option::none<vector<u8>>(), Option::none<vector<u8>>(), b"ipfs://description", config);
-
-    let witness = StarcoinDAO {};
-    let install_cap = DAOSpace::acquire_install_plugin_cap<StarcoinDAO, StarcoinDAO>(&witness);
-    DAOSpace::install_plugin<StarcoinDAO, StarcoinDAO, InstallPluginProposalPlugin>(&install_cap, InstallPluginProposalPlugin::required_caps());
-    DAOSpace::install_plugin<StarcoinDAO, StarcoinDAO, UpgradeModulePlugin>(&install_cap, UpgradeModulePlugin::required_caps());
-    DAOSpace::install_plugin<StarcoinDAO, StarcoinDAO, ConfigProposalPlugin>(&install_cap, ConfigProposalPlugin::required_caps());
-    DAOSpace::install_plugin<StarcoinDAO, StarcoinDAO, StakeToSBTPlugin>(&install_cap, StakeToSBTPlugin::required_caps());
-    DAOSpace::install_plugin<StarcoinDAO, StarcoinDAO, GasOracleProposalPlugin>(&install_cap, GasOracleProposalPlugin::required_caps());
-    DAOSpace::install_plugin<StarcoinDAO, StarcoinDAO, TreasuryPlugin>(&install_cap, TreasuryPlugin::required_caps());
-
-    StakeToSBTPlugin::accept_token_by_dao<StarcoinDAO, STC>(&witness);
-    StakeToSBTPlugin::set_sbt_weight_by_dao<StarcoinDAO, STC>(&witness, 60000, 1000);
-}
-
- - - -
- - - -## Function `delegate_config_capability` - - - -
public(friend) fun delegate_config_capability<TokenT: store, ConfigT: copy, drop, store>(cap: Config::ModifyConfigCapability<ConfigT>)
-
- - - -
-Implementation - - -
public(friend) fun delegate_config_capability<TokenT: store, ConfigT: copy + drop + store>(cap: Config::ModifyConfigCapability<ConfigT>) {
-    DAOSpace::set_custom_config_cap<StarcoinDAO, ConfigT>(cap);
-}
-
- - - -
- - - -## Function `set_treasury_withdraw_proposal_scale` - -scale up the quorum votes for treasury withdraw proposal. - - -
public(friend) fun set_treasury_withdraw_proposal_scale(scale: u8)
-
- - - -
-Implementation - - -
public(friend) fun set_treasury_withdraw_proposal_scale(scale: u8) {
-    TreasuryPlugin::set_scale_factor(scale, &StarcoinDAO {});
-}
-
- - - -
diff --git a/release/v12/docs/StarcoinVerifier.md b/release/v12/docs/StarcoinVerifier.md deleted file mode 100644 index 21650547..00000000 --- a/release/v12/docs/StarcoinVerifier.md +++ /dev/null @@ -1,703 +0,0 @@ - - - -# Module `0x1::StarcoinVerifier` - - - -- [Struct `AccountState`](#0x1_StarcoinVerifier_AccountState) -- [Struct `StateProof`](#0x1_StarcoinVerifier_StateProof) -- [Struct `SparseMerkleProof`](#0x1_StarcoinVerifier_SparseMerkleProof) -- [Struct `SMTNode`](#0x1_StarcoinVerifier_SMTNode) -- [Constants](#@Constants_0) -- [Function `bcs_deserialize_account_state`](#0x1_StarcoinVerifier_bcs_deserialize_account_state) -- [Function `new_state_proof`](#0x1_StarcoinVerifier_new_state_proof) -- [Function `new_sparse_merkle_proof`](#0x1_StarcoinVerifier_new_sparse_merkle_proof) -- [Function `new_smt_node`](#0x1_StarcoinVerifier_new_smt_node) -- [Function `empty_smt_node`](#0x1_StarcoinVerifier_empty_smt_node) -- [Function `verify_state_proof`](#0x1_StarcoinVerifier_verify_state_proof) -- [Function `verify_smp`](#0x1_StarcoinVerifier_verify_smp) -- [Function `compute_smp_root_by_path_and_node_hash`](#0x1_StarcoinVerifier_compute_smp_root_by_path_and_node_hash) -- [Function `placeholder`](#0x1_StarcoinVerifier_placeholder) -- [Function `create_literal_hash`](#0x1_StarcoinVerifier_create_literal_hash) -- [Function `hash_key`](#0x1_StarcoinVerifier_hash_key) -- [Function `hash_value`](#0x1_StarcoinVerifier_hash_value) -- [Function `count_common_prefix`](#0x1_StarcoinVerifier_count_common_prefix) -- [Function `get_bit_at_from_msb`](#0x1_StarcoinVerifier_get_bit_at_from_msb) - - -
use 0x1::BCS;
-use 0x1::Hash;
-use 0x1::Option;
-use 0x1::StructuredHash;
-use 0x1::Vector;
-
- - - - - -## Struct `AccountState` - - - -
struct AccountState has copy, drop, store
-
- - - -
-Fields - - -
-
-storage_roots: vector<Option::Option<vector<u8>>> -
-
- -
-
- - -
- - - -## Struct `StateProof` - - - -
struct StateProof has copy, drop, store
-
- - - -
-Fields - - -
-
-account_proof: StarcoinVerifier::SparseMerkleProof -
-
- - * Account state's proof for global state root. - -
-
-account_state: vector<u8> -
-
- - * Account state including storage roots. - -
-
-proof: StarcoinVerifier::SparseMerkleProof -
-
- - * State's proof for account storage root. - -
-
- - -
- - - -## Struct `SparseMerkleProof` - - - -
struct SparseMerkleProof has copy, drop, store
-
- - - -
-Fields - - -
-
-siblings: vector<vector<u8>> -
-
- -
-
-leaf: StarcoinVerifier::SMTNode -
-
- -
-
- - -
- - - -## Struct `SMTNode` - - - -
struct SMTNode has copy, drop, store
-
- - - -
-Fields - - -
-
-hash1: vector<u8> -
-
- -
-
-hash2: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ACCOUNT_STORAGE_INDEX_RESOURCE: u64 = 1;
-
- - - - - - - -
const BLOB_HASH_PREFIX: vector<u8> = [66, 108, 111, 98];
-
- - - - - - - -
const DEFAULT_VALUE: vector<u8> = [];
-
- - - - - - - -
const ERROR_ACCOUNT_STORAGE_ROOTS: u64 = 101;
-
- - - - - - - -
const ERROR_LITERAL_HASH_WRONG_LENGTH: u64 = 102;
-
- - - - - - - -
const HASH_LEN_IN_BITS: u64 = 256;
-
- - - - - - - -
const SPARSE_MERKLE_INTERNAL_NODE: vector<u8> = [83, 112, 97, 114, 115, 101, 77, 101, 114, 107, 108, 101, 73, 110, 116, 101, 114, 110, 97, 108, 78, 111, 100, 101];
-
- - - - - - - -
const SPARSE_MERKLE_LEAF_NODE: vector<u8> = [83, 112, 97, 114, 115, 101, 77, 101, 114, 107, 108, 101, 76, 101, 97, 102, 78, 111, 100, 101];
-
- - - - - - - -
const SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL: vector<u8> = [83, 80, 65, 82, 83, 69, 95, 77, 69, 82, 75, 76, 69, 95, 80, 76, 65, 67, 69, 72, 79, 76, 68, 69, 82, 95, 72, 65, 83, 72];
-
- - - - - -## Function `bcs_deserialize_account_state` - - - -
public fun bcs_deserialize_account_state(data: &vector<u8>): StarcoinVerifier::AccountState
-
- - - -
-Implementation - - -
public fun bcs_deserialize_account_state(data: &vector<u8>): AccountState {
-    let (vec, _) = BCS::deserialize_option_bytes_vector(data, 0);
-    AccountState{
-        storage_roots: vec
-    }
-}
-
- - - -
- - - -## Function `new_state_proof` - - - -
public fun new_state_proof(account_proof: StarcoinVerifier::SparseMerkleProof, account_state: vector<u8>, proof: StarcoinVerifier::SparseMerkleProof): StarcoinVerifier::StateProof
-
- - - -
-Implementation - - -
public fun new_state_proof(account_proof: SparseMerkleProof, account_state: vector<u8>, proof: SparseMerkleProof): StateProof {
-    StateProof{
-        account_proof,
-        account_state,
-        proof,
-    }
-}
-
- - - -
- - - -## Function `new_sparse_merkle_proof` - - - -
public fun new_sparse_merkle_proof(siblings: vector<vector<u8>>, leaf: StarcoinVerifier::SMTNode): StarcoinVerifier::SparseMerkleProof
-
- - - -
-Implementation - - -
public fun new_sparse_merkle_proof(siblings: vector<vector<u8>>, leaf: SMTNode): SparseMerkleProof {
-    SparseMerkleProof{
-        siblings,
-        leaf,
-    }
-}
-
- - - -
- - - -## Function `new_smt_node` - - - -
public fun new_smt_node(hash1: vector<u8>, hash2: vector<u8>): StarcoinVerifier::SMTNode
-
- - - -
-Implementation - - -
public fun new_smt_node(hash1: vector<u8>, hash2: vector<u8>): SMTNode {
-    SMTNode{
-        hash1,
-        hash2,
-    }
-}
-
- - - -
- - - -## Function `empty_smt_node` - - - -
public fun empty_smt_node(): StarcoinVerifier::SMTNode
-
- - - -
-Implementation - - -
public fun empty_smt_node(): SMTNode {
-    SMTNode{
-        hash1: Vector::empty(),
-        hash2: Vector::empty(),
-    }
-}
-
- - - -
- - - -## Function `verify_state_proof` - - - -
public fun verify_state_proof(state_proof: &StarcoinVerifier::StateProof, state_root: &vector<u8>, account_address: address, resource_struct_tag: &vector<u8>, state: &vector<u8>): bool
-
- - - -
-Implementation - - -
public fun verify_state_proof(state_proof: &StateProof, state_root: &vector<u8>,
-                                       account_address: address, resource_struct_tag: &vector<u8>,
-                                       state: &vector<u8>): bool {
-    let accountState: AccountState = bcs_deserialize_account_state(&state_proof.account_state);
-    assert!(Vector::length(&accountState.storage_roots) > ACCOUNT_STORAGE_INDEX_RESOURCE, ERROR_ACCOUNT_STORAGE_ROOTS);
-
-    // First, verify state for storage root.
-    let storageRoot = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE));
-    let ok: bool = verify_smp(&state_proof.proof.siblings,
-        &state_proof.proof.leaf,
-        storageRoot,
-        resource_struct_tag, // resource struct tag BCS serialized as key
-        state);
-    if (!ok) {
-        return false
-    };
-
-    // Then, verify account state for global state root.
-    ok = verify_smp(&state_proof.account_proof.siblings,
-        &state_proof.account_proof.leaf,
-        state_root,
-        &BCS::to_bytes<address>(&account_address), // account address as key
-        &state_proof.account_state,
-    );
-    ok
-}
-
- - - -
- - - -## Function `verify_smp` - -Verify sparse merkle proof by key and value. - - -
public fun verify_smp(sibling_nodes: &vector<vector<u8>>, leaf_data: &StarcoinVerifier::SMTNode, expected_root: &vector<u8>, key: &vector<u8>, value: &vector<u8>): bool
-
- - - -
-Implementation - - -
public fun verify_smp(sibling_nodes: &vector<vector<u8>>, leaf_data: &SMTNode, expected_root: &vector<u8>, key: &vector<u8>, value: &vector<u8>): bool {
-    let path = hash_key(key);
-    let current_hash: vector<u8>;
-    if (*value == DEFAULT_VALUE) {
-        // Non-membership proof.
-        if (empty_smt_node() == *leaf_data) {
-            current_hash = placeholder();
-        } else {
-            if (*&leaf_data.hash1 == *&path) {
-                return false
-            };
-            if (!(count_common_prefix(&leaf_data.hash1, &path) >= Vector::length(sibling_nodes))) {
-                return false
-            };
-            current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data);
-        };
-    } else {
-        // Membership proof.
-        if (empty_smt_node() == *leaf_data) {
-            return false
-        };
-        if (*&leaf_data.hash1 != *&path) {
-            return false
-        };
-        let value_hash = hash_value(value);
-        if (*&leaf_data.hash2 != value_hash) {
-            return false
-        };
-        current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data);
-    };
-
-    current_hash = compute_smp_root_by_path_and_node_hash(sibling_nodes, &path, ¤t_hash);
-    current_hash == *expected_root
-}
-
- - - -
- - - -## Function `compute_smp_root_by_path_and_node_hash` - - - -
public fun compute_smp_root_by_path_and_node_hash(sibling_nodes: &vector<vector<u8>>, path: &vector<u8>, node_hash: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
public fun compute_smp_root_by_path_and_node_hash(sibling_nodes: &vector<vector<u8>>, path: &vector<u8>, node_hash: &vector<u8>): vector<u8> {
-    let current_hash = *node_hash;
-    let i = 0;
-    let proof_length = Vector::length(sibling_nodes);
-    while (i < proof_length) {
-        let sibling = *Vector::borrow(sibling_nodes, i);
-        let bit = get_bit_at_from_msb(path, proof_length - i - 1);
-        let internal_node = if (bit) {
-            SMTNode{ hash1: sibling, hash2: current_hash }
-        } else {
-            SMTNode{ hash1: current_hash, hash2: sibling }
-        };
-        current_hash = StructuredHash::hash(SPARSE_MERKLE_INTERNAL_NODE, &internal_node);
-        i = i + 1;
-    };
-    current_hash
-}
-
- - - -
- - - -## Function `placeholder` - - - -
public fun placeholder(): vector<u8>
-
- - - -
-Implementation - - -
public fun placeholder(): vector<u8> {
-    create_literal_hash(&SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL)
-}
-
- - - -
- - - -## Function `create_literal_hash` - - - -
public fun create_literal_hash(word: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
public fun create_literal_hash(word: &vector<u8>): vector<u8> {
-    if (Vector::length(word)  <= 32) {
-        let lenZero = 32 - Vector::length(word);
-        let i = 0;
-        let r = *word;
-        while (i < lenZero) {
-            Vector::push_back(&mut r, 0);
-            i = i + 1;
-        };
-        return r
-    };
-    abort ERROR_LITERAL_HASH_WRONG_LENGTH
-}
-
- - - -
- - - -## Function `hash_key` - - - -
fun hash_key(key: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
fun hash_key(key: &vector<u8>): vector<u8> {
-    Hash::sha3_256(*key)
-}
-
- - - -
- - - -## Function `hash_value` - - - -
fun hash_value(value: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -
fun hash_value(value: &vector<u8>): vector<u8> {
-    StructuredHash::hash(BLOB_HASH_PREFIX, value)
-}
-
- - - -
- - - -## Function `count_common_prefix` - - - -
fun count_common_prefix(data1: &vector<u8>, data2: &vector<u8>): u64
-
- - - -
-Implementation - - -
fun count_common_prefix(data1: &vector<u8>, data2: &vector<u8>): u64 {
-    let count = 0;
-    let i = 0;
-    while ( i < Vector::length(data1) * 8) {
-        if (get_bit_at_from_msb(data1, i) == get_bit_at_from_msb(data2, i)) {
-            count = count + 1;
-        } else {
-            break
-        };
-        i = i + 1;
-    };
-    count
-}
-
- - - -
- - - -## Function `get_bit_at_from_msb` - - - -
fun get_bit_at_from_msb(data: &vector<u8>, index: u64): bool
-
- - - -
-Implementation - - -
fun get_bit_at_from_msb(data: &vector<u8>, index: u64): bool {
-    let pos = index / 8;
-    let bit = (7 - index % 8);
-    (*Vector::borrow(data, pos) >> (bit as u8)) & 1u8 != 0
-}
-
- - - -
diff --git a/release/v12/docs/StdlibUpgradeScripts.md b/release/v12/docs/StdlibUpgradeScripts.md deleted file mode 100644 index 4564c342..00000000 --- a/release/v12/docs/StdlibUpgradeScripts.md +++ /dev/null @@ -1,426 +0,0 @@ - - - -# Module `0x1::StdlibUpgradeScripts` - -The module for StdlibUpgrade init scripts - - -- [Function `upgrade_from_v2_to_v3`](#0x1_StdlibUpgradeScripts_upgrade_from_v2_to_v3) -- [Function `take_linear_withdraw_capability`](#0x1_StdlibUpgradeScripts_take_linear_withdraw_capability) -- [Function `do_upgrade_from_v5_to_v6`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v5_to_v6) -- [Function `upgrade_from_v5_to_v6`](#0x1_StdlibUpgradeScripts_upgrade_from_v5_to_v6) -- [Function `upgrade_from_v6_to_v7`](#0x1_StdlibUpgradeScripts_upgrade_from_v6_to_v7) -- [Function `do_upgrade_from_v6_to_v7`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v6_to_v7) -- [Function `do_upgrade_from_v6_to_v7_with_language_version`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v6_to_v7_with_language_version) -- [Function `upgrade_from_v7_to_v8`](#0x1_StdlibUpgradeScripts_upgrade_from_v7_to_v8) -- [Function `do_upgrade_from_v7_to_v8`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v7_to_v8) -- [Function `upgrade_from_v11_to_v12`](#0x1_StdlibUpgradeScripts_upgrade_from_v11_to_v12) -- [Function `do_upgrade_from_v11_to_v12`](#0x1_StdlibUpgradeScripts_do_upgrade_from_v11_to_v12) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::Account;
-use 0x1::AnyMemberPlugin;
-use 0x1::Block;
-use 0x1::Collection;
-use 0x1::Config;
-use 0x1::ConfigProposalPlugin;
-use 0x1::ConsensusConfig;
-use 0x1::CoreAddresses;
-use 0x1::DAOExtensionPoint;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAORegistry;
-use 0x1::Dao;
-use 0x1::GasOracleProposalPlugin;
-use 0x1::GenesisNFT;
-use 0x1::GenesisSignerCapability;
-use 0x1::GrantProposalPlugin;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::LanguageVersion;
-use 0x1::MemberProposalPlugin;
-use 0x1::MintProposalPlugin;
-use 0x1::ModifyDaoConfigProposal;
-use 0x1::NFT;
-use 0x1::Offer;
-use 0x1::OnChainConfigDao;
-use 0x1::Oracle;
-use 0x1::PackageTxnManager;
-use 0x1::RewardConfig;
-use 0x1::STC;
-use 0x1::STCUSDOracle;
-use 0x1::StakeToSBTPlugin;
-use 0x1::StarcoinDAO;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::TransactionPublishOption;
-use 0x1::TransactionTimeoutConfig;
-use 0x1::Treasury;
-use 0x1::TreasuryPlugin;
-use 0x1::TreasuryWithdrawDaoProposal;
-use 0x1::UpgradeModuleDaoProposal;
-use 0x1::UpgradeModulePlugin;
-use 0x1::VMConfig;
-
- - - - - -## Function `upgrade_from_v2_to_v3` - -Stdlib upgrade script from v2 to v3 - - -
public(script) fun upgrade_from_v2_to_v3(account: signer, total_stc_amount: u128)
-
- - - -
-Implementation - - -
public(script) fun upgrade_from_v2_to_v3(account: signer, total_stc_amount: u128) {
-    CoreAddresses::assert_genesis_address(&account);
-
-    let withdraw_cap = STC::upgrade_from_v1_to_v2(&account, total_stc_amount);
-
-    let mint_keys = Collection::borrow_collection<LinearTimeMintKey<STC>>(CoreAddresses::ASSOCIATION_ROOT_ADDRESS());
-    let mint_key = Collection::borrow(&mint_keys, 0);
-    let (total, minted, start_time, period) = Token::read_linear_time_key(mint_key);
-    Collection::return_collection(mint_keys);
-
-    let now = Timestamp::now_seconds();
-    let linear_withdraw_cap = Treasury::issue_linear_withdraw_capability(&mut withdraw_cap, total - minted, period - (now - start_time));
-    // Lock the TreasuryWithdrawCapability to Dao
-    TreasuryWithdrawDaoProposal::plugin(&account, withdraw_cap);
-    // Give a LinearWithdrawCapability Offer to association, association need to take the offer, and destroy old LinearTimeMintKey.
-    Offer::create(&account, linear_withdraw_cap, CoreAddresses::ASSOCIATION_ROOT_ADDRESS(), 0);
-}
-
- - - -
- - - -## Function `take_linear_withdraw_capability` - -association account should call this script after upgrade from v2 to v3. - - -
public(script) fun take_linear_withdraw_capability(signer: signer)
-
- - - -
-Implementation - - -
public(script) fun take_linear_withdraw_capability(signer: signer) {
-    let offered = Offer::redeem<LinearWithdrawCapability<STC>>(&signer, CoreAddresses::GENESIS_ADDRESS());
-    Treasury::add_linear_withdraw_capability(&signer, offered);
-    let mint_key = Collection::take<LinearTimeMintKey<STC>>(&signer);
-    Token::destroy_linear_time_key(mint_key);
-}
-
- - - -
- - - -## Function `do_upgrade_from_v5_to_v6` - - - -
public fun do_upgrade_from_v5_to_v6(sender: &signer)
-
- - - -
-Implementation - - -
public fun do_upgrade_from_v5_to_v6(sender: &signer) {
-    CoreAddresses::assert_genesis_address(sender);
-    Oracle::initialize(sender);
-    //register oracle
-    STCUSDOracle::register(sender);
-    NFT::initialize(sender);
-    let merkle_root = x"5969f0e8e19f8769276fb638e6060d5c02e40088f5fde70a6778dd69d659ee6d";
-    let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY";
-    GenesisNFT::initialize(sender, merkle_root, 1639u64, image);
-}
-
- - - -
- - - -## Function `upgrade_from_v5_to_v6` - - - -
public(script) fun upgrade_from_v5_to_v6(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun upgrade_from_v5_to_v6(sender: signer) {
-    Self::do_upgrade_from_v5_to_v6(&sender)
-}
-
- - - -
- - - -## Function `upgrade_from_v6_to_v7` - - - -
public(script) fun upgrade_from_v6_to_v7(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun upgrade_from_v6_to_v7(sender: signer) {
-    Self::do_upgrade_from_v6_to_v7_with_language_version(&sender, 2);
-}
-
- - - -
- - - -## Function `do_upgrade_from_v6_to_v7` - -deprecated, use do_upgrade_from_v6_to_v7_with_language_version. - - -
public fun do_upgrade_from_v6_to_v7(sender: &signer)
-
- - - -
-Implementation - - -
public fun do_upgrade_from_v6_to_v7(sender: &signer) {
-    do_upgrade_from_v6_to_v7_with_language_version(sender, 2);
-}
-
- - - -
- - - -## Function `do_upgrade_from_v6_to_v7_with_language_version` - - - -
public fun do_upgrade_from_v6_to_v7_with_language_version(sender: &signer, language_version: u64)
-
- - - -
-Implementation - - -
public fun do_upgrade_from_v6_to_v7_with_language_version(sender: &signer, language_version: u64) {
-    // initialize the language version config.
-    Config::publish_new_config(sender, LanguageVersion::new(language_version));
-    // use STC Dao to upgrade onchain's move-language-version configuration.
-    OnChainConfigDao::plugin<STC, LanguageVersion::LanguageVersion>(sender);
-    // upgrade genesis NFT
-    GenesisNFT::upgrade_to_nft_type_info_v2(sender);
-}
-
- - - -
- - - -## Function `upgrade_from_v7_to_v8` - - - -
public(script) fun upgrade_from_v7_to_v8(sender: signer)
-
- - - -
-Implementation - - -
public(script) fun upgrade_from_v7_to_v8(sender: signer) {
-    do_upgrade_from_v7_to_v8(&sender);
-}
-
- - - -
- - - -## Function `do_upgrade_from_v7_to_v8` - - - -
public fun do_upgrade_from_v7_to_v8(sender: &signer)
-
- - - -
-Implementation - - -
public fun do_upgrade_from_v7_to_v8(sender: &signer) {
-    {
-        let cap = Oracle::extract_signer_cap(sender);
-        GenesisSignerCapability::initialize(sender, cap);
-    };
-
-    {
-        let cap = NFT::extract_signer_cap(sender);
-        Account::destroy_signer_cap(cap);
-    };
-}
-
- - - -
- - - -## Function `upgrade_from_v11_to_v12` - - - -
public(script) fun upgrade_from_v11_to_v12()
-
- - - -
-Implementation - - -
public(script) fun upgrade_from_v11_to_v12() {
-    do_upgrade_from_v11_to_v12();
-}
-
- - - -
- - - -## Function `do_upgrade_from_v11_to_v12` - - - -
public fun do_upgrade_from_v11_to_v12()
-
- - - -
-Implementation - - -
public fun do_upgrade_from_v11_to_v12() {
-    let genessis_signer = GenesisSignerCapability::get_genesis_signer();
-    Block::checkpoints_init();
-    DAORegistry::initialize();
-
-    DAOExtensionPoint::initialize();
-    DAOPluginMarketplace::initialize();
-
-    AnyMemberPlugin::initialize(&genessis_signer);
-    ConfigProposalPlugin::initialize(&genessis_signer);
-    GrantProposalPlugin::initialize(&genessis_signer);
-    InstallPluginProposalPlugin::initialize(&genessis_signer);
-    MemberProposalPlugin::initialize(&genessis_signer);
-    MintProposalPlugin::initialize(&genessis_signer);
-    StakeToSBTPlugin::initialize(&genessis_signer);
-    UpgradeModulePlugin::initialize(&genessis_signer);
-    GasOracleProposalPlugin::initialize(&genessis_signer);
-    TreasuryPlugin::initialize(&genessis_signer);
-
-    //TODO : config rate need mind
-    // voting_delay: 60000 ms
-    // voting_period: 3600000 ms
-    // voting_quorum_rate: 4
-    // min_action_delay: 3600000 ms
-    let signer_cap = Account::get_genesis_capability();
-    let upgrade_plan_cap = UpgradeModuleDaoProposal::get_genesis_upgrade_cap<STC>();
-    StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, Dao::voting_delay<STC>(), Dao::voting_period<STC>(), Dao::voting_quorum_rate<STC>(), Dao::min_action_delay<STC>(), 1000 * 1000 * 1000 * 1000);
-
-    StarcoinDAO::delegate_config_capability<STC, TransactionPublishOption::TransactionPublishOption>(
-        OnChainConfigDao::config_cap<STC, TransactionPublishOption::TransactionPublishOption>());
-    StarcoinDAO::delegate_config_capability<STC, VMConfig::VMConfig>(
-        OnChainConfigDao::config_cap<STC, VMConfig::VMConfig>());
-    StarcoinDAO::delegate_config_capability<STC, ConsensusConfig::ConsensusConfig>(
-        OnChainConfigDao::config_cap<STC, ConsensusConfig::ConsensusConfig>());
-    StarcoinDAO::delegate_config_capability<STC, RewardConfig::RewardConfig>(
-        OnChainConfigDao::config_cap<STC, RewardConfig::RewardConfig>());
-    StarcoinDAO::delegate_config_capability<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>(
-        OnChainConfigDao::config_cap<STC, TransactionTimeoutConfig::TransactionTimeoutConfig>());
-    StarcoinDAO::delegate_config_capability<STC, LanguageVersion::LanguageVersion>(
-        OnChainConfigDao::config_cap<STC, LanguageVersion::LanguageVersion>());
-
-    let signer = GenesisSignerCapability::get_genesis_signer();
-    let cap = TreasuryWithdrawDaoProposal::takeout_withdraw_capability<STC>(&signer);
-    TreasuryPlugin::delegate_capability<STC>(&signer, cap);
-    StarcoinDAO::set_treasury_withdraw_proposal_scale(100);
-
-    // clean old DAO resources
-    ModifyDaoConfigProposal::destroy_modify_config_capability<STC>(&genessis_signer);
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/Timestamp.md b/release/v12/docs/Timestamp.md deleted file mode 100644 index a4af9aaa..00000000 --- a/release/v12/docs/Timestamp.md +++ /dev/null @@ -1,461 +0,0 @@ - - - -# Module `0x1::Timestamp` - -The module implements onchain timestamp oracle. -Timestamp is updated on each block. It always steps forward, and never come backward. - - -- [Resource `CurrentTimeMilliseconds`](#0x1_Timestamp_CurrentTimeMilliseconds) -- [Resource `TimeHasStarted`](#0x1_Timestamp_TimeHasStarted) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_Timestamp_initialize) -- [Function `update_global_time`](#0x1_Timestamp_update_global_time) -- [Function `now_seconds`](#0x1_Timestamp_now_seconds) -- [Function `now_milliseconds`](#0x1_Timestamp_now_milliseconds) -- [Function `set_time_has_started`](#0x1_Timestamp_set_time_has_started) -- [Function `is_genesis`](#0x1_Timestamp_is_genesis) -- [Function `assert_genesis`](#0x1_Timestamp_assert_genesis) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::CoreAddresses;
-use 0x1::Errors;
-
- - - - - -## Resource `CurrentTimeMilliseconds` - - - -
struct CurrentTimeMilliseconds has key
-
- - - -
-Fields - - -
-
-milliseconds: u64 -
-
- -
-
- - -
- - - -## Resource `TimeHasStarted` - -A singleton resource used to determine whether time has started. This -is called at the end of genesis. - - -
struct TimeHasStarted has key
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const EINVALID_TIMESTAMP: u64 = 14;
-
- - - - - - - -
const ENOT_GENESIS: u64 = 12;
-
- - - - - - - -
const ENOT_INITIALIZED: u64 = 101;
-
- - - - - -Conversion factor between seconds and milliseconds - - -
const MILLI_CONVERSION_FACTOR: u64 = 1000;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(account: &signer, genesis_timestamp: u64)
-
- - - -
-Implementation - - -
public fun initialize(account: &signer, genesis_timestamp: u64) {
-    // Only callable by the Genesis address
-    CoreAddresses::assert_genesis_address(account);
-    let milli_timer = CurrentTimeMilliseconds {milliseconds: genesis_timestamp};
-    move_to<CurrentTimeMilliseconds>(account, milli_timer);
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if exists<CurrentTimeMilliseconds>(Signer::address_of(account));
-ensures exists<CurrentTimeMilliseconds>(Signer::address_of(account));
-
- - - -
- - - -## Function `update_global_time` - - - -
public fun update_global_time(account: &signer, timestamp: u64)
-
- - - -
-Implementation - - -
public fun update_global_time(account: &signer, timestamp: u64) acquires CurrentTimeMilliseconds {
-    CoreAddresses::assert_genesis_address(account);
-    //Do not update time before time start.
-    let global_milli_timer = borrow_global_mut<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-    assert!(timestamp > global_milli_timer.milliseconds, Errors::invalid_argument(EINVALID_TIMESTAMP));
-    global_milli_timer.milliseconds = timestamp;
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if timestamp <= global<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS()).milliseconds;
-ensures global<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS()).milliseconds == timestamp;
-
- - - -
- - - -## Function `now_seconds` - - - -
public fun now_seconds(): u64
-
- - - -
-Implementation - - -
public fun now_seconds(): u64 acquires CurrentTimeMilliseconds {
-    now_milliseconds() / MILLI_CONVERSION_FACTOR
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-ensures result == now_milliseconds() / MILLI_CONVERSION_FACTOR;
-
- - - - - - - -
fun spec_now_seconds(): u64 {
-   global<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS()).milliseconds / MILLI_CONVERSION_FACTOR
-}
-
- - - -
- - - -## Function `now_milliseconds` - - - -
public fun now_milliseconds(): u64
-
- - - -
-Implementation - - -
public fun now_milliseconds(): u64 acquires CurrentTimeMilliseconds {
-    borrow_global<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS()).milliseconds
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-ensures result == global<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS()).milliseconds;
-
- - - - - - - -
fun spec_now_millseconds(): u64 {
-   global<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS()).milliseconds
-}
-
- - - -
- - - -## Function `set_time_has_started` - -Marks that time has started and genesis has finished. This can only be called from genesis. - - -
public fun set_time_has_started(account: &signer)
-
- - - -
-Implementation - - -
public fun set_time_has_started(account: &signer) {
-    CoreAddresses::assert_genesis_address(account);
-
-    // Current time must have been initialized.
-    assert!(
-        exists<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS()),
-        Errors::invalid_state(ENOT_INITIALIZED)
-    );
-    move_to(account, TimeHasStarted{});
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<CurrentTimeMilliseconds>(Signer::address_of(account));
-aborts_if exists<TimeHasStarted>(Signer::address_of(account));
-ensures exists<TimeHasStarted>(Signer::address_of(account));
-
- - - -
- - - -## Function `is_genesis` - -Helper function to determine if the blockchain is in genesis state. - - -
public fun is_genesis(): bool
-
- - - -
-Implementation - - -
public fun is_genesis(): bool {
-    !exists<TimeHasStarted>(CoreAddresses::GENESIS_ADDRESS())
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == !exists<TimeHasStarted>(CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `assert_genesis` - -Helper function to assert genesis state. - - -
public fun assert_genesis()
-
- - - -
-Implementation - - -
public fun assert_genesis() {
-    assert!(is_genesis(), Errors::invalid_state(ENOT_GENESIS));
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-include AbortsIfNotGenesis;
-
- - -Helper schema to specify that a function aborts if not in genesis. - - - - - -
schema AbortsIfNotGenesis {
-    aborts_if !is_genesis();
-}
-
- - - - - - - -
schema AbortsIfTimestampNotExists {
-    aborts_if !exists<CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Token.md b/release/v12/docs/Token.md deleted file mode 100644 index a32c5fb7..00000000 --- a/release/v12/docs/Token.md +++ /dev/null @@ -1,1845 +0,0 @@ - - - -# Module `0x1::Token` - -Token implementation of Starcoin. - - -- [Struct `Token`](#0x1_Token_Token) -- [Struct `TokenCode`](#0x1_Token_TokenCode) -- [Resource `MintCapability`](#0x1_Token_MintCapability) -- [Resource `FixedTimeMintKey`](#0x1_Token_FixedTimeMintKey) -- [Resource `LinearTimeMintKey`](#0x1_Token_LinearTimeMintKey) -- [Resource `BurnCapability`](#0x1_Token_BurnCapability) -- [Struct `MintEvent`](#0x1_Token_MintEvent) -- [Struct `BurnEvent`](#0x1_Token_BurnEvent) -- [Resource `TokenInfo`](#0x1_Token_TokenInfo) -- [Constants](#@Constants_0) -- [Function `register_token`](#0x1_Token_register_token) -- [Function `remove_mint_capability`](#0x1_Token_remove_mint_capability) -- [Function `add_mint_capability`](#0x1_Token_add_mint_capability) -- [Function `destroy_mint_capability`](#0x1_Token_destroy_mint_capability) -- [Function `remove_burn_capability`](#0x1_Token_remove_burn_capability) -- [Function `add_burn_capability`](#0x1_Token_add_burn_capability) -- [Function `destroy_burn_capability`](#0x1_Token_destroy_burn_capability) -- [Function `mint`](#0x1_Token_mint) -- [Function `mint_with_capability`](#0x1_Token_mint_with_capability) -- [Function `do_mint`](#0x1_Token_do_mint) -- [Function `issue_fixed_mint_key`](#0x1_Token_issue_fixed_mint_key) -- [Function `issue_linear_mint_key`](#0x1_Token_issue_linear_mint_key) -- [Function `destroy_linear_time_key`](#0x1_Token_destroy_linear_time_key) -- [Function `read_linear_time_key`](#0x1_Token_read_linear_time_key) -- [Function `burn`](#0x1_Token_burn) -- [Function `burn_with_capability`](#0x1_Token_burn_with_capability) -- [Function `zero`](#0x1_Token_zero) -- [Function `value`](#0x1_Token_value) -- [Function `split`](#0x1_Token_split) -- [Function `withdraw`](#0x1_Token_withdraw) -- [Function `join`](#0x1_Token_join) -- [Function `deposit`](#0x1_Token_deposit) -- [Function `destroy_zero`](#0x1_Token_destroy_zero) -- [Function `scaling_factor`](#0x1_Token_scaling_factor) -- [Function `market_cap`](#0x1_Token_market_cap) -- [Function `is_registered_in`](#0x1_Token_is_registered_in) -- [Function `is_same_token`](#0x1_Token_is_same_token) -- [Function `token_address`](#0x1_Token_token_address) -- [Function `token_code`](#0x1_Token_token_code) -- [Function `type_of`](#0x1_Token_type_of) -- [Function `name_of`](#0x1_Token_name_of) -- [Function `name_of_token`](#0x1_Token_name_of_token) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Math;
-use 0x1::Signer;
-
- - - - - -## Struct `Token` - -The token has a TokenType color that tells us what token the -value inside represents. - - -
struct Token<TokenType> has store
-
- - - -
-Fields - - -
-
-value: u128 -
-
- -
-
- - -
- - - -## Struct `TokenCode` - -Token Code which identify a unique Token. - - -
struct TokenCode has copy, drop, store
-
- - - -
-Fields - - -
-
-addr: address -
-
- address who define the module contains the Token Type. -
-
-module_name: vector<u8> -
-
- module which contains the Token Type. -
-
-name: vector<u8> -
-
- name of the token. may nested if the token is an instantiated generic token type. -
-
- - -
- - - -## Resource `MintCapability` - -A minting capability allows tokens of type TokenType to be minted - - -
struct MintCapability<TokenType> has store, key
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `FixedTimeMintKey` - -A fixed time mint key which can mint token until global time > end_time - - -
struct FixedTimeMintKey<TokenType> has store, key
-
- - - -
-Fields - - -
-
-total: u128 -
-
- -
-
-end_time: u64 -
-
- -
-
- - -
- - - -## Resource `LinearTimeMintKey` - -A linear time mint key which can mint token in a period by time-based linear release. - - -
struct LinearTimeMintKey<TokenType> has store, key
-
- - - -
-Fields - - -
-
-total: u128 -
-
- -
-
-minted: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-period: u64 -
-
- -
-
- - -
- - - -## Resource `BurnCapability` - -A burn capability allows tokens of type TokenType to be burned. - - -
struct BurnCapability<TokenType> has store, key
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `MintEvent` - -Event emitted when token minted. - - -
struct MintEvent has drop, store
-
- - - -
-Fields - - -
-
-amount: u128 -
-
- funds added to the system -
-
-token_code: Token::TokenCode -
-
- full info of Token. -
-
- - -
- - - -## Struct `BurnEvent` - -Event emitted when token burned. - - -
struct BurnEvent has drop, store
-
- - - -
-Fields - - -
-
-amount: u128 -
-
- funds removed from the system -
-
-token_code: Token::TokenCode -
-
- full info of Token -
-
- - -
- - - -## Resource `TokenInfo` - -Token information. - - -
struct TokenInfo<TokenType> has key
-
- - - -
-Fields - - -
-
-total_value: u128 -
-
- The total value for the token represented by - TokenType. Mutable. -
-
-scaling_factor: u128 -
-
- The scaling factor for the coin (i.e. the amount to divide by - to get to the human-readable representation for this currency). - e.g. 10^6 for Coin1 -
-
-mint_events: Event::EventHandle<Token::MintEvent> -
-
- event stream for minting -
-
-burn_events: Event::EventHandle<Token::BurnEvent> -
-
- event stream for burning -
-
- - -
- - - -## Constants - - - - - - -
const EAMOUNT_EXCEEDS_COIN_VALUE: u64 = 102;
-
- - - - - - - -
const EDEPRECATED_FUNCTION: u64 = 19;
-
- - - - - - - -
const EDESTROY_KEY_NOT_EMPTY: u64 = 104;
-
- - - - - - - -
const EDESTROY_TOKEN_NON_ZERO: u64 = 16;
-
- - - - - - - -
const EEMPTY_KEY: u64 = 106;
-
- - - - - - - -
const EINVALID_ARGUMENT: u64 = 18;
-
- - - - - - - -
const EMINT_AMOUNT_EQUAL_ZERO: u64 = 109;
-
- - - - - - - -
const EMINT_KEY_TIME_LIMIT: u64 = 103;
-
- - - - - - - -
const EPERIOD_NEW: u64 = 108;
-
- - - - - - - -
const EPRECISION_TOO_LARGE: u64 = 105;
-
- - - - - - - -
const ESPLIT: u64 = 107;
-
- - - - - -Token register's address should same as TokenType's address. - - -
const ETOKEN_REGISTER: u64 = 101;
-
- - - - - -2^128 < 10**39 - - -
const MAX_PRECISION: u8 = 38;
-
- - - - - -## Function `register_token` - -Register the type TokenType as a Token and got MintCapability and BurnCapability. - - -
public fun register_token<TokenType: store>(account: &signer, precision: u8)
-
- - - -
-Implementation - - -
public fun register_token<TokenType: store>(
-    account: &signer,
-    precision: u8,
-) {
-    assert!(precision <= MAX_PRECISION, Errors::invalid_argument(EPRECISION_TOO_LARGE));
-    let scaling_factor = Math::pow(10, (precision as u64));
-    let token_address = token_address<TokenType>();
-    assert!(Signer::address_of(account) == token_address, Errors::requires_address(ETOKEN_REGISTER));
-    move_to(account, MintCapability<TokenType> {});
-    move_to(account, BurnCapability<TokenType> {});
-    move_to(
-        account,
-        TokenInfo<TokenType> {
-            total_value: 0,
-            scaling_factor,
-            mint_events: Event::new_event_handle<MintEvent>(account),
-            burn_events: Event::new_event_handle<BurnEvent>(account),
-        },
-    );
-}
-
- - - -
- -
-Specification - - - -
include RegisterTokenAbortsIf<TokenType>;
-include RegisterTokenEnsures<TokenType>;
-
- - - - - - - -
schema RegisterTokenAbortsIf<TokenType> {
-    precision: u8;
-    account: signer;
-    aborts_if precision > MAX_PRECISION;
-    aborts_if Signer::address_of(account) != SPEC_TOKEN_TEST_ADDRESS();
-    aborts_if exists<MintCapability<TokenType>>(Signer::address_of(account));
-    aborts_if exists<BurnCapability<TokenType>>(Signer::address_of(account));
-    aborts_if exists<TokenInfo<TokenType>>(Signer::address_of(account));
-}
-
- - - - - - - -
schema RegisterTokenEnsures<TokenType> {
-    account: signer;
-    ensures exists<MintCapability<TokenType>>(Signer::address_of(account));
-    ensures exists<BurnCapability<TokenType>>(Signer::address_of(account));
-    ensures exists<TokenInfo<TokenType>>(Signer::address_of(account));
-}
-
- - - -
- - - -## Function `remove_mint_capability` - -Remove mint capability from signer. - - -
public fun remove_mint_capability<TokenType: store>(signer: &signer): Token::MintCapability<TokenType>
-
- - - -
-Implementation - - -
public fun remove_mint_capability<TokenType: store>(signer: &signer): MintCapability<TokenType>
-acquires MintCapability {
-    move_from<MintCapability<TokenType>>(Signer::address_of(signer))
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<MintCapability<TokenType>>(Signer::address_of(signer));
-ensures !exists<MintCapability<TokenType>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `add_mint_capability` - -Add mint capability to signer. - - -
public fun add_mint_capability<TokenType: store>(signer: &signer, cap: Token::MintCapability<TokenType>)
-
- - - -
-Implementation - - -
public fun add_mint_capability<TokenType: store>(signer: &signer, cap: MintCapability<TokenType>) {
-    move_to(signer, cap)
-}
-
- - - -
- -
-Specification - - - -
aborts_if exists<MintCapability<TokenType>>(Signer::address_of(signer));
-ensures exists<MintCapability<TokenType>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `destroy_mint_capability` - -Destroy the given mint capability. - - -
public fun destroy_mint_capability<TokenType: store>(cap: Token::MintCapability<TokenType>)
-
- - - -
-Implementation - - -
public fun destroy_mint_capability<TokenType: store>(cap: MintCapability<TokenType>) {
-    let MintCapability<TokenType> {} = cap;
-}
-
- - - -
- -
-Specification - - - -
- - - -## Function `remove_burn_capability` - -remove the token burn capability from signer. - - -
public fun remove_burn_capability<TokenType: store>(signer: &signer): Token::BurnCapability<TokenType>
-
- - - -
-Implementation - - -
public fun remove_burn_capability<TokenType: store>(signer: &signer): BurnCapability<TokenType>
-acquires BurnCapability {
-    move_from<BurnCapability<TokenType>>(Signer::address_of(signer))
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<BurnCapability<TokenType>>(Signer::address_of(signer));
-ensures !exists<BurnCapability<TokenType>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `add_burn_capability` - -Add token burn capability to signer. - - -
public fun add_burn_capability<TokenType: store>(signer: &signer, cap: Token::BurnCapability<TokenType>)
-
- - - -
-Implementation - - -
public fun add_burn_capability<TokenType: store>(signer: &signer, cap: BurnCapability<TokenType>) {
-    move_to(signer, cap)
-}
-
- - - -
- -
-Specification - - - -
aborts_if exists<BurnCapability<TokenType>>(Signer::address_of(signer));
-ensures exists<BurnCapability<TokenType>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `destroy_burn_capability` - -Destroy the given burn capability. - - -
public fun destroy_burn_capability<TokenType: store>(cap: Token::BurnCapability<TokenType>)
-
- - - -
-Implementation - - -
public fun destroy_burn_capability<TokenType: store>(cap: BurnCapability<TokenType>) {
-    let BurnCapability<TokenType> {} = cap;
-}
-
- - - -
- -
-Specification - - - -
- - - -## Function `mint` - -Return amount tokens. -Fails if the sender does not have a published MintCapability. - - -
public fun mint<TokenType: store>(account: &signer, amount: u128): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun mint<TokenType: store>(account: &signer, amount: u128): Token<TokenType>
-acquires TokenInfo, MintCapability {
-    mint_with_capability(
-        borrow_global<MintCapability<TokenType>>(Signer::address_of(account)),
-        amount,
-    )
-}
-
- - - -
- -
-Specification - - - -
aborts_if spec_abstract_total_value<TokenType>() + amount > MAX_U128;
-aborts_if !exists<MintCapability<TokenType>>(Signer::address_of(account));
-
- - - -
- - - -## Function `mint_with_capability` - -Mint a new Token::Token worth amount. -The caller must have a reference to a MintCapability. -Only the Association account can acquire such a reference, and it can do so only via -borrow_sender_mint_capability - - -
public fun mint_with_capability<TokenType: store>(_capability: &Token::MintCapability<TokenType>, amount: u128): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun mint_with_capability<TokenType: store>(
-    _capability: &MintCapability<TokenType>,
-    amount: u128,
-): Token<TokenType> acquires TokenInfo {
-    do_mint(amount)
-}
-
- - - -
- -
-Specification - - - -
aborts_if spec_abstract_total_value<TokenType>() + amount > MAX_U128;
-ensures spec_abstract_total_value<TokenType>() ==
-        old(global<TokenInfo<TokenType>>(SPEC_TOKEN_TEST_ADDRESS()).total_value) + amount;
-
- - - -
- - - -## Function `do_mint` - - - -
fun do_mint<TokenType: store>(amount: u128): Token::Token<TokenType>
-
- - - -
-Implementation - - -
fun do_mint<TokenType: store>(amount: u128): Token<TokenType> acquires TokenInfo {
-    // update market cap resource to reflect minting
-    let (token_address, module_name, token_name) = name_of_token<TokenType>();
-    let info = borrow_global_mut<TokenInfo<TokenType>>(token_address);
-    info.total_value = info.total_value + amount;
-    Event::emit_event(
-        &mut info.mint_events,
-        MintEvent {
-            amount,
-            token_code: TokenCode { addr: token_address, module_name, name: token_name },
-        },
-    );
-    Token<TokenType> { value: amount }
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<TokenInfo<TokenType>>(SPEC_TOKEN_TEST_ADDRESS());
-aborts_if spec_abstract_total_value<TokenType>() + amount > MAX_U128;
-
- - - -
- - - -## Function `issue_fixed_mint_key` - -Deprecated since @v3 -Issue a FixedTimeMintKey with given MintCapability. - - -
public fun issue_fixed_mint_key<TokenType: store>(_capability: &Token::MintCapability<TokenType>, _amount: u128, _period: u64): Token::FixedTimeMintKey<TokenType>
-
- - - -
-Implementation - - -
public fun issue_fixed_mint_key<TokenType: store>(
-    _capability: &MintCapability<TokenType>,
-    _amount: u128,
-    _period: u64,
-): FixedTimeMintKey<TokenType> {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- -
-Specification - - - -
aborts_if true;
-
- - - -
- - - -## Function `issue_linear_mint_key` - -Deprecated since @v3 -Issue a LinearTimeMintKey with given MintCapability. - - -
public fun issue_linear_mint_key<TokenType: store>(_capability: &Token::MintCapability<TokenType>, _amount: u128, _period: u64): Token::LinearTimeMintKey<TokenType>
-
- - - -
-Implementation - - -
public fun issue_linear_mint_key<TokenType: store>(
-    _capability: &MintCapability<TokenType>,
-    _amount: u128,
-    _period: u64,
-): LinearTimeMintKey<TokenType> {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- -
-Specification - - - -
aborts_if true;
-
- - - -
- - - -## Function `destroy_linear_time_key` - -Destroy LinearTimeMintKey, for deprecated - - -
public fun destroy_linear_time_key<TokenType: store>(key: Token::LinearTimeMintKey<TokenType>): (u128, u128, u64, u64)
-
- - - -
-Implementation - - -
public fun destroy_linear_time_key<TokenType: store>(key: LinearTimeMintKey<TokenType>): (u128, u128, u64, u64) {
-    let LinearTimeMintKey<TokenType> { total, minted, start_time, period } = key;
-    (total, minted, start_time, period)
-}
-
- - - -
- - - -## Function `read_linear_time_key` - - - -
public fun read_linear_time_key<TokenType: store>(key: &Token::LinearTimeMintKey<TokenType>): (u128, u128, u64, u64)
-
- - - -
-Implementation - - -
public fun read_linear_time_key<TokenType: store>(key: &LinearTimeMintKey<TokenType>): (u128, u128, u64, u64) {
-    (key.total, key.minted, key.start_time, key.period)
-}
-
- - - -
- - - -## Function `burn` - -Burn some tokens of signer. - - -
public fun burn<TokenType: store>(account: &signer, tokens: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun burn<TokenType: store>(account: &signer, tokens: Token<TokenType>)
-acquires TokenInfo, BurnCapability {
-    burn_with_capability(
-        borrow_global<BurnCapability<TokenType>>(Signer::address_of(account)),
-        tokens,
-    )
-}
-
- - - -
- -
-Specification - - - -
aborts_if spec_abstract_total_value<TokenType>() - tokens.value < 0;
-aborts_if !exists<BurnCapability<TokenType>>(Signer::address_of(account));
-
- - - -
- - - -## Function `burn_with_capability` - -Burn tokens with the given BurnCapability. - - -
public fun burn_with_capability<TokenType: store>(_capability: &Token::BurnCapability<TokenType>, tokens: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun burn_with_capability<TokenType: store>(
-    _capability: &BurnCapability<TokenType>,
-    tokens: Token<TokenType>,
-) acquires TokenInfo {
-    let (token_address, module_name, token_name) = name_of_token<TokenType>();
-    let info = borrow_global_mut<TokenInfo<TokenType>>(token_address);
-    let Token { value } = tokens;
-    info.total_value = info.total_value - value;
-    Event::emit_event(
-        &mut info.burn_events,
-        BurnEvent {
-            amount: value,
-            token_code: TokenCode { addr: token_address, module_name, name: token_name },
-        },
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if spec_abstract_total_value<TokenType>() - tokens.value < 0;
-ensures spec_abstract_total_value<TokenType>() ==
-        old(global<TokenInfo<TokenType>>(SPEC_TOKEN_TEST_ADDRESS()).total_value) - tokens.value;
-
- - - -
- - - -## Function `zero` - -Create a new Token::Token with a value of 0 - - -
public fun zero<TokenType: store>(): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun zero<TokenType: store>(): Token<TokenType> {
-    Token<TokenType> { value: 0 }
-}
-
- - - -
- -
-Specification - - - -
ensures result.value == 0;
-
- - - -
- - - -## Function `value` - -Public accessor for the value of a token - - -
public fun value<TokenType: store>(token: &Token::Token<TokenType>): u128
-
- - - -
-Implementation - - -
public fun value<TokenType: store>(token: &Token<TokenType>): u128 {
-    token.value
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == token.value;
-
- - - -
- - - -## Function `split` - -Splits the given token into two and returns them both - - -
public fun split<TokenType: store>(token: Token::Token<TokenType>, value: u128): (Token::Token<TokenType>, Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun split<TokenType: store>(
-    token: Token<TokenType>,
-    value: u128,
-): (Token<TokenType>, Token<TokenType>) {
-    let rest = withdraw(&mut token, value);
-    (token, rest)
-}
-
- - - -
- -
-Specification - - - -
aborts_if token.value < value;
-ensures token.value == result_1.value + result_2.value;
-
- - - -
- - - -## Function `withdraw` - -"Divides" the given token into two, where the original token is modified in place. -The original token will have value = original value - value -The new token will have a value = value -Fails if the tokens value is less than value - - -
public fun withdraw<TokenType: store>(token: &mut Token::Token<TokenType>, value: u128): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun withdraw<TokenType: store>(
-    token: &mut Token<TokenType>,
-    value: u128,
-): Token<TokenType> {
-    // Check that `value` is less than the token's value
-    assert!(token.value >= value, Errors::limit_exceeded(EAMOUNT_EXCEEDS_COIN_VALUE));
-    token.value = token.value - value;
-    Token { value: value }
-}
-
- - - -
- -
-Specification - - - -
aborts_if token.value < value;
-ensures result.value == value;
-ensures token.value == old(token).value - value;
-
- - - -
- - - -## Function `join` - -Merges two tokens of the same token and returns a new token whose -value is equal to the sum of the two inputs - - -
public fun join<TokenType: store>(token1: Token::Token<TokenType>, token2: Token::Token<TokenType>): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun join<TokenType: store>(
-    token1: Token<TokenType>,
-    token2: Token<TokenType>,
-): Token<TokenType> {
-    deposit(&mut token1, token2);
-    token1
-}
-
- - - -
- -
-Specification - - - -
aborts_if token1.value + token2.value > max_u128();
-ensures token1.value + token2.value == result.value;
-
- - - -
- - - -## Function `deposit` - -"Merges" the two tokens -The token passed in by reference will have a value equal to the sum of the two tokens -The check token is consumed in the process - - -
public fun deposit<TokenType: store>(token: &mut Token::Token<TokenType>, check: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun deposit<TokenType: store>(token: &mut Token<TokenType>, check: Token<TokenType>) {
-    let Token { value } = check;
-    token.value = token.value + value;
-}
-
- - - -
- -
-Specification - - - -
aborts_if token.value + check.value > max_u128();
-ensures old(token).value + check.value == token.value;
-
- - - -
- - - -## Function `destroy_zero` - -Destroy a token -Fails if the value is non-zero -The amount of Token in the system is a tightly controlled property, -so you cannot "burn" any non-zero amount of Token - - -
public fun destroy_zero<TokenType: store>(token: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun destroy_zero<TokenType: store>(token: Token<TokenType>) {
-    let Token { value } = token;
-    assert!(value == 0, Errors::invalid_state(EDESTROY_TOKEN_NON_ZERO))
-}
-
- - - -
- -
-Specification - - - -
aborts_if token.value > 0;
-
- - - -
- - - -## Function `scaling_factor` - -Returns the scaling_factor for the TokenType token. - - -
public fun scaling_factor<TokenType: store>(): u128
-
- - - -
-Implementation - - -
public fun scaling_factor<TokenType: store>(): u128 acquires TokenInfo {
-    let token_address = token_address<TokenType>();
-    borrow_global<TokenInfo<TokenType>>(token_address).scaling_factor
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == global<TokenInfo<TokenType>>(SPEC_TOKEN_TEST_ADDRESS()).scaling_factor;
-
- - - -
- - - -## Function `market_cap` - -Return the total amount of token of type TokenType. - - -
public fun market_cap<TokenType: store>(): u128
-
- - - -
-Implementation - - -
public fun market_cap<TokenType: store>(): u128 acquires TokenInfo {
-    let token_address = token_address<TokenType>();
-    borrow_global<TokenInfo<TokenType>>(token_address).total_value
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == global<TokenInfo<TokenType>>(SPEC_TOKEN_TEST_ADDRESS()).total_value;
-
- - - -
- - - -## Function `is_registered_in` - -Return true if the type TokenType is a registered in token_address. - - -
public fun is_registered_in<TokenType: store>(token_address: address): bool
-
- - - -
-Implementation - - -
public fun is_registered_in<TokenType: store>(token_address: address): bool {
-    exists<TokenInfo<TokenType>>(token_address)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == exists<TokenInfo<TokenType>>(token_address);
-
- - - -
- - - -## Function `is_same_token` - -Return true if the type TokenType1 is same with TokenType2 - - -
public fun is_same_token<TokenType1: store, TokenType2: store>(): bool
-
- - - -
-Implementation - - -
public fun is_same_token<TokenType1: store, TokenType2: store>(): bool {
-    return token_code<TokenType1>() == token_code<TokenType2>()
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `token_address` - -Return the TokenType's address - - -
public fun token_address<TokenType: store>(): address
-
- - - -
-Implementation - - -
public fun token_address<TokenType: store>(): address {
-    let (addr, _, _) = name_of<TokenType>();
-    addr
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures [abstract] exists<TokenInfo<TokenType>>(result);
-ensures [abstract] result == SPEC_TOKEN_TEST_ADDRESS();
-ensures [abstract] global<TokenInfo<TokenType>>(result).total_value == 100000000u128;
-
- - - -
- - - -## Function `token_code` - -Return the token code for the registered token. - - -
public fun token_code<TokenType: store>(): Token::TokenCode
-
- - - -
-Implementation - - -
public fun token_code<TokenType: store>(): TokenCode {
-    let (addr, module_name, name) = name_of<TokenType>();
-    TokenCode {
-        addr,
-        module_name,
-        name
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-
- - -We use an uninterpreted function to represent the result of derived address. The actual value -does not matter for the verification of callers. - - - - - -
fun spec_token_code<TokenType>(): TokenCode;
-
- - - -
- - - -## Function `type_of` - - - -
public(friend) fun type_of<T>(): (address, vector<u8>, vector<u8>)
-
- - - -
-Implementation - - -
public (friend) fun type_of<T>(): (address, vector<u8>, vector<u8>){
-    name_of<T>()
-}
-
- - - -
- - - -## Function `name_of` - -Return Token's module address, module name, and type name of TokenType. - - -
fun name_of<TokenType>(): (address, vector<u8>, vector<u8>)
-
- - - -
-Implementation - - -
native fun name_of<TokenType>(): (address, vector<u8>, vector<u8>);
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-
- - - -
- - - -## Function `name_of_token` - - - -
fun name_of_token<TokenType: store>(): (address, vector<u8>, vector<u8>)
-
- - - -
-Implementation - - -
fun name_of_token<TokenType: store>(): (address, vector<u8>, vector<u8>) {
-    name_of<TokenType>()
-}
-
- - - -
- -
-Specification - - - -
pragma opaque = true;
-aborts_if false;
-ensures [abstract] exists<TokenInfo<TokenType>>(result_1);
-ensures [abstract] result_1 == SPEC_TOKEN_TEST_ADDRESS();
-ensures [abstract] global<TokenInfo<TokenType>>(result_1).total_value == 100000000u128;
-
- - - - - - - -
fun SPEC_TOKEN_TEST_ADDRESS(): address {
-   @0x2
-}
-
- - - - - - - -
fun spec_abstract_total_value<TokenType>(): num {
-   global<TokenInfo<TokenType>>(SPEC_TOKEN_TEST_ADDRESS()).total_value
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/TransactionFee.md b/release/v12/docs/TransactionFee.md deleted file mode 100644 index b6dcc89b..00000000 --- a/release/v12/docs/TransactionFee.md +++ /dev/null @@ -1,245 +0,0 @@ - - - -# Module `0x1::TransactionFee` - -TransactionFee collect gas fees used by transactions in blocks temporarily. -Then they are distributed in TransactionManager. - - -- [Resource `TransactionFee`](#0x1_TransactionFee_TransactionFee) -- [Function `initialize`](#0x1_TransactionFee_initialize) -- [Function `add_txn_fee_token`](#0x1_TransactionFee_add_txn_fee_token) -- [Function `pay_fee`](#0x1_TransactionFee_pay_fee) -- [Function `distribute_transaction_fees`](#0x1_TransactionFee_distribute_transaction_fees) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::CoreAddresses;
-use 0x1::STC;
-use 0x1::Timestamp;
-use 0x1::Token;
-
- - - - - -## Resource `TransactionFee` - -The TransactionFee resource holds a preburn resource for each -fiat TokenType that can be collected as a transaction fee. - - -
struct TransactionFee<TokenType> has key
-
- - - -
-Fields - - -
-
-fee: Token::Token<TokenType> -
-
- -
-
- - -
- - - -## Function `initialize` - -Called in genesis. Sets up the needed resources to collect transaction fees from the -TransactionFee resource with the TreasuryCompliance account. - - -
public fun initialize(account: &signer)
-
- - - -
-Implementation - - -
public fun initialize(
-    account: &signer,
-) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-
-    // accept fees in all the currencies
-    add_txn_fee_token<STC>(account);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if exists<TransactionFee<STC>>(Signer::address_of(account));
-
- - - -
- - - -## Function `add_txn_fee_token` - -publishing a wrapper of the Preburn<TokenType> resource under fee_account - - -
fun add_txn_fee_token<TokenType: store>(account: &signer)
-
- - - -
-Implementation - - -
fun add_txn_fee_token<TokenType: store>(
-    account: &signer,
-) {
-    move_to(
-        account,
-        TransactionFee<TokenType> {
-            fee: Token::zero(),
-        }
-    )
- }
-
- - - -
- -
-Specification - - - -
aborts_if exists<TransactionFee<TokenType>>(Signer::address_of(account));
-
- - - -
- - - -## Function `pay_fee` - -Deposit token into the transaction fees bucket - - -
public fun pay_fee<TokenType: store>(token: Token::Token<TokenType>)
-
- - - -
-Implementation - - -
public fun pay_fee<TokenType: store>(token: Token<TokenType>) acquires TransactionFee {
-    let txn_fees = borrow_global_mut<TransactionFee<TokenType>>(
-        CoreAddresses::GENESIS_ADDRESS()
-    );
-    Token::deposit(&mut txn_fees.fee, token)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if global<TransactionFee<TokenType>>(CoreAddresses::GENESIS_ADDRESS()).fee.value + token.value > max_u128();
-
- - - -
- - - -## Function `distribute_transaction_fees` - -Distribute the transaction fees collected in the TokenType token. -If the TokenType is STC, it unpacks the token and preburns the -underlying fiat. - - -
public fun distribute_transaction_fees<TokenType: store>(account: &signer): Token::Token<TokenType>
-
- - - -
-Implementation - - -
public fun distribute_transaction_fees<TokenType: store>(
-    account: &signer,
-): Token<TokenType> acquires TransactionFee {
-    let fee_address =  CoreAddresses::GENESIS_ADDRESS();
-    CoreAddresses::assert_genesis_address(account);
-
-    // extract fees
-    let txn_fees = borrow_global_mut<TransactionFee<TokenType>>(fee_address);
-    let value = Token::value<TokenType>(&txn_fees.fee);
-    if (value > 0) {
-        Token::withdraw(&mut txn_fees.fee, value)
-    }else {
-        Token::zero<TokenType>()
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/TransactionManager.md b/release/v12/docs/TransactionManager.md deleted file mode 100644 index b1686d9e..00000000 --- a/release/v12/docs/TransactionManager.md +++ /dev/null @@ -1,444 +0,0 @@ - - - -# Module `0x1::TransactionManager` - -TransactionManager manages: -1. prologue and epilogue of transactions. -2. prologue of blocks. - - -- [Constants](#@Constants_0) -- [Function `prologue`](#0x1_TransactionManager_prologue) -- [Function `epilogue`](#0x1_TransactionManager_epilogue) -- [Function `epilogue_v2`](#0x1_TransactionManager_epilogue_v2) -- [Function `block_prologue`](#0x1_TransactionManager_block_prologue) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Account;
-use 0x1::Block;
-use 0x1::BlockReward;
-use 0x1::ChainId;
-use 0x1::CoreAddresses;
-use 0x1::Epoch;
-use 0x1::Errors;
-use 0x1::GasOracle;
-use 0x1::GasOracleProposalPlugin;
-use 0x1::PackageTxnManager;
-use 0x1::STC;
-use 0x1::Signer;
-use 0x1::StarcoinDAO;
-use 0x1::Timestamp;
-use 0x1::Token;
-use 0x1::TransactionFee;
-use 0x1::TransactionPublishOption;
-use 0x1::TransactionTimeout;
-use 0x1::Vector;
-
- - - - - -## Constants - - - - - - -
const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0;
-
- - - - - - - -
const EPROLOGUE_BAD_CHAIN_ID: u64 = 6;
-
- - - - - - - -
const EPROLOGUE_MODULE_NOT_ALLOWED: u64 = 7;
-
- - - - - - - -
const EPROLOGUE_SCRIPT_NOT_ALLOWED: u64 = 8;
-
- - - - - - - -
const EPROLOGUE_TRANSACTION_EXPIRED: u64 = 5;
-
- - - - - - - -
const TXN_PAYLOAD_TYPE_PACKAGE: u8 = 1;
-
- - - - - - - -
const TXN_PAYLOAD_TYPE_SCRIPT: u8 = 0;
-
- - - - - - - -
const TXN_PAYLOAD_TYPE_SCRIPT_FUNCTION: u8 = 2;
-
- - - - - -## Function `prologue` - -The prologue is invoked at the beginning of every transaction -It verifies: -- The account's auth key matches the transaction's public key -- That the account has enough balance to pay for all of the gas -- That the sequence number matches the transaction's sequence key - - -
public fun prologue<TokenType: store>(account: signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, txn_expiration_time: u64, chain_id: u8, txn_payload_type: u8, txn_script_or_package_hash: vector<u8>, txn_package_address: address)
-
- - - -
-Implementation - - -
public fun prologue<TokenType: store>(
-    account: signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    txn_expiration_time: u64,
-    chain_id: u8,
-    txn_payload_type: u8,
-    txn_script_or_package_hash: vector<u8>,
-    txn_package_address: address,
-) {
-    // Can only be invoked by genesis account
-    assert!(
-        Signer::address_of(&account) == CoreAddresses::GENESIS_ADDRESS(),
-        Errors::requires_address(EPROLOGUE_ACCOUNT_DOES_NOT_EXIST),
-    );
-    // Check that the chain ID stored on-chain matches the chain ID
-    // specified by the transaction
-    assert!(ChainId::get() == chain_id, Errors::invalid_argument(EPROLOGUE_BAD_CHAIN_ID));
-    let (stc_price,scaling_factor)= if (!STC::is_stc<TokenType>()){
-        (GasOracleProposalPlugin::gas_oracle_read<StarcoinDAO, TokenType>(),GasOracle::get_scaling_factor<TokenType>())
-    }else{
-        (1,1)
-    };
-
-    Account::txn_prologue_v2<TokenType>(
-        &account,
-        txn_sender,
-        txn_sequence_number,
-        txn_authentication_key_preimage,
-        txn_gas_price,
-        txn_max_gas_units,
-        stc_price,
-        scaling_factor,
-    );
-    assert!(
-        TransactionTimeout::is_valid_transaction_timestamp(txn_expiration_time),
-        Errors::invalid_argument(EPROLOGUE_TRANSACTION_EXPIRED),
-    );
-    if (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE) {
-        // stdlib upgrade is not affected by PublishOption
-        if (txn_package_address != CoreAddresses::GENESIS_ADDRESS()) {
-            assert!(
-                TransactionPublishOption::is_module_allowed(Signer::address_of(&account)),
-                Errors::invalid_argument(EPROLOGUE_MODULE_NOT_ALLOWED),
-            );
-        };
-        PackageTxnManager::package_txn_prologue_v2(
-            &account,
-            txn_sender,
-            txn_package_address,
-            txn_script_or_package_hash,
-        );
-    } else if (txn_payload_type == TXN_PAYLOAD_TYPE_SCRIPT) {
-        assert!(
-            TransactionPublishOption::is_script_allowed(
-                Signer::address_of(&account),
-            ),
-            Errors::invalid_argument(EPROLOGUE_SCRIPT_NOT_ALLOWED),
-        );
-    };
-    // do nothing for TXN_PAYLOAD_TYPE_SCRIPT_FUNCTION
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<ChainId::ChainId>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if ChainId::get() != chain_id;
-aborts_if !exists<Account::Account>(txn_sender);
-aborts_if Hash::sha3_256(txn_authentication_key_preimage) != global<Account::Account>(txn_sender).authentication_key;
-aborts_if txn_gas_price * txn_max_gas_units > max_u64();
-include Timestamp::AbortsIfTimestampNotExists;
-include Block::AbortsIfBlockMetadataNotExist;
-aborts_if txn_gas_price * txn_max_gas_units > 0 && !exists<Account::Balance<TokenType>>(txn_sender);
-aborts_if txn_gas_price * txn_max_gas_units > 0 && txn_sequence_number >= max_u64();
-aborts_if txn_sequence_number < global<Account::Account>(txn_sender).sequence_number;
-aborts_if txn_sequence_number != global<Account::Account>(txn_sender).sequence_number;
-include TransactionTimeout::AbortsIfTimestampNotValid;
-aborts_if !TransactionTimeout::spec_is_valid_transaction_timestamp(txn_expiration_time);
-include TransactionPublishOption::AbortsIfTxnPublishOptionNotExistWithBool {
-    is_script_or_package: (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE || txn_payload_type == TXN_PAYLOAD_TYPE_SCRIPT),
-};
-aborts_if txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE && txn_package_address != CoreAddresses::GENESIS_ADDRESS() && !TransactionPublishOption::spec_is_module_allowed(Signer::address_of(account));
-aborts_if txn_payload_type == TXN_PAYLOAD_TYPE_SCRIPT && !TransactionPublishOption::spec_is_script_allowed(Signer::address_of(account));
-include PackageTxnManager::CheckPackageTxnAbortsIfWithType{is_package: (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE), sender:txn_sender, package_address: txn_package_address, package_hash: txn_script_or_package_hash};
-
- - - -
- - - -## Function `epilogue` - -The epilogue is invoked at the end of transactions. -It collects gas and bumps the sequence number - - -
public fun epilogue<TokenType: store>(account: signer, txn_sender: address, txn_sequence_number: u64, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64, txn_payload_type: u8, _txn_script_or_package_hash: vector<u8>, txn_package_address: address, success: bool)
-
- - - -
-Implementation - - -
public fun epilogue<TokenType: store>(
-    account: signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining: u64,
-    txn_payload_type: u8,
-    _txn_script_or_package_hash: vector<u8>,
-    txn_package_address: address,
-    // txn execute success or fail.
-    success: bool,
-) {
-    epilogue_v2<TokenType>(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining, txn_payload_type, _txn_script_or_package_hash, txn_package_address, success)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-include CoreAddresses::AbortsIfNotGenesisAddress;
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if !exists<Account::Account>(txn_sender);
-aborts_if !exists<Account::Balance<TokenType>>(txn_sender);
-aborts_if txn_max_gas_units < gas_units_remaining;
-aborts_if txn_sequence_number + 1 > max_u64();
-aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u64();
-include PackageTxnManager::AbortsIfPackageTxnEpilogue {
-    is_package: (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE),
-    package_address: txn_package_address,
-    success: success,
-};
-
- - - -
- - - -## Function `epilogue_v2` - -The epilogue is invoked at the end of transactions. -It collects gas and bumps the sequence number - - -
public fun epilogue_v2<TokenType: store>(account: signer, txn_sender: address, txn_sequence_number: u64, txn_authentication_key_preimage: vector<u8>, txn_gas_price: u64, txn_max_gas_units: u64, gas_units_remaining: u64, txn_payload_type: u8, _txn_script_or_package_hash: vector<u8>, txn_package_address: address, success: bool)
-
- - - -
-Implementation - - -
public fun epilogue_v2<TokenType: store>(
-    account: signer,
-    txn_sender: address,
-    txn_sequence_number: u64,
-    txn_authentication_key_preimage: vector<u8>,
-    txn_gas_price: u64,
-    txn_max_gas_units: u64,
-    gas_units_remaining: u64,
-    txn_payload_type: u8,
-    _txn_script_or_package_hash: vector<u8>,
-    txn_package_address: address,
-    // txn execute success or fail.
-    success: bool,
-) {
-    CoreAddresses::assert_genesis_address(&account);
-    let (stc_price,scaling_factor) =
-    if (!STC::is_stc<TokenType>()){
-        (GasOracleProposalPlugin::gas_oracle_read<StarcoinDAO, TokenType>(),GasOracle::get_scaling_factor<TokenType>())
-    }else{
-        (1,1)
-    };
-    Account::txn_epilogue_v3<TokenType>(
-        &account,
-        txn_sender,
-        txn_sequence_number,
-        txn_authentication_key_preimage,
-        txn_gas_price,
-        txn_max_gas_units,
-        gas_units_remaining,
-        stc_price,
-        scaling_factor
-    );
-    if (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE) {
-        PackageTxnManager::package_txn_epilogue(
-            &account,
-            txn_sender,
-            txn_package_address,
-            success,
-        );
-    }
-}
-
- - - -
- - - -## Function `block_prologue` - -Set the metadata for the current block and distribute transaction fees and block rewards. -The runtime always runs this before executing the transactions in a block. - - -
public fun block_prologue(account: signer, parent_hash: vector<u8>, timestamp: u64, author: address, auth_key_vec: vector<u8>, uncles: u64, number: u64, chain_id: u8, parent_gas_used: u64)
-
- - - -
-Implementation - - -
public fun block_prologue(
-    account: signer,
-    parent_hash: vector<u8>,
-    timestamp: u64,
-    author: address,
-    auth_key_vec: vector<u8>,
-    uncles: u64,
-    number: u64,
-    chain_id: u8,
-    parent_gas_used: u64,
-) {
-    // Can only be invoked by genesis account
-    CoreAddresses::assert_genesis_address(&account);
-    // Check that the chain ID stored on-chain matches the chain ID
-    // specified by the transaction
-    assert!(ChainId::get() == chain_id, Errors::invalid_argument(EPROLOGUE_BAD_CHAIN_ID));
-
-    // deal with previous block first.
-    let txn_fee = TransactionFee::distribute_transaction_fees<STC>(&account);
-
-    // then deal with current block.
-    Timestamp::update_global_time(&account, timestamp);
-    Block::process_block_metadata(
-        &account,
-        parent_hash,
-        author,
-        timestamp,
-        uncles,
-        number,
-    );
-    let reward = Epoch::adjust_epoch(&account, number, timestamp, uncles, parent_gas_used);
-    // pass in previous block gas fees.
-    BlockReward::process_block_reward(&account, number, reward, author, auth_key_vec, txn_fee);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/TransactionPublishOption.md b/release/v12/docs/TransactionPublishOption.md deleted file mode 100644 index cc211f66..00000000 --- a/release/v12/docs/TransactionPublishOption.md +++ /dev/null @@ -1,348 +0,0 @@ - - - -# Module `0x1::TransactionPublishOption` - -TransactionPublishOption provide an option to limit: -- whether user can use script or publish custom modules on chain. - - -- [Struct `TransactionPublishOption`](#0x1_TransactionPublishOption_TransactionPublishOption) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_TransactionPublishOption_initialize) -- [Function `new_transaction_publish_option`](#0x1_TransactionPublishOption_new_transaction_publish_option) -- [Function `is_script_allowed`](#0x1_TransactionPublishOption_is_script_allowed) -- [Function `is_module_allowed`](#0x1_TransactionPublishOption_is_module_allowed) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Errors;
-use 0x1::Signer;
-use 0x1::Timestamp;
-
- - - - - -## Struct `TransactionPublishOption` - -Defines and holds the publishing policies for the VM. There are three possible configurations: -1. !script_allowed && !module_publishing_allowed No module publishing, only script function in module are allowed. -2. script_allowed && !module_publishing_allowed No module publishing, custom scripts are allowed. -3. script_allowed && module_publishing_allowed Both module publishing and custom scripts are allowed. -We represent these as the following resource. - - -
struct TransactionPublishOption has copy, drop, store
-
- - - -
-Fields - - -
-
-script_allowed: bool -
-
- -
-
-module_publishing_allowed: bool -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const EINVALID_ARGUMENT: u64 = 18;
-
- - - - - - - -
const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0;
-
- - - - - -The script hash already exists in the allowlist - - -
const EALLOWLIST_ALREADY_CONTAINS_SCRIPT: u64 = 1002;
-
- - - - - -The script hash has an invalid length - - -
const EINVALID_SCRIPT_HASH: u64 = 1001;
-
- - - - - - - -
const SCRIPT_HASH_LENGTH: u64 = 32;
-
- - - - - -## Function `initialize` - -Module initialization. - - -
public fun initialize(account: &signer, script_allowed: bool, module_publishing_allowed: bool)
-
- - - -
-Implementation - - -
public fun initialize(
-    account: &signer,
-    script_allowed: bool,
-    module_publishing_allowed: bool,
-) {
-    Timestamp::assert_genesis();
-    assert!(
-        Signer::address_of(account) == CoreAddresses::GENESIS_ADDRESS(),
-        Errors::requires_address(EPROLOGUE_ACCOUNT_DOES_NOT_EXIST),
-    );
-    let transaction_publish_option = Self::new_transaction_publish_option(script_allowed, module_publishing_allowed);
-    Config::publish_new_config(
-        account,
-        transaction_publish_option,
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-include Config::PublishNewConfigAbortsIf<TransactionPublishOption>;
-include Config::PublishNewConfigEnsures<TransactionPublishOption>;
-
- - - -
- - - -## Function `new_transaction_publish_option` - -Create a new option. Mainly used in DAO. - - -
public fun new_transaction_publish_option(script_allowed: bool, module_publishing_allowed: bool): TransactionPublishOption::TransactionPublishOption
-
- - - -
-Implementation - - -
public fun new_transaction_publish_option(
-    script_allowed: bool,
-    module_publishing_allowed: bool,
-): TransactionPublishOption {
-    TransactionPublishOption { script_allowed, module_publishing_allowed }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `is_script_allowed` - -Check if sender can execute script with - - -
public fun is_script_allowed(account: address): bool
-
- - - -
-Implementation - - -
public fun is_script_allowed(account: address): bool {
-    let publish_option = Config::get_by_address<TransactionPublishOption>(account);
-    publish_option.script_allowed
-}
-
- - - -
- -
-Specification - - - -
include Config::AbortsIfConfigNotExist<TransactionPublishOption>{
-    addr: account
-};
-
- - - -
- - - -## Function `is_module_allowed` - -Check if a sender can publish a module - - -
public fun is_module_allowed(account: address): bool
-
- - - -
-Implementation - - -
public fun is_module_allowed(account: address): bool {
-    let publish_option = Config::get_by_address<TransactionPublishOption>(account);
-    publish_option.module_publishing_allowed
-}
-
- - - -
- -
-Specification - - - -
include Config::AbortsIfConfigNotExist<TransactionPublishOption>{
-    addr: account
-};
-
- - - - - - - -
schema AbortsIfTxnPublishOptionNotExist {
-    include Config::AbortsIfConfigNotExist<TransactionPublishOption>{
-        addr: CoreAddresses::GENESIS_ADDRESS()
-    };
-}
-
- - - - - - - -
schema AbortsIfTxnPublishOptionNotExistWithBool {
-    is_script_or_package : bool;
-    aborts_if is_script_or_package && !exists<Config::Config<TransactionPublishOption>>(CoreAddresses::GENESIS_ADDRESS());
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
- - - - - - - -
fun spec_is_script_allowed(addr: address) : bool{
-   let publish_option = Config::get_by_address<TransactionPublishOption>(addr);
-   publish_option.script_allowed
-}
-
- - - - - - - -
fun spec_is_module_allowed(addr: address) : bool{
-   let publish_option = Config::get_by_address<TransactionPublishOption>(addr);
-   publish_option.module_publishing_allowed
-}
-
diff --git a/release/v12/docs/TransactionTimeout.md b/release/v12/docs/TransactionTimeout.md deleted file mode 100644 index 9e5baaf1..00000000 --- a/release/v12/docs/TransactionTimeout.md +++ /dev/null @@ -1,108 +0,0 @@ - - - -# Module `0x1::TransactionTimeout` - -A module used to check expiration time of transactions. - - -- [Function `is_valid_transaction_timestamp`](#0x1_TransactionTimeout_is_valid_transaction_timestamp) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::Block;
-use 0x1::Timestamp;
-use 0x1::TransactionTimeoutConfig;
-
- - - - - -## Function `is_valid_transaction_timestamp` - -Check whether the given timestamp is valid for transactions. - - -
public fun is_valid_transaction_timestamp(txn_timestamp: u64): bool
-
- - - -
-Implementation - - -
public fun is_valid_transaction_timestamp(txn_timestamp: u64): bool {
-  let current_block_time = Timestamp::now_seconds();
-  let block_number = Block::get_current_block_number();
-  // before first block, just require txn_timestamp > genesis timestamp.
-  if (block_number == 0) {
-    return txn_timestamp > current_block_time
-  };
-  let timeout = TransactionTimeoutConfig::duration_seconds();
-  let max_txn_time = current_block_time + timeout;
-  current_block_time < txn_timestamp && txn_timestamp < max_txn_time
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if !exists<Block::BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-include Timestamp::AbortsIfTimestampNotExists;
-aborts_if Block::get_current_block_number() != 0 && Timestamp::now_seconds() + TransactionTimeoutConfig::duration_seconds() > max_u64();
-aborts_if Block::get_current_block_number() != 0 && !exists<Config::Config<TransactionTimeoutConfig::TransactionTimeoutConfig>>(CoreAddresses::GENESIS_ADDRESS());
-
- - - - - - - -
schema AbortsIfTimestampNotValid {
-    aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-    aborts_if !exists<Block::BlockMetadata>(CoreAddresses::GENESIS_ADDRESS());
-    include Timestamp::AbortsIfTimestampNotExists;
-    aborts_if Block::get_current_block_number() != 0 && Timestamp::now_seconds() + TransactionTimeoutConfig::duration_seconds() > max_u64();
-    aborts_if Block::get_current_block_number() != 0 && !exists<Config::Config<TransactionTimeoutConfig::TransactionTimeoutConfig>>(CoreAddresses::GENESIS_ADDRESS());
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
- - - - - - - -
fun spec_is_valid_transaction_timestamp(txn_timestamp: u64):bool {
- if (Block::get_current_block_number() == 0) {
-   txn_timestamp > Timestamp::now_seconds()
- } else {
-     Timestamp::now_seconds() < txn_timestamp && txn_timestamp <
-     (Timestamp::now_seconds() + TransactionTimeoutConfig::duration_seconds())
- }
-}
-
diff --git a/release/v12/docs/TransactionTimeoutConfig.md b/release/v12/docs/TransactionTimeoutConfig.md deleted file mode 100644 index e0488861..00000000 --- a/release/v12/docs/TransactionTimeoutConfig.md +++ /dev/null @@ -1,235 +0,0 @@ - - - -# Module `0x1::TransactionTimeoutConfig` - -Onchain configuration for timeout setting of transaction. - - -- [Struct `TransactionTimeoutConfig`](#0x1_TransactionTimeoutConfig_TransactionTimeoutConfig) -- [Function `initialize`](#0x1_TransactionTimeoutConfig_initialize) -- [Function `new_transaction_timeout_config`](#0x1_TransactionTimeoutConfig_new_transaction_timeout_config) -- [Function `get_transaction_timeout_config`](#0x1_TransactionTimeoutConfig_get_transaction_timeout_config) -- [Function `duration_seconds`](#0x1_TransactionTimeoutConfig_duration_seconds) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Timestamp;
-
- - - - - -## Struct `TransactionTimeoutConfig` - -config structs. - - -
struct TransactionTimeoutConfig has copy, drop, store
-
- - - -
-Fields - - -
-
-duration_seconds: u64 -
-
- timeout in second. -
-
- - -
- - - -## Function `initialize` - -Initialize function. Should only be called in genesis. - - -
public fun initialize(account: &signer, duration_seconds: u64)
-
- - - -
-Implementation - - -
public fun initialize(account: &signer, duration_seconds: u64) {
-    Timestamp::assert_genesis();
-    CoreAddresses::assert_genesis_address(account);
-
-    Config::publish_new_config<Self::TransactionTimeoutConfig>(
-        account,
-        new_transaction_timeout_config(duration_seconds)
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if !Timestamp::is_genesis();
-aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-include Config::PublishNewConfigAbortsIf<TransactionTimeoutConfig>;
-include Config::PublishNewConfigEnsures<TransactionTimeoutConfig>;
-
- - - -
- - - -## Function `new_transaction_timeout_config` - -Create a new timeout config used in dao proposal. - - -
public fun new_transaction_timeout_config(duration_seconds: u64): TransactionTimeoutConfig::TransactionTimeoutConfig
-
- - - -
-Implementation - - -
public fun new_transaction_timeout_config(duration_seconds: u64) : TransactionTimeoutConfig {
-    TransactionTimeoutConfig {duration_seconds: duration_seconds}
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `get_transaction_timeout_config` - -Get current timeout config. - - -
public fun get_transaction_timeout_config(): TransactionTimeoutConfig::TransactionTimeoutConfig
-
- - - -
-Implementation - - -
public fun get_transaction_timeout_config(): TransactionTimeoutConfig {
-    Config::get_by_address<TransactionTimeoutConfig>(CoreAddresses::GENESIS_ADDRESS())
-}
-
- - - -
- -
-Specification - - - -
include Config::AbortsIfConfigNotExist<TransactionTimeoutConfig>{
-    addr: CoreAddresses::GENESIS_ADDRESS()
-};
-
- - - -
- - - -## Function `duration_seconds` - -Get current txn timeout in seconds. - - -
public fun duration_seconds(): u64
-
- - - -
-Implementation - - -
public fun duration_seconds() :u64 {
-    let config = get_transaction_timeout_config();
-    config.duration_seconds
-}
-
- - - -
- -
-Specification - - - -
include Config::AbortsIfConfigNotExist<TransactionTimeoutConfig>{
-    addr: CoreAddresses::GENESIS_ADDRESS()
-};
-
- - - - - - - -
schema AbortsIfTxnTimeoutConfigNotExist {
-    include Config::AbortsIfConfigNotExist<TransactionTimeoutConfig>{
-        addr: CoreAddresses::GENESIS_ADDRESS()
-    };
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict = true;
-
diff --git a/release/v12/docs/TransferScripts.md b/release/v12/docs/TransferScripts.md deleted file mode 100644 index 030fd6e3..00000000 --- a/release/v12/docs/TransferScripts.md +++ /dev/null @@ -1,253 +0,0 @@ - - - -# Module `0x1::TransferScripts` - - - -- [Constants](#@Constants_0) -- [Function `peer_to_peer`](#0x1_TransferScripts_peer_to_peer) -- [Function `peer_to_peer_v2`](#0x1_TransferScripts_peer_to_peer_v2) -- [Function `batch_peer_to_peer`](#0x1_TransferScripts_batch_peer_to_peer) -- [Function `batch_peer_to_peer_v2`](#0x1_TransferScripts_batch_peer_to_peer_v2) -- [Function `peer_to_peer_batch`](#0x1_TransferScripts_peer_to_peer_batch) -- [Function `peer_to_peer_with_metadata`](#0x1_TransferScripts_peer_to_peer_with_metadata) -- [Function `peer_to_peer_with_metadata_v2`](#0x1_TransferScripts_peer_to_peer_with_metadata_v2) - - -
use 0x1::Account;
-use 0x1::Errors;
-use 0x1::Vector;
-
- - - - - -## Constants - - - - - - -
const EDEPRECATED_FUNCTION: u64 = 19;
-
- - - - - - - -
const EADDRESS_AND_AUTH_KEY_MISMATCH: u64 = 101;
-
- - - - - - - -
const ELENGTH_MISMATCH: u64 = 102;
-
- - - - - -## Function `peer_to_peer` - - - -
public(script) fun peer_to_peer<TokenType: store>(account: signer, payee: address, _payee_auth_key: vector<u8>, amount: u128)
-
- - - -
-Implementation - - -
public(script) fun peer_to_peer<TokenType: store>(account: signer, payee: address, _payee_auth_key: vector<u8>, amount: u128) {
-     peer_to_peer_v2<TokenType>(account, payee, amount)
-}
-
- - - -
- - - -## Function `peer_to_peer_v2` - - - -
public(script) fun peer_to_peer_v2<TokenType: store>(account: signer, payee: address, amount: u128)
-
- - - -
-Implementation - - -
public(script) fun peer_to_peer_v2<TokenType: store>(account: signer, payee: address, amount: u128) {
-    if (!Account::exists_at(payee)) {
-        Account::create_account_with_address<TokenType>(payee);
-    };
-    Account::pay_from<TokenType>(&account, payee, amount)
-}
-
- - - -
- - - -## Function `batch_peer_to_peer` - -Batch transfer token to others. - - -
public(script) fun batch_peer_to_peer<TokenType: store>(account: signer, payeees: vector<address>, _payee_auth_keys: vector<vector<u8>>, amounts: vector<u128>)
-
- - - -
-Implementation - - -
public(script) fun batch_peer_to_peer<TokenType: store>(account: signer, payeees: vector<address>, _payee_auth_keys: vector<vector<u8>>, amounts: vector<u128>) {
-     batch_peer_to_peer_v2<TokenType>(account, payeees, amounts)
-}
-
- - - -
- - - -## Function `batch_peer_to_peer_v2` - -Batch transfer token to others. - - -
public(script) fun batch_peer_to_peer_v2<TokenType: store>(account: signer, payeees: vector<address>, amounts: vector<u128>)
-
- - - -
-Implementation - - -
public(script) fun batch_peer_to_peer_v2<TokenType: store>(account: signer, payeees: vector<address>, amounts: vector<u128>) {
-    let len = Vector::length(&payeees);
-    assert!(len == Vector::length(&amounts), ELENGTH_MISMATCH);
-    let i = 0;
-    while (i < len){
-        let payee = *Vector::borrow(&payeees, i);
-        if (!Account::exists_at(payee)) {
-            Account::create_account_with_address<TokenType>(payee);
-        };
-        let amount = *Vector::borrow(&amounts, i);
-        Account::pay_from<TokenType>(&account, payee, amount);
-        i = i + 1;
-    }
-}
-
- - - -
- - - -## Function `peer_to_peer_batch` - - - -
public(script) fun peer_to_peer_batch<TokenType: store>(_account: signer, _payeees: vector<u8>, _payee_auth_keys: vector<u8>, _amount: u128)
-
- - - -
-Implementation - - -
public(script) fun peer_to_peer_batch<TokenType: store>(_account: signer, _payeees: vector<u8>, _payee_auth_keys: vector<u8>, _amount: u128) {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- - - -## Function `peer_to_peer_with_metadata` - - - -
public(script) fun peer_to_peer_with_metadata<TokenType: store>(account: signer, payee: address, _payee_auth_key: vector<u8>, amount: u128, metadata: vector<u8>)
-
- - - -
-Implementation - - -
public(script) fun peer_to_peer_with_metadata<TokenType: store>(
-    account: signer,
-    payee: address,
-    _payee_auth_key: vector<u8>,
-    amount: u128,
-    metadata: vector<u8>,
-) {
-     peer_to_peer_with_metadata_v2<TokenType>(account, payee, amount, metadata)
-}
-
- - - -
- - - -## Function `peer_to_peer_with_metadata_v2` - - - -
public(script) fun peer_to_peer_with_metadata_v2<TokenType: store>(account: signer, payee: address, amount: u128, metadata: vector<u8>)
-
- - - -
-Implementation - - -
public(script) fun peer_to_peer_with_metadata_v2<TokenType: store>(
-        account: signer,
-        payee: address,
-        amount: u128,
-        metadata: vector<u8>,
-) {
-    if (!Account::exists_at(payee)) {
-        Account::create_account_with_address<TokenType>(payee);
-    };
-    Account::pay_from_with_metadata<TokenType>(&account,payee, amount, metadata)
-}
-
- - - -
diff --git a/release/v12/docs/Treasury.md b/release/v12/docs/Treasury.md deleted file mode 100644 index 09400578..00000000 --- a/release/v12/docs/Treasury.md +++ /dev/null @@ -1,1230 +0,0 @@ - - - -# Module `0x1::Treasury` - -The module for the Treasury of DAO, which can hold the token of DAO. - - -- [Resource `Treasury`](#0x1_Treasury_Treasury) -- [Resource `WithdrawCapability`](#0x1_Treasury_WithdrawCapability) -- [Resource `LinearWithdrawCapability`](#0x1_Treasury_LinearWithdrawCapability) -- [Struct `WithdrawEvent`](#0x1_Treasury_WithdrawEvent) -- [Struct `DepositEvent`](#0x1_Treasury_DepositEvent) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_Treasury_initialize) -- [Function `exists_at`](#0x1_Treasury_exists_at) -- [Function `balance`](#0x1_Treasury_balance) -- [Function `deposit`](#0x1_Treasury_deposit) -- [Function `do_withdraw`](#0x1_Treasury_do_withdraw) -- [Function `withdraw_with_capability`](#0x1_Treasury_withdraw_with_capability) -- [Function `withdraw`](#0x1_Treasury_withdraw) -- [Function `issue_linear_withdraw_capability`](#0x1_Treasury_issue_linear_withdraw_capability) -- [Function `withdraw_with_linear_capability`](#0x1_Treasury_withdraw_with_linear_capability) -- [Function `withdraw_by_linear`](#0x1_Treasury_withdraw_by_linear) -- [Function `split_linear_withdraw_cap`](#0x1_Treasury_split_linear_withdraw_cap) -- [Function `withdraw_amount_of_linear_cap`](#0x1_Treasury_withdraw_amount_of_linear_cap) -- [Function `is_empty_linear_withdraw_cap`](#0x1_Treasury_is_empty_linear_withdraw_cap) -- [Function `remove_withdraw_capability`](#0x1_Treasury_remove_withdraw_capability) -- [Function `add_withdraw_capability`](#0x1_Treasury_add_withdraw_capability) -- [Function `destroy_withdraw_capability`](#0x1_Treasury_destroy_withdraw_capability) -- [Function `add_linear_withdraw_capability`](#0x1_Treasury_add_linear_withdraw_capability) -- [Function `remove_linear_withdraw_capability`](#0x1_Treasury_remove_linear_withdraw_capability) -- [Function `destroy_linear_withdraw_capability`](#0x1_Treasury_destroy_linear_withdraw_capability) -- [Function `is_empty_linear_withdraw_capability`](#0x1_Treasury_is_empty_linear_withdraw_capability) -- [Function `get_linear_withdraw_capability_total`](#0x1_Treasury_get_linear_withdraw_capability_total) -- [Function `get_linear_withdraw_capability_withdraw`](#0x1_Treasury_get_linear_withdraw_capability_withdraw) -- [Function `get_linear_withdraw_capability_period`](#0x1_Treasury_get_linear_withdraw_capability_period) -- [Function `get_linear_withdraw_capability_start_time`](#0x1_Treasury_get_linear_withdraw_capability_start_time) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Event;
-use 0x1::Math;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::Token;
-
- - - - - -## Resource `Treasury` - - - -
struct Treasury<TokenT> has store, key
-
- - - -
-Fields - - -
-
-balance: Token::Token<TokenT> -
-
- -
-
-withdraw_events: Event::EventHandle<Treasury::WithdrawEvent> -
-
- event handle for treasury withdraw event -
-
-deposit_events: Event::EventHandle<Treasury::DepositEvent> -
-
- event handle for treasury deposit event -
-
- - -
- -
-Specification - - - -
- - - -## Resource `WithdrawCapability` - -A withdraw capability allows tokens of type TokenT to be withdraw from Treasury. - - -
struct WithdrawCapability<TokenT> has store, key
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `LinearWithdrawCapability` - -A linear time withdraw capability which can withdraw token from Treasury in a period by time-based linear release. - - -
struct LinearWithdrawCapability<TokenT> has store, key
-
- - - -
-Fields - - -
-
-total: u128 -
-
- The total amount of tokens that can be withdrawn by this capability -
-
-withdraw: u128 -
-
- The amount of tokens that have been withdrawn by this capability -
-
-start_time: u64 -
-
- The time-based linear release start time, timestamp in seconds. -
-
-period: u64 -
-
- The time-based linear release period in seconds -
-
- - -
- - - -## Struct `WithdrawEvent` - -Message for treasury withdraw event. - - -
struct WithdrawEvent has drop, store
-
- - - -
-Fields - - -
-
-amount: u128 -
-
- -
-
- - -
- - - -## Struct `DepositEvent` - -Message for treasury deposit event. - - -
struct DepositEvent has drop, store
-
- - - -
-Fields - - -
-
-amount: u128 -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_INVALID_PERIOD: u64 = 101;
-
- - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 104;
-
- - - - - - - -
const ERR_TOO_BIG_AMOUNT: u64 = 103;
-
- - - - - - - -
const ERR_TREASURY_NOT_EXIST: u64 = 105;
-
- - - - - - - -
const ERR_ZERO_AMOUNT: u64 = 102;
-
- - - - - -## Function `initialize` - -Init a Treasury for TokenT. Can only be called by token issuer. - - -
public fun initialize<TokenT: store>(signer: &signer, init_token: Token::Token<TokenT>): Treasury::WithdrawCapability<TokenT>
-
- - - -
-Implementation - - -
public fun initialize<TokenT: store>(signer: &signer, init_token: Token<TokenT>): WithdrawCapability<TokenT> {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    let treasure = Treasury {
-        balance: init_token,
-        withdraw_events: Event::new_event_handle<WithdrawEvent>(signer),
-        deposit_events: Event::new_event_handle<DepositEvent>(signer),
-    };
-    move_to(signer, treasure);
-    WithdrawCapability<TokenT>{}
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(signer) != Token::SPEC_TOKEN_TEST_ADDRESS();
-aborts_if exists<Treasury<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-ensures exists<Treasury<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-ensures result == WithdrawCapability<TokenT>{};
-
- - - -
- - - -## Function `exists_at` - -Check the Treasury of TokenT is exists. - - -
public fun exists_at<TokenT: store>(): bool
-
- - - -
-Implementation - - -
public fun exists_at<TokenT: store>(): bool {
-    let token_issuer = Token::token_address<TokenT>();
-    exists<Treasury<TokenT>>(token_issuer)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == exists<Treasury<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-
- - - -
- - - -## Function `balance` - -Get the balance of TokenT's Treasury -if the Treasury do not exists, return 0. - - -
public fun balance<TokenT: store>(): u128
-
- - - -
-Implementation - - -
public fun balance<TokenT:store>(): u128 acquires Treasury {
-    let token_issuer = Token::token_address<TokenT>();
-    if (!exists<Treasury<TokenT>>(token_issuer)) {
-        return 0
-    };
-    let treasury = borrow_global<Treasury<TokenT>>(token_issuer);
-    Token::value(&treasury.balance)
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures if (exists<Treasury<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS()))
-            result == spec_balance<TokenT>()
-        else
-            result == 0;
-
- - - -
- - - -## Function `deposit` - - - -
public fun deposit<TokenT: store>(token: Token::Token<TokenT>)
-
- - - -
-Implementation - - -
public fun deposit<TokenT: store>(token: Token<TokenT>) acquires Treasury {
-    assert!(exists_at<TokenT>(), Errors::not_published(ERR_TREASURY_NOT_EXIST));
-    let token_address = Token::token_address<TokenT>();
-    let treasury = borrow_global_mut<Treasury<TokenT>>(token_address);
-    let amount = Token::value(&token);
-    Event::emit_event(
-        &mut treasury.deposit_events,
-        DepositEvent { amount },
-    );
-    Token::deposit(&mut treasury.balance, token);
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Treasury<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-aborts_if spec_balance<TokenT>() + token.value > MAX_U128;
-ensures spec_balance<TokenT>() == old(spec_balance<TokenT>()) + token.value;
-
- - - -
- - - -## Function `do_withdraw` - - - -
fun do_withdraw<TokenT: store>(amount: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
fun do_withdraw<TokenT: store>(amount: u128): Token<TokenT> acquires Treasury {
-    assert!(amount > 0, Errors::invalid_argument(ERR_ZERO_AMOUNT));
-    assert!(exists_at<TokenT>(), Errors::not_published(ERR_TREASURY_NOT_EXIST));
-    let token_address = Token::token_address<TokenT>();
-    let treasury = borrow_global_mut<Treasury<TokenT>>(token_address);
-    assert!(amount <= Token::value(&treasury.balance) , Errors::invalid_argument(ERR_TOO_BIG_AMOUNT));
-    Event::emit_event(
-        &mut treasury.withdraw_events,
-        WithdrawEvent { amount },
-    );
-    Token::withdraw(&mut treasury.balance, amount)
-}
-
- - - -
- -
-Specification - - - -
include WithdrawSchema<TokenT>;
-
- - - - - - - -
schema WithdrawSchema<TokenT> {
-    amount: u64;
-    aborts_if amount <= 0;
-    aborts_if !exists<Treasury<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-    aborts_if spec_balance<TokenT>() < amount;
-    ensures spec_balance<TokenT>() ==
-        old(spec_balance<TokenT>()) - amount;
-}
-
- - - -
- - - -## Function `withdraw_with_capability` - -Withdraw tokens with given LinearWithdrawCapability. - - -
public fun withdraw_with_capability<TokenT: store>(_cap: &mut Treasury::WithdrawCapability<TokenT>, amount: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun withdraw_with_capability<TokenT: store>(
-    _cap: &mut WithdrawCapability<TokenT>,
-    amount: u128,
-): Token<TokenT> acquires Treasury {
-    do_withdraw(amount)
-}
-
- - - -
- -
-Specification - - - -
include WithdrawSchema<TokenT>;
-
- - - -
- - - -## Function `withdraw` - -Withdraw from TokenT's treasury, the signer must have WithdrawCapability - - -
public fun withdraw<TokenT: store>(signer: &signer, amount: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun withdraw<TokenT: store>(
-    signer: &signer,
-    amount: u128
-): Token<TokenT> acquires Treasury, WithdrawCapability {
-    let cap = borrow_global_mut<WithdrawCapability<TokenT>>(Signer::address_of(signer));
-    Self::withdraw_with_capability(cap, amount)
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<WithdrawCapability<TokenT>>(Signer::address_of(signer));
-include WithdrawSchema<TokenT>;
-
- - - -
- - - -## Function `issue_linear_withdraw_capability` - -Issue a LinearWithdrawCapability with given WithdrawCapability. - - -
public fun issue_linear_withdraw_capability<TokenT: store>(_capability: &mut Treasury::WithdrawCapability<TokenT>, amount: u128, period: u64): Treasury::LinearWithdrawCapability<TokenT>
-
- - - -
-Implementation - - -
public fun issue_linear_withdraw_capability<TokenT: store>(
-    _capability: &mut WithdrawCapability<TokenT>,
-    amount: u128,
-    period: u64
-): LinearWithdrawCapability<TokenT> {
-    assert!(period > 0, Errors::invalid_argument(ERR_INVALID_PERIOD));
-    assert!(amount > 0, Errors::invalid_argument(ERR_ZERO_AMOUNT));
-    let start_time = Timestamp::now_seconds();
-    LinearWithdrawCapability<TokenT> {
-        total: amount,
-        withdraw: 0,
-        start_time,
-        period,
-    }
-}
-
- - - -
- -
-Specification - - - -
aborts_if period == 0;
-aborts_if amount == 0;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(StarcoinFramework::CoreAddresses::GENESIS_ADDRESS());
-
- - - -
- - - -## Function `withdraw_with_linear_capability` - -Withdraw tokens with given LinearWithdrawCapability. - - -
public fun withdraw_with_linear_capability<TokenT: store>(cap: &mut Treasury::LinearWithdrawCapability<TokenT>): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun withdraw_with_linear_capability<TokenT: store>(
-    cap: &mut LinearWithdrawCapability<TokenT>,
-): Token<TokenT> acquires Treasury {
-    let amount = withdraw_amount_of_linear_cap(cap);
-    let token = do_withdraw(amount);
-    cap.withdraw = cap.withdraw + amount;
-    token
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial;
-
- - - -
- - - -## Function `withdraw_by_linear` - -Withdraw from TokenT's treasury, the signer must have LinearWithdrawCapability - - -
public fun withdraw_by_linear<TokenT: store>(signer: &signer): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun withdraw_by_linear<TokenT:store>(
-    signer: &signer,
-): Token<TokenT> acquires Treasury, LinearWithdrawCapability {
-    let cap = borrow_global_mut<LinearWithdrawCapability<TokenT>>(Signer::address_of(signer));
-    Self::withdraw_with_linear_capability(cap)
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial;
-aborts_if !exists<LinearWithdrawCapability<TokenT>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `split_linear_withdraw_cap` - -Split the given LinearWithdrawCapability. - - -
public fun split_linear_withdraw_cap<TokenT: store>(cap: &mut Treasury::LinearWithdrawCapability<TokenT>, amount: u128): (Token::Token<TokenT>, Treasury::LinearWithdrawCapability<TokenT>)
-
- - - -
-Implementation - - -
public fun split_linear_withdraw_cap<TokenT: store>(
-    cap: &mut LinearWithdrawCapability<TokenT>,
-    amount: u128,
-): (Token<TokenT>, LinearWithdrawCapability<TokenT>) acquires Treasury {
-    assert!(amount > 0, Errors::invalid_argument(ERR_ZERO_AMOUNT));
-    let token = Self::withdraw_with_linear_capability(cap);
-    assert!((cap.withdraw + amount) <= cap.total, Errors::invalid_argument(ERR_TOO_BIG_AMOUNT));
-    cap.total = cap.total - amount;
-    let start_time = Timestamp::now_seconds();
-    let new_period = cap.start_time + cap.period - start_time;
-    let new_key = LinearWithdrawCapability<TokenT> {
-        total: amount,
-        withdraw: 0,
-        start_time,
-        period: new_period
-    };
-    (token, new_key)
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial;
-ensures old(cap.total - cap.withdraw) ==
-    result_1.value + (result_2.total - result_2.withdraw) + (cap.total - cap.withdraw);
-
- - - -
- - - -## Function `withdraw_amount_of_linear_cap` - -Returns the amount of the LinearWithdrawCapability can mint now. - - -
public fun withdraw_amount_of_linear_cap<TokenT: store>(cap: &Treasury::LinearWithdrawCapability<TokenT>): u128
-
- - - -
-Implementation - - -
public fun withdraw_amount_of_linear_cap<TokenT: store>(cap: &LinearWithdrawCapability<TokenT>): u128 {
-    let now = Timestamp::now_seconds();
-    let elapsed_time = now - cap.start_time;
-    if (elapsed_time >= cap.period) {
-        cap.total - cap.withdraw
-    } else {
-        Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw
-    }
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(StarcoinFramework::CoreAddresses::GENESIS_ADDRESS());
-aborts_if Timestamp::spec_now_seconds() < cap.start_time;
-aborts_if Timestamp::spec_now_seconds() - cap.start_time >= cap.period && cap.total < cap.withdraw;
-aborts_if [abstract]
-    Timestamp::spec_now_seconds() - cap.start_time < cap.period && Math::spec_mul_div() < cap.withdraw;
-ensures [abstract] result <= cap.total - cap.withdraw;
-
- - - -
- - - -## Function `is_empty_linear_withdraw_cap` - -Check if the given LinearWithdrawCapability is empty. - - -
public fun is_empty_linear_withdraw_cap<TokenT: store>(key: &Treasury::LinearWithdrawCapability<TokenT>): bool
-
- - - -
-Implementation - - -
public fun is_empty_linear_withdraw_cap<TokenT:store>(key: &LinearWithdrawCapability<TokenT>) : bool {
-    key.total == key.withdraw
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == (key.total == key.withdraw);
-
- - - -
- - - -## Function `remove_withdraw_capability` - -Remove mint capability from signer. - - -
public fun remove_withdraw_capability<TokenT: store>(signer: &signer): Treasury::WithdrawCapability<TokenT>
-
- - - -
-Implementation - - -
public fun remove_withdraw_capability<TokenT: store>(signer: &signer): WithdrawCapability<TokenT>
-acquires WithdrawCapability {
-    move_from<WithdrawCapability<TokenT>>(Signer::address_of(signer))
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<WithdrawCapability<TokenT>>(Signer::address_of(signer));
-ensures !exists<WithdrawCapability<TokenT>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `add_withdraw_capability` - -Save mint capability to signer. - - -
public fun add_withdraw_capability<TokenT: store>(signer: &signer, cap: Treasury::WithdrawCapability<TokenT>)
-
- - - -
-Implementation - - -
public fun add_withdraw_capability<TokenT: store>(signer: &signer, cap: WithdrawCapability<TokenT>) {
-    move_to(signer, cap)
-}
-
- - - -
- -
-Specification - - - -
aborts_if exists<WithdrawCapability<TokenT>>(Signer::address_of(signer));
-ensures exists<WithdrawCapability<TokenT>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `destroy_withdraw_capability` - -Destroy the given mint capability. - - -
public fun destroy_withdraw_capability<TokenT: store>(cap: Treasury::WithdrawCapability<TokenT>)
-
- - - -
-Implementation - - -
public fun destroy_withdraw_capability<TokenT: store>(cap: WithdrawCapability<TokenT>) {
-    let WithdrawCapability<TokenT> {} = cap;
-}
-
- - - -
- -
-Specification - - - -
- - - -## Function `add_linear_withdraw_capability` - -Add LinearWithdrawCapability to signer, a address only can have one LinearWithdrawCapability - - -
public fun add_linear_withdraw_capability<TokenT: store>(signer: &signer, cap: Treasury::LinearWithdrawCapability<TokenT>)
-
- - - -
-Implementation - - -
public fun add_linear_withdraw_capability<TokenT: store>(signer: &signer, cap: LinearWithdrawCapability<TokenT>) {
-    move_to(signer, cap)
-}
-
- - - -
- -
-Specification - - - -
aborts_if exists<LinearWithdrawCapability<TokenT>>(Signer::address_of(signer));
-ensures exists<LinearWithdrawCapability<TokenT>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `remove_linear_withdraw_capability` - -Remove LinearWithdrawCapability from signer. - - -
public fun remove_linear_withdraw_capability<TokenT: store>(signer: &signer): Treasury::LinearWithdrawCapability<TokenT>
-
- - - -
-Implementation - - -
public fun remove_linear_withdraw_capability<TokenT: store>(signer: &signer): LinearWithdrawCapability<TokenT>
-acquires LinearWithdrawCapability {
-    move_from<LinearWithdrawCapability<TokenT>>(Signer::address_of(signer))
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<LinearWithdrawCapability<TokenT>>(Signer::address_of(signer));
-ensures !exists<LinearWithdrawCapability<TokenT>>(Signer::address_of(signer));
-
- - - -
- - - -## Function `destroy_linear_withdraw_capability` - -Destroy LinearWithdrawCapability. - - -
public fun destroy_linear_withdraw_capability<TokenT: store>(cap: Treasury::LinearWithdrawCapability<TokenT>)
-
- - - -
-Implementation - - -
public fun destroy_linear_withdraw_capability<TokenT: store>(cap: LinearWithdrawCapability<TokenT>) {
-    let LinearWithdrawCapability{ total: _, withdraw: _, start_time: _, period: _ } = cap;
-}
-
- - - -
- - - -## Function `is_empty_linear_withdraw_capability` - - - -
public fun is_empty_linear_withdraw_capability<TokenT: store>(cap: &Treasury::LinearWithdrawCapability<TokenT>): bool
-
- - - -
-Implementation - - -
public fun is_empty_linear_withdraw_capability<TokenT: store>(cap: &LinearWithdrawCapability<TokenT>): bool {
-    cap.total == cap.withdraw
-}
-
- - - -
- - - -## Function `get_linear_withdraw_capability_total` - -Get LinearWithdrawCapability total amount - - -
public fun get_linear_withdraw_capability_total<TokenT: store>(cap: &Treasury::LinearWithdrawCapability<TokenT>): u128
-
- - - -
-Implementation - - -
public fun get_linear_withdraw_capability_total<TokenT: store>(cap: &LinearWithdrawCapability<TokenT>): u128 {
-    cap.total
-}
-
- - - -
- - - -## Function `get_linear_withdraw_capability_withdraw` - -Get LinearWithdrawCapability withdraw amount - - -
public fun get_linear_withdraw_capability_withdraw<TokenT: store>(cap: &Treasury::LinearWithdrawCapability<TokenT>): u128
-
- - - -
-Implementation - - -
public fun get_linear_withdraw_capability_withdraw<TokenT: store>(cap: &LinearWithdrawCapability<TokenT>): u128 {
-    cap.withdraw
-}
-
- - - -
- - - -## Function `get_linear_withdraw_capability_period` - -Get LinearWithdrawCapability period in seconds - - -
public fun get_linear_withdraw_capability_period<TokenT: store>(cap: &Treasury::LinearWithdrawCapability<TokenT>): u64
-
- - - -
-Implementation - - -
public fun get_linear_withdraw_capability_period<TokenT: store>(cap: &LinearWithdrawCapability<TokenT>): u64 {
-    cap.period
-}
-
- - - -
- - - -## Function `get_linear_withdraw_capability_start_time` - -Get LinearWithdrawCapability start_time in seconds - - -
public fun get_linear_withdraw_capability_start_time<TokenT: store>(cap: &Treasury::LinearWithdrawCapability<TokenT>): u64
-
- - - -
-Implementation - - -
public fun get_linear_withdraw_capability_start_time<TokenT: store>(cap: &LinearWithdrawCapability<TokenT>): u64 {
-    cap.start_time
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
- - - - - - - -
fun spec_balance<TokenType>(): num {
-   global<Treasury<TokenType>>(Token::SPEC_TOKEN_TEST_ADDRESS()).balance.value
-}
-
diff --git a/release/v12/docs/TreasuryPlugin.md b/release/v12/docs/TreasuryPlugin.md deleted file mode 100644 index 8821d43a..00000000 --- a/release/v12/docs/TreasuryPlugin.md +++ /dev/null @@ -1,560 +0,0 @@ - - - -# Module `0x1::TreasuryPlugin` - - - -- [Struct `TreasuryPlugin`](#0x1_TreasuryPlugin_TreasuryPlugin) -- [Resource `WithdrawCapabilityHolder`](#0x1_TreasuryPlugin_WithdrawCapabilityHolder) -- [Struct `QuorumScale`](#0x1_TreasuryPlugin_QuorumScale) -- [Struct `WithdrawTokenAction`](#0x1_TreasuryPlugin_WithdrawTokenAction) -- [Constants](#@Constants_0) -- [Function `initialize`](#0x1_TreasuryPlugin_initialize) -- [Function `delegate_capability`](#0x1_TreasuryPlugin_delegate_capability) -- [Function `required_caps`](#0x1_TreasuryPlugin_required_caps) -- [Function `withdraw_limitation`](#0x1_TreasuryPlugin_withdraw_limitation) -- [Function `create_withdraw_proposal`](#0x1_TreasuryPlugin_create_withdraw_proposal) -- [Function `create_withdraw_proposal_entry`](#0x1_TreasuryPlugin_create_withdraw_proposal_entry) -- [Function `execute_withdraw_proposal`](#0x1_TreasuryPlugin_execute_withdraw_proposal) -- [Function `execute_withdraw_proposal_entry`](#0x1_TreasuryPlugin_execute_withdraw_proposal_entry) -- [Function `withdraw_for_block_reward`](#0x1_TreasuryPlugin_withdraw_for_block_reward) -- [Function `set_scale_factor`](#0x1_TreasuryPlugin_set_scale_factor) -- [Function `set_scale_factor_inner`](#0x1_TreasuryPlugin_set_scale_factor_inner) - - -
use 0x1::CoreAddresses;
-use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::Errors;
-use 0x1::Option;
-use 0x1::Signer;
-use 0x1::Token;
-use 0x1::Treasury;
-use 0x1::Vector;
-
- - - - - -## Struct `TreasuryPlugin` - - - -
struct TreasuryPlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `WithdrawCapabilityHolder` - -A wrapper of Token MintCapability. - - -
struct WithdrawCapabilityHolder<TokenT> has key
-
- - - -
-Fields - - -
-
-cap: Treasury::WithdrawCapability<TokenT> -
-
- -
-
- - -
- - - -## Struct `QuorumScale` - -Scale up quorum_votes for withdraw proposal. -scale must be in [0, 100]. -The final quorum_votes = (1.0 + scale / 100) * base_quorum_votes - - -
struct QuorumScale has copy, drop, store
-
- - - -
-Fields - - -
-
-scale: u8 -
-
- -
-
- - -
- - - -## Struct `WithdrawTokenAction` - -WithdrawToken request. - - -
struct WithdrawTokenAction<TokenT> has copy, drop, store
-
- - - -
-Fields - - -
-
-receiver: address -
-
- the receiver of withdraw tokens. -
-
-amount: u128 -
-
- how many tokens to mint. -
-
-period: u64 -
-
- How long in milliseconds does it take for the token to be released -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 101;
-
- - - - - - - -
const ERR_CAPABILITY_NOT_EXIST: u64 = 104;
-
- - - - - - - -
const ERR_INVALID_SCALE_FACTOR: u64 = 105;
-
- - - - - -Only receiver can execute treasury withdraw proposal - - -
const ERR_NOT_RECEIVER: u64 = 102;
-
- - - - - -The withdraw amount of propose is too many. - - -
const ERR_TOO_MANY_WITHDRAW_AMOUNT: u64 = 103;
-
- - - - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = TreasuryPlugin {};
-
-    DAOPluginMarketplace::register_plugin<TreasuryPlugin>(
-        &witness,
-        b"0x1::TreasuryPlugin",
-        b"The plugin for withdraw token from Treasury.",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<TreasuryPlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://treasury-plugin",
-    );
-}
-
- - - -
- - - -## Function `delegate_capability` - -Delegate Treasury::WithdrawCapability to DAO -Should be called by token issuer. - - -
public fun delegate_capability<TokenT: store>(sender: &signer, cap: Treasury::WithdrawCapability<TokenT>)
-
- - - -
-Implementation - - -
public fun delegate_capability<TokenT: store>(sender: &signer, cap: Treasury::WithdrawCapability<TokenT>) {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    move_to(sender, WithdrawCapabilityHolder<TokenT> { cap });
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps(): vector<CapType> {
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `withdraw_limitation` - - - -
fun withdraw_limitation<DAOT: store, TokenT: store>(): u128
-
- - - -
-Implementation - - -
fun withdraw_limitation<DAOT: store, TokenT: store>(): u128 {
-    let market_cap = Token::market_cap<TokenT>();
-    let balance_in_treasury = Treasury::balance<TokenT>();
-    let supply = market_cap - balance_in_treasury;
-    let rate = DAOSpace::voting_quorum_rate<DAOT>();
-    let rate = (rate as u128);
-    supply * rate / 100
-}
-
- - - -
- - - -## Function `create_withdraw_proposal` - - - -
public fun create_withdraw_proposal<DAOT: store, TokenT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, receiver: address, amount: u128, period: u64, action_delay: u64)
-
- - - -
-Implementation - - -
public fun create_withdraw_proposal<DAOT: store, TokenT: store>(
-    sender: &signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    receiver: address,
-    amount: u128,
-    period: u64,
-    action_delay: u64)
-{
-    let limit = withdraw_limitation<DAOT, TokenT>();
-    assert!(amount <= limit,  Errors::invalid_argument(ERR_TOO_MANY_WITHDRAW_AMOUNT));
-    let witness = TreasuryPlugin {};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, TreasuryPlugin>(&witness);
-    let action = WithdrawTokenAction<TokenT> {
-        receiver,
-        amount,
-        period,
-    };
-
-    if (!DAOSpace::exists_custom_config<DAOT, QuorumScale>()) {
-        set_scale_factor_inner<DAOT>(0u8);
-    };
-    let scale = DAOSpace::get_custom_config<DAOT, QuorumScale>().scale;
-    DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::some(scale));
-}
-
- - - -
- - - -## Function `create_withdraw_proposal_entry` - - - -
public(script) fun create_withdraw_proposal_entry<DAOT: store, TokenT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, receiver: address, amount: u128, period: u64, action_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun create_withdraw_proposal_entry<DAOT: store, TokenT: store>(
-    sender: signer,
-    title:vector<u8>,
-    introduction:vector<u8>,
-    extend: vector<u8>,
-    receiver: address,
-    amount: u128,
-    period: u64,
-    action_delay: u64)
-{
-    create_withdraw_proposal<DAOT, TokenT>(&sender, title, introduction, extend, receiver, amount, period, action_delay);
-}
-
- - - -
- - - -## Function `execute_withdraw_proposal` - - - -
public fun execute_withdraw_proposal<DAOT: store, TokenT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_withdraw_proposal<DAOT: store, TokenT: store>(sender: &signer, proposal_id: u64) acquires WithdrawCapabilityHolder {
-    let witness = TreasuryPlugin {};
-    let proposal_cap = DAOSpace::acquire_proposal_cap<DAOT, TreasuryPlugin>(&witness);
-    let WithdrawTokenAction<TokenT> { receiver, amount, period } =
-        DAOSpace::execute_proposal<DAOT, TreasuryPlugin, WithdrawTokenAction<TokenT>>(&proposal_cap, sender, proposal_id);
-    assert!(receiver == Signer::address_of(sender), Errors::not_published(ERR_NOT_RECEIVER));
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(exists<WithdrawCapabilityHolder<TokenT>>(token_issuer), Errors::not_published(ERR_CAPABILITY_NOT_EXIST));
-    let cap = borrow_global_mut<WithdrawCapabilityHolder<TokenT>>(token_issuer);
-    let linear_cap = Treasury::issue_linear_withdraw_capability<TokenT>(&mut cap.cap, amount, period);
-    Treasury::add_linear_withdraw_capability(sender, linear_cap);
-}
-
- - - -
- - - -## Function `execute_withdraw_proposal_entry` - - - -
public(script) fun execute_withdraw_proposal_entry<DAOT: store, TokenT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_withdraw_proposal_entry<DAOT: store, TokenT: store>(sender: signer, proposal_id: u64) acquires WithdrawCapabilityHolder {
-    execute_withdraw_proposal<DAOT, TokenT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `withdraw_for_block_reward` - -Provider a port for get block reward STC from Treasury, only genesis account can invoke this function. -The TreasuryWithdrawCapability is locked in TreasuryWithdrawDaoProposal, and only can withdraw by DAO proposal. -This approach is not graceful, but restricts the operation to genesis accounts only, so there are no security issues either. - - -
public fun withdraw_for_block_reward<TokenT: store>(signer: &signer, reward: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun withdraw_for_block_reward<TokenT: store>(signer: &signer, reward: u128): Token<TokenT>
-acquires WithdrawCapabilityHolder  {
-    CoreAddresses::assert_genesis_address(signer);
-    let cap = borrow_global_mut<WithdrawCapabilityHolder<TokenT>>(Signer::address_of(signer));
-    Treasury::withdraw_with_capability(&mut cap.cap, reward)
-}
-
- - - -
- - - -## Function `set_scale_factor` - - - -
public fun set_scale_factor<DAOT: store>(scale: u8, _witness: &DAOT)
-
- - - -
-Implementation - - -
public fun set_scale_factor<DAOT: store>(scale: u8, _witness: &DAOT) {
-    assert!(
-        scale >= 0 && scale <= 100,
-        Errors::invalid_argument(ERR_INVALID_SCALE_FACTOR),
-    );
-    set_scale_factor_inner<DAOT>(scale);
-}
-
- - - -
- - - -## Function `set_scale_factor_inner` - - - -
fun set_scale_factor_inner<DAOT: store>(scale: u8)
-
- - - -
-Implementation - - -
fun set_scale_factor_inner<DAOT: store>(scale: u8) {
-    let plugin = TreasuryPlugin {};
-    let cap = DAOSpace::acquire_modify_config_cap<DAOT, TreasuryPlugin>(&plugin);
-    DAOSpace::set_custom_config<DAOT, TreasuryPlugin, QuorumScale>(&mut cap, QuorumScale { scale });
-}
-
- - - -
diff --git a/release/v12/docs/TreasuryScripts.md b/release/v12/docs/TreasuryScripts.md deleted file mode 100644 index 2559cc21..00000000 --- a/release/v12/docs/TreasuryScripts.md +++ /dev/null @@ -1,204 +0,0 @@ - - - -# Module `0x1::TreasuryScripts` - - - -- [Function `withdraw_and_split_lt_withdraw_cap`](#0x1_TreasuryScripts_withdraw_and_split_lt_withdraw_cap) -- [Function `withdraw_token_with_linear_withdraw_capability`](#0x1_TreasuryScripts_withdraw_token_with_linear_withdraw_capability) -- [Function `propose_withdraw`](#0x1_TreasuryScripts_propose_withdraw) -- [Function `execute_withdraw_proposal`](#0x1_TreasuryScripts_execute_withdraw_proposal) - - -
use 0x1::Account;
-use 0x1::Offer;
-use 0x1::Token;
-use 0x1::Treasury;
-use 0x1::TreasuryWithdrawDaoProposal;
-
- - - - - -## Function `withdraw_and_split_lt_withdraw_cap` - - - -
public(script) fun withdraw_and_split_lt_withdraw_cap<TokenT: store>(signer: signer, for_address: address, amount: u128, lock_period: u64)
-
- - - -
-Implementation - - -
public(script) fun withdraw_and_split_lt_withdraw_cap<TokenT: store>(
-    signer: signer,
-    for_address: address,
-    amount: u128,
-    lock_period: u64,
-) {
-    // 1. take cap: LinearWithdrawCapability<TokenT>
-    let cap = Treasury::remove_linear_withdraw_capability<TokenT>(&signer);
-
-    // 2. withdraw token and split
-    let (tokens, new_cap) = Treasury::split_linear_withdraw_cap(&mut cap, amount);
-
-    // 3. deposit
-    Account::deposit_to_self(&signer, tokens);
-
-    // 4. put or destroy key
-    if (Treasury::is_empty_linear_withdraw_capability(&cap)) {
-        Treasury::destroy_linear_withdraw_capability(cap);
-    } else {
-        Treasury::add_linear_withdraw_capability(&signer, cap);
-    };
-
-    // 5. offer
-    Offer::create(&signer, new_cap, for_address, lock_period);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `withdraw_token_with_linear_withdraw_capability` - - - -
public(script) fun withdraw_token_with_linear_withdraw_capability<TokenT: store>(signer: signer)
-
- - - -
-Implementation - - -
public(script) fun withdraw_token_with_linear_withdraw_capability<TokenT: store>(
-    signer: signer,
-) {
-    // 1. take cap
-    let cap = Treasury::remove_linear_withdraw_capability<TokenT>(&signer);
-
-    // 2. withdraw token
-    let tokens = Treasury::withdraw_with_linear_capability(&mut cap);
-
-    // 3. deposit
-    Account::deposit_to_self(&signer, tokens);
-
-    // 4. put or destroy key
-    if (Treasury::is_empty_linear_withdraw_capability(&cap)) {
-        Treasury::destroy_linear_withdraw_capability(cap);
-    } else {
-        Treasury::add_linear_withdraw_capability(&signer, cap);
-    };
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `propose_withdraw` - - - -
public(script) fun propose_withdraw<TokenT: copy, drop, store>(signer: signer, receiver: address, amount: u128, period: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public(script) fun propose_withdraw<TokenT: copy + drop + store>(signer: signer, receiver: address, amount: u128, period: u64, exec_delay: u64){
-    TreasuryWithdrawDaoProposal::propose_withdraw<TokenT>(&signer, receiver, amount, period, exec_delay)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `execute_withdraw_proposal` - - - -
public(script) fun execute_withdraw_proposal<TokenT: copy, drop, store>(signer: signer, proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public(script) fun execute_withdraw_proposal<TokenT:copy + drop + store>(signer: signer, proposer_address: address,
-                                                                   proposal_id: u64,){
-    TreasuryWithdrawDaoProposal::execute_withdraw_proposal<TokenT>(&signer, proposer_address, proposal_id);
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
diff --git a/release/v12/docs/TreasuryWithdrawDaoProposal.md b/release/v12/docs/TreasuryWithdrawDaoProposal.md deleted file mode 100644 index 2854c0c7..00000000 --- a/release/v12/docs/TreasuryWithdrawDaoProposal.md +++ /dev/null @@ -1,361 +0,0 @@ - - - -# Module `0x1::TreasuryWithdrawDaoProposal` - -TreasuryWithdrawDaoProposal is a dao proposal for withdraw Token from Treasury. - - -- [Resource `WrappedWithdrawCapability`](#0x1_TreasuryWithdrawDaoProposal_WrappedWithdrawCapability) -- [Struct `WithdrawToken`](#0x1_TreasuryWithdrawDaoProposal_WithdrawToken) -- [Constants](#@Constants_0) -- [Function `plugin`](#0x1_TreasuryWithdrawDaoProposal_plugin) -- [Function `takeout_withdraw_capability`](#0x1_TreasuryWithdrawDaoProposal_takeout_withdraw_capability) -- [Function `propose_withdraw`](#0x1_TreasuryWithdrawDaoProposal_propose_withdraw) -- [Function `execute_withdraw_proposal`](#0x1_TreasuryWithdrawDaoProposal_execute_withdraw_proposal) -- [Function `withdraw_for_block_reward`](#0x1_TreasuryWithdrawDaoProposal_withdraw_for_block_reward) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::CoreAddresses;
-use 0x1::Dao;
-use 0x1::Errors;
-use 0x1::Signer;
-use 0x1::Token;
-use 0x1::Treasury;
-
- - - - - -## Resource `WrappedWithdrawCapability` - -A wrapper of Token MintCapability. - - -
struct WrappedWithdrawCapability<TokenT> has key
-
- - - -
-Fields - - -
-
-cap: Treasury::WithdrawCapability<TokenT> -
-
- -
-
- - -
- - - -## Struct `WithdrawToken` - -WithdrawToken request. - - -
struct WithdrawToken has copy, drop, store
-
- - - -
-Fields - - -
-
-receiver: address -
-
- the receiver of withdraw tokens. -
-
-amount: u128 -
-
- how many tokens to mint. -
-
-period: u64 -
-
- How long in milliseconds does it take for the token to be released -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 101;
-
- - - - - - - -
const ERR_CAPABILITY_NOT_EXIST: u64 = 104;
-
- - - - - -The withdraw amount of propose is too many. - - -
const ERR_TOO_MANY_WITHDRAW_AMOUNT: u64 = 103;
-
- - - - - -Only receiver can execute TreasuryWithdrawDaoProposal - - -
const ERR_NEED_RECEIVER_TO_EXECUTE: u64 = 102;
-
- - - - - -## Function `plugin` - -Plugin method of the module. -Should be called by token issuer. - - -
public fun plugin<TokenT: store>(signer: &signer, cap: Treasury::WithdrawCapability<TokenT>)
-
- - - -
-Implementation - - -
public fun plugin<TokenT: store>(signer: &signer, cap: Treasury::WithdrawCapability<TokenT>) {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    move_to(signer, WrappedWithdrawCapability<TokenT> { cap: cap });
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-let sender = Signer::address_of(signer);
-aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS();
-aborts_if !exists<Treasury::WithdrawCapability<TokenT>>(sender);
-aborts_if exists<WrappedWithdrawCapability<TokenT>>(sender);
-ensures !exists<Treasury::WithdrawCapability<TokenT>>(sender);
-ensures exists<WrappedWithdrawCapability<TokenT>>(sender);
-
- - - -
- - - -## Function `takeout_withdraw_capability` - -withdraw Treasury::WithdrawCapability - - -
public fun takeout_withdraw_capability<TokenT: store>(sender: &signer): Treasury::WithdrawCapability<TokenT>
-
- - - -
-Implementation - - -
public fun takeout_withdraw_capability<TokenT: store>(sender: &signer): Treasury::WithdrawCapability<TokenT>
-acquires WrappedWithdrawCapability {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-
-    assert!(exists<WrappedWithdrawCapability<TokenT>>(Signer::address_of(sender)), Errors::not_published(ERR_CAPABILITY_NOT_EXIST));
-    let WrappedWithdrawCapability<TokenT> { cap } = move_from<WrappedWithdrawCapability<TokenT>>(Signer::address_of(sender));
-    cap
-}
-
- - - -
- - - -## Function `propose_withdraw` - -Entrypoint for the proposal. - - -
public fun propose_withdraw<TokenT: copy, drop, store>(signer: &signer, receiver: address, amount: u128, period: u64, exec_delay: u64)
-
- - - -
-Implementation - - -
public fun propose_withdraw<TokenT: copy + drop + store>(signer: &signer, receiver: address, amount: u128, period: u64, exec_delay: u64) {
-    let quorum_votes = Dao::quorum_votes<TokenT>();
-    assert!(amount <= quorum_votes,  Errors::invalid_argument(ERR_TOO_MANY_WITHDRAW_AMOUNT));
-    Dao::propose<TokenT, WithdrawToken>(
-        signer,
-        WithdrawToken { receiver, amount, period },
-        exec_delay,
-    );
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-let quorum_votes = Dao::spec_quorum_votes<TokenT>();
-aborts_if amount > quorum_votes;
-include Dao::AbortIfDaoConfigNotExist<TokenT>;
-include Dao::AbortIfDaoInfoNotExist<TokenT>;
-aborts_if !exists<Timestamp::CurrentTimeMilliseconds>(CoreAddresses::GENESIS_ADDRESS());
-aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config<TokenT>().min_action_delay;
-include Dao::CheckQuorumVotes<TokenT>;
-let sender = Signer::address_of(signer);
-aborts_if exists<Dao::Proposal<TokenT, WithdrawToken>>(sender);
-
- - - -
- - - -## Function `execute_withdraw_proposal` - -Once the proposal is agreed, anyone can call the method to make the proposal happen. - - -
public fun execute_withdraw_proposal<TokenT: copy, drop, store>(signer: &signer, proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_withdraw_proposal<TokenT: copy + drop + store>(
-    signer: &signer,
-    proposer_address: address,
-    proposal_id: u64,
-) acquires WrappedWithdrawCapability {
-    let WithdrawToken { receiver, amount, period } = Dao::extract_proposal_action<TokenT, WithdrawToken>(
-        proposer_address,
-        proposal_id,
-    );
-    assert!(receiver == Signer::address_of(signer), Errors::requires_address(ERR_NEED_RECEIVER_TO_EXECUTE));
-    let cap = borrow_global_mut<WrappedWithdrawCapability<TokenT>>(Token::token_address<TokenT>());
-    let linear_cap = Treasury::issue_linear_withdraw_capability<TokenT>(&mut cap.cap, amount, period);
-    Treasury::add_linear_withdraw_capability(signer, linear_cap);
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = true;
-let expected_states = vec<u8>(6);
-include Dao::CheckProposalStates<TokenT, WithdrawToken>{expected_states};
-let proposal = global<Dao::Proposal<TokenT, WithdrawToken>>(proposer_address);
-aborts_if Option::is_none(proposal.action);
-aborts_if !exists<WrappedWithdrawCapability<TokenT>>(Token::SPEC_TOKEN_TEST_ADDRESS());
-
- - - -
- - - -## Function `withdraw_for_block_reward` - -Provider a port for get block reward STC from Treasury, only genesis account can invoke this function. -The TreasuryWithdrawCapability is locked in TreasuryWithdrawDaoProposal, and only can withdraw by DAO proposal. -This approach is not graceful, but restricts the operation to genesis accounts only, so there are no security issues either. - - -
public fun withdraw_for_block_reward<TokenT: store>(signer: &signer, reward: u128): Token::Token<TokenT>
-
- - - -
-Implementation - - -
public fun withdraw_for_block_reward<TokenT: store>(signer: &signer, reward: u128):Token<TokenT> acquires WrappedWithdrawCapability  {
-    CoreAddresses::assert_genesis_address(signer);
-    let cap = borrow_global_mut<WrappedWithdrawCapability<TokenT>>(Signer::address_of(signer));
-    Treasury::withdraw_with_capability(&mut cap.cap, reward)
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-pragma aborts_if_is_partial;
-
diff --git a/release/v12/docs/TypeInfo.md b/release/v12/docs/TypeInfo.md deleted file mode 100644 index 48646ddd..00000000 --- a/release/v12/docs/TypeInfo.md +++ /dev/null @@ -1,158 +0,0 @@ - - - -# Module `0x1::TypeInfo` - - - -- [Struct `TypeInfo`](#0x1_TypeInfo_TypeInfo) -- [Function `account_address`](#0x1_TypeInfo_account_address) -- [Function `module_name`](#0x1_TypeInfo_module_name) -- [Function `struct_name`](#0x1_TypeInfo_struct_name) -- [Function `type_of`](#0x1_TypeInfo_type_of) - - -
use 0x1::Token;
-
- - - - - -## Struct `TypeInfo` - - - -
struct TypeInfo has copy, drop, store
-
- - - -
-Fields - - -
-
-account_address: address -
-
- -
-
-module_name: vector<u8> -
-
- -
-
-struct_name: vector<u8> -
-
- -
-
- - -
- - - -## Function `account_address` - - - -
public fun account_address(type_info: &TypeInfo::TypeInfo): address
-
- - - -
-Implementation - - -
public fun account_address(type_info: &TypeInfo):address{
-    type_info.account_address
-}
-
- - - -
- - - -## Function `module_name` - - - -
public fun module_name(type_info: &TypeInfo::TypeInfo): vector<u8>
-
- - - -
-Implementation - - -
public fun module_name(type_info: &TypeInfo):vector<u8>{
-    *&type_info.module_name
-}
-
- - - -
- - - -## Function `struct_name` - - - -
public fun struct_name(type_info: &TypeInfo::TypeInfo): vector<u8>
-
- - - -
-Implementation - - -
public fun struct_name(type_info: &TypeInfo):vector<u8>{
-    *&type_info.struct_name
-}
-
- - - -
- - - -## Function `type_of` - - - -
public fun type_of<T>(): TypeInfo::TypeInfo
-
- - - -
-Implementation - - -
public fun type_of<T>():TypeInfo{
-    let (account_address, module_name, struct_name) = Token::type_of<T>();
-    TypeInfo {
-        account_address,
-        module_name,
-        struct_name
-    }
-}
-
- - - -
diff --git a/release/v12/docs/U256.md b/release/v12/docs/U256.md deleted file mode 100644 index 4abb01ba..00000000 --- a/release/v12/docs/U256.md +++ /dev/null @@ -1,944 +0,0 @@ - - - -# Module `0x1::U256` - -Implementation u256. - - -- [Struct `U256`](#0x1_U256_U256) -- [Constants](#@Constants_0) -- [Function `zero`](#0x1_U256_zero) -- [Function `one`](#0x1_U256_one) -- [Function `from_u64`](#0x1_U256_from_u64) -- [Function `from_u128`](#0x1_U256_from_u128) -- [Function `from_big_endian`](#0x1_U256_from_big_endian) -- [Function `from_little_endian`](#0x1_U256_from_little_endian) -- [Function `to_u128`](#0x1_U256_to_u128) -- [Function `compare`](#0x1_U256_compare) -- [Function `add`](#0x1_U256_add) -- [Function `sub`](#0x1_U256_sub) -- [Function `mul`](#0x1_U256_mul) -- [Function `div`](#0x1_U256_div) -- [Function `rem`](#0x1_U256_rem) -- [Function `pow`](#0x1_U256_pow) -- [Function `from_bytes`](#0x1_U256_from_bytes) -- [Function `native_add`](#0x1_U256_native_add) -- [Function `native_sub`](#0x1_U256_native_sub) -- [Function `native_mul`](#0x1_U256_native_mul) -- [Function `native_div`](#0x1_U256_native_div) -- [Function `native_rem`](#0x1_U256_native_rem) -- [Function `native_pow`](#0x1_U256_native_pow) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Vector;
-
- - - - - -## Struct `U256` - -use vector to represent data. -so that we can use buildin vector ops later to construct U256. -vector should always has two elements. - - -
struct U256 has copy, drop, store
-
- - - -
-Fields - - -
-
-bits: vector<u64> -
-
- little endian representation -
-
- - -
- -
-Specification - - - -
invariant len(bits) == 4;
-
- - - - - - - -
fun value_of_U256(a: U256): num {
-   a.bits[0] +
-   a.bits[1] * P64 +
-   a.bits[2] * P64 * P64 +
-   a.bits[3] * P64 * P64 * P64
-}
-
- - - -
- - - -## Constants - - - - - - -
const P32: u64 = 4294967296;
-
- - - - - - - -
const P64: u128 = 18446744073709551616;
-
- - - - - - - -
const EQUAL: u8 = 0;
-
- - - - - - - -
const GREATER_THAN: u8 = 2;
-
- - - - - - - -
const LESS_THAN: u8 = 1;
-
- - - - - - - -
const ERR_INVALID_LENGTH: u64 = 100;
-
- - - - - - - -
const ERR_OVERFLOW: u64 = 200;
-
- - - - - - - -
const WORD: u8 = 4;
-
- - - - - -## Function `zero` - - - -
public fun zero(): U256::U256
-
- - - -
-Implementation - - -
public fun zero(): U256 {
-    from_u128(0u128)
-}
-
- - - -
- - - -## Function `one` - - - -
public fun one(): U256::U256
-
- - - -
-Implementation - - -
public fun one(): U256 {
-    from_u128(1u128)
-}
-
- - - -
- - - -## Function `from_u64` - - - -
public fun from_u64(v: u64): U256::U256
-
- - - -
-Implementation - - -
public fun from_u64(v: u64): U256 {
-    from_u128((v as u128))
-}
-
- - - -
- - - -## Function `from_u128` - - - -
public fun from_u128(v: u128): U256::U256
-
- - - -
-Implementation - - -
public fun from_u128(v: u128): U256 {
-    let low = ((v & 0xffffffffffffffff) as u64);
-    let high = ((v >> 64) as u64);
-    let bits = Vector::singleton(low);
-    Vector::push_back(&mut bits, high);
-    Vector::push_back(&mut bits, 0u64);
-    Vector::push_back(&mut bits, 0u64);
-    U256 { bits }
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-ensures value_of_U256(result) == v;
-
- - - -
- - - -## Function `from_big_endian` - - - -
public fun from_big_endian(data: vector<u8>): U256::U256
-
- - - -
-Implementation - - -
public fun from_big_endian(data: vector<u8>): U256 {
-    // TODO: define error code.
-    assert!(Vector::length(&data) <= 32, Errors::invalid_argument(ERR_INVALID_LENGTH));
-    from_bytes(&data, true)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `from_little_endian` - - - -
public fun from_little_endian(data: vector<u8>): U256::U256
-
- - - -
-Implementation - - -
public fun from_little_endian(data: vector<u8>): U256 {
-    // TODO: define error code.
-    assert!(Vector::length(&data) <= 32, Errors::invalid_argument(ERR_INVALID_LENGTH));
-    from_bytes(&data, false)
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-
- - - -
- - - -## Function `to_u128` - - - -
public fun to_u128(v: &U256::U256): u128
-
- - - -
-Implementation - - -
public fun to_u128(v: &U256): u128 {
-    assert!(*Vector::borrow(&v.bits, 3) == 0, Errors::invalid_state(ERR_OVERFLOW));
-    assert!(*Vector::borrow(&v.bits, 2) == 0, Errors::invalid_state(ERR_OVERFLOW));
-    ((*Vector::borrow(&v.bits, 1) as u128) << 64) | (*Vector::borrow(&v.bits, 0) as u128)
-}
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if value_of_U256(v) >= P64 * P64;
-ensures value_of_U256(v) == result;
-
- - - -
- - - -## Function `compare` - - - -
public fun compare(a: &U256::U256, b: &U256::U256): u8
-
- - - -
-Implementation - - -
public fun compare(a: &U256, b: &U256): u8 {
-    let i = (WORD as u64);
-    while (i > 0) {
-        i = i - 1;
-        let a_bits = *Vector::borrow(&a.bits, i);
-        let b_bits = *Vector::borrow(&b.bits, i);
-        if (a_bits != b_bits) {
-            if (a_bits < b_bits) {
-                return LESS_THAN
-            } else {
-                return GREATER_THAN
-            }
-        }
-    };
-    return EQUAL
-}
-
- - - -
- - - -## Function `add` - - - -
public fun add(a: U256::U256, b: U256::U256): U256::U256
-
- - - -
-Implementation - - -
public fun add(a: U256, b: U256): U256 {
-    native_add(&mut a, &b);
-    a
-}
-
- - - -
- -
-Specification - - - -
aborts_if value_of_U256(a) + value_of_U256(b) >= P64 * P64 * P64 * P64;
-ensures value_of_U256(result) == value_of_U256(a) + value_of_U256(b);
-
- - - -
- - - -## Function `sub` - - - -
public fun sub(a: U256::U256, b: U256::U256): U256::U256
-
- - - -
-Implementation - - -
public fun sub(a: U256, b: U256): U256 {
-    native_sub(&mut a, &b);
-    a
-}
-
- - - -
- -
-Specification - - - -
aborts_if value_of_U256(a) < value_of_U256(b);
-ensures value_of_U256(result) == value_of_U256(a) - value_of_U256(b);
-
- - - -
- - - -## Function `mul` - - - -
public fun mul(a: U256::U256, b: U256::U256): U256::U256
-
- - - -
-Implementation - - -
public fun mul(a: U256, b: U256): U256 {
-    native_mul(&mut a, &b);
-    a
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-pragma timeout = 200;
-aborts_if value_of_U256(a) * value_of_U256(b) >= P64 * P64 * P64 * P64;
-ensures value_of_U256(result) == value_of_U256(a) * value_of_U256(b);
-
- - - -
- - - -## Function `div` - - - -
public fun div(a: U256::U256, b: U256::U256): U256::U256
-
- - - -
-Implementation - - -
public fun div(a: U256, b: U256): U256 {
-    native_div(&mut a, &b);
-    a
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-pragma timeout = 160;
-aborts_if value_of_U256(b) == 0;
-ensures value_of_U256(result) == value_of_U256(a) / value_of_U256(b);
-
- - - -
- - - -## Function `rem` - - - -
public fun rem(a: U256::U256, b: U256::U256): U256::U256
-
- - - -
-Implementation - - -
public fun rem(a: U256, b: U256): U256 {
-    native_rem(&mut a, &b);
-    a
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-pragma timeout = 160;
-aborts_if value_of_U256(b) == 0;
-ensures value_of_U256(result) == value_of_U256(a) % value_of_U256(b);
-
- - - -
- - - -## Function `pow` - - - -
public fun pow(a: U256::U256, b: U256::U256): U256::U256
-
- - - -
-Implementation - - -
public fun pow(a: U256, b: U256): U256 {
-    native_pow(&mut a, &b);
-    a
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-pragma opaque;
-pragma timeout = 600;
-let p = pow_spec(value_of_U256(a), value_of_U256(b));
-aborts_if p >= P64 * P64 * P64 * P64;
-ensures value_of_U256(result) == p;
-
- - - -
- - - -## Function `from_bytes` - - - -
fun from_bytes(data: &vector<u8>, be: bool): U256::U256
-
- - - -
-Implementation - - -
native fun from_bytes(data: &vector<u8>, be: bool): U256;
-
- - - -
- - - -## Function `native_add` - - - -
fun native_add(a: &mut U256::U256, b: &U256::U256)
-
- - - -
-Implementation - - -
native fun native_add(a: &mut U256, b: &U256);
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if value_of_U256(a) + value_of_U256(b) >= P64 * P64 * P64 * P64;
-ensures value_of_U256(a) == value_of_U256(old(a)) + value_of_U256(b);
-
- - - -
- - - -## Function `native_sub` - - - -
fun native_sub(a: &mut U256::U256, b: &U256::U256)
-
- - - -
-Implementation - - -
native fun native_sub(a: &mut U256, b: &U256);
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if value_of_U256(a) - value_of_U256(b) < 0;
-ensures value_of_U256(a) == value_of_U256(old(a)) - value_of_U256(b);
-
- - - -
- - - -## Function `native_mul` - - - -
fun native_mul(a: &mut U256::U256, b: &U256::U256)
-
- - - -
-Implementation - - -
native fun native_mul(a: &mut U256, b: &U256);
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if value_of_U256(a) * value_of_U256(b) >= P64 * P64 * P64 * P64;
-ensures value_of_U256(a) == value_of_U256(old(a)) * value_of_U256(b);
-
- - - -
- - - -## Function `native_div` - - - -
fun native_div(a: &mut U256::U256, b: &U256::U256)
-
- - - -
-Implementation - - -
native fun native_div(a: &mut U256, b: &U256);
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if value_of_U256(b) == 0;
-ensures value_of_U256(a) == value_of_U256(old(a)) / value_of_U256(b);
-
- - - -
- - - -## Function `native_rem` - - - -
fun native_rem(a: &mut U256::U256, b: &U256::U256)
-
- - - -
-Implementation - - -
native fun native_rem(a: &mut U256, b: &U256);
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if value_of_U256(b) == 0;
-ensures value_of_U256(a) == value_of_U256(old(a)) % value_of_U256(b);
-
- - - -
- - - -## Function `native_pow` - - - -
fun native_pow(a: &mut U256::U256, b: &U256::U256)
-
- - - -
-Implementation - - -
native fun native_pow(a: &mut U256, b: &U256);
-
- - - -
- -
-Specification - - - -
pragma opaque;
-aborts_if pow_spec(value_of_U256(a), value_of_U256(b)) >= P64 * P64 * P64 * P64;
-ensures value_of_U256(a) == pow_spec(value_of_U256(old(a)), value_of_U256(b));
-
- - - - - - - -
fun pow_spec(base: num, expon: num): num {
-   // This actually doesn't follow a strict definition as 0^0 is undefined
-   // mathematically. But the U256::pow of Rust is defined to be like this:
-   // Link: https://docs.rs/uint/0.9.3/src/uint/uint.rs.html#1000-1003
-   if (expon > 0) {
-       let x = pow_spec(base, expon / 2);
-       if (expon % 2 == 0) { x * x } else { x * x * base }
-   } else {
-       1
-   }
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = true;
-
diff --git a/release/v12/docs/UpgradeModuleDaoProposal.md b/release/v12/docs/UpgradeModuleDaoProposal.md deleted file mode 100644 index fc089941..00000000 --- a/release/v12/docs/UpgradeModuleDaoProposal.md +++ /dev/null @@ -1,363 +0,0 @@ - - - -# Module `0x1::UpgradeModuleDaoProposal` - -UpgradeModuleDaoProposal is a proposal moudle used to upgrade contract codes under a token. - - -- [Resource `UpgradeModuleCapability`](#0x1_UpgradeModuleDaoProposal_UpgradeModuleCapability) -- [Struct `UpgradeModule`](#0x1_UpgradeModuleDaoProposal_UpgradeModule) -- [Struct `UpgradeModuleV2`](#0x1_UpgradeModuleDaoProposal_UpgradeModuleV2) -- [Constants](#@Constants_0) -- [Function `plugin`](#0x1_UpgradeModuleDaoProposal_plugin) -- [Function `get_genesis_upgrade_cap`](#0x1_UpgradeModuleDaoProposal_get_genesis_upgrade_cap) -- [Function `propose_module_upgrade_v2`](#0x1_UpgradeModuleDaoProposal_propose_module_upgrade_v2) -- [Function `submit_module_upgrade_plan`](#0x1_UpgradeModuleDaoProposal_submit_module_upgrade_plan) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Dao;
-use 0x1::Errors;
-use 0x1::PackageTxnManager;
-use 0x1::Signer;
-use 0x1::Token;
-
- - - - - -## Resource `UpgradeModuleCapability` - -A wrapper of PackageTxnManager::UpgradePlanCapability. - - -
struct UpgradeModuleCapability<TokenT> has key
-
- - - -
-Fields - - -
-
-cap: PackageTxnManager::UpgradePlanCapability -
-
- -
-
- - -
- - - -## Struct `UpgradeModule` - -request of upgrading module contract code. - - -
struct UpgradeModule has copy, drop, store
-
- - - -
-Fields - - -
-
-module_address: address -
-
- -
-
-package_hash: vector<u8> -
-
- -
-
-version: u64 -
-
- -
-
- - -
- - - -## Struct `UpgradeModuleV2` - - - -
struct UpgradeModuleV2 has copy, drop, store
-
- - - -
-Fields - - -
-
-module_address: address -
-
- -
-
-package_hash: vector<u8> -
-
- -
-
-version: u64 -
-
- -
-
-enforced: bool -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_NOT_AUTHORIZED: u64 = 401;
-
- - - - - - - -
const ERR_ADDRESS_MISSMATCH: u64 = 402;
-
- - - - - - - -
const ERR_UNABLE_TO_UPGRADE: u64 = 400;
-
- - - - - -## Function `plugin` - -If this goverment can upgrade module, call this to register capability. - - -
public fun plugin<TokenT: store>(signer: &signer, cap: PackageTxnManager::UpgradePlanCapability)
-
- - - -
-Implementation - - -
public fun plugin<TokenT: store>(
-    signer: &signer,
-    cap: PackageTxnManager::UpgradePlanCapability,
-) {
-    let token_issuer = Token::token_address<TokenT>();
-    assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED));
-    move_to(signer, UpgradeModuleCapability<TokenT> { cap })
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = false;
-let sender = Signer::address_of(signer);
-aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS();
-aborts_if exists<UpgradeModuleCapability<TokenT>>(sender);
-
- - - -
- - - -## Function `get_genesis_upgrade_cap` - - - -
public(friend) fun get_genesis_upgrade_cap<TokenT: store>(): PackageTxnManager::UpgradePlanCapability
-
- - - -
-Implementation - - -
public (friend) fun get_genesis_upgrade_cap<TokenT:store>():PackageTxnManager::UpgradePlanCapability acquires UpgradeModuleCapability{
-    let UpgradeModuleCapability<TokenT>{
-        cap
-    } = move_from(Token::token_address<TokenT>());
-    cap
-}
-
- - - -
- - - -## Function `propose_module_upgrade_v2` - - - -
public fun propose_module_upgrade_v2<TokenT: copy, drop, store>(signer: &signer, module_address: address, package_hash: vector<u8>, version: u64, exec_delay: u64, enforced: bool)
-
- - - -
-Implementation - - -
public fun propose_module_upgrade_v2<TokenT: copy + drop + store>(
-    signer: &signer,
-    module_address: address,
-    package_hash: vector<u8>,
-    version: u64,
-    exec_delay: u64,
-    enforced: bool,
-) acquires UpgradeModuleCapability {
-    let cap = borrow_global<UpgradeModuleCapability<TokenT>>(Token::token_address<TokenT>());
-    let account_address = PackageTxnManager::account_address(&cap.cap);
-    assert!(account_address == module_address, Errors::requires_capability(ERR_ADDRESS_MISSMATCH));
-    Dao::propose<TokenT, UpgradeModuleV2>(
-        signer,
-        UpgradeModuleV2 { module_address, package_hash, version, enforced },
-        exec_delay,
-    );
-}
-
- - - -
- -
-Specification - - - -
pragma aborts_if_is_partial = true;
-include AbortIfUnableUpgrade<TokenT>;
-
- - - -
- - - -## Function `submit_module_upgrade_plan` - -Once the proposal is agreed, anyone can call this method to generate the upgrading plan. - - -
public fun submit_module_upgrade_plan<TokenT: copy, drop, store>(proposer_address: address, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun submit_module_upgrade_plan<TokenT: copy + drop + store>(
-    proposer_address: address,
-    proposal_id: u64,
-) acquires UpgradeModuleCapability {
-    let UpgradeModuleV2 { module_address, package_hash, version, enforced } = Dao::extract_proposal_action<
-        TokenT,
-        UpgradeModuleV2,
-    >(proposer_address, proposal_id);
-    let cap = borrow_global<UpgradeModuleCapability<TokenT>>(Token::token_address<TokenT>());
-    let account_address = PackageTxnManager::account_address(&cap.cap);
-    assert!(account_address == module_address, Errors::requires_capability(ERR_ADDRESS_MISSMATCH));
-    PackageTxnManager::submit_upgrade_plan_with_cap_v2(
-        &cap.cap,
-        package_hash,
-        version,
-        enforced,
-    );
-}
-
- - - -
- -
-Specification - - - -
let expected_states = vec<u8>(6);
-include Dao::CheckProposalStates<TokenT, UpgradeModule>{expected_states};
-let proposal = global<Dao::Proposal<TokenT, UpgradeModule>>(proposer_address);
-aborts_if Option::is_none(proposal.action);
-let action = proposal.action.vec[0];
-include AbortIfUnableUpgrade<TokenT>{module_address: action.module_address};
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-pragma aborts_if_is_partial;
-
diff --git a/release/v12/docs/UpgradeModulePlugin.md b/release/v12/docs/UpgradeModulePlugin.md deleted file mode 100644 index db2dd9fd..00000000 --- a/release/v12/docs/UpgradeModulePlugin.md +++ /dev/null @@ -1,329 +0,0 @@ - - - -# Module `0x1::UpgradeModulePlugin` - - - -- [Struct `UpgradeModulePlugin`](#0x1_UpgradeModulePlugin_UpgradeModulePlugin) -- [Struct `UpgradeModuleAction`](#0x1_UpgradeModulePlugin_UpgradeModuleAction) -- [Function `initialize`](#0x1_UpgradeModulePlugin_initialize) -- [Function `required_caps`](#0x1_UpgradeModulePlugin_required_caps) -- [Function `create_proposal`](#0x1_UpgradeModulePlugin_create_proposal) -- [Function `create_proposal_entry`](#0x1_UpgradeModulePlugin_create_proposal_entry) -- [Function `execute_proposal`](#0x1_UpgradeModulePlugin_execute_proposal) -- [Function `execute_proposal_entry`](#0x1_UpgradeModulePlugin_execute_proposal_entry) -- [Function `install_plugin_proposal`](#0x1_UpgradeModulePlugin_install_plugin_proposal) -- [Function `install_plugin_proposal_entry`](#0x1_UpgradeModulePlugin_install_plugin_proposal_entry) - - -
use 0x1::DAOPluginMarketplace;
-use 0x1::DAOSpace;
-use 0x1::InstallPluginProposalPlugin;
-use 0x1::Option;
-use 0x1::Vector;
-
- - - - - -## Struct `UpgradeModulePlugin` - - - -
struct UpgradeModulePlugin has drop, store
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `UpgradeModuleAction` - - - -
struct UpgradeModuleAction has drop, store
-
- - - -
-Fields - - -
-
-package_hash: vector<u8> -
-
- -
-
-version: u64 -
-
- -
-
-enforced: bool -
-
- -
-
- - -
- - - -## Function `initialize` - - - -
public fun initialize(_sender: &signer)
-
- - - -
-Implementation - - -
public fun initialize(_sender: &signer) {
-    let witness = UpgradeModulePlugin{};
-
-    DAOPluginMarketplace::register_plugin<UpgradeModulePlugin>(
-        &witness,
-        b"0x1::UpgradeModulePlugin",
-        b"The plugin for upgrade module.",
-        Option::none(),
-    );
-
-    let implement_extpoints = Vector::empty<vector<u8>>();
-    let depend_extpoints = Vector::empty<vector<u8>>();
-
-    DAOPluginMarketplace::publish_plugin_version<UpgradeModulePlugin>(
-        &witness,
-        b"v0.1.0",
-        *&implement_extpoints,
-        *&depend_extpoints,
-        b"inner-plugin://upgrade-module-plugin",
-    );
-}
-
- - - -
- - - -## Function `required_caps` - - - -
public fun required_caps(): vector<DAOSpace::CapType>
-
- - - -
-Implementation - - -
public fun required_caps(): vector<CapType> {
-    let caps = Vector::singleton(DAOSpace::proposal_cap_type());
-    Vector::push_back(&mut caps, DAOSpace::upgrade_module_cap_type());
-    caps
-}
-
- - - -
- - - -## Function `create_proposal` - - - -
public fun create_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public fun create_proposal<DAOT: store>(sender: &signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64, package_hash: vector<u8>, version: u64, enforced: bool) {
-    let witness = UpgradeModulePlugin{};
-    let cap = DAOSpace::acquire_proposal_cap<DAOT, UpgradeModulePlugin>(&witness);
-    let action = UpgradeModuleAction{
-        package_hash,
-        version,
-        enforced
-    };
-    DAOSpace::create_proposal<
-        DAOT,
-        UpgradeModulePlugin,
-        UpgradeModuleAction>(&cap, sender, action, title, introduction, extend, action_delay, Option::none<u8>());
-}
-
- - - -
- - - -## Function `create_proposal_entry` - - - -
public(script) fun create_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64, package_hash: vector<u8>, version: u64, enforced: bool)
-
- - - -
-Implementation - - -
public (script) fun create_proposal_entry <DAOT: store>(sender: signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64, package_hash: vector<u8>, version: u64, enforced: bool) {
-    create_proposal<DAOT>(&sender, title, introduction, extend, action_delay, package_hash, version, enforced);
-}
-
- - - -
- - - -## Function `execute_proposal` - - - -
public fun execute_proposal<DAOT: store>(sender: &signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public fun execute_proposal<DAOT: store>(sender: &signer, proposal_id: u64) {
-    let witness = UpgradeModulePlugin{};
-    let proposal_cap =
-        DAOSpace::acquire_proposal_cap<DAOT, UpgradeModulePlugin>(&witness);
-    let upgrade_module_cap =
-        DAOSpace::acquire_upgrade_module_cap<DAOT, UpgradeModulePlugin>(&witness);
-
-    let UpgradeModuleAction{
-        package_hash,
-        version,
-        enforced
-    } = DAOSpace::execute_proposal<
-        DAOT,
-        UpgradeModulePlugin,
-        UpgradeModuleAction>(&proposal_cap, sender, proposal_id);
-    DAOSpace::submit_upgrade_plan<DAOT, UpgradeModulePlugin>(&mut upgrade_module_cap, package_hash, version, enforced);
-}
-
- - - -
- - - -## Function `execute_proposal_entry` - - - -
public(script) fun execute_proposal_entry<DAOT: store>(sender: signer, proposal_id: u64)
-
- - - -
-Implementation - - -
public (script) fun execute_proposal_entry<DAOT: store>(sender: signer, proposal_id: u64) {
-    execute_proposal<DAOT>(&sender, proposal_id);
-}
-
- - - -
- - - -## Function `install_plugin_proposal` - - - -
public fun install_plugin_proposal<DAOT: store>(sender: &signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public fun install_plugin_proposal<DAOT:store>(sender:&signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    InstallPluginProposalPlugin::create_proposal<DAOT, UpgradeModulePlugin>(sender,required_caps(), title, introduction,  extend, action_delay);
-}
-
- - - -
- - - -## Function `install_plugin_proposal_entry` - - - -
public(script) fun install_plugin_proposal_entry<DAOT: store>(sender: signer, title: vector<u8>, introduction: vector<u8>, extend: vector<u8>, action_delay: u64)
-
- - - -
-Implementation - - -
public (script) fun install_plugin_proposal_entry<DAOT:store>(sender:signer, title:vector<u8>, introduction:vector<u8>, extend: vector<u8>, action_delay:u64){
-    install_plugin_proposal<DAOT>(&sender, title, introduction, extend, action_delay);
-}
-
- - - -
diff --git a/release/v12/docs/VMConfig.md b/release/v12/docs/VMConfig.md deleted file mode 100644 index 8aa3ef34..00000000 --- a/release/v12/docs/VMConfig.md +++ /dev/null @@ -1,710 +0,0 @@ - - - -# Module `0x1::VMConfig` - -VMConfig keep track of VM related configuration, like gas schedule. - - -- [Struct `VMConfig`](#0x1_VMConfig_VMConfig) -- [Struct `GasSchedule`](#0x1_VMConfig_GasSchedule) -- [Struct `GasConstants`](#0x1_VMConfig_GasConstants) -- [Struct `GasCost`](#0x1_VMConfig_GasCost) -- [Function `instruction_schedule`](#0x1_VMConfig_instruction_schedule) -- [Function `native_schedule`](#0x1_VMConfig_native_schedule) -- [Function `gas_constants`](#0x1_VMConfig_gas_constants) -- [Function `new_gas_cost`](#0x1_VMConfig_new_gas_cost) -- [Function `new_vm_config`](#0x1_VMConfig_new_vm_config) -- [Function `initialize`](#0x1_VMConfig_initialize) -- [Module Specification](#@Module_Specification_0) - - -
use 0x1::ChainId;
-use 0x1::Config;
-use 0x1::CoreAddresses;
-use 0x1::Vector;
-
- - - - - -## Struct `VMConfig` - -The struct to hold all config data needed to operate the VM. -* gas_schedule: Cost of running the VM. - - -
struct VMConfig has copy, drop, store
-
- - - -
-Fields - - -
-
-gas_schedule: VMConfig::GasSchedule -
-
- -
-
- - -
- - - -## Struct `GasSchedule` - -The gas schedule keeps two separate schedules for the gas: -* The instruction_schedule: This holds the gas for each bytecode instruction. -* The native_schedule: This holds the gas for used (per-byte operated over) for each native -function. -A couple notes: -1. In the case that an instruction is deleted from the bytecode, that part of the cost schedule -still needs to remain the same; once a slot in the table is taken by an instruction, that is its -slot for the rest of time (since that instruction could already exist in a module on-chain). -2. The initialization of the module will publish the instruction table to the genesis -address, and will preload the vector with the gas schedule for instructions. The VM will then -load this into memory at the startup of each block. - - -
struct GasSchedule has copy, drop, store
-
- - - -
-Fields - - -
-
-instruction_schedule: vector<u8> -
-
- -
-
-native_schedule: vector<u8> -
-
- -
-
-gas_constants: VMConfig::GasConstants -
-
- -
-
- - -
- - - -## Struct `GasConstants` - -The gas constants contains all kind of constants used in gas calculation. - - -
struct GasConstants has copy, drop, store
-
- - - -
-Fields - - -
-
-global_memory_per_byte_cost: u64 -
-
- The cost per-byte written to global storage. -
-
-global_memory_per_byte_write_cost: u64 -
-
- The cost per-byte written to storage. -
-
-min_transaction_gas_units: u64 -
-
- We charge one unit of gas per-byte for the first 600 bytes -
-
-large_transaction_cutoff: u64 -
-
- Any transaction over this size will be charged INTRINSIC_GAS_PER_BYTE per byte -
-
-instrinsic_gas_per_byte: u64 -
-
- The units of gas that should be charged per byte for every transaction. -
-
-maximum_number_of_gas_units: u64 -
-
- 1 nanosecond should equal one unit of computational gas. We bound the maximum - computational time of any given transaction at 10 milliseconds. We want this number and - MAX_PRICE_PER_GAS_UNIT to always satisfy the inequality that - MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits::MAX) -
-
-min_price_per_gas_unit: u64 -
-
- The minimum gas price that a transaction can be submitted with. -
-
-max_price_per_gas_unit: u64 -
-
- The maximum gas unit price that a transaction can be submitted with. -
-
-max_transaction_size_in_bytes: u64 -
-
- The max transaction size in bytes that a transaction can have. -
-
-gas_unit_scaling_factor: u64 -
-
- gas unit scaling factor. -
-
-default_account_size: u64 -
-
- default account size. -
-
- - -
- - - -## Struct `GasCost` - -The GasCost tracks: -- instruction cost: how much time/computational power is needed to perform the instruction -- memory cost: how much memory is required for the instruction, and storage overhead - - -
struct GasCost has copy, drop, store
-
- - - -
-Fields - - -
-
-instruction_gas: u64 -
-
- -
-
-memory_gas: u64 -
-
- -
-
- - -
- - - -## Function `instruction_schedule` - - - -
public fun instruction_schedule(): vector<VMConfig::GasCost>
-
- - - -
-Implementation - - -
public fun instruction_schedule(): vector<GasCost> {
-    let table = Vector::empty();
-
-    // POP
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // RET
-    Vector::push_back(&mut table, new_gas_cost(638, 1));
-    // BR_TRUE
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // BR_FALSE
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // BRANCH
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LD_U64
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LD_CONST
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LD_TRUE
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LD_FALSE
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // COPY_LOC
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // MOVE_LOC
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // ST_LOC
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // MUT_BORROW_LOC
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // IMM_BORROW_LOC
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // MUT_BORROW_FIELD
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // IMM_BORROW_FIELD
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // CALL
-    Vector::push_back(&mut table, new_gas_cost(1132, 1));
-    // PACK
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // UNPACK
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // READ_REF
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // WRITE_REF
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // ADD
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // SUB
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // MUL
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // MOD
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // DIV
-    Vector::push_back(&mut table, new_gas_cost(3, 1));
-    // BIT_OR
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // BIT_AND
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // XOR
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // OR
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // AND
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // NOT
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // EQ
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // NEQ
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LT
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // GT
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LE
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // GE
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // ABORT
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // NOP
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // EXISTS
-    Vector::push_back(&mut table, new_gas_cost(41, 1));
-    // MUT_BORROW_GLOBAL
-    Vector::push_back(&mut table, new_gas_cost(21, 1));
-    // IML_BORROW_GLOBAL
-    Vector::push_back(&mut table, new_gas_cost(23, 1));
-    // MOVE_FROM
-    Vector::push_back(&mut table, new_gas_cost(459, 1));
-    // MOVE_TO
-    Vector::push_back(&mut table, new_gas_cost(13, 1));
-    // FREEZE_REF
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // SHL
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // SHR
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LD_U8
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // LD_U128
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-
-    // CAST_U8
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // CAST_U64
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // CAST_U128
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // MUT_BORORW_FIELD_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // IMM_BORORW_FIELD_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(1, 1));
-    // CALL_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(582, 1));
-    // PACK_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // UNPACK_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    // EXISTS_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(34, 1));
-    // MUT_BORROW_GLOBAL_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(15, 1));
-    // IMM_BORROW_GLOBAL_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(14, 1));
-    // MOVE_FROM_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(13, 1));
-    // MOVE_TO_GENERIC
-    Vector::push_back(&mut table, new_gas_cost(27, 1));
-
-    // VEC_PACK
-    Vector::push_back(&mut table, new_gas_cost(84, 1));
-    // VEC_LEN
-    Vector::push_back(&mut table, new_gas_cost(98, 1));
-    // VEC_IMM_BORROW
-    Vector::push_back(&mut table, new_gas_cost(1334, 1));
-    // VEC_MUT_BORROW
-    Vector::push_back(&mut table, new_gas_cost(1902, 1));
-    // VEC_PUSH_BACK
-    Vector::push_back(&mut table, new_gas_cost(53, 1));
-    // VEC_POP_BACK
-    Vector::push_back(&mut table, new_gas_cost(227, 1));
-    // VEC_UNPACK
-    Vector::push_back(&mut table, new_gas_cost(572, 1));
-    // VEC_SWAP
-    Vector::push_back(&mut table, new_gas_cost(1436, 1));
-    table
-}
-
- - - -
- - - -## Function `native_schedule` - - - -
public fun native_schedule(): vector<VMConfig::GasCost>
-
- - - -
-Implementation - - -
public fun native_schedule(): vector<GasCost> {
-    let table = Vector::empty();
-    //Hash::sha2_256 0
-    Vector::push_back(&mut table, new_gas_cost(21, 1));
-    //Hash::sha3_256 1
-    Vector::push_back(&mut table, new_gas_cost(64, 1));
-    //Signature::ed25519_verify 2
-    Vector::push_back(&mut table, new_gas_cost(61, 1));
-    //ED25519_THRESHOLD_VERIFY 3 this native funciton is deprecated
-    Vector::push_back(&mut table, new_gas_cost(3351, 1));
-    //BSC::to_bytes 4
-    Vector::push_back(&mut table, new_gas_cost(181, 1));
-    //Vector::length 5
-    Vector::push_back(&mut table, new_gas_cost(98, 1));
-    //Vector::empty 6
-    Vector::push_back(&mut table, new_gas_cost(84, 1));
-    //Vector::borrow 7
-    Vector::push_back(&mut table, new_gas_cost(1334, 1));
-    //Vector::borrow_mut 8
-    Vector::push_back(&mut table, new_gas_cost(1902, 1));
-    //Vector::push_back 9
-    Vector::push_back(&mut table, new_gas_cost(53, 1));
-    //Vector::pop_back 10
-    Vector::push_back(&mut table, new_gas_cost(227, 1));
-    //Vector::destory_empty 11
-    Vector::push_back(&mut table, new_gas_cost(572, 1));
-    //Vector::swap 12
-    Vector::push_back(&mut table, new_gas_cost(1436, 1));
-    //Signature::ed25519_validate_pubkey 13
-    Vector::push_back(&mut table, new_gas_cost(26, 1));
-    //Signer::borrow_address 14
-    Vector::push_back(&mut table, new_gas_cost(353, 1));
-    //Account::creator_signer 15
-    Vector::push_back(&mut table, new_gas_cost(24, 1));
-    //Account::destroy_signer 16
-    Vector::push_back(&mut table, new_gas_cost(212, 1));
-    //Event::emit_event 17
-    Vector::push_back(&mut table, new_gas_cost(52, 1));
-    //BCS::to_address 18
-    Vector::push_back(&mut table, new_gas_cost(26, 1));
-    //Token::name_of 19
-    Vector::push_back(&mut table, new_gas_cost(2002, 1));
-    //Hash::keccak_256 20
-    Vector::push_back(&mut table, new_gas_cost(64, 1));
-    //Hash::ripemd160 21
-    Vector::push_back(&mut table, new_gas_cost(64, 1));
-    //Signature::native_ecrecover 22
-    Vector::push_back(&mut table, new_gas_cost(128, 1));
-    //U256::from_bytes 23
-    Vector::push_back(&mut table, new_gas_cost(2, 1));
-    //U256::add 24
-    Vector::push_back(&mut table, new_gas_cost(4, 1));
-    //U256::sub 25
-    Vector::push_back(&mut table, new_gas_cost(4, 1));
-    //U256::mul 26
-    Vector::push_back(&mut table, new_gas_cost(4, 1));
-    //U256::div 27
-    Vector::push_back(&mut table, new_gas_cost(10, 1));
-    // U256::rem 28
-    Vector::push_back(&mut table, new_gas_cost(4, 1));
-    // U256::pow 29
-    Vector::push_back(&mut table, new_gas_cost(8, 1));
-    // TODO: settle down the gas cost
-    // Vector::append 30
-    Vector::push_back(&mut table, new_gas_cost(40, 1));
-    // Vector::remove 31
-    Vector::push_back(&mut table, new_gas_cost(20, 1));
-    // Vector::reverse 32
-    Vector::push_back(&mut table, new_gas_cost(10, 1));
-
-    table
-}
-
- - - -
- - - -## Function `gas_constants` - - - -
public fun gas_constants(): VMConfig::GasConstants
-
- - - -
-Implementation - - -
public fun gas_constants(): GasConstants {
-    let min_price_per_gas_unit: u64 = if (ChainId::is_test()) { 0 }  else { 1 };
-    let maximum_number_of_gas_units: u64 = 40000000;//must less than base_block_gas_limit
-
-    if (ChainId::is_test() || ChainId::is_dev() || ChainId::is_halley()) {
-        maximum_number_of_gas_units = maximum_number_of_gas_units * 10
-    };
-    GasConstants {
-        global_memory_per_byte_cost: 4,
-        global_memory_per_byte_write_cost: 9,
-        min_transaction_gas_units: 600,
-        large_transaction_cutoff: 600,
-        instrinsic_gas_per_byte: 8,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit: 10000,
-        max_transaction_size_in_bytes: 1024 * 128,
-        gas_unit_scaling_factor: 1,
-        default_account_size: 800,
-    }
-}
-
- - - -
- - - -## Function `new_gas_cost` - - - -
fun new_gas_cost(instr_gas: u64, mem_gas: u64): VMConfig::GasCost
-
- - - -
-Implementation - - -
fun new_gas_cost(instr_gas: u64, mem_gas: u64): GasCost {
-    GasCost {
-        instruction_gas: instr_gas,
-        memory_gas: mem_gas,
-    }
-}
-
- - - -
- - - -## Function `new_vm_config` - -Create a new vm config, mainly used in DAO. - - -
public fun new_vm_config(instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64): VMConfig::VMConfig
-
- - - -
-Implementation - - -
public fun new_vm_config(
-    instruction_schedule: vector<u8>,
-    native_schedule: vector<u8>,
-    global_memory_per_byte_cost: u64,
-    global_memory_per_byte_write_cost: u64,
-    min_transaction_gas_units: u64,
-    large_transaction_cutoff: u64,
-    instrinsic_gas_per_byte: u64,
-    maximum_number_of_gas_units: u64,
-    min_price_per_gas_unit: u64,
-    max_price_per_gas_unit: u64,
-    max_transaction_size_in_bytes: u64,
-    gas_unit_scaling_factor: u64,
-    default_account_size: u64,
-): VMConfig {
-    let gas_constants = GasConstants {
-        global_memory_per_byte_cost,
-        global_memory_per_byte_write_cost,
-        min_transaction_gas_units,
-        large_transaction_cutoff,
-        instrinsic_gas_per_byte,
-        maximum_number_of_gas_units,
-        min_price_per_gas_unit,
-        max_price_per_gas_unit,
-        max_transaction_size_in_bytes,
-        gas_unit_scaling_factor,
-        default_account_size,
-    };
-    VMConfig {
-        gas_schedule: GasSchedule { instruction_schedule, native_schedule, gas_constants },
-    }
-}
-
- - - -
- - - -## Function `initialize` - -Initialize the table under the genesis account - - -
public fun initialize(account: &signer, instruction_schedule: vector<u8>, native_schedule: vector<u8>, global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, min_transaction_gas_units: u64, large_transaction_cutoff: u64, instrinsic_gas_per_byte: u64, maximum_number_of_gas_units: u64, min_price_per_gas_unit: u64, max_price_per_gas_unit: u64, max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64)
-
- - - -
-Implementation - - -
public fun initialize(
-    account: &signer,
-    instruction_schedule: vector<u8>,
-    native_schedule: vector<u8>,
-    global_memory_per_byte_cost: u64,
-    global_memory_per_byte_write_cost: u64,
-    min_transaction_gas_units: u64,
-    large_transaction_cutoff: u64,
-    instrinsic_gas_per_byte: u64,
-    maximum_number_of_gas_units: u64,
-    min_price_per_gas_unit: u64,
-    max_price_per_gas_unit: u64,
-    max_transaction_size_in_bytes: u64,
-    gas_unit_scaling_factor: u64,
-    default_account_size: u64,
-) {
-    CoreAddresses::assert_genesis_address(account);
-    Config::publish_new_config<VMConfig>(
-        account,
-        new_vm_config(
-            instruction_schedule,
-            native_schedule,
-            global_memory_per_byte_cost,
-            global_memory_per_byte_write_cost,
-            min_transaction_gas_units,
-            large_transaction_cutoff,
-            instrinsic_gas_per_byte,
-            maximum_number_of_gas_units,
-            min_price_per_gas_unit,
-            max_price_per_gas_unit,
-            max_transaction_size_in_bytes,
-            gas_unit_scaling_factor,
-            default_account_size,
-        ),
-    );
-}
-
- - - -
- -
-Specification - - - -
aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS();
-aborts_if exists<Config::Config<VMConfig>>(Signer::address_of(account));
-aborts_if
-    exists<Config::ModifyConfigCapabilityHolder<VMConfig>>(
-        Signer::address_of(account),
-    );
-ensures exists<Config::Config<VMConfig>>(Signer::address_of(account));
-ensures
-    exists<Config::ModifyConfigCapabilityHolder<VMConfig>>(
-        Signer::address_of(account),
-    );
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/Vector.md b/release/v12/docs/Vector.md deleted file mode 100644 index d43cbcfd..00000000 --- a/release/v12/docs/Vector.md +++ /dev/null @@ -1,792 +0,0 @@ - - - -# Module `0x1::Vector` - -A variable-sized container that can hold any type. Indexing is 0-based, and -vectors are growable. This module has many native functions. -Verification of modules that use this one uses model functions that are implemented -directly in Boogie. The specification language has built-in functions operations such -as vec. There are some helper functions defined here for specifications in other -modules as well. - ->Note: We did not verify most of the -Move functions here because many have loops, requiring loop invariants to prove, and -the return on investment didn't seem worth it for these simple functions. - - -- [Constants](#@Constants_0) -- [Function `empty`](#0x1_Vector_empty) -- [Function `length`](#0x1_Vector_length) -- [Function `borrow`](#0x1_Vector_borrow) -- [Function `push_back`](#0x1_Vector_push_back) -- [Function `borrow_mut`](#0x1_Vector_borrow_mut) -- [Function `pop_back`](#0x1_Vector_pop_back) -- [Function `destroy_empty`](#0x1_Vector_destroy_empty) -- [Function `swap`](#0x1_Vector_swap) -- [Function `singleton`](#0x1_Vector_singleton) -- [Function `reverse`](#0x1_Vector_reverse) -- [Function `native_reverse`](#0x1_Vector_native_reverse) -- [Function `append`](#0x1_Vector_append) -- [Function `native_append`](#0x1_Vector_native_append) -- [Function `is_empty`](#0x1_Vector_is_empty) -- [Function `contains`](#0x1_Vector_contains) -- [Function `index_of`](#0x1_Vector_index_of) -- [Function `remove`](#0x1_Vector_remove) -- [Function `native_remove`](#0x1_Vector_native_remove) -- [Function `swap_remove`](#0x1_Vector_swap_remove) -- [Function `split`](#0x1_Vector_split) -- [Module Specification](#@Module_Specification_1) - - [Helper Functions](#@Helper_Functions_2) - - -
- - - - - -## Constants - - - - -The index into the vector is out of bounds - - -
const EINDEX_OUT_OF_BOUNDS: u64 = 0;
-
- - - - - -## Function `empty` - -Create an empty vector. - - -
public fun empty<Element>(): vector<Element>
-
- - - -
-Implementation - - -
native public fun empty<Element>(): vector<Element>;
-
- - - -
- - - -## Function `length` - -Return the length of the vector. - - -
public fun length<Element>(v: &vector<Element>): u64
-
- - - -
-Implementation - - -
native public fun length<Element>(v: &vector<Element>): u64;
-
- - - -
- - - -## Function `borrow` - -Acquire an immutable reference to the ith element of the vector v. -Aborts if i is out of bounds. - - -
public fun borrow<Element>(v: &vector<Element>, i: u64): &Element
-
- - - -
-Implementation - - -
native public fun borrow<Element>(v: &vector<Element>, i: u64): ∈
-
- - - -
- - - -## Function `push_back` - -Add element e to the end of the vector v. - - -
public fun push_back<Element>(v: &mut vector<Element>, e: Element)
-
- - - -
-Implementation - - -
native public fun push_back<Element>(v: &mut vector<Element>, e: Element);
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the ith element in the vector v. -Aborts if i is out of bounds. - - -
public fun borrow_mut<Element>(v: &mut vector<Element>, i: u64): &mut Element
-
- - - -
-Implementation - - -
native public fun borrow_mut<Element>(v: &mut vector<Element>, i: u64): &mut Element;
-
- - - -
- - - -## Function `pop_back` - -Pop an element from the end of vector v. -Aborts if v is empty. - - -
public fun pop_back<Element>(v: &mut vector<Element>): Element
-
- - - -
-Implementation - - -
native public fun pop_back<Element>(v: &mut vector<Element>): Element;
-
- - - -
- - - -## Function `destroy_empty` - -Destroy the vector v. -Aborts if v is not empty. - - -
public fun destroy_empty<Element>(v: vector<Element>)
-
- - - -
-Implementation - - -
native public fun destroy_empty<Element>(v: vector<Element>);
-
- - - -
- - - -## Function `swap` - -Swaps the elements at the ith and jth indices in the vector v. -Aborts if ior j is out of bounds. - - -
public fun swap<Element>(v: &mut vector<Element>, i: u64, j: u64)
-
- - - -
-Implementation - - -
native public fun swap<Element>(v: &mut vector<Element>, i: u64, j: u64);
-
- - - -
- - - -## Function `singleton` - -Return an vector of size one containing element e. - - -
public fun singleton<Element>(e: Element): vector<Element>
-
- - - -
-Implementation - - -
public fun singleton<Element>(e: Element): vector<Element> {
-    let v = empty();
-    push_back(&mut v, e);
-    v
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-ensures result == vec(e);
-
- - - - - - - -
fun spec_singleton<Element>(e: Element): vector<Element> {
-   vec(e)
-}
-
- - - -
- - - -## Function `reverse` - -Reverses the order of the elements in the vector v in place. - - -
public fun reverse<Element>(v: &mut vector<Element>)
-
- - - -
-Implementation - - -
public fun reverse<Element>(v: &mut vector<Element>) {
-    native_reverse(v)
-}
-
- - - -
- -
-Specification - - - -
pragma intrinsic = true;
-
- - - -
- - - -## Function `native_reverse` - - - -
fun native_reverse<Element>(this: &mut vector<Element>)
-
- - - -
-Implementation - - -
native fun native_reverse<Element>(this: &mut vector<Element>);
-
- - - -
- - - -## Function `append` - -Pushes all of the elements of the other vector into the lhs vector. - - -
public fun append<Element>(lhs: &mut vector<Element>, other: vector<Element>)
-
- - - -
-Implementation - - -
public fun append<Element>(lhs: &mut vector<Element>, other: vector<Element>) {
-    native_append(lhs, other);
-}
-
- - - -
- -
-Specification - - - -
pragma intrinsic = true;
-
- - - -
- - - -## Function `native_append` - - - -
fun native_append<Element>(lhs: &mut vector<Element>, other: vector<Element>)
-
- - - -
-Implementation - - -
native fun native_append<Element>(lhs: &mut vector<Element>, other: vector<Element>);
-
- - - -
- - - -## Function `is_empty` - -Return true if the vector v has no elements and false otherwise. - - -
public fun is_empty<Element>(v: &vector<Element>): bool
-
- - - -
-Implementation - - -
public fun is_empty<Element>(v: &vector<Element>): bool {
-    length(v) == 0
-}
-
- - - -
- -
-Specification - - - -
pragma intrinsic = true;
-
- - - -
- - - -## Function `contains` - -Return true if e is in the vector v. - - -
public fun contains<Element>(v: &vector<Element>, e: &Element): bool
-
- - - -
-Implementation - - -
public fun contains<Element>(v: &vector<Element>, e: &Element): bool {
-    let i = 0;
-    let len = length(v);
-    while (i < len) {
-        if (borrow(v, i) == e) return true;
-        i = i + 1;
-    };
-    false
-}
-
- - - -
- -
-Specification - - - -
pragma intrinsic = true;
-
- - - -
- - - -## Function `index_of` - -Return (true, i) if e is in the vector v at index i. -Otherwise, returns (false, 0). - - -
public fun index_of<Element>(v: &vector<Element>, e: &Element): (bool, u64)
-
- - - -
-Implementation - - -
public fun index_of<Element>(v: &vector<Element>, e: &Element): (bool, u64) {
-    let i = 0;
-    let len = length(v);
-    while (i < len) {
-        if (borrow(v, i) == e) return (true, i);
-        i = i + 1;
-    };
-    (false, 0)
-}
-
- - - -
- -
-Specification - - - -
pragma intrinsic = true;
-
- - - -
- - - -## Function `remove` - -Remove the ith element of the vector v, shifting all subsequent elements. -This is O(n) and preserves ordering of elements in the vector. -Aborts if i is out of bounds. - - -
public fun remove<Element>(v: &mut vector<Element>, i: u64): Element
-
- - - -
-Implementation - - -
public fun remove<Element>(v: &mut vector<Element>, i: u64): Element {
-    let len = length(v);
-    // i out of bounds; abort
-    if (i >= len) abort EINDEX_OUT_OF_BOUNDS;
-
-    native_remove(v, i)
-}
-
- - - -
- -
-Specification - - - -
pragma intrinsic = true;
-
- - - -
- - - -## Function `native_remove` - - - -
fun native_remove<Element>(this: &mut vector<Element>, i: u64): Element
-
- - - -
-Implementation - - -
native fun native_remove<Element>(this: &mut vector<Element>, i: u64): Element;
-
- - - -
- - - -## Function `swap_remove` - -Swap the ith element of the vector v with the last element and then pop the vector. -This is O(1), but does not preserve ordering of elements in the vector. -Aborts if i is out of bounds. - - -
public fun swap_remove<Element>(v: &mut vector<Element>, i: u64): Element
-
- - - -
-Implementation - - -
public fun swap_remove<Element>(v: &mut vector<Element>, i: u64): Element {
-    let last_idx = length(v) - 1;
-    swap(v, i, last_idx);
-    pop_back(v)
-}
-
- - - -
- -
-Specification - - - -
pragma intrinsic = true;
-
- - - -
- - - -## Function `split` - -Split a vector into sub-vectors of size sub_len, - - -
public fun split<Element: copy, drop, store>(v: &vector<Element>, sub_len: u64): vector<vector<Element>>
-
- - - -
-Implementation - - -
public fun split<Element: copy + drop + store>(v: &vector<Element>, sub_len: u64): vector<vector<Element>> {
-    let result = empty<vector<Element>>();
-    let len = length(v) / sub_len;
-
-    let rem = 0;
-    if (len * sub_len < length(v)) {
-        rem = length(v) - len * sub_len;
-    };
-
-    let i = 0;
-    while (i < len) {
-        let sub = empty<Element>();
-        let j = 0;
-        while (j < sub_len) {
-            let index = sub_len * i + j;
-            push_back(&mut sub, *borrow(v, index));
-            j = j + 1;
-        };
-        push_back<vector<Element>>(&mut result, sub);
-        i = i + 1;
-    };
-
-    if (rem > 0) {
-        let sub = empty<Element>();
-        let index = length(v) - rem;
-        while (index < length(v)) {
-            push_back(&mut sub, *borrow(v, index));
-            index = index + 1;
-        };
-        push_back<vector<Element>>(&mut result, sub);
-    };
-    result
-}
-
- - - -
- -
-Specification - - - -
pragma verify = false;
-aborts_if sub_len == 0;
-
- - - -
- - - -## Module Specification - - - - - -### Helper Functions - -Check whether a vector contains an element. - - - - - -
fun spec_contains<Element>(v: vector<Element>, e: Element): bool {
-   exists x in v: x == e
-}
-
- - -Check if v1 is equal to the result of adding e at the end of v2 - - - - - -
fun eq_push_back<Element>(v1: vector<Element>, v2: vector<Element>, e: Element): bool {
-   len(v1) == len(v2) + 1 &&
-   v1[len(v1)-1] == e &&
-   v1[0..len(v1)-1] == v2[0..len(v2)]
-}
-
- - -Check if v is equal to the result of concatenating v1 and v2 - - - - - -
fun eq_append<Element>(v: vector<Element>, v1: vector<Element>, v2: vector<Element>): bool {
-   len(v) == len(v1) + len(v2) &&
-   v[0..len(v1)] == v1 &&
-   v[len(v1)..len(v)] == v2
-}
-
- - -Check v1 is equal to the result of removing the first element of v2 - - - - - -
fun eq_pop_front<Element>(v1: vector<Element>, v2: vector<Element>): bool {
-   len(v1) + 1 == len(v2) &&
-   v1 == v2[1..len(v2)]
-}
-
- - -Check that v1 is equal to the result of removing the element at index i from v2. - - - - - -
fun eq_remove_elem_at_index<Element>(i: u64, v1: vector<Element>, v2: vector<Element>): bool {
-   len(v1) + 1 == len(v2) &&
-   v1[0..i] == v2[0..i] &&
-   v1[i..len(v1)] == v2[i + 1..len(v2)]
-}
-
diff --git a/release/v12/docs/Version.md b/release/v12/docs/Version.md deleted file mode 100644 index 64012d09..00000000 --- a/release/v12/docs/Version.md +++ /dev/null @@ -1,146 +0,0 @@ - - - -# Module `0x1::Version` - -Version tracks version of something, like current VM version. - - -- [Struct `Version`](#0x1_Version_Version) -- [Constants](#@Constants_0) -- [Function `new_version`](#0x1_Version_new_version) -- [Function `get`](#0x1_Version_get) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Config;
-
- - - - - -## Struct `Version` - -Version. - - -
struct Version has copy, drop, store
-
- - - -
-Fields - - -
-
-major: u64 -
-
- major number. -
-
- - -
- - - -## Constants - - - - - - -
const EMAJOR_TO_OLD: u64 = 101;
-
- - - - - -## Function `new_version` - -Create a new version. - - -
public fun new_version(major: u64): Version::Version
-
- - - -
-Implementation - - -
public fun new_version(major: u64): Version {
-    Version { major }
-}
-
- - - -
- -
-Specification - - - -
aborts_if false;
-
- - - -
- - - -## Function `get` - -Get version under addr. - - -
public fun get(addr: address): u64
-
- - - -
-Implementation - - -
public fun get(addr: address): u64 {
-    let version = Config::get_by_address<Self::Version>(addr);
-    version.major
-}
-
- - - -
- -
-Specification - - - -
aborts_if !exists<Config::Config<Version>>(addr);
-
- - - -
- - - -## Module Specification - - - -
pragma verify;
-pragma aborts_if_is_strict;
-
diff --git a/release/v12/docs/YieldFarming.md b/release/v12/docs/YieldFarming.md deleted file mode 100644 index e1535fd0..00000000 --- a/release/v12/docs/YieldFarming.md +++ /dev/null @@ -1,886 +0,0 @@ - - - -# Module `0x1::YieldFarming` - - - -- [Resource `Farming`](#0x1_YieldFarming_Farming) -- [Resource `FarmingAsset`](#0x1_YieldFarming_FarmingAsset) -- [Resource `ParameterModifyCapability`](#0x1_YieldFarming_ParameterModifyCapability) -- [Resource `Stake`](#0x1_YieldFarming_Stake) -- [Struct `Exp`](#0x1_YieldFarming_Exp) -- [Constants](#@Constants_0) -- [Function `exp`](#0x1_YieldFarming_exp) -- [Function `mul_u128`](#0x1_YieldFarming_mul_u128) -- [Function `div_u128`](#0x1_YieldFarming_div_u128) -- [Function `truncate`](#0x1_YieldFarming_truncate) -- [Function `initialize`](#0x1_YieldFarming_initialize) -- [Function `initialize_asset`](#0x1_YieldFarming_initialize_asset) -- [Function `modify_parameter`](#0x1_YieldFarming_modify_parameter) -- [Function `stake`](#0x1_YieldFarming_stake) -- [Function `unstake`](#0x1_YieldFarming_unstake) -- [Function `harvest`](#0x1_YieldFarming_harvest) -- [Function `query_gov_token_amount`](#0x1_YieldFarming_query_gov_token_amount) -- [Function `query_total_stake`](#0x1_YieldFarming_query_total_stake) -- [Function `query_stake`](#0x1_YieldFarming_query_stake) -- [Function `calculate_harvest_index_with_asset`](#0x1_YieldFarming_calculate_harvest_index_with_asset) -- [Function `calculate_harvest_index_weight_zero`](#0x1_YieldFarming_calculate_harvest_index_weight_zero) -- [Function `calculate_harvest_index`](#0x1_YieldFarming_calculate_harvest_index) -- [Function `calculate_withdraw_amount`](#0x1_YieldFarming_calculate_withdraw_amount) -- [Function `exists_at`](#0x1_YieldFarming_exists_at) -- [Function `exists_asset_at`](#0x1_YieldFarming_exists_asset_at) -- [Function `exists_stake_at_address`](#0x1_YieldFarming_exists_stake_at_address) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Token;
-
- - - - - -## Resource `Farming` - -The object of yield farming -RewardTokenT meaning token of yield farming - - -
struct Farming<PoolType, RewardTokenT> has store, key
-
- - - -
-Fields - - -
-
-treasury_token: Token::Token<RewardTokenT> -
-
- -
-
- - -
- - - -## Resource `FarmingAsset` - - - -
struct FarmingAsset<PoolType, AssetT> has store, key
-
- - - -
-Fields - - -
-
-asset_total_weight: u128 -
-
- -
-
-harvest_index: u128 -
-
- -
-
-last_update_timestamp: u64 -
-
- -
-
-release_per_second: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
- - -
- - - -## Resource `ParameterModifyCapability` - -Capability to modify parameter such as period and release amount - - -
struct ParameterModifyCapability<PoolType, AssetT> has store, key
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `Stake` - -To store user's asset token - - -
struct Stake<PoolType, AssetT> has store, key
-
- - - -
-Fields - - -
-
-asset: AssetT -
-
- -
-
-asset_weight: u128 -
-
- -
-
-last_harvest_index: u128 -
-
- -
-
-gain: u128 -
-
- -
-
- - -
- - - -## Struct `Exp` - - - -
struct Exp has copy, drop, store
-
- - - -
-Fields - - -
-
-mantissa: u128 -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const EDEPRECATED_FUNCTION: u64 = 19;
-
- - - - - - - -
const ERR_EXP_DIVIDE_BY_ZERO: u64 = 107;
-
- - - - - - - -
const ERR_FARMING_BALANCE_EXCEEDED: u64 = 108;
-
- - - - - - - -
const ERR_FARMING_HAVERST_NO_GAIN: u64 = 105;
-
- - - - - - - -
const ERR_FARMING_INIT_REPEATE: u64 = 101;
-
- - - - - - - -
const ERR_FARMING_NOT_ENOUGH_ASSET: u64 = 109;
-
- - - - - - - -
const ERR_FARMING_NOT_STILL_FREEZE: u64 = 102;
-
- - - - - - - -
const ERR_FARMING_STAKE_EXISTS: u64 = 103;
-
- - - - - - - -
const ERR_FARMING_STAKE_NOT_EXISTS: u64 = 104;
-
- - - - - - - -
const ERR_FARMING_TIMESTAMP_INVALID: u64 = 110;
-
- - - - - - - -
const ERR_FARMING_TOTAL_WEIGHT_IS_ZERO: u64 = 106;
-
- - - - - - - -
const EXP_SCALE: u128 = 1000000000000000000;
-
- - - - - -## Function `exp` - - - -
fun exp(num: u128, denom: u128): YieldFarming::Exp
-
- - - -
-Implementation - - -
fun exp(num: u128, denom: u128): Exp {
-    // if overflow move will abort
-    let scaledNumerator = mul_u128(num, EXP_SCALE);
-    let rational = div_u128(scaledNumerator, denom);
-    Exp {
-        mantissa: rational
-    }
-}
-
- - - -
- - - -## Function `mul_u128` - - - -
fun mul_u128(a: u128, b: u128): u128
-
- - - -
-Implementation - - -
fun mul_u128(a: u128, b: u128): u128 {
-    if (a == 0 || b == 0) {
-        return 0
-    };
-
-    a * b
-}
-
- - - -
- - - -## Function `div_u128` - - - -
fun div_u128(a: u128, b: u128): u128
-
- - - -
-Implementation - - -
fun div_u128(a: u128, b: u128): u128 {
-    if ( b == 0) {
-        abort Errors::invalid_argument(ERR_EXP_DIVIDE_BY_ZERO)
-    };
-    if (a == 0) {
-        return 0
-    };
-    a / b
-}
-
- - - -
- - - -## Function `truncate` - - - -
fun truncate(exp: YieldFarming::Exp): u128
-
- - - -
-Implementation - - -
fun truncate(exp: Exp): u128 {
-    return exp.mantissa / EXP_SCALE
-}
-
- - - -
- - - -## Function `initialize` - -Called by token issuer -this will declare a yield farming pool - - -
public fun initialize<PoolType: store, RewardTokenT: store>(_account: &signer, _treasury_token: Token::Token<RewardTokenT>)
-
- - - -
-Implementation - - -
public fun initialize<
-    PoolType: store,
-    RewardTokenT: store>(_account: &signer,
-                         _treasury_token: Token::Token<RewardTokenT>) {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- - - -## Function `initialize_asset` - - - -
public fun initialize_asset<PoolType: store, AssetT: store>(_account: &signer, _release_per_second: u128, _delay: u64): YieldFarming::ParameterModifyCapability<PoolType, AssetT>
-
- - - -
-Implementation - - -
public fun initialize_asset<PoolType: store, AssetT: store>(
-    _account: &signer,
-    _release_per_second: u128,
-    _delay: u64): ParameterModifyCapability<PoolType, AssetT> {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- - - -## Function `modify_parameter` - - - -
public fun modify_parameter<PoolType: store, RewardTokenT: store, AssetT: store>(_cap: &YieldFarming::ParameterModifyCapability<PoolType, AssetT>, _broker: address, _release_per_second: u128)
-
- - - -
-Implementation - - -
public fun modify_parameter<PoolType: store, RewardTokenT: store, AssetT: store>(
-    _cap: &ParameterModifyCapability<PoolType, AssetT>,
-    _broker: address,
-    _release_per_second: u128) {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- - - -## Function `stake` - -Call by stake user, staking amount of asset in order to get yield farming token - - -
public fun stake<PoolType: store, RewardTokenT: store, AssetT: store>(_account: &signer, _broker: address, _asset: AssetT, _asset_weight: u128)
-
- - - -
-Implementation - - -
public fun stake<PoolType: store, RewardTokenT: store, AssetT: store>(
-    _account: &signer,
-    _broker: address,
-    _asset: AssetT,
-    _asset_weight: u128) {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- - - -## Function `unstake` - -Unstake asset from farming pool - - -
public fun unstake<PoolType: store, RewardTokenT: store, AssetT: store>(_account: &signer, _broker: address): (AssetT, Token::Token<RewardTokenT>)
-
- - - -
-Implementation - - -
public fun unstake<PoolType: store, RewardTokenT: store, AssetT: store>(_account: &signer, _broker: address)
-: (AssetT, Token::Token<RewardTokenT>) {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- - - -## Function `harvest` - -Harvest yield farming token from stake - - -
public fun harvest<PoolType: store, RewardTokenT: store, AssetT: store>(_account: &signer, _broker: address, _amount: u128): Token::Token<RewardTokenT>
-
- - - -
-Implementation - - -
public fun harvest<PoolType: store,
-                   RewardTokenT: store,
-                   AssetT: store>(
-    _account: &signer,
-    _broker: address,
-    _amount: u128): Token::Token<RewardTokenT> {
-    abort Errors::deprecated(EDEPRECATED_FUNCTION)
-}
-
- - - -
- - - -## Function `query_gov_token_amount` - -The user can quering all yield farming amount in any time and scene - - -
public fun query_gov_token_amount<PoolType: store, RewardTokenT: store, AssetT: store>(_account: &signer, _broker: address): u128
-
- - - -
-Implementation - - -
public fun query_gov_token_amount<PoolType: store,
-                                  RewardTokenT: store,
-                                  AssetT: store>(_account: &signer, _broker: address): u128 {
-    0
-}
-
- - - -
- - - -## Function `query_total_stake` - -Query total stake count from yield farming resource - - -
public fun query_total_stake<PoolType: store, AssetT: store>(_broker: address): u128
-
- - - -
-Implementation - - -
public fun query_total_stake<PoolType: store,
-                             AssetT: store>(_broker: address): u128 {
-    0
-}
-
- - - -
- - - -## Function `query_stake` - -Query stake weight from user staking objects. - - -
public fun query_stake<PoolType: store, AssetT: store>(_account: &signer): u128
-
- - - -
-Implementation - - -
public fun query_stake<PoolType: store,
-                       AssetT: store>(_account: &signer): u128 {
-    0
-}
-
- - - -
- - - -## Function `calculate_harvest_index_with_asset` - -Update farming asset - - -
fun calculate_harvest_index_with_asset<PoolType, AssetT>(_farming_asset: &YieldFarming::FarmingAsset<PoolType, AssetT>, _now_seconds: u64): u128
-
- - - -
-Implementation - - -
fun calculate_harvest_index_with_asset<PoolType, AssetT>(_farming_asset: &FarmingAsset<PoolType, AssetT>, _now_seconds: u64): u128 {
-    0
-}
-
- - - -
- - - -## Function `calculate_harvest_index_weight_zero` - -There is calculating from harvest index and global parameters without asset_total_weight - - -
public fun calculate_harvest_index_weight_zero(_harvest_index: u128, _last_update_timestamp: u64, _now_seconds: u64, _release_per_second: u128): u128
-
- - - -
-Implementation - - -
public fun calculate_harvest_index_weight_zero(_harvest_index: u128,
-                                               _last_update_timestamp: u64,
-                                               _now_seconds: u64,
-                                               _release_per_second: u128): u128 {
-    0
-}
-
- - - -
- - - -## Function `calculate_harvest_index` - -There is calculating from harvest index and global parameters - - -
public fun calculate_harvest_index(_harvest_index: u128, _asset_total_weight: u128, _last_update_timestamp: u64, _now_seconds: u64, _release_per_second: u128): u128
-
- - - -
-Implementation - - -
public fun calculate_harvest_index(_harvest_index: u128,
-                                   _asset_total_weight: u128,
-                                   _last_update_timestamp: u64,
-                                   _now_seconds: u64,
-                                   _release_per_second: u128): u128 {
-    0
-}
-
- - - -
- - - -## Function `calculate_withdraw_amount` - -This function will return a gain index - - -
public fun calculate_withdraw_amount(_harvest_index: u128, _last_harvest_index: u128, _asset_weight: u128): u128
-
- - - -
-Implementation - - -
public fun calculate_withdraw_amount(_harvest_index: u128,
-                                     _last_harvest_index: u128,
-                                     _asset_weight: u128): u128 {
-    0
-}
-
- - - -
- - - -## Function `exists_at` - -Check the Farming of TokenT is exists. - - -
public fun exists_at<PoolType: store, RewardTokenT: store>(broker: address): bool
-
- - - -
-Implementation - - -
public fun exists_at<PoolType: store, RewardTokenT: store>(broker: address): bool {
-    exists<Farming<PoolType, RewardTokenT>>(broker)
-}
-
- - - -
- - - -## Function `exists_asset_at` - -Check the Farming of AsssetT is exists. - - -
public fun exists_asset_at<PoolType: store, AssetT: store>(broker: address): bool
-
- - - -
-Implementation - - -
public fun exists_asset_at<PoolType: store, AssetT: store>(broker: address): bool {
-    exists<FarmingAsset<PoolType, AssetT>>(broker)
-}
-
- - - -
- - - -## Function `exists_stake_at_address` - -Check stake at address exists. - - -
public fun exists_stake_at_address<PoolType: store, AssetT: store>(account: address): bool
-
- - - -
-Implementation - - -
public fun exists_stake_at_address<PoolType: store, AssetT: store>(account: address): bool {
-    exists<Stake<PoolType, AssetT>>(account)
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-
diff --git a/release/v12/docs/YieldFarmingV2.md b/release/v12/docs/YieldFarmingV2.md deleted file mode 100644 index f6d77651..00000000 --- a/release/v12/docs/YieldFarmingV2.md +++ /dev/null @@ -1,1429 +0,0 @@ - - - -# Module `0x1::YieldFarmingV2` - - - -- [Struct `Exp`](#0x1_YieldFarmingV2_Exp) -- [Resource `Farming`](#0x1_YieldFarmingV2_Farming) -- [Resource `FarmingAsset`](#0x1_YieldFarmingV2_FarmingAsset) -- [Resource `Stake`](#0x1_YieldFarmingV2_Stake) -- [Resource `ParameterModifyCapability`](#0x1_YieldFarmingV2_ParameterModifyCapability) -- [Resource `HarvestCapability`](#0x1_YieldFarmingV2_HarvestCapability) -- [Constants](#@Constants_0) -- [Function `exp_direct`](#0x1_YieldFarmingV2_exp_direct) -- [Function `exp_direct_expand`](#0x1_YieldFarmingV2_exp_direct_expand) -- [Function `mantissa`](#0x1_YieldFarmingV2_mantissa) -- [Function `add_exp`](#0x1_YieldFarmingV2_add_exp) -- [Function `exp`](#0x1_YieldFarmingV2_exp) -- [Function `add_u128`](#0x1_YieldFarmingV2_add_u128) -- [Function `sub_u128`](#0x1_YieldFarmingV2_sub_u128) -- [Function `mul_u128`](#0x1_YieldFarmingV2_mul_u128) -- [Function `div_u128`](#0x1_YieldFarmingV2_div_u128) -- [Function `truncate`](#0x1_YieldFarmingV2_truncate) -- [Function `initialize`](#0x1_YieldFarmingV2_initialize) -- [Function `add_asset`](#0x1_YieldFarmingV2_add_asset) -- [Function `modify_parameter`](#0x1_YieldFarmingV2_modify_parameter) -- [Function `stake`](#0x1_YieldFarmingV2_stake) -- [Function `stake_for_cap`](#0x1_YieldFarmingV2_stake_for_cap) -- [Function `unstake`](#0x1_YieldFarmingV2_unstake) -- [Function `unstake_with_cap`](#0x1_YieldFarmingV2_unstake_with_cap) -- [Function `harvest`](#0x1_YieldFarmingV2_harvest) -- [Function `harvest_with_cap`](#0x1_YieldFarmingV2_harvest_with_cap) -- [Function `query_gov_token_amount`](#0x1_YieldFarmingV2_query_gov_token_amount) -- [Function `query_total_stake`](#0x1_YieldFarmingV2_query_total_stake) -- [Function `query_stake`](#0x1_YieldFarmingV2_query_stake) -- [Function `query_info`](#0x1_YieldFarmingV2_query_info) -- [Function `calculate_harvest_index_with_asset`](#0x1_YieldFarmingV2_calculate_harvest_index_with_asset) -- [Function `calculate_harvest_index_weight_zero`](#0x1_YieldFarmingV2_calculate_harvest_index_weight_zero) -- [Function `calculate_harvest_index`](#0x1_YieldFarmingV2_calculate_harvest_index) -- [Function `calculate_withdraw_amount`](#0x1_YieldFarmingV2_calculate_withdraw_amount) -- [Function `exists_at`](#0x1_YieldFarmingV2_exists_at) -- [Function `exists_asset_at`](#0x1_YieldFarmingV2_exists_asset_at) -- [Function `exists_stake_at_address`](#0x1_YieldFarmingV2_exists_stake_at_address) -- [Module Specification](#@Module_Specification_1) - - -
use 0x1::Errors;
-use 0x1::Math;
-use 0x1::Signer;
-use 0x1::Timestamp;
-use 0x1::Token;
-
- - - - - -## Struct `Exp` - - - -
struct Exp has copy, drop, store
-
- - - -
-Fields - - -
-
-mantissa: u128 -
-
- -
-
- - -
- - - -## Resource `Farming` - -The object of yield farming -RewardTokenT meaning token of yield farming - - -
struct Farming<PoolType, RewardTokenT> has store, key
-
- - - -
-Fields - - -
-
-treasury_token: Token::Token<RewardTokenT> -
-
- -
-
- - -
- - - -## Resource `FarmingAsset` - - - -
struct FarmingAsset<PoolType, AssetT> has store, key
-
- - - -
-Fields - - -
-
-asset_total_weight: u128 -
-
- -
-
-harvest_index: u128 -
-
- -
-
-last_update_timestamp: u64 -
-
- -
-
-release_per_second: u128 -
-
- -
-
-start_time: u64 -
-
- -
-
-alive: bool -
-
- -
-
- - -
- - - -## Resource `Stake` - -To store user's asset token - - -
struct Stake<PoolType, AssetT> has store, key
-
- - - -
-Fields - - -
-
-asset: AssetT -
-
- -
-
-asset_weight: u128 -
-
- -
-
-last_harvest_index: u128 -
-
- -
-
-gain: u128 -
-
- -
-
- - -
- - - -## Resource `ParameterModifyCapability` - -Capability to modify parameter such as period and release amount - - -
struct ParameterModifyCapability<PoolType, AssetT> has store, key
-
- - - -
-Fields - - -
-
-dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `HarvestCapability` - -Harvest ability to harvest - - -
struct HarvestCapability<PoolType, AssetT> has store, key
-
- - - -
-Fields - - -
-
-trigger: address -
-
- -
-
- - -
- - - -## Constants - - - - - - -
const ERR_EXP_DIVIDE_BY_ZERO: u64 = 107;
-
- - - - - - - -
const ERR_FARMING_BALANCE_EXCEEDED: u64 = 108;
-
- - - - - - - -
const ERR_FARMING_HAVERST_NO_GAIN: u64 = 105;
-
- - - - - - - -
const ERR_FARMING_INIT_REPEATE: u64 = 101;
-
- - - - - - - -
const ERR_FARMING_NOT_ENOUGH_ASSET: u64 = 109;
-
- - - - - - - -
const ERR_FARMING_NOT_STILL_FREEZE: u64 = 102;
-
- - - - - - - -
const ERR_FARMING_STAKE_EXISTS: u64 = 103;
-
- - - - - - - -
const ERR_FARMING_STAKE_NOT_EXISTS: u64 = 104;
-
- - - - - - - -
const ERR_FARMING_TIMESTAMP_INVALID: u64 = 110;
-
- - - - - - - -
const ERR_FARMING_TOTAL_WEIGHT_IS_ZERO: u64 = 106;
-
- - - - - - - -
const EXP_SCALE: u128 = 1000000000000000000;
-
- - - - - - - -
const ERR_FARMING_ALIVE_STATE_INVALID: u64 = 114;
-
- - - - - - - -
const ERR_FARMING_CALC_LAST_IDX_BIGGER_THAN_NOW: u64 = 112;
-
- - - - - - - -
const ERR_FARMING_NOT_ALIVE: u64 = 113;
-
- - - - - - - -
const ERR_FARMING_TOKEN_SCALE_OVERFLOW: u64 = 111;
-
- - - - - - - -
const EXP_MAX_SCALE: u128 = 9;
-
- - - - - -## Function `exp_direct` - - - -
fun exp_direct(num: u128): YieldFarmingV2::Exp
-
- - - -
-Implementation - - -
fun exp_direct(num: u128): Exp {
-    Exp {
-        mantissa: num
-    }
-}
-
- - - -
- - - -## Function `exp_direct_expand` - - - -
fun exp_direct_expand(num: u128): YieldFarmingV2::Exp
-
- - - -
-Implementation - - -
fun exp_direct_expand(num: u128): Exp {
-    Exp {
-        mantissa: mul_u128(num, EXP_SCALE)
-    }
-}
-
- - - -
- - - -## Function `mantissa` - - - -
fun mantissa(a: YieldFarmingV2::Exp): u128
-
- - - -
-Implementation - - -
fun mantissa(a: Exp): u128 {
-    a.mantissa
-}
-
- - - -
- - - -## Function `add_exp` - - - -
fun add_exp(a: YieldFarmingV2::Exp, b: YieldFarmingV2::Exp): YieldFarmingV2::Exp
-
- - - -
-Implementation - - -
fun add_exp(a: Exp, b: Exp): Exp {
-    Exp {
-        mantissa: add_u128(a.mantissa, b.mantissa)
-    }
-}
-
- - - -
- - - -## Function `exp` - - - -
fun exp(num: u128, denom: u128): YieldFarmingV2::Exp
-
- - - -
-Implementation - - -
fun exp(num: u128, denom: u128): Exp {
-    // if overflow move will abort
-    let scaledNumerator = mul_u128(num, EXP_SCALE);
-    let rational = div_u128(scaledNumerator, denom);
-    Exp {
-        mantissa: rational
-    }
-}
-
- - - -
- - - -## Function `add_u128` - - - -
fun add_u128(a: u128, b: u128): u128
-
- - - -
-Implementation - - -
fun add_u128(a: u128, b: u128): u128 {
-    a + b
-}
-
- - - -
- - - -## Function `sub_u128` - - - -
fun sub_u128(a: u128, b: u128): u128
-
- - - -
-Implementation - - -
fun sub_u128(a: u128, b: u128): u128 {
-    a - b
-}
-
- - - -
- - - -## Function `mul_u128` - - - -
fun mul_u128(a: u128, b: u128): u128
-
- - - -
-Implementation - - -
fun mul_u128(a: u128, b: u128): u128 {
-    if (a == 0 || b == 0) {
-        return 0
-    };
-    a * b
-}
-
- - - -
- - - -## Function `div_u128` - - - -
fun div_u128(a: u128, b: u128): u128
-
- - - -
-Implementation - - -
fun div_u128(a: u128, b: u128): u128 {
-    if (b == 0) {
-        abort Errors::invalid_argument(ERR_EXP_DIVIDE_BY_ZERO)
-    };
-    if (a == 0) {
-        return 0
-    };
-    a / b
-}
-
- - - -
- - - -## Function `truncate` - - - -
fun truncate(exp: YieldFarmingV2::Exp): u128
-
- - - -
-Implementation - - -
fun truncate(exp: Exp): u128 {
-    return exp.mantissa / EXP_SCALE
-}
-
- - - -
- - - -## Function `initialize` - -Called by token issuer -this will declare a yield farming pool - - -
public fun initialize<PoolType: store, RewardTokenT: store>(signer: &signer, treasury_token: Token::Token<RewardTokenT>)
-
- - - -
-Implementation - - -
public fun initialize<
-    PoolType: store,
-    RewardTokenT: store>(signer: &signer, treasury_token: Token::Token<RewardTokenT>) {
-    let scaling_factor = Math::pow(10, (EXP_MAX_SCALE as u64));
-    let token_scale = Token::scaling_factor<RewardTokenT>();
-    assert!(token_scale <= scaling_factor, Errors::limit_exceeded(ERR_FARMING_TOKEN_SCALE_OVERFLOW));
-    assert!(!exists_at<PoolType, RewardTokenT>(
-        Signer::address_of(signer)), Errors::invalid_state(ERR_FARMING_INIT_REPEATE));
-
-    move_to(signer, Farming<PoolType, RewardTokenT> {
-        treasury_token,
-    });
-}
-
- - - -
- - - -## Function `add_asset` - -Add asset pools - - -
public fun add_asset<PoolType: store, AssetT: store>(signer: &signer, release_per_second: u128, delay: u64): YieldFarmingV2::ParameterModifyCapability<PoolType, AssetT>
-
- - - -
-Implementation - - -
public fun add_asset<PoolType: store, AssetT: store>(
-    signer: &signer,
-    release_per_second: u128,
-    delay: u64): ParameterModifyCapability<PoolType, AssetT> {
-    assert!(!exists_asset_at<PoolType, AssetT>(
-        Signer::address_of(signer)),
-        Errors::invalid_state(ERR_FARMING_INIT_REPEATE));
-
-    let now_seconds = Timestamp::now_seconds();
-
-    move_to(signer, FarmingAsset<PoolType, AssetT> {
-        asset_total_weight: 0,
-        harvest_index: 0,
-        last_update_timestamp: now_seconds,
-        release_per_second,
-        start_time: now_seconds + delay,
-        alive: true
-    });
-    ParameterModifyCapability<PoolType, AssetT> {}
-}
-
- - - -
- - - -## Function `modify_parameter` - -Remove asset for make this pool to the state of not alive -Please make sure all user unstaking from this pool - - -
public fun modify_parameter<PoolType: store, RewardTokenT: store, AssetT: store>(_cap: &YieldFarmingV2::ParameterModifyCapability<PoolType, AssetT>, broker: address, release_per_second: u128, alive: bool)
-
- - - -
-Implementation - - -
public fun modify_parameter<PoolType: store, RewardTokenT: store, AssetT: store>(
-    _cap: &ParameterModifyCapability<PoolType, AssetT>,
-    broker: address,
-    release_per_second: u128,
-    alive: bool) acquires FarmingAsset {
-
-    // Not support to shuttingdown alive state.
-    assert!(alive, Errors::invalid_state(ERR_FARMING_ALIVE_STATE_INVALID));
-
-    let farming_asset = borrow_global_mut<FarmingAsset<PoolType, AssetT>>(broker);
-    // assert!(farming_asset.alive != alive, Errors::invalid_state(ERR_FARMING_ALIVE_STATE_INVALID));
-
-    let now_seconds = Timestamp::now_seconds();
-
-    farming_asset.release_per_second = release_per_second;
-    farming_asset.last_update_timestamp = now_seconds;
-
-    // if the pool is alive, then update index
-    if (farming_asset.alive) {
-        farming_asset.harvest_index = calculate_harvest_index_with_asset<PoolType, AssetT>(farming_asset, now_seconds);
-    };
-    farming_asset.alive = alive;
-}
-
- - - -
- - - -## Function `stake` - -Call by stake user, staking amount of asset in order to get yield farming token - - -
public fun stake<PoolType: store, RewardTokenT: store, AssetT: store>(signer: &signer, broker: address, asset: AssetT, asset_weight: u128, _cap: &YieldFarmingV2::ParameterModifyCapability<PoolType, AssetT>)
-
- - - -
-Implementation - - -
public fun stake<PoolType: store, RewardTokenT: store, AssetT: store>(
-    signer: &signer,
-    broker: address,
-    asset: AssetT,
-    asset_weight: u128,
-    _cap: &ParameterModifyCapability<PoolType, AssetT>) acquires FarmingAsset {
-    let harvest_cap = stake_for_cap<
-        PoolType,
-        RewardTokenT,
-        AssetT>(signer, broker, asset, asset_weight, _cap);
-
-    move_to(signer, harvest_cap);
-}
-
- - - -
- - - -## Function `stake_for_cap` - - - -
public fun stake_for_cap<PoolType: store, RewardTokenT: store, AssetT: store>(signer: &signer, broker: address, asset: AssetT, asset_weight: u128, _cap: &YieldFarmingV2::ParameterModifyCapability<PoolType, AssetT>): YieldFarmingV2::HarvestCapability<PoolType, AssetT>
-
- - - -
-Implementation - - -
public fun stake_for_cap<PoolType: store, RewardTokenT: store, AssetT: store>(
-    signer: &signer,
-    broker: address,
-    asset: AssetT,
-    asset_weight: u128,
-    _cap: &ParameterModifyCapability<PoolType, AssetT>)
-: HarvestCapability<PoolType, AssetT> acquires FarmingAsset {
-    let account = Signer::address_of(signer);
-    assert!(!exists_stake_at_address<PoolType, AssetT>(account),
-        Errors::invalid_state(ERR_FARMING_STAKE_EXISTS));
-
-    let farming_asset = borrow_global_mut<FarmingAsset<PoolType, AssetT>>(broker);
-    assert!(farming_asset.alive, Errors::invalid_state(ERR_FARMING_NOT_ALIVE));
-
-    // Check locking time
-    let now_seconds = Timestamp::now_seconds();
-    assert!(farming_asset.start_time <= now_seconds, Errors::invalid_state(ERR_FARMING_NOT_STILL_FREEZE));
-
-    let time_period = now_seconds - farming_asset.last_update_timestamp;
-
-    if (farming_asset.asset_total_weight <= 0) {
-        // Stake as first user
-        let gain = farming_asset.release_per_second * (time_period as u128);
-        move_to(signer, Stake<PoolType, AssetT> {
-            asset,
-            asset_weight,
-            last_harvest_index: 0,
-            gain,
-        });
-        farming_asset.harvest_index = 0;
-        farming_asset.asset_total_weight = asset_weight;
-    } else {
-        let new_harvest_index = calculate_harvest_index_with_asset<PoolType, AssetT>(farming_asset, now_seconds);
-        move_to(signer, Stake<PoolType, AssetT> {
-            asset,
-            asset_weight,
-            last_harvest_index: new_harvest_index,
-            gain: 0,
-        });
-        farming_asset.asset_total_weight = farming_asset.asset_total_weight + asset_weight;
-        farming_asset.harvest_index = new_harvest_index;
-    };
-    farming_asset.last_update_timestamp = now_seconds;
-    HarvestCapability<PoolType, AssetT> { trigger: account }
-}
-
- - - -
- - - -## Function `unstake` - -Unstake asset from farming pool - - -
public fun unstake<PoolType: store, RewardTokenT: store, AssetT: store>(signer: &signer, broker: address): (AssetT, Token::Token<RewardTokenT>)
-
- - - -
-Implementation - - -
public fun unstake<PoolType: store, RewardTokenT: store, AssetT: store>(
-    signer: &signer,
-    broker: address)
-: (AssetT, Token::Token<RewardTokenT>) acquires HarvestCapability, Farming, FarmingAsset, Stake {
-    let account = Signer::address_of(signer);
-    let cap = move_from<HarvestCapability<PoolType, AssetT>>(account);
-    unstake_with_cap(broker, cap)
-}
-
- - - -
- - - -## Function `unstake_with_cap` - - - -
public fun unstake_with_cap<PoolType: store, RewardTokenT: store, AssetT: store>(broker: address, cap: YieldFarmingV2::HarvestCapability<PoolType, AssetT>): (AssetT, Token::Token<RewardTokenT>)
-
- - - -
-Implementation - - -
public fun unstake_with_cap<PoolType: store, RewardTokenT: store, AssetT: store>(
-    broker: address,
-    cap: HarvestCapability<PoolType, AssetT>)
-: (AssetT, Token::Token<RewardTokenT>) acquires Farming, FarmingAsset, Stake {
-    // Destroy capability
-    let HarvestCapability<PoolType, AssetT> { trigger } = cap;
-
-    let farming = borrow_global_mut<Farming<PoolType, RewardTokenT>>(broker);
-    let farming_asset = borrow_global_mut<FarmingAsset<PoolType, AssetT>>(broker);
-
-    let Stake<PoolType, AssetT> { last_harvest_index, asset_weight, asset, gain } =
-        move_from<Stake<PoolType, AssetT>>(trigger);
-
-    let now_seconds = Timestamp::now_seconds();
-    let new_harvest_index = calculate_harvest_index_with_asset<PoolType, AssetT>(farming_asset, now_seconds);
-
-    let period_gain = calculate_withdraw_amount(new_harvest_index, last_harvest_index, asset_weight);
-    let total_gain = gain + period_gain;
-    let withdraw_token = Token::withdraw<RewardTokenT>(&mut farming.treasury_token, total_gain);
-
-    // Dont update harvest index that because the `Stake` object has droped.
-    // let new_index = calculate_harvest_index_with_asset<PoolType, AssetT>(farming_asset, now_seconds);
-    assert!(farming_asset.asset_total_weight >= asset_weight, Errors::invalid_state(ERR_FARMING_NOT_ENOUGH_ASSET));
-
-    // Update farm asset
-    farming_asset.asset_total_weight = farming_asset.asset_total_weight - asset_weight;
-    farming_asset.last_update_timestamp = now_seconds;
-
-    if (farming_asset.alive) {
-        farming_asset.harvest_index = new_harvest_index;
-    };
-
-    (asset, withdraw_token)
-}
-
- - - -
- - - -## Function `harvest` - -Harvest yield farming token from stake - - -
public fun harvest<PoolType: store, RewardTokenT: store, AssetT: store>(signer: &signer, broker: address, amount: u128): Token::Token<RewardTokenT>
-
- - - -
-Implementation - - -
public fun harvest<PoolType: store,
-                   RewardTokenT: store,
-                   AssetT: store>(
-    signer: &signer,
-    broker: address,
-    amount: u128) : Token::Token<RewardTokenT> acquires HarvestCapability, Farming, FarmingAsset, Stake {
-    let account = Signer::address_of(signer);
-    let cap = borrow_global_mut<HarvestCapability<PoolType, AssetT>>(account);
-    harvest_with_cap(broker, amount, cap)
-}
-
- - - -
- - - -## Function `harvest_with_cap` - - - -
public fun harvest_with_cap<PoolType: store, RewardTokenT: store, AssetT: store>(broker: address, amount: u128, _cap: &YieldFarmingV2::HarvestCapability<PoolType, AssetT>): Token::Token<RewardTokenT>
-
- - - -
-Implementation - - -
public fun harvest_with_cap<PoolType: store,
-                            RewardTokenT: store,
-                            AssetT: store>(
-    broker: address,
-    amount: u128,
-    _cap: &HarvestCapability<PoolType, AssetT>): Token::Token<RewardTokenT> acquires Farming, FarmingAsset, Stake {
-    let farming = borrow_global_mut<Farming<PoolType, RewardTokenT>>(broker);
-    let farming_asset = borrow_global_mut<FarmingAsset<PoolType, AssetT>>(broker);
-    let stake = borrow_global_mut<Stake<PoolType, AssetT>>(_cap.trigger);
-
-    let now_seconds = Timestamp::now_seconds();
-    let new_harvest_index = calculate_harvest_index_with_asset<PoolType, AssetT>(farming_asset, now_seconds);
-
-    let period_gain = calculate_withdraw_amount(
-        new_harvest_index,
-        stake.last_harvest_index,
-        stake.asset_weight
-    );
-
-    let total_gain = stake.gain + period_gain;
-    //assert!(total_gain > 0, Errors::limit_exceeded(ERR_FARMING_HAVERST_NO_GAIN));
-    assert!(total_gain >= amount, Errors::limit_exceeded(ERR_FARMING_BALANCE_EXCEEDED));
-
-    let withdraw_amount = if (amount <= 0) {
-        total_gain
-    } else {
-        amount
-    };
-
-    let withdraw_token = Token::withdraw<RewardTokenT>(&mut farming.treasury_token, withdraw_amount);
-    stake.gain = total_gain - withdraw_amount;
-    stake.last_harvest_index = new_harvest_index;
-
-    if (farming_asset.alive) {
-        farming_asset.harvest_index = new_harvest_index;
-    };
-    farming_asset.last_update_timestamp = now_seconds;
-
-    withdraw_token
-}
-
- - - -
- - - -## Function `query_gov_token_amount` - -The user can quering all yield farming amount in any time and scene - - -
public fun query_gov_token_amount<PoolType: store, RewardTokenT: store, AssetT: store>(account: address, broker: address): u128
-
- - - -
-Implementation - - -
public fun query_gov_token_amount<PoolType: store,
-                                  RewardTokenT: store,
-                                  AssetT: store>(account: address, broker: address): u128 acquires FarmingAsset, Stake {
-    let farming_asset = borrow_global_mut<FarmingAsset<PoolType, AssetT>>(broker);
-    let stake = borrow_global_mut<Stake<PoolType, AssetT>>(account);
-    let now_seconds = Timestamp::now_seconds();
-
-    let new_harvest_index = calculate_harvest_index_with_asset<PoolType, AssetT>(
-        farming_asset,
-        now_seconds
-    );
-
-    let new_gain = calculate_withdraw_amount(
-        new_harvest_index,
-        stake.last_harvest_index,
-        stake.asset_weight
-    );
-    stake.gain + new_gain
-}
-
- - - -
- - - -## Function `query_total_stake` - -Query total stake count from yield farming resource - - -
public fun query_total_stake<PoolType: store, AssetT: store>(broker: address): u128
-
- - - -
-Implementation - - -
public fun query_total_stake<PoolType: store,
-                             AssetT: store>(broker: address): u128 acquires FarmingAsset {
-    let farming_asset = borrow_global_mut<FarmingAsset<PoolType, AssetT>>(broker);
-    farming_asset.asset_total_weight
-}
-
- - - -
- - - -## Function `query_stake` - -Query stake weight from user staking objects. - - -
public fun query_stake<PoolType: store, AssetT: store>(account: address): u128
-
- - - -
-Implementation - - -
public fun query_stake<PoolType: store,
-                       AssetT: store>(account: address): u128 acquires Stake {
-    let stake = borrow_global_mut<Stake<PoolType, AssetT>>(account);
-    stake.asset_weight
-}
-
- - - -
- - - -## Function `query_info` - -Queyry pool info from pool type -return value: (alive, release_per_second, asset_total_weight, harvest_index) - - -
public fun query_info<PoolType: store, AssetT: store>(broker: address): (bool, u128, u128, u128)
-
- - - -
-Implementation - - -
public fun query_info<PoolType: store, AssetT: store>(broker: address): (bool, u128, u128, u128) acquires FarmingAsset {
-    let asset = borrow_global_mut<FarmingAsset<PoolType, AssetT>>(broker);
-    (
-        asset.alive,
-        asset.release_per_second,
-        asset.asset_total_weight,
-        asset.harvest_index
-    )
-}
-
- - - -
- - - -## Function `calculate_harvest_index_with_asset` - -Update farming asset - - -
fun calculate_harvest_index_with_asset<PoolType, AssetT>(farming_asset: &YieldFarmingV2::FarmingAsset<PoolType, AssetT>, now_seconds: u64): u128
-
- - - -
-Implementation - - -
fun calculate_harvest_index_with_asset<PoolType, AssetT>(farming_asset: &FarmingAsset<PoolType, AssetT>, now_seconds: u64): u128 {
-    // Recalculate harvest index
-    if (farming_asset.asset_total_weight <= 0) {
-        calculate_harvest_index_weight_zero(
-            farming_asset.harvest_index,
-            farming_asset.last_update_timestamp,
-            now_seconds,
-            farming_asset.release_per_second
-        )
-    } else {
-        calculate_harvest_index(
-            farming_asset.harvest_index,
-            farming_asset.asset_total_weight,
-            farming_asset.last_update_timestamp,
-            now_seconds,
-            farming_asset.release_per_second
-        )
-    }
-}
-
- - - -
- - - -## Function `calculate_harvest_index_weight_zero` - -There is calculating from harvest index and global parameters without asset_total_weight - - -
public fun calculate_harvest_index_weight_zero(harvest_index: u128, last_update_timestamp: u64, now_seconds: u64, release_per_second: u128): u128
-
- - - -
-Implementation - - -
public fun calculate_harvest_index_weight_zero(harvest_index: u128,
-                                               last_update_timestamp: u64,
-                                               now_seconds: u64,
-                                               release_per_second: u128): u128 {
-    assert!(last_update_timestamp <= now_seconds, Errors::invalid_argument(ERR_FARMING_TIMESTAMP_INVALID));
-    let time_period = now_seconds - last_update_timestamp;
-    let addtion_index = release_per_second * ((time_period as u128));
-    harvest_index + mantissa(exp_direct_expand(addtion_index))
-}
-
- - - -
- - - -## Function `calculate_harvest_index` - -There is calculating from harvest index and global parameters - - -
public fun calculate_harvest_index(harvest_index: u128, asset_total_weight: u128, last_update_timestamp: u64, now_seconds: u64, release_per_second: u128): u128
-
- - - -
-Implementation - - -
public fun calculate_harvest_index(harvest_index: u128,
-                                   asset_total_weight: u128,
-                                   last_update_timestamp: u64,
-                                   now_seconds: u64,
-                                   release_per_second: u128): u128 {
-    assert!(asset_total_weight > 0, Errors::invalid_argument(ERR_FARMING_TOTAL_WEIGHT_IS_ZERO));
-    assert!(last_update_timestamp <= now_seconds, Errors::invalid_argument(ERR_FARMING_TIMESTAMP_INVALID));
-
-    let time_period = now_seconds - last_update_timestamp;
-    let numr = (release_per_second * (time_period as u128));
-    let denom = asset_total_weight;
-    harvest_index + mantissa(exp(numr, denom))
-}
-
- - - -
- - - -## Function `calculate_withdraw_amount` - -This function will return a gain index - - -
public fun calculate_withdraw_amount(harvest_index: u128, last_harvest_index: u128, asset_weight: u128): u128
-
- - - -
-Implementation - - -
public fun calculate_withdraw_amount(harvest_index: u128,
-                                     last_harvest_index: u128,
-                                     asset_weight: u128): u128 {
-    assert!(harvest_index >= last_harvest_index, Errors::invalid_argument(ERR_FARMING_CALC_LAST_IDX_BIGGER_THAN_NOW));
-    let amount = asset_weight * (harvest_index - last_harvest_index);
-    truncate(exp_direct(amount))
-}
-
- - - -
- - - -## Function `exists_at` - -Check the Farming of TokenT is exists. - - -
public fun exists_at<PoolType: store, RewardTokenT: store>(broker: address): bool
-
- - - -
-Implementation - - -
public fun exists_at<PoolType: store, RewardTokenT: store>(broker: address): bool {
-    exists<Farming<PoolType, RewardTokenT>>(broker)
-}
-
- - - -
- - - -## Function `exists_asset_at` - -Check the Farming of AsssetT is exists. - - -
public fun exists_asset_at<PoolType: store, AssetT: store>(broker: address): bool
-
- - - -
-Implementation - - -
public fun exists_asset_at<PoolType: store, AssetT: store>(broker: address): bool {
-    exists<FarmingAsset<PoolType, AssetT>>(broker)
-}
-
- - - -
- - - -## Function `exists_stake_at_address` - -Check stake at address exists. - - -
public fun exists_stake_at_address<PoolType: store, AssetT: store>(account: address): bool
-
- - - -
-Implementation - - -
public fun exists_stake_at_address<PoolType: store, AssetT: store>(account: address): bool {
-    exists<Stake<PoolType, AssetT>>(account)
-}
-
- - - -
- - - -## Module Specification - - - -
pragma verify = false;
-
diff --git a/release/v12/source_maps/ASCII.mvsm b/release/v12/source_maps/ASCII.mvsm deleted file mode 100644 index 00902e84..00000000 Binary files a/release/v12/source_maps/ASCII.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Account.mvsm b/release/v12/source_maps/Account.mvsm deleted file mode 100644 index 9822a3e3..00000000 Binary files a/release/v12/source_maps/Account.mvsm and /dev/null differ diff --git a/release/v12/source_maps/AccountScripts.mvsm b/release/v12/source_maps/AccountScripts.mvsm deleted file mode 100644 index 58f14083..00000000 Binary files a/release/v12/source_maps/AccountScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/AnyMemberPlugin.mvsm b/release/v12/source_maps/AnyMemberPlugin.mvsm deleted file mode 100644 index b3f2257e..00000000 Binary files a/release/v12/source_maps/AnyMemberPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Arith.mvsm b/release/v12/source_maps/Arith.mvsm deleted file mode 100644 index 2d249cc2..00000000 Binary files a/release/v12/source_maps/Arith.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Authenticator.mvsm b/release/v12/source_maps/Authenticator.mvsm deleted file mode 100644 index a76afa8e..00000000 Binary files a/release/v12/source_maps/Authenticator.mvsm and /dev/null differ diff --git a/release/v12/source_maps/BCS.mvsm b/release/v12/source_maps/BCS.mvsm deleted file mode 100644 index b6cf0c12..00000000 Binary files a/release/v12/source_maps/BCS.mvsm and /dev/null differ diff --git a/release/v12/source_maps/BitOperators.mvsm b/release/v12/source_maps/BitOperators.mvsm deleted file mode 100644 index b0aefd58..00000000 Binary files a/release/v12/source_maps/BitOperators.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Block.mvsm b/release/v12/source_maps/Block.mvsm deleted file mode 100644 index dee05fbb..00000000 Binary files a/release/v12/source_maps/Block.mvsm and /dev/null differ diff --git a/release/v12/source_maps/BlockReward.mvsm b/release/v12/source_maps/BlockReward.mvsm deleted file mode 100644 index e8e01b8b..00000000 Binary files a/release/v12/source_maps/BlockReward.mvsm and /dev/null differ diff --git a/release/v12/source_maps/ChainId.mvsm b/release/v12/source_maps/ChainId.mvsm deleted file mode 100644 index 24fc09e8..00000000 Binary files a/release/v12/source_maps/ChainId.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Collection.mvsm b/release/v12/source_maps/Collection.mvsm deleted file mode 100644 index 39570537..00000000 Binary files a/release/v12/source_maps/Collection.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Collection2.mvsm b/release/v12/source_maps/Collection2.mvsm deleted file mode 100644 index f344b7b8..00000000 Binary files a/release/v12/source_maps/Collection2.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Compare.mvsm b/release/v12/source_maps/Compare.mvsm deleted file mode 100644 index 27000bfa..00000000 Binary files a/release/v12/source_maps/Compare.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Config.mvsm b/release/v12/source_maps/Config.mvsm deleted file mode 100644 index f17f771b..00000000 Binary files a/release/v12/source_maps/Config.mvsm and /dev/null differ diff --git a/release/v12/source_maps/ConfigProposalPlugin.mvsm b/release/v12/source_maps/ConfigProposalPlugin.mvsm deleted file mode 100644 index d433c503..00000000 Binary files a/release/v12/source_maps/ConfigProposalPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/ConsensusConfig.mvsm b/release/v12/source_maps/ConsensusConfig.mvsm deleted file mode 100644 index a50dd53c..00000000 Binary files a/release/v12/source_maps/ConsensusConfig.mvsm and /dev/null differ diff --git a/release/v12/source_maps/ConsensusStrategy.mvsm b/release/v12/source_maps/ConsensusStrategy.mvsm deleted file mode 100644 index ad7218db..00000000 Binary files a/release/v12/source_maps/ConsensusStrategy.mvsm and /dev/null differ diff --git a/release/v12/source_maps/CoreAddresses.mvsm b/release/v12/source_maps/CoreAddresses.mvsm deleted file mode 100644 index 9c738c26..00000000 Binary files a/release/v12/source_maps/CoreAddresses.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DAOAccount.mvsm b/release/v12/source_maps/DAOAccount.mvsm deleted file mode 100644 index 84bb114a..00000000 Binary files a/release/v12/source_maps/DAOAccount.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DAOExtensionPoint.mvsm b/release/v12/source_maps/DAOExtensionPoint.mvsm deleted file mode 100644 index 2681d3ee..00000000 Binary files a/release/v12/source_maps/DAOExtensionPoint.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DAOPluginMarketplace.mvsm b/release/v12/source_maps/DAOPluginMarketplace.mvsm deleted file mode 100644 index 17cc781b..00000000 Binary files a/release/v12/source_maps/DAOPluginMarketplace.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DAORegistry.mvsm b/release/v12/source_maps/DAORegistry.mvsm deleted file mode 100644 index 7205d047..00000000 Binary files a/release/v12/source_maps/DAORegistry.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DAOSpace.mvsm b/release/v12/source_maps/DAOSpace.mvsm deleted file mode 100644 index 5354ff2f..00000000 Binary files a/release/v12/source_maps/DAOSpace.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Dao.mvsm b/release/v12/source_maps/Dao.mvsm deleted file mode 100644 index 1907c094..00000000 Binary files a/release/v12/source_maps/Dao.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DaoVoteScripts.mvsm b/release/v12/source_maps/DaoVoteScripts.mvsm deleted file mode 100644 index 9b109228..00000000 Binary files a/release/v12/source_maps/DaoVoteScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Debug.mvsm b/release/v12/source_maps/Debug.mvsm deleted file mode 100644 index c9280d83..00000000 Binary files a/release/v12/source_maps/Debug.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DummyToken.mvsm b/release/v12/source_maps/DummyToken.mvsm deleted file mode 100644 index 358f8f03..00000000 Binary files a/release/v12/source_maps/DummyToken.mvsm and /dev/null differ diff --git a/release/v12/source_maps/DummyTokenScripts.mvsm b/release/v12/source_maps/DummyTokenScripts.mvsm deleted file mode 100644 index 868a6a83..00000000 Binary files a/release/v12/source_maps/DummyTokenScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/EVMAddress.mvsm b/release/v12/source_maps/EVMAddress.mvsm deleted file mode 100644 index 0375d0f8..00000000 Binary files a/release/v12/source_maps/EVMAddress.mvsm and /dev/null differ diff --git a/release/v12/source_maps/EmptyScripts.mvsm b/release/v12/source_maps/EmptyScripts.mvsm deleted file mode 100644 index a363d54f..00000000 Binary files a/release/v12/source_maps/EmptyScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Epoch.mvsm b/release/v12/source_maps/Epoch.mvsm deleted file mode 100644 index 838a4c9d..00000000 Binary files a/release/v12/source_maps/Epoch.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Errors.mvsm b/release/v12/source_maps/Errors.mvsm deleted file mode 100644 index eec4d13e..00000000 Binary files a/release/v12/source_maps/Errors.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Event.mvsm b/release/v12/source_maps/Event.mvsm deleted file mode 100644 index 0126b384..00000000 Binary files a/release/v12/source_maps/Event.mvsm and /dev/null differ diff --git a/release/v12/source_maps/EventUtil.mvsm b/release/v12/source_maps/EventUtil.mvsm deleted file mode 100644 index 91ef2539..00000000 Binary files a/release/v12/source_maps/EventUtil.mvsm and /dev/null differ diff --git a/release/v12/source_maps/FixedPoint32.mvsm b/release/v12/source_maps/FixedPoint32.mvsm deleted file mode 100644 index 78217175..00000000 Binary files a/release/v12/source_maps/FixedPoint32.mvsm and /dev/null differ diff --git a/release/v12/source_maps/GasOracle.mvsm b/release/v12/source_maps/GasOracle.mvsm deleted file mode 100644 index 4a9e51a7..00000000 Binary files a/release/v12/source_maps/GasOracle.mvsm and /dev/null differ diff --git a/release/v12/source_maps/GasOracleProposalPlugin.mvsm b/release/v12/source_maps/GasOracleProposalPlugin.mvsm deleted file mode 100644 index 7381aadc..00000000 Binary files a/release/v12/source_maps/GasOracleProposalPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Genesis.mvsm b/release/v12/source_maps/Genesis.mvsm deleted file mode 100644 index 5295f7ad..00000000 Binary files a/release/v12/source_maps/Genesis.mvsm and /dev/null differ diff --git a/release/v12/source_maps/GenesisNFT.mvsm b/release/v12/source_maps/GenesisNFT.mvsm deleted file mode 100644 index 14a6f17f..00000000 Binary files a/release/v12/source_maps/GenesisNFT.mvsm and /dev/null differ diff --git a/release/v12/source_maps/GenesisNFTScripts.mvsm b/release/v12/source_maps/GenesisNFTScripts.mvsm deleted file mode 100644 index d11198e8..00000000 Binary files a/release/v12/source_maps/GenesisNFTScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/GenesisSignerCapability.mvsm b/release/v12/source_maps/GenesisSignerCapability.mvsm deleted file mode 100644 index e32b2cb7..00000000 Binary files a/release/v12/source_maps/GenesisSignerCapability.mvsm and /dev/null differ diff --git a/release/v12/source_maps/GrantProposalPlugin.mvsm b/release/v12/source_maps/GrantProposalPlugin.mvsm deleted file mode 100644 index 8f1250a4..00000000 Binary files a/release/v12/source_maps/GrantProposalPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Hash.mvsm b/release/v12/source_maps/Hash.mvsm deleted file mode 100644 index ecc3c9d3..00000000 Binary files a/release/v12/source_maps/Hash.mvsm and /dev/null differ diff --git a/release/v12/source_maps/IdentifierNFT.mvsm b/release/v12/source_maps/IdentifierNFT.mvsm deleted file mode 100644 index 9f1b3d4c..00000000 Binary files a/release/v12/source_maps/IdentifierNFT.mvsm and /dev/null differ diff --git a/release/v12/source_maps/IdentifierNFTScripts.mvsm b/release/v12/source_maps/IdentifierNFTScripts.mvsm deleted file mode 100644 index 4e9e4589..00000000 Binary files a/release/v12/source_maps/IdentifierNFTScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/InstallPluginProposalPlugin.mvsm b/release/v12/source_maps/InstallPluginProposalPlugin.mvsm deleted file mode 100644 index ee12064f..00000000 Binary files a/release/v12/source_maps/InstallPluginProposalPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/LanguageVersion.mvsm b/release/v12/source_maps/LanguageVersion.mvsm deleted file mode 100644 index e8e96ca7..00000000 Binary files a/release/v12/source_maps/LanguageVersion.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Math.mvsm b/release/v12/source_maps/Math.mvsm deleted file mode 100644 index 5626733b..00000000 Binary files a/release/v12/source_maps/Math.mvsm and /dev/null differ diff --git a/release/v12/source_maps/MemberProposalPlugin.mvsm b/release/v12/source_maps/MemberProposalPlugin.mvsm deleted file mode 100644 index b3485cbc..00000000 Binary files a/release/v12/source_maps/MemberProposalPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/MerkleNFTDistributor.mvsm b/release/v12/source_maps/MerkleNFTDistributor.mvsm deleted file mode 100644 index eb54fa0f..00000000 Binary files a/release/v12/source_maps/MerkleNFTDistributor.mvsm and /dev/null differ diff --git a/release/v12/source_maps/MerkleProof.mvsm b/release/v12/source_maps/MerkleProof.mvsm deleted file mode 100644 index 234610da..00000000 Binary files a/release/v12/source_maps/MerkleProof.mvsm and /dev/null differ diff --git a/release/v12/source_maps/MintDaoProposal.mvsm b/release/v12/source_maps/MintDaoProposal.mvsm deleted file mode 100644 index b505ef00..00000000 Binary files a/release/v12/source_maps/MintDaoProposal.mvsm and /dev/null differ diff --git a/release/v12/source_maps/MintProposalPlugin.mvsm b/release/v12/source_maps/MintProposalPlugin.mvsm deleted file mode 100644 index 43d9c184..00000000 Binary files a/release/v12/source_maps/MintProposalPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/MintScripts.mvsm b/release/v12/source_maps/MintScripts.mvsm deleted file mode 100644 index 698d3240..00000000 Binary files a/release/v12/source_maps/MintScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/ModifyDaoConfigProposal.mvsm b/release/v12/source_maps/ModifyDaoConfigProposal.mvsm deleted file mode 100644 index e033d6cb..00000000 Binary files a/release/v12/source_maps/ModifyDaoConfigProposal.mvsm and /dev/null differ diff --git a/release/v12/source_maps/ModuleUpgradeScripts.mvsm b/release/v12/source_maps/ModuleUpgradeScripts.mvsm deleted file mode 100644 index a3981d95..00000000 Binary files a/release/v12/source_maps/ModuleUpgradeScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/NFT.mvsm b/release/v12/source_maps/NFT.mvsm deleted file mode 100644 index b27322cb..00000000 Binary files a/release/v12/source_maps/NFT.mvsm and /dev/null differ diff --git a/release/v12/source_maps/NFTGallery.mvsm b/release/v12/source_maps/NFTGallery.mvsm deleted file mode 100644 index 26147d3e..00000000 Binary files a/release/v12/source_maps/NFTGallery.mvsm and /dev/null differ diff --git a/release/v12/source_maps/NFTGalleryScripts.mvsm b/release/v12/source_maps/NFTGalleryScripts.mvsm deleted file mode 100644 index 4e781a7a..00000000 Binary files a/release/v12/source_maps/NFTGalleryScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Offer.mvsm b/release/v12/source_maps/Offer.mvsm deleted file mode 100644 index 9659b966..00000000 Binary files a/release/v12/source_maps/Offer.mvsm and /dev/null differ diff --git a/release/v12/source_maps/OnChainConfigDao.mvsm b/release/v12/source_maps/OnChainConfigDao.mvsm deleted file mode 100644 index f9bd60c1..00000000 Binary files a/release/v12/source_maps/OnChainConfigDao.mvsm and /dev/null differ diff --git a/release/v12/source_maps/OnChainConfigScripts.mvsm b/release/v12/source_maps/OnChainConfigScripts.mvsm deleted file mode 100644 index f7f6ddb8..00000000 Binary files a/release/v12/source_maps/OnChainConfigScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/OnChainStarcoinDAOConfig.mvsm b/release/v12/source_maps/OnChainStarcoinDAOConfig.mvsm deleted file mode 100644 index 6fee9d1e..00000000 Binary files a/release/v12/source_maps/OnChainStarcoinDAOConfig.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Option.mvsm b/release/v12/source_maps/Option.mvsm deleted file mode 100644 index 1be82c1f..00000000 Binary files a/release/v12/source_maps/Option.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Oracle.mvsm b/release/v12/source_maps/Oracle.mvsm deleted file mode 100644 index 5723aa3c..00000000 Binary files a/release/v12/source_maps/Oracle.mvsm and /dev/null differ diff --git a/release/v12/source_maps/PackageTxnManager.mvsm b/release/v12/source_maps/PackageTxnManager.mvsm deleted file mode 100644 index 17c79436..00000000 Binary files a/release/v12/source_maps/PackageTxnManager.mvsm and /dev/null differ diff --git a/release/v12/source_maps/PriceOracle.mvsm b/release/v12/source_maps/PriceOracle.mvsm deleted file mode 100644 index 73871f2f..00000000 Binary files a/release/v12/source_maps/PriceOracle.mvsm and /dev/null differ diff --git a/release/v12/source_maps/PriceOracleAggregator.mvsm b/release/v12/source_maps/PriceOracleAggregator.mvsm deleted file mode 100644 index f892dfdc..00000000 Binary files a/release/v12/source_maps/PriceOracleAggregator.mvsm and /dev/null differ diff --git a/release/v12/source_maps/PriceOracleScripts.mvsm b/release/v12/source_maps/PriceOracleScripts.mvsm deleted file mode 100644 index 59a0413c..00000000 Binary files a/release/v12/source_maps/PriceOracleScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/RewardConfig.mvsm b/release/v12/source_maps/RewardConfig.mvsm deleted file mode 100644 index f5b7f758..00000000 Binary files a/release/v12/source_maps/RewardConfig.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Ring.mvsm b/release/v12/source_maps/Ring.mvsm deleted file mode 100644 index 1247e5ea..00000000 Binary files a/release/v12/source_maps/Ring.mvsm and /dev/null differ diff --git a/release/v12/source_maps/SBTVoteStrategy.mvsm b/release/v12/source_maps/SBTVoteStrategy.mvsm deleted file mode 100644 index 93c7dbb5..00000000 Binary files a/release/v12/source_maps/SBTVoteStrategy.mvsm and /dev/null differ diff --git a/release/v12/source_maps/SIP_2.mvsm b/release/v12/source_maps/SIP_2.mvsm deleted file mode 100644 index 203f1efe..00000000 Binary files a/release/v12/source_maps/SIP_2.mvsm and /dev/null differ diff --git a/release/v12/source_maps/SIP_3.mvsm b/release/v12/source_maps/SIP_3.mvsm deleted file mode 100644 index 6cd8b35c..00000000 Binary files a/release/v12/source_maps/SIP_3.mvsm and /dev/null differ diff --git a/release/v12/source_maps/STC.mvsm b/release/v12/source_maps/STC.mvsm deleted file mode 100644 index f0bfaeec..00000000 Binary files a/release/v12/source_maps/STC.mvsm and /dev/null differ diff --git a/release/v12/source_maps/STCUSDOracle.mvsm b/release/v12/source_maps/STCUSDOracle.mvsm deleted file mode 100644 index a1ef79bc..00000000 Binary files a/release/v12/source_maps/STCUSDOracle.mvsm and /dev/null differ diff --git a/release/v12/source_maps/SharedEd25519PublicKey.mvsm b/release/v12/source_maps/SharedEd25519PublicKey.mvsm deleted file mode 100644 index 8e9ebfce..00000000 Binary files a/release/v12/source_maps/SharedEd25519PublicKey.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Signature.mvsm b/release/v12/source_maps/Signature.mvsm deleted file mode 100644 index b2b491f2..00000000 Binary files a/release/v12/source_maps/Signature.mvsm and /dev/null differ diff --git a/release/v12/source_maps/SignedInteger64.mvsm b/release/v12/source_maps/SignedInteger64.mvsm deleted file mode 100644 index 1c9f9d8b..00000000 Binary files a/release/v12/source_maps/SignedInteger64.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Signer.mvsm b/release/v12/source_maps/Signer.mvsm deleted file mode 100644 index 6d140223..00000000 Binary files a/release/v12/source_maps/Signer.mvsm and /dev/null differ diff --git a/release/v12/source_maps/SimpleMap.mvsm b/release/v12/source_maps/SimpleMap.mvsm deleted file mode 100644 index 0b9f85f3..00000000 Binary files a/release/v12/source_maps/SimpleMap.mvsm and /dev/null differ diff --git a/release/v12/source_maps/SnapshotUtil.mvsm b/release/v12/source_maps/SnapshotUtil.mvsm deleted file mode 100644 index 414f4b8d..00000000 Binary files a/release/v12/source_maps/SnapshotUtil.mvsm and /dev/null differ diff --git a/release/v12/source_maps/StakeToSBTPlugin.mvsm b/release/v12/source_maps/StakeToSBTPlugin.mvsm deleted file mode 100644 index 1247500d..00000000 Binary files a/release/v12/source_maps/StakeToSBTPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/StarcoinDAO.mvsm b/release/v12/source_maps/StarcoinDAO.mvsm deleted file mode 100644 index d159bf1e..00000000 Binary files a/release/v12/source_maps/StarcoinDAO.mvsm and /dev/null differ diff --git a/release/v12/source_maps/StarcoinVerifier.mvsm b/release/v12/source_maps/StarcoinVerifier.mvsm deleted file mode 100644 index 06917792..00000000 Binary files a/release/v12/source_maps/StarcoinVerifier.mvsm and /dev/null differ diff --git a/release/v12/source_maps/StdlibUpgradeScripts.mvsm b/release/v12/source_maps/StdlibUpgradeScripts.mvsm deleted file mode 100644 index 6849cba9..00000000 Binary files a/release/v12/source_maps/StdlibUpgradeScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/StructuredHash.mvsm b/release/v12/source_maps/StructuredHash.mvsm deleted file mode 100644 index a60c3dc6..00000000 Binary files a/release/v12/source_maps/StructuredHash.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Timestamp.mvsm b/release/v12/source_maps/Timestamp.mvsm deleted file mode 100644 index 5ca75a3e..00000000 Binary files a/release/v12/source_maps/Timestamp.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Token.mvsm b/release/v12/source_maps/Token.mvsm deleted file mode 100644 index cfb8ab7d..00000000 Binary files a/release/v12/source_maps/Token.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TransactionFee.mvsm b/release/v12/source_maps/TransactionFee.mvsm deleted file mode 100644 index 8adc0c39..00000000 Binary files a/release/v12/source_maps/TransactionFee.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TransactionManager.mvsm b/release/v12/source_maps/TransactionManager.mvsm deleted file mode 100644 index 25092a0c..00000000 Binary files a/release/v12/source_maps/TransactionManager.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TransactionPublishOption.mvsm b/release/v12/source_maps/TransactionPublishOption.mvsm deleted file mode 100644 index 733e3e93..00000000 Binary files a/release/v12/source_maps/TransactionPublishOption.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TransactionTimeout.mvsm b/release/v12/source_maps/TransactionTimeout.mvsm deleted file mode 100644 index fbc35f79..00000000 Binary files a/release/v12/source_maps/TransactionTimeout.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TransactionTimeoutConfig.mvsm b/release/v12/source_maps/TransactionTimeoutConfig.mvsm deleted file mode 100644 index 1d2e6e97..00000000 Binary files a/release/v12/source_maps/TransactionTimeoutConfig.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TransferScripts.mvsm b/release/v12/source_maps/TransferScripts.mvsm deleted file mode 100644 index c6f8c3f4..00000000 Binary files a/release/v12/source_maps/TransferScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Treasury.mvsm b/release/v12/source_maps/Treasury.mvsm deleted file mode 100644 index b929d21d..00000000 Binary files a/release/v12/source_maps/Treasury.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TreasuryPlugin.mvsm b/release/v12/source_maps/TreasuryPlugin.mvsm deleted file mode 100644 index 23a6f634..00000000 Binary files a/release/v12/source_maps/TreasuryPlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TreasuryScripts.mvsm b/release/v12/source_maps/TreasuryScripts.mvsm deleted file mode 100644 index ac524c2a..00000000 Binary files a/release/v12/source_maps/TreasuryScripts.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TreasuryWithdrawDaoProposal.mvsm b/release/v12/source_maps/TreasuryWithdrawDaoProposal.mvsm deleted file mode 100644 index 84561dc8..00000000 Binary files a/release/v12/source_maps/TreasuryWithdrawDaoProposal.mvsm and /dev/null differ diff --git a/release/v12/source_maps/TypeInfo.mvsm b/release/v12/source_maps/TypeInfo.mvsm deleted file mode 100644 index 4c35a8be..00000000 Binary files a/release/v12/source_maps/TypeInfo.mvsm and /dev/null differ diff --git a/release/v12/source_maps/U256.mvsm b/release/v12/source_maps/U256.mvsm deleted file mode 100644 index 78433b97..00000000 Binary files a/release/v12/source_maps/U256.mvsm and /dev/null differ diff --git a/release/v12/source_maps/UpgradeModuleDaoProposal.mvsm b/release/v12/source_maps/UpgradeModuleDaoProposal.mvsm deleted file mode 100644 index 695f18f2..00000000 Binary files a/release/v12/source_maps/UpgradeModuleDaoProposal.mvsm and /dev/null differ diff --git a/release/v12/source_maps/UpgradeModulePlugin.mvsm b/release/v12/source_maps/UpgradeModulePlugin.mvsm deleted file mode 100644 index b6f9cd1b..00000000 Binary files a/release/v12/source_maps/UpgradeModulePlugin.mvsm and /dev/null differ diff --git a/release/v12/source_maps/VMConfig.mvsm b/release/v12/source_maps/VMConfig.mvsm deleted file mode 100644 index 08c4f2ad..00000000 Binary files a/release/v12/source_maps/VMConfig.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Vector.mvsm b/release/v12/source_maps/Vector.mvsm deleted file mode 100644 index 6de0c78c..00000000 Binary files a/release/v12/source_maps/Vector.mvsm and /dev/null differ diff --git a/release/v12/source_maps/Version.mvsm b/release/v12/source_maps/Version.mvsm deleted file mode 100644 index 4e2fe5b5..00000000 Binary files a/release/v12/source_maps/Version.mvsm and /dev/null differ diff --git a/release/v12/source_maps/YieldFarming.mvsm b/release/v12/source_maps/YieldFarming.mvsm deleted file mode 100644 index b82907b0..00000000 Binary files a/release/v12/source_maps/YieldFarming.mvsm and /dev/null differ diff --git a/release/v12/source_maps/YieldFarmingV2.mvsm b/release/v12/source_maps/YieldFarmingV2.mvsm deleted file mode 100644 index 14631abf..00000000 Binary files a/release/v12/source_maps/YieldFarmingV2.mvsm and /dev/null differ diff --git a/release/v12/sources/ASCII.move b/release/v12/sources/ASCII.move deleted file mode 100644 index 0e118f95..00000000 --- a/release/v12/sources/ASCII.move +++ /dev/null @@ -1,138 +0,0 @@ -module StarcoinFramework::ASCII { - use StarcoinFramework::Vector; - use StarcoinFramework::Errors; - use StarcoinFramework::Option::{Self, Option}; - - /// An invalid ASCII character was encountered when creating an ASCII string. - const EINVALID_ASCII_CHARACTER: u64 = 101; - - /// The `String` struct holds a vector of bytes that all represent - /// valid ASCII characters. Note that these ASCII characters may not all - /// be printable. To determine if a `String` contains only "printable" - /// characters you should use the `all_characters_printable` predicate - /// defined in this module. - struct String has copy, drop, store { - bytes: vector, - } - - - /// An ASCII character. - struct Char has copy, drop, store { - byte: u8, - } - - /// Convert a `byte` into a `Char` that is checked to make sure it is valid ASCII. - public fun char(byte: u8): Char { - assert!(is_valid_char(byte), Errors::invalid_argument(EINVALID_ASCII_CHARACTER)); - Char { byte } - } - - - /// Convert a vector of bytes `bytes` into an `String`. Aborts if - /// `bytes` contains non-ASCII characters. - public fun string(bytes: vector): String { - let x = try_string(bytes); - assert!( - Option::is_some(&x), - Errors::invalid_argument(EINVALID_ASCII_CHARACTER) - ); - Option::destroy_some(x) - } - - /// Convert a vector of bytes `bytes` into an `String`. Returns - /// `Some()` if the `bytes` contains all valid ASCII - /// characters. Otherwise returns `None`. - public fun try_string(bytes: vector): Option { - let len = Vector::length(&bytes); - let i = 0; - while ( i < len ) { - let possible_byte = *Vector::borrow(&bytes, i); - if (!is_valid_char(possible_byte)) return Option::none(); - i = i + 1; - }; - Option::some(String { bytes }) - } - - /// Returns `true` if all characters in `string` are printable characters - /// Returns `false` otherwise. Not all `String`s are printable strings. - public fun all_characters_printable(string: &String): bool { - let len = Vector::length(&string.bytes); - let i = 0; - while ( i < len ) { - let byte = *Vector::borrow(&string.bytes, i); - if (!is_printable_char(byte)) return false; - i = i + 1; - }; - true - } - - public fun push_char(string: &mut String, char: Char) { - Vector::push_back(&mut string.bytes, char.byte); - } - - - public fun pop_char(string: &mut String): Char { - Char { byte: Vector::pop_back(&mut string.bytes) } - } - - - public fun length(string: &String): u64 { - Vector::length(as_bytes(string)) - } - - /// Get the inner bytes of the `string` as a reference - public fun as_bytes(string: &String): &vector { - &string.bytes - } - - /// Unpack the `string` to get its backing bytes - public fun into_bytes(string: String): vector { - let String { bytes } = string; - bytes - } - - /// Unpack the `char` into its underlying byte. - public fun byte(char: Char): u8 { - let Char { byte } = char; - byte - } - - /// Returns `true` if `byte` is a valid ASCII character. Returns `false` otherwise. - public fun is_valid_char(byte: u8): bool { - byte <= 0x7F - } - - /// Returns `true` if `byte` is an printable ASCII character. Returns `false` otherwise. - public fun is_printable_char(byte: u8): bool { - byte >= 0x20 && // Disallow metacharacters - byte <= 0x7E // Don't allow DEL metacharacter - } - - /// split string by char. Returns vector - public fun split_by_char(string: String, char: Char): vector { - let result = Vector::empty(); - let len = length(&string); - let i = 0; - let buffer = Vector::empty(); - while ( i < len ) { - let byte = *Vector::borrow(&string.bytes, i); - if (byte != char.byte) { - Vector::push_back(&mut buffer, byte); - } else { - Vector::push_back(&mut result, string(buffer)); - buffer = Vector::empty(); - if (i != 0 && i == len - 1) { - // special - Vector::push_back(&mut result, string(copy buffer)); - }; - }; - - i = i + 1; - }; - - if (len == 0 || Vector::length(&buffer) != 0) { - Vector::push_back(&mut result, string(buffer)); - }; - result - } -} \ No newline at end of file diff --git a/release/v12/sources/Account.move b/release/v12/sources/Account.move deleted file mode 100644 index 71052527..00000000 --- a/release/v12/sources/Account.move +++ /dev/null @@ -1,1234 +0,0 @@ -address StarcoinFramework { - -/// The module for the account resource that governs every account -module Account { - use StarcoinFramework::Authenticator; - use StarcoinFramework::Event; - use StarcoinFramework::Hash; - use StarcoinFramework::Token::{Self, Token}; - use StarcoinFramework::Vector; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::TransactionFee; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::STC::{Self, STC, is_stc}; - use StarcoinFramework::BCS; - use StarcoinFramework::Math; - - friend StarcoinFramework::Genesis; - friend StarcoinFramework::StdlibUpgradeScripts; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Every account has a Account::Account resource - struct Account has key { - /// The current authentication key. - /// This can be different than the key used to create the account - authentication_key: vector, - /// A `withdrawal_capability` allows whoever holds this capability - /// to withdraw from the account. At the time of account creation - /// this capability is stored in this option. It can later be - /// "extracted" from this field via `extract_withdraw_capability`, - /// and can also be restored via `restore_withdraw_capability`. - withdrawal_capability: Option, - /// A `key_rotation_capability` allows whoever holds this capability - /// the ability to rotate the authentication key for the account. At - /// the time of account creation this capability is stored in this - /// option. It can later be "extracted" from this field via - /// `extract_key_rotation_capability`, and can also be restored via - /// `restore_key_rotation_capability`. - key_rotation_capability: Option, - - /// event handle for account balance withdraw event - withdraw_events: Event::EventHandle, - /// event handle for account balance deposit event - deposit_events: Event::EventHandle, - - /// Event handle for accept_token event - accept_token_events: Event::EventHandle, - - /// The current sequence number. - /// Incremented by one each time a transaction is submitted - sequence_number: u64, - } - - /// A resource that holds the tokens stored in this account - struct Balance has key { - token: Token, - } - - /// The holder of WithdrawCapability for account_address can withdraw Token from - /// account_address/Account::Account/balance. - /// There is at most one WithdrawCapability in existence for a given address. - struct WithdrawCapability has store { - account_address: address, - } - - /// The holder of KeyRotationCapability for account_address can rotate the authentication key for - /// account_address (i.e., write to account_address/Account::Account/authentication_key). - /// There is at most one KeyRotationCapability in existence for a given address. - struct KeyRotationCapability has store { - account_address: address, - } - - /// Message for balance withdraw event. - struct WithdrawEvent has drop, store { - /// The amount of Token sent - amount: u128, - /// The code symbol for the token that was sent - token_code: Token::TokenCode, - /// Metadata associated with the withdraw - metadata: vector, - } - /// Message for balance deposit event. - struct DepositEvent has drop, store { - /// The amount of Token sent - amount: u128, - /// The code symbol for the token that was sent - token_code: Token::TokenCode, - /// Metadata associated with the deposit - metadata: vector, - } - - /// Message for accept token events - struct AcceptTokenEvent has drop, store { - token_code: Token::TokenCode, - } - - // SignerDelegated can only be stored under address, not in other structs. - struct SignerDelegated has key {} - // SignerCapability can only be stored in other structs, not under address. - // So that the capability is always controlled by contracts, not by some EOA. - struct SignerCapability has store { addr: address } - - // Resource marking whether the account enable auto-accept-token feature. - struct AutoAcceptToken has key { enable: bool } - - /// Message for rotate_authentication_key events - struct RotateAuthKeyEvent has drop, store { - account_address: address, - new_auth_key: vector, - } - - /// Message for extract_withdraw_capability events - struct ExtractWithdrawCapEvent has drop, store { - account_address: address, - } - - /// Message for SignerDelegate events - struct SignerDelegateEvent has drop, store { - account_address: address - } - - struct EventStore has key { - /// Event handle for rotate_authentication_key event - rotate_auth_key_events: Event::EventHandle, - /// Event handle for extract_withdraw_capability event - extract_withdraw_cap_events: Event::EventHandle, - /// Event handle for signer delegated event - signer_delegate_events: Event::EventHandle, - } - - const MAX_U64: u128 = 18446744073709551615; - - const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0; - const EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY: u64 = 1; - const EPROLOGUE_SEQUENCE_NUMBER_TOO_OLD: u64 = 2; - const EPROLOGUE_SEQUENCE_NUMBER_TOO_NEW: u64 = 3; - const EPROLOGUE_CANT_PAY_GAS_DEPOSIT: u64 = 4; - - const EPROLOGUE_SEQUENCE_NUMBER_TOO_BIG: u64 = 9; - - const EINSUFFICIENT_BALANCE: u64 = 10; - const ECOIN_DEPOSIT_IS_ZERO: u64 = 15; - const EBAD_TRANSACTION_FEE_TOKEN: u64 = 18; - - const EDEPRECATED_FUNCTION: u64 = 19; - - const EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED: u64 = 101; - const EMALFORMED_AUTHENTICATION_KEY: u64 = 102; - const EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED: u64 = 103; - const EADDRESS_PUBLIC_KEY_INCONSISTENT: u64 = 104; - const EADDRESS_AND_AUTH_KEY_MISMATCH: u64 = 105; - const ERR_TOKEN_NOT_ACCEPT: u64 = 106; - const ERR_SIGNER_ALREADY_DELEGATED: u64 = 107; - - const EPROLOGUE_SIGNER_ALREADY_DELEGATED: u64 = 200; - - const DUMMY_AUTH_KEY:vector = x"0000000000000000000000000000000000000000000000000000000000000000"; - // cannot be dummy key, or empty key - const CONTRACT_ACCOUNT_AUTH_KEY_PLACEHOLDER:vector = x"0000000000000000000000000000000000000000000000000000000000000001"; - - /// The address bytes length - const ADDRESS_LENGTH: u64 = 16; - - /// A one-way action, once SignerCapability is removed from signer, the address cannot send txns anymore. - /// This function can only called once by signer. - public fun remove_signer_capability(signer: &signer): SignerCapability - acquires Account, EventStore { - let signer_addr = Signer::address_of(signer); - assert!(!is_signer_delegated(signer_addr), Errors::invalid_state(ERR_SIGNER_ALREADY_DELEGATED)); - - // set to account auth key to noop. - { - let key_rotation_capability = extract_key_rotation_capability(signer); - rotate_authentication_key_with_capability(&key_rotation_capability, CONTRACT_ACCOUNT_AUTH_KEY_PLACEHOLDER); - destroy_key_rotation_capability(key_rotation_capability); - move_to(signer, SignerDelegated {}); - - make_event_store_if_not_exist(signer); - let event_store = borrow_global_mut(signer_addr); - Event::emit_event( - &mut event_store.signer_delegate_events, - SignerDelegateEvent { - account_address: signer_addr - } - ); - }; - - let signer_cap = SignerCapability {addr: signer_addr }; - signer_cap - } - - //TODO: Create StarcoinDAO , need modify or remove get_genesis_capability soon - public (friend) fun get_genesis_capability():SignerCapability{ - let signer_cap = SignerCapability {addr: Token::token_address() }; - signer_cap - } - - public fun create_signer_with_cap(cap: &SignerCapability): signer { - create_signer(cap.addr) - } - public fun destroy_signer_cap(cap: SignerCapability) { - let SignerCapability {addr: _} = cap; - } - - public fun signer_address(cap: &SignerCapability): address { - cap.addr - } - public fun is_signer_delegated(addr: address): bool { - exists(addr) - } - - /// Create an genesis account at `new_account_address` and return signer. - /// Genesis authentication_key is zero bytes. - public fun create_genesis_account( - new_account_address: address, - ) :signer { - Timestamp::assert_genesis(); - let new_account = create_signer(new_account_address); - make_account(&new_account, DUMMY_AUTH_KEY); - new_account - } - - spec create_genesis_account { - aborts_if !Timestamp::is_genesis(); - aborts_if len(DUMMY_AUTH_KEY) != 32; - aborts_if exists(new_account_address); - } - - /// Release genesis account signer - public fun release_genesis_signer(_genesis_account: signer){ - } - - spec release_genesis_signer { - aborts_if false; - } - - /// Deprecated since @v5 - public fun create_account(_authentication_key: vector): address { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - spec create_account { - aborts_if true; - } - - /// Creates a new account at `fresh_address` with a balance of zero and empty auth key, the address as init auth key for check transaction. - /// Creating an account at address StarcoinFramework will cause runtime failure as it is a - /// reserved address for the MoveVM. - public fun create_account_with_address(fresh_address: address) acquires Account { - let new_account = create_signer(fresh_address); - make_account(&new_account, DUMMY_AUTH_KEY); - // Make sure all account accept STC. - if (!STC::is_stc()){ - do_accept_token(&new_account); - }; - do_accept_token(&new_account); - } - - spec create_account_with_address { - //abort condition for make_account - aborts_if exists(fresh_address); - //abort condition for do_accept_token - aborts_if Token::spec_token_code() != Token::spec_token_code() && exists>(fresh_address); - //abort condition for do_accept_token - aborts_if exists>(fresh_address); - ensures exists_at(fresh_address); - ensures exists>(fresh_address); - } - - fun make_account( - new_account: &signer, - authentication_key: vector, - ) { - assert!(Vector::length(&authentication_key) == 32, Errors::invalid_argument(EMALFORMED_AUTHENTICATION_KEY)); - let new_account_addr = Signer::address_of(new_account); - Event::publish_generator(new_account); - move_to(new_account, Account { - authentication_key, - withdrawal_capability: Option::some( - WithdrawCapability { - account_address: new_account_addr - }), - key_rotation_capability: Option::some( - KeyRotationCapability { - account_address: new_account_addr - }), - withdraw_events: Event::new_event_handle(new_account), - deposit_events: Event::new_event_handle(new_account), - accept_token_events: Event::new_event_handle(new_account), - sequence_number: 0, - }); - move_to(new_account, AutoAcceptToken{enable: true}); - move_to(new_account, EventStore { - rotate_auth_key_events: Event::new_event_handle(new_account), - extract_withdraw_cap_events: Event::new_event_handle(new_account), - signer_delegate_events: Event::new_event_handle(new_account), - }); - } - - spec make_account { - aborts_if len(authentication_key) != 32; - aborts_if exists(Signer::address_of(new_account)); - aborts_if exists(Signer::address_of(new_account)); - ensures exists_at(Signer::address_of(new_account)); - } - - native fun create_signer(addr: address): signer; - - public(script) fun create_account_with_initial_amount(account: signer, fresh_address: address, _auth_key: vector, initial_amount: u128) - acquires Account, Balance, AutoAcceptToken { - create_account_with_initial_amount_entry(account, fresh_address, initial_amount); - } - - public(script) fun create_account_with_initial_amount_v2(account: signer, fresh_address: address, initial_amount: u128) - acquires Account, Balance, AutoAcceptToken { - create_account_with_initial_amount_entry(account, fresh_address, initial_amount); - } - - public(script) fun create_account_with_initial_amount_entry(account: signer, fresh_address: address, initial_amount: u128) - acquires Account, Balance, AutoAcceptToken { - create_account_with_address(fresh_address); - if (initial_amount > 0) { - pay_from(&account, fresh_address, initial_amount); - }; - } - - spec create_account_with_initial_amount { - pragma verify = false; - } - - spec create_account_with_initial_amount_v2 { - pragma verify = false; - } - - /// Generate an new address and create a new account, then delegate the account and return the new account address and `SignerCapability` - public fun create_delegate_account(sender: &signer) : (address, SignerCapability) acquires Balance, Account, EventStore { - let new_address = generate_fresh_address(sender); - Self::create_account_with_address(new_address); - let new_signer = Self::create_signer(new_address); - (new_address, Self::remove_signer_capability(&new_signer)) - } - - /// Generate a fresh address from the sender address and the sender's sequence number, and ensure the generated address is not exists onchain. - public fun generate_fresh_address(sender: &signer) : address acquires Balance, Account { - let try_times = 0u64; - while(true){ - let sender_address = Signer::address_of(sender); - let sequence_number = Self::sequence_number(sender_address); - // use stc balance as part of seed, just for new address more random. - let stc_balance = Self::balance(sender_address); - - let seed_bytes = BCS::to_bytes(&sender_address); - Vector::append(&mut seed_bytes, BCS::to_bytes(&sequence_number)); - Vector::append(&mut seed_bytes, BCS::to_bytes(&stc_balance)); - Vector::append(&mut seed_bytes, BCS::to_bytes(&try_times)); - - let seed_hash = Hash::sha3_256(seed_bytes); - - let i = 0; - let address_bytes = Vector::empty(); - while (i < ADDRESS_LENGTH) { - Vector::push_back(&mut address_bytes, *Vector::borrow(&seed_hash,i)); - i = i + 1; - }; - let new_address = BCS::to_address(address_bytes); - if (Self::exists_at(new_address)){ - try_times = try_times + 1; - continue - }else{ - return new_address - } - }; - //unreachable - abort 0 - } - - spec create_delegate_account { - pragma verify = false; - //TODO write spec - } - - /// Deposits the `to_deposit` token into the self's account balance - public fun deposit_to_self(account: &signer, to_deposit: Token) - acquires Account, Balance, AutoAcceptToken { - let account_address = Signer::address_of(account); - if (!is_accepts_token(account_address)){ - do_accept_token(account); - }; - deposit(account_address, to_deposit); - } - - spec deposit_to_self { - aborts_if to_deposit.value == 0; - let is_accepts_token = exists>(Signer::address_of(account)); - aborts_if is_accepts_token && global>(Signer::address_of(account)).token.value + to_deposit.value > max_u128(); - aborts_if !exists(Signer::address_of(account)); - ensures exists>(Signer::address_of(account)); - } - - /// Deposits the `to_deposit` token into the `receiver`'s account balance with the no metadata - /// It's a reverse operation of `withdraw`. - public fun deposit( - receiver: address, - to_deposit: Token, - ) acquires Account, Balance, AutoAcceptToken { - deposit_with_metadata(receiver, to_deposit, x"") - } - - spec deposit { - include DepositWithMetadataAbortsIf; - } - - /// Deposits the `to_deposit` token into the `receiver`'s account balance with the attached `metadata` - /// It's a reverse operation of `withdraw_with_metadata`. - public fun deposit_with_metadata( - receiver: address, - to_deposit: Token, - metadata: vector, - ) acquires Account, Balance, AutoAcceptToken { - - if (!exists_at(receiver)) { - create_account_with_address(receiver); - }; - - try_accept_token(receiver); - - let deposit_value = Token::value(&to_deposit); - if (deposit_value > 0u128) { - // Deposit the `to_deposit` token - deposit_to_balance(borrow_global_mut>(receiver), to_deposit); - - // emit deposit event - emit_account_deposit_event(receiver, deposit_value, metadata); - } else { - Token::destroy_zero(to_deposit); - }; - } - - spec deposit_with_metadata { - include DepositWithMetadataAbortsIf; - ensures exists>(receiver); - ensures old(global>(receiver)).token.value + to_deposit.value == global>(receiver).token.value; - } - - spec schema DepositWithMetadataAbortsIf { - receiver: address; - to_deposit: Token; - - aborts_if to_deposit.value == 0; - aborts_if !exists(receiver); - aborts_if !exists>(receiver); - - aborts_if global>(receiver).token.value + to_deposit.value > max_u128(); - - } - - /// Helper to deposit `amount` to the given account balance - fun deposit_to_balance(balance: &mut Balance, token: Token::Token) { - Token::deposit(&mut balance.token, token) - } - - spec deposit_to_balance { - aborts_if balance.token.value + token.value > MAX_U128; - } - - - - /// Helper to withdraw `amount` from the given account balance and return the withdrawn Token - fun withdraw_from_balance(balance: &mut Balance, amount: u128): Token{ - Token::withdraw(&mut balance.token, amount) - } - - spec withdraw_from_balance { - aborts_if balance.token.value < amount; - } - - /// Withdraw `amount` Token from the account balance - public fun withdraw(account: &signer, amount: u128): Token - acquires Account, Balance { - withdraw_with_metadata(account, amount, x"") - } - spec withdraw { - aborts_if !exists>(Signer::address_of(account)); - aborts_if !exists(Signer::address_of(account)); - aborts_if global>(Signer::address_of(account)).token.value < amount; - aborts_if Option::is_none(global(Signer::address_of(account)).withdrawal_capability); - } - - - /// Withdraw `amount` tokens from `signer` with given `metadata`. - public fun withdraw_with_metadata(account: &signer, amount: u128, metadata: vector): Token - acquires Account, Balance { - let sender_addr = Signer::address_of(account); - let sender_balance = borrow_global_mut>(sender_addr); - // The sender_addr has delegated the privilege to withdraw from her account elsewhere--abort. - assert!(!delegated_withdraw_capability(sender_addr), Errors::invalid_state(EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED)); - if (amount == 0){ - return Token::zero() - }; - emit_account_withdraw_event(sender_addr, amount, metadata); - // The sender_addr has retained her withdrawal privileges--proceed. - withdraw_from_balance(sender_balance, amount) - } - - spec withdraw_with_metadata { - aborts_if !exists>(Signer::address_of(account)); - aborts_if !exists(Signer::address_of(account)); - aborts_if global>(Signer::address_of(account)).token.value < amount; - aborts_if Option::is_none(global(Signer::address_of(account)).withdrawal_capability); - } - - spec fun spec_withdraw(account: signer, amount: u128): Token { - Token { value: amount } - } - - /// Withdraw `amount` Token from the account under cap.account_address with no metadata - public fun withdraw_with_capability( - cap: &WithdrawCapability, amount: u128 - ): Token acquires Balance, Account { - withdraw_with_capability_and_metadata(cap, amount, x"") - } - - spec withdraw_with_capability { - aborts_if !exists>(cap.account_address); - aborts_if !exists(cap.account_address); - aborts_if global>(cap.account_address).token.value < amount; - } - - /// Withdraw `amount` Token from the account under cap.account_address with metadata - public fun withdraw_with_capability_and_metadata( - cap: &WithdrawCapability, amount: u128, metadata: vector - ): Token acquires Balance, Account { - let balance = borrow_global_mut>(cap.account_address); - emit_account_withdraw_event(cap.account_address, amount, metadata); - withdraw_from_balance(balance , amount) - } - - spec withdraw_with_capability_and_metadata { - aborts_if !exists>(cap.account_address); - aborts_if !exists(cap.account_address); - aborts_if global>(cap.account_address).token.value < amount; - } - - - /// Return a unique capability granting permission to withdraw from the sender's account balance. - public fun extract_withdraw_capability( - sender: &signer - ): WithdrawCapability acquires Account, EventStore { - let sender_addr = Signer::address_of(sender); - // Abort if we already extracted the unique withdraw capability for this account. - assert!(!delegated_withdraw_capability(sender_addr), Errors::invalid_state(EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED)); - - make_event_store_if_not_exist(sender); - let event_store = borrow_global_mut(sender_addr); - Event::emit_event( - &mut event_store.extract_withdraw_cap_events, - ExtractWithdrawCapEvent { - account_address: sender_addr, - } - ); - let account = borrow_global_mut(sender_addr); - Option::extract(&mut account.withdrawal_capability) - } - - spec extract_withdraw_capability { - aborts_if !exists(Signer::address_of(sender)); - aborts_if Option::is_none(global( Signer::address_of(sender)).withdrawal_capability); - } - - /// Return the withdraw capability to the account it originally came from - public fun restore_withdraw_capability(cap: WithdrawCapability) - acquires Account { - let account = borrow_global_mut(cap.account_address); - Option::fill(&mut account.withdrawal_capability, cap) - } - - spec restore_withdraw_capability { - aborts_if Option::is_some(global(cap.account_address).withdrawal_capability); - aborts_if !exists(cap.account_address); - } - - fun emit_account_withdraw_event(account: address, amount: u128, metadata: vector) - acquires Account { - // emit withdraw event - let account = borrow_global_mut(account); - - Event::emit_event(&mut account.withdraw_events, WithdrawEvent { - amount, - token_code: Token::token_code(), - metadata, - }); - } - spec emit_account_withdraw_event { - aborts_if !exists(account); - } - - fun emit_account_deposit_event(account: address, amount: u128, metadata: vector) - acquires Account { - // emit withdraw event - let account = borrow_global_mut(account); - - Event::emit_event(&mut account.deposit_events, DepositEvent { - amount, - token_code: Token::token_code(), - metadata, - }); - } - spec emit_account_deposit_event { - aborts_if !exists(account); - } - - - /// Withdraws `amount` Token using the passed in WithdrawCapability, and deposits it - /// into the `payee`'s account balance. Creates the `payee` account if it doesn't exist. - public fun pay_from_capability( - cap: &WithdrawCapability, - payee: address, - amount: u128, - metadata: vector, - ) acquires Account, Balance, AutoAcceptToken { - let tokens = withdraw_with_capability_and_metadata(cap, amount, *&metadata); - deposit_with_metadata( - payee, - tokens, - metadata, - ); - } - - spec pay_from_capability { - // condition for withdraw_with_capability_and_metadata() - aborts_if !exists>(cap.account_address); - aborts_if !exists(cap.account_address); - aborts_if global>(cap.account_address).token.value < amount; - // condition for deposit_with_metadata() - aborts_if amount == 0; - aborts_if !exists(payee); - aborts_if !exists>(payee); - aborts_if cap.account_address != payee && global>(payee).token.value + amount > MAX_U128; - } - - /// Withdraw `amount` Token from the transaction sender's - /// account balance and send the token to the `payee` address with the - /// attached `metadata` Creates the `payee` account if it does not exist - public fun pay_from_with_metadata( - account: &signer, - payee: address, - amount: u128, - metadata: vector, - ) acquires Account, Balance, AutoAcceptToken { - let tokens = withdraw_with_metadata(account, amount, *&metadata); - deposit_with_metadata( - payee, - tokens, - metadata, - ); - } - - spec pay_from_with_metadata { - // condition for withdraw_with_metadata() - aborts_if !exists>(Signer::address_of(account)); - aborts_if !exists(Signer::address_of(account)); - aborts_if global>(Signer::address_of(account)).token.value < amount; - aborts_if Option::is_none(global(Signer::address_of(account)).withdrawal_capability); - // condition for deposit_with_metadata() - aborts_if amount == 0; - aborts_if !exists(payee); - aborts_if !exists>(payee); - aborts_if Signer::address_of(account) != payee && global>(payee).token.value + amount > max_u128(); -} - spec schema DepositWithPayerAndMetadataAbortsIf { - payer: address; - payee: address; - to_deposit: Token; - - aborts_if to_deposit.value == 0; - aborts_if !exists(payer); - aborts_if !exists(payee); - aborts_if !exists>(payee); - aborts_if global>(payee).token.value + to_deposit.value > max_u128(); - } - - - /// Withdraw `amount` Token from the transaction sender's - /// account balance and send the token to the `payee` address - /// Creates the `payee` account if it does not exist - public fun pay_from( - account: &signer, - payee: address, - amount: u128 - ) acquires Account, Balance, AutoAcceptToken { - pay_from_with_metadata(account, payee, amount, x""); - } - - spec pay_from { - // condition for withdraw_with_metadata() - aborts_if !exists>(Signer::address_of(account)); - aborts_if !exists(Signer::address_of(account)); - aborts_if global>(Signer::address_of(account)).token.value < amount; - aborts_if Option::is_none(global(Signer::address_of(account)).withdrawal_capability); - // condition for deposit_with_metadata() - aborts_if amount == 0; - aborts_if !exists(payee); - aborts_if !exists>(payee); - aborts_if Signer::address_of(account) != payee && global>(payee).token.value + amount > max_u128(); - } - - /// Rotate the authentication key for the account under cap.account_address - public fun rotate_authentication_key_with_capability( - cap: &KeyRotationCapability, - new_authentication_key: vector, - ) acquires Account { - let sender_account_resource = borrow_global_mut(cap.account_address); - // Don't allow rotating to clearly invalid key - assert!(Vector::length(&new_authentication_key) == 32, Errors::invalid_argument(EMALFORMED_AUTHENTICATION_KEY)); - sender_account_resource.authentication_key = new_authentication_key; - } - - spec rotate_authentication_key_with_capability { - aborts_if !exists(cap.account_address); - aborts_if len(new_authentication_key) != 32; - ensures global(cap.account_address).authentication_key == new_authentication_key; - } - - spec fun spec_rotate_authentication_key_with_capability(addr: address, new_authentication_key: vector): bool { - global(addr).authentication_key == new_authentication_key - } - - - /// Return a unique capability granting permission to rotate the sender's authentication key - public fun extract_key_rotation_capability(account: &signer): KeyRotationCapability - acquires Account { - let account_address = Signer::address_of(account); - // Abort if we already extracted the unique key rotation capability for this account. - assert!(!delegated_key_rotation_capability(account_address), Errors::invalid_state(EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED)); - let account = borrow_global_mut(account_address); - Option::extract(&mut account.key_rotation_capability) - } - - spec extract_key_rotation_capability { - aborts_if !exists(Signer::address_of(account)); - aborts_if Option::is_none(global(Signer::address_of(account)).key_rotation_capability); - } - - /// Return the key rotation capability to the account it originally came from - public fun restore_key_rotation_capability(cap: KeyRotationCapability) - acquires Account { - let account = borrow_global_mut(cap.account_address); - Option::fill(&mut account.key_rotation_capability, cap) - } - public fun destroy_key_rotation_capability(cap: KeyRotationCapability) { - let KeyRotationCapability {account_address: _} = cap; - } - - spec restore_key_rotation_capability { - aborts_if Option::is_some(global(cap.account_address).key_rotation_capability); - aborts_if !exists(cap.account_address); - } - - public(script) fun rotate_authentication_key(account: signer, new_key: vector) acquires Account, EventStore { - rotate_authentication_key_entry(account, new_key); - } - - public(script) fun rotate_authentication_key_entry(account: signer, new_key: vector) acquires Account, EventStore { - do_rotate_authentication_key(&account, new_key); - } - - public fun do_rotate_authentication_key(account: &signer, new_key: vector) acquires Account, EventStore { - let key_rotation_capability = extract_key_rotation_capability(account); - rotate_authentication_key_with_capability(&key_rotation_capability, copy new_key); - restore_key_rotation_capability(key_rotation_capability); - - make_event_store_if_not_exist(account); - let signer_addr = Signer::address_of(account); - let event_store = borrow_global_mut(signer_addr); - Event::emit_event( - &mut event_store.rotate_auth_key_events, - RotateAuthKeyEvent { - account_address: signer_addr, - new_auth_key: new_key, - } - ); - } - - spec rotate_authentication_key { - pragma verify = false; - } - - /// Helper to return the u128 value of the `balance` for `account` - fun balance_for(balance: &Balance): u128 { - Token::value(&balance.token) - } - - spec balance_for { - aborts_if false; - } - - /// Return the current TokenType balance of the account at `addr`. - public fun balance(addr: address): u128 acquires Balance { - if (exists>(addr)) { - balance_for(borrow_global>(addr)) - } else { - 0u128 - } - } - - - /// Add a balance of `Token` type to the sending account. - public fun do_accept_token(account: &signer) acquires Account { - move_to(account, Balance{ token: Token::zero() }); - let token_code = Token::token_code(); - // Load the sender's account - let sender_account_ref = borrow_global_mut(Signer::address_of(account)); - // Log a sent event - Event::emit_event( - &mut sender_account_ref.accept_token_events, - AcceptTokenEvent { - token_code: token_code, - }, - ); - } - - spec do_accept_token { - aborts_if exists>(Signer::address_of(account)); - aborts_if !exists(Signer::address_of(account)); - } - - public(script) fun accept_token(account: signer) acquires Account { - accept_token_entry(account); - } - - public(script) fun accept_token_entry(account: signer) acquires Account { - do_accept_token(&account); - } - - spec accept_token { - pragma verify = false; - } - - /// This is a alias of is_accept_token - public fun is_accepts_token(addr: address): bool acquires AutoAcceptToken { - Self::is_accept_token(addr) - } - - spec is_accepts_token { - aborts_if false; - } - - /// Return whether the account at `addr` accept `Token` type tokens - public fun is_accept_token(addr: address): bool acquires AutoAcceptToken { - if (can_auto_accept_token(addr)) { - true - } else { - exists>(addr) - } - } - - spec is_accept_token { - aborts_if false; - } - - /// Check whether the address can auto accept token. - public fun can_auto_accept_token(addr: address): bool acquires AutoAcceptToken { - if (exists(addr)) { - borrow_global(addr).enable - } else { - false - } - } - - public(script) fun set_auto_accept_token_entry(account: signer, enable: bool) acquires AutoAcceptToken { - set_auto_accept_token(&account, enable); - } - - /// Configure whether auto-accept tokens. - public fun set_auto_accept_token(account: &signer, enable: bool) acquires AutoAcceptToken { - let addr = Signer::address_of(account); - if (exists(addr)) { - let config = borrow_global_mut(addr); - config.enable = enable; - } else { - move_to(account, AutoAcceptToken{enable}); - }; - } - spec set_auto_accept_token { - aborts_if false; - } - - /// try to accept token for `addr`. - fun try_accept_token(addr: address) acquires AutoAcceptToken, Account { - if (!exists>(addr)) { - if (can_auto_accept_token(addr)) { - let signer = create_signer(addr); - do_accept_token(&signer); - }else{ - abort Errors::not_published(ERR_TOKEN_NOT_ACCEPT) - } - }; - } - spec try_accept_token { - aborts_if false; - } - - /// Helper to return the sequence number field for given `account` - fun sequence_number_for_account(account: &Account): u64 { - account.sequence_number - } - - spec is_accepts_token { - aborts_if false; - } - - /// Return the current sequence number at `addr` - public fun sequence_number(addr: address): u64 acquires Account { - sequence_number_for_account(borrow_global(addr)) - } - - spec sequence_number { - aborts_if !exists(addr); - } - - /// Return the authentication key for this account - public fun authentication_key(addr: address): vector acquires Account { - *&borrow_global(addr).authentication_key - } - - spec authentication_key { - aborts_if !exists(addr); - } - - /// Return true if the account at `addr` has delegated its key rotation capability - public fun delegated_key_rotation_capability(addr: address): bool - acquires Account { - Option::is_none(&borrow_global(addr).key_rotation_capability) - } - - spec delegated_key_rotation_capability { - aborts_if !exists(addr); - } - - /// Return true if the account at `addr` has delegated its withdraw capability - public fun delegated_withdraw_capability(addr: address): bool - acquires Account { - Option::is_none(&borrow_global(addr).withdrawal_capability) - } - - spec delegated_withdraw_capability { - aborts_if !exists(addr); - } - - /// Return a reference to the address associated with the given withdraw capability - public fun withdraw_capability_address(cap: &WithdrawCapability): &address { - &cap.account_address - } - - spec withdraw_capability_address { - aborts_if false; - } - - /// Return a reference to the address associated with the given key rotation capability - public fun key_rotation_capability_address(cap: &KeyRotationCapability): &address { - &cap.account_address - } - - spec key_rotation_capability_address { - aborts_if false; - } - - /// Checks if an account exists at `check_addr` - public fun exists_at(check_addr: address): bool { - exists(check_addr) - } - - spec exists_at { - aborts_if false; - } - - fun is_dummy_auth_key(account: &Account): bool { - *&account.authentication_key == DUMMY_AUTH_KEY - } - - /// The prologue is invoked at the beginning of every transaction - /// It verifies: - /// - The account's auth key matches the transaction's public key - /// - That the account has enough balance to pay for all of the gas - /// - That the sequence number matches the transaction's sequence key - public fun txn_prologue( - account: &signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - ) acquires Account, Balance { - txn_prologue_v2( - account, - txn_sender, - txn_sequence_number, - txn_authentication_key_preimage, - txn_gas_price, - txn_max_gas_units, - 1, - 1, - ) - } - spec txn_prologue { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(txn_sender); - aborts_if global(txn_sender).authentication_key == DUMMY_AUTH_KEY && Authenticator::spec_derived_address(Hash::sha3_256(txn_authentication_key_preimage)) != txn_sender; - aborts_if global(txn_sender).authentication_key != DUMMY_AUTH_KEY && Hash::sha3_256(txn_authentication_key_preimage) != global(txn_sender).authentication_key; - aborts_if txn_sequence_number < global(txn_sender).sequence_number; - } - - public fun txn_prologue_v2( - account: &signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - stc_price: u128, - stc_price_scaling: u128 - ) acquires Account, Balance { - CoreAddresses::assert_genesis_address(account); - - // Verify that the transaction sender's account exists - assert!(exists_at(txn_sender), Errors::requires_address(EPROLOGUE_ACCOUNT_DOES_NOT_EXIST)); - // Verify the account has not delegate its signer cap. - assert!(!is_signer_delegated(txn_sender), Errors::invalid_state(EPROLOGUE_SIGNER_ALREADY_DELEGATED)); - - // Load the transaction sender's account - let sender_account = borrow_global_mut(txn_sender); - - if (is_dummy_auth_key(sender_account)){ - // if sender's auth key is empty, use address as auth key for check transaction. - assert!( - Authenticator::derived_address(Hash::sha3_256(txn_authentication_key_preimage)) == txn_sender, - Errors::invalid_argument(EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY) - ); - }else{ - // Check that the hash of the transaction's public key matches the account's auth key - assert!( - Hash::sha3_256(txn_authentication_key_preimage) == *&sender_account.authentication_key, - Errors::invalid_argument(EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY) - ); - }; - // Check that the account has enough balance for all of the gas - let (max_transaction_fee_stc,max_transaction_fee_token) = transaction_fee_simulate(txn_gas_price,txn_max_gas_units,0, stc_price, stc_price_scaling); - assert!( - max_transaction_fee_stc <= MAX_U64, - Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT), - ); - if (max_transaction_fee_stc > 0) { - assert!( - (txn_sequence_number as u128) < MAX_U64, - Errors::limit_exceeded(EPROLOGUE_SEQUENCE_NUMBER_TOO_BIG) - ); - let balance_amount_token = balance(txn_sender); - assert!(balance_amount_token >= max_transaction_fee_token, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT)); - if (!is_stc()){ - let balance_amount_stc= balance(CoreAddresses::GENESIS_ADDRESS()); - assert!(balance_amount_stc >= max_transaction_fee_stc, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT)); - } - }; - // Check that the transaction sequence number matches the sequence number of the account - assert!(txn_sequence_number >= sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_OLD)); - assert!(txn_sequence_number == sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_NEW)); - - } - - - /// The epilogue is invoked at the end of transactions. - /// It collects gas and bumps the sequence number - public fun txn_epilogue( - account: &signer, - txn_sender: address, - txn_sequence_number: u64, - txn_gas_price: u64, - txn_max_gas_units: u64, - gas_units_remaining: u64, - ) acquires Account, Balance { - txn_epilogue_v3(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining,1,1) - } - - spec txn_epilogue { - pragma verify = false; - } - - public fun transaction_fee_simulate( - txn_gas_price:u64, - txn_max_gas_units: u64, - gas_units_remaining:u64, - stc_price: u128, - stc_price_scaling: u128, - ): (u128, u128){ - let transaction_fee_stc =(txn_gas_price * (txn_max_gas_units - gas_units_remaining) as u128); - let transaction_fee_token= Math::mul_div((transaction_fee_stc as u128), stc_price, stc_price_scaling); - transaction_fee_token = if (transaction_fee_token == 0 && transaction_fee_stc > 0 ) { 1 } else { transaction_fee_token}; - (transaction_fee_stc, transaction_fee_token) - } - /// The epilogue is invoked at the end of transactions. - /// It collects gas and bumps the sequence number - public fun txn_epilogue_v2( - account: &signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - gas_units_remaining: u64, - ) acquires Account, Balance { - txn_epilogue_v3( - account, - txn_sender, - txn_sequence_number, - txn_authentication_key_preimage, - txn_gas_price, - txn_max_gas_units, - gas_units_remaining,1,1) - } - - spec txn_epilogue_v2 { - pragma verify = false; // Todo: fix me, cost too much time - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(txn_sender); - aborts_if !exists>(txn_sender); - aborts_if txn_max_gas_units < gas_units_remaining; - let transaction_fee_amount = txn_gas_price * (txn_max_gas_units - gas_units_remaining); - aborts_if transaction_fee_amount > max_u128(); - aborts_if global>(txn_sender).token.value < transaction_fee_amount; - aborts_if txn_sequence_number + 1 > max_u64(); - aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && - global>(txn_sender).token.value < txn_gas_price * (txn_max_gas_units - gas_units_remaining); - aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && - !exists>(CoreAddresses::GENESIS_ADDRESS()); - aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && - global>(CoreAddresses::GENESIS_ADDRESS()).fee.value + txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u128(); - } - - /// The epilogue is invoked at the end of transactions. - /// It collects gas and bumps the sequence number - public fun txn_epilogue_v3( - account: &signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - gas_units_remaining: u64, - stc_price: u128, - stc_price_scaling: u128, - ) acquires Account, Balance { - CoreAddresses::assert_genesis_address(account); - // Charge for gas - let (transaction_fee_amount_stc,transaction_fee_amount_token) = transaction_fee_simulate( - txn_gas_price, - txn_max_gas_units, - gas_units_remaining, - stc_price, - stc_price_scaling); - assert!( - balance(txn_sender) >= transaction_fee_amount_token, - Errors::limit_exceeded(EINSUFFICIENT_BALANCE) - ); - if (!is_stc()){ - let genesis_balance_amount_stc=balance(CoreAddresses::GENESIS_ADDRESS()); - assert!(genesis_balance_amount_stc >= transaction_fee_amount_stc, - Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT) - ); - }; - // Load the transaction sender's account and balance resources - let sender_account = borrow_global_mut(txn_sender); - // Bump the sequence number - sender_account.sequence_number = txn_sequence_number + 1; - // Set auth key when user send transaction first. - if (is_dummy_auth_key(sender_account) && !Vector::is_empty(&txn_authentication_key_preimage)){ - sender_account.authentication_key = Hash::sha3_256(txn_authentication_key_preimage); - }; - if (transaction_fee_amount_stc > 0) { - let transaction_fee_token = withdraw_from_balance( - borrow_global_mut>(txn_sender), - transaction_fee_amount_token - ); - deposit_to_balance(borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_token); - let stc_fee_token = withdraw_from_balance(borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_amount_stc); - TransactionFee::pay_fee(stc_fee_token); - }; - } - - spec txn_epilogue_v2 { - pragma verify = false; // Todo: fix me, cost too much time - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(txn_sender); - aborts_if !exists>(txn_sender); - aborts_if txn_sequence_number + 1 > max_u64(); - aborts_if !exists>(txn_sender); - aborts_if txn_max_gas_units < gas_units_remaining; - } - - public(script) fun remove_zero_balance_entry(account: signer) acquires Balance { - remove_zero_balance(&account); - } - - /// Remove zero Balance - public fun remove_zero_balance(account: &signer) acquires Balance { - let addr: address = Signer::address_of(account); - let Balance { token } = move_from>(addr); - Token::destroy_zero(token); - } - - spec remove_zero_balance { - let addr = Signer::address_of(account); - aborts_if !exists>(addr); - ensures !exists>(addr); - } - - /// Make a event store if it's not exist. - fun make_event_store_if_not_exist(account: &signer) { - if (!exists(Signer::address_of(account))) { - move_to(account, EventStore { - rotate_auth_key_events: Event::new_event_handle(account), - extract_withdraw_cap_events: Event::new_event_handle(account), - signer_delegate_events: Event::new_event_handle(account), - }) - }; - } -} - -} diff --git a/release/v12/sources/AccountScripts.move b/release/v12/sources/AccountScripts.move deleted file mode 100644 index 6c77bf97..00000000 --- a/release/v12/sources/AccountScripts.move +++ /dev/null @@ -1,21 +0,0 @@ -address StarcoinFramework { -module AccountScripts { - use StarcoinFramework::Account; - /// Enable account's auto-accept-token feature. - /// The script function is reenterable. - public(script) fun enable_auto_accept_token(account: signer) { - Account::set_auto_accept_token_entry(account, true); - } - - /// Disable account's auto-accept-token feature. - /// The script function is reenterable. - public(script) fun disable_auto_accept_token(account: signer) { - Account::set_auto_accept_token_entry(account, false); - } - - /// Remove zero Balance - public(script) fun remove_zero_balance(account: signer) { - Account::remove_zero_balance_entry(account); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/AnyMemberPlugin.move b/release/v12/sources/AnyMemberPlugin.move deleted file mode 100644 index 36fb4c45..00000000 --- a/release/v12/sources/AnyMemberPlugin.move +++ /dev/null @@ -1,73 +0,0 @@ -/// This plugin let every can join the DAO, and auto get 1 sbt. -module StarcoinFramework::AnyMemberPlugin{ - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::Signer; - use StarcoinFramework::Option; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct AnyMemberPlugin has store, drop{} - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::member_cap_type()); - caps - } - - public fun initialize(_sender: &signer) { - let witness = AnyMemberPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::AnyMemberPlugin", - b"The member plugin that allow all member to do join.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://any-member-plugin", - ); - } - - public fun join(sender: &signer, image_data:vector, image_url:vector){ - let witness = AnyMemberPlugin{}; - let sender_addr = Signer::address_of(sender); - if (DAOSpace::is_member(sender_addr) ) { - return - }; - let member_cap = DAOSpace::acquire_member_cap(&witness); - let op_image_data = if(Vector::is_empty(&image_data)){ - Option::none>() - }else{ - Option::some(image_data) - }; - let op_image_url = if(Vector::is_empty(&image_url)){ - Option::none>() - }else{ - Option::some(image_url) - }; - - DAOSpace::issue_member_offer(&member_cap, sender_addr, op_image_data, op_image_url, 1); - DAOSpace::accept_member_offer(sender); - } - - public (script) fun join_entry(sender: signer, image_data:vector, image_url:vector){ - join(&sender, image_data, image_url); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/release/v12/sources/Authenticator.move b/release/v12/sources/Authenticator.move deleted file mode 100644 index 1acda180..00000000 --- a/release/v12/sources/Authenticator.move +++ /dev/null @@ -1,155 +0,0 @@ - -address StarcoinFramework { -/// Move representation of the authenticator types -/// - Ed25519 (single-sig) -/// - MultiEd25519 (K-of-N multisig) -module Authenticator { - use StarcoinFramework::Hash; - use StarcoinFramework::BCS; - use StarcoinFramework::Vector; - use StarcoinFramework::Errors; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - const AUTHENTICATION_KEY_LENGTH: u64 = 32; - - const ED25519_SCHEME_ID: u8 = 0; - const MULTI_ED25519_SCHEME_ID: u8 = 1; - - /// A multi-ed25519 public key - struct MultiEd25519PublicKey has copy, drop, store { - /// vector of ed25519 public keys - public_keys: vector>, - /// approval threshold - threshold: u8, - } - - /// Maximum number of keys allowed in a MultiEd25519 public/private key - const MAX_MULTI_ED25519_KEYS: u64 = 32; - - const EWRONG_AUTHENTICATION_KEY_LENGTH: u64 = 101; - /// Threshold provided was 0 which can't be used to create a `MultiEd25519` key - const EZERO_THRESHOLD: u64 = 102; - /// Not enough keys were provided for the specified threshold when creating an `MultiEd25519` key - const ENOT_ENOUGH_KEYS_FOR_THRESHOLD: u64 = 103; - /// Too many keys were provided for the specified threshold when creating an `MultiEd25519` key - const ENUM_KEYS_ABOVE_MAX_THRESHOLD: u64 = 104; - - /// Create a a multisig policy from a vector of ed25519 public keys and a threshold. - /// Note: this does *not* check uniqueness of keys. Repeated keys are convenient to - /// encode weighted multisig policies. For example Alice AND 1 of Bob or Carol is - /// public_key: {alice_key, alice_key, bob_key, carol_key}, threshold: 3 - /// Aborts if threshold is zero or bigger than the length of `public_keys`. - public fun create_multi_ed25519( - public_keys: vector>, - threshold: u8 - ): MultiEd25519PublicKey { - // check threshold requirements - let len = Vector::length(&public_keys); - assert!(threshold != 0, Errors::invalid_argument(EZERO_THRESHOLD)); - assert!( - (threshold as u64) <= len, - Errors::invalid_argument(ENOT_ENOUGH_KEYS_FOR_THRESHOLD) - ); - // the multied25519 signature scheme allows at most 32 keys - assert!( - len <= MAX_MULTI_ED25519_KEYS, - Errors::invalid_argument(ENUM_KEYS_ABOVE_MAX_THRESHOLD) - ); - - MultiEd25519PublicKey { public_keys, threshold } - } - - spec create_multi_ed25519 { - aborts_if threshold == 0; - aborts_if threshold > Vector::length(public_keys); - aborts_if Vector::length(public_keys) > 32; - } - - /// Compute an authentication key for the ed25519 public key `public_key` - public fun ed25519_authentication_key(public_key: vector): vector { - Vector::push_back(&mut public_key, ED25519_SCHEME_ID); - Hash::sha3_256(public_key) - } - - spec ed25519_authentication_key { - pragma opaque = true; - aborts_if false; - ensures [abstract] result == spec_ed25519_authentication_key(public_key); - } - - /// We use an uninterpreted function to represent the result of key construction. The actual value - /// does not matter for the verification of callers. - spec fun spec_ed25519_authentication_key(public_key: vector): vector; - - /// convert authentication key to address - public fun derived_address(authentication_key: vector): address { - assert!(Vector::length(&authentication_key) == AUTHENTICATION_KEY_LENGTH, Errors::invalid_argument(EWRONG_AUTHENTICATION_KEY_LENGTH)); - let address_bytes = Vector::empty(); - - let i = 16; - while (i < 32) { - let b = *Vector::borrow(&authentication_key, i); - Vector::push_back(&mut address_bytes, b); - i = i + 1; - }; - - BCS::to_address(address_bytes) - } - - spec derived_address { - pragma opaque = true; - aborts_if len(authentication_key) != 32; - ensures [abstract] result == spec_derived_address(authentication_key); - } - - /// We use an uninterpreted function to represent the result of derived address. The actual value - /// does not matter for the verification of callers. - spec fun spec_derived_address(authentication_key: vector): address; - - /// Compute a multied25519 account authentication key for the policy `k` - public fun multi_ed25519_authentication_key(k: &MultiEd25519PublicKey): vector { - let public_keys = &k.public_keys; - let len = Vector::length(public_keys); - let authentication_key_preimage = Vector::empty(); - let i = 0; - while (i < len) { - let public_key = *Vector::borrow(public_keys, i); - Vector::append( - &mut authentication_key_preimage, - public_key - ); - i = i + 1; - }; - Vector::append(&mut authentication_key_preimage, BCS::to_bytes(&k.threshold)); - Vector::push_back(&mut authentication_key_preimage, MULTI_ED25519_SCHEME_ID); - Hash::sha3_256(authentication_key_preimage) - } - - spec multi_ed25519_authentication_key { - aborts_if false; - } - - /// Return the public keys involved in the multisig policy `k` - public fun public_keys(k: &MultiEd25519PublicKey): &vector> { - &k.public_keys - } - - spec public_keys { - aborts_if false; - } - - /// Return the threshold for the multisig policy `k` - public fun threshold(k: &MultiEd25519PublicKey): u8 { - *&k.threshold - } - - spec threshold { - aborts_if false; - } - -} -} diff --git a/release/v12/sources/BCS.move b/release/v12/sources/BCS.move deleted file mode 100644 index a2f56a5b..00000000 --- a/release/v12/sources/BCS.move +++ /dev/null @@ -1,742 +0,0 @@ -address StarcoinFramework { -/// Utility for converting a Move value to its binary representation in BCS (Diem Canonical -/// Serialization). BCS is the binary encoding for Move resources and other non-module values -/// published on-chain. -module BCS { - - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::BCS; - - const ERR_INPUT_NOT_LARGE_ENOUGH: u64 = 201; - const ERR_UNEXPECTED_BOOL_VALUE: u64 = 205; - const ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32: u64 = 206; - const ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT: u64 = 207; - const INTEGER32_MAX_VALUE: u64 = 2147483647; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - /// Return the binary representation of `v` in BCS (Starcoin Canonical Serialization) format - native public fun to_bytes(v: &MoveValue): vector; - - /// Return the address of key bytes - native public fun to_address(key_bytes: vector): address; - // ------------------------------------------------------------------------ - // Specification - // ------------------------------------------------------------------------ - - - spec native fun serialize(v: &MoveValue): vector; - - - public fun deserialize_option_bytes_vector(input: &vector, offset: u64): (vector>>, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty>>(); - while (i < len) { - let (opt_bs, o) = deserialize_option_bytes(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - spec deserialize_option_bytes_vector { - pragma verify = false; - } - - public fun deserialize_option_tuple(input: &vector, offset: u64): (Option::Option>, Option::Option>, u64) { - let (tag, new_offset) = deserialize_option_tag(input, offset); - if (!tag) { - return (Option::none>(), Option::none>(), new_offset) - } else { - let (bs1, new_offset) = deserialize_bytes(input, new_offset); - let (bs2, new_offset) = deserialize_bytes(input, new_offset); - - (Option::some>(bs1), Option::some>(bs2), new_offset) - } - } - spec deserialize_option_tuple { - pragma verify = false; - } - - #[test] - fun test_deserialize_option_tuple() { - let tuple_bytes = Vector::empty(); - let tuple1_bytes = x"01020304"; - let tuple2_bytes = x"05060708"; - let tuple1_bcs = to_bytes(&tuple1_bytes); - let tuple2_bcs = to_bytes(&tuple2_bytes); - Vector::append(&mut tuple_bytes, tuple1_bcs); - Vector::append(&mut tuple_bytes, tuple2_bcs); - - let tuple_option_bcs = Vector::empty(); - Vector::append(&mut tuple_option_bcs, x"01"); - Vector::append(&mut tuple_option_bcs, tuple_bytes); - - let offset = 0; - let (tuple1, tuple2, _offset) = deserialize_option_tuple(&tuple_option_bcs, offset); - let tuple1_option = Option::some(tuple1_bytes); - let tuple2_option = Option::some(tuple2_bytes); - assert!(tuple1 == tuple1_option, 999); - assert!(tuple2 == tuple2_option, 1000); - } - - public fun deserialize_bytes_vector(input: &vector, offset: u64): (vector>, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty>(); - while (i < len) { - let (opt_bs, o) = deserialize_bytes(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - - spec deserialize_bytes_vector { - pragma verify = false; - } - - #[test] - public fun test_deserialize_bytes_array() { - let hello = b"hello"; - let world = b"world"; - let hello_world = Vector::empty>(); - Vector::push_back(&mut hello_world, hello); - Vector::push_back(&mut hello_world, world); - let bs = BCS::to_bytes>>(&hello_world); - let (r, _) = deserialize_bytes_vector(&bs, 0); - assert!(hello_world == r, 1001); - } - - public fun deserialize_u64_vector(input: &vector, offset: u64): (vector, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty(); - while (i < len) { - let (opt_bs, o) = deserialize_u64(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - - spec deserialize_u64_vector { - pragma verify = false; - } - - public fun deserialize_u128_vector(input: &vector, offset: u64): (vector, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty(); - while (i < len) { - let (opt_bs, o) = deserialize_u128(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - - spec deserialize_u128_vector { - pragma verify = false; - } - - #[test] - public fun test_deserialize_u128_array() { - let hello:u128 = 1111111; - let world:u128 = 2222222; - let hello_world = Vector::empty(); - Vector::push_back(&mut hello_world, hello); - Vector::push_back(&mut hello_world, world); - let bs = BCS::to_bytes>(&hello_world); - let (r, _) = deserialize_u128_vector(&bs, 0); - assert!(hello_world == r, 1002); - } - - public fun deserialize_option_bytes(input: &vector, offset: u64): (Option::Option>, u64) { - let (tag, new_offset) = deserialize_option_tag(input, offset); - if (!tag) { - return (Option::none>(), new_offset) - } else { - let (bs, new_offset) = deserialize_bytes(input, new_offset); - return (Option::some>(bs), new_offset) - } - } - - spec deserialize_option_bytes { - pragma verify = false; - } - - public fun deserialize_address(input: &vector, offset: u64): (address, u64) { - let (content, new_offset) = deserialize_16_bytes(input, offset); - (BCS::to_address(content), new_offset) - } - - spec deserialize_address { - pragma verify = false; - } - - #[test] - fun test_deserialize_address() { - let addr = @0x18351d311d32201149a4df2a9fc2db8a; - let bs = BCS::to_bytes
(&addr); - let (r, offset) = deserialize_address(&bs, 0); - assert!(addr == r, 1003); - assert!(offset == 16, 1004); - } - - public fun deserialize_16_bytes(input: &vector, offset: u64): (vector, u64) { - let content = get_n_bytes(input, offset, 16); - (content, offset + 16) - } - - spec deserialize_16_bytes { - pragma verify = false; - } - - public fun deserialize_bytes(input: &vector, offset: u64): (vector, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let content = get_n_bytes(input, new_offset, len); - (content, new_offset + len) - } - - spec deserialize_bytes { - pragma verify = false; - } - - #[test] - public fun test_deserialize_bytes() { - let hello = b"hello world"; - let bs = BCS::to_bytes>(&hello); - let (r, _) = deserialize_bytes(&bs, 0); - assert!(hello == r, 1005); - } - - public fun deserialize_u128(input: &vector, offset: u64): (u128, u64) { - let u = get_n_bytes_as_u128(input, offset, 16); - (u, offset + 16) - } - - spec deserialize_u128 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u128() { - let max_int128 = 170141183460469231731687303715884105727; - let u: u128 = max_int128; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u128(&bs, 0); - assert!(u == r, 1006); - assert!(offset == 16, 1007); - } - - - public fun deserialize_u64(input: &vector, offset: u64): (u64, u64) { - let u = get_n_bytes_as_u128(input, offset, 8); - ((u as u64), offset + 8) - } - - spec deserialize_u64 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u64() { - let u: u64 = 12811111111111; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u64(&bs, 0); - assert!(u == r, 1008); - assert!(offset == 8, 1009); - } - - public fun deserialize_u32(input: &vector, offset: u64): (u64, u64) { - let u = get_n_bytes_as_u128(input, offset, 4); - ((u as u64), offset + 4) - } - - spec deserialize_u32 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u32() { - let u: u64 = 1281111; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u32(&bs, 0); - _ = r; - assert!(u == r, 1010); - assert!(offset == 4, 1011); - } - - public fun deserialize_u16(input: &vector, offset: u64): (u64, u64) { - let u = get_n_bytes_as_u128(input, offset, 2); - ((u as u64), offset + 2) - } - - spec deserialize_u16 { - pragma verify = false; - } - - public fun deserialize_u8(input: &vector, offset: u64): (u8, u64) { - let u = get_byte(input, offset); - (u, offset + 1) - } - - spec deserialize_u8 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u8() { - let u: u8 = 128; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u8(&bs, 0); - assert!(u == r, 1012); - assert!(offset == 1, 1013); - } - - public fun deserialize_option_tag(input: &vector, offset: u64): (bool, u64) { - deserialize_bool(input, offset) - } - - spec deserialize_option_tag { - pragma verify = false; - } - - public fun deserialize_len(input: &vector, offset: u64): (u64, u64) { - deserialize_uleb128_as_u32(input, offset) - } - - spec deserialize_len { - pragma verify = false; - } - - public fun deserialize_bool(input: &vector, offset: u64): (bool, u64) { - let b = get_byte(input, offset); - if (b == 1) { - return (true, offset + 1) - } else if (b == 0) { - return (false, offset + 1) - } else { - abort ERR_UNEXPECTED_BOOL_VALUE - } - } - - spec deserialize_bool { - pragma verify = false; - } - - #[test] - public fun test_deserialize_bool() { - let t = true; - let bs = BCS::to_bytes(&t); - let (d, _) = deserialize_bool(&bs, 0); - assert!(d, 1014); - - let f = false; - bs = BCS::to_bytes(&f); - (d, _) = deserialize_bool(&bs, 0); - assert!(!d, 1015); - } - - fun get_byte(input: &vector, offset: u64): u8 { - assert!(((offset + 1) <= Vector::length(input)) && (offset < offset + 1), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - *Vector::borrow(input, offset) - } - - spec get_byte { - pragma verify = false; - } - - fun get_n_bytes(input: &vector, offset: u64, n: u64): vector { - assert!(((offset + n) <= Vector::length(input)) && (offset <= offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - let i = 0; - let content = Vector::empty(); - while (i < n) { - let b = *Vector::borrow(input, offset + i); - Vector::push_back(&mut content, b); - i = i + 1; - }; - content - } - - spec get_n_bytes { - pragma verify = false; - } - - fun get_n_bytes_as_u128(input: &vector, offset: u64, n: u64): u128 { - assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - let number: u128 = 0; - let i = 0; - while (i < n) { - let byte = *Vector::borrow(input, offset + i); - let s = (i as u8) * 8; - number = number + ((byte as u128) << s); - i = i + 1; - }; - number - } - - spec get_n_bytes_as_u128 { - pragma verify = false; - } - - public fun deserialize_uleb128_as_u32(input: &vector, offset: u64): (u64, u64) { - let value: u64 = 0; - let shift = 0; - let new_offset = offset; - while (shift < 32) { - let x = get_byte(input, new_offset); - new_offset = new_offset + 1; - let digit: u8 = x & 0x7F; - value = value | (digit as u64) << shift; - if ((value < 0) || (value > INTEGER32_MAX_VALUE)) { - abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32 - }; - if (digit == x) { - if (shift > 0 && digit == 0) { - abort ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT - }; - return (value, new_offset) - }; - shift = shift + 7 - }; - abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32 - } - - spec deserialize_uleb128_as_u32 { - pragma verify = false; - } - - #[test] - public fun test_deserialize_uleb128_as_u32() { - let i: u64 = 0x7F; - let bs = serialize_u32_as_uleb128(i); - let (len, _) = deserialize_uleb128_as_u32(&bs, 0); - assert!(len == i, 1016); - - let i2: u64 = 0x8F; - let bs2 = serialize_u32_as_uleb128(i2); - (len, _) = deserialize_uleb128_as_u32(&bs2, 0); - assert!(len == i2, 1017); - } - - - #[test] - public fun test_deserialize_uleb128_as_u32_max_int() { - let max_int: u64 = 2147483647; - - let bs = serialize_u32_as_uleb128(max_int); - let (len, _) = deserialize_uleb128_as_u32(&bs, 0); - assert!(len == max_int, 1018); - } - - #[test] - #[expected_failure(abort_code = 206)] - public fun test_deserialize_uleb128_as_u32_exceeded_max_int() { - let max_int: u64 = 2147483647; - let exceeded_max_int: u64 = max_int + 1; - - let bs = serialize_u32_as_uleb128(exceeded_max_int); - let (_, _) = deserialize_uleb128_as_u32(&bs, 0); - } - - - fun serialize_u32_as_uleb128(value: u64): vector { - let output = Vector::empty(); - while ((value >> 7) != 0) { - Vector::push_back(&mut output, (((value & 0x7f) | 0x80) as u8)); - value = value >> 7; - }; - Vector::push_back(&mut output, (value as u8)); - output - } - - spec serialize_u32_as_uleb128 { - pragma verify = false; - } - - // skip Vector>> - public fun skip_option_bytes_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - while (i < len) { - new_offset = skip_option_bytes(input, new_offset); - i = i + 1; - }; - new_offset - } - - spec skip_option_bytes_vector { - pragma verify = false; - } - - #[test] - fun test_skip_option_bytes_vector(){ - let vec = Vector::empty>>(); - Vector::push_back(&mut vec, Option::some(x"01020304")); - Vector::push_back(&mut vec, Option::some(x"04030201")); - let vec = to_bytes(&vec); - //vec : [2, 1, 4, 1, 2, 3, 4, 1, 4, 4, 3, 2, 1] - assert!(skip_option_bytes_vector(&vec, 0) == 13,2000); - } - - // skip Option::Option> - public fun skip_option_bytes(input: &vector, offset: u64): u64 { - let (tag, new_offset) = deserialize_option_tag(input, offset); - if (!tag) { - new_offset - } else { - skip_bytes(input, new_offset) - } - } - - spec skip_option_bytes { - pragma verify = false; - } - - #[test] - fun test_skip_none_option_bytes(){ - let op = Option::none>(); - let op = to_bytes(&op); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut op, vec); - // op : [0, 4, 1, 2, 3, 4] - assert!(skip_option_bytes(&op, 0) == 1,2007); - } - - #[test] - fun test_skip_some_option_bytes(){ - let op = Option::some(x"01020304"); - let op = to_bytes(&op); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut op, vec); - // op : [1, 4, 1, 2, 3, 4, 4, 1, 2, 3, 4] - assert!(skip_option_bytes(&op, 0) == 6,2008); - } - - // skip vector> - public fun skip_bytes_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - while (i < len) { - new_offset = skip_bytes(input, new_offset); - i = i + 1; - }; - new_offset - } - - spec skip_bytes_vector { - pragma verify = false; - } - - // skip vector - public fun skip_bytes(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - new_offset + len - } - - spec skip_bytes { - pragma verify = false; - } - - #[test] - fun test_skip_bytes(){ - let vec = to_bytes(&x"01020304"); - let u_64 = to_bytes(&10); - Vector::append(&mut vec, u_64); - // vec : [4, 1, 2, 3, 4, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_bytes(&vec, 0) == 5,2001); - } - - // skip some bytes - public fun skip_n_bytes(input: &vector, offset: u64, n:u64): u64 { - can_skip(input, offset, n ); - offset + n - } - - spec skip_n_bytes { - pragma verify = false; - } - - #[test] - fun test_skip_n_bytes(){ - let vec = to_bytes(&x"01020304"); - let u_64 = to_bytes(&10); - Vector::append(&mut vec, u_64); - // vec : [4, 1, 2, 3, 4, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_n_bytes(&vec, 0, 1) == 1,2002); - } - - // skip vector - public fun skip_u64_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - can_skip(input, new_offset, len * 8); - new_offset + len * 8 - } - - spec skip_u64_vector { - pragma verify = false; - } - - #[test] - fun test_skip_u64_vector(){ - let vec = Vector::empty(); - Vector::push_back(&mut vec, 11111); - Vector::push_back(&mut vec, 22222); - let u_64 = to_bytes(&10); - let vec = to_bytes(&vec); - Vector::append(&mut vec, u_64); - // vec : [2, 103, 43, 0, 0, 0, 0, 0, 0, 206, 86, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_u64_vector(&vec, 0) == 17,2004); - } - - // skip vector - public fun skip_u128_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - can_skip(input, new_offset, len * 16); - new_offset + len * 16 - } - - spec skip_u128_vector { - pragma verify = false; - } - - #[test] - fun test_skip_u128_vector(){ - let vec = Vector::empty(); - Vector::push_back(&mut vec, 11111); - Vector::push_back(&mut vec, 22222); - let u_64 = to_bytes(&10); - let vec = to_bytes(&vec); - Vector::append(&mut vec, u_64); - // vec : [2, 103, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 206, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_u128_vector(&vec, 0) == 33,2003); - } - - // skip u256 - public fun skip_u256(input: &vector, offset: u64): u64 { - can_skip(input, offset, 32 ); - offset + 32 - } - - spec skip_u256 { - pragma verify = false; - } - - // skip u128 - public fun skip_u128(input: &vector, offset: u64): u64 { - can_skip(input, offset, 16 ); - offset + 16 - } - - spec skip_u128 { - pragma verify = false; - } - - #[test] - fun test_skip_u128(){ - let u_128:u128 = 100; - let u_128 = to_bytes(&u_128); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut u_128, vec); - // u_128 : [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4] - assert!(skip_u128(&u_128, 0) == 16,2005); - } - - // skip u64 - public fun skip_u64(input: &vector, offset: u64): u64 { - can_skip(input, offset, 8 ); - offset + 8 - } - - spec skip_u64 { - pragma verify = false; - } - - #[test] - fun test_skip_u64(){ - let u_64:u64 = 100; - let u_64 = to_bytes(&u_64); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut u_64, vec); - // u_64 : [100, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4] - assert!(skip_u64(&u_64, 0) == 8,2006); - } - - // skip u32 - public fun skip_u32(input: &vector, offset: u64): u64 { - can_skip(input, offset, 4 ); - offset + 4 - } - - spec skip_u32 { - pragma verify = false; - } - - // skip u16 - public fun skip_u16(input: &vector, offset: u64): u64 { - can_skip(input, offset, 2 ); - offset + 2 - } - - spec skip_u16 { - pragma verify = false; - } - - // skip u8 - public fun skip_u8(input: &vector, offset: u64): u64 { - can_skip(input, offset, 1 ); - offset + 1 - } - - spec skip_u8 { - pragma verify = false; - } - - // skip address - public fun skip_address(input: &vector, offset: u64): u64 { - skip_n_bytes(input, offset, 16) - } - - spec skip_address { - pragma verify = false; - } - - #[test] - fun test_address(){ - let addr:address = @0x1; - let addr = to_bytes(&addr); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut addr, vec); - // addr : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 1, 2, 3, 4] - assert!(skip_address(&addr, 0) == 16,2006); - } - - // skip bool - public fun skip_bool(input: &vector, offset: u64): u64{ - can_skip(input, offset, 1); - offset + 1 - } - - spec skip_bool { - pragma verify = false; - } - - fun can_skip(input: &vector, offset: u64, n: u64){ - assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - } - - spec can_skip { - pragma verify = false; - } -} -} diff --git a/release/v12/sources/Bitwise.move b/release/v12/sources/Bitwise.move deleted file mode 100644 index 9f8f0138..00000000 --- a/release/v12/sources/Bitwise.move +++ /dev/null @@ -1,39 +0,0 @@ -address StarcoinFramework { -/// Functions for bit operations. -module BitOperators { - - spec module { - pragma verify = false; - } - - /// bit and: x & y - public fun and(x: u64, y: u64): u64 { - (x & y as u64) - } - - /// bit or: x | y - public fun or(x: u64, y: u64): u64 { - (x | y as u64) - } - - /// bit xor: x ^ y - public fun xor(x: u64, y: u64): u64 { - (x ^ y as u64) - } - - /// bit not: !x - public fun not(x: u64): u64 { - (x ^ 18446744073709551615u64 as u64) - } - - /// left shift n bits. - public fun lshift(x: u64, n: u8): u64 { - (x << n as u64) - } - - /// right shift n bits. - public fun rshift(x: u64, n: u8): u64 { - (x >> n as u64) - } -} -} \ No newline at end of file diff --git a/release/v12/sources/Block.move b/release/v12/sources/Block.move deleted file mode 100644 index d1e841fa..00000000 --- a/release/v12/sources/Block.move +++ /dev/null @@ -1,453 +0,0 @@ -address StarcoinFramework { -/// Block module provide metadata for generated blocks. -module Block { - use StarcoinFramework::Event; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Signer; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::Ring; - use StarcoinFramework::BCS; - use StarcoinFramework::Hash; - use StarcoinFramework::GenesisSignerCapability; - - spec module { - pragma verify; - pragma aborts_if_is_strict = true; - } - - /// Block metadata struct. - struct BlockMetadata has key { - /// number of the current block - number: u64, - /// Hash of the parent block. - parent_hash: vector, - /// Author of the current block. - author: address, - /// number of uncles. - uncles: u64, - /// Handle of events when new blocks are emitted - new_block_events: Event::EventHandle, - } - - /// Events emitted when new block generated. - struct NewBlockEvent has drop, store { - number: u64, - author: address, - timestamp: u64, - uncles: u64, - } - - // - struct Checkpoint has copy,drop,store{ - //number of the block - block_number: u64, - //Hash of the block - block_hash: vector, - //State root of the block - state_root: Option::Option>, - } - - // - struct Checkpoints has key,store{ - //all checkpoints - checkpoints : Ring::Ring, - index : u64, - last_number : u64, - } - - const EBLOCK_NUMBER_MISMATCH : u64 = 17; - const ERROR_NO_HAVE_CHECKPOINT: u64 = 18; - const ERROR_NOT_BLOCK_HEADER : u64 = 19; - const ERROR_INTERVAL_TOO_LITTLE: u64 = 20; - const ERR_ALREADY_INITIALIZED : u64 = 21; - - const CHECKPOINT_LENGTH : u64 = 60; - const BLOCK_HEADER_LENGTH : u64 = 247; - const BLOCK_INTERVAL_NUMBER : u64 = 5; - - /// This can only be invoked by the GENESIS_ACCOUNT at genesis - public fun initialize(account: &signer, parent_hash: vector) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - - move_to( - account, - BlockMetadata { - number: 0, - parent_hash: parent_hash, - author: CoreAddresses::GENESIS_ADDRESS(), - uncles: 0, - new_block_events: Event::new_event_handle(account), - }); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if exists(Signer::address_of(account)); - } - - /// Get the current block number - public fun get_current_block_number(): u64 acquires BlockMetadata { - borrow_global(CoreAddresses::GENESIS_ADDRESS()).number - } - - spec get_current_block_number { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get the hash of the parent block. - public fun get_parent_hash(): vector acquires BlockMetadata { - *&borrow_global(CoreAddresses::GENESIS_ADDRESS()).parent_hash - } - - spec get_parent_hash { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Gets the address of the author of the current block - public fun get_current_author(): address acquires BlockMetadata { - borrow_global(CoreAddresses::GENESIS_ADDRESS()).author - } - - spec get_current_author { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Call at block prologue - public fun process_block_metadata(account: &signer, parent_hash: vector,author: address, timestamp: u64, uncles:u64, number:u64) acquires BlockMetadata{ - CoreAddresses::assert_genesis_address(account); - - let block_metadata_ref = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - assert!(number == (block_metadata_ref.number + 1), Errors::invalid_argument(EBLOCK_NUMBER_MISMATCH)); - block_metadata_ref.number = number; - block_metadata_ref.author= author; - block_metadata_ref.parent_hash = parent_hash; - block_metadata_ref.uncles = uncles; - - Event::emit_event( - &mut block_metadata_ref.new_block_events, - NewBlockEvent { - number: number, - author: author, - timestamp: timestamp, - uncles: uncles, - } - ); - } - - spec process_block_metadata { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if number != global(CoreAddresses::GENESIS_ADDRESS()).number + 1; - } - - spec schema AbortsIfBlockMetadataNotExist { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - public fun checkpoints_init(){ - - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - - let checkpoints = Ring::create_with_capacity(CHECKPOINT_LENGTH); - move_to( - &signer, - Checkpoints { - checkpoints : checkpoints, - index : 0, - last_number : 0, - }); - } - - spec checkpoints_init { - pragma verify = false; - } - - public (script) fun checkpoint_entry(_account: signer) acquires BlockMetadata, Checkpoints { - checkpoint(); - } - - spec checkpoint_entry { - pragma verify = false; - } - - public fun checkpoint() acquires BlockMetadata, Checkpoints{ - let parent_block_number = get_current_block_number() - 1; - let parent_block_hash = get_parent_hash(); - - let checkpoints = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - base_checkpoint(checkpoints, parent_block_number, parent_block_hash); - - } - - spec checkpoint { - pragma verify = false; - } - - fun base_checkpoint(checkpoints: &mut Checkpoints, parent_block_number: u64, parent_block_hash:vector){ - assert!(checkpoints.last_number + BLOCK_INTERVAL_NUMBER <= parent_block_number || checkpoints.last_number == 0, Errors::invalid_argument(ERROR_INTERVAL_TOO_LITTLE)); - - checkpoints.index = checkpoints.index + 1; - checkpoints.last_number = parent_block_number; - let op_checkpoint = Ring::push(&mut checkpoints.checkpoints, Checkpoint { - block_number: parent_block_number, - block_hash: parent_block_hash, - state_root: Option::none>(), - } ); - if(Option::is_some(&op_checkpoint)){ - Option::destroy_some(op_checkpoint); - }else{ - Option::destroy_none(op_checkpoint); - } - } - - spec base_checkpoint { - pragma verify = false; - } - - public fun latest_state_root():(u64,vector) acquires Checkpoints{ - let checkpoints = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - base_latest_state_root(checkpoints) - } - - spec latest_state_root { - pragma verify = false; - } - - fun base_latest_state_root(checkpoints: &Checkpoints):(u64,vector){ - let len = Ring::capacity(&checkpoints.checkpoints); - let j = if(checkpoints.index < len - 1){ - checkpoints.index - }else{ - len - }; - let i = checkpoints.index; - while( j > 0){ - let op_checkpoint = Ring::borrow(&checkpoints.checkpoints, i - 1 ); - if( Option::is_some(op_checkpoint) && Option::is_some(&Option::borrow(op_checkpoint).state_root) ) { - let state_root = Option::borrow(&Option::borrow(op_checkpoint).state_root); - return (Option::borrow(op_checkpoint).block_number, *state_root) - }; - j = j - 1; - i = i - 1; - }; - - abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT) - } - - spec base_latest_state_root { - pragma verify = false; - } - - public (script) fun update_state_root_entry(_account: signer , header: vector) - acquires Checkpoints { - update_state_root(header); - } - - spec update_state_root_entry { - pragma verify = false; - } - - public fun update_state_root(header: vector) acquires Checkpoints { - let checkpoints = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - base_update_state_root(checkpoints, header); - } - - spec update_state_root { - pragma verify = false; - } - - fun base_update_state_root(checkpoints: &mut Checkpoints, header: vector){ - let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader"); - - //parent_hash - let new_offset = BCS::skip_bytes(&header,0); - //timestamp - let new_offset = BCS::skip_u64(&header,new_offset); - //number - let (number,new_offset) = BCS::deserialize_u64(&header,new_offset); - //author - new_offset = BCS::skip_address(&header,new_offset); - //author_auth_key - new_offset = BCS::skip_option_bytes(&header,new_offset); - //txn_accumulator_root - new_offset = BCS::skip_bytes(&header,new_offset); - //block_accumulator_root - new_offset = BCS::skip_bytes(&header,new_offset); - //state_root - let (state_root,_new_offset) = BCS::deserialize_bytes(&header,new_offset); - - Vector::append(&mut prefix,header); - let block_hash = Hash::sha3_256(prefix); - - let len = Ring::capacity(&checkpoints.checkpoints); - let j = if(checkpoints.index < len - 1){ - checkpoints.index - }else{ - len - }; - let i = checkpoints.index; - while( j > 0){ - let op_checkpoint = Ring::borrow_mut(&mut checkpoints.checkpoints, i - 1); - - if( Option::is_some(op_checkpoint) && &Option::borrow(op_checkpoint).block_hash == &block_hash && Option::borrow(op_checkpoint).block_number == number) { - - let op_state_root = &mut Option::borrow_mut(op_checkpoint).state_root; - if(Option::is_some(op_state_root)){ - Option::swap(op_state_root, state_root); - }else{ - Option::fill(op_state_root, state_root); - }; - return - }; - j = j - 1; - i = i - 1; - }; - - abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT) - } - - spec base_update_state_root { - pragma verify = false; - } - - #[test] - fun test_header(){ - // Block header Unit test - // Use Main Genesis BlockHeader in Rust - // BlockHeader { - // id: Some(HashValue(0x80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d)), - // parent_hash: HashValue(0xb82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529a), - // timestamp: 1621311100863, - // number: 0, - // author: 0x00000000000000000000000000000001, - // author_auth_key: None, - // txn_accumulator_root: HashValue(0x43609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae), - // block_accumulator_root: HashValue(0x414343554d554c41544f525f504c414345484f4c4445525f4841534800000000), - // state_root: HashValue(0x61125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d), - // gas_used: 0, - // difficulty: 11660343, - // body_hash: HashValue(0x7564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b), - // chain_id: ChainId { id: 1 }, - // nonce: 0, - // extra: BlockHeaderExtra([0, 0, 0, 0]) - // } - // Blockheader BCS : 20b82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529abf17ac7d79010000000000000000000000000000000000000000000000000001002043609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae20414343554d554c41544f525f504c414345484f4c4445525f48415348000000002061125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d00000000000000000000000000000000000000000000000000000000000000000000000000b1ec37207564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b010000000000000000 - - let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader"); - let header = x"20b82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529abf17ac7d79010000000000000000000000000000000000000000000000000001002043609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae20414343554d554c41544f525f504c414345484f4c4445525f48415348000000002061125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d00000000000000000000000000000000000000000000000000000000000000000000000000b1ec37207564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b010000000000000000"; - let (_parent_hash,new_offset) = BCS::deserialize_bytes(&header,0); - let (_timestamp,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (number,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_author,new_offset) = BCS::deserialize_address(&header,new_offset); - let (_author_auth_key,new_offset) = BCS::deserialize_option_bytes(&header,new_offset); - let (_txn_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_block_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (state_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_gas_used,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_difficultyfirst,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_difficultylast,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_body_hash,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_chain_id,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_nonce,new_offset) = BCS::deserialize_u32(&header,new_offset); - let (_extra1,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra2,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra3,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra4,_new_offset) = BCS::deserialize_u8(&header,new_offset); - - Vector::append(&mut prefix,header); - let block_hash = Hash::sha3_256(prefix); - assert!(block_hash == x"80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d" ,1001); - assert!(number == 0,1002); - assert!(state_root == x"61125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d",1003); - } - - #[test] - fun test_header2(){ - // Block header Unit test - // Use BlockHeader in integration test - //"number":"2", - //"block_hash":"0x9433bb7b56333dfc33e012f3b22b67277a3026448eb5043747d59284f648343d" - //"parent_hash":"0x9be97e678afa8a0a4cf9ca612be6f64810a6f7d5f8b4b4ddf5e4971ef4b5eb48" - //"state_root":"0xd2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a" - //"header":"0x209be97e678afa8a0a4cf9ca612be6f64810a6f7d5f8b4b4ddf5e4971ef4b5eb4820aa26050000000002000000000000000000000000000000000000000000000200205c79e9493845327132ab3011c7c6c9d8bddcfde5553abb90cf5ef7fdfb39a4aa20c4d8e6cdb52520794dad5241f51a4eed46a5e5264dd148032cc3bdb8e3bdbe7a20d2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a0000000000000000000000000000000000000000000000000000000000000000000000000000000020c01e0329de6d899348a8ef4bd51db56175b3fa0988e57c3dcec8eaf13a164d97fe0000000000000000" - - let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader"); - let header = x"209be97e678afa8a0a4cf9ca612be6f64810a6f7d5f8b4b4ddf5e4971ef4b5eb4820aa26050000000002000000000000000000000000000000000000000000000200205c79e9493845327132ab3011c7c6c9d8bddcfde5553abb90cf5ef7fdfb39a4aa20c4d8e6cdb52520794dad5241f51a4eed46a5e5264dd148032cc3bdb8e3bdbe7a20d2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a0000000000000000000000000000000000000000000000000000000000000000000000000000000020c01e0329de6d899348a8ef4bd51db56175b3fa0988e57c3dcec8eaf13a164d97fe0000000000000000"; - let (_parent_hash,new_offset) = BCS::deserialize_bytes(&header,0); - let (_timestamp,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (number,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_author,new_offset) = BCS::deserialize_address(&header,new_offset); - let (_author_auth_key,new_offset) = BCS::deserialize_option_bytes(&header,new_offset); - let (_txn_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_block_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (state_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_gas_used,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_difficultyfirst,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_difficultylast,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_body_hash,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_chain_id,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_nonce,new_offset) = BCS::deserialize_u32(&header,new_offset); - let (_extra1,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra2,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra3,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra4,_new_offset) = BCS::deserialize_u8(&header,new_offset); - - Vector::append(&mut prefix,header); - let block_hash = Hash::sha3_256(prefix); - assert!(block_hash == x"9433bb7b56333dfc33e012f3b22b67277a3026448eb5043747d59284f648343d" ,1001); - assert!(number == 2,1002); - assert!(state_root == x"d2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a",1003); - } - - #[test] - fun test_checkpoint(){ - let checkpoints = Checkpoints { - checkpoints : Ring::create_with_capacity(3), - index : 0, - last_number : 0 - }; - - base_checkpoint(&mut checkpoints, 0, x"80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d"); - - let Checkpoints{ - checkpoints: ring, - index : index, - last_number: last_number - } = checkpoints; - assert!( index == 1 && last_number == 0 , 10020); - Ring::destroy(ring); - } - - #[test] - fun test_latest_state_root(){ - let header = x"20b82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529abf17ac7d79010000000000000000000000000000000000000000000000000001002043609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae20414343554d554c41544f525f504c414345484f4c4445525f48415348000000002061125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d00000000000000000000000000000000000000000000000000000000000000000000000000b1ec37207564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b010000000000000000"; - - let checkpoints = Checkpoints { - checkpoints : Ring::create_with_capacity(3), - index : 0, - last_number : 0 - }; - - base_checkpoint(&mut checkpoints, 0, x"80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d"); - - base_update_state_root(&mut checkpoints, copy header); - - let (number , state_root ) = base_latest_state_root(&checkpoints); - let Checkpoints{ - checkpoints: ring, - index : index, - last_number: last_number - } = checkpoints; - assert!( index == 1 && last_number == 0 , 10020); - assert!( number == 0 && state_root == x"61125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d" , 10020); - Ring::destroy(ring); - } - -} -} \ No newline at end of file diff --git a/release/v12/sources/BlockReward.move b/release/v12/sources/BlockReward.move deleted file mode 100644 index de9a96bd..00000000 --- a/release/v12/sources/BlockReward.move +++ /dev/null @@ -1,192 +0,0 @@ -address StarcoinFramework { -/// The module provide block rewarding calculation logic. -module BlockReward { - use StarcoinFramework::Timestamp; - use StarcoinFramework::Token; - use StarcoinFramework::STC::{STC}; - use StarcoinFramework::Vector; - use StarcoinFramework::Account; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::Config; - use StarcoinFramework::Event; - use StarcoinFramework::Treasury; - use StarcoinFramework::TreasuryPlugin; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Queue of rewards distributed to miners. - struct RewardQueue has key { - /// How many block rewards has been handled. - reward_number: u64, - /// informations about the reward distribution. - infos: vector, - /// event handle used to emit block reward event. - reward_events: Event::EventHandle, - } - - /// Reward info of miners. - struct RewardInfo has store { - /// number of the block miner minted. - number: u64, - /// how many stc rewards. - reward: u128, - /// miner who mint the block. - miner: address, - /// store the gas fee that users consumed. - gas_fees: Token::Token, - } - - /// block reward event - struct BlockRewardEvent has drop, store { - /// block number - block_number: u64, - /// STC reward. - block_reward: u128, - /// gas fees in STC. - gas_fees: u128, - /// block miner - miner: address, - } - - const EAUTHOR_AUTH_KEY_IS_EMPTY: u64 = 101; - const ECURRENT_NUMBER_IS_WRONG: u64 = 102; - const EREWARD_NUMBER_IS_WRONG: u64 = 103; - const EMINER_EXIST: u64 = 104; - const EAUTHOR_ADDRESS_AND_AUTH_KEY_MISMATCH: u64 = 105; - - /// Initialize the module, should be called in genesis. - public fun initialize(account: &signer, reward_delay: u64) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - - RewardConfig::initialize(account, reward_delay); - move_to(account, RewardQueue { - reward_number: 0, - infos: Vector::empty(), - reward_events: Event::new_event_handle(account), - }); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - include Config::PublishNewConfigAbortsIf; - include Config::PublishNewConfigEnsures; - aborts_if exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Process the given block rewards. - public fun process_block_reward(account: &signer, current_number: u64, current_reward: u128, - current_author: address, _auth_key_vec: vector, - previous_block_gas_fees: Token::Token) acquires RewardQueue { - CoreAddresses::assert_genesis_address(account); - if (current_number == 0) { - Token::destroy_zero(previous_block_gas_fees); - return - }; - - let rewards = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let len = Vector::length(&rewards.infos); - assert!((current_number == (rewards.reward_number + len + 1)), Errors::invalid_argument(ECURRENT_NUMBER_IS_WRONG)); - - // distribute gas fee to last block reward info. - // if not last block reward info, the passed in gas fee must be zero. - if (len == 0) { - Token::destroy_zero(previous_block_gas_fees); - } else { - let reward_info = Vector::borrow_mut(&mut rewards.infos, len - 1); - assert!(current_number == reward_info.number + 1, Errors::invalid_argument(ECURRENT_NUMBER_IS_WRONG)); - Token::deposit(&mut reward_info.gas_fees, previous_block_gas_fees); - }; - - let reward_delay = RewardConfig::reward_delay(); - if (len >= reward_delay) {//pay and remove - let i = len; - while (i > 0 && i >= reward_delay) { - let RewardInfo { number: reward_block_number, reward: block_reward, gas_fees, miner } = Vector::remove(&mut rewards.infos, 0); - - let gas_fee_value = Token::value(&gas_fees); - let total_reward = gas_fees; - // add block reward to total. - if (block_reward > 0) { - // if no STC in Treasury, BlockReward will been 0. - let treasury_balance = Treasury::balance(); - if (treasury_balance < block_reward) { - block_reward = treasury_balance; - }; - if (block_reward > 0) { - let reward = TreasuryPlugin::withdraw_for_block_reward(account, block_reward); - Token::deposit(&mut total_reward, reward); - }; - }; - // distribute total. - if (Token::value(&total_reward) > 0) { - Account::deposit(miner, total_reward); - } else { - Token::destroy_zero(total_reward); - }; - // emit reward event. - Event::emit_event( - &mut rewards.reward_events, - BlockRewardEvent { - block_number: reward_block_number, - block_reward: block_reward, - gas_fees: gas_fee_value, - miner, - } - ); - - rewards.reward_number = rewards.reward_number + 1; - i = i - 1; - } - }; - - if (!Account::exists_at(current_author)) { - Account::create_account_with_address(current_author); - }; - let current_info = RewardInfo { - number: current_number, - reward: current_reward, - miner: current_author, - gas_fees: Token::zero(), - }; - Vector::push_back(&mut rewards.infos, current_info); - - } - - spec process_block_reward { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - // abort if current block is genesis, and previous block gas fees != 0 - aborts_if current_number == 0 && Token::value(previous_block_gas_fees) != 0; - - aborts_if current_number > 0 && !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if current_number > 0 && (global(CoreAddresses::GENESIS_ADDRESS()).reward_number + Vector::length(global(CoreAddresses::GENESIS_ADDRESS()).infos) + 1) != current_number; - aborts_if current_number > 0 && !exists>(CoreAddresses::GENESIS_ADDRESS()); - - - let reward_info_length = Vector::length(global(CoreAddresses::GENESIS_ADDRESS()).infos); - - // abort if no previous block but has gas fees != 0. - aborts_if current_number > 0 && reward_info_length == 0 && Token::value(previous_block_gas_fees) != 0; - // abort if previous block number != current_block_number - 1. - aborts_if current_number > 0 && reward_info_length != 0 && Vector::borrow(global(CoreAddresses::GENESIS_ADDRESS()).infos, reward_info_length - 1).number != current_number - 1; - - aborts_if current_number > 0 && Vector::length(global(CoreAddresses::GENESIS_ADDRESS()).infos) >= global>(CoreAddresses::GENESIS_ADDRESS()).payload.reward_delay - && (global(CoreAddresses::GENESIS_ADDRESS()).reward_number + 1) != Vector::borrow(global(CoreAddresses::GENESIS_ADDRESS()).infos, 0).number; - - aborts_if current_number > 0 && Vector::length(global(CoreAddresses::GENESIS_ADDRESS()).infos) >= global>(CoreAddresses::GENESIS_ADDRESS()).payload.reward_delay - && (global(CoreAddresses::GENESIS_ADDRESS()).reward_number + 1) > max_u64(); - - aborts_if current_number > 0 && !Account::exists_at(current_author) ; - - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/ChainId.move b/release/v12/sources/ChainId.move deleted file mode 100644 index 927777a8..00000000 --- a/release/v12/sources/ChainId.move +++ /dev/null @@ -1,94 +0,0 @@ -address StarcoinFramework { -/// The module provides chain id information. -module ChainId { - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Signer; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// chain id data structure. - struct ChainId has key { - /// real id. - id: u8 - } - - const MAIN_CHAIN_ID: u8 = 1; - const BARNARD_CHAIN_ID: u8 = 251; - const PROXIMA_CHAIN_ID: u8 = 252; - const HALLEY_CHAIN_ID: u8 = 253; - const DEV_CHAIN_ID: u8 = 254; - const TEST_CHAIN_ID: u8 = 255; - - /// Publish the chain ID under the genesis account - public fun initialize(account: &signer, id: u8) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - move_to(account, ChainId { id }); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if exists(Signer::address_of(account)); - ensures exists(Signer::address_of(account)); - } - - /// Return the chain ID of this chain - public fun get(): u8 acquires ChainId { - borrow_global(CoreAddresses::GENESIS_ADDRESS()).id - } - - public fun is_dev(): bool acquires ChainId { - get() == DEV_CHAIN_ID - } - public fun is_test(): bool acquires ChainId { - get() == TEST_CHAIN_ID - } - public fun is_halley(): bool acquires ChainId { - get() == HALLEY_CHAIN_ID - } - public fun is_proxima(): bool acquires ChainId { - get() == PROXIMA_CHAIN_ID - } - public fun is_barnard(): bool acquires ChainId { - get() == BARNARD_CHAIN_ID - } - public fun is_main(): bool acquires ChainId { - get() == MAIN_CHAIN_ID - } - - spec is_dev { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } - spec is_test { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } - spec is_halley { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } - spec is_proxima { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } - spec is_barnard { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } - spec is_main { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } - - spec get { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures exists(CoreAddresses::GENESIS_ADDRESS()); - } -} -} diff --git a/release/v12/sources/Collection.move b/release/v12/sources/Collection.move deleted file mode 100644 index d2ffcbd0..00000000 --- a/release/v12/sources/Collection.move +++ /dev/null @@ -1,118 +0,0 @@ -address StarcoinFramework { -/// Deprecated since @v3 please use Collection2 -/// Provide a account based vector for save resource. -module Collection { - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - use StarcoinFramework::Option::{Self, Option}; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = false; - } - - /// Collection in memory, can not drop & store. - struct Collection{ - items:vector, - /// the owner of Collection. - owner: address, - } - - /// Collection in global store. - struct CollectionStore has key { - /// items in the CollectionStore. - /// use Option at here is for temporary take away from store to construct Collection. - items: Option>, - } - - const EDEPRECATED_FUNCTION: u64 = 19; - - const ECOLLECTION_NOT_EXIST: u64 = 101; - /// The operator require the collection owner. - const ECOLLECTION_NOT_OWNER: u64 = 102; - - /// Acquire an immutable reference to the `i`th element of the collection `c`. - /// Aborts if `i` is out of bounds. - public fun borrow(c: &Collection, i: u64): &T{ - Vector::borrow(&c.items, i) - } - - /// Pop an element from the end of vector `v`. - /// Aborts if `v` is empty. - public fun pop_back(account: &signer, c: &mut Collection): T { - assert!(Signer::address_of(account) == c.owner, Errors::requires_address(ECOLLECTION_NOT_OWNER)); - Vector::pop_back(&mut c.items) - } - - /// check the Collection exists in `addr` - fun exists_at(addr: address): bool{ - exists>(addr) - } - - spec exists_at {aborts_if false;} - - /// Deprecated since @v3 - /// Put items to account's Collection last position. - public fun put(_account: &signer, _item: T) { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - spec put {aborts_if false;} - - /// Take last item from account's Collection of T. - public fun take(account: &signer): T acquires CollectionStore{ - let addr = Signer::address_of(account); - let c = borrow_collection(addr); - let item = pop_back(account, &mut c); - return_collection(c); - item - } - - spec take { - aborts_if false; - } - - /// Borrow collection of T from `addr` - public fun borrow_collection(addr: address): Collection acquires CollectionStore{ - assert!(exists_at(addr), Errors::invalid_state(ECOLLECTION_NOT_EXIST)); - let c = borrow_global_mut>(addr); - let items = Option::extract(&mut c.items); - Collection{ - items, - owner: addr - } - } - - spec borrow_collection { - aborts_if false; - } - - /// Return the Collection of T - public fun return_collection(c: Collection) acquires CollectionStore{ - let Collection{ items, owner } = c; - if (Vector::is_empty(&items)) { - let c = move_from>(owner); - destroy_empty(c); - Vector::destroy_empty(items); - }else{ - let c = borrow_global_mut>(owner); - Option::fill(&mut c.items, items); - } - } - - spec return_collection { - aborts_if false; - } - - fun destroy_empty(c: CollectionStore){ - let CollectionStore{ items } = c; - Option::destroy_none(items); - } - - spec destroy_empty { - aborts_if false; - } - -} -} \ No newline at end of file diff --git a/release/v12/sources/Collection2.move b/release/v12/sources/Collection2.move deleted file mode 100644 index db5f44e3..00000000 --- a/release/v12/sources/Collection2.move +++ /dev/null @@ -1,235 +0,0 @@ -address StarcoinFramework { -/// Provide a account based vector for save resource item. -/// The resource in CollectionStore can borrowed by anyone, anyone can get immutable ref of item. -/// and the owner of Collection can allow others to add item to Collection or get mut ref from Collection.git -module Collection2 { - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - use StarcoinFramework::Option::{Self, Option}; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = false; - } - - /// Collection in memory, can not drop & store. - struct Collection{ - items: vector, - owner: address, - can_put: bool, - can_mut: bool, - can_take: bool, - } - - /// Collection in global store. - struct CollectionStore has key { - /// items in the CollectionStore. - /// use Option at here is for temporary take away from store to construct Collection. - items: Option>, - anyone_can_put: bool, - anyone_can_mut: bool, - } - - const ERR_COLLECTION_NOT_EXIST: u64 = 101; - /// The operator require the collection owner or collection set anyone_can_put to true. - const ERR_COLLECTION_CAN_NOT_ADD: u64 = 102; - /// The operator require the collection owner or collection set anyone_can_mut to true. - const ERR_COLLECTION_CAN_NOT_MUT: u64 = 103; - /// The operator require the collection owner - const ERR_COLLECTION_CAN_NOT_TAKE: u64 = 104; - const ERR_COLLECTION_INVALID_BORROW_STATE: u64 = 105; - const ERR_COLLECTION_IS_NOT_EMPTY: u64 = 106; - - /// Return the length of the collection. - public fun length(c: &Collection): u64{ - Vector::length(&c.items) - } - - spec length {aborts_if false;} - - /// Acquire an immutable reference to the `i`th element of the collection `c`. - /// Aborts if `i` is out of bounds. - public fun borrow(c: &Collection, i: u64): &T{ - Vector::borrow(&c.items, i) - } - - /// Add item `v` to the end of the collection `c`. - /// require owner of Collection. - public fun push_back(c: &mut Collection, t: T){ - assert!(c.can_put, Errors::requires_address(ERR_COLLECTION_CAN_NOT_ADD)); - Vector::push_back(&mut c.items, t); - } - - /// Return a mutable reference to the `i`th item in the Collection `c`. - /// Aborts if `i` is out of bounds. - public fun borrow_mut(c: &mut Collection, i: u64): &mut T{ - assert!(c.can_mut, Errors::requires_address(ERR_COLLECTION_CAN_NOT_MUT)); - Vector::borrow_mut(&mut c.items, i) - } - - /// Pop an element from the end of vector `v`. - /// Aborts if `v` is empty. - public fun pop_back(c: &mut Collection): T { - assert!(c.can_take, Errors::requires_address(ERR_COLLECTION_CAN_NOT_TAKE)); - Vector::pop_back(&mut c.items) - } - - public fun remove(c: &mut Collection, i: u64): T{ - assert!(c.can_take, Errors::requires_address(ERR_COLLECTION_CAN_NOT_TAKE)); - Vector::remove(&mut c.items, i) - } - - public fun append(c: &mut Collection, other: T) { - assert!(c.can_put, Errors::requires_address(ERR_COLLECTION_CAN_NOT_ADD)); - Vector::append(&mut c.items, Vector::singleton(other)) - } - - public fun append_all(c: &mut Collection, other: vector) { - assert!(c.can_put, Errors::requires_address(ERR_COLLECTION_CAN_NOT_ADD)); - Vector::append(&mut c.items, other) - } - - /// check the Collection exists in `addr` - public fun exists_at(addr: address): bool{ - exists>(addr) - } - - spec exists_at {aborts_if false;} - - /// check `addr` is accept T and other can send T to `addr`, - /// it means exists a Collection of T at `addr` and anyone_can_put of the Collection is true - public fun is_accept(addr: address): bool acquires CollectionStore { - if (!exists>(addr)){ - return false - }; - let cs = borrow_global>(addr); - cs.anyone_can_put - } - - /// signer allow other send T to self - /// create a Collection of T and set anyone_can_put to true - /// if the Collection exists, just update anyone_can_put to true - public fun accept(signer: &signer) acquires CollectionStore { - let addr = Signer::address_of(signer); - if (!exists>(addr)){ - Self::create_collection(signer, true, false); - }; - let cs = borrow_global_mut>(addr); - if (!cs.anyone_can_put) { - cs.anyone_can_put = true; - } - } - - /// Put items to `to_addr`'s Collection of T - /// put = borrow_collection + append + return_collection. - public fun put(signer: &signer, owner: address, item: T) acquires CollectionStore{ - let c = Self::borrow_collection(signer, owner); - Self::append(&mut c, item); - Self::return_collection(c); - } - - spec put {aborts_if false;} - - /// Put all items to owner's collection of T. - public fun put_all(signer: &signer, owner: address, items: vector) acquires CollectionStore{ - let c = Self::borrow_collection(signer, owner); - Self::append_all(&mut c, items); - Self::return_collection(c); - } - - spec put_all {aborts_if false;} - - /// Take last item from signer's Collection of T. - public fun take(signer: &signer): T acquires CollectionStore{ - let addr = Signer::address_of(signer); - let c = borrow_collection(signer, addr); - let item = pop_back(&mut c); - return_collection(c); - item - } - - spec take { - aborts_if false; - } - - public fun create_collection(signer: &signer, anyone_can_put: bool, anyone_can_mut: bool) { - move_to(signer, CollectionStore{items: Option::some(Vector::empty()), anyone_can_put, anyone_can_mut}) - } - - /// Return the length of Collection from `owner`, if collection do not exist, return 0. - public fun length_of(owner: address) : u64 acquires CollectionStore{ - if (exists_at(owner)){ - let cs = borrow_global_mut>(owner); - //if items is None, indicate it is borrowed - assert!(!Option::is_none(&cs.items), Errors::invalid_state(ERR_COLLECTION_INVALID_BORROW_STATE)); - let items = Option::borrow(&cs.items); - Vector::length(items) - }else{ - 0 - } - } - - /// Borrow collection of T from `owner`, auto detected the collection's can_put|can_mut|can_take by the `sender` and Collection config. - public fun borrow_collection(sender: &signer, owner: address): Collection acquires CollectionStore{ - assert!(exists_at(owner), Errors::invalid_state(ERR_COLLECTION_NOT_EXIST)); - let cs = borrow_global_mut>(owner); - //if items is None, indicate it is borrowed - assert!(!Option::is_none(&cs.items), Errors::invalid_state(ERR_COLLECTION_INVALID_BORROW_STATE)); - let items = Option::extract(&mut cs.items); - let is_owner = owner == Signer::address_of(sender); - let can_put = cs.anyone_can_put || is_owner; - let can_mut = cs.anyone_can_mut || is_owner; - let can_take = is_owner; - Collection{ - items, - owner, - can_put, - can_mut, - can_take, - } - } - - spec borrow_collection { - aborts_if false; - } - - /// Return the Collection of T - public fun return_collection(c: Collection) acquires CollectionStore{ - let Collection{ items, owner, can_put:_, can_mut:_, can_take:_ } = c; - let cs = borrow_global_mut>(owner); - assert!(Option::is_none(&cs.items), Errors::invalid_state(ERR_COLLECTION_INVALID_BORROW_STATE)); - Option::fill(&mut cs.items, items); - } - - spec return_collection { - aborts_if false; - } - - public fun destroy_collection(signer: &signer) acquires CollectionStore{ - let c = move_from>(Signer::address_of(signer)); - destroy_empty(c); - } - - spec destroy_collection { - aborts_if false; - } - - fun destroy_empty(c: CollectionStore){ - let CollectionStore{ items, anyone_can_put:_, anyone_can_mut:_,} = c; - if (Option::is_some(&items)) { - let item_vec = Option::extract(&mut items); - assert!(Vector::is_empty(&item_vec), Errors::invalid_state(ERR_COLLECTION_IS_NOT_EMPTY)); - Vector::destroy_empty(item_vec); - Option::destroy_none(items); - }else{ - Option::destroy_none(items); - } - } - - spec destroy_empty { - aborts_if false; - } - -} -} \ No newline at end of file diff --git a/release/v12/sources/Compare.move b/release/v12/sources/Compare.move deleted file mode 100644 index 41110b9b..00000000 --- a/release/v12/sources/Compare.move +++ /dev/null @@ -1,126 +0,0 @@ -address StarcoinFramework { -module Compare { - use StarcoinFramework::Vector; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - const EQUAL: u8 = 0; - const LESS_THAN: u8 = 1; - const GREATER_THAN: u8 = 2; - - /// Compare `v1` and `v2` using - /// (1) byte-by-byte comparison from right to left until we reach the end of the shorter vector, - /// then - /// (2) vector length to break ties. - /// Returns either `EQUAL` (0u8), `LESS_THAN` (1u8), or `GREATER_THAN` (2u8). - /// This function is designed to compare BCS (Starcoin Canonical Serialization)-encoded values - /// (i.e., vectors produced by `BCS::to_bytes`). A typical client will call - /// `Compare::cmp_bcs_bytes(BCS::to_bytes(&t1), BCS::to_bytes(&t2))`. The comparison provides the - /// following guarantees w.r.t the original values t1 and t2: - /// - `cmp_bcs_bytes(bcs_ext(t1), bcs_ext(t2)) == LESS_THAN` iff `cmp_bcs_bytes(t2, t1) == GREATER_THAN` - /// - `Compare::cmp(t1, t2) == EQUAL` iff `t1 == t2` and (similarly) - /// `Compare::cmp(t1, t2) != EQUAL` iff `t1 != t2`, where `==` and `!=` denote the Move - /// bytecode operations for polymorphic equality. - /// - for all primitive types `T` with `<` and `>` comparison operators exposed in Move bytecode - /// (`u8`, `u64`, `u128`), we have - /// `compare_bcs_bytes(bcs_ext(t1), bcs_ext(t2)) == LESS_THAN` iff `t1 < t2` and (similarly) - /// `compare_bcs_bytes(bcs_ext(t1), bcs_ext(t2)) == LESS_THAN` iff `t1 > t2`. - /// For all other types, the order is whatever the BCS encoding of the type and the comparison - /// strategy above gives you. One case where the order might be surprising is the `address` type. - /// CoreAddresses are 16 byte hex values that BCS encodes with the identity function. The right to - /// left, byte-by-byte comparison means that (for example) - /// `compare_bcs_bytes(bcs_ext(0x01), bcs_ext(0x10)) == LESS_THAN` (as you'd expect), but - /// `compare_bcs_bytes(bcs_ext(0x100), bcs_ext(0x001)) == LESS_THAN` (as you probably wouldn't expect). - /// Keep this in mind when using this function to compare addresses. - public fun cmp_bcs_bytes(v1: &vector, v2: &vector): u8 { - let i1 = Vector::length(v1); - let i2 = Vector::length(v2); - let len_cmp = cmp_u64(i1, i2); - - // BCS uses little endian encoding for all integer types, so we choose to compare from left - // to right. Going right to left would make the behavior of Compare.cmp diverge from the - // bytecode operators < and > on integer values (which would be confusing). - while (i1 > 0 && i2 > 0) { - i1 = i1 - 1; - i2 = i2 - 1; - let v1 = *Vector::borrow(v1, i1); - let v2 = *Vector::borrow(v2, i2); - let elem_cmp = if (v1 == v2) EQUAL - else if (v1 < v2) LESS_THAN - else GREATER_THAN; - if (elem_cmp != 0) return elem_cmp - // else, compare next element - }; - // all compared elements equal; use length comparison to break the tie - len_cmp - } - - public fun cmp_bytes(v1: &vector, v2: &vector): u8 { - let l1 = Vector::length(v1); - let l2 = Vector::length(v2); - let len_cmp = cmp_u64(l1, l2); - let i = 0; - while (i < l1 && i < l2) { - let v1 = *Vector::borrow(v1, i); - let v2 = *Vector::borrow(v2, i); - let elem_cmp = if (v1 == v2) EQUAL - else if (v1 < v2) LESS_THAN - else GREATER_THAN; - if (elem_cmp != 0) { - return elem_cmp - }; - // else, compare next element - i = i + 1; - }; - // all compared elements equal; use length comparison to break the tie - len_cmp - } - - spec cmp_bytes { - pragma verify = false; - } - - spec cmp_bcs_bytes { - pragma verify = false; - } - - // Compare two `u64`'s - fun cmp_u64(i1: u64, i2: u64): u8 { - if (i1 == i2) EQUAL - else if (i1 < i2) LESS_THAN - else GREATER_THAN - } - - spec cmp_u64 { - aborts_if false; - } - - public fun is_equal(result: u8): bool { - result == EQUAL - } - - spec is_equal { - aborts_if false; - } - - public fun is_less_than(result: u8): bool { - result == LESS_THAN - } - - spec is_less_than { - aborts_if false; - } - - public fun is_greater_than(result: u8): bool { - result == GREATER_THAN - } - - spec is_greater_than { - aborts_if false; - } -} - -} diff --git a/release/v12/sources/Config.move b/release/v12/sources/Config.move deleted file mode 100644 index 54e28ab0..00000000 --- a/release/v12/sources/Config.move +++ /dev/null @@ -1,281 +0,0 @@ -address StarcoinFramework { -/// The module provides a general implmentation of configuration for onchain contracts. -module Config { - use StarcoinFramework::Event; - use StarcoinFramework::Signer; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::Errors; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// A generic singleton resource that holds a value of a specific type. - struct Config has key { payload: ConfigValue } - - /// Accounts with this privilege can modify config of type ConfigValue under account_address - struct ModifyConfigCapability has store { - account_address: address, - events: Event::EventHandle>, - } - - /// A holder for ModifyConfigCapability, for extraction and restoration of ModifyConfigCapability. - struct ModifyConfigCapabilityHolder has key, store { - cap: Option>, - } - - /// Event emitted when config value is changed. - struct ConfigChangeEvent has drop, store { - account_address: address, - value: ConfigValue, - } - - const ECONFIG_VALUE_DOES_NOT_EXIST: u64 = 13; - const ECAPABILITY_HOLDER_NOT_EXISTS: u64 = 101; - - - - spec fun spec_get(addr: address): ConfigValue { - global>(addr).payload - } - - - /// Get a copy of `ConfigValue` value stored under `addr`. - public fun get_by_address(addr: address): ConfigValue acquires Config { - assert!(exists>(addr), Errors::invalid_state(ECONFIG_VALUE_DOES_NOT_EXIST)); - *&borrow_global>(addr).payload - } - - spec get_by_address { - aborts_if !exists>(addr); - ensures exists>(addr); - ensures result == spec_get(addr); - } - - /// Check whether the config of `ConfigValue` type exists under `addr`. - public fun config_exist_by_address(addr: address): bool { - exists>(addr) - } - - spec config_exist_by_address { - aborts_if false; - ensures result == exists>(addr); - } - - /// Set a config item to a new value with capability stored under signer - public fun set( - account: &signer, - payload: ConfigValue, - ) acquires Config, ModifyConfigCapabilityHolder { - let signer_address = Signer::address_of(account); - assert!( - exists>(signer_address), - Errors::requires_capability(ECAPABILITY_HOLDER_NOT_EXISTS), - ); - let cap_holder = borrow_global_mut>(signer_address); - assert!(Option::is_some(&cap_holder.cap), Errors::requires_capability(ECAPABILITY_HOLDER_NOT_EXISTS)); - set_with_capability(Option::borrow_mut(&mut cap_holder.cap), payload); - } - - spec set { - let addr = Signer::address_of(account); - let cap_opt = spec_cap(addr); - let cap = Option::borrow(spec_cap(Signer::address_of(account))); - - aborts_if !exists>(addr); - aborts_if Option::is_none>(cap_opt); - ensures exists>(addr); - - // TODO: For unknown reason we can't specify the strict abort conditions. - // Intuitively, the commented out spec should be able to be verified because - // it is exactly the spec of the callee `set_with_capability()`. - //aborts_if !exists>(Option::borrow(spec_cap(Signer::address_of(account))).account_address); - pragma aborts_if_is_partial; - ensures exists>( - Option::borrow(spec_cap(Signer::address_of(account))).account_address, - ); - ensures global>( - Option::borrow(spec_cap(Signer::address_of(account))).account_address, - ).payload == payload; - } - - - spec fun spec_cap(addr: address): Option> { - global>(addr).cap - } - - - /// Set a config item to a new value with cap. - public fun set_with_capability( - cap: &mut ModifyConfigCapability, - payload: ConfigValue, - ) acquires Config { - let addr = cap.account_address; - assert!(exists>(addr), Errors::invalid_state(ECONFIG_VALUE_DOES_NOT_EXIST)); - let config = borrow_global_mut>(addr); - config.payload = copy payload; - emit_config_change_event(cap, payload); - } - - spec set_with_capability { - aborts_if !exists>(cap.account_address); - ensures exists>(cap.account_address); - ensures global>(cap.account_address).payload == payload; - } - - /// Publish a new config item. The caller will use the returned ModifyConfigCapability to specify the access control - /// policy for who can modify the config. - public fun publish_new_config_with_capability( - account: &signer, - payload: ConfigValue, - ): ModifyConfigCapability acquires ModifyConfigCapabilityHolder{ - publish_new_config(account, payload); - extract_modify_config_capability(account) - } - - spec publish_new_config_with_capability { - include PublishNewConfigAbortsIf; - - ensures exists>(Signer::address_of(account)); - ensures global>(Signer::address_of(account)).payload == payload; - - ensures exists>(Signer::address_of(account)); - ensures Option::is_none(global>(Signer::address_of(account)).cap); - } - - /// Publish a new config item under account address. - public fun publish_new_config(account: &signer, payload: ConfigValue) { - move_to(account, Config{ payload }); - let cap = ModifyConfigCapability { - account_address: Signer::address_of(account), - events: Event::new_event_handle>(account), - }; - move_to(account, ModifyConfigCapabilityHolder{cap: Option::some(cap)}); - } - - spec publish_new_config { - include PublishNewConfigAbortsIf; - - ensures exists>(Signer::address_of(account)); - ensures global>(Signer::address_of(account)).payload == payload; - - ensures exists>(Signer::address_of(account)); - ensures Option::is_some(global>(Signer::address_of(account)).cap); - } - - spec schema PublishNewConfigAbortsIf { - account: signer; - aborts_if exists>(Signer::address_of(account)); - aborts_if exists>(Signer::address_of(account)); - } - - spec schema AbortsIfConfigNotExist { - addr: address; - - aborts_if !exists>(addr); - } - - spec schema AbortsIfConfigOrCapabilityNotExist { - addr: address; - - aborts_if !exists>(addr); - aborts_if !exists>(addr); - } - - spec schema PublishNewConfigEnsures { - account: signer; - ensures exists>(Signer::address_of(account)); - ensures exists>(Signer::address_of(account)); - } - - spec schema AbortsIfCapNotExist { - address: address; - aborts_if !exists>(address); - aborts_if Option::is_none>( - global>(address).cap, - ); - } - - /// Extract account's ModifyConfigCapability for ConfigValue type - public fun extract_modify_config_capability( - account: &signer, - ): ModifyConfigCapability acquires ModifyConfigCapabilityHolder { - let signer_address = Signer::address_of(account); - assert!( - exists>(signer_address), - Errors::requires_capability(ECAPABILITY_HOLDER_NOT_EXISTS) - ); - let cap_holder = borrow_global_mut>(signer_address); - Option::extract(&mut cap_holder.cap) - } - - spec extract_modify_config_capability { - let address = Signer::address_of(account); - include AbortsIfCapNotExist; - - ensures exists>(address); - ensures Option::is_none>( - global>(address).cap - ); - ensures result == old(Option::borrow(global>(address).cap)); - } - - /// Restore account's ModifyConfigCapability - public fun restore_modify_config_capability( - cap: ModifyConfigCapability, - ) acquires ModifyConfigCapabilityHolder { - let cap_holder = borrow_global_mut>(cap.account_address); - Option::fill(&mut cap_holder.cap, cap); - } - - spec restore_modify_config_capability { - aborts_if !exists>(cap.account_address); - aborts_if Option::is_some(global>(cap.account_address).cap); - - ensures exists>(cap.account_address); - ensures Option::is_some(global>(cap.account_address).cap); - ensures Option::borrow(global>(cap.account_address).cap) == cap; - } - - /// Destroy the given ModifyConfigCapability - public fun destroy_modify_config_capability( - cap: ModifyConfigCapability, - ) { - let ModifyConfigCapability{account_address:_, events} = cap; - Event::destroy_handle(events) - } - - spec destroy_modify_config_capability { - aborts_if false; - } - - /// Return the address of the given ModifyConfigCapability - public fun account_address(cap: &ModifyConfigCapability): address { - cap.account_address - } - - spec account_address { - aborts_if false; - ensures result == cap.account_address; - } - - /// Emit a config change event. - fun emit_config_change_event( - cap: &mut ModifyConfigCapability, - value: ConfigValue, - ) { - Event::emit_event>( - &mut cap.events, - ConfigChangeEvent { - account_address: cap.account_address, - value, - }, - ); - } - - spec emit_config_change_event { - aborts_if false; - } -} -} diff --git a/release/v12/sources/ConfigProposalPlugin.move b/release/v12/sources/ConfigProposalPlugin.move deleted file mode 100644 index be9d43af..00000000 --- a/release/v12/sources/ConfigProposalPlugin.move +++ /dev/null @@ -1,81 +0,0 @@ -/// Called by other contract which need proposal config -module StarcoinFramework::ConfigProposalPlugin { - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct ConfigProposalPlugin has store, drop{} - - struct ConfigProposalAction has store, drop { - config: ConfigT, - } - - public fun initialize(_sender: &signer) { - let witness = ConfigProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::ConfigProposalPlugin", - b"The config proposal plugin", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://config-proposal-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type()); - caps - } - - public fun create_proposal(sender: &signer, title:vector, introduction:vector, extend: vector,action_delay: u64, config: ConfigT) { - let witness = ConfigProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = ConfigProposalAction{ - config - }; - DAOSpace::create_proposal< - DAOT, - ConfigProposalPlugin, - ConfigProposalAction>(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64) { - let witness = ConfigProposalPlugin{}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - let modify_config_cap = - DAOSpace::acquire_modify_config_cap(&witness); - - let ConfigProposalAction{ config } = DAOSpace::execute_proposal< - DAOT, - ConfigProposalPlugin, - ConfigProposalAction>(&proposal_cap, sender, proposal_id); - DAOSpace::set_custom_config(&mut modify_config_cap, config); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64) { - execute_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/release/v12/sources/ConsensusConfig.move b/release/v12/sources/ConsensusConfig.move deleted file mode 100644 index 03644354..00000000 --- a/release/v12/sources/ConsensusConfig.move +++ /dev/null @@ -1,230 +0,0 @@ -address StarcoinFramework { -/// The module provide configuration of consensus parameters. -module ConsensusConfig { - use StarcoinFramework::Config; - use StarcoinFramework::Signer; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Math; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_strict; - } - - /// consensus configurations. - struct ConsensusConfig has copy, drop, store { - /// Uncle block rate per epoch - uncle_rate_target: u64, - /// Average target time to calculate a block's difficulty - base_block_time_target: u64, - /// Rewards per block - base_reward_per_block: u128, - /// Percentage of `base_reward_per_block` to reward a uncle block - base_reward_per_uncle_percent: u64, - /// Blocks each epoch - epoch_block_count: u64, - /// How many ancestor blocks which use to calculate next block's difficulty - base_block_difficulty_window: u64, - /// Minimum target time to calculate a block's difficulty - min_block_time_target: u64, - /// Maximum target time to calculate a block's difficulty - max_block_time_target: u64, - /// Maximum number of uncle block per block - base_max_uncles_per_block: u64, - /// Maximum gases per block - base_block_gas_limit: u64, - /// Strategy to calculate difficulty - strategy: u8, - } - - const EINVALID_ARGUMENT: u64 = 18; - - /// Initialization of the module. - public fun initialize( - account: &signer, - uncle_rate_target: u64, - epoch_block_count: u64, - base_block_time_target: u64, - base_block_difficulty_window: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - ) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - - Config::publish_new_config( - account, - new_consensus_config( - uncle_rate_target, - base_block_time_target, - base_reward_per_block, - base_reward_per_uncle_percent, - epoch_block_count, - base_block_difficulty_window, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, - ), - ); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if uncle_rate_target == 0; - aborts_if epoch_block_count == 0; - aborts_if base_reward_per_block == 0; - aborts_if base_block_time_target == 0; - aborts_if base_block_difficulty_window == 0; - aborts_if min_block_time_target == 0; - aborts_if max_block_time_target < min_block_time_target; - - include Config::PublishNewConfigAbortsIf; - include Config::PublishNewConfigEnsures; - } - - /// Create a new consensus config mainly used in DAO. - public fun new_consensus_config(uncle_rate_target: u64, - base_block_time_target: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - epoch_block_count: u64, - base_block_difficulty_window: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8,): ConsensusConfig { - assert!(uncle_rate_target > 0, Errors::invalid_argument(EINVALID_ARGUMENT)); - assert!(base_block_time_target > 0, Errors::invalid_argument(EINVALID_ARGUMENT)); - assert!(base_reward_per_block > 0, Errors::invalid_argument(EINVALID_ARGUMENT)); - assert!(epoch_block_count > 0, Errors::invalid_argument(EINVALID_ARGUMENT)); - assert!(base_block_difficulty_window > 0, Errors::invalid_argument(EINVALID_ARGUMENT)); - // base_reward_per_uncle_percent can been zero. - assert!(min_block_time_target > 0, Errors::invalid_argument(EINVALID_ARGUMENT)); - assert!(max_block_time_target >= min_block_time_target, Errors::invalid_argument(EINVALID_ARGUMENT)); - - ConsensusConfig { - uncle_rate_target, - base_block_time_target, - base_reward_per_block, - epoch_block_count, - base_block_difficulty_window, - base_reward_per_uncle_percent, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, - } - } - - spec new_consensus_config { - aborts_if uncle_rate_target == 0; - aborts_if epoch_block_count == 0; - aborts_if base_reward_per_block == 0; - aborts_if base_block_time_target == 0; - aborts_if base_block_difficulty_window == 0; - aborts_if min_block_time_target == 0; - aborts_if max_block_time_target < min_block_time_target; - } - - /// Get config data. - public fun get_config(): ConsensusConfig { - Config::get_by_address(CoreAddresses::GENESIS_ADDRESS()) - } - - spec get_config { - aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - } - - spec fun spec_get_config(): ConsensusConfig { - global>(CoreAddresses::GENESIS_ADDRESS()).payload - } - - /// Get uncle_rate_target - public fun uncle_rate_target(config: &ConsensusConfig): u64 { - config.uncle_rate_target - } - /// Get base_block_time_target - public fun base_block_time_target(config: &ConsensusConfig): u64 { - config.base_block_time_target - } - - /// Get base_reward_per_block - public fun base_reward_per_block(config: &ConsensusConfig): u128 { - config.base_reward_per_block - } - - /// Get epoch_block_count - public fun epoch_block_count(config: &ConsensusConfig): u64 { - config.epoch_block_count - } - - /// Get base_block_difficulty_window - public fun base_block_difficulty_window(config: &ConsensusConfig): u64 { - config.base_block_difficulty_window - } - - /// Get base_reward_per_uncle_percent - public fun base_reward_per_uncle_percent(config: &ConsensusConfig): u64 { - config.base_reward_per_uncle_percent - } - - /// Get min_block_time_target - public fun min_block_time_target(config: &ConsensusConfig): u64 { - config.min_block_time_target - } - - /// Get max_block_time_target - public fun max_block_time_target(config: &ConsensusConfig): u64 { - config.max_block_time_target - } - - /// Get base_max_uncles_per_block - public fun base_max_uncles_per_block(config: &ConsensusConfig): u64 { - config.base_max_uncles_per_block - } - - /// Get base_block_gas_limit - public fun base_block_gas_limit(config: &ConsensusConfig): u64 { - config.base_block_gas_limit - } - - /// Get strategy - public fun strategy(config: &ConsensusConfig): u8 { - config.strategy - } - - /// Compute block reward given the `new_epoch_block_time_target`. - public fun compute_reward_per_block(new_epoch_block_time_target: u64): u128 { - let config = get_config(); - do_compute_reward_per_block(&config, new_epoch_block_time_target) - } - - spec compute_reward_per_block { - aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - include Math::MulDivAbortsIf{x: spec_get_config().base_reward_per_block, y: new_epoch_block_time_target, z: spec_get_config().base_block_time_target}; - } - - /// Compute block reward given the `new_epoch_block_time_target`, and the consensus config. - public fun do_compute_reward_per_block(config: &ConsensusConfig, new_epoch_block_time_target: u64): u128 { - Math::mul_div(config.base_reward_per_block, (new_epoch_block_time_target as u128), (config.base_block_time_target as u128)) - } - - spec do_compute_reward_per_block { - include Math::MulDivAbortsIf{x: config.base_reward_per_block, y: new_epoch_block_time_target, z: config.base_block_time_target}; - } - - -} -} \ No newline at end of file diff --git a/release/v12/sources/ConsensusStrategy.move b/release/v12/sources/ConsensusStrategy.move deleted file mode 100644 index 99cb8b61..00000000 --- a/release/v12/sources/ConsensusStrategy.move +++ /dev/null @@ -1,49 +0,0 @@ -address StarcoinFramework { -/// The module provides the information of current consensus strategy. -module ConsensusStrategy { - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Signer; - use StarcoinFramework::Config; - - /// ConsensusStrategy data. - struct ConsensusStrategy has copy, drop, store { - /// Value of strategy - value: u8 - } - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Publish the chain ID under the genesis account - public fun initialize(account: &signer, consensus_strategy: u8) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - let cap = Config::publish_new_config_with_capability( - account, - ConsensusStrategy { value:consensus_strategy } - ); - //destroy the cap, so ConsensusStrategy can not been change. - Config::destroy_modify_config_capability(cap); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if exists>(Signer::address_of(account)); - aborts_if exists>(Signer::address_of(account)); - ensures exists>(Signer::address_of(account)); - } - - /// Return the consensus strategy type of this chain - public fun get(): u8 { - Config::get_by_address(CoreAddresses::GENESIS_ADDRESS()).value - } - - spec get { - aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - } -} -} diff --git a/release/v12/sources/CoreAddresses.move b/release/v12/sources/CoreAddresses.move deleted file mode 100644 index 3f234c86..00000000 --- a/release/v12/sources/CoreAddresses.move +++ /dev/null @@ -1,51 +0,0 @@ -address StarcoinFramework { -/// The module provide addresses used in stdlib. -module CoreAddresses { - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - const ENOT_GENESIS_ACCOUNT: u64 = 11; - - /// The address of the genesis - public fun GENESIS_ADDRESS(): address { - @0x1 - } - - /// Assert signer is genesis. - public fun assert_genesis_address(account: &signer) { - assert!(Signer::address_of(account) == GENESIS_ADDRESS(), - Errors::requires_address(ENOT_GENESIS_ACCOUNT)) - } - spec assert_genesis_address { - pragma opaque; - include AbortsIfNotGenesisAddress; - } - - /// Specifies that a function aborts if the account does not have the Diem root address. - spec schema AbortsIfNotGenesisAddress { - account: signer; - aborts_if Signer::address_of(account) != GENESIS_ADDRESS(); - } - - /// The address of the root association account. This account is - /// created in genesis, and cannot be changed. This address has - /// ultimate authority over the permissions granted (or removed) from - /// accounts on-chain. - public fun ASSOCIATION_ROOT_ADDRESS(): address { - @0xA550C18 - } - - /// The reserved address for transactions inserted by the VM into blocks (e.g. - /// block metadata transactions). Because the transaction is sent from - /// the VM, an account _cannot_ exist at the `0x0` address since there - /// is no signer for the transaction. - public fun VM_RESERVED_ADDRESS(): address { - @0x0 - } -} -} diff --git a/release/v12/sources/DAOAccount.move b/release/v12/sources/DAOAccount.move deleted file mode 100644 index b297dfa0..00000000 --- a/release/v12/sources/DAOAccount.move +++ /dev/null @@ -1,121 +0,0 @@ -module StarcoinFramework::DAOAccount{ - use StarcoinFramework::Account::{Self, SignerCapability}; - use StarcoinFramework::PackageTxnManager::{Self, UpgradePlanCapability}; - use StarcoinFramework::Option; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::Version; - use StarcoinFramework::Config; - - - friend StarcoinFramework::StarcoinDAO; - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - const ERR_ACCOUNT_CAP_NOT_EXISTS:u64 = 100; - const ERR_ACCOUNT_CAP_EXISTS: u64 = 101; - const ERR_ACCOUNT_IS_NOT_SAME: u64 = 102; - const ERR_UPGARDE_PLAN_CAP_NOT_EXISTS: u64 = 103; - - /// DAOAccount - struct DAOAccount has key{ - dao_address: address, - signer_cap: SignerCapability, - upgrade_plan_cap: UpgradePlanCapability, - } - - /// This capability can control the DAO account - struct DAOAccountCap has store, key{ - dao_address: address, - } - - /// Create a new DAO Account and return DAOAccountCap - /// DAO Account is a delegate account, the `creator` has the `DAOAccountCap` - public fun create_account(creator: &signer): DAOAccountCap { - let (_dao_address, signer_cap) = Account::create_delegate_account(creator); - upgrade_to_dao_with_signer_cap(signer_cap) - } - - /// Entry function for create dao account, the `DAOAccountCap` save to the `creator` account - public(script) fun create_account_entry(sender: signer){ - let cap = create_account(&sender); - assert!(!exists(Signer::address_of(&sender)), Errors::already_published(ERR_ACCOUNT_CAP_EXISTS)); - move_to(&sender, cap); - } - - /// Extract the DAOAccountCap from the `sender` - public fun extract_dao_account_cap(sender: &signer): DAOAccountCap acquires DAOAccountCap { - let sender_addr = Signer::address_of(sender); - assert!(exists(sender_addr), Errors::not_published(ERR_ACCOUNT_CAP_NOT_EXISTS)); - move_from(sender_addr) - } - - /// Restore the DAOAccountCap to the `sender` - public fun restore_dao_account_cap(sender: &signer, cap: DAOAccountCap) { - let sender_addr = Signer::address_of(sender); - assert!(!exists(sender_addr), Errors::already_published(ERR_ACCOUNT_CAP_EXISTS)); - move_to(sender, cap) - } - - /// Upgrade `sender` account to DAO account - public fun upgrade_to_dao(sender: signer): DAOAccountCap { - let signer_cap = Account::remove_signer_capability(&sender); - upgrade_to_dao_with_signer_cap(signer_cap) - } - - /// Upgrade the account which have the `signer_cap` to a DAO Account - public fun upgrade_to_dao_with_signer_cap(signer_cap: SignerCapability): DAOAccountCap { - let dao_signer = Account::create_signer_with_cap(&signer_cap); - let dao_address = Signer::address_of(&dao_signer); - - let upgrade_plan_cap = if(Config::config_exist_by_address(dao_address)){ - assert!(PackageTxnManager::exists_upgrade_plan_cap(dao_address), Errors::not_published(ERR_UPGARDE_PLAN_CAP_NOT_EXISTS)); - PackageTxnManager::extract_submit_upgrade_plan_cap(&dao_signer) - }else{ - Config::publish_new_config(&dao_signer, Version::new_version(1)); - PackageTxnManager::update_module_upgrade_strategy(&dao_signer, PackageTxnManager::get_strategy_two_phase(), Option::some(1)); - PackageTxnManager::extract_submit_upgrade_plan_cap(&dao_signer) - }; - upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap, upgrade_plan_cap) - } - - /// Upgrade the account which have the `signer_cap` to a DAO Account - public fun upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap: SignerCapability, upgrade_plan_cap:UpgradePlanCapability): DAOAccountCap { - let dao_signer = Account::create_signer_with_cap(&signer_cap); - let dao_address = Signer::address_of(&dao_signer); - - assert!(Account::signer_address(&signer_cap) == PackageTxnManager::account_address(&upgrade_plan_cap), Errors::already_published(ERR_ACCOUNT_IS_NOT_SAME)); - - move_to(&dao_signer, DAOAccount{ - dao_address, - signer_cap, - upgrade_plan_cap, - }); - - DAOAccountCap{ - dao_address - } - } - - /// Provide a function to create signer with `DAOAccountCap` - public fun dao_signer(cap: &DAOAccountCap): signer acquires DAOAccount { - let signer_cap = &borrow_global(cap.dao_address).signer_cap; - Account::create_signer_with_cap(signer_cap) - } - - /// Sumbit upgrade plan for the DAO account - /// This function is a shortcut for create signer with DAOAccountCap and invoke `PackageTxnManager::submit_upgrade_plan_v2` - public fun submit_upgrade_plan(cap: &DAOAccountCap, package_hash: vector, version:u64, enforced: bool) acquires DAOAccount{ - let upgrade_plan_cap = &borrow_global(cap.dao_address).upgrade_plan_cap; - PackageTxnManager::submit_upgrade_plan_with_cap_v2(upgrade_plan_cap, package_hash, version, enforced); - } - - /// Sumbit upgrade plan for the DAO account, sender must hold the `DAOAccountCap` - public(script) fun submit_upgrade_plan_entry(sender: signer, package_hash: vector, version:u64, enforced: bool) acquires DAOAccount, DAOAccountCap{ - let addr = Signer::address_of(&sender); - let cap = borrow_global(addr); - submit_upgrade_plan(cap, package_hash, version, enforced) - } -} \ No newline at end of file diff --git a/release/v12/sources/DAOExtensionPoint.move b/release/v12/sources/DAOExtensionPoint.move deleted file mode 100644 index 7c88aa63..00000000 --- a/release/v12/sources/DAOExtensionPoint.move +++ /dev/null @@ -1,437 +0,0 @@ -module StarcoinFramework::DAOExtensionPoint { - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Vector; - use StarcoinFramework::NFT; - use StarcoinFramework::NFTGallery; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::Event; - use StarcoinFramework::TypeInfo::{Self, TypeInfo}; - - const ERR_ALREADY_INITIALIZED: u64 = 100; - const ERR_NOT_CONTRACT_OWNER: u64 = 101; - const ERR_EXPECT_EXT_POINT_NFT: u64 = 102; - const ERR_NOT_FOUND_EXT_POINT: u64 = 103; - const ERR_ALREADY_REGISTERED: u64 = 104; - const ERR_STAR_ALREADY_STARED: u64 = 105; - const ERR_STAR_NOT_FOUND_STAR: u64 = 106; - const ERR_TAG_DUPLICATED: u64 = 107; - - const ERR_VERSION_COUNT_LIMIT: u64 = 108; - const ERR_ITEMS_COUNT_LIMIT: u64 = 109; - const ERR_STRING_TOO_LONG: u64 = 110; - - const MAX_VERSION_COUNT: u64 = 256; // Max version count for extension point. - const MAX_LABELS_COUNT: u64 = 20; // Max labels count for extension point. - - const MAX_INPUT_LEN: u64 = 64; - const MAX_TEXT_LEN: u64 = 256; - - struct Version has store { - number: u64, - tag: vector, - types_d_ts: vector, - document: vector, - created_at: u64, - } - - struct Registry has key, store { - next_id: u64, - } - - struct Entry has key, store { - id: u64, - name: vector, - description: vector, - labels: vector>, - next_version_number: u64, - versions: vector, - star_count: u64, - created_at: u64, - updated_at: u64, - } - - struct Star has key, store { - created_at: u64, - } - - struct OwnerNFTMeta has copy, store, drop { - extpoint_id: u64, - registry_address: address, - } - - struct OwnerNFTBody has store{} - - struct NFTMintCapHolder has key { - cap: NFT::MintCapability, - nft_metadata: NFT::Metadata, - } - - /// registry event handlers - struct RegistryEventHandlers has key, store{ - register: Event::EventHandle, - } - - struct ExtensionPointRegisterEvent has drop, store{ - id: u64, - type: TypeInfo, - name: vector, - description:vector, - labels: vector> - } - - /// extension point event handlers - struct ExtensionPointEventHandlers has key, store{ - publish_version: Event::EventHandle>, - star: Event::EventHandle>, - unstar: Event::EventHandle>, - update: Event::EventHandle>, - } - - struct PublishVersionEvent has drop, store{ - sender: address, - version_number: u64, - } - - struct StarEvent has drop, store{ - sender: address, - } - - struct UnstarEvent has drop, store{ - sender: address, - } - - struct UpdateInfoEvent has drop, store{ - sender: address, - id: u64, - name: vector, - description:vector, - labels: vector> - } - - fun next_extpoint_id(registry: &mut Registry): u64 { - let extpoint_id = registry.next_id; - registry.next_id = extpoint_id + 1; - extpoint_id - } - - fun next_extpoint_version_number(extpoint: &mut Entry): u64 { - let version_number = extpoint.next_version_number; - extpoint.next_version_number = version_number + 1; - version_number - } - - fun has_extpoint_nft(sender_addr: address, extpoint_id: u64): bool { - if (!NFTGallery::is_accept(sender_addr)) { - return false - }; - - let nft_infos = NFTGallery::get_nft_infos(sender_addr); - let len = Vector::length(&nft_infos); - if (len == 0) { - return false - }; - - let idx = len - 1; - loop { - let nft_info = Vector::borrow(&nft_infos, idx); - let (_, _, _, type_meta) = NFT::unpack_info(*nft_info); - if (type_meta.extpoint_id == extpoint_id) { - return true - }; - - if (idx == 0) { - return false - }; - - idx = idx - 1; - } - } - - fun ensure_exists_extpoint_nft(sender_addr: address, extpoint_id: u64) { - assert!(has_extpoint_nft(sender_addr, extpoint_id), Errors::invalid_state(ERR_EXPECT_EXT_POINT_NFT)); - } - - fun assert_tag_no_repeat(v: &vector, tag:vector) { - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert!(*&e.tag != *&tag, Errors::invalid_argument(ERR_TAG_DUPLICATED)); - i = i + 1; - }; - } - - fun assert_string_length(s: &vector, max_len: u64) { - let len = Vector::length(s); - assert!(len <= max_len, Errors::invalid_argument(ERR_STRING_TOO_LONG)); - } - - fun assert_string_array_length(v: &vector>, max_item_len: u64, max_string_len: u64) { - assert!(Vector::length(v) <= max_item_len, Errors::limit_exceeded(ERR_ITEMS_COUNT_LIMIT)); - - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert_string_length(e, max_string_len); - i = i + 1; - }; - } - - public fun initialize() { - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - - let nft_name = b"ExtPointOwnerNFT"; - let nft_image = b"ipfs://QmdTwdhFi61zhRM3MtPLxuKyaqv3ePECLGsMg9pMrePv4i"; - let nft_description = b"The extension point owner NFT"; - let basemeta = NFT::new_meta_with_image_data(nft_name, nft_image, nft_description); - let basemeta_bak = *&basemeta; - NFT::register_v2(&signer, basemeta); - - let nft_mint_cap = NFT::remove_mint_capability(&signer); - move_to(&signer, NFTMintCapHolder{ - cap: nft_mint_cap, - nft_metadata: basemeta_bak, - }); - - move_to(&signer, Registry{ - next_id: 1, - }); - - move_to(&signer, RegistryEventHandlers { - register: Event::new_event_handle(&signer), - }); - } - - public fun register(sender: &signer, name: vector, description: vector, types_d_ts:vector, dts_doc:vector, - option_labels: Option>>):u64 acquires Registry, NFTMintCapHolder, RegistryEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - assert_string_length(&types_d_ts, MAX_TEXT_LEN); - assert_string_length(&dts_doc, MAX_TEXT_LEN); - - assert!(!exists>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_REGISTERED)); - let registry = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let extpoint_id = next_extpoint_id(registry); - - let version = Version { - number: 1, - tag: b"v0.1.0", - types_d_ts: types_d_ts, - document: dts_doc, - created_at: Timestamp::now_seconds(), - }; - - let labels = if(Option::is_some(&option_labels)){ - Option::destroy_some(option_labels) - } else { - Vector::empty>() - }; - - assert_string_array_length(&labels, MAX_LABELS_COUNT, MAX_INPUT_LEN); - - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - move_to(&genesis_account, Entry{ - id: copy extpoint_id, - name: copy name, - description: copy description, - labels: copy labels, - next_version_number: 2, - versions: Vector::singleton(version), - star_count: 0, - created_at: Timestamp::now_seconds(), - updated_at: Timestamp::now_seconds(), - }); - - move_to(&genesis_account, ExtensionPointEventHandlers{ - publish_version: Event::new_event_handle>(&genesis_account), - star: Event::new_event_handle>(&genesis_account), - unstar: Event::new_event_handle>(&genesis_account), - update: Event::new_event_handle>(&genesis_account), - }); - - // grant owner NFT to sender - let nft_mint_cap = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let meta = OwnerNFTMeta{ - registry_address: CoreAddresses::GENESIS_ADDRESS(), - extpoint_id: extpoint_id, - }; - - let nft = NFT::mint_with_cap_v2(CoreAddresses::GENESIS_ADDRESS(), &mut nft_mint_cap.cap, *&nft_mint_cap.nft_metadata, meta, OwnerNFTBody{}); - NFTGallery::deposit(sender, nft); - - // registry register event emit - let registry_event_handlers = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut registry_event_handlers.register, - ExtensionPointRegisterEvent { - id: copy extpoint_id, - type: TypeInfo::type_of(), - name: copy name, - description: copy description, - labels: copy labels, - }, - ); - - extpoint_id - } - - public fun publish_version( - sender: &signer, - tag: vector, - types_d_ts:vector, - dts_doc: vector, - ) acquires Entry, ExtensionPointEventHandlers { - assert_string_length(&tag, MAX_INPUT_LEN); - assert_string_length(&types_d_ts, MAX_TEXT_LEN); - assert_string_length(&dts_doc, MAX_TEXT_LEN); - - let sender_addr = Signer::address_of(sender); - let extp = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - - ensure_exists_extpoint_nft(sender_addr, extp.id); - assert!(Vector::length(&extp.versions) <= MAX_VERSION_COUNT, Errors::limit_exceeded(ERR_VERSION_COUNT_LIMIT)); - assert_tag_no_repeat(&extp.versions, copy tag); - - let number = next_extpoint_version_number(extp); - Vector::push_back(&mut extp.versions, Version{ - number: number, - tag: tag, - types_d_ts: types_d_ts, - document: dts_doc, - created_at: Timestamp::now_seconds(), - }); - - extp.updated_at = Timestamp::now_seconds(); - - // publish version event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.publish_version, - PublishVersionEvent { - sender: copy sender_addr, - version_number: copy number, - }, - ); - } - - public fun update(sender: &signer, name: vector, description: vector, option_labels: Option>>) acquires Entry, ExtensionPointEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - - let sender_addr = Signer::address_of(sender); - let extp = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - ensure_exists_extpoint_nft(sender_addr, extp.id); - - extp.name = name; - extp.description = description; - - if(Option::is_some(&option_labels)){ - let labels = Option::destroy_some(option_labels); - assert_string_array_length(&labels, MAX_LABELS_COUNT, MAX_INPUT_LEN); - extp.labels = labels; - }; - - extp.updated_at = Timestamp::now_seconds(); - - // update extpoint entry event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.update, - UpdateInfoEvent { - sender: sender_addr, - id: *&extp.id, - name: *&extp.name, - description: *&extp.description, - labels: *&extp.labels, - }, - ); - } - - public fun has_star_plugin(sender: &signer): bool { - let sender_addr = Signer::address_of(sender); - return exists>(sender_addr) - } - - public fun star(sender: &signer) acquires Entry, ExtensionPointEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(!exists>(sender_addr), Errors::invalid_state(ERR_STAR_ALREADY_STARED)); - - move_to(sender, Star{ - created_at: Timestamp::now_seconds(), - }); - - let entry = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - entry.star_count = entry.star_count + 1; - entry.updated_at = Timestamp::now_seconds(); - - // star event emit - let extpoint_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut extpoint_event_handlers.star, - StarEvent { - sender: sender_addr, - }, - ); - } - - public fun unstar(sender: &signer) acquires Star, Entry, ExtensionPointEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::invalid_state(ERR_STAR_NOT_FOUND_STAR)); - - let star = move_from>(sender_addr); - let Star {created_at:_} = star; - - let entry = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - entry.star_count = entry.star_count - 1; - entry.updated_at = Timestamp::now_seconds(); - - // unstar event emit - let extpoint_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut extpoint_event_handlers.unstar, - UnstarEvent { - sender: sender_addr, - }, - ); - } - - // public entrys - public(script) fun register_entry(sender: signer, name: vector, description: vector, types_d_ts:vector, dts_doc:vector, - labels: vector>) acquires Registry, NFTMintCapHolder, RegistryEventHandlers { - let option_labels = if(Vector::length(&labels) == 0){ - Option::none>>() - } else { - Option::some(labels) - }; - - register(&sender, name, description, types_d_ts, dts_doc, option_labels); - } - - public(script) fun publish_version_entry( - sender: signer, - tag: vector, - types_d_ts:vector, - dts_doc: vector, - ) acquires Entry, ExtensionPointEventHandlers { - publish_version(&sender, tag, types_d_ts, dts_doc); - } - - public(script) fun update_entry(sender: signer, name: vector, description: vector, labels: vector>) acquires Entry, ExtensionPointEventHandlers { - let option_labels = if(Vector::length(&labels) == 0){ - Option::none>>() - } else { - Option::some(labels) - }; - - update(&sender, name, description, option_labels); - } - - public(script) fun star_entry(sender: signer) acquires Entry, ExtensionPointEventHandlers { - star(&sender); - } - - public(script) fun unstar_entry(sender: signer) acquires Star, Entry, ExtensionPointEventHandlers { - unstar(&sender); - } -} diff --git a/release/v12/sources/DAOPluginMarketplace.move b/release/v12/sources/DAOPluginMarketplace.move deleted file mode 100644 index 00afaeec..00000000 --- a/release/v12/sources/DAOPluginMarketplace.move +++ /dev/null @@ -1,359 +0,0 @@ -module StarcoinFramework::DAOPluginMarketplace { - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Vector; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::Event; - use StarcoinFramework::TypeInfo::{Self, TypeInfo}; - - const ERR_ALREADY_INITIALIZED: u64 = 100; - const ERR_NOT_CONTRACT_OWNER: u64 = 101; - const ERR_NOT_FOUND_PLUGIN: u64 = 102; - const ERR_EXPECT_PLUGIN_NFT: u64 = 103; - const ERR_PLUGIN_ALREADY_EXISTS: u64 = 104; - const ERR_STAR_ALREADY_STARED: u64 = 105; - const ERR_STAR_NOT_FOUND_STAR: u64 = 106; - const ERR_TAG_DUPLICATED: u64 = 107; - - const ERR_VERSION_COUNT_LIMIT: u64 = 108; - const ERR_ITEMS_COUNT_LIMIT: u64 = 109; - const ERR_STRING_TOO_LONG: u64 = 110; - - const MAX_VERSION_COUNT: u64 = 5; // Max version count for extension point. - const MAX_ITEMS_COUNT: u64 = 20; // Max items count for vector. - - const MAX_INPUT_LEN: u64 = 64; - const MAX_TEXT_LEN: u64 = 256; - - struct PluginVersion has store { - number: u64, //Numeric version number, such as 1, 2, 3 - tag: vector, //Plugin tag, e.g. v0.1.1 - implement_extpoints: vector>, //Implemented extension points - depend_extpoints: vector>, //Dependent extension points - js_entry_uri: vector, //Front-end JS code resource URI, for example: "https://cdn.xxxx.xxxx/xxxx/xxxxx.js" - created_at: u64, //Plugin creation time - } - - struct PluginRegistry has key, store { - next_plugin_id: u64, - } - - struct PluginEntry has key, store { - id: u64, //Plugin ID - name: vector, //plugin name - description: vector, //Plugin description - labels: vector>, //Plugin label - next_version_number: u64, //next version number - versions: vector, //All versions of the plugin - star_count: u64, //Star count - created_at: u64, //Plugin creation time - updated_at: u64, //Plugin last update time - } - - struct Star has key, store { - created_at: u64, //creation time - } - - fun next_plugin_id(plugin_registry: &mut PluginRegistry): u64 { - let plugin_id = plugin_registry.next_plugin_id; - plugin_registry.next_plugin_id = plugin_id + 1; - plugin_id - } - - fun next_plugin_version_number(plugin: &mut PluginEntry): u64 { - let version_number = plugin.next_version_number; - plugin.next_version_number = version_number + 1; - version_number - } - - fun assert_tag_no_repeat(v: &vector, tag:vector) { - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert!(*&e.tag != *&tag, Errors::invalid_argument(ERR_TAG_DUPLICATED)); - i = i + 1; - }; - } - - fun assert_string_length(s: &vector, max_len: u64) { - let len = Vector::length(s); - assert!(len <= max_len, Errors::invalid_argument(ERR_STRING_TOO_LONG)); - } - - fun assert_string_array_length(v: &vector>, max_item_len: u64, max_string_len: u64) { - assert!(Vector::length(v) <= max_item_len, Errors::limit_exceeded(ERR_ITEMS_COUNT_LIMIT)); - - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert_string_length(e, max_string_len); - i = i + 1; - }; - } - - /// registry event handlers - struct RegistryEventHandlers has key, store{ - register: Event::EventHandle, - } - - struct PluginRegisterEvent has drop, store{ - id: u64, - type: TypeInfo, - name: vector, - description:vector, - labels: vector> - } - - /// plugin event handlers - struct PluginEventHandlers has key, store{ - publish_version: Event::EventHandle>, - star: Event::EventHandle>, - unstar: Event::EventHandle>, - update_plugin: Event::EventHandle>, - } - - struct PluginPublishVersionEvent has drop, store{ - plugin_type: TypeInfo, - version_number: u64, - } - - struct StarPluginEvent has drop, store{ - sender: address, - } - - struct UnstarPluginEvent has drop, store{ - sender: address, - } - - struct UpdatePluginInfoEvent has drop, store{ - id: u64, - type: TypeInfo, - name: vector, - description:vector, - labels: vector> - } - - public fun initialize() { - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - - move_to(&signer, PluginRegistry{ - next_plugin_id: 1, - }); - - move_to(&signer, RegistryEventHandlers { - register: Event::new_event_handle(&signer), - }); - } - - public fun register_plugin(_witness: &PluginT, name: vector, description: vector, option_labels: Option>>): u64 - acquires PluginRegistry, RegistryEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - - assert!(!exists>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_PLUGIN_ALREADY_EXISTS)); - let plugin_registry = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let plugin_id = next_plugin_id(plugin_registry); - - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - - let labels = if(Option::is_some(&option_labels)){ - Option::destroy_some(option_labels) - } else { - Vector::empty>() - }; - - assert_string_array_length(&labels, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - - move_to(&genesis_account, PluginEntry{ - id: copy plugin_id, - name: copy name, - description: copy description, - labels: copy labels, - next_version_number: 1, - versions: Vector::empty(), - star_count: 0, - created_at: Timestamp::now_seconds(), - updated_at: Timestamp::now_seconds(), - }); - - move_to(&genesis_account, PluginEventHandlers{ - publish_version: Event::new_event_handle>(&genesis_account), - star: Event::new_event_handle>(&genesis_account), - unstar: Event::new_event_handle>(&genesis_account), - update_plugin: Event::new_event_handle>(&genesis_account), - }); - - // registry register event emit - let registry_event_handlers = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut registry_event_handlers.register, - PluginRegisterEvent { - id: copy plugin_id, - type: TypeInfo::type_of(), - name: copy name, - description: copy description, - labels: copy labels, - }, - ); - - plugin_id - } - - public fun exists_plugin(): bool { - return exists>(CoreAddresses::GENESIS_ADDRESS()) - } - - public fun take_plugin_id(): u64 acquires PluginEntry { - let plugin = borrow_global>(CoreAddresses::GENESIS_ADDRESS()); - return plugin.id - } - - public fun publish_plugin_version( - _witness: &PluginT, - tag: vector, - implement_extpoints: vector>, - depend_extpoints: vector>, - js_entry_uri: vector, - ) acquires PluginEntry, PluginEventHandlers { - assert_string_length(&tag, MAX_INPUT_LEN); - assert_string_array_length(&implement_extpoints, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - assert_string_array_length(&depend_extpoints, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - assert_string_length(&js_entry_uri, MAX_TEXT_LEN); - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - - assert_tag_no_repeat(&plugin.versions, copy tag); - - // Remove the old version when the number of versions is greater than MAX_VERSION_COUNT - if (Vector::length(&plugin.versions) >= MAX_VERSION_COUNT) { - let oldest_version = Vector::remove(&mut plugin.versions, 0); - let PluginVersion { - number: _, - tag: _, - implement_extpoints: _, - depend_extpoints: _, - js_entry_uri: _, - created_at: _, - } = oldest_version; - }; - - let version_number = next_plugin_version_number(plugin); - Vector::push_back(&mut plugin.versions, PluginVersion{ - number: copy version_number, - tag: tag, - implement_extpoints: implement_extpoints, - depend_extpoints: depend_extpoints, - js_entry_uri: js_entry_uri, - created_at: Timestamp::now_seconds(), - }); - - plugin.updated_at = Timestamp::now_seconds(); - - // plugin register event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.publish_version, - PluginPublishVersionEvent { - plugin_type: TypeInfo::type_of(), - version_number: copy version_number, - }, - ); - } - - public fun exists_plugin_version( - version_number: u64, - ): bool acquires PluginEntry { - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - return version_number > 0 && version_number < plugin.next_version_number - } - - public fun star_plugin(sender: &signer) acquires PluginEntry, PluginEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(!exists>(sender_addr), Errors::invalid_state(ERR_STAR_ALREADY_STARED)); - - move_to(sender, Star{ - created_at: Timestamp::now_seconds(), - }); - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - plugin.star_count = plugin.star_count + 1; - plugin.updated_at = Timestamp::now_seconds(); - - // star plugin event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.star, - StarPluginEvent { - sender: sender_addr, - }, - ); - } - - public fun unstar_plugin(sender: &signer) acquires PluginEntry, Star, PluginEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::invalid_state(ERR_STAR_NOT_FOUND_STAR)); - - let star = move_from>(sender_addr); - let Star { created_at:_} = star; - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - plugin.star_count = plugin.star_count - 1; - plugin.updated_at = Timestamp::now_seconds(); - - // unstar plugin event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.unstar, - UnstarPluginEvent { - sender: sender_addr, - }, - ); - } - - public fun has_star_plugin(sender: &signer): bool { - let sender_addr = Signer::address_of(sender); - return exists>(sender_addr) - } - - public fun update_plugin(_witness: &PluginT, name: vector, description: vector, option_labels: Option>>) acquires PluginEntry, PluginEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - - plugin.name = name; - plugin.description = description; - - if(Option::is_some(&option_labels)){ - let labels = Option::destroy_some(option_labels); - assert_string_array_length(&labels, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - plugin.labels = labels; - }; - - plugin.updated_at = Timestamp::now_seconds(); - - // update plugin event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.update_plugin, - UpdatePluginInfoEvent { - id: *&plugin.id, - type: TypeInfo::type_of(), - name: *&plugin.name, - description: *&plugin.description, - labels: *&plugin.labels, - }, - ); - } - - // public entrys - public(script) fun star_plugin_entry(sender: signer) acquires PluginEntry, PluginEventHandlers { - star_plugin(&sender); - } - - public(script) fun unstar_plugin_entry(sender: signer) acquires PluginEntry, Star, PluginEventHandlers { - unstar_plugin(&sender); - } -} - diff --git a/release/v12/sources/DAORegistry.move b/release/v12/sources/DAORegistry.move deleted file mode 100644 index 6195ab6c..00000000 --- a/release/v12/sources/DAORegistry.move +++ /dev/null @@ -1,57 +0,0 @@ -module StarcoinFramework::DAORegistry{ - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - - friend StarcoinFramework::Genesis; - friend StarcoinFramework::StdlibUpgradeScripts; - friend StarcoinFramework::DAOSpace; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - const ERR_ALREADY_INITIALIZED: u64 = 100; - - /// Global DAO registry info - struct DAORegistry has key{ - next_dao_id: u64, - } - - /// Registry Entry for record the mapping between `DAOT` and `dao_address` - struct DAORegistryEntry has key{ - dao_id: u64, - dao_address: address, - } - - public(friend) fun initialize(){ - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - move_to(&signer, DAORegistry{next_dao_id: 1}) - } - - // This function should call from DAOSpace module - public(friend) fun register(dao_address: address): u64 acquires DAORegistry{ - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - let dao_id = next_dao_id(); - move_to(&genesis_account, DAORegistryEntry{ - dao_id, - dao_address, - }); - dao_id - } - - fun next_dao_id(): u64 acquires DAORegistry { - let dao_registry = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let dao_id = dao_registry.next_dao_id; - dao_registry.next_dao_id = dao_id + 1; - dao_id - - } - - public fun dao_address():address acquires DAORegistryEntry{ - *&borrow_global>(CoreAddresses::GENESIS_ADDRESS()).dao_address - } - -} \ No newline at end of file diff --git a/release/v12/sources/DAOSpace.move b/release/v12/sources/DAOSpace.move deleted file mode 100644 index b94b03f0..00000000 --- a/release/v12/sources/DAOSpace.move +++ /dev/null @@ -1,2604 +0,0 @@ -module StarcoinFramework::DAOSpace { - use StarcoinFramework::DAOAccount::{Self, DAOAccountCap}; - use StarcoinFramework::Account; - use StarcoinFramework::Vector; - use StarcoinFramework::NFT::{Self, NFT}; - use StarcoinFramework::NFTGallery; - use StarcoinFramework::IdentifierNFT; - use StarcoinFramework::Signer; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::Token::{Self, Token}; - use StarcoinFramework::Errors; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::STC::{Self, STC}; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Config; - use StarcoinFramework::Event; - use StarcoinFramework::Math; - use StarcoinFramework::StarcoinVerifier; - use StarcoinFramework::StarcoinVerifier::StateProof; - use StarcoinFramework::BCS; - use StarcoinFramework::SBTVoteStrategy; - use StarcoinFramework::SnapshotUtil; - use StarcoinFramework::Block; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::EventUtil; - use StarcoinFramework::ASCII; - use StarcoinFramework::Offer; - use StarcoinFramework::TypeInfo; - - friend StarcoinFramework::StarcoinDAO; - - const MAX_PROPOSALS: u64 = 1000; - - const ERR_NO_GRANTED: u64 = 100; - const ERR_REPEAT_ELEMENT: u64 = 101; - const ERR_STORAGE_ERROR: u64 = 102; - const ERR_NFT_ERROR: u64 = 103; - const ERR_ALREADY_INIT: u64 = 104; - const ERR_TOKEN_ERROR: u64 = 105; - const ERR_DAO_EXT: u64 = 106; - - /// member - const ERR_EXPECT_MEMBER: u64 = 200; - const ERR_EXPECT_NOT_MEMBER: u64 = 201; - - /// config or arguments - const ERR_ACTION_DELAY_TOO_SMALL: u64 = 300; - const ERR_CONFIG_PARAM_INVALID: u64 = 301; - const ERR_INVALID_AMOUNT:u64 = 302; - const ERR_TOO_SMALL_TOTAL:u64 = 303; - const ERR_HAVE_SAME_GRANT:u64 = 304; - const ERR_NOT_HAVE_GRANT:u64 = 305; - - /// proposal - const ERR_PROPOSAL_STATE_INVALID: u64 = 400; - const ERR_PROPOSAL_ID_MISMATCH: u64 = 401; - const ERR_PROPOSER_MISMATCH: u64 = 402; - const ERR_PROPOSAL_NOT_EXIST: u64 = 403; - const ERR_QUORUM_RATE_INVALID: u64 = 404; - const ERR_PROPOSAL_ACTION_INDEX_NOT_EXIST: u64 = 405; - const ERR_PROPOSAL_OUT_OF_LIMIT: u64 = 406; - - /// action - const ERR_ACTION_MUST_EXIST: u64 = 500; - const ERR_ACTION_INDEX_INVALID: u64 = 501; - const ERR_PROPOSAL_ACTIONS_NOT_EXIST: u64 = 502; - - /// vote - const ERR_VOTE_STATE_MISMATCH: u64 = 600; - const ERR_VOTED_OTHERS_ALREADY: u64 = 601; - const ERR_VOTED_ALREADY: u64 = 602; - const ERR_VOTE_PARAM_INVALID: u64 = 603; - const ERR_SNAPSHOT_PROOF_PARAM_INVALID: u64 = 604; - const ERR_STATE_PROOF_VERIFY_INVALID: u64 = 605; - - /// plugin - const ERR_PLUGIN_NOT_EXIST: u64 = 700; - const ERR_PLUGIN_VERSION_NOT_EXIST: u64 = 701; - const ERR_PLUGIN_HAS_INSTALLED: u64 = 702; - const ERR_PLUGIN_NOT_INSTALLED: u64 = 703; - - /// grant - const ERR_OFFER_NOT_EXIST: u64 = 800; - const ERR_OFFER_NOT_RECEIPTOR: u64 = 801; - - /// DAO resource, every DAO has this resource at it's DAO account - struct DAO has key { - id: u64, - name: vector, - // description ipfs://xxxxx - description:vector, - dao_address: address, - next_member_id: u64, - next_proposal_id: u64, - } - - /// Configuration of the DAO. - struct DAOConfig has copy, drop, store { - /// after proposal created, how long use should wait before he can vote (in milliseconds) - voting_delay: u64, - /// how long the voting window is (in milliseconds). - voting_period: u64, - /// the quorum rate to agree on the proposal. - /// if 50% votes needed, then the voting_quorum_rate should be 50. - /// it should between (0, 100]. - voting_quorum_rate: u8, - /// how long the proposal should wait before it can be executed (in milliseconds). - min_action_delay: u64, - /// how many STC should be deposited to create a proposal. - min_proposal_deposit: u128, - } - - struct DAOCustomConfig has copy, drop, store { - config: ConfigT - } - - struct DAOAccountCapHolder has key { - cap: DAOAccountCap, - } - - - /// Capability for minting SBT. - struct DAOSBTMintCapHolder has key { - cap: Token::MintCapability, - } - - /// Capability for burning SBT. - struct DAOSBTBurnCapHolder has key { - cap: Token::BurnCapability, - } - - /// Capability for minting any tokens. - struct DAOTokenMintCapHolder has key { - cap: Token::MintCapability, - } - - /// Capability for burning any tokens. - struct DAOTokenBurnCapHolder has key { - cap: Token::BurnCapability, - } - - struct DAONFTMintCapHolder has key { - cap: NFT::MintCapability>, - } - - struct DAONFTBurnCapHolder has key { - cap: NFT::BurnCapability>, - } - - struct DAONFTUpdateCapHolder has key { - cap: NFT::UpdateCapability>, - } - - struct DAOConfigModifyCapHolder has key { - cap: Config::ModifyConfigCapability - } - - struct DAOCustomConfigModifyCapHolder has key { - cap: Config::ModifyConfigCapability - } - - /// A type describing a capability. - struct CapType has copy, drop, store { code: u8 } - - /// Create a install plugin capability type. - public fun install_plugin_cap_type(): CapType { CapType{ code: 0 } } - - /// Create a upgrade module capability type. - public fun upgrade_module_cap_type(): CapType { CapType{ code: 1 } } - - /// Create a modify dao config capability type. - public fun modify_config_cap_type(): CapType { CapType{ code: 2 } } - - /// Create a withdraw Token capability type. - public fun withdraw_token_cap_type(): CapType { CapType{ code: 3 } } - - /// Create a withdraw NFT capability type. - public fun withdraw_nft_cap_type(): CapType { CapType{ code: 4 } } - - /// Create a write data to DAO account capability type. - public fun storage_cap_type(): CapType { CapType{ code: 5 } } - - /// Create a member capability type. - /// This cap can issue DAO member NFT or update member's SBT - public fun member_cap_type(): CapType { CapType{ code: 6 } } - - /// Create a vote capability type. - public fun proposal_cap_type(): CapType { CapType{ code: 7 } } - - /// Create a grant capability type. - public fun grant_cap_type(): CapType { CapType{ code: 8 } } - - /// Create a token minting capability type. - public fun token_mint_cap_type(): CapType { CapType{code: 9 } } - - /// Create a token burning capability type. - public fun token_burn_cap_type(): CapType { CapType{code: 10 } } - - /// Creates a grant capability type. - public fun plugin_event_cap_type(): CapType { CapType{ code: 11 } } - - /// Create all capability types. - public fun all_caps(): vector { - let caps = Vector::singleton(install_plugin_cap_type()); - Vector::push_back(&mut caps, upgrade_module_cap_type()); - Vector::push_back(&mut caps, modify_config_cap_type()); - Vector::push_back(&mut caps, withdraw_token_cap_type()); - Vector::push_back(&mut caps, withdraw_nft_cap_type()); - Vector::push_back(&mut caps, storage_cap_type()); - Vector::push_back(&mut caps, member_cap_type()); - Vector::push_back(&mut caps, proposal_cap_type()); - Vector::push_back(&mut caps, grant_cap_type()); - Vector::push_back(&mut caps, token_mint_cap_type()); - Vector::push_back(&mut caps, token_burn_cap_type()); - Vector::push_back(&mut caps, plugin_event_cap_type()); - caps - } - - struct DAOInstallPluginCap has drop {} - - struct DAOUpgradeModuleCap has drop {} - - struct DAOModifyConfigCap has drop {} - - struct DAOWithdrawTokenCap has drop {} - - struct DAOWithdrawNFTCap has drop {} - - struct DAOStorageCap has drop {} - - struct DAOMemberCap has drop {} - - struct DAOProposalCap has drop {} - - struct DAOGrantCap has drop {} - - struct DAOPluginEventCap has drop {} - - struct DAOGrantWithdrawTokenKey has key, store{ - /// The total amount of tokens that can be withdrawn by this capability - total: u128, - /// The amount of tokens that have been withdrawn by this capability - withdraw: u128, - /// The time-based linear release start time, timestamp in seconds. - start_time: u64, - /// The time-based linear release period in seconds - period: u64, - } - - /// The info for DAO installed Plugin - struct InstalledPluginInfo has key { - plugin_id: u64, // The plugin id of plugin marketplace - granted_caps: vector, // The granted capabilities - } - - /// The DAO member NFT metadata - struct DAOMember has copy, store, drop { - //Member id - id: u64, - } - - /// The DAO member NFT Body, hold the SBT token - struct DAOMemberBody has store { - sbt: Token, - } - - /// Create a dao with a exists DAO account - public fun create_dao( - cap: DAOAccountCap, - name: vector, - image_data:Option::Option>, - image_url:Option::Option>, - description: vector, - config: DAOConfig - ) acquires DAOEvent { - let dao_signer = DAOAccount::dao_signer(&cap); - - let dao_address = Signer::address_of(&dao_signer); - let id = DAORegistry::register(dao_address); - ASCII::string(copy name); - let dao = DAO{ - id, - name: copy name, - description: copy description, - dao_address, - next_member_id: 1, - next_proposal_id: 1, - }; - - move_to(&dao_signer, dao); - move_to(&dao_signer, DAOAccountCapHolder{ - cap - }); - - Token::register_token(&dao_signer, 1); - let token_mint_cap = Token::remove_mint_capability(&dao_signer); - let token_burn_cap = Token::remove_burn_capability(&dao_signer); - - move_to(&dao_signer, DAOSBTMintCapHolder{ - cap: token_mint_cap, - }); - move_to(&dao_signer, DAOSBTBurnCapHolder{ - cap: token_burn_cap, - }); - - let nft_name = copy name; - let nft_description = copy name; - let basemeta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(nft_name, Option::destroy_some(image_data), nft_description) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(nft_name, Option::destroy_some(image_url), nft_description) - }else{ - NFT::new_meta(nft_name, nft_description) - }; - - - NFT::register_v2>(&dao_signer, basemeta); - let nft_mint_cap = NFT::remove_mint_capability>(&dao_signer); - move_to(&dao_signer, DAONFTMintCapHolder{ - cap: nft_mint_cap, - }); - - let nft_burn_cap = NFT::remove_burn_capability>(&dao_signer); - move_to(&dao_signer, DAONFTBurnCapHolder{ - cap: nft_burn_cap, - }); - - let nft_update_cap = NFT::remove_update_capability>(&dao_signer); - move_to(&dao_signer, DAONFTUpdateCapHolder{ - cap: nft_update_cap, - }); - - let config_modify_cap = Config::publish_new_config_with_capability(&dao_signer, config); - move_to(&dao_signer, DAOConfigModifyCapHolder{ - cap: config_modify_cap, - }); - - move_to(&dao_signer, DAOEvent { - dao_create_event: Event::new_event_handle(&dao_signer), - }); - move_to(&dao_signer ,MemberEvent{ - member_offer_event_handler: Event::new_event_handle(&dao_signer), - member_join_event_handler:Event::new_event_handle(&dao_signer), - member_quit_event_handler:Event::new_event_handle(&dao_signer), - member_revoke_event_handler:Event::new_event_handle(&dao_signer), - member_increase_sbt_event_handler:Event::new_event_handle(&dao_signer), - member_decrease_sbt_event_handler:Event::new_event_handle(&dao_signer), - }); - move_to(&dao_signer, ProposalEvent { - proposal_create_event: Event::new_event_handle(&dao_signer), - vote_event: Event::new_event_handle(&dao_signer), - proposal_action_event: Event::new_event_handle(&dao_signer), - }); - - // dao event emit - let dao_event = borrow_global_mut >(dao_address); - Event::emit_event(&mut dao_event.dao_create_event, - DAOCreatedEvent { - id, - name: copy name, - description:copy description, - dao_address, - }, - ); - } - - /// Upgrade account to DAO account and create DAO - public fun upgrade_to_dao( - sender: signer, - name: vector, - image_data:Option::Option>, - image_url:Option::Option>, - description:vector, - config: DAOConfig - ) acquires DAOEvent{ - let cap = DAOAccount::upgrade_to_dao(sender); - create_dao(cap, name, image_data, image_url, description, config) - } - - /// dao event - struct DAOEvent has key, store{ - dao_create_event:Event::EventHandle, - } - - struct DAOCreatedEvent has drop, store{ - id: u64, - name: vector, - description:vector, - dao_address: address, - } - - /// member event - struct MemberEvent has key, store{ - member_offer_event_handler:Event::EventHandle, - member_join_event_handler:Event::EventHandle, - member_quit_event_handler:Event::EventHandle, - member_revoke_event_handler:Event::EventHandle, - member_increase_sbt_event_handler:Event::EventHandle, - member_decrease_sbt_event_handler:Event::EventHandle, - } - - const MEMBER_OFFER_CREATE: u8 = 0; - const MEMBER_OFFER_REBACK: u8 = 1; - const MEMBER_OFFER_USE: u8 = 2; - - struct MemberOfferEvent has drop, store{ - /// dao id - dao_id: u64, - //type: Create: 0 / Reback: 1 / Use: 2 - type: u8, - //address - addr: address, - //image_data - image_data:Option::Option>, - //image_url - image_url:Option::Option>, - // SBT - sbt: u128, - } - - - const MEMBERJOIN_DIRECT :u8 = 0; - const MEMBERJOIN_OFFER :u8 = 1; - - struct MemberJoinEvent has drop, store{ - /// dao id - dao_id: u64, - // type: direct/offer - type: u8, - //Member id - member_id : u64, - //address - addr: address, - // SBT - sbt: u128, - } - - struct MemberRevokeEvent has drop, store{ - /// dao id - dao_id: u64, - //Member id - member_id : u64, - //address - addr: address, - // SBT - sbt: u128, - } - - struct MemberQuitEvent has drop, store{ - /// dao id - dao_id: u64, - //Member id - member_id : u64, - //address - addr: address, - // SBT - sbt: u128, - } - - struct MemberIncreaseSBTEvent has drop, store{ - //Member id - member_id : u64, - //address - addr: address, - //increase sbt amount - increase_sbt:u128 , - // SBT - sbt: u128, - } - - struct MemberDecreaseSBTEvent has drop, store{ - //Member id - member_id : u64, - //address - addr: address, - //decrease sbt amount - decrease_sbt:u128 , - // SBT - sbt: u128, - } - - // Capability support function - - /// Install plugin with DAOInstallPluginCap - public fun install_plugin(_cap: &DAOInstallPluginCap, granted_caps: vector) acquires DAOAccountCapHolder { - do_install_plugin(granted_caps); - } - - fun do_install_plugin(granted_caps: vector) acquires DAOAccountCapHolder { - assert!(DAOPluginMarketplace::exists_plugin(), Errors::invalid_state(ERR_PLUGIN_NOT_EXIST)); - assert_no_repeat(&granted_caps); - let dao_signer = dao_signer(); - let plugin_id = DAOPluginMarketplace::take_plugin_id(); - - assert!(!exists>(Signer::address_of(&dao_signer)), Errors::already_published(ERR_PLUGIN_HAS_INSTALLED)); - move_to(&dao_signer, InstalledPluginInfo{ - plugin_id: plugin_id, - granted_caps, - }); - } - - /// Uninstall plugin with DAOInstallPluginCap - public fun uninstall_plugin(_cap: &DAOInstallPluginCap) acquires DAOAccountCapHolder, InstalledPluginInfo { - do_uninstall_plugin(); - } - - fun do_uninstall_plugin() acquires DAOAccountCapHolder, InstalledPluginInfo { - assert!(DAOPluginMarketplace::exists_plugin(), Errors::invalid_state(ERR_PLUGIN_NOT_EXIST)); - - let dao_signer = dao_signer(); - let dao_address = Signer::address_of(&dao_signer); - - assert!(exists>(dao_address), Errors::already_published(ERR_PLUGIN_NOT_INSTALLED)); - let installed_plugin = move_from>(dao_address); - - let InstalledPluginInfo { - plugin_id:_, - granted_caps:_, - } = installed_plugin; - } - - // ModuleUpgrade functions - - /// Submit upgrade module plan - public fun submit_upgrade_plan(_cap: &DAOUpgradeModuleCap, package_hash: vector, version: u64, enforced: bool) acquires DAOAccountCapHolder { - let dao_account_cap = &mut borrow_global_mut(dao_address()).cap; - DAOAccount::submit_upgrade_plan(dao_account_cap, package_hash, version, enforced); - } - - // Storage capability function - - struct StorageItem has key { - item: V, - } - - /// Save the item to the storage - public fun save_to_storage(_cap: &DAOStorageCap, item: V) acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - assert!(!exists>(Signer::address_of(&dao_signer)), Errors::already_published(ERR_STORAGE_ERROR)); - move_to(&dao_signer, StorageItem{ - item - }); - } - - /// Get the item from the storage - public fun take_from_storage(_cap: &DAOStorageCap): V acquires StorageItem { - let dao_address = dao_address(); - assert!(exists>(dao_address), Errors::not_published(ERR_STORAGE_ERROR)); - let StorageItem{ item } = move_from>(dao_address); - item - } - - /// Check the item has exists in storage - public fun exists_in_storage(): bool { - exists>(dao_address()) - } - - /// Copy the item from the storage - public fun copy_from_storage(_cap: &DAOStorageCap): V acquires StorageItem { - let dao_address = dao_address(); - assert!(exists>(dao_address), Errors::not_published(ERR_STORAGE_ERROR)); - let storage_item = borrow_global>(dao_address); - *&storage_item.item - } - - // Withdraw Token capability function - - /// Withdraw the token from the DAO account - public fun withdraw_token(_cap: &DAOWithdrawTokenCap, amount: u128): Token acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - //we should extract the WithdrawCapability from account, and invoke the withdraw_with_cap ? - Account::withdraw(&dao_signer, amount) - } - - // NFT capability function - - /// Withdraw the NFT from the DAO account - public fun withdraw_nft(_cap: &DAOWithdrawNFTCap, id: u64): NFT acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - let nft = NFTGallery::withdraw(&dao_signer, id); - assert!(Option::is_some(&nft), Errors::not_published(ERR_NFT_ERROR)); - Option::destroy_some(nft) - } - - // Membership function - - struct MemeberOffer has drop, store{ - to_address: address, - image_data:Option::Option>, - image_url:Option::Option>, - init_sbt: u128 - } - - /// invite a new member to the DAO - public fun issue_member_offer(_cap: &DAOMemberCap, to_address: address, image_data:Option::Option>, image_url:Option::Option>, init_sbt: u128) acquires DAOAccountCapHolder, MemberEvent, DAO { - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let memeber_event = borrow_global_mut(dao_address); - if(is_member(to_address)){ - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_REBACK, - image_data, - image_url, - sbt: init_sbt, - }); - return - }; - - let op_index = Offer::find_offer>(dao_address, to_address); - if(Option::is_some(&op_index)){ - let MemeberOffer{ - to_address, - image_data, - image_url, - init_sbt - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_REBACK, - image_data, - image_url, - sbt: init_sbt, - }); - return - }; - - let offered = MemeberOffer { - to_address, - image_data: copy image_data, - image_url: copy image_url, - init_sbt - }; - Offer::create_v2>(&dao_signer, offered, to_address, 0); - - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_CREATE, - image_data, - image_url, - sbt: init_sbt, - }); - } - - /// Review the member offer - public fun revoke_member_offer(_cap: &DAOMemberCap, to_address: address) acquires DAOAccountCapHolder, MemberEvent, DAO { - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let op_index = Offer::find_offer>(dao_address, to_address); - let memeber_event = borrow_global_mut(dao_address); - if(Option::is_some(&op_index)){ - let MemeberOffer{ - to_address, - image_data, - image_url, - init_sbt - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_REBACK, - image_data, - image_url, - sbt: init_sbt, - }); - } - } - - /// Accept the MemberOffer and become a member - public fun accept_member_offer(sender: &signer) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent, DAONFTUpdateCapHolder { - let dao_address = dao_address(); - let op_index = Offer::find_offer>(dao_address, Signer::address_of(sender)); - assert!(Option::is_some(&op_index),1003); - let memeber_event = borrow_global_mut(dao_address); - let MemeberOffer { - to_address, - image_data, - image_url, - init_sbt - }= Offer::redeem_v2>(sender, dao_address, Option::destroy_some(op_index)); - assert!(to_address == Signer::address_of(sender), Errors::invalid_argument(ERR_OFFER_NOT_RECEIPTOR)); - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_USE, - image_data: copy image_data, - image_url: copy image_url, - sbt: init_sbt, - }); - if(is_member(to_address)){ - increase_member_sbt(&DAOMemberCap{}, to_address, init_sbt); - }else{ - do_join_member(sender, image_data, image_url, init_sbt); - Event::emit_event(&mut memeber_event.member_join_event_handler, MemberJoinEvent { - dao_id: dao_id(dao_address), - type:MEMBERJOIN_OFFER, - member_id:Option::destroy_some(query_member_id(to_address)), - addr:to_address, - sbt: init_sbt, - }); - } - } - - public (script) fun accept_member_offer_entry(sender: signer) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent , DAONFTUpdateCapHolder { - accept_member_offer(&sender) - } - - fun do_join_member(sender: &signer, image_data:Option::Option>, image_url:Option::Option>, init_sbt: u128) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO { - let to_address = Signer::address_of(sender); - ensure_not_member(to_address); - IdentifierNFT::accept, DAOMemberBody>(sender); - let member_id = next_member_id(); - - let meta = DAOMember{ - id: member_id, - }; - - let dao_address = dao_address(); - - let token_mint_cap = &borrow_global_mut>(dao_address).cap; - let sbt = Token::mint_with_capability(token_mint_cap, init_sbt); - - let body = DAOMemberBody{ - sbt, - }; - - let dao = borrow_global(dao_address); - let nft_name = *&dao.name; - let nft_description = *&dao.name; - - let basemeta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(nft_name, Option::destroy_some(image_data), nft_description) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(nft_name, Option::destroy_some(image_url), nft_description) - }else{ - NFT::new_meta(nft_name, nft_description) - }; - let nft_mint_cap = &mut borrow_global_mut>(dao_address).cap; - - let nft = NFT::mint_with_cap_v2(dao_address, nft_mint_cap, basemeta, meta, body); - IdentifierNFT::grant_to(nft_mint_cap, to_address, nft); - } - - /// Member quit DAO by self - public (script) fun quit_member_entry(sender: signer) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO, DAOAccountCapHolder { - quit_member(&sender); - } - - /// Member quit DAO by self - public fun quit_member(sender: &signer) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO, DAOAccountCapHolder { - let member_addr = Signer::address_of(sender); - if(!is_member(member_addr)){ - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let op_index = Offer::find_offer>(dao_address, member_addr); - if(Option::is_some(&op_index)){ - Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - }; - return - }; - - let (member_id , sbt) = do_remove_member(member_addr); - let dao_address = dao_address(); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_quit_event_handler, MemberQuitEvent { - dao_id: dao_id(dao_address), - member_id, - addr:member_addr, - sbt, - }); - } - - /// Revoke membership with cap - public fun revoke_member(_cap: &DAOMemberCap, member_addr: address) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO { - let (member_id , sbt) = do_remove_member(member_addr); - let dao_address = dao_address(); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_revoke_event_handler, MemberRevokeEvent { - dao_id: dao_id(dao_address), - member_id, - addr:member_addr, - sbt: sbt, - }); - } - - public fun ensure_member(member_addr:address){ - assert!(is_member(member_addr), Errors::invalid_state(ERR_EXPECT_MEMBER)); - } - - public fun ensure_not_member(member_addr:address){ - assert!(!is_member(member_addr), Errors::invalid_state(ERR_EXPECT_NOT_MEMBER)); - } - - fun do_remove_member(member_addr: address):(u64,u128) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder { - ensure_member(member_addr); - let dao_address = dao_address(); - - let nft_burn_cap = &mut borrow_global_mut>(dao_address).cap; - let nft = IdentifierNFT::revoke, DAOMemberBody>(nft_burn_cap, member_addr); - let member_id = NFT::get_type_meta, DAOMemberBody>(&nft).id; - let DAOMemberBody{ sbt } = NFT::burn_with_cap(nft_burn_cap, nft); - let sbt_amount = Token::value(&sbt); - let token_burn_cap = &mut borrow_global_mut>(dao_address).cap; - Token::burn_with_capability(token_burn_cap, sbt); - (member_id, sbt_amount) - } - - // join member - public fun join_member_with_member_cap( - _cap: &DAOMemberCap, - sender: &signer, - image_data:Option::Option>, - image_url:Option::Option>, - init_sbt: u128 - ) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent { - let dao_address = dao_address(); - let memeber_event = borrow_global_mut(dao_address); - do_join_member(sender, image_data, image_url, init_sbt); - let to_address = Signer::address_of(sender); - Event::emit_event(&mut memeber_event.member_join_event_handler, MemberJoinEvent { - dao_id: dao_id(dao_address), - type:MEMBERJOIN_DIRECT, - member_id:Option::destroy_some(query_member_id(to_address)), - addr:to_address, - sbt: init_sbt, - }); - } - - /// Increment the member SBT - public fun increase_member_sbt(_cap: &DAOMemberCap, member_addr: address, amount: u128) acquires DAONFTUpdateCapHolder, DAOSBTMintCapHolder, MemberEvent { - ensure_member(member_addr); - let dao_address = dao_address(); - - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft); - let member_id = NFT::get_type_meta, DAOMemberBody>(nft).id; - - let body = NFT::borrow_body_mut_with_cap(nft_update_cap, nft); - - let token_mint_cap = &mut borrow_global_mut>(dao_address).cap; - let increase_sbt = Token::mint_with_capability(token_mint_cap, amount); - Token::deposit(&mut body.sbt, increase_sbt); - - let sbt_amount = Token::value(&body.sbt); - IdentifierNFT::return_back(borrow_nft); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_increase_sbt_event_handler, MemberIncreaseSBTEvent { - member_id, - addr:member_addr, - increase_sbt:amount, - sbt: sbt_amount, - }); - } - - /// Decrement the member SBT - public fun decrease_member_sbt(_cap: &DAOMemberCap, member_addr: address, amount: u128) acquires DAONFTUpdateCapHolder, DAOSBTBurnCapHolder, MemberEvent { - ensure_member(member_addr); - let dao_address = dao_address(); - - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft); - let member_id = NFT::get_type_meta, DAOMemberBody>(nft).id; - - let body = NFT::borrow_body_mut_with_cap(nft_update_cap, nft); - - let token_burn_cap = &mut borrow_global_mut>(dao_address).cap; - let decrease_sbt = Token::withdraw(&mut body.sbt, amount); - let sbt_amount = Token::value(&body.sbt); - - Token::burn_with_capability(token_burn_cap, decrease_sbt); - IdentifierNFT::return_back(borrow_nft); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_decrease_sbt_event_handler, MemberDecreaseSBTEvent { - member_id, - addr:member_addr, - decrease_sbt:amount, - sbt: sbt_amount, - }); - } - - public fun set_member_image( - _cap: &DAOMemberCap, - member_addr: address, - image_data: Option::Option>, - image_url: Option::Option> - ) acquires DAONFTUpdateCapHolder { - ensure_member(member_addr); - - let dao_address = dao_address(); - - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft); - let metadata = *NFT::get_type_meta, DAOMemberBody>(nft); - let old_basemeta = NFT::get_base_meta, DAOMemberBody>(nft); - let new_basemeta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(NFT::meta_name(old_basemeta), Option::destroy_some(image_data), NFT::meta_description(old_basemeta)) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(NFT::meta_name(old_basemeta), Option::destroy_some(image_url), NFT::meta_description(old_basemeta)) - }else{ - NFT::new_meta(NFT::meta_name(old_basemeta), NFT::meta_description(old_basemeta)) - }; - NFT::update_meta_with_cap(nft_update_cap, nft, new_basemeta, metadata); - - IdentifierNFT::return_back(borrow_nft); - } - - /// Query amount of the member SBT - public fun query_sbt(member_addr: address) - : u128 acquires DAONFTUpdateCapHolder { - if (!is_member(member_addr)) { - return 0 - }; - let dao_address = dao_address(); - - let nft_update_cap = - &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = - IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft(&mut borrow_nft); - let body = NFT::borrow_body(nft); - - let result = Token::value(&body.sbt); - IdentifierNFT::return_back(borrow_nft); - result - } - - /// Query member id of the member - public fun query_member_id(member_addr: address): Option::Option{ - if(!is_member(member_addr)){ - return Option::none() - }; - let nft_info = Option::destroy_some(IdentifierNFT::get_nft_info, DAOMemberBody>(member_addr)); - let (_, _, _, type_meta) = NFT::unpack_info(nft_info); - Option::some(type_meta.id) - } - /// Check the `member_addr` account is a member of DAOT - public fun is_member(member_addr: address): bool { - IdentifierNFT::owns, DAOMemberBody>(member_addr) - } - - public fun is_exist_member_offer(member_addr: address):bool{ - let dao_address = dao_address(); - Option::is_some(&Offer::find_offer>(dao_address, member_addr)) - } - - struct PluginEvent has key, store { - event_handle: Event::EventHandle, - } - - /// Plugin event - public fun init_plugin_event< - DAOT: store, - PluginT: store, - EventT: store + drop - >(_cap: &DAOPluginEventCap) acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - EventUtil::init_event(&dao_signer); - } - - public fun emit_plugin_event< - DAOT: store, - PluginT: store, - EventT: store + drop - >( - _cap: &DAOPluginEventCap, - event: EventT - ) { - EventUtil::emit_event(dao_address(), event); - } - - - /// Grant Event - - struct GrantEvent has key, store{ - create_grant_event_handler:Event::EventHandle, - revoke_grant_event_handler:Event::EventHandle, - withdraw_grant_event_handler:Event::EventHandle, - refund_grant_event_handler:Event::EventHandle, - } - - struct GrantCreateEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - start_time:u64, - period:u64, - now_time:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantRevokeEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantRefundEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantConfigEvent has drop, store{ - dao_id: u64, - old_grantee:address, - new_grantee:address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantWithdrawEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - withdraw_value:u128, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - - struct GrantInfo has copy, drop ,store{ - total:u128, - grantee: address, - withdraw:u128, - start_time:u64, - period:u64 - } - - /// Grant function - - - /// Accept grant offer by self - public fun grant_accept_offer(sender: &signer) { - let dao_address = dao_address(); - let op_index = Offer::find_offer>(dao_address, Signer::address_of(sender)); - assert!(Option::is_some(&op_index),1003); - let grant_key = Offer::redeem_v2>(sender, dao_address, Option::destroy_some(op_index)); - move_to(sender, grant_key) - } - - /// Accept grant offer by self entry - public (script) fun grant_accept_offer_entry(sender: signer) { - grant_accept_offer(&sender) - } - - /// Grant offer and init/emit a event - public fun grant_offer(_cap:&DAOGrantCap, grantee: address, total:u128, start_time:u64, period:u64) acquires DAOAccountCapHolder, GrantEvent, DAO { - let dao_signer = dao_signer(); - let dao_address = dao_address(); - - if (!exists(dao_address)){ - move_to(&dao_signer, GrantEvent{ - create_grant_event_handler:Event::new_event_handle(&dao_signer), - revoke_grant_event_handler:Event::new_event_handle(&dao_signer), - withdraw_grant_event_handler:Event::new_event_handle(&dao_signer), - refund_grant_event_handler:Event::new_event_handle(&dao_signer), - }); - }; - let grant_event = borrow_global_mut(dao_address); - - Event::emit_event(&mut grant_event.create_grant_event_handler, GrantCreateEvent { - dao_id:dao_id(dao_address), - grantee, - total, - start_time, - period, - now_time:Timestamp::now_seconds(), - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - - Offer::create_v2>( - &dao_signer, - DAOGrantWithdrawTokenKey{ - total, - withdraw: 0 , - start_time, - period - }, - grantee, - 0 - ); - } - - /// Grant offer refund - public fun grant_offer_refund(sender: &signer)acquires DAOAccountCapHolder, GrantEvent, DAO { - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let grantee = Signer::address_of(sender); - let op_index = Offer::find_offer>(dao_address, grantee); - assert!(Option::is_some(&op_index), Errors::not_published(ERR_OFFER_NOT_EXIST)); - let grant_event = borrow_global_mut(dao_address); - let DAOGrantWithdrawTokenKey{ - total, - withdraw, - start_time, - period - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent { - dao_id:dao_id(dao_address), - grantee, - total, - withdraw, - start_time, - period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - } - - /// Grant offer refund entry - public (script) fun grant_offer_refund_entry(sender: signer)acquires DAOAccountCapHolder, GrantEvent, DAO{ - grant_offer_refund(&sender); - } - - /// Withdraw token with grant - public (script) fun grant_withdraw_entry(sender: signer, amount:u128) acquires DAOAccountCapHolder, DAOGrantWithdrawTokenKey, GrantEvent, DAO{ - grant_withdraw(&sender, amount); - } - - /// Withdraw token with grant - public fun grant_withdraw(sender: &signer, amount:u128) acquires DAOAccountCapHolder, DAOGrantWithdrawTokenKey, GrantEvent, DAO{ - let account_address = Signer::address_of(sender); - assert!(exists>(account_address) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - - let cap = borrow_global_mut>(account_address); - let now = Timestamp::now_seconds(); - let elapsed_time = now - cap.start_time; - let can_amount = if (elapsed_time >= cap.period) { - cap.total - cap.withdraw - } else { - Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw - }; - - assert!(can_amount > 0, Errors::invalid_argument(ERR_INVALID_AMOUNT)); - assert!(can_amount >= amount, Errors::invalid_argument(ERR_INVALID_AMOUNT)); - - let dao_signer = dao_signer(); - let dao_address = dao_address(); - - assert!(amount <= Account::balance(dao_address) , Errors::invalid_argument(ERR_INVALID_AMOUNT)); - cap.withdraw = cap.withdraw + amount; - - let grant_event = borrow_global_mut(dao_address); - Event::emit_event(&mut grant_event.withdraw_grant_event_handler, GrantWithdrawEvent { - dao_id:dao_id(dao_address), - grantee: account_address, - total:cap.total, - withdraw:cap.withdraw, - start_time:cap.start_time, - period:cap.period, - withdraw_value:amount, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - let token = Account::withdraw(&dao_signer, amount); - Account::deposit(account_address, token); - } - - public fun query_grant_withdrawable_amount(addr: address):u128 acquires DAOGrantWithdrawTokenKey{ - assert!(exists>(addr) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - let cap = borrow_global>(addr); - let now = Timestamp::now_seconds(); - let elapsed_time = now - cap.start_time; - if (elapsed_time >= cap.period) { - cap.total - cap.withdraw - } else { - Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw - } - } - /// Is exist DAOGrantWithdrawTokenKey - public fun is_exist_grant(addr:address):bool{ - exists>(addr) - } - /// Revoke grant - public fun grant_revoke(_cap:&DAOGrantCap, grantee: address ) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO { - let dao_address = dao_address(); - let grant_event = borrow_global_mut(dao_address); - if(exists>(grantee)){ - let DAOGrantWithdrawTokenKey{ - total, - withdraw, - start_time, - period - } = move_from>(grantee); - - Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent { - dao_id:dao_id(dao_address), - grantee, - total, - withdraw, - start_time, - period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - }; - } - - /// Revoke grant offer - public fun grant_offer_revoke(_cap:&DAOGrantCap, grantee: address ) acquires GrantEvent, DAO, DAOAccountCapHolder { - let dao_signer = dao_signer(); - let dao_address = dao_address(); - let grant_event = borrow_global_mut(dao_address); - let op_index = Offer::find_offer>(dao_address, grantee); - if(Option::is_some(&op_index)) { - let DAOGrantWithdrawTokenKey { - total, - withdraw, - start_time, - period - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent { - dao_id: dao_id(dao_address), - grantee, - total, - withdraw, - start_time, - period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - }; - } - - /// Refund the grant - public fun refund_grant(sender: &signer) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO { - let dao_address = dao_address(); - let grantee = Signer::address_of(sender); - assert!(exists>(grantee) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - let DAOGrantWithdrawTokenKey{ - total:total, - withdraw:withdraw, - start_time:start_time, - period:period - } = move_from>(grantee); - - let grant_event = borrow_global_mut(dao_address); - Event::emit_event(&mut grant_event.refund_grant_event_handler, GrantRefundEvent { - dao_id:dao_id(dao_address), - grantee, - total:total, - withdraw:withdraw, - start_time:start_time, - period:period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - } - - /// Refund the grant entry - public (script) fun refund_grant_entry(sender: signer) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO { - refund_grant(&sender); - } - - /// Query address grant - public fun query_grant(addr: address): GrantInfo acquires DAOGrantWithdrawTokenKey{ - assert!(exists>(addr) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - let cap = borrow_global>(addr); - GrantInfo{ - total : cap.total, - grantee : addr, - withdraw : cap.withdraw, - start_time : cap.start_time, - period : cap.period - } - } - - /// Query grant info total - public fun query_grant_info_total(grant_info: &GrantInfo):u128{ - grant_info.total - } - - /// Query grant info withdraw - public fun query_grant_info_withdraw(grant_info: &GrantInfo):u128{ - grant_info.withdraw - } - - /// Query grant info start_time - public fun query_grant_info_start_time(grant_info: &GrantInfo):u64{ - grant_info.start_time - } - - /// Query grant info period - public fun query_grant_info_period(grant_info: &GrantInfo):u64{ - grant_info.period - } - - /// Acquiring Capabilities - fun validate_cap(cap: CapType) acquires InstalledPluginInfo { - let addr = dao_address(); - // When create a new DAO, one can pass a `DAOT` type as the `PluginT` type, - // in this case, the signer is equal to have the root cap. - if (TypeInfo::type_of() != TypeInfo::type_of()) { - if (exists>(addr)) { - let plugin_info = borrow_global>(addr); - assert!(Vector::contains(&plugin_info.granted_caps, &cap), Errors::requires_capability(ERR_NO_GRANTED)); - } else { - abort (Errors::requires_capability(ERR_NO_GRANTED)) - } - } - } - - /// Acquire the installed plugin capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_install_plugin_cap(_witness: &PluginT): DAOInstallPluginCap acquires InstalledPluginInfo { - validate_cap(install_plugin_cap_type()); - DAOInstallPluginCap{} - } - - /// Acquire the upgrade module capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_upgrade_module_cap(_witness: &PluginT): DAOUpgradeModuleCap acquires InstalledPluginInfo { - validate_cap(upgrade_module_cap_type()); - DAOUpgradeModuleCap{} - } - - /// Acquire the modify config capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_modify_config_cap(_witness: &PluginT): DAOModifyConfigCap acquires InstalledPluginInfo { - validate_cap(modify_config_cap_type()); - DAOModifyConfigCap{} - } - - /// Acquires the withdraw Token capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_withdraw_token_cap(_witness: &PluginT): DAOWithdrawTokenCap acquires InstalledPluginInfo { - validate_cap(withdraw_token_cap_type()); - DAOWithdrawTokenCap{} - } - - /// Acquires the withdraw NFT capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_withdraw_nft_cap(_witness: &PluginT): DAOWithdrawNFTCap acquires InstalledPluginInfo { - validate_cap(withdraw_nft_cap_type()); - DAOWithdrawNFTCap{} - } - - /// Acquires the storage capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_storage_cap(_witness: &PluginT): DAOStorageCap acquires InstalledPluginInfo { - validate_cap(storage_cap_type()); - DAOStorageCap{} - } - - /// Acquires the membership capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_member_cap(_witness: &PluginT): DAOMemberCap acquires InstalledPluginInfo { - validate_cap(member_cap_type()); - DAOMemberCap{} - } - - /// Acquire the proposql capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_proposal_cap(_witness: &PluginT): DAOProposalCap acquires InstalledPluginInfo { - validate_cap(proposal_cap_type()); - DAOProposalCap{} - } - - /// Acquire the grant capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_grant_cap(_witness: &PluginT): DAOGrantCap acquires InstalledPluginInfo { - validate_cap(grant_cap_type()); - DAOGrantCap{} - } - - - /// Acquire the plugin event capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_plugin_event_cap(_witness: &PluginT): DAOPluginEventCap acquires InstalledPluginInfo { - validate_cap(plugin_event_cap_type()); - DAOPluginEventCap {} - } - - /// Delegate the token mint capability to DAO - /// _witness parameter ensures that the caller is the module which define PluginT - public fun delegate_token_mint_cap(cap: Token::MintCapability, _witness: &PluginT) - acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - move_to>( - &dao_signer, - DAOTokenMintCapHolder { cap }, - ); - } - - /// Delegate the token burn capability to DAO - /// _witness parameter ensures that the caller is the module which define PluginT - public fun delegate_token_burn_cap(cap: Token::BurnCapability, _witness: &PluginT) - acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - move_to>( - &dao_signer, - DAOTokenBurnCapHolder { cap }, - ); - } - - /// Mint token - public fun mint_token(amount: u128, _witness: &PluginT): Token - acquires InstalledPluginInfo, DAOTokenMintCapHolder { - validate_cap(token_mint_cap_type()); - let dao_addr = dao_address(); - assert!(exists>(dao_addr), Errors::not_published(ERR_TOKEN_ERROR)); - let DAOTokenMintCapHolder { cap } = - borrow_global>(dao_addr); - let tokens = Token::mint_with_capability(cap, amount); - tokens - } - - /// Burn token - public fun burn_token(tokens: Token, _witness: &PluginT) - acquires InstalledPluginInfo, DAOTokenBurnCapHolder { - validate_cap(token_burn_cap_type()); - let dao_addr = dao_address(); - assert!(exists>(dao_addr), Errors::not_published(ERR_TOKEN_ERROR)); - let DAOTokenBurnCapHolder { cap } = - borrow_global>(dao_addr); - Token::burn_with_capability(cap, tokens); - } - - /// Proposal - /// -------------------------------------------------- - /// Proposal state - const PENDING: u8 = 1; - const ACTIVE: u8 = 2; - const REJECTED: u8 = 3; - const DEFEATED: u8 = 4; - const AGREED: u8 = 5; - const QUEUED: u8 = 6; - const EXECUTABLE: u8 = 7; - const EXTRACTED: u8 = 8; - - struct ProposalState has copy, drop, store { state: u8 } - - /// voting choice: 1:yes, 2:no, 3: no_with_veto, 4:abstain - const VOTING_CHOICE_YES: u8 = 1; - const VOTING_CHOICE_NO: u8 = 2; - // Review: How to prevent spam, cosmos provide a NO_WITH_VETO option, and the proposer need deposit some Token when create proposal. - // this choice from https://docs.cosmos.network/master/modules/gov/01_concepts.html - const VOTING_CHOICE_NO_WITH_VETO: u8 = 3; - const VOTING_CHOICE_ABSTAIN: u8 = 4; - - struct VotingChoice has copy, drop, store { - choice: u8, - } - - public fun choice_yes(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_YES } } - - public fun choice_no(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_NO } } - - /// no_with_veto counts as no but also adds a veto vote - public fun choice_no_with_veto(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_NO_WITH_VETO } } - - public fun choice_abstain(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_ABSTAIN } } - - /// Proposal data struct. - /// review: it is safe to has `copy` and `drop`? - struct Proposal has store, copy, drop { - /// id of the proposal - id: u64, - /// creator of the proposal - proposer: address, - /// title of proposal - title: vector, - /// introduction of proposal , short introduction - introduction:vector, - /// extend of proposal , ipfs:// | { "title":"xxxxx",........ } - extend:vector, - /// when voting begins. - start_time: u64, - /// when voting ends. - end_time: u64, - /// count of voters who `yes|no|abstain` with the proposal - yes_votes: u128, - no_votes: u128, - abstain_votes: u128, - /// no_with_veto counts as no but also adds a veto vote - no_with_veto_votes: u128, - /// executable after this time. - eta: u64, - /// after how long, the agreed proposal can be executed. - action_delay: u64, - /// how many votes to reach to make the proposal valid. - quorum_votes: u128, - /// the block number when submit proposal - block_number: u64, - /// the state root of the block which has the block_number - state_root: vector, - } - - struct ProposalAction has store { - /// id of the proposal - proposal_id: u64, - //To prevent spam, proposals must be submitted with a deposit - deposit: Token, - /// proposal action. - action: Action, - } - - struct ProposalActionIndex has store, drop { - /// id of the proposal - proposal_id: u64, - } - - /// Keep a global proposal record for query proposal by id. - /// Replace with Table when support Table. - struct GlobalProposals has key { - proposals: vector, - } - - /// Every ActionT keep a vector in the DAO account - struct ProposalActions has key { - actions: vector>, - } - - - /// Keep a global proposal action record for query action by proposal_id. - /// Replace with Table when support Table. - struct GlobalProposalActions has key { - proposal_action_indexs: vector, - } - - /// User vote. - struct Vote has store { - /// proposal id. - proposal_id: u64, - /// vote weight - vote_weight: u128, - /// vote choise - choice: u8, - } - - /// User vote info. has drop cap - struct VoteInfo has store, drop { - /// proposal id. - proposal_id: u64, - /// vote weight - vote_weight: u128, - /// vote choise - choice: u8, - } - - /// Every voter keep a vector Vote for per DAO - struct MyVotes has key { - votes: vector, - } - - /// use bcs se/de for Snapshot proofs - struct SnapshotProof has store, drop, copy { - state: vector, - account_state: vector, - account_proof_leaf: HashNode, - account_proof_siblings: vector>, - account_state_proof_leaf: HashNode, - account_state_proof_siblings: vector>, - } - - struct HashNode has store, drop, copy { - hash1: vector, - hash2: vector, - } - - /// proposal event - struct ProposalEvent has key, store { - /// proposal creating event. - proposal_create_event: Event::EventHandle, - /// voting event. - vote_event: Event::EventHandle, - /// proposal action event. - proposal_action_event: Event::EventHandle, - } - - /// emitted when proposal created. - struct ProposalCreatedEvent has drop, store { - /// dao id - dao_id: u64, - /// title - title: vector, - /// the proposal id. - proposal_id: u64, - /// introduction of proposal , short introduction - introduction:vector, - /// extend of proposal , ipfs:// | { "title":"xxxxx",........ } - extend: vector, - /// proposer is the user who create the proposal. - proposer: address, - } - - /// emitted when user vote/revoke_vote. - struct VotedEvent has drop, store { - /// dao id - dao_id: u64, - /// the proposal id. - proposal_id: u64, - /// the voter. - voter: address, - /// 1:yes, 2:no, 3:no_with_veto, 4:abstain - choice: u8, - /// latest vote count of the voter. - // vote_amount: u128, - vote_weight: u128, - } - - /// emitted when proposal executed. - struct ProposalActionEvent has drop, store { - /// dao id - dao_id: u64, - /// the proposal id. - proposal_id: u64, - /// the sender. - sender: address, - /// proposal state after the action: EXTRACTED or REJECTED - state: u8, - } - - /// propose a proposal. - /// `title`: title of the proposal - /// `introduction`: short introduction of the proposal - /// `extend`: extend of proposal , ipfs:// | { "title":"xxxxx",........ } - /// `action`: the actual action to execute. - /// `action_delay`: the delay to execute after the proposal is agreed - /// `quorum_scale_factor`: used to scale up the base quorum_votes_rate. - /// The final quorum_votes_rate = (1.0 + scale / 100) * quorum_votes_rate - public fun create_proposal( - _cap: &DAOProposalCap, - sender: &signer, - action: ActionT, - title: vector, - introduction: vector, - extend: vector, - action_delay: u64, - quorum_scale_factor: Option::Option, - ): u64 acquires DAO, GlobalProposals, DAOAccountCapHolder, ProposalActions, ProposalEvent, GlobalProposalActions { - // check DAO member - let sender_addr = Signer::address_of(sender); - ensure_member(sender_addr); - - if (action_delay == 0) { - action_delay = min_action_delay(); - } else { - assert!(action_delay >= min_action_delay(), Errors::invalid_argument(ERR_ACTION_DELAY_TOO_SMALL)); - }; - - let min_proposal_deposit = min_proposal_deposit(); - let deposit = Account::withdraw(sender, min_proposal_deposit); - - let proposal_id = next_proposal_id(); - let proposer = Signer::address_of(sender); - let start_time = Timestamp::now_milliseconds() + voting_delay(); - let quorum_votes = quorum_votes(quorum_scale_factor); - let voting_period = voting_period(); - - let (block_number,state_root) = block_number_and_state_root(); - - let proposal = Proposal { - id: proposal_id, - proposer, - title: copy title, - introduction: copy introduction, - extend: copy extend, - start_time, - end_time: start_time + voting_period, - yes_votes: 0, - no_votes: 0, - abstain_votes: 0, - no_with_veto_votes: 0, - eta: 0, - action_delay, - quorum_votes, - block_number, - state_root, - }; - let proposal_action = ProposalAction{ - proposal_id, - deposit, - action, - }; - let proposal_action_index = ProposalActionIndex{ - proposal_id, - }; - - let dao_signer = dao_signer(); - let dao_address = dao_address(); - - let actions = Vector::singleton(proposal_action); - // check ProposalActions is exists - if(exists>(dao_address)){ - let current_actions = borrow_global_mut>(dao_address); - assert!(Vector::length(¤t_actions.actions) < MAX_PROPOSALS, Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT)); - Vector::append(&mut current_actions.actions, actions); - }else{ - move_to(&dao_signer, ProposalActions{ - actions, - }); - }; - - let proposal_action_indexs = Vector::singleton(proposal_action_index); - // check GlobalProposalActions is exists - if(exists(dao_address)){ - let current_global_proposal_actions = borrow_global_mut(dao_address); - assert!(Vector::length(¤t_global_proposal_actions.proposal_action_indexs) < MAX_PROPOSALS, - Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT)); - Vector::append(&mut current_global_proposal_actions.proposal_action_indexs, proposal_action_indexs); - }else{ - move_to(&dao_signer, GlobalProposalActions{ - proposal_action_indexs, - }); - }; - - let proposals = Vector::singleton(proposal); - // check GlobalProposals is exists - if(exists(dao_address)){ - let current_global_proposals = borrow_global_mut(dao_address); - assert!(Vector::length(¤t_global_proposals.proposals) < MAX_PROPOSALS, - Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT)); - Vector::append(&mut current_global_proposals.proposals, proposals); - }else{ - move_to(&dao_signer, GlobalProposals{ - proposals, - }); - }; - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut>(dao_address); - Event::emit_event(&mut proposal_event.proposal_create_event, - ProposalCreatedEvent { dao_id, proposal_id, title, introduction: copy introduction, extend: copy extend, proposer }, - ); - - proposal_id - } - - /// get lastest block number and state root - fun block_number_and_state_root(): (u64, vector) { - Block::latest_state_root() - } - - - /// votes for a proposal. - /// User can only vote once, then the stake is locked, - /// The voting power depends on the strategy of the proposal configuration and the user's token amount at the time of the snapshot - public fun cast_vote( - sender: &signer, - proposal_id: u64, - snpashot_raw_proofs: vector, - choice: VotingChoice, - ) acquires GlobalProposals, MyVotes, ProposalEvent, GlobalProposalActions, DAO { - let sender_addr = Signer::address_of(sender); - ensure_member(sender_addr); - - let dao_address = dao_address(); - let proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal_mut(proposals, proposal_id); - - { - let state = proposal_state_with_proposal(proposal); - // only when proposal is active, use can cast vote. - assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - }; - - // verify snapshot state proof - let snapshot_proof = deserialize_snapshot_proofs(&snpashot_raw_proofs); - let state_proof = new_state_proof_from_proofs(&snapshot_proof); - let resource_struct_tag = SnapshotUtil::get_sturct_tag(); - // verify state_proof according to proposal snapshot proofs, and state root - let verify = StarcoinVerifier::verify_state_proof(&state_proof, &proposal.state_root, sender_addr, &resource_struct_tag, &snapshot_proof.state); - assert!(verify, Errors::invalid_state(ERR_STATE_PROOF_VERIFY_INVALID)); - - // decode sbt value from snapshot state - let vote_weight = SBTVoteStrategy::get_voting_power(&snapshot_proof.state); - - assert!(!has_voted(sender_addr, proposal_id), Errors::invalid_state(ERR_VOTED_ALREADY)); - - let vote = Vote{ - proposal_id, - vote_weight, - choice: choice.choice, - }; - - do_cast_vote(proposal, &mut vote); - - if (exists>(sender_addr)) { - assert!(vote.proposal_id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY)); - let my_votes = borrow_global_mut>(sender_addr); - Vector::push_back(&mut my_votes.votes, vote); - } else { - move_to(sender, MyVotes{ - votes: Vector::singleton(vote), - }); - }; - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut >(DAORegistry::dao_address()); - Event::emit_event(&mut proposal_event.vote_event, - VotedEvent { - dao_id, - proposal_id, - voter: sender_addr, - choice: choice.choice, - vote_weight, - }, - ); - } - -// pub struct StateWithProofView { -// pub state: Option>>, -// pub account_state: Option>>, -// pub account_proof: SparseMerkleProofView, -// pub account_state_proof: SparseMerkleProofView, -// } - -// pub struct SparseMerkleProofView { -// /// This proof can be used to authenticate whether a given leaf exists in the tree or not. -// /// - If this is `Some(HashValue, HashValue)` -// /// - If the first `HashValue` equals requested key, this is an inclusion proof and the -// /// second `HashValue` equals the hash of the corresponding account blob. -// /// - Otherwise this is a non-inclusion proof. The first `HashValue` is the only key -// /// that exists in the subtree and the second `HashValue` equals the hash of the -// /// corresponding account blob. -// /// - If this is `None`, this is also a non-inclusion proof which indicates the subtree is -// /// empty. -// pub leaf: Option<(HashValue, HashValue)>, -// -// /// All siblings in this proof, including the default ones. Siblings are ordered from the bottom -// /// level to the root level. -// pub siblings: Vec, -// } - fun deserialize_snapshot_proofs(snpashot_raw_proofs: &vector): SnapshotProof{ - assert!(Vector::length(snpashot_raw_proofs) > 0, Errors::invalid_argument(ERR_SNAPSHOT_PROOF_PARAM_INVALID)); - let offset= 0; - let (state_option, offset) = BCS::deserialize_option_bytes(snpashot_raw_proofs, offset); - let (account_state_option, offset) = BCS::deserialize_option_bytes(snpashot_raw_proofs, offset); - - let (account_proof_leaf1_option, account_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(snpashot_raw_proofs, offset); - let account_proof_leaf1 = Option::get_with_default(&mut account_proof_leaf1_option, Vector::empty()); - let account_proof_leaf2 = Option::get_with_default(&mut account_proof_leaf2_option, Vector::empty()); - let (account_proof_siblings, offset) = BCS::deserialize_bytes_vector(snpashot_raw_proofs, offset); - - let (account_state_proof_leaf1_option, account_state_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(snpashot_raw_proofs, offset); - let account_state_proof_leaf1 = Option::get_with_default(&mut account_state_proof_leaf1_option, Vector::empty()); - let account_state_proof_leaf2 = Option::get_with_default(&mut account_state_proof_leaf2_option, Vector::empty()); - let (account_state_proof_siblings, _offset) = BCS::deserialize_bytes_vector(snpashot_raw_proofs, offset); - - SnapshotProof { - state: Option::get_with_default(&mut state_option, Vector::empty()), - account_state: Option::get_with_default(&mut account_state_option, Vector::empty()), - account_proof_leaf: HashNode { - hash1: account_proof_leaf1, - hash2: account_proof_leaf2, - }, - account_proof_siblings, - account_state_proof_leaf: HashNode { - hash1: account_state_proof_leaf1, - hash2: account_state_proof_leaf2, - }, - account_state_proof_siblings, - } - } - - fun new_state_proof_from_proofs(snpashot_proofs: &SnapshotProof): StateProof{ - let state_proof = StarcoinVerifier::new_state_proof( - StarcoinVerifier::new_sparse_merkle_proof( - *&snpashot_proofs.account_proof_siblings, - StarcoinVerifier::new_smt_node( - *&snpashot_proofs.account_proof_leaf.hash1, - *&snpashot_proofs.account_proof_leaf.hash2, - ), - ), - *&snpashot_proofs.account_state, - StarcoinVerifier::new_sparse_merkle_proof( - *&snpashot_proofs.account_state_proof_siblings, - StarcoinVerifier::new_smt_node( - *&snpashot_proofs.account_state_proof_leaf.hash1, - *&snpashot_proofs.account_state_proof_leaf.hash2, - ), - ), - ); - state_proof - } - - #[test] - fun test_snapshot_proof() { - // barnard, block number 6201718 - let snpashot_raw_proofs = x"0145016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f64617461005704000000000000640000000000000000000000000000000145020120cc969848619e507450ebf01437155ab5f2dbb554fe611cb71958855a1b2ec664012035f2374c333a51e46b62b693ebef25b9be2cefde8d156db08bff28f9a0b87742012073837fcf4e69ae60e18ea291b9f25c86ce8053c6ee647a2b287083327c67dd7e20dac300fb581a6df034a44a99e8eb1cd55c7dd8f0a9e78f1114a6b4eda01d834e0e2078179a07914562223d40068488a0d65673b3b2681642633dc33904575f8f070b20b7c2a21de200ca82241e5e480e922258591b219dd56c24c4d94299020ee8299a204f541db82477510f699c9d75dd6d8280639a1ec9d0b90962cbc0c2b06514a78b20cacfce99bb564cfb70eec6a61bb76b9d56eb1b626d7fa231338792e1f572a8df20da6c1337ca5d8f0fa18b2db35844c610858a710edac35206ef0bf52fd32a4ac920ef6fb8f82d32ca2b7c482b7942505e6492bffa3ed14dd635bae16a14b4ac32e6202ad7b36e08e7b5d208de8eec1ef1964dc8433ccca8ac4632f36054926e858ac32027d5ccc8aa57b964ad50334f62821188b89945ae999ad0bb31cdc16df1763f8120afa983813953d6aa9563db12d5e443c9e8114c3482867c95a661a240d6f0e0ec206466ac318f5d9deb7b64b12622a0f4bed2f19379667d18b6ccfeaa84171d812f20eb45021b7b39887925a5b49018cdc8ad44c14835a42e5775666315f4a3e0ba42204c2b365a78e4615873772a0f039a7326150472b4923d40640863dbe42a2351eb20825d0c21dd1105faf528934842419f8661d695fc72ec6ef8036f5d03359126d3205d806c027eecdfbc3960e68c5997718a0709a6079f96e1af3ffe21878ada2b830120fa60f8311936961f5e9dee5ccafaea83ed91c6eaa04a7dea0b85a38cf84d8564207ef6a85019523861474cdf47f4db8087e5368171d95cc2c1e57055a72ca39cb704208db1e4e4c864882bd611b1cda02ca30c43b3c7bc56ee7cb174598188da8b49ef2063b3f1e4f05973830ba40e0c50c4e59f31d3baa5643d19676ddbacbf797bf6b720b39d31107837c1751d439706c8ddac96f8c148b8430ac4f40546f33fb9871e4320fb0ad035780bb8f1c6481bd674ccad0948cd2e8e6b97c08e582f67cc26918fb3"; - let state_root = x"d5cd5dc44799c989a84b7d4a810259f373b13a9bf8ee21ecbed0fab264e2090d"; - let account_address = @0x6bfb460477adf9dd0455d3de2fc7f211; - // 0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - let resource_struct_tag = x"000000000000000000000000000000010d4964656e7469666965724e46540d4964656e7469666965724e465402076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650944616f4d656d62657201076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650d44616f4d656d626572426f647901076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00"; - - let snapshot_proof = deserialize_snapshot_proofs(&snpashot_raw_proofs); - let state_proof = new_state_proof_from_proofs(&snapshot_proof); - - let b = StarcoinVerifier::verify_state_proof( - &state_proof, - &state_root, - account_address, - &resource_struct_tag, - &snapshot_proof.state, - ); - assert!(b, 8006); - } - - - // Execute the proposal and return the action. - public fun execute_proposal( - _cap: &DAOProposalCap, - sender: &signer, - proposal_id: u64, - ): ActionT acquires ProposalActions, GlobalProposals, GlobalProposalActions, ProposalEvent, DAO { - // Only executable proposal's action can be extracted. - assert!(proposal_state(proposal_id) == EXECUTABLE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - let dao_address = dao_address(); - let sender_addr = Signer::address_of(sender); - assert!(exists>(dao_address), Errors::invalid_state(ERR_PROPOSAL_ACTIONS_NOT_EXIST)); - - let (actionT, deposit) = take_proposal_action(dao_address, proposal_id); - - let global_proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal(global_proposals, proposal_id); - - Account::deposit(proposal.proposer, deposit); - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut>(dao_address); - Event::emit_event(&mut proposal_event.proposal_action_event, - ProposalActionEvent { dao_id, proposal_id, sender: sender_addr, state: EXTRACTED } - ); - - actionT - } - - // Clean proposals that have been rejected or executed. - public fun clean_proposals(_sender: &signer) - acquires GlobalProposals, GlobalProposalActions { - let dao_address = dao_address(); - let global_proposals = borrow_global_mut(dao_address); - - let i = 0; - let len = Vector::length(&global_proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&global_proposals.proposals, i); - let state = proposal_state_with_proposal(proposal); - if (state == EXTRACTED || state == REJECTED) { - let _ = Vector::remove(&mut global_proposals.proposals, i); - len = len - 1; - } else { - i = i + 1; - } - }; - } - - public (script) fun clean_proposals_entry(sender: signer) - acquires GlobalProposals, GlobalProposalActions { - clean_proposals(&sender); - } - - // Clean specific proposal by proposal id, only for rejected or executed proposals - public fun clean_proposal_by_id(_sender: &signer, proposal_id: u64) - acquires GlobalProposals, GlobalProposalActions { - let dao_address = dao_address(); - let global_proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal(global_proposals, proposal_id); - let state = proposal_state_with_proposal(proposal); - assert!(state == EXTRACTED || state == REJECTED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - - let _ = remove_proposal(global_proposals, proposal_id); - } - - public (script) fun clean_proposal_by_id_entry(sender: signer, proposal_id: u64) - acquires GlobalProposals, GlobalProposalActions { - clean_proposal_by_id(&sender, proposal_id) - } - - fun take_proposal_action(dao_address: address, proposal_id: u64): (ActionT, Token) - acquires ProposalActions, GlobalProposalActions { - let actions = borrow_global_mut>(dao_address); - let index_opt = find_action(&actions.actions, proposal_id); - assert!(Option::is_some(&index_opt), Errors::invalid_argument(ERR_ACTION_INDEX_INVALID)); - - let index = Option::extract(&mut index_opt); - let ProposalAction{ proposal_id:_, deposit, action} = Vector::remove(&mut actions.actions, index); - - // remove proposal action index - let global_proposal_actions = borrow_global_mut(dao_address); - let proposal_action_index_opt = find_proposal_action_index(global_proposal_actions, proposal_id); - assert!(Option::is_some(&proposal_action_index_opt), Errors::invalid_argument(ERR_PROPOSAL_ACTION_INDEX_NOT_EXIST)); - let propopsal_action_index = Option::extract(&mut proposal_action_index_opt); - let ProposalActionIndex{ proposal_id:_,} = Vector::remove(&mut global_proposal_actions.proposal_action_indexs, propopsal_action_index); - - (action, deposit) - } - - fun remove_proposal(proposals: &mut GlobalProposals, proposal_id: u64): Proposal { - let i = 0; - let len = Vector::length(&proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&proposals.proposals, i); - if(proposal.id == proposal_id){ - let proposal = Vector::remove(&mut proposals.proposals, i); - return proposal - }; - i = i + 1; - }; - abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST) - } - - fun find_action(actions: &vector>, proposal_id: u64): Option{ - let i = 0; - let len = Vector::length(actions); - while(i < len){ - let action = Vector::borrow(actions, i); - if(action.proposal_id == proposal_id){ - return Option::some(i) - }; - i = i + 1; - }; - Option::none() - } - - fun do_cast_vote(proposal: &mut Proposal, vote: &mut Vote){ - if (choice_yes().choice == vote.choice) { - proposal.yes_votes = proposal.yes_votes + vote.vote_weight; - } else if (choice_no().choice == vote.choice) { - proposal.no_votes = proposal.no_votes + vote.vote_weight; - } else if ( choice_no_with_veto().choice == vote.choice) { - proposal.no_with_veto_votes = proposal.no_with_veto_votes + vote.vote_weight; - } else if (choice_abstain().choice == vote.choice) { - proposal.abstain_votes = proposal.abstain_votes + vote.vote_weight; - } else { - abort Errors::invalid_argument(ERR_VOTE_PARAM_INVALID) - }; - } - - fun has_voted(sender: address, proposal_id: u64): bool acquires MyVotes{ - if(exists>(sender)){ - let my_votes = borrow_global>(sender); - let vote = vote_info(my_votes, proposal_id); - Option::is_some(&vote) - }else{ - false - } - } - - /// vote info by proposal_id - fun vote_info(my_votes: &MyVotes, proposal_id: u64): Option{ - let len = Vector::length(&my_votes.votes); - let idx = 0; - loop { - if (idx >= len) { - break - }; - let vote = Vector::borrow(&my_votes.votes, idx); - if (proposal_id == vote.proposal_id) { - let vote_info = VoteInfo { - proposal_id: vote.proposal_id, - vote_weight: vote.vote_weight, - choice: vote.choice, - }; - return Option::some(vote_info) - }; - idx = idx + 1; - }; - Option::none() - } - - /// Proposals are rejected when their nowithveto option reaches a certain threshold - /// A portion of the pledged tokens will be rewarded to the executor who executes the proposal - public fun reject_proposal(sender: &signer, proposal_id: u64) - acquires DAO, ProposalEvent, ProposalActions, GlobalProposals, GlobalProposalActions{ - // Only REJECTED proposal's action can be burn token. - assert!(proposal_state(proposal_id) == REJECTED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - let dao_address = dao_address(); - assert!(exists>(dao_address), Errors::invalid_state(ERR_PROPOSAL_ACTIONS_NOT_EXIST)); - let (_, token) = take_proposal_action(dao_address, proposal_id); - // Part of the token is awarded to whoever executes this method , current: 10 % - let award_amount = Token::value(&token) / 10; - let (burn_token , award_token) = Token::split(token, award_amount); - Account::deposit(Signer::address_of(sender), award_token); - STC::burn(burn_token); - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut>(dao_address); - Event::emit_event(&mut proposal_event.proposal_action_event, - ProposalActionEvent { dao_id, proposal_id, sender: Signer::address_of(sender), state: REJECTED } - ); - } - - public (script) fun reject_proposal_entry(sender: signer, proposal_id: u64) - acquires DAO, ProposalEvent, ProposalActions, GlobalProposals, GlobalProposalActions{ - reject_proposal(&sender, proposal_id); - } - - /// get vote info by proposal_id - public fun get_vote_info(voter: address, proposal_id: u64): (u64, u8, u128)acquires MyVotes { - if(exists>(voter)){ - let my_votes = borrow_global>(voter); - let vote_option = vote_info(my_votes, proposal_id); - if(!Option::is_some(&vote_option)){ - return (0, 0, 0) - }; - let vote = Option::extract(&mut vote_option); - (vote.proposal_id, vote.choice, vote.vote_weight) - }else{ - (0, 0, 0) - } - } - - public fun proposal_state(proposal_id: u64) : u8 acquires GlobalProposalActions, GlobalProposals { - let dao_address = dao_address(); - let proposals = borrow_global(dao_address); - let proposal = borrow_proposal(proposals, proposal_id); - - proposal_state_with_proposal(proposal) - } - - fun proposal_state_with_proposal(proposal: &Proposal) : u8 acquires GlobalProposalActions { - let dao_address = dao_address(); - let current_time = Timestamp::now_milliseconds(); - - let global_proposal_actions = borrow_global(dao_address); - let action_index_opt = find_proposal_action_index(global_proposal_actions, proposal.id); - - do_proposal_state(proposal, current_time, action_index_opt) - } - - fun do_proposal_state(proposal: &Proposal, current_time: u64, action_index_opt: Option): u8 { - if (current_time < proposal.start_time) { - // Pending - PENDING - } else if (current_time <= proposal.end_time) { - // Active - ACTIVE - } else if (proposal.no_with_veto_votes >= (proposal.no_votes + proposal.yes_votes) ){ - // rejected - REJECTED - } else if (proposal.yes_votes <= (proposal.no_votes + proposal.no_with_veto_votes) || - ( proposal.yes_votes + proposal.no_votes + proposal.abstain_votes + proposal.no_with_veto_votes ) < proposal.quorum_votes) { - // Defeated - DEFEATED - } else if (proposal.eta == 0) { - // Agreed. - AGREED - } else if (current_time < proposal.eta) { - // Queued, waiting to execute - QUEUED - } else if (Option::is_some(&action_index_opt)) { - EXECUTABLE - } else { - EXTRACTED - } - } - - fun borrow_proposal_mut(proposals: &mut GlobalProposals, proposal_id: u64): &mut Proposal{ - let i = 0; - let len = Vector::length(&proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&proposals.proposals, i); - if(proposal.id == proposal_id){ - return Vector::borrow_mut(&mut proposals.proposals, i) - }; - i = i + 1; - }; - abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST) - } - - fun borrow_proposal(proposals: &GlobalProposals, proposal_id: u64): &Proposal { - let i = 0; - let len = Vector::length(&proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&proposals.proposals, i); - if(proposal.id == proposal_id){ - return proposal - }; - i = i + 1; - }; - abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST) - } - - fun find_proposal_action_index(global_proposal_action: &GlobalProposalActions, proposal_id: u64): Option { - let i = 0; - let len = Vector::length(&global_proposal_action.proposal_action_indexs); - while(i < len){ - let proposal_action_index = Vector::borrow(&global_proposal_action.proposal_action_indexs, i); - if(proposal_action_index.proposal_id == proposal_id){ - return Option::some(i) - }; - i = i + 1; - }; - Option::none() - } - - /// Return a copy of Proposal of proposal_id - public fun proposal(proposal_id: u64): Proposal acquires GlobalProposals{ - let dao_address = dao_address(); - let global_proposals = borrow_global(dao_address); - *borrow_proposal(global_proposals, proposal_id) - } - - /// get proposal's id. - public fun proposal_id(proposal: &Proposal): u64 { - proposal.id - } - - /// get proposal's proposer. - public fun proposal_proposer(proposal: &Proposal): address { - proposal.proposer - } - - /// get proposal's time(start_time/end_time). - public fun proposal_time(proposal: &Proposal): (u64, u64) { - (proposal.start_time,proposal.end_time) - } - - /// get proposal's votes(Yes/No/Abstain/Veto). - public fun proposal_votes(proposal: &Proposal): (u128, u128, u128, u128) { - (proposal.yes_votes, proposal.no_votes, proposal.abstain_votes, proposal.no_with_veto_votes) - } - - /// get proposal's block number. - public fun proposal_block_number(proposal: &Proposal): u64 { - proposal.block_number - } - - /// get proposal's state root. - public fun proposal_state_root(proposal: &Proposal): vector { - *&proposal.state_root - } - - /// queue agreed proposal to execute. - public(script) fun queue_proposal_action_entry( - _signer: signer, - proposal_id: u64, - ) acquires GlobalProposalActions, GlobalProposals { - queue_proposal_action(proposal_id) - } - - /// queue agreed proposal to execute. - public fun queue_proposal_action( - proposal_id: u64, - ) acquires GlobalProposalActions, GlobalProposals { - // Only agreed proposal can be submitted. - assert!(proposal_state(proposal_id) == AGREED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - let dao_address = dao_address(); - let proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal_mut(proposals, proposal_id); - proposal.eta = Timestamp::now_milliseconds() + proposal.action_delay; - } - - public(script) fun cast_vote_entry( - sender: signer, - proposal_id: u64, - snpashot_raw_proofs: vector, - choice: u8, - ) acquires MyVotes, GlobalProposals, ProposalEvent, GlobalProposalActions, DAO { - let sender_addr = Signer::address_of(&sender); - if (has_voted(sender_addr, proposal_id)) { - abort Errors::invalid_state(ERR_VOTED_ALREADY) - }; - - let vote_choice = VotingChoice { - choice, - }; - cast_vote(&sender, proposal_id, snpashot_raw_proofs, vote_choice) - } - - /// DAOConfig - /// --------------------------------------------------- - - /// create a dao config - public fun new_dao_config( - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128, - ): DAOConfig{ - assert!(voting_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - assert!(voting_period > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - assert!( - voting_quorum_rate > 0 && voting_quorum_rate <= 100, - Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID), - ); - assert!(min_action_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - DAOConfig { voting_delay, voting_period, voting_quorum_rate, min_action_delay, min_proposal_deposit } - } - - // Get config - public fun get_custom_config(): ConfigT { - let dao_address = dao_address(); - Config::get_by_address(dao_address) - } - - // Get config - public fun exists_custom_config(): bool { - let dao_address = dao_address(); - Config::config_exist_by_address(dao_address) - } - - /// Update, save function of custom plugin configuration - public fun set_custom_config( - _cap: &mut DAOModifyConfigCap, - config: ConfigT) - acquires DAOCustomConfigModifyCapHolder, DAOAccountCapHolder { - let dao_address = dao_address(); - if (Config::config_exist_by_address(dao_address)) { - let cap_holder = - borrow_global_mut>(dao_address); - let modify_config_cap = &mut cap_holder.cap; - Config::set_with_capability(modify_config_cap, config); - } else { - let signer = dao_signer(); - move_to(&signer, DAOCustomConfigModifyCapHolder { - cap: Config::publish_new_config_with_capability(&signer, config) - }); - } - } - - //StarcoinDAO add Config cap - public (friend) fun set_custom_config_cap( - config_cap: Config::ModifyConfigCapability) - acquires DAOAccountCapHolder{ - let signer = dao_signer(); - move_to(&signer, DAOCustomConfigModifyCapHolder { - cap: config_cap - }); - } - - /// Update DAO description - public fun set_dao_description( - _cap: &mut DAOModifyConfigCap, - description: vector) - acquires DAO{ - let dao_address = dao_address(); - let dao = borrow_global_mut(dao_address); - dao.description = description; - } - - - /// Update DAO NFT image - public fun set_dao_image( - _cap: &mut DAOModifyConfigCap, - image_data:Option::Option>, - image_url:Option::Option>) - acquires DAONFTUpdateCapHolder{ - let dao_address = dao_address(); - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let old_meta = NFT::nft_type_info_meta>(); - let new_meta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(NFT::meta_name(&old_meta), Option::destroy_some(image_data), NFT::meta_description(&old_meta)) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(NFT::meta_name(&old_meta), Option::destroy_some(image_url), NFT::meta_description(&old_meta)) - }else{ - NFT::new_meta(NFT::meta_name(&old_meta), NFT::meta_description(&old_meta)) - }; - NFT::update_nft_type_info_meta_with_cap>(nft_update_cap, new_meta); - } - - /// get default voting delay of the DAO. - public fun voting_delay(): u64 { - get_config().voting_delay - } - - /// get the default voting period of the DAO. - public fun voting_period(): u64 { - get_config().voting_period - } - - /// Quorum votes to make proposal valid. - public fun quorum_votes(scale_factor: Option::Option): u128 { - let scale_factor = if (Option::is_none(&scale_factor)) { - 0u8 - } else { - Option::extract(&mut scale_factor) - }; - assert!( - scale_factor >= 0 && scale_factor <= 100, - Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID), - ); - - let market_cap = Token::market_cap(); - let rate = (voting_quorum_rate() as u128); - let rate = rate + rate * (scale_factor as u128) / 100; - assert!( - rate > 0 && rate <= 100, - Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID), - ); - market_cap * rate / 100 - } - - /// Get the quorum rate in percent. - public fun voting_quorum_rate(): u8 { - get_config().voting_quorum_rate - } - - /// Get the min action delay of the DAO. - public fun min_action_delay(): u64 { - get_config().min_action_delay - } - - /// Get the min proposal deposit of the DAO. - public fun min_proposal_deposit(): u128{ - get_config().min_proposal_deposit - } - - fun get_config(): DAOConfig { - let dao_address= dao_address(); - Config::get_by_address(dao_address) - } - - /// Update function, modify dao config. - public fun modify_dao_config( - _cap: &mut DAOModifyConfigCap, - new_config: DAOConfig, - ) acquires DAOConfigModifyCapHolder { - let modify_config_cap = &mut borrow_global_mut( - dao_address(), - ).cap; - Config::set_with_capability(modify_config_cap, new_config); - } - - /// set voting delay - public fun set_voting_delay( - config: &mut DAOConfig, - value: u64, - ) { - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - config.voting_delay = value; - } - - /// set voting period - public fun set_voting_period( - config: &mut DAOConfig, - value: u64, - ) { - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - config.voting_period = value; - } - - /// set voting quorum rate - public fun set_voting_quorum_rate( - config: &mut DAOConfig, - value: u8, - ) { - assert!(value <= 100 && value > 0, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID)); - config.voting_quorum_rate = value; - } - - /// set min action delay - public fun set_min_action_delay( - config: &mut DAOConfig, - value: u64, - ) { - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - config.min_action_delay = value; - } - - /// set min action delay - public fun set_min_proposal_deposit( - config: &mut DAOConfig, - value: u128, - ) { - config.min_proposal_deposit = value; - } - - - /// Helpers - /// --------------------------------------------------- - - - fun next_member_id(): u64 acquires DAO { - let dao_address = dao_address(); - let dao = borrow_global_mut(dao_address); - let member_id = dao.next_member_id; - dao.next_member_id = member_id + 1; - member_id - } - - fun next_proposal_id(): u64 acquires DAO { - let dao_address = dao_address(); - let dao = borrow_global_mut(dao_address); - let proposal_id = dao.next_proposal_id; - dao.next_proposal_id = proposal_id + 1; - proposal_id - } - - fun assert_no_repeat(v: &vector) { - let i = 1; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - let j = 0; - while (j < i) { - let f = Vector::borrow(v, j); - assert!(e != f, Errors::invalid_argument(ERR_REPEAT_ELEMENT)); - j = j + 1; - }; - i = i + 1; - }; - } - - #[test] - fun test_assert_no_repeat() { - let v = Vector::singleton(1); - Vector::push_back(&mut v, 2); - Vector::push_back(&mut v, 3); - assert_no_repeat(&v); - } - - #[test] - #[expected_failure] - fun test_assert_no_repeat_fail() { - let v = Vector::singleton(1); - Vector::push_back(&mut v, 2); - Vector::push_back(&mut v, 3); - Vector::push_back(&mut v, 1); - assert_no_repeat(&v); - } - - /// Helper to remove an element from a vector. - fun remove_element(v: &mut vector, x: &E) { - let (found, index) = Vector::index_of(v, x); - if (found) { - Vector::remove(v, index); - } - } - - /// Helper to add an element to a vector. - fun add_element(v: &mut vector, x: E) { - if (!Vector::contains(v, &x)) { - Vector::push_back(v, x) - } - } - - fun convert_option_bytes_vector(input: &vector>>): vector> { - let len = Vector::length(input); - let i = 0; - let output = Vector::empty>(); - while (i < len) { - let option = Vector::borrow(input, i); - if (Option::is_some(option)){ - Vector::push_back(&mut output, Option::extract(&mut *option)); - }; - i = i + 1; - }; - output - } - - fun dao_signer(): signer acquires DAOAccountCapHolder { - let cap = &borrow_global(dao_address()).cap; - DAOAccount::dao_signer(cap) - } - - public fun dao_address(): address { - DAORegistry::dao_address() - } - - public fun dao_id(dao_address: address): u64 acquires DAO { - if (exists(dao_address)){ - let dao = borrow_global(dao_address); - dao.id - }else{ - 0 - } - } -} \ No newline at end of file diff --git a/release/v12/sources/Dao.move b/release/v12/sources/Dao.move deleted file mode 100644 index 426db892..00000000 --- a/release/v12/sources/Dao.move +++ /dev/null @@ -1,1073 +0,0 @@ -address StarcoinFramework { -module Dao { - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Option; - use StarcoinFramework::Config; - use StarcoinFramework::Event; - use StarcoinFramework::Errors; - use StarcoinFramework::Treasury; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// Proposal state - const PENDING: u8 = 1; - const ACTIVE: u8 = 2; - const DEFEATED: u8 = 3; - const AGREED: u8 = 4; - const QUEUED: u8 = 5; - const EXECUTABLE: u8 = 6; - const EXTRACTED: u8 = 7; - - /// global DAO info of the specified token type `Token`. - struct DaoGlobalInfo has key { - /// next proposal id. - next_proposal_id: u64, - /// proposal creating event. - proposal_create_event: Event::EventHandle, - /// voting event. - vote_changed_event: Event::EventHandle, - } - - /// Configuration of the `Token`'s DAO. - struct DaoConfig has copy, drop, store { - /// after proposal created, how long use should wait before he can vote (in milliseconds) - voting_delay: u64, - /// how long the voting window is (in milliseconds). - voting_period: u64, - /// the quorum rate to agree on the proposal. - /// if 50% votes needed, then the voting_quorum_rate should be 50. - /// it should between (0, 100]. - voting_quorum_rate: u8, - /// how long the proposal should wait before it can be executed (in milliseconds). - min_action_delay: u64, - } - - spec DaoConfig { - invariant voting_quorum_rate > 0 && voting_quorum_rate <= 100; - invariant voting_delay > 0; - invariant voting_period > 0; - invariant min_action_delay > 0; - } - - /// emitted when proposal created. - struct ProposalCreatedEvent has drop, store { - /// the proposal id. - proposal_id: u64, - /// proposer is the user who create the proposal. - proposer: address, - } - - /// emitted when user vote/revoke_vote. - struct VoteChangedEvent has drop, store { - /// the proposal id. - proposal_id: u64, - /// the voter. - voter: address, - /// creator of the proposal. - proposer: address, - /// agree with the proposal or not - agree: bool, - /// latest vote count of the voter. - vote: u128, - } - - /// Proposal data struct. - struct Proposal has key { - /// id of the proposal - id: u64, - /// creator of the proposal - proposer: address, - /// when voting begins. - start_time: u64, - /// when voting ends. - end_time: u64, - /// count of voters who agree with the proposal - for_votes: u128, - /// count of voters who're against the proposal - against_votes: u128, - /// executable after this time. - eta: u64, - /// after how long, the agreed proposal can be executed. - action_delay: u64, - /// how many votes to reach to make the proposal pass. - quorum_votes: u128, - /// proposal action. - action: Option::Option, - } - - /// User vote info. - struct Vote has key { - /// vote for the proposal under the `proposer`. - proposer: address, - /// proposal id. - id: u64, - /// how many tokens to stake. - stake: Token::Token, - /// vote for or vote against. - agree: bool, - } - - const ERR_NOT_AUTHORIZED: u64 = 1401; - const ERR_ACTION_DELAY_TOO_SMALL: u64 = 1402; - const ERR_PROPOSAL_STATE_INVALID: u64 = 1403; - const ERR_PROPOSAL_ID_MISMATCH: u64 = 1404; - const ERR_PROPOSER_MISMATCH: u64 = 1405; - const ERR_QUORUM_RATE_INVALID: u64 = 1406; - const ERR_CONFIG_PARAM_INVALID: u64 = 1407; - const ERR_VOTE_STATE_MISMATCH: u64 = 1408; - const ERR_ACTION_MUST_EXIST: u64 = 1409; - const ERR_VOTED_OTHERS_ALREADY: u64 = 1410; - - /// plugin function, can only be called by token issuer. - /// Any token who wants to have gov functionality - /// can optin this module by call this `register function`. - public fun plugin( - signer: &signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - ) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - // let proposal_id = ProposalId {next: 0}; - let gov_info = DaoGlobalInfo { - next_proposal_id: 0, - proposal_create_event: Event::new_event_handle(signer), - vote_changed_event: Event::new_event_handle(signer), - }; - move_to(signer, gov_info); - let config = new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - ); - Config::publish_new_config(signer, config); - } - - spec plugin { - let sender = Signer::address_of(signer); - aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS(); - - include NewDaoConfigParamSchema; - - include Config::PublishNewConfigAbortsIf>{account: signer}; - - aborts_if exists>(sender); - } - - spec schema RequirePluginDao { - let token_addr = Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if !exists>(token_addr); - aborts_if !exists>>(token_addr); - } - spec schema AbortIfDaoInfoNotExist { - let token_addr = Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if !exists>(token_addr); - } - spec schema AbortIfDaoConfigNotExist { - let token_addr = Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if !exists>>(token_addr); - } - spec schema AbortIfTimestampNotExist { - use StarcoinFramework::CoreAddresses; - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - spec module { - apply - AbortIfDaoInfoNotExist - to - generate_next_proposal_id; - - apply - AbortIfDaoConfigNotExist - to - get_config, - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - quorum_votes; - } - - /// create a dao config - public fun new_dao_config( - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - ): DaoConfig { - assert!(voting_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - assert!(voting_period > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - assert!( - voting_quorum_rate > 0 && voting_quorum_rate <= 100, - Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID), - ); - assert!(min_action_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - DaoConfig { voting_delay, voting_period, voting_quorum_rate, min_action_delay } - } - - spec new_dao_config { - include NewDaoConfigParamSchema; - } - - spec schema NewDaoConfigParamSchema { - voting_delay: u64; - voting_period: u64; - voting_quorum_rate: u8; - min_action_delay: u64; - - aborts_if voting_delay == 0; - aborts_if voting_period == 0; - aborts_if voting_quorum_rate == 0 || voting_quorum_rate > 100; - aborts_if min_action_delay == 0; - } - - /// propose a proposal. - /// `action`: the actual action to execute. - /// `action_delay`: the delay to execute after the proposal is agreed - public fun propose( - signer: &signer, - action: ActionT, - action_delay: u64, - ) acquires DaoGlobalInfo { - if (action_delay == 0) { - action_delay = min_action_delay(); - } else { - assert!(action_delay >= min_action_delay(), Errors::invalid_argument(ERR_ACTION_DELAY_TOO_SMALL)); - }; - let proposal_id = generate_next_proposal_id(); - let proposer = Signer::address_of(signer); - let start_time = Timestamp::now_milliseconds() + voting_delay(); - let quorum_votes = quorum_votes(); - let proposal = Proposal { - id: proposal_id, - proposer, - start_time, - end_time: start_time + voting_period(), - for_votes: 0, - against_votes: 0, - eta: 0, - action_delay, - quorum_votes, - action: Option::some(action), - }; - move_to(signer, proposal); - // emit event - let gov_info = borrow_global_mut>(Token::token_address()); - Event::emit_event( - &mut gov_info.proposal_create_event, - ProposalCreatedEvent { proposal_id, proposer }, - ); - } - - spec propose { - use StarcoinFramework::CoreAddresses; - pragma verify = false; - let proposer = Signer::address_of(signer); - - include GenerateNextProposalIdSchema; - - pragma addition_overflow_unchecked = true; // start_time calculation - - include AbortIfDaoConfigNotExist; - include AbortIfDaoInfoNotExist; - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - - aborts_if action_delay > 0 && action_delay < spec_dao_config().min_action_delay; - include CheckQuorumVotes; - - let sender = Signer::address_of(signer); - aborts_if exists>(sender); - modifies global>(Token::SPEC_TOKEN_TEST_ADDRESS()); - - ensures exists>(sender); - } - - /// votes for a proposal. - /// User can only vote once, then the stake is locked, - /// which can only be unstaked by user after the proposal is expired, or cancelled, or executed. - /// So think twice before casting vote. - public fun cast_vote( - signer: &signer, - proposer_address: address, - proposal_id: u64, - stake: Token::Token, - agree: bool, - ) acquires Proposal, DaoGlobalInfo, Vote { - { - let state = proposal_state(proposer_address, proposal_id); - // only when proposal is active, use can cast vote. - assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - }; - let proposal = borrow_global_mut>(proposer_address); - assert!(proposal.id == proposal_id, Errors::invalid_argument(ERR_PROPOSAL_ID_MISMATCH)); - let sender = Signer::address_of(signer); - let total_voted = if (exists>(sender)) { - let my_vote = borrow_global_mut>(sender); - assert!(my_vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY)); - assert!(my_vote.agree == agree, Errors::invalid_state(ERR_VOTE_STATE_MISMATCH)); - - do_cast_vote(proposal, my_vote, stake); - Token::value(&my_vote.stake) - } else { - let my_vote = Vote { - proposer: proposer_address, - id: proposal_id, - stake: Token::zero(), - agree, - }; - do_cast_vote(proposal, &mut my_vote, stake); - let total_voted = Token::value(&my_vote.stake); - move_to(signer, my_vote); - total_voted - }; - - // emit event - let gov_info = borrow_global_mut>(Token::token_address()); - Event::emit_event( - &mut gov_info.vote_changed_event, - VoteChangedEvent { - proposal_id, - proposer: proposer_address, - voter: sender, - agree, - vote: total_voted, - }, - ); - } - - spec schema CheckVoteOnCast { - proposal_id: u64; - agree: bool; - voter: address; - stake_value: u128; - let vote = global>(voter); - aborts_if vote.id != proposal_id; - aborts_if vote.agree != agree; - aborts_if vote.stake.value + stake_value > MAX_U128; - } - - spec cast_vote { - pragma addition_overflow_unchecked = true; - - include AbortIfDaoInfoNotExist; - - let expected_states = vec(ACTIVE); - include CheckProposalStates {expected_states}; - let sender = Signer::address_of(signer); - let vote_exists = exists>(sender); - include vote_exists ==> CheckVoteOnCast { - voter: sender, - proposal_id: proposal_id, - agree: agree, - stake_value: stake.value, - }; - - modifies global>(proposer_address); - ensures !vote_exists ==> global>(sender).stake.value == stake.value; - } - - fun do_cast_vote(proposal: &mut Proposal, vote: &mut Vote, stake: Token::Token) { - let stake_value = Token::value(&stake); - Token::deposit(&mut vote.stake, stake); - if (vote.agree) { - proposal.for_votes = proposal.for_votes + stake_value; - } else { - proposal.against_votes = proposal.against_votes + stake_value; - }; - } - - spec do_cast_vote { - pragma addition_overflow_unchecked = true; - aborts_if vote.stake.value + stake.value > MAX_U128; - ensures vote.stake.value == old(vote).stake.value + stake.value; - ensures vote.agree ==> old(proposal).for_votes + stake.value == proposal.for_votes; - ensures vote.agree ==> old(proposal).against_votes == proposal.against_votes; - ensures !vote.agree ==> old(proposal).against_votes + stake.value == proposal.against_votes; - ensures !vote.agree ==> old(proposal).for_votes == proposal.for_votes; - } - - - /// Let user change their vote during the voting time. - public fun change_vote( - signer: &signer, - proposer_address: address, - proposal_id: u64, - agree: bool, - ) acquires Proposal, DaoGlobalInfo, Vote { - { - let state = proposal_state(proposer_address, proposal_id); - // only when proposal is active, user can change vote. - assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - }; - let proposal = borrow_global_mut>(proposer_address); - assert!(proposal.id == proposal_id, Errors::invalid_argument(ERR_PROPOSAL_ID_MISMATCH)); - let my_vote = borrow_global_mut>(Signer::address_of(signer)); - { - assert!(my_vote.proposer == proposer_address, Errors::invalid_argument(ERR_PROPOSER_MISMATCH)); - assert!(my_vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY)); - }; - - // flip the vote - if (my_vote.agree != agree) { - let total_voted = do_flip_vote(my_vote, proposal); - // emit event - let gov_info = borrow_global_mut>(Token::token_address()); - Event::emit_event( - &mut gov_info.vote_changed_event, - VoteChangedEvent { - proposal_id, - proposer: proposer_address, - voter: Signer::address_of(signer), - agree, - vote: total_voted, - }, - ); - }; - } - spec schema CheckVoteOnProposal { - vote: Vote; - proposer_address: address; - proposal_id: u64; - - aborts_if vote.id != proposal_id; - aborts_if vote.proposer != proposer_address; - } - spec schema CheckChangeVote { - vote: Vote; - proposer_address: address; - let proposal = global>(proposer_address); - include AbortIfDaoInfoNotExist; - include CheckFlipVote {my_vote: vote, proposal}; - } - spec change_vote { - pragma verify = false; - let expected_states = vec(ACTIVE); - include CheckProposalStates{expected_states}; - - let sender = Signer::address_of(signer); - aborts_if !exists>(sender); - let vote = global>(sender); - include CheckVoteOnProposal{vote, proposer_address, proposal_id}; - include vote.agree != agree ==> CheckChangeVote{vote, proposer_address}; - - ensures vote.agree != agree ==> vote.agree == agree; - } - - fun do_flip_vote(my_vote: &mut Vote, proposal: &mut Proposal): u128 { - my_vote.agree = !my_vote.agree; - let total_voted = Token::value(&my_vote.stake); - if (my_vote.agree) { - proposal.for_votes = proposal.for_votes + total_voted; - proposal.against_votes = proposal.against_votes - total_voted; - } else { - proposal.for_votes = proposal.for_votes - total_voted; - proposal.against_votes = proposal.against_votes + total_voted; - }; - total_voted - } - spec schema CheckFlipVote { - my_vote: Vote; - proposal: Proposal; - aborts_if my_vote.agree && proposal.for_votes < my_vote.stake.value; - aborts_if my_vote.agree && proposal.against_votes + my_vote.stake.value > MAX_U128; - aborts_if !my_vote.agree && proposal.against_votes < my_vote.stake.value; - aborts_if !my_vote.agree && proposal.for_votes + my_vote.stake.value > MAX_U128; - } - - spec do_flip_vote { - include CheckFlipVote; - ensures my_vote.agree == !old(my_vote).agree; - } - - /// Revoke some voting powers from vote on `proposal_id` of `proposer_address`. - public fun revoke_vote( - signer: &signer, - proposer_address: address, - proposal_id: u64, - voting_power: u128, - ): Token::Token acquires Proposal, Vote, DaoGlobalInfo { - { - let state = proposal_state(proposer_address, proposal_id); - // only when proposal is active, user can revoke vote. - assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - }; - // get proposal - let proposal = borrow_global_mut>(proposer_address); - - // get vote - let my_vote = move_from>(Signer::address_of(signer)); - { - assert!(my_vote.proposer == proposer_address, Errors::invalid_argument(ERR_PROPOSER_MISMATCH)); - assert!(my_vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY)); - }; - // revoke vote on proposal - let reverted_stake =do_revoke_vote(proposal, &mut my_vote, voting_power); - // emit vote changed event - let gov_info = borrow_global_mut>(Token::token_address()); - Event::emit_event( - &mut gov_info.vote_changed_event, - VoteChangedEvent { - proposal_id, - proposer: proposer_address, - voter: Signer::address_of(signer), - agree: my_vote.agree, - vote: Token::value(&my_vote.stake), - }, - ); - - // if user has no stake, destroy his vote. resolve https://github.com/starcoinorg/starcoin/issues/2925. - if (Token::value(&my_vote.stake) == 0u128) { - let Vote {stake, proposer: _, id: _, agree: _} = my_vote; - Token::destroy_zero(stake); - } else { - move_to(signer, my_vote); - }; - - reverted_stake - } - - spec revoke_vote { - pragma verify = false; - include AbortIfDaoInfoNotExist; - let expected_states = vec(ACTIVE); - include CheckProposalStates {expected_states}; - let sender = Signer::address_of(signer); - - aborts_if !exists>(sender); - let vote = global>(sender); - include CheckVoteOnProposal {vote, proposer_address, proposal_id}; - include CheckRevokeVote { - vote, - proposal: global>(proposer_address), - to_revoke: voting_power, - }; - - modifies global>(sender); - modifies global>(proposer_address); - modifies global>(Token::SPEC_TOKEN_TEST_ADDRESS()); - - ensures global>(sender).stake.value + result.value == old(global>(sender)).stake.value; - ensures result.value == voting_power; - } - - fun do_revoke_vote(proposal: &mut Proposal, vote: &mut Vote, to_revoke: u128): Token::Token { - spec { - assume vote.stake.value >= to_revoke; - }; - let reverted_stake = Token::withdraw(&mut vote.stake, to_revoke); - if (vote.agree) { - proposal.for_votes = proposal.for_votes - to_revoke; - } else { - proposal.against_votes = proposal.against_votes - to_revoke; - }; - spec { - assert Token::value(reverted_stake) == to_revoke; - }; - reverted_stake - } - spec schema CheckRevokeVote { - vote: Vote; - proposal: Proposal; - to_revoke: u128; - aborts_if vote.stake.value < to_revoke; - aborts_if vote.agree && proposal.for_votes < to_revoke; - aborts_if !vote.agree && proposal.against_votes < to_revoke; - } - - spec do_revoke_vote { - include CheckRevokeVote; - ensures vote.agree ==> old(proposal).for_votes == proposal.for_votes + to_revoke; - ensures !vote.agree ==> old(proposal).against_votes == proposal.against_votes + to_revoke; - ensures result.value == to_revoke; - } - - /// Retrieve back my staked token voted for a proposal. - public fun unstake_votes( - signer: &signer, - proposer_address: address, - proposal_id: u64, - ): Token::Token acquires Proposal, Vote { - // only check state when proposal exists. - // because proposal can be destroyed after it ends in DEFEATED or EXTRACTED state. - if (proposal_exists(proposer_address, proposal_id)) { - let state = proposal_state(proposer_address, proposal_id); - // Only after vote period end, user can unstake his votes. - assert!(state > ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - }; - let Vote { proposer, id, stake, agree: _ } = move_from>( - Signer::address_of(signer), - ); - // these checks are still required. - assert!(proposer == proposer_address, Errors::requires_address(ERR_PROPOSER_MISMATCH)); - assert!(id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY)); - stake - } - - spec unstake_votes { - pragma verify = false; - let expected_states = vec(DEFEATED); - let expected_states1 = concat(expected_states,vec(AGREED)); - let expected_states2 = concat(expected_states1,vec(QUEUED)); - let expected_states3 = concat(expected_states2,vec(EXECUTABLE)); - let expected_states4 = concat(expected_states3,vec(EXTRACTED)); - aborts_if expected_states4[0] != DEFEATED; - aborts_if expected_states4[1] != AGREED; - aborts_if expected_states4[2] != QUEUED; - aborts_if expected_states4[3] != EXECUTABLE; - aborts_if expected_states4[4] != EXTRACTED; - include spec_proposal_exists(proposer_address, proposal_id) ==> - CheckProposalStates{expected_states: expected_states4}; - let sender = Signer::address_of(signer); - aborts_if !exists>(sender); - let vote = global>(sender); - include CheckVoteOnProposal{vote, proposer_address, proposal_id}; - ensures !exists>(sender); - ensures result.value == old(vote).stake.value; - } - - - /// queue agreed proposal to execute. - public(script) fun queue_proposal_action( - proposer_address: address, - proposal_id: u64, - ) acquires Proposal { - // Only agreed proposal can be submitted. - assert!( - proposal_state(proposer_address, proposal_id) == AGREED, - Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID) - ); - let proposal = borrow_global_mut>(proposer_address); - proposal.eta = Timestamp::now_milliseconds() + proposal.action_delay; - } - spec queue_proposal_action { - pragma verify = false; - let expected_states = vec(AGREED); - include CheckProposalStates{expected_states}; - - let proposal = global>(proposer_address); - aborts_if Timestamp::spec_now_millseconds() + proposal.action_delay > MAX_U64; - ensures proposal.eta >= Timestamp::spec_now_millseconds(); - } - - /// extract proposal action to execute. - public fun extract_proposal_action( - proposer_address: address, - proposal_id: u64, - ): ActionT acquires Proposal { - // Only executable proposal's action can be extracted. - assert!( - proposal_state(proposer_address, proposal_id) == EXECUTABLE, - Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID), - ); - let proposal = borrow_global_mut>(proposer_address); - let action: ActionT = Option::extract(&mut proposal.action); - action - } - spec extract_proposal_action { - pragma aborts_if_is_partial = false; - let expected_states = vec(EXECUTABLE); - include CheckProposalStates{expected_states}; - modifies global>(proposer_address); - ensures Option::is_none(global>(proposer_address).action); - } - - - /// remove terminated proposal from proposer - public(script) fun destroy_terminated_proposal( - proposer_address: address, - proposal_id: u64, - ) acquires Proposal { - let proposal_state = proposal_state(proposer_address, proposal_id); - assert!( - proposal_state == DEFEATED || proposal_state == EXTRACTED, - Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID), - ); - let Proposal { - id: _, - proposer: _, - start_time: _, - end_time: _, - for_votes: _, - against_votes: _, - eta: _, - action_delay: _, - quorum_votes: _, - action, - } = move_from>(proposer_address); - if (proposal_state == DEFEATED) { - let _ = Option::extract(&mut action); - }; - Option::destroy_none(action); - } - - spec destroy_terminated_proposal { - let expected_states = concat(vec(DEFEATED), vec(EXTRACTED)); - aborts_if len(expected_states) != 2; - aborts_if expected_states[0] != DEFEATED; - aborts_if expected_states[1] != EXTRACTED; - - aborts_if !exists>(proposer_address); - let proposal = global>(proposer_address); - aborts_if proposal.id != proposal_id; - include AbortIfTimestampNotExist; - let current_time = Timestamp::spec_now_millseconds(); - let state = do_proposal_state(proposal, current_time); - aborts_if (forall s in expected_states : s != state); - aborts_if state == DEFEATED && Option::is_none(global>(proposer_address).action); - aborts_if state == EXTRACTED && Option::is_some(global>(proposer_address).action); - modifies global>(proposer_address); - } - - /// check whether a proposal exists in `proposer_address` with id `proposal_id`. - public fun proposal_exists( - proposer_address: address, - proposal_id: u64, - ): bool acquires Proposal { - if (exists>(proposer_address)) { - let proposal = borrow_global>(proposer_address); - return proposal.id == proposal_id - }; - false - } - spec proposal_exists { - ensures exists>(proposer_address) && - borrow_global>(proposer_address).id == proposal_id ==> - result; - } - - spec fun spec_proposal_exists( - proposer_address: address, - proposal_id: u64, - ): bool { - if (exists>(proposer_address)) { - let proposal = global>(proposer_address); - proposal.id == proposal_id - } else { - false - } - } - - /// Get the proposal state. - public fun proposal_state( - proposer_address: address, - proposal_id: u64, - ): u8 acquires Proposal { - let proposal = borrow_global>(proposer_address); - assert!(proposal.id == proposal_id, Errors::invalid_argument(ERR_PROPOSAL_ID_MISMATCH)); - let current_time = Timestamp::now_milliseconds(); - do_proposal_state(proposal, current_time) - } - - spec schema CheckProposalStates { - proposer_address: address; - proposal_id: u64; - expected_states: vector; - aborts_if !exists>(proposer_address); - - let proposal = global>(proposer_address); - aborts_if proposal.id != proposal_id; - - include AbortIfTimestampNotExist; - let current_time = Timestamp::spec_now_millseconds(); - let state = do_proposal_state(proposal, current_time); - aborts_if (forall s in expected_states : s != state); - } - - spec proposal_state { - use StarcoinFramework::CoreAddresses; - include AbortIfTimestampNotExist; - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if !exists>(proposer_address); - - let proposal = global>(proposer_address); - aborts_if proposal.id != proposal_id; - } - - fun do_proposal_state( - proposal: &Proposal, - current_time: u64, - ): u8 { - if (current_time < proposal.start_time) { - // Pending - PENDING - } else if (current_time <= proposal.end_time) { - // Active - ACTIVE - } else if (proposal.for_votes <= proposal.against_votes || - proposal.for_votes < proposal.quorum_votes) { - // Defeated - DEFEATED - } else if (proposal.eta == 0) { - // Agreed. - AGREED - } else if (current_time < proposal.eta) { - // Queued, waiting to execute - QUEUED - } else if (Option::is_some(&proposal.action)) { - EXECUTABLE - } else { - EXTRACTED - } - } - - - /// get proposal's information. - /// return: (id, start_time, end_time, for_votes, against_votes). - public fun proposal_info( - proposer_address: address, - ): (u64, u64, u64, u128, u128) acquires Proposal { - let proposal = borrow_global>(proposer_address); - (proposal.id, proposal.start_time, proposal.end_time, proposal.for_votes, proposal.against_votes) - } - - spec proposal_info { - aborts_if !exists>(proposer_address); - } - - /// Get voter's vote info on proposal with `proposal_id` of `proposer_address`. - public fun vote_of( - voter: address, - proposer_address: address, - proposal_id: u64, - ): (bool, u128) acquires Vote { - let vote = borrow_global>(voter); - assert!(vote.proposer == proposer_address, Errors::requires_address(ERR_PROPOSER_MISMATCH)); - assert!(vote.id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY)); - (vote.agree, Token::value(&vote.stake)) - } - - spec vote_of { - aborts_if !exists>(voter); - let vote = global>(voter); - include CheckVoteOnProposal{vote, proposer_address, proposal_id}; - } - - /// Check whether voter has voted on proposal with `proposal_id` of `proposer_address`. - public fun has_vote( - voter: address, - proposer_address: address, - proposal_id: u64, - ): bool acquires Vote { - if (!exists>(voter)) { - return false - }; - - let vote = borrow_global>(voter); - vote.proposer == proposer_address && vote.id == proposal_id - } - - fun generate_next_proposal_id(): u64 acquires DaoGlobalInfo { - let gov_info = borrow_global_mut>(Token::token_address()); - let proposal_id = gov_info.next_proposal_id; - gov_info.next_proposal_id = proposal_id + 1; - proposal_id - } - - spec generate_next_proposal_id { - include GenerateNextProposalIdSchema; - ensures result == old(global>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id); - } - - spec schema GenerateNextProposalIdSchema { - aborts_if global>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id >= MAX_U64; - modifies global>(Token::SPEC_TOKEN_TEST_ADDRESS()); - ensures - global>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id == - old(global>(Token::SPEC_TOKEN_TEST_ADDRESS()).next_proposal_id) + 1; - } - - //// Helper functions - - //// Query functions - - /// get default voting delay of the DAO. - public fun voting_delay(): u64 { - get_config().voting_delay - } - - spec voting_delay { - aborts_if false; - } - - /// get the default voting period of the DAO. - public fun voting_period(): u64 { - get_config().voting_period - } - - spec voting_period { - aborts_if false; - } - - /// Quorum votes to make proposal pass. - public fun quorum_votes(): u128 { - let market_cap = Token::market_cap(); - let balance_in_treasury = Treasury::balance(); - let supply = market_cap - balance_in_treasury; - let rate = voting_quorum_rate(); - let rate = (rate as u128); - supply * rate / 100 - } - spec schema CheckQuorumVotes { - aborts_if Token::spec_abstract_total_value() * spec_dao_config().voting_quorum_rate > MAX_U128; - } - spec quorum_votes { - pragma verify = false; - include CheckQuorumVotes; - } - - spec fun spec_quorum_votes(): u128 { - let supply = Token::spec_abstract_total_value() - Treasury::spec_balance(); - supply * spec_dao_config().voting_quorum_rate / 100 - } - - /// Get the quorum rate in percent. - public fun voting_quorum_rate(): u8 { - get_config().voting_quorum_rate - } - - spec voting_quorum_rate { - aborts_if false; - ensures result == global>>((Token::SPEC_TOKEN_TEST_ADDRESS())).payload.voting_quorum_rate; - } - - /// Get the min_action_delay of the DAO. - public fun min_action_delay(): u64 { - get_config().min_action_delay - } - - spec min_action_delay { - aborts_if false; - ensures result == spec_dao_config().min_action_delay; - } - - fun get_config(): DaoConfig { - let token_issuer = Token::token_address(); - Config::get_by_address>(token_issuer) - } - - spec get_config { - aborts_if false; - ensures result == global>>(Token::SPEC_TOKEN_TEST_ADDRESS()).payload; - } - - - spec fun spec_dao_config(): DaoConfig { - global>>((Token::SPEC_TOKEN_TEST_ADDRESS())).payload - } - - - spec schema CheckModifyConfigWithCap { - cap: Config::ModifyConfigCapability>; - aborts_if cap.account_address != Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if !exists>>(cap.account_address); - } - - /// update function, modify dao config. - /// if any param is 0, it means no change to that param. - public fun modify_dao_config( - cap: &mut Config::ModifyConfigCapability>, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - ) { - assert!(Config::account_address(cap) == Token::token_address(), Errors::invalid_argument(ERR_NOT_AUTHORIZED)); - let config = get_config(); - if (voting_period > 0) { - config.voting_period = voting_period; - }; - if (voting_delay > 0) { - config.voting_delay = voting_delay; - }; - if (voting_quorum_rate > 0) { - assert!(voting_quorum_rate <= 100, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID)); - config.voting_quorum_rate = voting_quorum_rate; - }; - if (min_action_delay > 0) { - config.min_action_delay = min_action_delay; - }; - Config::set_with_capability>(cap, config); - } - - spec modify_dao_config { - include CheckModifyConfigWithCap; - aborts_if voting_quorum_rate > 0 && voting_quorum_rate > 100; - } - - /// set voting delay - public fun set_voting_delay( - cap: &mut Config::ModifyConfigCapability>, - value: u64, - ) { - assert!(Config::account_address(cap) == Token::token_address(), Errors::invalid_argument(ERR_NOT_AUTHORIZED)); - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - let config = get_config(); - config.voting_delay = value; - Config::set_with_capability>(cap, config); - } - - spec set_voting_delay { - include CheckModifyConfigWithCap; - aborts_if value == 0; - } - - /// set voting period - public fun set_voting_period( - cap: &mut Config::ModifyConfigCapability>, - value: u64, - ) { - assert!(Config::account_address(cap) == Token::token_address(), Errors::invalid_argument(ERR_NOT_AUTHORIZED)); - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - let config = get_config(); - config.voting_period = value; - Config::set_with_capability>(cap, config); - } - - spec set_voting_period { - include CheckModifyConfigWithCap; - aborts_if value == 0; - } - - /// set voting quorum rate - public fun set_voting_quorum_rate( - cap: &mut Config::ModifyConfigCapability>, - value: u8, - ) { - assert!(Config::account_address(cap) == Token::token_address(), Errors::invalid_argument(ERR_NOT_AUTHORIZED)); - assert!(value <= 100 && value > 0, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID)); - let config = get_config(); - config.voting_quorum_rate = value; - Config::set_with_capability>(cap, config); - } - - spec set_voting_quorum_rate { - aborts_if !(value > 0 && value <= 100); - include CheckModifyConfigWithCap; - } - - /// set min action delay - public fun set_min_action_delay( - cap: &mut Config::ModifyConfigCapability>, - value: u64, - ) { - assert!(Config::account_address(cap) == Token::token_address(), Errors::invalid_argument(ERR_NOT_AUTHORIZED)); - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - let config = get_config(); - config.min_action_delay = value; - Config::set_with_capability>(cap, config); - } - spec set_min_action_delay { - aborts_if value == 0; - include CheckModifyConfigWithCap; - } -} -} diff --git a/release/v12/sources/DaoVoteScripts.move b/release/v12/sources/DaoVoteScripts.move deleted file mode 100644 index b24fdb83..00000000 --- a/release/v12/sources/DaoVoteScripts.move +++ /dev/null @@ -1,77 +0,0 @@ -address StarcoinFramework { -module DaoVoteScripts { - use StarcoinFramework::Dao; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_partial = false; - pragma aborts_if_is_strict = true; - } - - public ( script ) fun cast_vote( - signer: signer, - proposer_address: address, - proposal_id: u64, - agree: bool, - votes: u128, - ) { - let sender = Signer::address_of(&signer); - if (Dao::has_vote(sender, proposer_address, proposal_id)) { - // if already voted, and vote is not same as the current cast, change the existing vote. - // resolve https://github.com/starcoinorg/starcoin/issues/2925. - let (agree_voted, _) = Dao::vote_of(sender, proposer_address, proposal_id); - if (agree_voted != agree) { - Dao::change_vote(&signer, proposer_address, proposal_id, agree); - } - }; - - let votes = Account::withdraw(&signer, votes); - Dao::cast_vote(&signer, proposer_address, proposal_id, votes, agree); - } - - /// revoke all votes on a proposal - public ( script ) fun revoke_vote( - signer: signer, - proposer_address: address, - proposal_id: u64, - ) { - let sender = Signer::address_of(&signer); - let (_, power) = Dao::vote_of(sender, proposer_address, proposal_id); - let my_token = Dao::revoke_vote(&signer, proposer_address, proposal_id, power); - Account::deposit(sender, my_token); - } - - /// Let user change their vote during the voting time. - public(script) fun flip_vote( - signer: signer, - proposer_address: address, - proposal_id: u64, - ) { - let (agree, _) = Dao::vote_of(Signer::address_of(&signer), proposer_address, proposal_id); - Dao::change_vote(&signer, proposer_address, proposal_id, !agree); - } - - /// revoke some votes on a proposal - public ( script ) fun revoke_vote_of_power( - signer: signer, - proposer_address: address, - proposal_id: u64, - power: u128, - ) { - let sender = Signer::address_of(&signer); - let my_token = Dao::revoke_vote(&signer, proposer_address, proposal_id, power); - Account::deposit(sender, my_token); - } - - public ( script ) fun unstake_vote( - signer: signer, - proposer_address: address, - proposal_id: u64, - ) { - let my_token = Dao::unstake_votes(&signer, proposer_address, proposal_id); - Account::deposit(Signer::address_of(&signer), my_token); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/Debug.move b/release/v12/sources/Debug.move deleted file mode 100644 index 7fb0f1c2..00000000 --- a/release/v12/sources/Debug.move +++ /dev/null @@ -1,16 +0,0 @@ -address StarcoinFramework { -/// The module provide debug print for Move. -module Debug { - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// Print data of Type `T`. - native public fun print(x: &T); - - /// Print current stack. - native public fun print_stack_trace(); -} - -} diff --git a/release/v12/sources/DummyToken.move b/release/v12/sources/DummyToken.move deleted file mode 100644 index 4f6270e8..00000000 --- a/release/v12/sources/DummyToken.move +++ /dev/null @@ -1,77 +0,0 @@ -address StarcoinFramework{ -/// The module provide a dummy token implementation. -module DummyToken { - use StarcoinFramework::Token::{Self, Token}; - use StarcoinFramework::Errors; - - /// The DummyToken type. - struct DummyToken has copy, drop, store { } - - - const EMINT_TOO_MUCH:u64 = 101; - - const PRECISION: u8 = 3; - - /// Burn capability of the token. - struct SharedBurnCapability has key { - cap: Token::BurnCapability, - } - - /// Mint capability of the token. - struct SharedMintCapability has key, store { - cap: Token::MintCapability, - } - - /// Initialization of the module. - public fun initialize(account: &signer) { - Token::register_token( - account, - PRECISION, - ); - - let burn_cap = Token::remove_burn_capability(account); - move_to(account, SharedBurnCapability{cap: burn_cap}); - - let burn_cap = Token::remove_mint_capability(account); - move_to(account, SharedMintCapability{cap: burn_cap}); - } - - /// Returns true if `TokenType` is `DummyToken::DummyToken` - public fun is_dummy_token(): bool { - Token::is_same_token() - } - - /// Burn the given token. - public fun burn(token: Token) acquires SharedBurnCapability{ - let cap = borrow_global(token_address()); - Token::burn_with_capability(&cap.cap, token); - } - - /// Anyone can mint DummyToken, amount should < 10000 - public fun mint(_account: &signer, amount: u128) : Token acquires SharedMintCapability{ - assert!(amount <= 10000, Errors::invalid_argument(EMINT_TOO_MUCH)); - let cap = borrow_global(token_address()); - Token::mint_with_capability(&cap.cap, amount) - } - - /// Return the token address. - public fun token_address(): address { - Token::token_address() - } -} - -module DummyTokenScripts{ - use StarcoinFramework::DummyToken::{Self,DummyToken}; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - - public(script) fun mint(sender: signer, amount: u128){ - let token = DummyToken::mint(&sender, amount); - let sender_addr = Signer::address_of(&sender); - if(Account::is_accept_token(sender_addr)){ - Account::do_accept_token(&sender); - }; - Account::deposit(sender_addr, token); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/EmptyScripts.move b/release/v12/sources/EmptyScripts.move deleted file mode 100644 index d7bfbe5a..00000000 --- a/release/v12/sources/EmptyScripts.move +++ /dev/null @@ -1,14 +0,0 @@ -address StarcoinFramework { - // A empty scripts module for call a script but do nothing. - module EmptyScripts { - - spec module { - pragma verify = false; - pragma aborts_if_is_partial = false; - pragma aborts_if_is_strict = false; - } - - public(script) fun empty_script() { - } - } -} \ No newline at end of file diff --git a/release/v12/sources/Epoch.move b/release/v12/sources/Epoch.move deleted file mode 100644 index de12b7ea..00000000 --- a/release/v12/sources/Epoch.move +++ /dev/null @@ -1,380 +0,0 @@ -address StarcoinFramework { -/// The module provide epoch functionality for starcoin. -module Epoch { - use StarcoinFramework::Config; - use StarcoinFramework::Signer; - use StarcoinFramework::CoreAddresses; - - use StarcoinFramework::Event; - use StarcoinFramework::Errors; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Math; - use StarcoinFramework::Option; - use StarcoinFramework::ConsensusConfig::{Self, ConsensusConfig}; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// Current epoch info. - struct Epoch has key { - /// Number of current epoch - number: u64, - /// Start time of current epoch - start_time: u64, - /// Start block's number of current epoch - start_block_number: u64, - /// End block's number of current epoch - end_block_number: u64, - /// Average target time to calculate a block's difficulty in current epoch - block_time_target: u64, - /// Rewards per block in current epoch - reward_per_block: u128, - /// Percentage of `reward_per_block` to reward a uncle block in current epoch - reward_per_uncle_percent: u64, - /// How many ancestor blocks which use to calculate next block's difficulty in current epoch - block_difficulty_window: u64, - /// Maximum number of uncle block per block in current epoch - max_uncles_per_block: u64, - /// Maximum gases per block in current epoch - block_gas_limit: u64, - /// Strategy to calculate difficulty in current epoch - strategy: u8, - /// Switch Epoch Event - new_epoch_events: Event::EventHandle, - } - - /// New epoch event. - struct NewEpochEvent has drop, store { - /// Epoch::number - number: u64, - /// Epoch::start_time - start_time: u64, - /// Epoch::start_block_number - start_block_number: u64, - /// Epoch::end_block_number - end_block_number: u64, - /// Epoch::block_time_target - block_time_target: u64, - /// Epoch::reward_per_block - reward_per_block: u128, - /// Total rewards during previous epoch - previous_epoch_total_reward: u128, - } - - /// Epoch data. - struct EpochData has key { - /// Up to now, Number of uncle block during current epoch - uncles: u64, - /// Up to now, Total rewards during current epoch - total_reward: u128, - /// Up to now, Total gases during current epoch - total_gas: u128, - } - - const THOUSAND: u64 = 1000; - const THOUSAND_U128: u128 = 1000; - const HUNDRED: u64 = 100; - - const EUNREACHABLE: u64 = 19; - const EINVALID_UNCLES_COUNT: u64 = 101; - - /// Initialization of the module. - public fun initialize( - account: &signer, - ) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - - let config = ConsensusConfig::get_config(); - move_to( - account, - Epoch { - number: 0, - start_time: Timestamp::now_milliseconds(), - start_block_number: 0, - end_block_number: ConsensusConfig::epoch_block_count(&config), - block_time_target: ConsensusConfig::base_block_time_target(&config), - reward_per_block: ConsensusConfig::base_reward_per_block(&config), - reward_per_uncle_percent: ConsensusConfig::base_reward_per_uncle_percent(&config), - block_difficulty_window: ConsensusConfig::base_block_difficulty_window(&config), - max_uncles_per_block: ConsensusConfig::base_max_uncles_per_block(&config), - block_gas_limit: ConsensusConfig::base_block_gas_limit(&config), - strategy: ConsensusConfig::strategy(&config), - new_epoch_events: Event::new_event_handle(account), - }, - ); - move_to(account, EpochData { uncles: 0, total_reward: 0, total_gas: 0 }); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - - aborts_if exists(Signer::address_of(account)); - aborts_if exists(Signer::address_of(account)); - } - - /// compute next block time_target. - public fun compute_next_block_time_target(config: &ConsensusConfig, last_epoch_time_target: u64, epoch_start_time: u64, now_milli_second: u64, start_block_number: u64, end_block_number: u64, total_uncles: u64): u64 { - let total_time = now_milli_second - epoch_start_time; - let blocks = end_block_number - start_block_number; - let avg_block_time = total_time / blocks; - let uncles_rate = total_uncles * THOUSAND / blocks; - let new_epoch_block_time_target = (THOUSAND + uncles_rate) * avg_block_time / - (ConsensusConfig::uncle_rate_target(config) + THOUSAND); - if (new_epoch_block_time_target > last_epoch_time_target * 2) { - new_epoch_block_time_target = last_epoch_time_target * 2; - }; - if (new_epoch_block_time_target < last_epoch_time_target / 2) { - new_epoch_block_time_target = last_epoch_time_target / 2; - }; - let min_block_time_target = ConsensusConfig::min_block_time_target(config); - let max_block_time_target = ConsensusConfig::max_block_time_target(config); - if (new_epoch_block_time_target < min_block_time_target) { - new_epoch_block_time_target = min_block_time_target; - }; - if (new_epoch_block_time_target > max_block_time_target) { - new_epoch_block_time_target = max_block_time_target; - }; - new_epoch_block_time_target - } - - spec compute_next_block_time_target { - pragma verify = false; - } - - /// adjust_epoch try to advance to next epoch if current epoch ends. - public fun adjust_epoch(account: &signer, block_number: u64, timestamp: u64, uncles: u64, parent_gas_used:u64): u128 - acquires Epoch, EpochData { - CoreAddresses::assert_genesis_address(account); - - let epoch_ref = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - assert!(epoch_ref.max_uncles_per_block >= uncles, Errors::invalid_argument(EINVALID_UNCLES_COUNT)); - - let epoch_data = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let (new_epoch, reward_per_block) = if (block_number < epoch_ref.end_block_number) { - (false, epoch_ref.reward_per_block) - } else if (block_number == epoch_ref.end_block_number) { - //start a new epoch - assert!(uncles == 0, Errors::invalid_argument(EINVALID_UNCLES_COUNT)); - // block time target unit is milli_seconds. - let now_milli_seconds = timestamp; - - let config = ConsensusConfig::get_config(); - let last_epoch_time_target = epoch_ref.block_time_target; - let new_epoch_block_time_target = compute_next_block_time_target(&config, last_epoch_time_target, epoch_ref.start_time, now_milli_seconds, epoch_ref.start_block_number, epoch_ref.end_block_number, epoch_data.uncles); - let new_reward_per_block = ConsensusConfig::do_compute_reward_per_block(&config, new_epoch_block_time_target); - - //update epoch by adjust result or config, because ConsensusConfig may be updated. - epoch_ref.number = epoch_ref.number + 1; - epoch_ref.start_time = now_milli_seconds; - epoch_ref.start_block_number = block_number; - epoch_ref.end_block_number = block_number + ConsensusConfig::epoch_block_count(&config); - epoch_ref.block_time_target = new_epoch_block_time_target; - epoch_ref.reward_per_block = new_reward_per_block; - epoch_ref.reward_per_uncle_percent = ConsensusConfig::base_reward_per_uncle_percent(&config); - epoch_ref.block_difficulty_window = ConsensusConfig::base_block_difficulty_window(&config); - epoch_ref.max_uncles_per_block = ConsensusConfig::base_max_uncles_per_block(&config); - epoch_ref.strategy = ConsensusConfig::strategy(&config); - - epoch_data.uncles = 0; - let last_epoch_total_gas = epoch_data.total_gas + (parent_gas_used as u128); - adjust_gas_limit(&config, epoch_ref, last_epoch_time_target, new_epoch_block_time_target, last_epoch_total_gas); - emit_epoch_event(epoch_ref, epoch_data.total_reward); - (true, new_reward_per_block) - } else { - //This should never happened. - abort EUNREACHABLE - }; - let reward = reward_per_block + - reward_per_block * (epoch_ref.reward_per_uncle_percent as u128) * (uncles as u128) / (HUNDRED as u128); - update_epoch_data(epoch_data, new_epoch, reward, uncles, parent_gas_used); - reward - } - - spec adjust_epoch { - pragma verify = false; //timeout - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(Signer::address_of(account)); - aborts_if global(Signer::address_of(account)).max_uncles_per_block < uncles; - aborts_if exists(Signer::address_of(account)); - aborts_if block_number == global(Signer::address_of(account)).end_block_number && uncles != 0; - // ... - } - - fun adjust_gas_limit(config: &ConsensusConfig, epoch_ref: &mut Epoch, last_epoch_time_target: u64, new_epoch_time_target: u64, last_epoch_total_gas:u128) { - let new_gas_limit = compute_gas_limit(config, last_epoch_time_target, new_epoch_time_target, epoch_ref.block_gas_limit, last_epoch_total_gas); - if (Option::is_some(&new_gas_limit)) { - epoch_ref.block_gas_limit = Option::destroy_some(new_gas_limit); - } - } - - spec adjust_gas_limit { - pragma verify = false; //mul_div() timeout - } - - /// Compute block's gas limit of next epoch. - public fun compute_gas_limit(config: &ConsensusConfig, last_epoch_time_target: u64, new_epoch_time_target: u64, last_epoch_block_gas_limit: u64, last_epoch_total_gas: u128) : Option::Option { - let epoch_block_count = (ConsensusConfig::epoch_block_count(config) as u128); - let gas_limit_threshold = (last_epoch_total_gas >= Math::mul_div((last_epoch_block_gas_limit as u128) * epoch_block_count, (80 as u128), (HUNDRED as u128))); - let new_gas_limit = Option::none(); - - let min_block_time_target = ConsensusConfig::min_block_time_target(config); - let max_block_time_target = ConsensusConfig::max_block_time_target(config); - let base_block_gas_limit = ConsensusConfig::base_block_gas_limit(config); - if (last_epoch_time_target == new_epoch_time_target) { - if (new_epoch_time_target == min_block_time_target && gas_limit_threshold) { - let increase_gas_limit = in_or_decrease_gas_limit(last_epoch_block_gas_limit, 110, base_block_gas_limit); - new_gas_limit = Option::some(increase_gas_limit); - } else if (new_epoch_time_target == max_block_time_target && !gas_limit_threshold) { - let decrease_gas_limit = in_or_decrease_gas_limit(last_epoch_block_gas_limit, 90, base_block_gas_limit); - new_gas_limit = Option::some(decrease_gas_limit); - } - }; - - new_gas_limit - } - - spec compute_gas_limit { - pragma verify = false; //mul_div() timeout - } - - fun in_or_decrease_gas_limit(last_epoch_block_gas_limit: u64, percent: u64, min_block_gas_limit: u64): u64 { - let tmp_gas_limit = Math::mul_div((last_epoch_block_gas_limit as u128), (percent as u128), (HUNDRED as u128)); - let new_gas_limit = if (tmp_gas_limit > (min_block_gas_limit as u128)) { - (tmp_gas_limit as u64) - } else { - min_block_gas_limit - }; - - new_gas_limit - } - - spec in_or_decrease_gas_limit { - include Math::MulDivAbortsIf{x: last_epoch_block_gas_limit, y: percent, z: HUNDRED}; - aborts_if Math::spec_mul_div() > MAX_U64; - } - - fun update_epoch_data(epoch_data: &mut EpochData, new_epoch: bool, reward: u128, uncles: u64, parent_gas_used:u64) { - if (new_epoch) { - epoch_data.total_reward = reward; - epoch_data.uncles = uncles; - epoch_data.total_gas = 0; - } else { - epoch_data.total_reward = epoch_data.total_reward + reward; - epoch_data.uncles = epoch_data.uncles + uncles; - epoch_data.total_gas = epoch_data.total_gas + (parent_gas_used as u128); - } - } - - spec update_epoch_data { - aborts_if !new_epoch && epoch_data.total_reward + reward > MAX_U128; - aborts_if !new_epoch && epoch_data.uncles + uncles > MAX_U64; - aborts_if !new_epoch && epoch_data.total_gas + parent_gas_used > MAX_U128; - } - - fun emit_epoch_event(epoch_ref: &mut Epoch, previous_epoch_total_reward: u128) { - Event::emit_event( - &mut epoch_ref.new_epoch_events, - NewEpochEvent { - number: epoch_ref.number, - start_time: epoch_ref.start_time, - start_block_number: epoch_ref.start_block_number, - end_block_number: epoch_ref.end_block_number, - block_time_target: epoch_ref.block_time_target, - reward_per_block: epoch_ref.reward_per_block, - previous_epoch_total_reward, - }, - ); - } - - spec emit_epoch_event { - aborts_if false; - } - - /// Get start time of current epoch - public fun start_time(): u64 acquires Epoch { - let epoch_ref = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_ref.start_time - } - - spec start_time { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get uncles number of current epoch - public fun uncles(): u64 acquires EpochData { - let epoch_data = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_data.uncles - } - - spec uncles { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get total gas of current epoch - public fun total_gas(): u128 acquires EpochData { - let epoch_data = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_data.total_gas - } - - spec total_gas { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get block's gas_limit of current epoch - public fun block_gas_limit(): u64 acquires Epoch { - let epoch_ref = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_ref.block_gas_limit - } - - spec block_gas_limit { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get start block's number of current epoch - public fun start_block_number(): u64 acquires Epoch { - let epoch_ref = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_ref.start_block_number - } - - spec start_block_number { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get end block's number of current epoch - public fun end_block_number(): u64 acquires Epoch { - let epoch_ref = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_ref.end_block_number - } - - spec end_block_number { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get current epoch number - public fun number(): u64 acquires Epoch { - let epoch_ref = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_ref.number - } - - spec number { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get current block time target - public fun block_time_target(): u64 acquires Epoch { - let epoch_ref = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - epoch_ref.block_time_target - } - - spec block_time_target { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } - -} -} \ No newline at end of file diff --git a/release/v12/sources/Errors.move b/release/v12/sources/Errors.move deleted file mode 100644 index 4a181039..00000000 --- a/release/v12/sources/Errors.move +++ /dev/null @@ -1,169 +0,0 @@ -address StarcoinFramework { - -/// Module defining error codes used in Move aborts throughout the framework. -/// -/// A `u64` error code is constructed from two values: -/// -/// 1. The *error category* which is encoded in the lower 8 bits of the code. Error categories are -/// declared in this module and are globally unique across the Diem framework. There is a limited -/// fixed set of predefined categories, and the framework is guaranteed to use those consistently. -/// -/// 2. The *error reason* which is encoded in the remaining 56 bits of the code. The reason is a unique -/// number relative to the module which raised the error and can be used to obtain more information about -/// the error at hand. It is mostly used for diagnosis purposes. Error reasons may change over time as the -/// framework evolves. -/// -/// Rules to declare or use *error reason*: -/// 1. error reason is declared as const in the user module -/// 2. error reason name must start with "E", for example, const EACCOUNT_DOES_NOT_EXIST = ... -/// 3. value less than 100 is reserved for general purpose and shared by all modules -/// 4. don't change general purpose error reason value, it's co-related with error code in starcoin vm -/// 5. self-defined error reason value must be large than 100 -/// 6. error reason must be used together with error category -/// -module Errors { - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// A function to create an error from from a category and a reason. - fun make(category: u8, reason: u64): u64 { - (category as u64) + (reason << 8) - } - spec make { - pragma opaque = true; - pragma verify = false; - //ensures [concrete] result == category + (reason << 8); - aborts_if [abstract] false; - ensures [abstract] result == category; - } - - /// The system is in a state where the performed operation is not allowed. Example: call to a function only allowed - /// in genesis - const INVALID_STATE: u8 = 1; - - /// The signer of a transaction does not have the expected address for this operation. Example: a call to a function - /// which publishes a resource under a particular address. - const REQUIRES_ADDRESS: u8 = 2; - - /// The signer of a transaction does not have the expected role for this operation. Example: a call to a function - /// which requires the signer to have the role of treasury compliance. - const REQUIRES_ROLE: u8 = 3; - - /// The signer of a transaction does not have a required capability. - const REQUIRES_CAPABILITY: u8 = 4; - - /// A resource is required but not published. Example: access to non-existing resource. - const NOT_PUBLISHED: u8 = 5; - - /// Attempting to publish a resource that is already published. Example: calling an initialization function - /// twice. - const ALREADY_PUBLISHED: u8 = 6; - - /// An argument provided to an operation is invalid. Example: a signing key has the wrong format. - const INVALID_ARGUMENT: u8 = 7; - - /// A limit on an amount, e.g. a currency, is exceeded. Example: withdrawal of money after account limits window - /// is exhausted. - const LIMIT_EXCEEDED: u8 = 8; - - /// An internal error (bug) has occurred. - const INTERNAL: u8 = 10; - - /// deprecated code - const DEPRECATED: u8 = 11; - - /// A custom error category for extension points. - const CUSTOM: u8 = 255; - - /// Create an error of `invalid_state` - public fun invalid_state(reason: u64): u64 { make(INVALID_STATE, reason) } - spec invalid_state { - pragma opaque = true; - aborts_if false; - ensures result == INVALID_STATE; - } - - /// Create an error of `requires_address`. - public fun requires_address(reason: u64): u64 { make(REQUIRES_ADDRESS, reason) } - spec requires_address { - pragma opaque = true; - aborts_if false; - ensures result == REQUIRES_ADDRESS; - } - - /// Create an error of `requires_role`. - public fun requires_role(reason: u64): u64 { make(REQUIRES_ROLE, reason) } - spec requires_role { - pragma opaque = true; - aborts_if false; - ensures result == REQUIRES_ROLE; - } - - /// Create an error of `requires_capability`. - public fun requires_capability(reason: u64): u64 { make(REQUIRES_CAPABILITY, reason) } - spec requires_capability { - pragma opaque = true; - aborts_if false; - ensures result == REQUIRES_CAPABILITY; - } - - /// Create an error of `not_published`. - public fun not_published(reason: u64): u64 { make(NOT_PUBLISHED, reason) } - spec not_published { - pragma opaque = true; - aborts_if false; - ensures result == NOT_PUBLISHED; - } - - /// Create an error of `already_published`. - public fun already_published(reason: u64): u64 { make(ALREADY_PUBLISHED, reason) } - spec already_published { - pragma opaque = true; - aborts_if false; - ensures result == ALREADY_PUBLISHED; - } - - /// Create an error of `invalid_argument`. - public fun invalid_argument(reason: u64): u64 { make(INVALID_ARGUMENT, reason) } - spec invalid_argument { - pragma opaque = true; - aborts_if false; - ensures result == INVALID_ARGUMENT; - } - - /// Create an error of `limit_exceeded`. - public fun limit_exceeded(reason: u64): u64 { make(LIMIT_EXCEEDED, reason) } - spec limit_exceeded { - pragma opaque = true; - aborts_if false; - ensures result == LIMIT_EXCEEDED; - } - - /// Create an error of `internal`. - public fun internal(reason: u64): u64 { make(INTERNAL, reason) } - spec internal { - pragma opaque = true; - aborts_if false; - ensures result == INTERNAL; - } - - /// Create an error of `deprecated`. - public fun deprecated(reason: u64): u64 { make(DEPRECATED, reason) } - spec deprecated { - pragma opaque = true; - aborts_if false; - ensures result == DEPRECATED; - } - - /// Create an error of `custom`. - public fun custom(reason: u64): u64 { make(CUSTOM, reason) } - spec custom { - pragma opaque = true; - aborts_if false; - ensures result == CUSTOM; - } -} - -} diff --git a/release/v12/sources/Event.move b/release/v12/sources/Event.move deleted file mode 100644 index 69fedeac..00000000 --- a/release/v12/sources/Event.move +++ /dev/null @@ -1,95 +0,0 @@ -address StarcoinFramework { - -/// The Event module defines an `EventHandleGenerator` that is used to create -/// `EventHandle`s with unique GUIDs. It contains a counter for the number -/// of `EventHandle`s it generates. An `EventHandle` is used to count the number of -/// events emitted to a handle and emit events to the event store. -module Event { - use StarcoinFramework::Errors; - use StarcoinFramework::BCS; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - - /// A resource representing the counter used to generate uniqueness under each account. There won't be destructor for - /// this resource to guarantee the uniqueness of the generated handle. - struct EventHandleGenerator has key { - // A monotonically increasing counter - counter: u64, - addr: address, - } - - /// A handle for an event such that: - /// 1. Other modules can emit events to this handle. - /// 2. Storage can use this handle to prove the total number of events that happened in the past. - struct EventHandle has store { - /// Total number of events emitted to this event stream. - counter: u64, - /// A globally unique ID for this event stream. - guid: vector, - } - - /// The event generator resource was in an invalid state - const EEVENT_GENERATOR: u64 = 0; - - /// Publishs a new event handle generator. - public fun publish_generator(account: &signer) { - let addr = Signer::address_of(account); - assert!(!exists(addr), Errors::already_published(EEVENT_GENERATOR)); - move_to(account, EventHandleGenerator{ counter: 0, addr }) - } - - /// Derive a fresh unique id by using sender's EventHandleGenerator. The generated vector is indeed unique because it - /// was derived from the hash(sender's EventHandleGenerator || sender_address). This module guarantees that the - /// EventHandleGenerator is only going to be monotonically increased and there's no way to revert it or destroy it. Thus - /// such counter is going to give distinct value for each of the new event stream under each sender. And since we - /// hash it with the sender's address, the result is guaranteed to be globally unique. - fun fresh_guid(counter: &mut EventHandleGenerator): vector { - let sender_bytes = BCS::to_bytes(&counter.addr); - let count_bytes = BCS::to_bytes(&counter.counter); - counter.counter = counter.counter + 1; - - // EventHandleGenerator goes first just in case we want to extend address in the future. - Vector::append(&mut count_bytes, sender_bytes); - - count_bytes - } - - /// Use EventHandleGenerator to generate a unique event handle for `sig` - public fun new_event_handle(account: &signer): EventHandle - acquires EventHandleGenerator { - let addr = Signer::address_of(account); - assert!(exists(addr), Errors::not_published(EEVENT_GENERATOR)); - EventHandle { - counter: 0, - guid: fresh_guid(borrow_global_mut(addr)) - } - } - - /// Emit an event with payload `msg` by using `handle_ref`'s key and counter. - public fun emit_event(handle_ref: &mut EventHandle, msg: T) { - let guid = *&handle_ref.guid; - - write_to_event_store(guid, handle_ref.counter, msg); - handle_ref.counter = handle_ref.counter + 1; - } - - /// Native procedure that writes to the actual event stream in Event store - /// This will replace the "native" portion of EmitEvent bytecode - native fun write_to_event_store(guid: vector, count: u64, msg: T); - - /// Destroy a unique handle. - public fun destroy_handle(handle: EventHandle) { - EventHandle { counter: _, guid: _ } = handle; - } - - // ****************** SPECIFICATIONS ******************* - spec module {} // switch documentation context to module - - spec module { - /// Functions of the event module are mocked out using the intrinsic - /// pragma. They are implemented in the prover's prelude. - pragma intrinsic = true; - } -} - -} diff --git a/release/v12/sources/EventUtil.move b/release/v12/sources/EventUtil.move deleted file mode 100644 index 1ecfceb5..00000000 --- a/release/v12/sources/EventUtil.move +++ /dev/null @@ -1,36 +0,0 @@ -module StarcoinFramework::EventUtil { - use StarcoinFramework::Event; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - - const ERR_INIT_REPEATE: u64 = 101; - const ERR_RESOURCE_NOT_EXISTS: u64 = 102; - - struct EventHandleWrapper has key { - handle: Event::EventHandle, - } - - public fun init_event(sender: &signer) { - let broker = Signer::address_of(sender); - assert!(!exists>(broker), Errors::invalid_state(ERR_INIT_REPEATE)); - move_to(sender, EventHandleWrapper { - handle: Event::new_event_handle(sender) - }); - } - - public fun uninit_event(sender: &signer) acquires EventHandleWrapper { - let broker = Signer::address_of(sender); - assert!(exists>(broker), Errors::invalid_state(ERR_RESOURCE_NOT_EXISTS)); - let EventHandleWrapper { handle } = move_from>(broker); - Event::destroy_handle(handle); - } - - public fun emit_event(broker: address, event: EventT) acquires EventHandleWrapper { - let event_handle = borrow_global_mut>(broker); - Event::emit_event(&mut event_handle.handle, event); - } - - public fun exist_event(broker: address): bool { - exists>(broker) - } -} diff --git a/release/v12/sources/FixedPoint32.move b/release/v12/sources/FixedPoint32.move deleted file mode 100644 index e1a4b13c..00000000 --- a/release/v12/sources/FixedPoint32.move +++ /dev/null @@ -1,156 +0,0 @@ -address StarcoinFramework { -/// The module provide operations for FixedPoint32. -module FixedPoint32 { - - use StarcoinFramework::Errors; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// Define a fixed-point numeric type with 32 fractional bits. - /// This is just a u64 integer but it is wrapped in a struct to - /// make a unique type. - struct FixedPoint32 has copy, drop, store { value: u64 } - - const MAX_U64: u128 = 18446744073709551615; - - /// The denominator provided was zero - const EDENOMINATOR: u64 = 101; - /// The quotient value would be too large to be held in a `u64` - const EDIVISION: u64 = 102; - /// The multiplied value would be too large to be held in a `u64` - const EMULTIPLICATION: u64 = 103; - /// A division by zero was encountered - const EDIVISION_BY_ZERO: u64 = 104; - /// The computed ratio when converting to a `FixedPoint32` would be unrepresentable - const ERATIO_OUT_OF_RANGE: u64 = 105; - - /// Multiply a u64 integer by a fixed-point number, truncating any - /// fractional part of the product. This will abort if the product - /// overflows. - public fun multiply_u64(val: u64, multiplier: FixedPoint32): u64 { - // 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); - // The unscaled product has 32 fractional bits (from the multiplier) - // so rescale it by shifting away the low bits. - let product = unscaled_product >> 32; - // Check whether the value is too large. - assert!(product <= MAX_U64, Errors::limit_exceeded(EMULTIPLICATION)); - (product as u64) - } - spec multiply_u64 { - /// Currently, we ignore the actual implementation of this function in verification - /// and treat it as uninterpreted, which simplifies the verification problem significantly. - /// This way we avoid the non-linear arithmetic problem presented by this function. - /// - /// Abstracting this and related functions is possible because the correctness of currency - /// conversion (where `FixedPoint32` is used for) is not relevant for the rest of the contract - /// control flow, so we can assume some arbitrary (but fixed) behavior here. - pragma opaque = true; - include MultiplyAbortsIf; - ensures result == spec_multiply_u64(val, multiplier); - } - spec schema MultiplyAbortsIf { - val: num; - multiplier: FixedPoint32; - aborts_if spec_multiply_u64(val, multiplier) > MAX_U64 with Errors::LIMIT_EXCEEDED; - } - spec fun spec_multiply_u64(val: num, multiplier: FixedPoint32): num { - (val * multiplier.value) >> 32 - } - - /// Divide a u64 integer by a fixed-point number, truncating any - /// fractional part of the quotient. This will abort if the divisor - /// is zero or if the quotient overflows. - public fun divide_u64(val: u64, divisor: FixedPoint32): u64 { - // Check for division by zero. - assert!(divisor.value != 0, Errors::invalid_argument(EDIVISION_BY_ZERO)); - // First convert to 128 bits and then shift left to - // add 32 fractional zero bits to the dividend. - let scaled_value = (val as u128) << 32; - let quotient = scaled_value / (divisor.value as u128); - // Check whether the value is too large. - assert!(quotient <= MAX_U64, Errors::limit_exceeded(EDIVISION)); - // the value may be too large, which will cause the cast to fail - // with an arithmetic error. - (quotient as u64) - } - spec divide_u64 { - /// See comment at `Self::multiply_64`. - pragma opaque = true; - include DivideAbortsIf; - ensures result == spec_divide_u64(val, divisor); - } - spec schema DivideAbortsIf { - val: num; - divisor: FixedPoint32; - aborts_if divisor.value == 0 with Errors::INVALID_ARGUMENT; - aborts_if spec_divide_u64(val, divisor) > MAX_U64 with Errors::LIMIT_EXCEEDED; - } - spec fun spec_divide_u64(val: num, divisor: FixedPoint32): num { - (val << 32) / divisor.value - } - - /// Create a fixed-point value from a rational number specified by its - /// numerator and denominator. This function is for convenience; it is also - /// perfectly fine to create a fixed-point value by directly specifying the - /// raw value. This will abort if the denominator is zero or if the ratio is - /// not in the range 2^-32 .. 2^32-1. - public fun create_from_rational(numerator: u64, denominator: u64): FixedPoint32 { - // If the denominator is zero, this will abort. - // Scale the numerator to have 64 fractional bits and the denominator - // to have 32 fractional bits, so that the quotient will have 32 - // fractional bits. - let scaled_numerator = (numerator as u128) << 64; - let scaled_denominator = (denominator as u128) << 32; - assert!(scaled_denominator != 0, Errors::invalid_argument(EDENOMINATOR)); - let quotient = scaled_numerator / scaled_denominator; - assert!(quotient != 0 || numerator == 0, Errors::invalid_argument(ERATIO_OUT_OF_RANGE)); - // Return the quotient as a fixed-point number. We first need to check whether the cast - // can succeed. - assert!(quotient <= MAX_U64, Errors::limit_exceeded(ERATIO_OUT_OF_RANGE)); - FixedPoint32 { value: (quotient as u64) } - } - spec create_from_rational { - /// See comment at `Self::multiply_64`. - pragma opaque = true; - include CreateFromRationalAbortsIf; - ensures result == spec_create_from_rational(numerator, denominator); - } - spec schema CreateFromRationalAbortsIf { - numerator: u64; - denominator: u64; - let scaled_numerator = numerator << 64; - let scaled_denominator = denominator << 32; - let quotient = scaled_numerator / scaled_denominator; - aborts_if scaled_denominator == 0 with Errors::INVALID_ARGUMENT; - aborts_if quotient == 0 && scaled_numerator != 0 with Errors::INVALID_ARGUMENT; - aborts_if quotient > MAX_U64 with Errors::LIMIT_EXCEEDED; - } - spec fun spec_create_from_rational(numerator: num, denominator: num): FixedPoint32 { - FixedPoint32{value: (numerator << 64) / (denominator << 32)} - } - - /// create a fixedpoint 32 from u64. - public fun create_from_raw_value(value: u64): FixedPoint32 { - FixedPoint32 { value } - } - spec create_from_raw_value { - pragma opaque; - aborts_if false; - ensures result.value == value; - } - - /// Accessor for the raw u64 value. Other less common operations, such as - /// adding or subtracting FixedPoint32 values, can be done using the raw - /// values directly. - public fun get_raw_value(num: FixedPoint32): u64 { - num.value - } -} - -} diff --git a/release/v12/sources/GasOracleProposalPlugin.move b/release/v12/sources/GasOracleProposalPlugin.move deleted file mode 100644 index e6e7825b..00000000 --- a/release/v12/sources/GasOracleProposalPlugin.move +++ /dev/null @@ -1,128 +0,0 @@ -module StarcoinFramework::GasOracleProposalPlugin { - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::GasOracle::STCToken; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::Option; - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::Errors; - use StarcoinFramework::PriceOracleAggregator; - use StarcoinFramework::Account; - - const ERR_PLUGIN_ORACLE_EXIST: u64 = 1001; - const ERR_PLUGIN_ORACLE_NOT_EXIST: u64 = 1002; - - const ORACLE_UPDATED_IN: u64 = 600000; - - struct GasOracleProposalPlugin has store, drop {} - - struct OracleCreateAction has store { - precision: u8 - } - - struct OracleSourceAddAction has store, drop { - source_address: address - } - - struct OracleSourceRemoveAction has store, drop { - source_address: address - } - - struct OracleSources has copy, store { - source_addresses: vector
- } - - public fun initialize(_sender: &signer) { - let witness = GasOracleProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::GasOraclePlugin", - b"The plugin for gas oracle.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://gas-oracle-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::storage_cap_type()); - caps - } - - public(script) fun create_oracle_add_proposal(sender: signer, title:vector, introduction:vector, extend: vector, action_delay: u64, source_address: address) { - let witness = GasOracleProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = OracleSourceAddAction{ - source_address - }; - DAOSpace::create_proposal(&cap, &sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public(script) fun execute_oracle_add_proposal(sender: signer, proposal_id: u64) { - let witness = GasOracleProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let OracleSourceAddAction{ source_address } = DAOSpace::execute_proposal>(&proposal_cap, &sender, proposal_id); - let storage_cap = DAOSpace::acquire_storage_cap(&witness); - let source_addresses = if (!DAOSpace::exists_in_storage>()) { - let genesis_singer= GenesisSignerCapability::get_genesis_signer(); - Account::accept_token(genesis_singer); - Vector::singleton(source_address) - }else { - let OracleSources{ source_addresses } = DAOSpace::take_from_storage>(&storage_cap); - assert!(Vector::contains(&source_addresses, &source_address) == false, Errors::invalid_state(ERR_PLUGIN_ORACLE_EXIST)); - Vector::push_back(&mut source_addresses, source_address); - source_addresses - }; - - DAOSpace::save_to_storage(&storage_cap, OracleSources{ source_addresses }); - } - - public(script) fun create_oracle_remove_proposal(sender: signer, title:vector, introduction:vector, extend: vector, action_delay: u64, source_address: address) { - let witness = GasOracleProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = OracleSourceRemoveAction{ - source_address - }; - DAOSpace::create_proposal(&cap, &sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public(script) fun execute_oracle_remove_proposal(sender: signer, proposal_id: u64) { - let witness = GasOracleProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let OracleSourceRemoveAction{ source_address } = DAOSpace::execute_proposal>(&proposal_cap, &sender, proposal_id); - let storage_cap = DAOSpace::acquire_storage_cap(&witness); - assert!(DAOSpace::exists_in_storage>(), ERR_PLUGIN_ORACLE_NOT_EXIST); - let OracleSources{ source_addresses } = DAOSpace::take_from_storage>(&storage_cap); - let (exist,index)= Vector::index_of(&source_addresses, &source_address); - assert!(exist, Errors::invalid_state(ERR_PLUGIN_ORACLE_NOT_EXIST)); - Vector::remove(&mut source_addresses,index); - DAOSpace::save_to_storage(&storage_cap, OracleSources{ source_addresses }); - } - - public fun gas_oracle_read(): u128 { - let witness = GasOracleProposalPlugin{}; - let storage_cap = DAOSpace::acquire_storage_cap(&witness); - let OracleSources{ source_addresses } = DAOSpace::copy_from_storage>(&storage_cap); - PriceOracleAggregator::latest_price_average_aggregator>(&source_addresses, ORACLE_UPDATED_IN) - } - - public fun install_plugin_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, action_delay: u64) { - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public(script) fun install_plugin_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, action_delay: u64) { - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} \ No newline at end of file diff --git a/release/v12/sources/Genesis.move b/release/v12/sources/Genesis.move deleted file mode 100644 index a704645e..00000000 --- a/release/v12/sources/Genesis.move +++ /dev/null @@ -1,497 +0,0 @@ -/// The module for init Genesis -module StarcoinFramework::Genesis { - - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Account; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::STC::{Self, STC}; - use StarcoinFramework::DummyToken; - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::ConsensusConfig; - use StarcoinFramework::VMConfig; - use StarcoinFramework::Vector; - use StarcoinFramework::Block; - use StarcoinFramework::TransactionFee; - use StarcoinFramework::BlockReward; - use StarcoinFramework::ChainId; - use StarcoinFramework::ConsensusStrategy; - use StarcoinFramework::TransactionPublishOption; - use StarcoinFramework::TransactionTimeoutConfig; - use StarcoinFramework::Epoch; - use StarcoinFramework::Version; - use StarcoinFramework::Config; - use StarcoinFramework::Option; - use StarcoinFramework::Treasury; - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::STCUSDOracle; - use StarcoinFramework::GenesisNFT; - use StarcoinFramework::StarcoinDAO; - use StarcoinFramework::TreasuryPlugin; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::AnyMemberPlugin; - use StarcoinFramework::DAOExtensionPoint; - use StarcoinFramework::ConfigProposalPlugin; - use StarcoinFramework::GrantProposalPlugin; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::MemberProposalPlugin; - use StarcoinFramework::MintProposalPlugin; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::UpgradeModulePlugin; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::LanguageVersion; - use StarcoinFramework::Errors; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_partial = false; - pragma aborts_if_is_strict = true; - } - - public(script) fun initialize( - _stdlib_version: u64, - // block reward config - _reward_delay: u64, - _pre_mine_stc_amount: u128, - _time_mint_stc_amount: u128, - _time_mint_stc_period: u64, - _parent_hash: vector, - _association_auth_key: vector, - _genesis_auth_key: vector, - _chain_id: u8, - _genesis_timestamp: u64, - //consensus config - _uncle_rate_target: u64, - _epoch_block_count: u64, - _base_block_time_target: u64, - _base_block_difficulty_window: u64, - _base_reward_per_block: u128, - _base_reward_per_uncle_percent: u64, - _min_block_time_target: u64, - _max_block_time_target: u64, - _base_max_uncles_per_block: u64, - _base_block_gas_limit: u64, - _strategy: u8, - //vm config - _script_allowed: bool, - _module_publishing_allowed: bool, - _instruction_schedule: vector, - _native_schedule: vector, - //gas constants - _global_memory_per_byte_cost: u64, - _global_memory_per_byte_write_cost: u64, - _min_transaction_gas_units: u64, - _large_transaction_cutoff: u64, - _instrinsic_gas_per_byte: u64, - _maximum_number_of_gas_units: u64, - _min_price_per_gas_unit: u64, - _max_price_per_gas_unit: u64, - _max_transaction_size_in_bytes: u64, - _gas_unit_scaling_factor: u64, - _default_account_size: u64, - // dao config - _voting_delay: u64, - _voting_period: u64, - _voting_quorum_rate: u8, - _min_action_delay: u64, - // transaction timeout config - _transaction_timeout: u64, - ) { - abort Errors::deprecated(1) - } - - public(script) fun initialize_v2( - stdlib_version: u64, - // block reward and stc config - reward_delay: u64, - total_stc_amount: u128, - pre_mine_stc_amount: u128, - time_mint_stc_amount: u128, - time_mint_stc_period: u64, - parent_hash: vector, - association_auth_key: vector, - genesis_auth_key: vector, - chain_id: u8, - genesis_timestamp: u64, - //consensus config - uncle_rate_target: u64, - epoch_block_count: u64, - base_block_time_target: u64, - base_block_difficulty_window: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - //vm config - script_allowed: bool, - module_publishing_allowed: bool, - instruction_schedule: vector, - native_schedule: vector, - //gas constants - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - // dao config - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - // transaction timeout config - transaction_timeout: u64, - ) { - Self::do_initialize( - stdlib_version, - reward_delay, - total_stc_amount, - pre_mine_stc_amount, - time_mint_stc_amount, - time_mint_stc_period, - parent_hash, - association_auth_key, - genesis_auth_key, - chain_id, - genesis_timestamp, - uncle_rate_target, - epoch_block_count, - base_block_time_target, - base_block_difficulty_window, - base_reward_per_block, - base_reward_per_uncle_percent, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, - script_allowed, - module_publishing_allowed, - instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size, - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - transaction_timeout, - ); - } - - fun do_initialize( - stdlib_version: u64, - // block reward and stc config - reward_delay: u64, - total_stc_amount: u128, - pre_mine_stc_amount: u128, - time_mint_stc_amount: u128, - time_mint_stc_period: u64, - parent_hash: vector, - association_auth_key: vector, - genesis_auth_key: vector, - chain_id: u8, - genesis_timestamp: u64, - //consensus config - uncle_rate_target: u64, - epoch_block_count: u64, - base_block_time_target: u64, - base_block_difficulty_window: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - //vm config - script_allowed: bool, - module_publishing_allowed: bool, - instruction_schedule: vector, - native_schedule: vector, - //gas constants - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - // dao config - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - // transaction timeout config - transaction_timeout: u64, - ) { - Timestamp::assert_genesis(); - // create genesis account - let genesis_account = Account::create_genesis_account(CoreAddresses::GENESIS_ADDRESS()); - //Init global time - Timestamp::initialize(&genesis_account, genesis_timestamp); - ChainId::initialize(&genesis_account, chain_id); - ConsensusStrategy::initialize(&genesis_account, strategy); - Block::initialize(&genesis_account, parent_hash); - TransactionPublishOption::initialize( - &genesis_account, - script_allowed, - module_publishing_allowed, - ); - // init config - VMConfig::initialize( - &genesis_account, - instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size, - ); - TransactionTimeoutConfig::initialize(&genesis_account, transaction_timeout); - ConsensusConfig::initialize( - &genesis_account, - uncle_rate_target, - epoch_block_count, - base_block_time_target, - base_block_difficulty_window, - base_reward_per_block, - base_reward_per_uncle_percent, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, - ); - Epoch::initialize(&genesis_account); - let association = Account::create_genesis_account( - CoreAddresses::ASSOCIATION_ROOT_ADDRESS(), - ); - Config::publish_new_config(&genesis_account, Version::new_version(stdlib_version)); - // stdlib use two phase upgrade strategy. - PackageTxnManager::update_module_upgrade_strategy( - &genesis_account, - PackageTxnManager::get_strategy_two_phase(), - Option::some(0u64), - ); - BlockReward::initialize(&genesis_account, reward_delay); - - // stc should be initialized after genesis_account's module upgrade strategy set and all on chain config init. - let withdraw_cap = STC::initialize_v3(&genesis_account, total_stc_amount); - Account::do_accept_token(&genesis_account); - Account::do_accept_token(&association); - - DummyToken::initialize(&genesis_account); - - if (pre_mine_stc_amount > 0) { - let stc = Treasury::withdraw_with_capability(&mut withdraw_cap, pre_mine_stc_amount); - Account::deposit(Signer::address_of(&association), stc); - }; - if (time_mint_stc_amount > 0) { - let liner_withdraw_cap = Treasury::issue_linear_withdraw_capability(&mut withdraw_cap, time_mint_stc_amount, time_mint_stc_period); - Treasury::add_linear_withdraw_capability(&association, liner_withdraw_cap); - }; - - // Lock the TreasuryWithdrawCapability to Dao - TreasuryPlugin::delegate_capability(&genesis_account, withdraw_cap); - - TransactionFee::initialize(&genesis_account); - - // only test/dev network set genesis auth key. - if (!Vector::is_empty(&genesis_auth_key)) { - let genesis_rotate_key_cap = Account::extract_key_rotation_capability(&genesis_account); - Account::rotate_authentication_key_with_capability(&genesis_rotate_key_cap, genesis_auth_key); - Account::restore_key_rotation_capability(genesis_rotate_key_cap); - }; - - let assoc_rotate_key_cap = Account::extract_key_rotation_capability(&association); - Account::rotate_authentication_key_with_capability(&assoc_rotate_key_cap, association_auth_key); - Account::restore_key_rotation_capability(assoc_rotate_key_cap); - - // v5 -> v6 - { - let cap = Account::remove_signer_capability(&genesis_account); - GenesisSignerCapability::initialize(&genesis_account, cap); - //register oracle - STCUSDOracle::register(&genesis_account); - let merkle_root = x"5969f0e8e19f8769276fb638e6060d5c02e40088f5fde70a6778dd69d659ee6d"; - let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY"; - GenesisNFT::initialize(&genesis_account, merkle_root, 1639u64, image); - }; - Config::publish_new_config(&genesis_account, LanguageVersion::new(4)); - - //v11 -> v12 - Block::checkpoints_init(); - DAORegistry::initialize(); - - DAOExtensionPoint::initialize(); - DAOPluginMarketplace::initialize(); - - AnyMemberPlugin::initialize(&genesis_account); - ConfigProposalPlugin::initialize(&genesis_account); - GrantProposalPlugin::initialize(&genesis_account); - InstallPluginProposalPlugin::initialize(&genesis_account); - MemberProposalPlugin::initialize(&genesis_account); - MintProposalPlugin::initialize(&genesis_account); - StakeToSBTPlugin::initialize(&genesis_account); - UpgradeModulePlugin::initialize(&genesis_account); - GasOracleProposalPlugin::initialize(&genesis_account); - TreasuryPlugin::initialize(&genesis_account); - - let signer_cap = Account::get_genesis_capability(); - let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(&genesis_account); - StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, voting_delay, voting_period, voting_quorum_rate, min_action_delay, 1000 * 1000 * 1000 * 1000); - - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::set_treasury_withdraw_proposal_scale(100); - - //Start time, Timestamp::is_genesis() will return false. this call should at the end of genesis init. - Timestamp::set_time_has_started(&genesis_account); - Account::release_genesis_signer(genesis_account); - Account::release_genesis_signer(association); - } - - /// Init the genesis for unit tests - public fun initialize_for_unit_tests() { - let stdlib_version: u64 = 6; - let reward_delay: u64 = 7; - let total_stc_amount: u128 = 3185136000000000000u128; - let pre_mine_stc_amount: u128 = 159256800000000000u128; - let time_mint_stc_amount: u128 = (85043130u128 * 3u128 + 74213670u128 * 3u128) * 1000000000u128; - let time_mint_stc_period: u64 = 1000000000; - - let parent_hash: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; - let association_auth_key: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; - let genesis_auth_key: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; - let chain_id: u8 = 255; - let genesis_timestamp: u64 = 0; - - //consensus config - let uncle_rate_target: u64 = 80; - let epoch_block_count: u64 = 240; - let base_block_time_target: u64 = 10000; - let base_block_difficulty_window: u64 = 24; - let base_reward_per_block: u128 = 1000000000; - let base_reward_per_uncle_percent: u64 = 10; - let min_block_time_target: u64 = 1000; - let max_block_time_target: u64 = 20000; - let base_max_uncles_per_block: u64 = 2; - let base_block_gas_limit: u64 = 500000000; - let strategy: u8 = 0; - - //vm config - let script_allowed: bool = true; - let module_publishing_allowed: bool = true; - //TODO init the gas table. - let instruction_schedule: vector = Vector::empty(); - let native_schedule: vector = Vector::empty(); - - //gas constants - let global_memory_per_byte_cost: u64 = 1; - let global_memory_per_byte_write_cost: u64 = 1; - let min_transaction_gas_units: u64 = 1; - let large_transaction_cutoff: u64 = 1; - let instrinsic_gas_per_byte: u64 = 1; - let maximum_number_of_gas_units: u64 = 1; - let min_price_per_gas_unit: u64 = 1; - let max_price_per_gas_unit: u64 = 10000; - let max_transaction_size_in_bytes: u64 = 1024 * 1024; - let gas_unit_scaling_factor: u64 = 1; - let default_account_size: u64 = 600; - - // dao config - let voting_delay: u64 = 1000; - let voting_period: u64 = 6000; - let voting_quorum_rate: u8 = 4; - let min_action_delay: u64 = 1000; - - // transaction timeout config - let transaction_timeout: u64 = 10000; - - Self::do_initialize( - stdlib_version, - reward_delay, - total_stc_amount, - pre_mine_stc_amount, - time_mint_stc_amount, - time_mint_stc_period, - parent_hash, - association_auth_key, - genesis_auth_key, - chain_id, - genesis_timestamp, - uncle_rate_target, - epoch_block_count, - base_block_time_target, - base_block_difficulty_window, - base_reward_per_block, - base_reward_per_uncle_percent, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, - script_allowed, - module_publishing_allowed, - instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size, - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - transaction_timeout, - ); - } -} diff --git a/release/v12/sources/GenesisNFT.move b/release/v12/sources/GenesisNFT.move deleted file mode 100644 index 6e86a397..00000000 --- a/release/v12/sources/GenesisNFT.move +++ /dev/null @@ -1,81 +0,0 @@ -module StarcoinFramework::GenesisNFT { - use StarcoinFramework::IdentifierNFT; - use StarcoinFramework::Option::Option; - use StarcoinFramework::NFT::{Self, MintCapability}; - use StarcoinFramework::MerkleNFTDistributor; - use StarcoinFramework::CoreAddresses; - - spec module { - pragma verify = false; - } - - struct GenesisNFT has store{} - struct GenesisNFTMeta has copy, store, drop{ - index: u64 - } - struct GenesisNFTInfo has key, copy, store, drop{ - merkle_root: vector, - total_supply: u64, - } - struct GenesisNFTMintCapability has key{ - cap: MintCapability - } - - public fun initialize(sender: &signer, merkle_root: vector, leafs: u64, image: vector){ - CoreAddresses::assert_genesis_address(sender); - let metadata = NFT::new_meta_with_image(b"StarcoinGenesisNFT", image, b"The starcoin genesis NFT"); - let cap = MerkleNFTDistributor::register_v2(sender, merkle_root, leafs, metadata); - move_to(sender, GenesisNFTMintCapability{cap}); - } - - public fun upgrade_to_nft_type_info_v2(sender: &signer) acquires GenesisNFTMintCapability{ - CoreAddresses::assert_genesis_address(sender); - let cap = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - NFT::upgrade_nft_type_info_from_v1_to_v2(sender, &mut cap.cap); - let nft_info = NFT::remove_compat_info(&mut cap.cap); - move_to(sender, nft_info); - } - - public(script) fun mint_entry(sender: signer, index: u64, merkle_proof:vector>) - acquires GenesisNFTMintCapability { - mint(&sender, index, merkle_proof); - } - - public fun mint(sender: &signer, index: u64, merkle_proof:vector>) - acquires GenesisNFTMintCapability { - let metadata = NFT::empty_meta(); - let cap = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let nft = MerkleNFTDistributor::mint_with_cap(sender, &mut cap.cap, CoreAddresses::GENESIS_ADDRESS(), index, metadata, GenesisNFTMeta{index}, GenesisNFT{}, merkle_proof); - IdentifierNFT::grant(&mut cap.cap, sender, nft); - } - - public fun verify(account: address, index: u64, merkle_proof: vector>): bool { - MerkleNFTDistributor::verify_proof(account, CoreAddresses::GENESIS_ADDRESS(), index, merkle_proof) - } - - public fun get_info(owner: address): Option>{ - IdentifierNFT::get_nft_info(owner) - } - - public fun is_minted(index: u64): bool { - let creator = CoreAddresses::GENESIS_ADDRESS(); - MerkleNFTDistributor::is_minted(creator, index) - } - - public fun genesis_nft_info(): GenesisNFTInfo acquires GenesisNFTInfo{ - *borrow_global(CoreAddresses::GENESIS_ADDRESS()) - } -} - -module StarcoinFramework::GenesisNFTScripts { - use StarcoinFramework::GenesisNFT; - - spec module { - pragma verify = false; - } - - /// Mint a GenesisNFT - public(script) fun mint(sender: signer, index: u64, merkle_proof:vector>) { - GenesisNFT::mint_entry(sender, index, merkle_proof); - } -} diff --git a/release/v12/sources/GenesisSignerCapability.move b/release/v12/sources/GenesisSignerCapability.move deleted file mode 100644 index 20efb65a..00000000 --- a/release/v12/sources/GenesisSignerCapability.move +++ /dev/null @@ -1,37 +0,0 @@ -module StarcoinFramework::GenesisSignerCapability { - use StarcoinFramework::Account; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - - friend StarcoinFramework::NFT; - friend StarcoinFramework::Oracle; - friend StarcoinFramework::Genesis; - friend StarcoinFramework::StdlibUpgradeScripts; - friend StarcoinFramework::DAORegistry; - friend StarcoinFramework::DAOExtensionPoint; - friend StarcoinFramework::DAOPluginMarketplace; - friend StarcoinFramework::Block; - friend StarcoinFramework::DAOAccount; - - friend StarcoinFramework::GasOracleProposalPlugin; - - const ENOT_GENESIS_ACCOUNT: u64 = 11; - - struct GenesisSignerCapability has key { - cap: Account::SignerCapability, - } - - public(friend) fun initialize(signer: &signer, cap: Account::SignerCapability) { - CoreAddresses::assert_genesis_address(signer); - assert!( - Account::signer_address(&cap) == CoreAddresses::GENESIS_ADDRESS(), - Errors::invalid_argument(ENOT_GENESIS_ACCOUNT) - ); - move_to(signer, GenesisSignerCapability{cap}); - } - - public(friend) fun get_genesis_signer(): signer acquires GenesisSignerCapability { - let cap = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - Account::create_signer_with_cap(&cap.cap) - } -} \ No newline at end of file diff --git a/release/v12/sources/GrantProposalPlugin.move b/release/v12/sources/GrantProposalPlugin.move deleted file mode 100644 index 8160dd35..00000000 --- a/release/v12/sources/GrantProposalPlugin.move +++ /dev/null @@ -1,123 +0,0 @@ -module StarcoinFramework::GrantProposalPlugin{ - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct GrantProposalPlugin has store, drop{} - - struct GrantCreateAction has store, drop { - grantee: address, - total: u128, - start_time:u64, - period:u64 - } - - struct GrantConfigAction has store, drop { - old_grantee: address, - new_grantee:address, - total: u128, - start_time:u64, - period:u64 - } - - struct GrantRevokeAction has store, drop { - grantee:address - } - - public fun initialize(_sender: &signer) { - let witness = GrantProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::GrantProposalPlugin", - b"The plugin for grant proposal", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://grant-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::grant_cap_type()); - caps - } - - const ERR_GRANTTREASURY_WITHDRAW_NOT_GRANTEE :u64 = 101; - const ERR_GRANTTREASURY_WITHDRAW_TOO_MORE :u64 = 102; - const ERR_SENDER_NOT_SAME :u64 = 103; - - public fun create_grant_proposal(sender: &signer, title:vector, introduction:vector, extend: vector,grantee: address, total: u128, start_time:u64, period: u64, action_delay:u64){ - let witness = GrantProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = GrantCreateAction{ - grantee:grantee, - total:total, - start_time:start_time, - period:period - }; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_grant_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector,grantee: address, total: u128, start_time:u64, period: u64, action_delay:u64){ - create_grant_proposal(&sender, title, introduction, extend, grantee, total, start_time, period, action_delay); - } - - public fun execute_grant_proposal(sender: &signer, proposal_id: u64){ - let witness = GrantProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let GrantCreateAction{grantee, total, start_time, period} = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - assert!(grantee == Signer::address_of(sender),Errors::not_published(ERR_SENDER_NOT_SAME)); - let grant_cap = DAOSpace::acquire_grant_cap(&witness); - DAOSpace::grant_offer(&grant_cap, Signer::address_of(sender), total, start_time, period); - } - - public (script) fun execute_grant_proposal_entry(sender: signer, proposal_id: u64){ - execute_grant_proposal(&sender, proposal_id); - } - - public fun create_grant_revoke_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, grantee:address, action_delay:u64){ - let witness = GrantProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = GrantRevokeAction{ grantee }; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_grant_revoke_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, grantee:address, action_delay:u64){ - create_grant_revoke_proposal(&sender, title, introduction, extend, grantee, action_delay); - } - - public fun execute_grant_revoke_proposal(sender: &signer, proposal_id: u64){ - let witness = GrantProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let GrantRevokeAction{ grantee } = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - let grant_cap = DAOSpace::acquire_grant_cap(&witness); - DAOSpace::grant_revoke(&grant_cap , grantee); - } - - public (script) fun execute_grant_revoke_proposal_entry(sender: signer, proposal_id: u64){ - execute_grant_revoke_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/release/v12/sources/Hash.move b/release/v12/sources/Hash.move deleted file mode 100644 index df8d473d..00000000 --- a/release/v12/sources/Hash.move +++ /dev/null @@ -1,14 +0,0 @@ -address StarcoinFramework { -/// The module provide sha-hash functionality for Move. -module Hash { - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - native public fun sha2_256(data: vector): vector; - native public fun sha3_256(data: vector): vector; - native public fun keccak_256(data: vector): vector; - native public fun ripemd160(data: vector): vector; -} - -} diff --git a/release/v12/sources/InstallPluginProposalPlugin.move b/release/v12/sources/InstallPluginProposalPlugin.move deleted file mode 100644 index 6302cb5f..00000000 --- a/release/v12/sources/InstallPluginProposalPlugin.move +++ /dev/null @@ -1,68 +0,0 @@ -module StarcoinFramework::InstallPluginProposalPlugin{ - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - - struct InstallPluginProposalPlugin has store, drop{} - - struct InstallPluginAction has store, drop { - required_caps: vector, - } - - public fun initialize(_sender: &signer) { - let witness = InstallPluginProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::InstallPluginProposalPlugin", - b"The plugin for install plugin proposal", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://install-plugin-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type()); - caps - } - - /// Create a proposal to install a plugin. - /// We do not provide a entry function for create_proposal, because we can not use CapType as an entry function parameter, - /// every plugin should provide a entry function to create proposal to install self. - public fun create_proposal(sender: &signer, required_caps: vector, title:vector, introduction:vector, extend: vector, action_delay: u64){ - let witness = InstallPluginProposalPlugin{}; - - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = InstallPluginAction{ - required_caps, - }; - - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64){ - let witness = InstallPluginProposalPlugin{}; - - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let InstallPluginAction{required_caps} = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - - let install_plugin_cap = DAOSpace::acquire_install_plugin_cap(&witness); - DAOSpace::install_plugin(&install_plugin_cap, required_caps); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64) { - execute_proposal(&sender, proposal_id); - } -} \ No newline at end of file diff --git a/release/v12/sources/LanguageVersion.move b/release/v12/sources/LanguageVersion.move deleted file mode 100644 index 82dc1d5b..00000000 --- a/release/v12/sources/LanguageVersion.move +++ /dev/null @@ -1,22 +0,0 @@ -address StarcoinFramework { -module LanguageVersion { - struct LanguageVersion has copy, drop, store { - major: u64, - } - - public fun new(version: u64): LanguageVersion { - LanguageVersion {major: version} - } - - public fun version(version: &LanguageVersion): u64 { - version.major - } - - spec new { - pragma verify = false; - } - spec version { - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/Math.move b/release/v12/sources/Math.move deleted file mode 100644 index ccd25206..00000000 --- a/release/v12/sources/Math.move +++ /dev/null @@ -1,155 +0,0 @@ -address StarcoinFramework { -/// The module provide some improved math calculations. -module Math { - use StarcoinFramework::Vector; - - // TODO: verify the module. - spec module { - pragma verify = false; - pragma aborts_if_is_strict; - } - - const U64_MAX:u64 = 18446744073709551615; - const U128_MAX:u128 = 340282366920938463463374607431768211455; - - /// u64::MAX - public fun u64_max(): u64 { - U64_MAX - } - - /// u128::MAX - public fun u128_max(): u128 { - U128_MAX - } - - /// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) - public fun sqrt(y: u128): u64 { - if (y < 4) { - if (y == 0) { - 0u64 - } else { - 1u64 - } - } else { - let z = y; - let x = y / 2 + 1; - while (x < z) { - z = x; - x = (y / x + x) / 2; - }; - (z as u64) - } - } - - spec sqrt { - pragma opaque = true; - pragma verify = false; //while loop - aborts_if [abstract] false; - ensures [abstract] result == spec_sqrt(); - } - - /// We use an uninterpreted function to represent the result of sqrt. The actual value - /// does not matter for the verification of callers. - spec fun spec_sqrt(): u128; - - /// calculate the `y` pow of `x`. - public fun pow(x: u64, y: u64): u128 { - let result = 1u128; - let z = y; - let u = (x as u128); - while (z > 0) { - if (z % 2 == 1) { - result = (u * result as u128); - }; - u = (u * u as u128); - z = z / 2; - }; - result - } - - spec pow { - pragma opaque = true; - pragma verify = false; //while loop - aborts_if [abstract] false; - ensures [abstract] result == spec_pow(); - } - - /// We use an uninterpreted function to represent the result of pow. The actual value - /// does not matter for the verification of callers. - spec fun spec_pow(): u128; - - /// https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 - /// calculate x * y /z with as little loss of precision as possible and avoid overflow - public fun mul_div(x: u128, y: u128, z: u128): u128 { - if (y == z) { - return x - }; - if (x == z) { - return y - }; - let a = x / z; - let b = x % z; - //x = a * z + b; - let c = y / z; - let d = y % z; - //y = c * z + d; - a * c * z + a * d + b * c + b * d / z - } - - spec mul_div { - pragma opaque = true; - include MulDivAbortsIf; - aborts_if [abstract] false; - ensures [abstract] result == spec_mul_div(); - } - - spec schema MulDivAbortsIf { - x: u128; - y: u128; - z: u128; - aborts_if y != z && x > z && z == 0; - aborts_if y != z && x > z && z!=0 && x/z*y > MAX_U128; - aborts_if y != z && x <= z && z == 0; - //a * b overflow - aborts_if y != z && x <= z && x / z * (x % z) > MAX_U128; - //a * b * z overflow - aborts_if y != z && x <= z && x / z * (x % z) * z > MAX_U128; - //a * d overflow - aborts_if y != z && x <= z && x / z * (y % z) > MAX_U128; - //a * b * z + a * d overflow - aborts_if y != z && x <= z && x / z * (x % z) * z + x / z * (y % z) > MAX_U128; - //b * c overflow - aborts_if y != z && x <= z && x % z * (y / z) > MAX_U128; - //b * d overflow - aborts_if y != z && x <= z && x % z * (y % z) > MAX_U128; - //b * d / z overflow - aborts_if y != z && x <= z && x % z * (y % z) / z > MAX_U128; - //a * b * z + a * d + b * c overflow - aborts_if y != z && x <= z && x / z * (x % z) * z + x / z * (y % z) + x % z * (y / z) > MAX_U128; - //a * b * z + a * d + b * c + b * d / z overflow - aborts_if y != z && x <= z && x / z * (x % z) * z + x / z * (y % z) + x % z * (y / z) + x % z * (y % z) / z > MAX_U128; - - } - - spec fun spec_mul_div(): u128; - - /// calculate sum of nums - public fun sum(nums: &vector): u128 { - let len = Vector::length(nums); - let i = 0; - let sum = 0; - while (i < len){ - sum = sum + *Vector::borrow(nums, i); - i = i + 1; - }; - sum - } - - /// calculate average of nums - public fun avg(nums: &vector): u128{ - let len = Vector::length(nums); - let sum = sum(nums); - sum/(len as u128) - } -} -} \ No newline at end of file diff --git a/release/v12/sources/MemberProposalPlugin.move b/release/v12/sources/MemberProposalPlugin.move deleted file mode 100644 index 53e1146a..00000000 --- a/release/v12/sources/MemberProposalPlugin.move +++ /dev/null @@ -1,97 +0,0 @@ -module StarcoinFramework::MemberProposalPlugin{ - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::Errors; - - const ERR_MEMBER_EXIST:u64 = 101; - const ERR_MEMBER_OFFER_EXIST:u64 = 102; - - struct MemberProposalPlugin has store, drop{} - - struct MemberJoinAction has store, drop { - member: address, - init_sbt: u128, - image_url: vector , - image_data: vector - } - - public fun initialize(_sender: &signer) { - let witness = MemberProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::MemberProposalPlugin", - b"The plugin for member proposal", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://member-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::proposal_cap_type()); - caps - } - - public fun create_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, member: address, image_data:vector, image_url:vector, init_sbt: u128, action_delay: u64){ - let witness = MemberProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = MemberJoinAction{ - member, - init_sbt, - image_data, - image_url - }; - assert!(!DAOSpace::is_exist_member_offer(member), Errors::already_published(ERR_MEMBER_OFFER_EXIST)); - assert!(!DAOSpace::is_member(member), Errors::already_published(ERR_MEMBER_EXIST)); - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, member: address, image_data:vector, image_url:vector, init_sbt: u128, action_delay: u64){ - create_proposal(&sender, title, introduction, extend, member, image_data, image_url, init_sbt, action_delay); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64){ - let witness = MemberProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let MemberJoinAction{member, init_sbt, image_data, image_url} = DAOSpace::execute_proposal(&proposal_cap, sender, proposal_id); - let member_cap = DAOSpace::acquire_member_cap(&witness); - let op_image_data = if(Vector::length(&image_data) == 0){ - Option::none>() - }else{ - Option::some(image_data) - }; - let op_image_url = if(Vector::length(&image_url) == 0){ - Option::none>() - }else{ - Option::some(image_url) - }; - DAOSpace::issue_member_offer(&member_cap, member,op_image_data , op_image_url , init_sbt); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64){ - execute_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector,action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/release/v12/sources/MerkleNFT.move b/release/v12/sources/MerkleNFT.move deleted file mode 100644 index 959a8b3b..00000000 --- a/release/v12/sources/MerkleNFT.move +++ /dev/null @@ -1,148 +0,0 @@ -module StarcoinFramework::MerkleProof { - use StarcoinFramework::Hash; - use StarcoinFramework::Vector; - use StarcoinFramework::Compare; - - /// verify leaf node with hash of `leaf` with `proof` againest merkle `root`. - public fun verify(proof: &vector>, root: &vector, leaf: vector): bool { - let computed_hash = leaf; - let i = 0; - let proof_length = Vector::length(proof); - while (i < proof_length) { - let sibling = Vector::borrow(proof, i); - // computed_hash is left. - if (Compare::cmp_bytes( &computed_hash, sibling) < 2) { - let concated = concat(computed_hash, * sibling); - computed_hash = Hash::sha3_256(concated); - } else { - let concated = concat(*sibling, computed_hash); - computed_hash = Hash::sha3_256(concated); - }; - - i = i + 1; - }; - &computed_hash == root - } - - fun concat(v1: vector, v2: vector): vector { - Vector::append( &mut v1, v2); - v1 - } -} - -module StarcoinFramework::MerkleNFTDistributor { - use StarcoinFramework::Vector; - use StarcoinFramework::NFT::{Self, NFT, Metadata, MintCapability}; - use StarcoinFramework::Hash; - use StarcoinFramework::BCS; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::MerkleProof; - const ALREADY_MINTED: u64 = 1000; - const INVALID_PROOF: u64 = 1001; - const ERR_NO_MINT_CAPABILITY: u64 = 1002; - - struct MerkleNFTDistribution has key { - merkle_root: vector, - claimed_bitmap: vector, - } - - /// Deprecated, use `register_v2` instead. - public fun register( - signer: &signer, - merkle_root: vector, - leafs: u64, - info: Info, - meta: Metadata - ): MintCapability { - let bitmap_count = leafs / 128; - if (bitmap_count * 128 < leafs) { - bitmap_count = bitmap_count + 1; - }; - let claimed_bitmap = Vector::empty(); - let j = 0; - while (j < bitmap_count) { - Vector::push_back( &mut claimed_bitmap, 0u128); - j = j + 1; - }; - let distribution = MerkleNFTDistribution{ - merkle_root, - claimed_bitmap - }; - NFT::register(signer, info, meta); - move_to(signer, distribution); - NFT::remove_mint_capability(signer) - } - - public fun register_v2(signer: &signer, merkle_root: vector, leafs: u64, meta: Metadata): MintCapability { - let bitmap_count = leafs / 128; - if (bitmap_count * 128 < leafs) { - bitmap_count = bitmap_count + 1; - }; - let claimed_bitmap = Vector::empty(); - let j = 0; - while (j < bitmap_count) { - Vector::push_back( &mut claimed_bitmap, 0u128); - j = j + 1; - }; - let distribution = MerkleNFTDistribution{ - merkle_root, - claimed_bitmap - }; - NFT::register_v2(signer, meta); - move_to(signer, distribution); - NFT::remove_mint_capability(signer) - } - - public fun mint_with_cap(sender: &signer, cap:&mut MintCapability, creator: address, index: u64, base_meta: Metadata, type_meta: NFTMeta, body: NFTBody, merkle_proof:vector>): NFT - acquires MerkleNFTDistribution { - let addr = Signer::address_of(sender); - let distribution = borrow_global_mut>(creator); - let minted = is_minted_(distribution, index); - assert!(!minted, Errors::custom(ALREADY_MINTED)); - let leaf_data = encode_leaf(&index, &addr); - let verified = MerkleProof::verify(&merkle_proof, &distribution.merkle_root, Hash::sha3_256(leaf_data)); - assert!(verified, Errors::custom(INVALID_PROOF)); - set_minted_(distribution, index); - let nft = NFT::mint_with_cap(creator, cap, base_meta, type_meta, body); - return nft - } - - fun encode_leaf(index: &u64, account: &address): vector { - let leaf = Vector::empty(); - Vector::append(&mut leaf, BCS::to_bytes(index)); - Vector::append(&mut leaf, BCS::to_bytes(account)); - leaf - } - - fun set_minted_(distribution: &mut MerkleNFTDistribution, index: u64) { - let claimed_word_index = index / 128; - let claimed_bit_index = ((index % 128) as u8); - let word = Vector::borrow_mut(&mut distribution.claimed_bitmap, claimed_word_index); - // word | (1 << bit_index) - let mask = 1u128 << claimed_bit_index; - *word = (*word | mask); - } - - public fun verify_proof(account: address, creator: address, index: u64, merkle_proof:vector>): bool - acquires MerkleNFTDistribution { - let distribution = borrow_global_mut>(creator); - let leaf_data = encode_leaf(&index, &account); - MerkleProof::verify(&merkle_proof, &distribution.merkle_root, Hash::sha3_256(leaf_data)) - } - - public fun is_minted(creator: address, index: u64): bool - acquires MerkleNFTDistribution { - let distribution = borrow_global_mut>(creator); - is_minted_(distribution, index) - } - - fun is_minted_(distribution: &MerkleNFTDistribution, index: u64): bool { - let claimed_word_index = index / 128; - let claimed_bit_index = ((index % 128) as u8); - let word = Vector::borrow( &distribution.claimed_bitmap, claimed_word_index); - let mask = 1u128 << claimed_bit_index; - (*word & mask) == mask - } - -} diff --git a/release/v12/sources/MintDaoProposal.move b/release/v12/sources/MintDaoProposal.move deleted file mode 100644 index 18ff68cc..00000000 --- a/release/v12/sources/MintDaoProposal.move +++ /dev/null @@ -1,98 +0,0 @@ -address StarcoinFramework { -/// MintDaoProposal is a dao proposal for mint extra tokens. -module MintDaoProposal { - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - use StarcoinFramework::Dao; - use StarcoinFramework::Account; - use StarcoinFramework::Errors; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_strict; - pragma aborts_if_is_partial; - } - - /// A wrapper of Token MintCapability. - struct WrappedMintCapability has key { - cap: Token::MintCapability, - } - - /// MintToken request. - struct MintToken has copy, drop, store { - /// the receiver of minted tokens. - receiver: address, - /// how many tokens to mint. - amount: u128, - } - - const ERR_NOT_AUTHORIZED: u64 = 401; - - /// Plugin method of the module. - /// Should be called by token issuer. - public fun plugin(signer: &signer) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - let mint_cap = Token::remove_mint_capability(signer); - move_to(signer, WrappedMintCapability { cap: mint_cap }); - } - spec plugin { - pragma aborts_if_is_partial = false; - let sender = Signer::address_of(signer); - aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if !exists>(sender); - aborts_if exists>(sender); - - ensures !exists>(sender); - ensures exists>(sender); - } - - - /// Entrypoint for the proposal. - public fun propose_mint_to(signer: &signer, receiver: address, amount: u128, exec_delay: u64) { - Dao::propose( - signer, - MintToken { receiver, amount }, - exec_delay, - ); - } - spec propose_mint_to { - use StarcoinFramework::Timestamp; - use StarcoinFramework::CoreAddresses; - pragma aborts_if_is_partial = false; - - // copy from Dao::propose spec. - include Dao::AbortIfDaoConfigNotExist; - include Dao::AbortIfDaoInfoNotExist; - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config().min_action_delay; - include Dao::CheckQuorumVotes; - let sender = Signer::address_of(signer); - aborts_if exists>(sender); - } - - /// Once the proposal is agreed, anyone can call the method to make the proposal happen. - public fun execute_mint_proposal( - proposer_address: address, - proposal_id: u64, - ) acquires WrappedMintCapability { - let MintToken { receiver, amount } = Dao::extract_proposal_action( - proposer_address, - proposal_id, - ); - let cap = borrow_global>(Token::token_address()); - let tokens = Token::mint_with_capability(&cap.cap, amount); - Account::deposit(receiver, tokens); - } - - spec execute_mint_proposal { - use StarcoinFramework::Option; - pragma aborts_if_is_partial = true; - let expected_states = vec(6); - include Dao::CheckProposalStates{expected_states}; - let proposal = global>(proposer_address); - aborts_if Option::is_none(proposal.action); - aborts_if !exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/MintProposalPlugin.move b/release/v12/sources/MintProposalPlugin.move deleted file mode 100644 index 1d6a0180..00000000 --- a/release/v12/sources/MintProposalPlugin.move +++ /dev/null @@ -1,98 +0,0 @@ -module StarcoinFramework::MintProposalPlugin{ - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - - struct MintProposalPlugin has store, drop{} - - /// MintToken request. - struct MintTokenAction has copy, drop, store { - /// the receiver of minted tokens. - receiver: address, - /// how many tokens to mint. - amount: u128, - } - - public fun initialize(_sender: &signer) { - let witness = MintProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::MintProposalPlugin", - b"The plugin for minting tokens.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://mint-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::token_mint_cap_type()); - caps - } - - const ERR_NOT_RECEIVER :u64 = 101; - const ERR_NO_MINT_CAP: u64 = 102; - - public fun delegate_token_mint_cap(sender: &signer) { - let witness = MintProposalPlugin {}; - let mint_cap = Token::remove_mint_capability(sender); - DAOSpace::delegate_token_mint_cap(mint_cap, &witness); - } - - public (script) fun delegate_token_mint_cap_entry(sender: signer) { - delegate_token_mint_cap(&sender); - } - - public fun create_mint_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, receiver: address, amount: u128, action_delay: u64){ - let witness = MintProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = MintTokenAction{ - receiver, - amount, - }; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_mint_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, receiver: address, amount: u128, action_delay: u64){ - create_mint_proposal(&sender, extend, title, introduction, receiver, amount, action_delay); - } - - public fun execute_mint_proposal(sender: &signer, proposal_id: u64){ - let witness = MintProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let MintTokenAction{receiver, amount} = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - assert!(receiver == Signer::address_of(sender),Errors::not_published(ERR_NOT_RECEIVER)); - let tokens = DAOSpace::mint_token(amount, &witness); - Account::deposit(receiver, tokens); - } - - public (script) fun execute_mint_proposal_entry(sender: signer, proposal_id: u64){ - execute_mint_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender,required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/release/v12/sources/MintScripts.move b/release/v12/sources/MintScripts.move deleted file mode 100644 index cdfb599e..00000000 --- a/release/v12/sources/MintScripts.move +++ /dev/null @@ -1,4 +0,0 @@ -address StarcoinFramework { -module MintScripts { -} -} \ No newline at end of file diff --git a/release/v12/sources/ModifyDaoConfigProposal.move b/release/v12/sources/ModifyDaoConfigProposal.move deleted file mode 100644 index c9feca3e..00000000 --- a/release/v12/sources/ModifyDaoConfigProposal.move +++ /dev/null @@ -1,139 +0,0 @@ -address StarcoinFramework { -/// A proposal module which is used to modify Token's DAO configuration. -module ModifyDaoConfigProposal { - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - use StarcoinFramework::Config; - use StarcoinFramework::Dao; - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::Dao::DaoConfig; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_strict; - pragma aborts_if_is_partial; - } - - /// A wrapper of `Config::ModifyConfigCapability>`. - struct DaoConfigModifyCapability has key { - cap: Config::ModifyConfigCapability>, - } - - const ERR_NOT_AUTHORIZED: u64 = 401; - const ERR_QUORUM_RATE_INVALID: u64 = 402; - - /// a proposal action to update dao config. - /// if any field is `0`, that means the proposal want to update. - struct DaoConfigUpdate has copy, drop, store { - /// new voting delay setting. - voting_delay: u64, - /// new voting period setting. - voting_period: u64, - /// new voting quorum rate setting. - voting_quorum_rate: u8, - /// new min action delay setting. - min_action_delay: u64, - } - - /// Plugin method of the module. - /// Should be called by token issuer. - public fun plugin(signer: &signer) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - let dao_config_modify_cap = Config::extract_modify_config_capability< - Dao::DaoConfig, - >(signer); - assert!(Config::account_address(&dao_config_modify_cap) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - let cap = DaoConfigModifyCapability { cap: dao_config_modify_cap }; - move_to(signer, cap); - } - - spec plugin { - pragma aborts_if_is_partial = false; - let sender = Signer::address_of(signer); - aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS(); - include Config::AbortsIfCapNotExist>{address: sender}; - let config_cap = Config::spec_cap>(sender); - aborts_if Option::is_none(config_cap); - aborts_if Option::borrow(config_cap).account_address != sender; - aborts_if exists>(sender); - ensures exists>(sender); - } - - /// Destroy ModifyConfigCapability - public fun destroy_modify_config_capability(sender: &signer) - acquires DaoConfigModifyCapability { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - - let DaoConfigModifyCapability {cap} = move_from>(token_issuer); - Config::destroy_modify_config_capability>(cap); - } - - spec destroy_modify_config_capability { - pragma verify = false; - } - - /// Entrypoint for the proposal. - public(script) fun propose( - signer: signer, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - exec_delay: u64, - ) { - assert!(voting_quorum_rate <= 100, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID)); - let action = DaoConfigUpdate { - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - }; - Dao::propose(&signer, action, exec_delay); - } - spec propose { - use StarcoinFramework::Timestamp; - use StarcoinFramework::CoreAddresses; - pragma aborts_if_is_partial = false; - aborts_if voting_quorum_rate > 100; - - // copy from Dao::propose spec. - include Dao::AbortIfDaoConfigNotExist; - include Dao::AbortIfDaoInfoNotExist; - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config().min_action_delay; - include Dao::CheckQuorumVotes; - let sender = Signer::address_of(signer); - aborts_if exists>(sender); - - } - /// Once the proposal is agreed, anyone can call the method to make the proposal happen. - public(script) fun execute(proposer_address: address, proposal_id: u64) - acquires DaoConfigModifyCapability { - let DaoConfigUpdate { - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - } = Dao::extract_proposal_action(proposer_address, proposal_id); - let cap = borrow_global_mut>( - Token::token_address(), - ); - Dao::modify_dao_config( - &mut cap.cap, - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - ); - } - spec execute { - pragma aborts_if_is_partial = true; - // let expected_states = vec(6); - // include Dao::CheckProposalStates{expected_states}; - aborts_if !exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/ModuleUpgradeScripts.move b/release/v12/sources/ModuleUpgradeScripts.move deleted file mode 100644 index 498f86d7..00000000 --- a/release/v12/sources/ModuleUpgradeScripts.move +++ /dev/null @@ -1,116 +0,0 @@ -address StarcoinFramework { -module ModuleUpgradeScripts { - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::Config; - use StarcoinFramework::Signer; - use StarcoinFramework::Version; - use StarcoinFramework::Option; - use StarcoinFramework::UpgradeModuleDaoProposal; - use StarcoinFramework::Errors; - - const ERR_WRONG_UPGRADE_STRATEGY: u64 = 100; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_partial = false; - pragma aborts_if_is_strict = true; - } - - public(script) fun propose_module_upgrade_v2( - signer: signer, - module_address: address, - package_hash: vector, - version: u64, - exec_delay: u64, - enforced: bool, - ) { - UpgradeModuleDaoProposal::propose_module_upgrade_v2( - &signer, - module_address, - package_hash, - version, - exec_delay, - enforced - ); - } - - ///Update `sender`'s module upgrade strategy to `strategy` - public(script) fun update_module_upgrade_strategy( - sender: signer, - strategy: u8, - ) { - // 1. check version - if (strategy == PackageTxnManager::get_strategy_two_phase()) { - if (!Config::config_exist_by_address(Signer::address_of(&sender))) { - Config::publish_new_config(&sender, Version::new_version(1)); - } - }; - - // 2. update strategy - PackageTxnManager::update_module_upgrade_strategy( - &sender, - strategy, - Option::none(), - ); - } - - /// Update `sender`'s module upgrade strategy to `strategy` with min_time_limit. - /// This can only be invoked when strategy is STRATEGY_TWO_PHASE. - public(script) fun update_module_upgrade_strategy_with_min_time( - sender: signer, - strategy: u8, - min_time_limit: u64, - ){ - // 1. check version - assert!(strategy == PackageTxnManager::get_strategy_two_phase(), Errors::invalid_argument(ERR_WRONG_UPGRADE_STRATEGY)); - // 2. update strategy - PackageTxnManager::update_module_upgrade_strategy( - &sender, - strategy, - Option::some(min_time_limit), - ); - } - - /// a alias of execute_module_upgrade_plan_propose, will deprecated in the future. - public(script) fun submit_module_upgrade_plan( - sender: signer, - proposer_address: address, - proposal_id: u64, - ) { - Self::execute_module_upgrade_plan_propose(sender, proposer_address, proposal_id); - } - - ///Execute module upgrade plan propose by submit module upgrade plan, the propose must been agreed, and anyone can execute this function. - public(script) fun execute_module_upgrade_plan_propose( - _sender: signer, - proposer_address: address, - proposal_id: u64, - ) { - UpgradeModuleDaoProposal::submit_module_upgrade_plan(proposer_address, proposal_id); - } - - spec execute_module_upgrade_plan_propose { - pragma verify = false; - } - - ///Directly submit a upgrade plan, the `sender`'s module upgrade plan must been PackageTxnManager::STRATEGY_TWO_PHASE and have UpgradePlanCapability - public(script) fun submit_upgrade_plan(sender: signer, package_hash: vector, version:u64, enforced: bool) { - PackageTxnManager::submit_upgrade_plan_v2(&sender, package_hash, version, enforced); - } - - spec submit_upgrade_plan { - pragma verify = false; - } - - ///Cancel current upgrade plan, the `sender` must have `UpgradePlanCapability`. - public(script) fun cancel_upgrade_plan( - signer: signer, - ) { - PackageTxnManager::cancel_upgrade_plan(&signer); - } - - spec cancel_upgrade_plan { - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/NFT.move b/release/v12/sources/NFT.move deleted file mode 100644 index b32f3a2e..00000000 --- a/release/v12/sources/NFT.move +++ /dev/null @@ -1,1023 +0,0 @@ -address StarcoinFramework { -/// Non-fungible token standard and implementations. -module NFT { - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Account; - use StarcoinFramework::Vector; - use StarcoinFramework::Event; - use StarcoinFramework::GenesisSignerCapability; - - const ERR_NO_MINT_CAPABILITY: u64 = 101; - const ERR_NO_BURN_CAPABILITY: u64 = 102; - const ERR_NO_UPDATE_CAPABILITY: u64 = 103; - const ERR_CANOT_EMPTY: u64 = 104; - const ERR_NFT_TYPE_ALREADY_REGISTERED: u64 = 105; - const ERR_NFT_TYPE_NO_REGISTERED: u64 = 106; - - spec module { - pragma verify = false; - } - - struct MintEvent has drop, store { - id: u64, - creator: address, - base_meta: Metadata, - type_meta: NFTMeta, - } - - struct BurnEvent has drop, store { - id: u64, - } - - /// The info of NFT type, this type is deprecated, please use NFTTypeInfoV2 - struct NFTTypeInfo has key, store { - counter: u64, - meta: Metadata, - info: NFTTypeInfoExt, - mint_events: Event::EventHandle>, - } - - /// The info of NFT type - struct NFTTypeInfoV2 has key, store { - register: address, - counter: u64, - meta: Metadata, - mint_events: Event::EventHandle>, - burn_events: Event::EventHandle>, - } - - struct NFTTypeInfoCompat has key { - info: NFTTypeInfoExt, - } - - /// Deprecated. Use `new_nft_type_info_v2` instead. - fun new_nft_type_info( - sender: &signer, - info: NFTTypeInfoExt, - meta: Metadata - ): NFTTypeInfo { - NFTTypeInfo { - counter: 0, - info, - meta, - mint_events: Event::new_event_handle>(sender), - } - } - - fun new_nft_type_info_v2(sender: &signer, meta: Metadata): NFTTypeInfoV2 { - NFTTypeInfoV2 { - register: Signer::address_of(sender), - counter: 0, - meta, - mint_events: Event::new_event_handle>(sender), - burn_events: Event::new_event_handle>(sender), - } - } - - /// Note: this function is deprecated - public fun nft_type_info_ex_info( - ): NFTTypeInfoExt acquires NFTTypeInfo, NFTTypeInfoCompat { - if (exists>(CoreAddresses::GENESIS_ADDRESS())) { - let info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - *&info.info - } else { - let info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - *&info.info - } - } - - /// Note: this function is deprecated, please use nft_type_info_counter_v2 - public fun nft_type_info_counter( - ): u64 acquires NFTTypeInfo, NFTTypeInfoV2 { - if (exists>(CoreAddresses::GENESIS_ADDRESS())) { - Self::nft_type_info_counter_v2() - } else { - let info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - *&info.counter - } - } - - public fun nft_type_info_counter_v2(): u64 acquires NFTTypeInfoV2 { - let info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - *&info.counter - } - - public fun nft_type_info_meta(): Metadata acquires NFTTypeInfoV2 { - let info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - *&info.meta - } - - public fun upgrade_nft_type_info_from_v1_to_v2( - sender: &signer, - _cap: &mut MintCapability - ) acquires NFTTypeInfo { - if (exists>(CoreAddresses::GENESIS_ADDRESS())) { - let nft_type_info = move_from>(CoreAddresses::GENESIS_ADDRESS()); - let NFTTypeInfo { counter, meta, info, mint_events } = nft_type_info; - - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - - let nft_type_info_v2 = NFTTypeInfoV2 { - register: Signer::address_of(sender), - counter, - meta, - mint_events, - burn_events: Event::new_event_handle>(sender), - }; - move_to(&genesis_account, nft_type_info_v2); - move_to(&genesis_account, NFTTypeInfoCompat { info }); - } - } - - public fun remove_compat_info( - _cap: &mut MintCapability - ): NFTTypeInfoExt acquires NFTTypeInfoCompat { - let compat_info = move_from>(CoreAddresses::GENESIS_ADDRESS()); - let NFTTypeInfoCompat{info} = compat_info; - info - } - /// deprecated. - struct GenesisSignerCapability has key { - cap: Account::SignerCapability, - } - /// The capability to mint the nft. - struct MintCapability has key, store {} - /// The Capability to burn the nft. - struct BurnCapability has key, store {} - /// The Capability to update the nft metadata. - struct UpdateCapability has key, store {} - - struct Metadata has copy, store, drop { - /// NFT name's utf8 bytes. - name: vector, - /// Image link, such as ipfs://xxxx - image: vector, - /// Image bytes data, image or image_data can not empty for both. - image_data: vector, - /// NFT description utf8 bytes. - description: vector, - } - - public fun empty_meta(): Metadata { - Metadata { - name: Vector::empty(), - image: Vector::empty(), - image_data: Vector::empty(), - description: Vector::empty(), - } - } - - public fun new_meta(name: vector, description: vector): Metadata { - Metadata { - name, - image: Vector::empty(), - image_data: Vector::empty(), - description, - } - } - - public fun new_meta_with_image(name: vector, image: vector, description: vector): Metadata { - assert!(!Vector::is_empty(&name), Errors::invalid_argument(ERR_CANOT_EMPTY)); - assert!(!Vector::is_empty(&image), Errors::invalid_argument(ERR_CANOT_EMPTY)); - Metadata { - name, - image, - image_data: Vector::empty(), - description, - } - } - - public fun new_meta_with_image_data(name: vector, image_data: vector, description: vector): Metadata { - assert!(!Vector::is_empty(&name), Errors::invalid_argument(ERR_CANOT_EMPTY)); - assert!(!Vector::is_empty(&image_data), Errors::invalid_argument(ERR_CANOT_EMPTY)); - Metadata { - name, - image: Vector::empty(), - image_data, - description, - } - } - - public fun meta_name(metadata: &Metadata): vector { - *&metadata.name - } - - public fun meta_image(metadata: &Metadata): vector { - *&metadata.image - } - - public fun meta_image_data(metadata: &Metadata): vector { - *&metadata.image_data - } - - public fun meta_description(metadata: &Metadata): vector { - *&metadata.description - } - - struct NFT has store { - /// The creator of NFT - creator: address, - /// The unique id of NFT under NFTMeta type - id: u64, - /// The metadata of NFT - base_meta: Metadata, - /// The extension metadata of NFT - type_meta: NFTMeta, - /// The body of NFT, NFT is a box for NFTBody - body: NFTBody, - } - - /// The information of NFT instance return by get_nft_info - struct NFTInfo has copy, store, drop { - id: u64, - creator: address, - base_meta: Metadata, - type_meta: NFTMeta, - } - - public fun get_info(nft: &NFT): NFTInfo { - NFTInfo { - id: nft.id, - creator: nft.creator, - base_meta: *&nft.base_meta, - type_meta: *&nft.type_meta, - } - } - - public fun unpack_info( - nft_info: NFTInfo - ): (u64, address, Metadata, NFTMeta) { - let NFTInfo { id, creator, base_meta, type_meta } = nft_info; - (id, creator, base_meta, type_meta) - } - - public fun get_id(nft: &NFT): u64 { - return nft.id - } - - public fun get_base_meta(nft: &NFT): &Metadata { - return &nft.base_meta - } - - public fun get_type_meta(nft: &NFT): &NFTMeta { - return &nft.type_meta - } - - public fun get_creator(nft: &NFT): address { - return nft.creator - } - - /// deprecated. - public fun initialize(_signer: &signer) { - } - - /// Used in v7->v8 upgrade. struct `GenesisSignerCapability` is deprecated, - /// in favor of module `StarcoinFramework::GenesisSignerCapability`. - public fun extract_signer_cap(signer: &signer): Account::SignerCapability acquires GenesisSignerCapability { - CoreAddresses::assert_genesis_address(signer); - let cap = move_from(Signer::address_of(signer)); - let GenesisSignerCapability {cap} = cap; - cap - } - - /// Register a NFT type to genesis - /// Note: this function is deprecated, please use `register_v2` - public fun register( - sender: &signer, - info: NFTTypeInfoExt, - meta: Metadata - ) acquires NFTTypeInfo { - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - let type_info = new_nft_type_info(sender, info, meta); - move_to>(&genesis_account, type_info); - let mint_cap = MintCapability {}; - - Self::upgrade_nft_type_info_from_v1_to_v2(sender, &mut mint_cap); - - move_to>(sender, mint_cap); - move_to>(sender, BurnCapability {}); - move_to>(sender, UpdateCapability {}); - } - - /// Register a NFT type to genesis - public fun register_v2(sender: &signer, meta: Metadata) { - assert!(!is_registered(), Errors::invalid_argument(ERR_NFT_TYPE_ALREADY_REGISTERED)); - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - - let type_info = new_nft_type_info_v2(sender, meta); - move_to>(&genesis_account, type_info); - move_to>(sender, MintCapability {}); - move_to>(sender, BurnCapability {}); - move_to>(sender, UpdateCapability {}); - } - - /// Check the NFTMeta is register - public fun is_registered(): bool { - exists>(CoreAddresses::GENESIS_ADDRESS()) - } - - /// deprecated. Use "is_registered" instead. - public fun is_register(): bool { - is_registered() - } - - /// Add MintCapability to `sender` - public fun add_mint_capability(sender: &signer, cap: MintCapability) { - move_to(sender, cap); - } - - /// Remove the MintCapability from `sender` - public fun remove_mint_capability( - sender: &signer - ): MintCapability acquires MintCapability { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_MINT_CAPABILITY)); - move_from>(addr) - } - - /// Destroy the MintCapability - public fun destroy_mint_capability(cap: MintCapability) { - let MintCapability {} = cap; - } - - /// Mint nft with MintCapability, `creator` will been the NFT's creator. - /// Note: this function is deprecated, please use `mint_with_cap_v2` - public fun mint_with_cap( - creator: address, - cap: &mut MintCapability, - base_meta: Metadata, - type_meta: NFTMeta, - body: NFTBody - ): NFT acquires NFTTypeInfo, NFTTypeInfoV2 { - if (exists>(CoreAddresses::GENESIS_ADDRESS())) { - mint_with_cap_v2(creator, cap, base_meta, type_meta, body) - } else { - let nft_type_info = - borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - nft_type_info.counter = nft_type_info.counter + 1; - let id = nft_type_info.counter; - let nft = NFT { - id: id, - creator, - base_meta: copy base_meta, - type_meta: copy type_meta, - body, - }; - Event::emit_event(&mut nft_type_info.mint_events, MintEvent { - id, - creator, - base_meta, - type_meta, - }); - nft - } - } - - /// Mint nft with MintCapability, `creator` will been the NFT's creator. - public fun mint_with_cap_v2( - creator: address, - _cap: &mut MintCapability, - base_meta: Metadata, - type_meta: NFTMeta, - body: NFTBody - ): NFT acquires NFTTypeInfoV2 { - let nft_type_info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - nft_type_info.counter = nft_type_info.counter + 1; - let id = nft_type_info.counter; - let nft = NFT { - id, - creator, - base_meta: copy base_meta, - type_meta: copy type_meta, - body, - }; - Event::emit_event(&mut nft_type_info.mint_events, MintEvent { - id, - creator, - base_meta, - type_meta, - }); - nft - } - - /// Mint nft, the `sender` must have MintCapability - /// Note: this function is deprecated, please use `mint_v2` - public fun mint( - sender: &signer, - base_meta: Metadata, - type_meta: NFTMeta, - body: NFTBody - ): NFT acquires NFTTypeInfo, NFTTypeInfoV2, MintCapability { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_MINT_CAPABILITY)); - let cap = borrow_global_mut>(addr); - mint_with_cap(addr, cap, base_meta, type_meta, body) - } - - /// Mint nft, the `sender` must have MintCapability - public fun mint_v2( - sender: &signer, - base_meta: Metadata, - type_meta: NFTMeta, - body: NFTBody - ): NFT acquires NFTTypeInfoV2, MintCapability { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_MINT_CAPABILITY)); - let cap = borrow_global_mut>(addr); - mint_with_cap_v2(addr, cap, base_meta, type_meta, body) - } - - /// Add BurnCapability to `sender` - public fun add_burn_capability(sender: &signer, cap: BurnCapability) { - move_to(sender, cap); - } - - /// Remove the BurnCapability from `sender` - public fun remove_burn_capability( - sender: &signer - ): BurnCapability acquires BurnCapability { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_BURN_CAPABILITY)); - move_from>(addr) - } - - /// Destroy the BurnCapability - public fun destroy_burn_capability(cap: BurnCapability) { - let BurnCapability {} = cap; - } - - /// Burn nft with BurnCapability - public fun burn_with_cap( - _cap: &mut BurnCapability, - nft: NFT - ): NFTBody acquires NFTTypeInfoV2 { - let NFT { creator: _, id: id, base_meta: _, type_meta: _, body } = nft; - // only NFTTypeInfoV2 has burn_events EventHandle - if (exists>(CoreAddresses::GENESIS_ADDRESS())) { - let nft_type_info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut nft_type_info.burn_events, BurnEvent { - id, - }); - }; - body - } - - /// Burn nft, the `sender` must have BurnCapability - public fun burn( - sender: &signer, - nft: NFT - ): NFTBody acquires NFTTypeInfoV2, BurnCapability { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_BURN_CAPABILITY)); - let cap = borrow_global_mut>(addr); - burn_with_cap(cap, nft) - } - - /// Add UpdateCapability to `sender` - public fun add_update_capability(sender: &signer, cap: UpdateCapability) { - move_to(sender, cap); - } - - /// Remove the BurnCapability from `sender` - public fun remove_update_capability( - sender: &signer - ): UpdateCapability acquires UpdateCapability { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_UPDATE_CAPABILITY)); - move_from>(addr) - } - - /// Destroy the UpdateCapability - public fun destroy_update_capability(cap: UpdateCapability) { - let UpdateCapability {} = cap; - } - - /// Update the NFTTypeInfoV2 metadata with UpdateCapability - public fun update_nft_type_info_meta_with_cap( - _cap: &mut UpdateCapability, - new_meta: Metadata - ) acquires NFTTypeInfoV2{ - let info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - info.meta = new_meta; - } - - /// Update the NFTTypeInfoV2 metadata, the `sender` must have UpdateCapability - public fun update_nft_type_info_meta( - sender: &signer, - new_meta: Metadata - ) acquires UpdateCapability, NFTTypeInfoV2 { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_UPDATE_CAPABILITY)); - let cap = borrow_global_mut>(addr); - update_nft_type_info_meta_with_cap(cap, new_meta) - } - - /// Update the nft's base_meta and type_meta with UpdateCapability - public fun update_meta_with_cap( - _cap: &mut UpdateCapability, - nft: &mut NFT, - base_meta: Metadata, type_meta: NFTMeta - ) { - nft.base_meta = base_meta; - nft.type_meta = type_meta; - } - - /// Update the nft's base_meta and type_meta, the `sender` must have UpdateCapability - public fun update_meta( - sender: &signer, - nft: &mut NFT, - base_meta: Metadata, - type_meta: NFTMeta - ) acquires UpdateCapability { - let addr = Signer::address_of(sender); - assert!(exists>(addr), Errors::requires_capability(ERR_NO_UPDATE_CAPABILITY)); - let cap = borrow_global_mut>(addr); - update_meta_with_cap(cap, nft, base_meta, type_meta) - } - - /// Borrow NFTBody ref - public fun borrow_body(nft: &NFT): &NFTBody { - &nft.body - } - - /// Borrow NFTBody mut ref for update body with UpdateCapability - public fun borrow_body_mut_with_cap( - _cap: &mut UpdateCapability, - nft: &mut NFT - ): &mut NFTBody { - &mut nft.body - } -} - -/// IdentifierNFT using NFT as identifier for an on chain account -/// The NFT can not been transfer by owner. -module IdentifierNFT { - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::NFT::{Self, NFT, MintCapability, BurnCapability, UpdateCapability}; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - - const ERR_NFT_EXISTS: u64 = 101; - const ERR_NFT_NOT_EXISTS: u64 = 102; - const ERR_NFT_NOT_ACCEPT: u64 = 103; - const ERR_BORROW_ADDR_NOT_SAME: u64 = 104; - - spec module { - pragma verify = false; - } - - struct IdentifierNFT has key { - nft: Option>, - } - - //Used when borrowing or returning NFT, note: there is no drop ability, it must be returned after borrowing - struct BorrowNFT { - nft: NFT, - addr:address - } - - /// Check the `owner` is prepared with IdentifierNFT for accept the NFT - public fun is_accept(owner: address): bool { - exists>(owner) - } - - /// Accept NFT, prepare an empty IdentifierNFT for `sender` - public(script) fun accept_entry(sender: signer) { - accept(&sender); - } - - public fun accept(sender: &signer) { - let addr = Signer::address_of(sender); - if (!is_accept(addr)) { - move_to(sender, IdentifierNFT { - nft: Option::none(), - }); - } - } - - /// Destroy the empty IdentifierNFT - public(script) fun destroy_empty_entry(sender: signer) acquires IdentifierNFT { - destroy_empty(&sender); - } - - public fun destroy_empty(sender: &signer) acquires IdentifierNFT { - let addr = Signer::address_of(sender); - if (exists>(addr)) { - let id_nft = move_from>(addr); - assert!(Option::is_none(&id_nft.nft), Errors::already_published(ERR_NFT_EXISTS)); - let IdentifierNFT { nft } = id_nft; - Option::destroy_none(nft); - } - } - - /// Grant nft as IdentifierNFT to `sender` with MintCapability, sender will auto accept the NFT. - public fun grant( - cap: &mut MintCapability, - sender: &signer, - nft: NFT - ) acquires IdentifierNFT { - Self::accept(sender); - Self::grant_to(cap, Signer::address_of(sender), nft); - } - - /// Grant nft as IdentifierNFT to `receiver` with MintCapability, the receiver should accept the NFT first. - public fun grant_to( - _cap: &mut MintCapability, - receiver: address, - nft: NFT - ) acquires IdentifierNFT { - assert!(exists>(receiver), Errors::not_published(ERR_NFT_NOT_ACCEPT)); - let id_nft = borrow_global_mut>(receiver); - assert!(Option::is_none(&id_nft.nft), Errors::already_published(ERR_NFT_EXISTS)); - Option::fill(&mut id_nft.nft, nft); - } - - /// Revoke the NFT from owner. - public fun revoke( - _cap: &mut BurnCapability, - owner: address - ): NFT acquires IdentifierNFT { - assert!(exists>(owner), Errors::not_published(ERR_NFT_NOT_EXISTS)); - let id_nft = move_from>(owner); - assert!(Option::is_some(&id_nft.nft), Errors::not_published(ERR_NFT_NOT_EXISTS)); - let IdentifierNFT { nft } = id_nft; - Option::destroy_some(nft) - } - - /// borrow_out the NFT from owner. - public fun borrow_out( - _cap: &mut UpdateCapability, - owner: address - ): BorrowNFT acquires IdentifierNFT { - assert!(exists>(owner), Errors::not_published(ERR_NFT_NOT_EXISTS)); - - let id_nft = borrow_global_mut>(owner); - assert!(Option::is_some(&id_nft.nft), Errors::not_published(ERR_NFT_NOT_EXISTS)); - - let nft = Option::extract(&mut id_nft.nft); - - BorrowNFT{ - nft : nft, - addr: owner - } - } - - /// return_back the NFT to owner. - public fun return_back( - borrownft: BorrowNFT, - ) acquires IdentifierNFT { - - let BorrowNFT{ - nft: nft, - addr: owner - } = borrownft ; - assert!(exists>(owner), Errors::not_published(ERR_NFT_NOT_EXISTS)); - let id_nft = borrow_global_mut>(owner); - - Option::fill(&mut id_nft.nft , nft) - } - - public fun borrow_nft( - borrownft:&BorrowNFT - ) : & NFT { - & borrownft.nft - } - - public fun borrow_nft_mut ( - borrownft:&mut BorrowNFT - ) : &mut NFT { - &mut borrownft.nft - } - - /// Check `owner` is owns the IdentifierNFT - public fun owns(owner: address): bool acquires IdentifierNFT { - if (!exists>(owner)) { - return false - }; - let id_nft = borrow_global>(owner); - Option::is_some(&id_nft.nft) - } - /// deprecated. Use `owns()` instead. - public fun is_owns(owner: address): bool acquires IdentifierNFT { - owns(owner) - } - - public fun get_nft_info( - owner: address - ): Option> acquires IdentifierNFT { - if (!exists>(owner)) { - return Option::none>() - }; - let id_nft = borrow_global>(owner); - let info = if (Option::is_some(&id_nft.nft)) { - let nft = Option::borrow(&id_nft.nft); - Option::some(NFT::get_info(nft)) - } else { - Option::none>() - }; - info - } -} - -module IdentifierNFTScripts { - use StarcoinFramework::IdentifierNFT; - spec module { - pragma verify = false; - } - - /// Init IdentifierNFT for accept NFT as Identifier. - public(script) fun accept(sender: signer) { - IdentifierNFT::accept_entry(sender); - } - - /// Destroy empty IdentifierNFT - public(script) fun destroy_empty(sender: signer) { - IdentifierNFT::destroy_empty_entry(sender); - } -} - -/// NFTGallery is user collection of NFT. -module NFTGallery { - use StarcoinFramework::Signer; - use StarcoinFramework::NFT::{Self, NFT}; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::Event; - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - - const ERR_NFT_NOT_EXISTS: u64 = 101; - - const ERR_NFTGALLERY_NOT_EXISTS:u64 = 102; - - spec module { - pragma verify = false; - } - - struct WithdrawEvent has drop, store { - owner: address, - id: u64, - } - - struct DepositEvent has drop, store { - owner: address, - id: u64, - } - - struct NFTGallery has key, store { - withdraw_events: Event::EventHandle>, - deposit_events: Event::EventHandle>, - items: vector>, - } - - /// Check the `owner` is prepared with NFTGallery for accept the NFT - public fun is_accept(owner: address): bool { - exists>(owner) - } - - /// Init a NFTGallery to accept NFT for `sender` - public(script) fun accept_entry(sender: signer) { - accept(&sender); - } - - public fun accept(sender: &signer) { - let sender_addr = Signer::address_of(sender); - if (!is_accept(sender_addr)) { - let gallery = NFTGallery { - withdraw_events: Event::new_event_handle>(sender), - deposit_events: Event::new_event_handle>(sender), - items: Vector::empty>(), - }; - move_to(sender, gallery); - } - } - - /// Transfer NFT from `sender` to `receiver` - public(script) fun transfer_entry( - sender: signer, - id: u64, receiver: address - ) acquires NFTGallery { - transfer(&sender, id, receiver); - } - - public fun transfer( - sender: &signer, - id: u64, - receiver: address - ) acquires NFTGallery { - let nft = withdraw(sender, id); - assert!(Option::is_some(&nft), Errors::not_published(ERR_NFT_NOT_EXISTS)); - let nft = Option::destroy_some(nft); - deposit_to(receiver, nft) - } - - /// Get the NFT info by the NFT id. - public fun get_nft_info_by_id( - owner: address, - id: u64 - ): Option> acquires NFTGallery { - if(!is_accept(owner)){ - return Option::none>() - }; - let gallery = borrow_global_mut>(owner); - let idx = find_by_id(&gallery.items, id); - - let info = if (Option::is_some(&idx)) { - let i = Option::extract(&mut idx); - let nft = Vector::borrow>(&gallery.items, i); - Option::some(NFT::get_info(nft)) - } else { - Option::none>() - }; - return info - } - - /// Get the NFT info by the NFT idx in NFTGallery - public fun get_nft_info_by_idx( - owner: address, - idx: u64 - ): NFT::NFTInfo acquires NFTGallery { - assert!(exists>(owner), Errors::not_published(ERR_NFTGALLERY_NOT_EXISTS)); - let gallery = borrow_global_mut>(owner); - let nft = Vector::borrow>(&gallery.items, idx); - NFT::get_info(nft) - } - - /// Get the all NFT info - public fun get_nft_infos( - owner: address - ): vector> acquires NFTGallery { - if(!is_accept(owner)){ - return Vector::empty>() - }; - let gallery = borrow_global_mut>(owner); - let infos = Vector::empty(); - let len = Vector::length(&gallery.items); - let idx = 0; - while (len > idx) { - let nft = Vector::borrow>(&gallery.items, idx); - Vector::push_back(&mut infos, NFT::get_info(nft)); - idx = idx + 1; - }; - infos - } - - /// Deposit nft to `sender` NFTGallery - public fun deposit( - sender: &signer, - nft: NFT - ) acquires NFTGallery { - Self::accept(sender); - let sender_addr = Signer::address_of(sender); - deposit_to(sender_addr, nft) - } - - /// Deposit nft to `receiver` NFTGallery - public fun deposit_to( - receiver: address, - nft: NFT - ) acquires NFTGallery { - assert!(exists>(receiver), Errors::not_published(ERR_NFTGALLERY_NOT_EXISTS)); - let gallery = borrow_global_mut>(receiver); - Event::emit_event(&mut gallery.deposit_events, DepositEvent { id: NFT::get_id(&nft), owner: receiver }); - Vector::push_back(&mut gallery.items, nft); - } - - /// Withdraw one nft of NFTMeta from `sender`, caller should ensure at least one NFT in the Gallery. - public fun withdraw_one( - sender: &signer - ): NFT acquires NFTGallery { - let nft = do_withdraw(sender, Option::none()); - assert!(Option::is_some(&nft), Errors::not_published(ERR_NFT_NOT_EXISTS)); - Option::destroy_some(nft) - } - - /// Withdraw nft of NFTMeta and id from `sender` - public fun withdraw( - sender: &signer, - id: u64 - ): Option> acquires NFTGallery { - do_withdraw(sender, Option::some(id)) - } - - /// Withdraw nft of NFTMeta and id from `sender` - fun do_withdraw( - sender: &signer, - id: Option - ): Option> acquires NFTGallery { - let sender_addr = Signer::address_of(sender); - if(!is_accept(sender_addr)){ - return Option::none>() - }; - let gallery = borrow_global_mut>(sender_addr); - let len = Vector::length(&gallery.items); - let nft = if (len == 0) { - Option::none() - } else { - let idx = if (Option::is_some(&id)) { - let id = Option::extract(&mut id); - find_by_id(&gallery.items, id) - } else { - //default withdraw the last nft. - Option::some(len - 1) - }; - - if (Option::is_some(&idx)) { - let i = Option::extract(&mut idx); - let nft = Vector::remove>(&mut gallery.items, i); - Event::emit_event( - &mut gallery.withdraw_events, - WithdrawEvent { id: NFT::get_id(&nft), owner: sender_addr } - ); - Option::some(nft) - } else { - Option::none() - } - }; - nft - } - - fun find_by_id( - c: &vector>, - id: u64 - ): Option { - let len = Vector::length(c); - if (len == 0) { - return Option::none() - }; - let idx = len - 1; - loop { - let nft = Vector::borrow(c, idx); - if (NFT::get_id(nft) == id) { - return Option::some(idx) - }; - if (idx == 0) { - return Option::none() - }; - idx = idx - 1; - } - } - - /// Count all NFTs assigned to an owner - public fun count_of(owner: address): u64 acquires NFTGallery { - if(!is_accept(owner)){ - return 0 - }; - let gallery = borrow_global_mut>(owner); - Vector::length(&gallery.items) - } - - /// Remove empty NFTGallery. - public(script) fun remove_empty_gallery_entry(sender: signer) acquires NFTGallery { - remove_empty_gallery(&sender); - } - - public fun remove_empty_gallery(sender: &signer) acquires NFTGallery{ - let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::not_published(ERR_NFTGALLERY_NOT_EXISTS)); - let NFTGallery {withdraw_events, deposit_events, items} = move_from>(sender_addr); - - Event::destroy_handle>(withdraw_events); - Event::destroy_handle>(deposit_events); - Vector::destroy_empty>(items); - } - - spec remove_empty_gallery { - let sender_addr = Signer::address_of(sender); - aborts_if !exists>(sender_addr); - - let gallery = global>(sender_addr); - aborts_if Vector::length>(gallery.items) > 0; - - ensures !exists>(sender_addr); - } - -} - -module NFTGalleryScripts { - use StarcoinFramework::NFTGallery; - - spec module { - pragma verify = false; - } - - /// Init a NFTGallery for accept NFT - public(script) fun accept(sender: signer) { - NFTGallery::accept_entry(sender); - } - /// Transfer NFT with `id` from `sender` to `receiver` - public(script) fun transfer( - sender: signer, - id: u64, receiver: address - ) { - NFTGallery::transfer_entry(sender, id, receiver); - } - - /// Remove empty NFTGallery. - public(script) fun remove_empty_gallery(sender: signer) { - NFTGallery::remove_empty_gallery_entry(sender); - } -} -} diff --git a/release/v12/sources/Offer.move b/release/v12/sources/Offer.move deleted file mode 100644 index 40ad8ed1..00000000 --- a/release/v12/sources/Offer.move +++ /dev/null @@ -1,360 +0,0 @@ -address StarcoinFramework { -module Offer { - use StarcoinFramework::Timestamp; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// A wrapper around value `offered` that can be claimed by the address stored in `for` when after lock time. - struct Offer has key, store { offered: Offered, for: address, time_lock: u64 } - - struct Offers has key { - offers: vector> - } - - struct OfferInfo has drop, copy, store{ - for: address, - time_lock: u64 - } - - const ERR_DEPRECATED: u64 = 1; - - /// An offer of the specified type for the account does not match - const EOFFER_DNE_FOR_ACCOUNT: u64 = 101; - - /// Offer is not unlocked yet. - const EOFFER_NOT_UNLOCKED: u64 = 102; - - const EOFFER_OFFERS_ZERO: u64 = 103; - - const EOFFER_OFFERS_ARG_LEN_NOT_SAME: u64 = 104; - - const EOFFER_NOT_HAVE_OFFER: u64 = 105; - - const EOFFER_HAVE_OFFER: u64 = 106; - - const EOFFER_OFFERS_EMPTY: u64 = 107; - - /// Publish a value of type `Offered` under the sender's account. The value can be claimed by - /// either the `for` address or the transaction sender. - public fun create(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offer, Offers{ - let time_lock = Timestamp::now_seconds() + lock_period; - let account_address = Signer::address_of(account); - if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - Vector::push_back(offers, Offer { offered, for, time_lock }); - }else { - let offers = Vector::empty>(); - if(exists>(account_address)){ - Vector::push_back(&mut offers, move_from>(account_address)); - }; - Vector::push_back(&mut offers, Offer { offered, for, time_lock }); - move_to(account, Offers { offers }); - } - } - - spec create { - include Timestamp::AbortsIfTimestampNotExists; - aborts_if Timestamp::now_seconds() + lock_period > max_u64(); - aborts_if exists>(Signer::address_of(account)); - } - - public fun create_v2(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offers, Offer{ - let account_address = Signer::address_of(account); - let time_lock = Timestamp::now_seconds() + lock_period; - - if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - Vector::push_back(offers, Offer { offered, for, time_lock }); - }else { - let offers = Vector::empty>(); - if(exists>(account_address)){ - Vector::push_back(&mut offers, move_from>(account_address)); - }; - Vector::push_back(&mut offers, Offer { offered, for, time_lock }); - move_to(account, Offers { offers }); - }; - } - - spec create_v2 { - pragma verify = false; - } - - public fun create_offers(account: &signer, offereds: vector, for: vector
, lock_periods: vector) acquires Offers, Offer { - let offer_length = Vector::length(&offereds); - assert!(offer_length > 0, Errors::invalid_argument(EOFFER_OFFERS_ZERO)); - assert!(offer_length == Vector::length(&for) && offer_length == Vector::length(&lock_periods), Errors::invalid_argument(EOFFER_OFFERS_ARG_LEN_NOT_SAME)); - let account_address = Signer::address_of(account); - - if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - push(offers, offereds, for, lock_periods); - }else { - let offers = Vector::empty>(); - if(exists>(account_address)){ - Vector::push_back(&mut offers, move_from>(account_address)); - }; - push(&mut offers, offereds, for, lock_periods); - move_to(account, Offers { offers }); - }; - } - - spec create_offers { - pragma verify = false; - } - - fun push(offers: &mut vector>, offereds: vector, for: vector
, lock_periods: vector){ - let now = Timestamp::now_seconds(); - let offer_length = Vector::length(&offereds); - - let i = offer_length - 1; - loop{ - Vector::push_back(offers, Offer { - offered: Vector::remove(&mut offereds, i), - for: Vector::remove(&mut for, i), - time_lock: now + Vector::remove(&mut lock_periods, i) - }); - if(i == 0){ - break - }; - i = i - 1; - }; - Vector::destroy_empty(offereds); - Vector::destroy_empty(for); - Vector::destroy_empty(lock_periods); - } - - spec push { - pragma verify = false; - } - - /// Claim the value of type `Offered` published at `offer_address`. - /// Only succeeds if the sender is the intended recipient stored in `for` or the original - /// publisher `offer_address`, and now >= time_lock - /// Also fails if no such value exists. - public fun redeem(account: &signer, offer_address: address): Offered acquires Offer, Offers { - let account_address = Signer::address_of(account); - let Offer { offered, for, time_lock } = if(exists>(offer_address)){ - let op_index = find_offer(offer_address, account_address); - assert!(Option::is_some(&op_index),Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT)); - let offers = &mut borrow_global_mut>(offer_address).offers; - let index = Option::destroy_some(op_index); - let offer = Vector::remove(offers , index); - if(Vector::length(offers) == 0){ - let Offers { offers } = move_from>(offer_address); - Vector::destroy_empty(offers); - }; - offer - }else if(exists>(offer_address)){ - move_from>(offer_address) - }else{ - abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER) - }; - - let now = Timestamp::now_seconds(); - assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT)); - assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED)); - offered - } - - spec redeem { - aborts_if !exists>(offer_address); - aborts_if Signer::address_of(account) != global>(offer_address).for && Signer::address_of(account) != offer_address; - aborts_if Timestamp::now_seconds() < global>(offer_address).time_lock; - include Timestamp::AbortsIfTimestampNotExists; - } - - public fun redeem_v2(account: &signer, offer_address: address, idx: u64): Offered acquires Offer, Offers { - let account_address = Signer::address_of(account); - let Offer { offered, for, time_lock } = if(exists>(offer_address)){ - let offers = &mut borrow_global_mut>(offer_address).offers; - assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offer = Vector::remove(offers, idx); - if(Vector::length(offers) == 0){ - let Offers { offers } = move_from>(offer_address); - Vector::destroy_empty(offers); - }; - offer - }else if(exists>(offer_address)){ - move_from>(offer_address) - }else{ - abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER) - }; - - let now = Timestamp::now_seconds(); - assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT)); - assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED)); - offered - } - - spec redeem_v2 {pragma verify = false;} - - /// Returns true if an offer of type `Offered` exists at `offer_address`. - public fun exists_at(offer_address: address): bool { - exists>(offer_address) || exists>(offer_address) - } - - spec exists_at {pragma verify = false;} - - public fun exists_at_v2(offer_address: address): bool{ - exists>(offer_address) - } - - spec exists_at_v2 {pragma verify = false;} - - /// Returns the address of the `Offered` type stored at `offer_address`. - /// Fails if no such `Offer` exists. - public fun address_of(offer_address: address): address acquires Offer, Offers { - if(exists>(offer_address)){ - borrow_global>(offer_address).for - }else{ - assert!(!is_offers_empty(offer_address), Errors::invalid_argument(EOFFER_OFFERS_EMPTY)); - address_of_v2(offer_address, get_offers_length(offer_address) - 1) - } - - } - - spec address_of { - aborts_if !exists>(offer_address); - aborts_if !exists>(offer_address); - } - - public fun address_of_v2(offer_address: address, idx: u64): address acquires Offers { - assert!(exists>(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offers = & borrow_global>(offer_address).offers; - assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - Vector::borrow(offers, idx).for - } - - spec address_of_v2 { - pragma verify = false; - } - - public fun retake(account: &signer, idx: u64): Offered acquires Offer, Offers { - let account_address = Signer::address_of(account); - let Offer { offered: offered, for: _, time_lock: time_lock } = if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offer = Vector::remove(offers, idx); - if(Vector::length(offers) == 0){ - let Offers { offers } = move_from>(account_address); - Vector::destroy_empty(offers); - }; - offer - }else if(exists>(account_address)){ - move_from>(account_address) - }else{ - abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER) - }; - let now = Timestamp::now_seconds(); - assert!(now >= time_lock + ( 3600 * 24 * 30 * 3 ), Errors::not_published(EOFFER_NOT_UNLOCKED)); - offered - } - - spec retake { - pragma verify = false; - } - - public fun get_offers_infos(offer_address: address): Option::Option> acquires Offers{ - if(!exists_at_v2(offer_address)){ - return Option::none>() - }; - let offers = & borrow_global>(offer_address).offers; - let offer_infos = Vector::empty(); - let i = 0; - let length = Vector::length(offers); - while(i < length){ - Vector::push_back(&mut offer_infos, OfferInfo { for: Vector::borrow(offers, i).for, time_lock: Vector::borrow(offers, i).time_lock }); - i = i + 1; - }; - Option::some(offer_infos) - } - - spec get_offers_infos { - pragma verify = false; - } - - public fun get_offers_info(offer_address: address, idx: u64): Option::Option acquires Offers{ - if(!exists_at_v2(offer_address)){ - return Option::none() - }; - let offers = & borrow_global>(offer_address).offers; - assert!(Vector::length(offers) >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - Option::some(OfferInfo { for: Vector::borrow(offers, idx).for, time_lock: Vector::borrow(offers, idx).time_lock }) - } - - spec get_offers_info { - pragma verify = false; - } - - public fun unpack_offer_info(offer_info: OfferInfo):(address, u64){ - let OfferInfo{ for, time_lock } = offer_info; - ( for, time_lock ) - } - - spec unpack_offer_info { - pragma verify = false; - } - - public fun get_offers_length(offer_address: address): u64 acquires Offers{ - assert!(exists_at_v2(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offers = & borrow_global>(offer_address).offers; - Vector::length(offers) - } - - spec get_offers_length { - pragma verify = false; - } - - public fun is_offers_empty(offer_address: address): bool acquires Offers{ - if( get_offers_length(offer_address) == 0){ - true - }else{ - false - } - } - - spec is_offers_empty { - pragma verify = false; - } - - - /// Take Offer and put to signer's Collection. - public(script) fun take_offer(_signer: signer, _offer_address: address){ - abort Errors::invalid_state(ERR_DEPRECATED) - } - - spec take_offer { - pragma verify = false; - } - - - - public fun find_offer(offer_address: address, for: address):Option::Option acquires Offers { - if(!exists_at_v2(offer_address)){ - return Option::none() - }; - let offers = & borrow_global>(offer_address).offers; - let length = Vector::length(offers); - let i = 0; - while(i < length){ - let offer = Vector::borrow(offers, i); - if( offer.for == for ){ - return Option::some(i) - }; - i = i + 1; - }; - Option::none() - } - - spec find_offer { - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/OnChainConfigDao.move b/release/v12/sources/OnChainConfigDao.move deleted file mode 100644 index e6e1c96c..00000000 --- a/release/v12/sources/OnChainConfigDao.move +++ /dev/null @@ -1,106 +0,0 @@ -address StarcoinFramework { -/// OnChainConfigDao is a DAO proposal for modify onchain configuration. -module OnChainConfigDao { - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - use StarcoinFramework::Config; - use StarcoinFramework::Dao; - use StarcoinFramework::Errors; - use StarcoinFramework::CoreAddresses; - - friend StarcoinFramework::StdlibUpgradeScripts; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_strict; - pragma aborts_if_is_partial; - } - - /// A wrapper of `Config::ModifyConfigCapability`. - struct WrappedConfigModifyCapability has key { - cap: Config::ModifyConfigCapability, - } - - /// request of updating configuration. - struct OnChainConfigUpdate has copy, drop, store { - value: ConfigT, - } - - const ERR_NOT_AUTHORIZED: u64 = 401; - - /// Plugin method of the module. - /// Should be called by token issuer. - public fun plugin(signer: &signer) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - let config_modify_cap = Config::extract_modify_config_capability(signer); - let cap = WrappedConfigModifyCapability { cap: config_modify_cap }; - move_to(signer, cap); - } - spec plugin { - pragma aborts_if_is_partial = false; - let sender = Signer::address_of(signer); - aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS(); - include Config::AbortsIfCapNotExist{address: sender}; - aborts_if exists>(sender); - ensures exists>(sender); - } - - /// issue a proposal to update config of ConfigT goved by TokenT - public fun propose_update( - signer: &signer, - new_config: ConfigT, - exec_delay: u64, - ) { - Dao::propose>( - signer, - OnChainConfigUpdate { value: new_config }, - exec_delay, - ); - } - - spec propose_update { - use StarcoinFramework::Timestamp; - use StarcoinFramework::CoreAddresses; - pragma aborts_if_is_partial = false; - - // copy from Dao::propose spec. - include Dao::AbortIfDaoConfigNotExist; - include Dao::AbortIfDaoInfoNotExist; - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config().min_action_delay; - include Dao::CheckQuorumVotes; - let sender = Signer::address_of(signer); - aborts_if exists>>(sender); - } - - /// Once the proposal is agreed, anyone can call the method to make the proposal happen. - /// Caller need to make sure that the proposal of `proposal_id` under `proposal_address` is - /// the kind of this proposal module. - public fun execute( - proposer_address: address, - proposal_id: u64, - ) acquires WrappedConfigModifyCapability { - let OnChainConfigUpdate { value } = Dao::extract_proposal_action< - TokenT, - OnChainConfigUpdate, - >(proposer_address, proposal_id); - let cap = borrow_global_mut>( - Token::token_address(), - ); - Config::set_with_capability(&mut cap.cap, value); - } - spec execute { - pragma aborts_if_is_partial = true; - let expected_states = vec(6); - include Dao::CheckProposalStates>{expected_states}; - aborts_if !exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - } - - //StarcoinDAO init need Config Cap - public (friend) fun config_cap():Config::ModifyConfigCapabilityacquires WrappedConfigModifyCapability{ - let WrappedConfigModifyCapability {cap} = move_from>(CoreAddresses::GENESIS_ADDRESS()); - cap - } -} -} \ No newline at end of file diff --git a/release/v12/sources/OnChainConfigScripts.move b/release/v12/sources/OnChainConfigScripts.move deleted file mode 100644 index 581fee59..00000000 --- a/release/v12/sources/OnChainConfigScripts.move +++ /dev/null @@ -1,138 +0,0 @@ -address StarcoinFramework { -module OnChainConfigScripts { - use StarcoinFramework::ConsensusConfig; - use StarcoinFramework::OnChainConfigDao; - use StarcoinFramework::STC; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::TransactionPublishOption; - use StarcoinFramework::TransactionTimeoutConfig; - use StarcoinFramework::VMConfig; - use StarcoinFramework::Signer; - use StarcoinFramework::LanguageVersion; - - public ( script ) fun propose_update_consensus_config(account: signer, - uncle_rate_target: u64, - base_block_time_target: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - epoch_block_count: u64, - base_block_difficulty_window: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - exec_delay: u64) { - let consensus_config = ConsensusConfig::new_consensus_config(uncle_rate_target, - base_block_time_target, - base_reward_per_block, - base_reward_per_uncle_percent, - epoch_block_count, - base_block_difficulty_window, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy); - OnChainConfigDao::propose_update(&account, consensus_config, exec_delay); - } - - spec propose_update_consensus_config { - pragma verify = false; - } - - public ( script ) fun propose_update_reward_config(account: signer, - reward_delay: u64, - exec_delay: u64) { - let reward_config = RewardConfig::new_reward_config(reward_delay); - OnChainConfigDao::propose_update(&account, reward_config, exec_delay); - } - - spec propose_update_reward_config { - pragma verify = false; - } - - public ( script ) fun propose_update_txn_publish_option(account: signer, - script_allowed: bool, - module_publishing_allowed: bool, - exec_delay: u64) { - let txn_publish_option = TransactionPublishOption::new_transaction_publish_option(script_allowed, module_publishing_allowed); - OnChainConfigDao::propose_update(&account, txn_publish_option, exec_delay); - } - - spec propose_update_txn_publish_option { - pragma verify = false; - } - - public ( script ) fun propose_update_txn_timeout_config(account: signer, - duration_seconds: u64, - exec_delay: u64) { - let txn_timeout_config = TransactionTimeoutConfig::new_transaction_timeout_config(duration_seconds); - OnChainConfigDao::propose_update(&account, txn_timeout_config, exec_delay); - } - - spec propose_update_txn_timeout_config { - pragma verify = false; - } - - public ( script ) fun propose_update_vm_config(account: signer, - instruction_schedule: vector, - native_schedule: vector, - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - exec_delay: u64, ) { - let vm_config = VMConfig::new_vm_config(instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size); - OnChainConfigDao::propose_update(&account, vm_config, exec_delay); - } - - spec propose_update_vm_config { - pragma verify = false; - } - - public(script) fun propose_update_move_language_version(account: signer, new_version: u64, exec_delay: u64) { - let lang_version = LanguageVersion::new(new_version); - OnChainConfigDao::propose_update(&account, lang_version, exec_delay); - } - - spec propose_update_move_language_version { - pragma verify = false; - } - - public ( script ) fun execute_on_chain_config_proposal(account: signer, proposal_id: u64) { - OnChainConfigDao::execute(Signer::address_of(&account), proposal_id); - } - - spec execute_on_chain_config_proposal { - pragma verify = false; - } - - public(script) fun execute_on_chain_config_proposal_v2(proposer_address: address, proposal_id: u64) { - OnChainConfigDao::execute(proposer_address, proposal_id); - } - - spec execute_on_chain_config_proposal_v2 { - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/OnChainStarcoinDAOConfig.move b/release/v12/sources/OnChainStarcoinDAOConfig.move deleted file mode 100644 index a18df76b..00000000 --- a/release/v12/sources/OnChainStarcoinDAOConfig.move +++ /dev/null @@ -1,232 +0,0 @@ -module StarcoinFramework::OnChainStarcoinDAOConfig { - use StarcoinFramework::ConsensusConfig; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::TransactionPublishOption; - use StarcoinFramework::TransactionTimeoutConfig; - use StarcoinFramework::VMConfig; - use StarcoinFramework::LanguageVersion; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::ConfigProposalPlugin; - - public fun propose_update_consensus_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - uncle_rate_target: u64, - base_block_time_target: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - epoch_block_count: u64, - base_block_difficulty_window: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - exec_delay: u64) { - let consensus_config = ConsensusConfig::new_consensus_config(uncle_rate_target, - base_block_time_target, - base_reward_per_block, - base_reward_per_uncle_percent, - epoch_block_count, - base_block_difficulty_window, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, consensus_config); - } - - public ( script ) fun propose_update_consensus_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - uncle_rate_target: u64, - base_block_time_target: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - epoch_block_count: u64, - base_block_difficulty_window: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - exec_delay: u64) { - propose_update_consensus_config(&account, - title, - introduction, - description, - uncle_rate_target, - base_block_time_target, - base_reward_per_block, - base_reward_per_uncle_percent, - epoch_block_count, - base_block_difficulty_window, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, - exec_delay); - } - - spec propose_update_consensus_config { - pragma verify = false; - } - - public fun propose_update_reward_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - reward_delay: u64, - exec_delay: u64) { - let reward_config = RewardConfig::new_reward_config(reward_delay); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, reward_config); - } - - public ( script ) fun propose_update_reward_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - reward_delay: u64, - exec_delay: u64) { - propose_update_reward_config(&account, title, introduction, description, reward_delay, exec_delay); - } - spec propose_update_reward_config { - pragma verify = false; - } - - public fun propose_update_txn_publish_option(account: &signer, - title:vector, - introduction:vector, - description: vector, - script_allowed: bool, - module_publishing_allowed: bool, - exec_delay: u64) { - let txn_publish_option = TransactionPublishOption::new_transaction_publish_option(script_allowed, module_publishing_allowed); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, txn_publish_option); - } - - public ( script ) fun propose_update_txn_publish_option_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - script_allowed: bool, - module_publishing_allowed: bool, - exec_delay: u64) { - propose_update_txn_publish_option(&account, title, introduction, description, script_allowed, module_publishing_allowed, exec_delay); - } - spec propose_update_txn_publish_option { - pragma verify = false; - } - - public fun propose_update_txn_timeout_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - duration_seconds: u64, - exec_delay: u64) { - let txn_timeout_config = TransactionTimeoutConfig::new_transaction_timeout_config(duration_seconds); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, txn_timeout_config); - } - - public ( script ) fun propose_update_txn_timeout_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - duration_seconds: u64, - exec_delay: u64) { - propose_update_txn_timeout_config(&account, title, introduction,description,duration_seconds,exec_delay); - } - - spec propose_update_txn_timeout_config { - pragma verify = false; - } - - public fun propose_update_vm_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - instruction_schedule: vector, - native_schedule: vector, - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - exec_delay: u64, ) { - let vm_config = VMConfig::new_vm_config(instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, vm_config); - } - - public (script) fun propose_update_vm_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - instruction_schedule: vector, - native_schedule: vector, - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - exec_delay: u64, ) { - propose_update_vm_config(&account, - title, - introduction, - description, - instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size, - exec_delay) ; - } - - spec propose_update_vm_config { - pragma verify = false; - } - - public fun propose_update_move_language_version(account: &signer, title:vector, introduction:vector, description: vector, new_version: u64, exec_delay: u64) { - let lang_version = LanguageVersion::new(new_version); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, lang_version); - } - - public(script) fun propose_update_move_language_version_entry(account: signer, title:vector, introduction:vector, description: vector, new_version: u64, exec_delay: u64) { - propose_update_move_language_version(&account, title, introduction, description, new_version, exec_delay); - } -} \ No newline at end of file diff --git a/release/v12/sources/Option.move b/release/v12/sources/Option.move deleted file mode 100644 index 8baad1e0..00000000 --- a/release/v12/sources/Option.move +++ /dev/null @@ -1,235 +0,0 @@ -address StarcoinFramework { - -/// This module defines the Option type and its methods to represent and handle an optional value. -module Option { - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - - /// Abstraction of a value that may or may not be present. Implemented with a vector of size - /// zero or one because Move bytecode does not have ADTs. - struct Option has copy, drop, store { - vec: vector - } - spec Option { - /// The size of vector is always less than equal to 1 - /// because it's 0 for "none" or 1 for "some". - invariant len(vec) <= 1; - } - - /// The `Option` is in an invalid state for the operation attempted. - /// The `Option` is `Some` while it should be `None`. - const EOPTION_IS_SET: u64 = 0; - /// The `Option` is in an invalid state for the operation attempted. - /// The `Option` is `None` while it should be `Some`. - const EOPTION_NOT_SET: u64 = 1; - - /// Return an empty `Option` - public fun none(): Option { - Option { vec: Vector::empty() } - } - spec none { - pragma opaque; - aborts_if false; - ensures result == spec_none(); - } - spec fun spec_none(): Option { - Option{ vec: vec() } - } - - /// Return an `Option` containing `e` - public fun some(e: Element): Option { - Option { vec: Vector::singleton(e) } - } - spec some { - pragma opaque; - aborts_if false; - ensures result == spec_some(e); - } - spec fun spec_some(e: Element): Option { - Option{ vec: vec(e) } - } - - /// Return true if `t` does not hold a value - public fun is_none(t: &Option): bool { - Vector::is_empty(&t.vec) - } - spec is_none { - pragma opaque; - aborts_if false; - ensures result == is_none(t); - } - - /// Return true if `t` holds a value - public fun is_some(t: &Option): bool { - !Vector::is_empty(&t.vec) - } - spec is_some { - pragma opaque; - aborts_if false; - ensures result == is_some(t); - } - - /// Return true if the value in `t` is equal to `e_ref` - /// Always returns `false` if `t` does not hold a value - public fun contains(t: &Option, e_ref: &Element): bool { - Vector::contains(&t.vec, e_ref) - } - spec contains { - pragma opaque; - aborts_if false; - ensures result == spec_contains(t, e_ref); - } - spec fun spec_contains(t: Option, e: Element): bool { - is_some(t) && borrow(t) == e - } - - /// Return an immutable reference to the value inside `t` - /// Aborts if `t` does not hold a value - public fun borrow(t: &Option): &Element { - assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET)); - Vector::borrow(&t.vec, 0) - } - spec borrow { - pragma opaque; - include AbortsIfNone; - ensures result == borrow(t); - } - - /// Return a reference to the value inside `t` if it holds one - /// Return `default_ref` if `t` does not hold a value - public fun borrow_with_default(t: &Option, default_ref: &Element): &Element { - let vec_ref = &t.vec; - if (Vector::is_empty(vec_ref)) default_ref - else Vector::borrow(vec_ref, 0) - } - spec borrow_with_default { - pragma opaque; - aborts_if false; - ensures result == (if (is_some(t)) borrow(t) else default_ref); - } - - /// Return the value inside `t` if it holds one - /// Return `default` if `t` does not hold a value - public fun get_with_default( - t: &Option, - default: Element, - ): Element { - let vec_ref = &t.vec; - if (Vector::is_empty(vec_ref)) default - else *Vector::borrow(vec_ref, 0) - } - spec get_with_default { - pragma opaque; - aborts_if false; - ensures result == (if (is_some(t)) borrow(t) else default); - } - - /// Convert the none option `t` to a some option by adding `e`. - /// Aborts if `t` already holds a value - public fun fill(t: &mut Option, e: Element) { - let vec_ref = &mut t.vec; - if (Vector::is_empty(vec_ref)) Vector::push_back(vec_ref, e) - else abort Errors::invalid_argument(EOPTION_IS_SET) - } - spec fill { - pragma opaque; - aborts_if is_some(t) with Errors::INVALID_ARGUMENT; - ensures is_some(t); - ensures borrow(t) == e; - } - - /// Convert a `some` option to a `none` by removing and returning the value stored inside `t` - /// Aborts if `t` does not hold a value - public fun extract(t: &mut Option): Element { - assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET)); - Vector::pop_back(&mut t.vec) - } - spec extract { - pragma opaque; - include AbortsIfNone; - ensures result == borrow(old(t)); - ensures is_none(t); - } - - /// Return a mutable reference to the value inside `t` - /// Aborts if `t` does not hold a value - public fun borrow_mut(t: &mut Option): &mut Element { - assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET)); - Vector::borrow_mut(&mut t.vec, 0) - } - spec borrow_mut { - pragma opaque; - include AbortsIfNone; - ensures result == borrow(t); - } - - /// Swap the old value inside `t` with `e` and return the old value - /// Aborts if `t` does not hold a value - public fun swap(t: &mut Option, e: Element): Element { - assert!(is_some(t), Errors::invalid_argument(EOPTION_NOT_SET)); - let vec_ref = &mut t.vec; - let old_value = Vector::pop_back(vec_ref); - Vector::push_back(vec_ref, e); - old_value - } - spec swap { - pragma opaque; - include AbortsIfNone; - ensures result == borrow(old(t)); - ensures is_some(t); - ensures borrow(t) == e; - } - - /// Destroys `t.` If `t` holds a value, return it. Returns `default` otherwise - public fun destroy_with_default(t: Option, default: Element): Element { - let Option { vec } = t; - if (Vector::is_empty(&mut vec)) default - else Vector::pop_back(&mut vec) - } - spec destroy_with_default { - pragma opaque; - aborts_if false; - ensures result == (if (is_some(t)) borrow(t) else default); - } - - /// Unpack `t` and return its contents - /// Aborts if `t` does not hold a value - public fun destroy_some(t: Option): Element { - assert!(is_some(&t), Errors::invalid_argument(EOPTION_NOT_SET)); - let Option { vec } = t; - let elem = Vector::pop_back(&mut vec); - Vector::destroy_empty(vec); - elem - } - spec destroy_some { - pragma opaque; - include AbortsIfNone; - ensures result == borrow(t); - } - - /// Unpack `t` - /// Aborts if `t` holds a value - public fun destroy_none(t: Option) { - assert!(is_none(&t), Errors::invalid_argument(EOPTION_IS_SET)); - let Option { vec } = t; - Vector::destroy_empty(vec) - } - spec destroy_none { - pragma opaque; - aborts_if is_some(t) with Errors::INVALID_ARGUMENT; - } - - spec module {} // switch documentation context back to module level - - spec module { - pragma aborts_if_is_strict; - } - - /// # Helper Schema - - spec schema AbortsIfNone { - t: Option; - aborts_if is_none(t) with Errors::INVALID_ARGUMENT; - } -} -} diff --git a/release/v12/sources/Oracle.move b/release/v12/sources/Oracle.move deleted file mode 100644 index 44e5db5e..00000000 --- a/release/v12/sources/Oracle.move +++ /dev/null @@ -1,365 +0,0 @@ -address StarcoinFramework { -module Oracle { - use StarcoinFramework::Event; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Account; - use StarcoinFramework::GenesisSignerCapability; - - struct OracleInfo has key { - ///The datasource counter - counter: u64, - ///Ext info - info: Info, - } - - struct DataRecord has copy, store, drop { - ///The data version - version: u64, - ///The record value - value: ValueT, - ///Update timestamp millisecond - updated_at: u64, - } - - struct OracleFeed has key { - record: DataRecord, - } - - struct OracleUpdateEvent has copy,store,drop { - source_id: u64, - record: DataRecord, - } - - struct DataSource has key { - /// the id of data source of ValueT - id: u64, - /// the data version counter. - counter: u64, - update_events: Event::EventHandle>, - } - - struct UpdateCapability has store, key { - account: address, - } - - struct GenesisSignerCapability has key{ - cap: Account::SignerCapability, - } - - /// The oracle type not register. - const ERR_ORACLE_TYPE_NOT_REGISTER:u64 = 101; - /// No capability to update the oracle value. - const ERR_NO_UPDATE_CAPABILITY: u64 = 102; - const ERR_NO_DATA_SOURCE: u64 = 103; - const ERR_CAPABILITY_ACCOUNT_MISS_MATCH: u64 = 104; - const ERR_NO_ORACLE_FEED:u64 =105; - /// deprecated. - public fun initialize(_sender: &signer) { - } - - /// Used in v7->v8 upgrade. struct `GenesisSignerCapability` is deprecated, in favor of module `StarcoinFramework::GenesisSignerCapability`. - public fun extract_signer_cap(signer: &signer): Account::SignerCapability acquires GenesisSignerCapability{ - CoreAddresses::assert_genesis_address(signer); - let cap = move_from(Signer::address_of(signer)); - let GenesisSignerCapability {cap} = cap; - cap - } - - /// Register `OracleT` as an oracle type. - public fun register_oracle(_sender: &signer, info: Info) { - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - move_to(&genesis_account, OracleInfo { - counter: 0, - info, - }); - } - - /// Get the `OracleT` oracle's counter, the counter represent how many `OracleT` datasources - public fun get_oracle_counter() : u64 acquires OracleInfo { - let oracle_info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - oracle_info.counter - } - - public fun get_oracle_info() : Info acquires OracleInfo { - let oracle_info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - *&oracle_info.info - } - - /// Init a data source for type `OracleT` - public fun init_data_source(sender: &signer, init_value: ValueT) acquires OracleInfo{ - assert!(exists>(CoreAddresses::GENESIS_ADDRESS()), Errors::not_published(ERR_ORACLE_TYPE_NOT_REGISTER)); - let oracle_info = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - let now = Timestamp::now_milliseconds(); - move_to(sender, OracleFeed { - record: DataRecord { - version: 0, - value: init_value, - updated_at: now, - } - }); - let sender_addr = Signer::address_of(sender); - move_to(sender, DataSource { - id: oracle_info.counter, - counter: 1, - update_events: Event::new_event_handle>(sender), - }); - move_to(sender, UpdateCapability{account: sender_addr}); - oracle_info.counter = oracle_info.counter + 1; - } - - /// Check the DataSource is initiailzed at ds_addr - public fun is_data_source_initialized(ds_addr: address): bool { - exists>(ds_addr) - } - - /// Update Oracle's record with new value, the `sender` must have UpdateCapability - public fun update(sender: &signer, value: ValueT) acquires UpdateCapability, DataSource, OracleFeed{ - let account = Signer::address_of(sender); - assert!(exists>(account), Errors::requires_capability(ERR_NO_UPDATE_CAPABILITY)); - let cap = borrow_global_mut>(account); - update_with_cap(cap,value); - } - - /// Update Oracle's record with new value and UpdateCapability - public fun update_with_cap(cap: &mut UpdateCapability, value: ValueT) acquires DataSource,OracleFeed { - let account = cap.account; - assert!(exists>(account), Errors::requires_capability(ERR_NO_DATA_SOURCE)); - let source = borrow_global_mut>(account); - let now = Timestamp::now_milliseconds(); - let oracle_feed = borrow_global_mut>(account); - oracle_feed.record.version = source.counter; - oracle_feed.record.value = value; - oracle_feed.record.updated_at = now; - source.counter = source.counter + 1; - Event::emit_event(&mut source.update_events,OracleUpdateEvent{ - source_id: source.id, - record: *&oracle_feed.record - }); - } - - /// Read the Oracle's value from `ds_addr` - public fun read(ds_addr: address): ValueT acquires OracleFeed{ - assert!(exists>(ds_addr), Errors::invalid_state(ERR_NO_ORACLE_FEED)); - let oracle_feed = borrow_global>(ds_addr); - *&oracle_feed.record.value - } - - /// Read the Oracle's DataRecord from `ds_addr` - public fun read_record(ds_addr: address): DataRecord acquires OracleFeed{ - assert!(exists>(ds_addr), Errors::invalid_state(ERR_NO_ORACLE_FEED)); - let oracle_feed = borrow_global>(ds_addr); - *&oracle_feed.record - } - - /// Batch read Oracle's DataRecord from `ds_addrs` - public fun read_records(ds_addrs: &vector
): vector> acquires OracleFeed{ - let len = Vector::length(ds_addrs); - let results = Vector::empty(); - let i = 0; - while (i < len){ - let addr = *Vector::borrow(ds_addrs, i); - let record = Self::read_record(addr); - Vector::push_back(&mut results, record); - i = i + 1; - }; - results - } - - /// Remove UpdateCapability from current sender. - public fun remove_update_capability(sender: &signer):UpdateCapability acquires UpdateCapability{ - let account = Signer::address_of(sender); - assert!(exists>(account), Errors::requires_capability(ERR_NO_UPDATE_CAPABILITY)); - move_from>(account) - } - - /// Add UpdateCapability to current sender - public fun add_update_capability(sender: &signer, update_cap: UpdateCapability){ - assert!(Signer::address_of(sender) == update_cap.account, Errors::invalid_argument(ERR_CAPABILITY_ACCOUNT_MISS_MATCH)); - move_to(sender, update_cap); - } - - /// Unpack Record to fields: version, oracle, updated_at. - public fun unpack_record(record: DataRecord):(u64, ValueT, u64) { - (record.version,*&record.value,record.updated_at) - } -} -module PriceOracle { - use StarcoinFramework::Math; - use StarcoinFramework::Oracle::{Self, DataRecord, UpdateCapability}; - - struct PriceOracleInfo has copy, store, drop { - scaling_factor: u128, - } - - public(script) fun register_oracle_entry(sender: signer, precision: u8){ - register_oracle(&sender, precision); - } - - public fun register_oracle(sender: &signer, precision: u8){ - let scaling_factor = Math::pow(10, (precision as u64)); - Oracle::register_oracle(sender, PriceOracleInfo{ - scaling_factor, - }); - } - public(script) fun init_data_source_entry(sender: signer, init_value: u128){ - init_data_source(&sender, init_value); - } - - public fun init_data_source(sender: &signer, init_value: u128){ - Oracle::init_data_source(sender, init_value); - } - - public fun is_data_source_initialized(ds_addr: address): bool { - Oracle::is_data_source_initialized(ds_addr) - } - - public fun get_scaling_factor(): u128 { - let info = Oracle::get_oracle_info(); - info.scaling_factor - } - public(script) fun update_entry(sender: signer, value: u128){ - update(&sender, value); - } - - public fun update(sender: &signer, value: u128){ - Oracle::update(sender, value); - } - - public fun update_with_cap(cap: &mut UpdateCapability, value: u128) { - Oracle::update_with_cap(cap, value); - } - - public fun read(addr: address): u128 { - Oracle::read(addr) - } - - public fun read_record(addr: address): DataRecord { - Oracle::read_record(addr) - } - - public fun read_records(addrs: &vector
): vector> { - Oracle::read_records(addrs) - } - - public fun remove_update_capability(sender: &signer): UpdateCapability { - Oracle::remove_update_capability(sender) - } - - public fun add_update_capability(sender: &signer, update_cap: UpdateCapability) { - Oracle::add_update_capability(sender, update_cap) - } -} - -module GasOracle { - use StarcoinFramework::PriceOracle; - - struct STCToken has copy, store, drop { - } - - public fun register(sender: &signer, precision: u8){ - PriceOracle::register_oracle>(sender, precision); - } - public(script) fun register_entry(sender: signer, precision: u8){ - register(&sender, precision); - } - - public fun init_data_source(sender: &signer, init_value: u128){ - PriceOracle::init_data_source>(sender, init_value); - } - - public(script) fun init_data_source_entry(sender: signer, init_value: u128){ - init_data_source(&sender, init_value); - } - - public fun update(sender: &signer, value: u128){ - PriceOracle::update>(sender, value); - } - - public(script) fun update_entry(sender: signer, value: u128){ - update(&sender, value); - } - - public fun get_scaling_factor(): u128 { - PriceOracle::get_scaling_factor>() - } -} - -module STCUSDOracle{ - use StarcoinFramework::Oracle::{DataRecord}; - use StarcoinFramework::PriceOracle::{Self}; - - /// The STC to USD price oracle - struct STCUSD has copy,store,drop {} - - public fun register(sender: &signer){ - PriceOracle::register_oracle(sender, 6); - } - - public fun read(ds_addr: address) : u128{ - PriceOracle::read(ds_addr) - } - - public fun read_record(ds_addr: address): DataRecord{ - PriceOracle::read_record(ds_addr) - } - - public fun read_records(ds_addrs: &vector
): vector>{ - PriceOracle::read_records(ds_addrs) - } -} - -module PriceOracleScripts{ - use StarcoinFramework::PriceOracle; - - public(script) fun register_oracle(sender: signer, precision: u8){ - PriceOracle::register_oracle_entry(sender, precision); - } - - public(script) fun init_data_source(sender: signer, init_value: u128){ - PriceOracle::init_data_source_entry(sender, init_value); - } - - public(script) fun update(sender: signer, value: u128){ - PriceOracle::update_entry(sender, value); - } -} - -module PriceOracleAggregator{ - use StarcoinFramework::Vector; - use StarcoinFramework::Oracle; - use StarcoinFramework::PriceOracle; - use StarcoinFramework::Math; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Errors; - - /// No price data match requirement condition. - const ERR_NO_PRICE_DATA_AVIABLE:u64 = 101; - - /// Get latest price from datasources and calculate avg. - /// `addrs`: the datasource's addr, `updated_in`: the datasource should updated in x millseoconds. - public fun latest_price_average_aggregator(addrs: &vector
, updated_in: u64): u128 { - let len = Vector::length(addrs); - let price_records = PriceOracle::read_records(addrs); - let prices = Vector::empty(); - let i = 0; - let expect_updated_after = Timestamp::now_milliseconds() - updated_in; - while (i < len){ - let record = Vector::pop_back(&mut price_records); - let (_version, price, updated_at) = Oracle::unpack_record(record); - if (updated_at >= expect_updated_after) { - Vector::push_back(&mut prices, price); - }; - i = i + 1; - }; - // if all price data not match the update_in filter, abort. - assert!(!Vector::is_empty(&prices), Errors::invalid_state(ERR_NO_PRICE_DATA_AVIABLE)); - Math::avg(&prices) - } -} - - -} \ No newline at end of file diff --git a/release/v12/sources/PackageTxnManager.move b/release/v12/sources/PackageTxnManager.move deleted file mode 100644 index e0036d40..00000000 --- a/release/v12/sources/PackageTxnManager.move +++ /dev/null @@ -1,522 +0,0 @@ -address StarcoinFramework { - /// The module provides strategies for module upgrading. - module PackageTxnManager { - use StarcoinFramework::Option::{Self,Option}; - use StarcoinFramework::Signer; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Version; - use StarcoinFramework::Event; - use StarcoinFramework::Config; - use StarcoinFramework::Timestamp; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - /// module upgrade plan - struct UpgradePlan has copy, drop, store { - package_hash: vector, - active_after_time: u64, - version: u64, - } - - /// The holder of UpgradePlanCapability for account_address can submit UpgradePlan for account_address. - struct UpgradePlanCapability has key, store { - account_address: address, - } - - const STRATEGY_ARBITRARY: u8 = 0; - const STRATEGY_TWO_PHASE: u8 = 1; - const STRATEGY_NEW_MODULE: u8 = 2; - const STRATEGY_FREEZE: u8 = 3; - const DEFAULT_MIN_TIME_LIMIT: u64 = 86400000;// one day - - /// arbitary stragegy - public fun get_strategy_arbitrary(): u8 { STRATEGY_ARBITRARY } - /// two phase stragegy - public fun get_strategy_two_phase(): u8 { STRATEGY_TWO_PHASE } - /// new module strategy - public fun get_strategy_new_module(): u8 { STRATEGY_NEW_MODULE } - /// freezed strategy - public fun get_strategy_freeze(): u8 { STRATEGY_FREEZE } - /// default min time limit - public fun get_default_min_time_limit(): u64 { DEFAULT_MIN_TIME_LIMIT } - - const EUPGRADE_PLAN_IS_NONE: u64 = 102; - const EPACKAGE_HASH_INCORRECT: u64 = 103; - const EACTIVE_TIME_INCORRECT: u64 = 104; - const ESTRATEGY_FREEZED: u64 = 105; - const ESTRATEGY_INCORRECT: u64 = 106; - const ESTRATEGY_NOT_TWO_PHASE: u64 = 107; - const EUNKNOWN_STRATEGY: u64 = 108; - const ESENDER_AND_PACKAGE_ADDRESS_MISMATCH: u64 = 109; - - struct UpgradePlanV2 has copy, drop, store { - package_hash: vector, - active_after_time: u64, - version: u64, - enforced: bool, - } - - /// module upgrade strategy - struct ModuleUpgradeStrategy has key, store { - /// 0 arbitrary - /// 1 two phase upgrade - /// 2 only new module - /// 3 freeze - strategy: u8, - } - - /// data of two phase upgrade strategy. - struct TwoPhaseUpgrade has key { - config: TwoPhaseUpgradeConfig, - plan: Option, - version_cap: Config::ModifyConfigCapability, - upgrade_event: Event::EventHandle, - } - - /// config of two phase upgrade strategy. - struct TwoPhaseUpgradeConfig has copy, drop, store { - min_time_limit: u64, - } - - /// data of two phase upgrade strategy. - struct TwoPhaseUpgradeV2 has key { - config: TwoPhaseUpgradeConfig, - plan: Option, - version_cap: Config::ModifyConfigCapability, - upgrade_event: Event::EventHandle, - } - - /// module upgrade event. - struct UpgradeEvent has drop, store { - package_address: address, - package_hash: vector, - version: u64, - } - - struct UpgradePlanEventHolder has key { - upgrade_plan_event: Event::EventHandle - } - - /// module upgrade plan event when submitting a module upgrade plan - struct UpgradePlanEvent has drop, store { - package_address: address, - plan: UpgradePlanV2, - } - - /// Update account's ModuleUpgradeStrategy - public fun update_module_upgrade_strategy(account: &signer, strategy: u8, min_time: Option) - acquires ModuleUpgradeStrategy, TwoPhaseUpgrade, TwoPhaseUpgradeV2, UpgradePlanCapability, UpgradePlanEventHolder{ - assert!(strategy == STRATEGY_ARBITRARY || strategy == STRATEGY_TWO_PHASE || strategy == STRATEGY_NEW_MODULE || strategy == STRATEGY_FREEZE, Errors::invalid_argument(EUNKNOWN_STRATEGY)); - let account_address = Signer::address_of(account); - let previous_strategy = get_module_upgrade_strategy(account_address); - assert!(strategy > previous_strategy, Errors::invalid_argument(ESTRATEGY_INCORRECT)); - if (exists(account_address)) { - borrow_global_mut(account_address).strategy = strategy; - }else{ - move_to(account, ModuleUpgradeStrategy{ strategy: strategy}); - }; - if (strategy == STRATEGY_TWO_PHASE){ - let version_cap = Config::extract_modify_config_capability(account); - let min_time_limit = Option::get_with_default(&min_time, DEFAULT_MIN_TIME_LIMIT); - move_to(account, UpgradePlanCapability{ account_address}); - move_to(account, TwoPhaseUpgradeV2 { - config: TwoPhaseUpgradeConfig { min_time_limit }, - plan: Option::none(), - version_cap, - upgrade_event: Event::new_event_handle(account) - }); - move_to(account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(account) - }); - }; - //clean two phase upgrade resource - if (previous_strategy == STRATEGY_TWO_PHASE){ - if (exists(account_address)) { - let tpu = move_from(account_address); - let TwoPhaseUpgrade{plan:_, version_cap, upgrade_event, config: _} = tpu; - Event::destroy_handle(upgrade_event); - Config::destroy_modify_config_capability(version_cap); - }; - if (exists(account_address)) { - let tpu = move_from(account_address); - let TwoPhaseUpgradeV2{config: _, plan: _, version_cap, upgrade_event } = tpu; - Event::destroy_handle(upgrade_event); - if (exists(account_address)) { - let UpgradePlanEventHolder{ upgrade_plan_event } = move_from(account_address); - Event::destroy_handle(upgrade_plan_event); - }; - Config::destroy_modify_config_capability(version_cap); - }; - // UpgradePlanCapability may be extracted - if (exists(account_address)) { - let cap = move_from(account_address); - destroy_upgrade_plan_cap(cap); - }; - }; - } - - spec update_module_upgrade_strategy { - pragma verify = false; - aborts_if strategy != 0 && strategy != 1 && strategy != 2 && strategy != 3; - aborts_if exists(Signer::address_of(account)) && strategy <= global(Signer::address_of(account)).strategy; - aborts_if !exists(Signer::address_of(account)) && strategy == 0; - - aborts_if strategy == 1 && exists(Signer::address_of(account)); - aborts_if strategy == 1 && !exists>(Signer::address_of(account)); - let holder = global>(Signer::address_of(account)); - aborts_if strategy == 1 && Option::is_none>(holder.cap); - aborts_if strategy == 1 && exists(Signer::address_of(account)); - - aborts_if exists(Signer::address_of(account)) && global(Signer::address_of(account)).strategy == 1 - && !exists(Signer::address_of(account)); - } - - /// Get account address of UpgradePlanCapability - public fun account_address(cap: &UpgradePlanCapability): address { - cap.account_address - } - - /// destroy the given UpgradePlanCapability - public fun destroy_upgrade_plan_cap(cap: UpgradePlanCapability){ - let UpgradePlanCapability{account_address:_} = cap; - } - - spec destroy_upgrade_plan_cap { - aborts_if false; - } - - /// extract out UpgradePlanCapability from `signer`. - public fun extract_submit_upgrade_plan_cap(account: &signer): UpgradePlanCapability acquires ModuleUpgradeStrategy, UpgradePlanCapability{ - let account_address = Signer::address_of(account); - assert!(get_module_upgrade_strategy(account_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE)); - move_from(account_address) - } - - spec extract_submit_upgrade_plan_cap { - aborts_if !exists(Signer::address_of(account)); - aborts_if global(Signer::address_of(account)).strategy != 1; - aborts_if !exists(Signer::address_of(account)); - } - - public(script) fun convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2(account: signer, package_address: address) acquires TwoPhaseUpgrade { - let account_address = Signer::address_of(&account); - // sender should be package owner - assert!(account_address == package_address, Errors::requires_address(ESENDER_AND_PACKAGE_ADDRESS_MISMATCH)); - let tpu = move_from(account_address); - let TwoPhaseUpgrade{config, plan, version_cap, upgrade_event} = tpu; - if (Option::is_some(&plan)) { - let old_plan = Option::borrow(&plan); - move_to(&account, TwoPhaseUpgradeV2{ - config, - plan: Option::some(UpgradePlanV2 { - package_hash: *&old_plan.package_hash, - active_after_time: old_plan.active_after_time, - version: old_plan.version, - enforced: false }), - version_cap, - upgrade_event - }); - move_to(&account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(&account) - }); - } else { - move_to(&account, TwoPhaseUpgradeV2 { - config, - plan: Option::none(), - version_cap, - upgrade_event - }); - move_to(&account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(&account) - }); - }; - } - - spec convert_TwoPhaseUpgrade_to_TwoPhaseUpgradeV2 { - pragma verify = false; - } - - public fun submit_upgrade_plan_v2(account: &signer, package_hash: vector, version:u64, enforced: bool) - acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy,UpgradePlanEventHolder{ - let account_address = Signer::address_of(account); - let cap = borrow_global(account_address); - assert!(get_module_upgrade_strategy(cap.account_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE)); - if (!exists(account_address)) { - move_to(account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(account) - }) - }; - submit_upgrade_plan_with_cap_v2(cap, package_hash, version, enforced); - } - - spec submit_upgrade_plan_v2 { - pragma verify = false; - aborts_if !exists(Signer::address_of(account)); - include SubmitUpgradePlanWithCapAbortsIf{account: global(Signer::address_of(account)).account_address}; - ensures Option::is_some(global(global(Signer::address_of(account)).account_address).plan); - } - public fun submit_upgrade_plan_with_cap_v2(cap: &UpgradePlanCapability, package_hash: vector, version: u64, enforced: bool) - acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy, UpgradePlanEventHolder{ - let package_address = cap.account_address; - assert!(get_module_upgrade_strategy(package_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE)); - - let tpu = borrow_global_mut(package_address); - let active_after_time = Timestamp::now_milliseconds() + tpu.config.min_time_limit; - let plan = UpgradePlanV2 { package_hash, active_after_time, version, enforced }; - tpu.plan = Option::some(copy plan); - - // TODO - // if UpgradePlanCapability was delegated to DAO or contract, - // it's hard to upgrade the address to claim an UpgradePlanEventHolder. - // Try to fix this! - if (exists(package_address)) { - let event_holder = borrow_global_mut(package_address); - Event::emit_event(&mut event_holder.upgrade_plan_event, UpgradePlanEvent { - package_address, - plan - }); - } - } - spec submit_upgrade_plan_with_cap_v2 { - pragma verify = false; - include SubmitUpgradePlanWithCapAbortsIf{account: cap.account_address}; - ensures Option::is_some(global(cap.account_address).plan); - } - - spec schema SubmitUpgradePlanWithCapAbortsIf { - account: address; - aborts_if !exists(account); - aborts_if global(account).strategy != 1; - aborts_if !exists(account); - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if Timestamp::now_milliseconds() + global(account).config.min_time_limit > max_u64(); - } - - /// Cancel a module upgrade plan. - public fun cancel_upgrade_plan(account: &signer) acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy{ - let account_address = Signer::address_of(account); - let cap = borrow_global(account_address); - cancel_upgrade_plan_with_cap(cap); - } - - spec cancel_upgrade_plan { - aborts_if !exists(Signer::address_of(account)); - include CancelUpgradePlanWithCapAbortsIf{account: global(Signer::address_of(account)).account_address}; - ensures Option::is_none(global(global(Signer::address_of(account)).account_address).plan); - } - - /// Cancel a module upgrade plan with given cap. - public fun cancel_upgrade_plan_with_cap(cap: &UpgradePlanCapability) acquires TwoPhaseUpgradeV2,ModuleUpgradeStrategy{ - let package_address = cap.account_address; - assert!(get_module_upgrade_strategy(package_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE)); - let tpu = borrow_global_mut(package_address); - assert!(Option::is_some(&tpu.plan), Errors::invalid_state(EUPGRADE_PLAN_IS_NONE)); - tpu.plan = Option::none(); - } - - spec cancel_upgrade_plan_with_cap { - include CancelUpgradePlanWithCapAbortsIf{account: cap.account_address}; - ensures Option::is_none(global(cap.account_address).plan); - } - - spec schema CancelUpgradePlanWithCapAbortsIf { - account: address; - aborts_if !exists(account); - aborts_if global(account).strategy != 1; - aborts_if !exists(account); - aborts_if !Option::is_some(global(account).plan); - } - - /// Get module upgrade strategy of an module address. - public fun get_module_upgrade_strategy(module_address: address): u8 acquires ModuleUpgradeStrategy { - if (exists(module_address)) { - borrow_global(module_address).strategy - }else{ - 0 - } - } - - spec get_module_upgrade_strategy { - aborts_if false; - } - - spec fun spec_get_module_upgrade_strategy(module_address: address): u8 { - if (exists(module_address)) { - global(module_address).strategy - }else{ - 0 - } - } - - /// Get module upgrade plan of an address. - public fun get_upgrade_plan(_module_address: address): Option { - // DEPRECATED_CODE - Option::none() - } - - spec get_upgrade_plan { - aborts_if false; - } - - /// Get module upgrade plan of an address. - public fun get_upgrade_plan_v2(module_address: address): Option acquires TwoPhaseUpgradeV2 { - if (exists(module_address)) { - *&borrow_global(module_address).plan - } else { - Option::none() - } - } - - spec get_upgrade_plan_v2 { - pragma verify = false; - aborts_if false; - } - spec fun spec_get_upgrade_plan_v2(module_address: address): Option { - if (exists(module_address)) { - global(module_address).plan - }else{ - Option::spec_none() - } - } - - /// Check againest on the given package data. - public fun check_package_txn(package_address: address, package_hash: vector) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy{ - let strategy = get_module_upgrade_strategy(package_address); - if (strategy == STRATEGY_ARBITRARY){ - //do nothing - }else if(strategy == STRATEGY_TWO_PHASE){ - let plan_opt = get_upgrade_plan_v2(package_address); - assert!(Option::is_some(&plan_opt), Errors::invalid_argument(EUPGRADE_PLAN_IS_NONE)); - let plan = Option::borrow(&plan_opt); - assert!(*&plan.package_hash == package_hash, Errors::invalid_argument(EPACKAGE_HASH_INCORRECT)); - assert!(plan.active_after_time <= Timestamp::now_milliseconds(), Errors::invalid_argument(EACTIVE_TIME_INCORRECT)); - }else if(strategy == STRATEGY_NEW_MODULE){ - //do check at VM runtime. - }else if(strategy == STRATEGY_FREEZE){ - Errors::invalid_argument(ESTRATEGY_FREEZED); - }; - } - - spec check_package_txn { - pragma verify = false; - include CheckPackageTxnAbortsIf; - } - - public fun check_package_txn_v2(txn_sender: address, package_address: address, package_hash: vector) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy{ - let strategy = get_module_upgrade_strategy(package_address); - if (strategy == STRATEGY_ARBITRARY){ - assert!(txn_sender == package_address, Errors::requires_address(ESENDER_AND_PACKAGE_ADDRESS_MISMATCH)); - }else if(strategy == STRATEGY_TWO_PHASE){ - let plan_opt = get_upgrade_plan_v2(package_address); - assert!(Option::is_some(&plan_opt), Errors::invalid_argument(EUPGRADE_PLAN_IS_NONE)); - let plan = Option::borrow(&plan_opt); - assert!(*&plan.package_hash == package_hash, Errors::invalid_argument(EPACKAGE_HASH_INCORRECT)); - assert!(plan.active_after_time <= Timestamp::now_milliseconds(), Errors::invalid_argument(EACTIVE_TIME_INCORRECT)); - }else if(strategy == STRATEGY_NEW_MODULE){ - //do check at VM runtime. - assert!(txn_sender == package_address, Errors::requires_address(ESENDER_AND_PACKAGE_ADDRESS_MISMATCH)); - }else if(strategy == STRATEGY_FREEZE){ - Errors::invalid_argument(ESTRATEGY_FREEZED); - }; - } - - spec schema CheckPackageTxnAbortsIf { - package_address: address; - package_hash: vector; - aborts_if spec_get_module_upgrade_strategy(package_address) == 3; - aborts_if spec_get_module_upgrade_strategy(package_address) == 1 && Option::is_none(spec_get_upgrade_plan_v2(package_address)); - aborts_if spec_get_module_upgrade_strategy(package_address) == 1 && Option::borrow(spec_get_upgrade_plan_v2(package_address)).package_hash != package_hash; - aborts_if spec_get_module_upgrade_strategy(package_address) == 1 && !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if spec_get_module_upgrade_strategy(package_address) == 1 && Option::borrow(spec_get_upgrade_plan_v2(package_address)).active_after_time > Timestamp::now_milliseconds(); - } - - spec schema CheckPackageTxnAbortsIfWithType { - is_package: bool; - sender: address; - package_address: address; - package_hash: vector; - aborts_if is_package && spec_get_module_upgrade_strategy(package_address) == 3; - aborts_if is_package && spec_get_module_upgrade_strategy(package_address) == 1 && Option::is_none(spec_get_upgrade_plan_v2(package_address)); - aborts_if is_package && spec_get_module_upgrade_strategy(package_address) == 1 && Option::borrow(spec_get_upgrade_plan_v2(package_address)).package_hash != package_hash; - aborts_if is_package && spec_get_module_upgrade_strategy(package_address) == 1 && !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if is_package && spec_get_module_upgrade_strategy(package_address) == 1 && Option::borrow(spec_get_upgrade_plan_v2(package_address)).active_after_time > Timestamp::now_milliseconds(); - } - - fun finish_upgrade_plan(package_address: address) acquires TwoPhaseUpgradeV2 { - let tpu = borrow_global_mut(package_address); - if (Option::is_some(&tpu.plan)) { - let plan = Option::borrow(&tpu.plan); - Config::set_with_capability(&mut tpu.version_cap, Version::new_version(plan.version)); - Event::emit_event(&mut tpu.upgrade_event, UpgradeEvent { - package_address, - package_hash: *&plan.package_hash, - version: plan.version}); - }; - tpu.plan = Option::none(); - } - - spec finish_upgrade_plan { - pragma verify = false; - aborts_if !exists(package_address); - let tpu = global(package_address); - aborts_if Option::is_some(tpu.plan) && !exists>(tpu.version_cap.account_address); - } - - /// Prologue of package transaction. - public fun package_txn_prologue(account: &signer, package_address: address, package_hash: vector) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy { - // Can only be invoked by genesis account - CoreAddresses::assert_genesis_address(account); - check_package_txn(package_address, package_hash); - } - - spec package_txn_prologue { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - include CheckPackageTxnAbortsIf{}; - } - - public fun package_txn_prologue_v2(account: &signer, txn_sender: address, package_address: address, package_hash: vector) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy { - // Can only be invoked by genesis account - CoreAddresses::assert_genesis_address(account); - check_package_txn_v2(txn_sender, package_address, package_hash); - } - - /// Package txn finished, and clean UpgradePlan - public fun package_txn_epilogue(account: &signer, _txn_sender: address, package_address: address, success: bool) acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy { - // Can only be invoked by genesis account - CoreAddresses::assert_genesis_address(account); - let strategy = get_module_upgrade_strategy(package_address); - if(strategy == STRATEGY_TWO_PHASE){ - if (success) { - finish_upgrade_plan(package_address); - }; - }; - } - - spec schema AbortsIfPackageTxnEpilogue { - is_package: bool; - package_address: address; - success: bool; - aborts_if is_package && get_module_upgrade_strategy(package_address) == STRATEGY_TWO_PHASE && success && !exists(package_address); - } - - spec package_txn_epilogue { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if spec_get_module_upgrade_strategy(package_address) == 1 - && success && !exists(package_address); - aborts_if spec_get_module_upgrade_strategy(package_address) == 1 - && success && Option::is_some(global(package_address).plan) - && !exists>(global(package_address).version_cap.account_address); - } - - public fun exists_upgrade_plan_cap(addr :address):bool{ - exists(addr) - } - - spec exists_upgrade_plan_cap { - aborts_if false; - } - } -} \ No newline at end of file diff --git a/release/v12/sources/RewardConfig.move b/release/v12/sources/RewardConfig.move deleted file mode 100644 index 07179d9c..00000000 --- a/release/v12/sources/RewardConfig.move +++ /dev/null @@ -1,71 +0,0 @@ -address StarcoinFramework { -/// The module provide configuration for block reward. -module RewardConfig { - use StarcoinFramework::Timestamp; - use StarcoinFramework::Signer; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Config; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Reward configuration - struct RewardConfig has copy, drop, store { - /// how many blocks delay reward distribution. - reward_delay: u64, - } - - const EINVALID_ARGUMENT: u64 = 18; - - /// Module initialization. - public fun initialize(account: &signer, reward_delay: u64) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - - Config::publish_new_config( - account, - new_reward_config(reward_delay) - ); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if exists>(Signer::address_of(account)); - include Config::PublishNewConfigAbortsIf; - include Config::PublishNewConfigEnsures; - } - - /// Create a new reward config mainly used in DAO. - public fun new_reward_config(reward_delay: u64) : RewardConfig { - RewardConfig {reward_delay: reward_delay} - } - - spec new_reward_config {} - - /// Get reward configuration. - public fun get_reward_config(): RewardConfig { - Config::get_by_address(CoreAddresses::GENESIS_ADDRESS()) - } - - spec get_reward_config { - include GetRewardConfigAbortsIf; - } - - spec schema GetRewardConfigAbortsIf { - aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Get reward delay. - public fun reward_delay() :u64 { - let reward_config = get_reward_config(); - reward_config.reward_delay - } - - spec reward_delay { - aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/Ring.move b/release/v12/sources/Ring.move deleted file mode 100644 index 4ec1d26f..00000000 --- a/release/v12/sources/Ring.move +++ /dev/null @@ -1,154 +0,0 @@ -address StarcoinFramework { - -/// A ring-shaped container that can hold any type, indexed from 0 -/// The capacity is fixed at creation time, and the accessible index is constantly growing -module Ring { - - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::Errors; - - - /// The index into the vector is out of bounds - const ERROR_RING_INDEX_OUT_OF_BOUNDS:u64 = 101; - - struct Ring has store{ - data : vector>, - insertion_index : u64, - external_index : u64 - } - - /// Create a Ring with capacity. - public fun create_with_capacity( len: u64 ):Ring{ - let data = Vector::empty>(); - let i = 0; - while(i < len){ - Vector::push_back(&mut data , Option::none()); - i = i + 1; - }; - Ring { - data : data, - insertion_index : 0, - external_index : 0, - } - } - - spec create_with_capacity{ - pragma verify = false; - } - - ///is Ring full - public fun is_full(r: &Ring):bool{ - Option::is_some(Vector::borrow(&r.data, r.insertion_index)) - } - - spec is_full{ - pragma verify = false; - } - - ///Return the capacity of the Ring. - public fun capacity(r: &Ring): u64{ - Vector::length( &r.data ) - } - - spec capacity{ - pragma verify = false; - } - - /// Add element `e` to the insertion_index of the Ring `r`. - public fun push (r: &mut Ring , e: Element):Option::Option{ - let op_e = Vector::borrow_mut>(&mut r.data, r.insertion_index); - let res = if( Option::is_none(op_e) ){ - Option::fill( op_e, e); - Option::none() - }else{ - Option::some( Option::swap( op_e, e) ) - }; - r.insertion_index = ( r.insertion_index + 1 ) % Vector::length(&r.data); - r.external_index = r.external_index + 1; - res - } - - spec push{ - pragma verify = false; - } - - /// Return a reference to the `i`th element in the Ring `r`. - public fun borrow(r:& Ring, i: u64):&Option::Option{ - let len = capacity(r); - if( r.external_index > len - 1) { - assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow(&r.data, i % len) - }else { - assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow(&r.data, i ) - } - } - - spec borrow{ - pragma verify = false; - } - - /// Return a mutable reference to the `i`th element in the Ring `r`. - public fun borrow_mut(r: &mut Ring, i: u64):&mut Option::Option{ - let len = capacity(r); - if( r.external_index > len - 1) { - assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow_mut(&mut r.data, i % len) - }else { - assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow_mut(&mut r.data, i ) - } - - } - - spec borrow_mut{ - pragma verify = false; - } - - - /// Return `Option::Option` if `e` is in the Ring `r` at index `i`. - /// Otherwise, returns `Option::none`. - public fun index_of(r: &Ring, e: &Element):Option::Option{ - let i = 0; - let len = capacity(r); - while ( i < len ) { - if ( Option::borrow(Vector::borrow( &r.data, i )) == e) return Option::some(i + r.external_index - len); - i = i + 1; - }; - Option::none() - } - - spec index_of{ - pragma verify = false; - } - - /// Destroy the Ring `r`. - /// Returns the vector saved by ring - public fun destroy(r: Ring):vector{ - let Ring { - data : data , - insertion_index : _, - external_index : _, - } = r ; - let len = Vector::length(&data); - let i = 0; - let vec = Vector::empty(); - while ( i < len ) { - let op_e = Vector::pop_back( &mut data ); - if ( Option::is_some(&op_e) ) { - Vector::push_back(&mut vec, Option::destroy_some(op_e)) - }else { - Option::destroy_none(op_e) - }; - i = i + 1; - }; - Vector::destroy_empty(data); - vec - } - - spec destroy{ - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/SBTVoteStrategy.move b/release/v12/sources/SBTVoteStrategy.move deleted file mode 100644 index 8279771e..00000000 --- a/release/v12/sources/SBTVoteStrategy.move +++ /dev/null @@ -1,100 +0,0 @@ -module StarcoinFramework::SBTVoteStrategy{ - use StarcoinFramework::BCS; - #[test_only] - use StarcoinFramework::Debug; - use StarcoinFramework::Vector; - - const ERR_BCS_STATE_NTFS_LENGHT_TYPE_INVALID: u64 = 1413; - - /// deserialize snapshot vote value from state - public fun get_voting_power(state: &vector) : u128 { - let sbt_value = deserialize_sbt_value_from_bcs_state(state); - sbt_value - } - -// struct NFT has store { -// /// The creator of NFT -// creator: address, -// /// The unique id of NFT under NFTMeta type -// id: u64, -// /// The metadata of NFT -// base_meta: Metadata, -// /// The extension metadata of NFT -// type_meta: NFTMeta, -// /// The body of NFT, NFT is a box for NFTBody -// body: NFTBody, -// } -// -// struct Metadata has copy, store, drop { -// /// NFT name's utf8 bytes. -// name: vector, -// /// Image link, such as ipfs://xxxx -// image: vector, -// /// Image bytes data, image or image_data can not empty for both. -// image_data: vector, -// /// NFT description utf8 bytes. -// description: vector, -// } - - /// deserialize sbt value from bcs state - public fun deserialize_sbt_value_from_bcs_state(state: &vector) : u128{ - let len = Vector::length(state); - if (len == 0) { - return 0u128 - }; - - // nfts array length - let offset = 0; - let (nfts_len, offset) = BCS::deserialize_u8(state, offset); - // user has no sbt yet - if (nfts_len == 0) { - return 0u128 - }; - - offset = BCS::skip_address(state, offset); - offset = BCS::skip_u64(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_u64(state, offset); - let (value, _offset) = BCS::deserialize_u128(state, offset); - - value - } - - - #[test] - fun test_deserialize_sbt_value_from_bcs_state() { - // https://stcscan.io/barnard/address/0x6bfb460477adf9dd0455d3de2fc7f211/resources - // 0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>, 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - // {"json":{"nft":{"vec":[{"base_meta":{"description":"0x","image":"0x","image_data":"0x69616d67655f64617461","name":"0x64616f313031"},"body":{"sbt":{"value":100}},"creator":"0x6bfb460477adf9dd0455d3de2fc7f211","id":1,"type_meta":{"id":1111}}]}},"raw":"0x016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"} - let bs = x"016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"; - Debug::print>(&bs); - let offset = 0; - - // array length - offset = BCS::skip_u8(&bs, offset); - // creator - offset = BCS::skip_address(&bs, offset); - // id - offset = BCS::skip_u64(&bs, offset); - Debug::print(&offset); - // base_meta - offset = BCS::skip_bytes(&bs, offset); - offset = BCS::skip_bytes(&bs, offset); - offset = BCS::skip_bytes(&bs, offset); - offset = BCS::skip_bytes(&bs, offset); - // type_meta - offset = BCS::skip_u64(&bs, offset); - Debug::print(&offset); - // body - let (sbt_value, offset) = BCS::deserialize_u128(&bs, offset); - Debug::print(&sbt_value); - Debug::print(&offset); - let expect_sb_value = 100; - assert!(expect_sb_value == sbt_value, 8003); - Debug::print(&b"testdao02"); - } - -} \ No newline at end of file diff --git a/release/v12/sources/SIPs.move b/release/v12/sources/SIPs.move deleted file mode 100644 index effeb896..00000000 --- a/release/v12/sources/SIPs.move +++ /dev/null @@ -1,15 +0,0 @@ -address StarcoinFramework { -/// The modules define SIP. -/// Only the SIP that needs to do hard forked needs to be defined here, every SIP as a module, and can be a feature flag. - -/// https://github.com/starcoinorg/SIPs/tree/master/sip-2 -module SIP_2 { - -} - -/// https://github.com/starcoinorg/SIPs/tree/master/sip-3 -module SIP_3 { - -} - -} diff --git a/release/v12/sources/STC.move b/release/v12/sources/STC.move deleted file mode 100644 index 5307041f..00000000 --- a/release/v12/sources/STC.move +++ /dev/null @@ -1,120 +0,0 @@ -/// STC is the token of Starcoin blockchain. -/// It uses apis defined in the `Token` module. -module StarcoinFramework::STC { - use StarcoinFramework::Token::{Self, Token}; - use StarcoinFramework::Treasury; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// STC token marker. - struct STC has copy, drop, store {} - - /// precision of STC token. - const PRECISION: u8 = 9; - - /// Burn capability of STC. - struct SharedBurnCapability has key, store { - cap: Token::BurnCapability, - } - - /// STC initialization. - public fun initialize( - _account: &signer, - _voting_delay: u64, - _voting_period: u64, - _voting_quorum_rate: u8, - _min_action_delay: u64, - ) { - abort Errors::deprecated(1) - } - - spec initialize { - pragma verify = false; - } - - public fun upgrade_from_v1_to_v2(account: &signer, total_amount: u128, ): Treasury::WithdrawCapability { - CoreAddresses::assert_genesis_address(account); - - // Mint all stc, and destroy mint capability - let total_stc = Token::mint(account, total_amount - Token::market_cap()); - let withdraw_cap = Treasury::initialize(account, total_stc); - let mint_cap = Token::remove_mint_capability(account); - Token::destroy_mint_capability(mint_cap); - withdraw_cap - } - - spec upgrade_from_v1_to_v2 { - pragma verify = false; - } - - - /// STC initialization. - public fun initialize_v2( - _account: &signer, - _total_amount: u128, - _voting_delay: u64, - _voting_period: u64, - _voting_quorum_rate: u8, - _min_action_delay: u64, - ): Treasury::WithdrawCapability { - abort Errors::deprecated(1) - } - - spec initialize_v2 { - pragma verify = false; - } - - /// STC initialization. - public fun initialize_v3( - account: &signer, - total_amount: u128, - ): Treasury::WithdrawCapability { - Token::register_token(account, PRECISION); - - // Mint all stc, and destroy mint capability - - let total_stc = Token::mint(account, total_amount); - let withdraw_cap = Treasury::initialize(account, total_stc); - let mint_cap = Token::remove_mint_capability(account); - Token::destroy_mint_capability(mint_cap); - - let burn_cap = Token::remove_burn_capability(account); - move_to(account, SharedBurnCapability { cap: burn_cap }); - withdraw_cap - } - - spec initialize_v3 { - include Token::RegisterTokenAbortsIf { precision: PRECISION }; - } - - /// Returns true if `TokenType` is `STC::STC` - public fun is_stc(): bool { - Token::is_same_token() - } - - spec is_stc {} - - /// Burn STC tokens. - /// It can be called by anyone. - public fun burn(token: Token) acquires SharedBurnCapability { - let cap = borrow_global(token_address()); - Token::burn_with_capability(&cap.cap, token); - } - - spec burn { - aborts_if Token::spec_abstract_total_value() - token.value < 0; - aborts_if !exists(Token::SPEC_TOKEN_TEST_ADDRESS()); - } - - /// Return STC token address. - public fun token_address(): address { - Token::token_address() - } - - spec token_address {} -} \ No newline at end of file diff --git a/release/v12/sources/SharedEd25519PublicKey.move b/release/v12/sources/SharedEd25519PublicKey.move deleted file mode 100644 index 9b513d06..00000000 --- a/release/v12/sources/SharedEd25519PublicKey.move +++ /dev/null @@ -1,110 +0,0 @@ -address StarcoinFramework { -/// Each address that holds a `SharedEd25519PublicKey` resource can rotate the public key stored in -/// this resource, but the account's authentication key will be updated in lockstep. This ensures -/// that the two keys always stay in sync. -module SharedEd25519PublicKey { - use StarcoinFramework::Authenticator; - use StarcoinFramework::Account; - use StarcoinFramework::Signature; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// A resource that forces the account associated with `rotation_cap` to use a ed25519 - /// authentication key derived from `key` - struct SharedEd25519PublicKey has key { - /// 32 byte ed25519 public key - key: vector, - /// rotation capability for an account whose authentication key is always derived from `key` - rotation_cap: Account::KeyRotationCapability, - } - - const EMALFORMED_PUBLIC_KEY: u64 = 101; - - /// (1) Rotate the authentication key of the sender to `key` - /// (2) Publish a resource containing a 32-byte ed25519 public key and the rotation capability - /// of the sender under the `account`'s address. - /// Aborts if the sender already has a `SharedEd25519PublicKey` resource. - /// Aborts if the length of `new_public_key` is not 32. - public fun publish(account: &signer, key: vector) { - let t = SharedEd25519PublicKey { - key: x"", - rotation_cap: Account::extract_key_rotation_capability(account) - }; - rotate_key_(&mut t, key); - move_to(account, t); - } - - spec publish { - aborts_if !exists(Signer::address_of(account)); - aborts_if StarcoinFramework::Option::is_none(global(Signer::address_of(account)).key_rotation_capability); - aborts_if !exists( - StarcoinFramework::Option::borrow( - global(Signer::address_of(account)) - .key_rotation_capability - ).account_address); - aborts_if !Signature::ed25519_validate_pubkey(key); - aborts_if exists(Signer::address_of(account)); - aborts_if len(Authenticator::spec_ed25519_authentication_key(key)) != 32; - } - - fun rotate_key_(shared_key: &mut SharedEd25519PublicKey, new_public_key: vector) { - // Cryptographic check of public key validity - assert!( - Signature::ed25519_validate_pubkey(copy new_public_key), - Errors::invalid_argument(EMALFORMED_PUBLIC_KEY) - ); - Account::rotate_authentication_key_with_capability( - &shared_key.rotation_cap, - Authenticator::ed25519_authentication_key(copy new_public_key) - ); - shared_key.key = new_public_key; - } - - spec rotate_key_ { - aborts_if !exists(shared_key.rotation_cap.account_address); - aborts_if !Signature::ed25519_validate_pubkey(new_public_key); - aborts_if len(Authenticator::spec_ed25519_authentication_key(new_public_key)) != 32; - } - - /// (1) rotate the public key stored `account`'s `SharedEd25519PublicKey` resource to - /// `new_public_key` - /// (2) rotate the authentication key using the capability stored in the `account`'s - /// `SharedEd25519PublicKey` to a new value derived from `new_public_key` - /// Aborts if the sender does not have a `SharedEd25519PublicKey` resource. - /// Aborts if the length of `new_public_key` is not 32. - public fun rotate_key(account: &signer, new_public_key: vector) acquires SharedEd25519PublicKey { - rotate_key_(borrow_global_mut(Signer::address_of(account)), new_public_key); - } - - spec rotate_key { - aborts_if !exists(Signer::address_of(account)); - aborts_if !exists(global(Signer::address_of(account)).rotation_cap.account_address); - aborts_if !Signature::ed25519_validate_pubkey(new_public_key); - aborts_if len(Authenticator::spec_ed25519_authentication_key(new_public_key)) != 32; - } - - /// Return the public key stored under `addr`. - /// Aborts if `addr` does not hold a `SharedEd25519PublicKey` resource. - public fun key(addr: address): vector acquires SharedEd25519PublicKey { - *&borrow_global(addr).key - } - - spec key { - aborts_if !exists(addr); - } - - /// Returns true if `addr` holds a `SharedEd25519PublicKey` resource. - public fun exists_at(addr: address): bool { - exists(addr) - } - - spec exists_at { - aborts_if false; - } -} -} diff --git a/release/v12/sources/Signature.move b/release/v12/sources/Signature.move deleted file mode 100644 index 044636e4..00000000 --- a/release/v12/sources/Signature.move +++ /dev/null @@ -1,131 +0,0 @@ -address StarcoinFramework { - -/// Contains functions for [ed25519](https://en.wikipedia.org/wiki/EdDSA) digital signatures. -module Signature { - - use StarcoinFramework::Vector; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::EVMAddress::{Self, EVMAddress}; - - native public fun ed25519_validate_pubkey(public_key: vector): bool; - native public fun ed25519_verify(signature: vector, public_key: vector, message: vector): bool; - - /// recover address from ECDSA signature, if recover fail, return an empty vector - native fun native_ecrecover(hash: vector, signature: vector): vector; - - /// recover address from ECDSA signature, if recover fail, return None - public fun ecrecover(hash: vector, signature: vector):Option{ - let bytes = native_ecrecover(hash, signature); - if (Vector::is_empty(&bytes)){ - Option::none() - }else{ - Option::some(EVMAddress::new(bytes)) - } - } - - // verify eth secp256k1 sign and compare addr, if add equal return true - public fun secp256k1_verify(signature: vector, addr: vector, message: vector) : bool{ - let receover_address_opt:Option = ecrecover(message, signature); - let expect_address = EVMAddress::new(addr); - &Option::destroy_some(receover_address_opt) == &expect_address - } - - spec module { - pragma intrinsic = true; - } - - #[test] - fun test_ecrecover_invalid(){ - let h = b"00"; - let s = b"00"; - let addr = ecrecover(h, s); - assert!(Option::is_none(&addr), 1001); - } -} - -module EVMAddress{ - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - use StarcoinFramework::Vector; - - const EVM_ADDR_LENGTH:u64 = 20; - - struct EVMAddress has copy, store, drop{ - bytes: vector, - } - - /// Create EVMAddress from bytes, If bytes is larger than EVM_ADDR_LENGTH(20), bytes will be cropped from the left. - /// keep same as https://github.com/ethereum/go-ethereum/blob/master/common/types.go#L302 - public fun new(bytes: vector): EVMAddress{ - let len = Vector::length(&bytes); - let bytes = if (len > EVM_ADDR_LENGTH){ - let new_bytes = Vector::empty(); - let i = 0; - while (i < EVM_ADDR_LENGTH) { - Vector::push_back(&mut new_bytes, *Vector::borrow(&bytes, i)); - i = i + 1; - }; - new_bytes - }else if (len == EVM_ADDR_LENGTH){ - bytes - }else{ - let i = 0; - let new_bytes = Vector::empty(); - while (i < EVM_ADDR_LENGTH - len) { - // pad zero to address - Vector::push_back(&mut new_bytes, 0); - i = i + 1; - }; - Vector::append(&mut new_bytes, bytes); - new_bytes - }; - EVMAddress{ - bytes - } - } - - spec new { - pragma verify = false; - //TODO - } - - /// Get the inner bytes of the `addr` as a reference - public fun as_bytes(addr: &EVMAddress): &vector { - &addr.bytes - } - - spec as_bytes { - pragma verify = false; - //TODO - } - - /// Unpack the `addr` to get its backing bytes - public fun into_bytes(addr: EVMAddress): vector { - let EVMAddress { bytes } = addr; - bytes - } - - spec into_bytes { - pragma verify = false; - //TODO - } - - #[test] - fun test_evm_address_padding(){ - let addr1 = new(x"00"); - let addr2 = new(x"0000"); - assert!(&addr1.bytes == &addr2.bytes, 1001); - } - - #[test] - fun test_evm_address_crop(){ - let addr1 = new(x"01234567890123456789012345678901234567891111"); - let addr2 = new(x"01234567890123456789012345678901234567892222"); - assert!(&addr1.bytes == &addr2.bytes, 1001); - } -} -} diff --git a/release/v12/sources/SignedInteger64.move b/release/v12/sources/SignedInteger64.move deleted file mode 100644 index 5258cc78..00000000 --- a/release/v12/sources/SignedInteger64.move +++ /dev/null @@ -1,109 +0,0 @@ -address StarcoinFramework { -/// Implementation of i64. -module SignedInteger64 { - - /// Define a signed integer type with two 32 bits. - struct SignedInteger64 has copy, drop, store { - value: u64, - is_negative: bool, - } - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// Multiply a u64 integer by a signed integer number. - public fun multiply_u64(num: u64, multiplier: SignedInteger64): SignedInteger64 { - let product = multiplier.value * num; - SignedInteger64 { value: product, is_negative: multiplier.is_negative } - } - - /// Divide a u64 integer by a signed integer number. - public fun divide_u64(num: u64, divisor: SignedInteger64): SignedInteger64 { - let quotient = num / divisor.value; - SignedInteger64 { value: quotient, is_negative: divisor.is_negative } - } - - /// Sub: `num - minus` - public fun sub_u64(num: u64, minus: SignedInteger64): SignedInteger64 { - if (minus.is_negative) { - let result = num + minus.value; - SignedInteger64 { value: result, is_negative: false } - } else { - if (num >= minus.value) { - let result = num - minus.value; - SignedInteger64 { value: result, is_negative: false } - }else { - let result = minus.value - num; - SignedInteger64 { value: result, is_negative: true } - } - } - } - - /// Add: `num + addend` - public fun add_u64(num: u64, addend: SignedInteger64): SignedInteger64 { - if (addend.is_negative) { - if (num >= addend.value) { - let result = num - addend.value; - SignedInteger64 { value: result, is_negative: false } - }else { - let result = addend.value - num; - SignedInteger64 { value: result, is_negative: true } - } - } else { - let result = num + addend.value; - SignedInteger64 { value: result, is_negative: false } - } - } - - /// Create a signed integer value from a unsigned integer - public fun create_from_raw_value(value: u64, is_negative: bool): SignedInteger64 { - SignedInteger64 { value, is_negative } - } - - /// Get value part of i64 ignore sign part. - public fun get_value(num: SignedInteger64): u64 { - num.value - } - - /// Check if the given num is negative. - public fun is_negative(num: SignedInteger64): bool { - num.is_negative - } - - // **************** SPECIFICATIONS **************** - - spec multiply_u64 { - aborts_if multiplier.value * num > max_u64(); - } - - spec divide_u64 { - aborts_if divisor.value == 0; - } - - spec sub_u64 { - aborts_if minus.is_negative && num + minus.value > max_u64(); - } - - spec add_u64 { - aborts_if !addend.is_negative && num + addend.value > max_u64(); - } - - spec create_from_raw_value { - aborts_if false; - ensures result == SignedInteger64 { value, is_negative }; - } - - spec get_value { - aborts_if false; - ensures result == num.value; - } - - spec is_negative { - aborts_if false; - ensures result == num.is_negative; - } - -} -} diff --git a/release/v12/sources/Signer.move b/release/v12/sources/Signer.move deleted file mode 100644 index 47ec53be..00000000 --- a/release/v12/sources/Signer.move +++ /dev/null @@ -1,28 +0,0 @@ -address StarcoinFramework { -/// Provide access methods for Signer. -module Signer { - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - /// Borrows the address of the signer - /// Conceptually, you can think of the `signer` as being a resource struct wrapper around an - /// address - /// ``` - /// resource struct Signer has key, store { addr: address } - /// ``` - /// `borrow_address` borrows this inner field - native public fun borrow_address(s: &signer): &address; - - /// Copies the address of the signer - public fun address_of(s: &signer): address { - *borrow_address(s) - } - - spec address_of { - pragma opaque = true; - aborts_if false; - ensures result == address_of(s); - } -} -} diff --git a/release/v12/sources/SimpleMap.move b/release/v12/sources/SimpleMap.move deleted file mode 100644 index 8a8df0c1..00000000 --- a/release/v12/sources/SimpleMap.move +++ /dev/null @@ -1,229 +0,0 @@ -/// This module provides a solution for sorted maps, that is it has the properties that -/// 1) Keys point to Values -/// 2) Each Key must be unique -/// 3) A Key can be found within O(Log N) time -/// 4) The data is stored as sorted by Key -/// 5) Adds and removals take O(N) time -module StarcoinFramework::SimpleMap { - - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::Compare; - use StarcoinFramework::BCS; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Map key already exists - const EKEY_ALREADY_EXISTS: u64 = 1; - /// Map key is not found - const EKEY_NOT_FOUND: u64 = 2; - - struct SimpleMap has copy, drop, store { - data: vector>, - } - - struct Element has copy, drop, store { - key: Key, - value: Value, - } - - public fun length(map: &SimpleMap): u64 { - Vector::length(&map.data) - } - - public fun create(): SimpleMap { - SimpleMap { - data: Vector::empty(), - } - } - - public fun borrow( - map: &SimpleMap, - key: &Key, - ): &Value { - let (maybe_idx, _) = find(map, key); - assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND)); - let idx = Option::extract(&mut maybe_idx); - &Vector::borrow(&map.data, idx).value - } - - public fun borrow_mut( - map: &mut SimpleMap, - key: &Key, - ): &mut Value { - let (maybe_idx, _) = find(map, key); - assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND)); - let idx = Option::extract(&mut maybe_idx); - &mut Vector::borrow_mut(&mut map.data, idx).value - } - - public fun contains_key( - map: &SimpleMap, - key: &Key, - ): bool { - let (maybe_idx, _) = find(map, key); - Option::is_some(&maybe_idx) - } - - public fun destroy_empty(map: SimpleMap) { - let SimpleMap { data } = map; - Vector::destroy_empty(data); - } - - public fun add( - map: &mut SimpleMap, - key: Key, - value: Value, - ) { - let (maybe_idx, maybe_placement) = find(map, &key); - assert!(Option::is_none(&maybe_idx), Errors::invalid_argument(EKEY_ALREADY_EXISTS)); - - // Append to the end and then swap elements until the list is ordered again - Vector::push_back(&mut map.data, Element { key, value }); - - let placement = Option::extract(&mut maybe_placement); - let end = Vector::length(&map.data) - 1; - while (placement < end) { - Vector::swap(&mut map.data, placement, end); - placement = placement + 1; - }; - } - - public fun remove( - map: &mut SimpleMap, - key: &Key, - ): (Key, Value) { - let (maybe_idx, _) = find(map, key); - assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND)); - - let placement = Option::extract(&mut maybe_idx); - let end = Vector::length(&map.data) - 1; - - while (placement < end) { - Vector::swap(&mut map.data, placement, placement + 1); - placement = placement + 1; - }; - - let Element { key, value } = Vector::pop_back(&mut map.data); - (key, value) - } - - fun find( - map: &SimpleMap, - key: &Key, - ): (Option::Option, Option::Option) { - let length = Vector::length(&map.data); - - if (length == 0) { - return (Option::none(), Option::some(0)) - }; - - let left = 0; - let right = length; - - while (left != right) { - let mid = left + (right - left) / 2; - let potential_key = &Vector::borrow(&map.data, mid).key; - if (Compare::is_less_than(Compare::cmp_bytes(&BCS::to_bytes(potential_key), &BCS::to_bytes(key)))) { - left = mid + 1; - } else { - right = mid; - }; - }; - - if (left != length && key == &Vector::borrow(&map.data, left).key) { - (Option::some(left), Option::none()) - } else { - (Option::none(), Option::some(left)) - } - } - - #[test] - public fun add_remove_many() { - let map = create(); - - assert!(length(&map) == 0, 0); - assert!(!contains_key(&map, &3), 1); - add(&mut map, 3, 1); - assert!(length(&map) == 1, 2); - assert!(contains_key(&map, &3), 3); - assert!(borrow(&map, &3) == &1, 4); - *borrow_mut(&mut map, &3) = 2; - assert!(borrow(&map, &3) == &2, 5); - - assert!(!contains_key(&map, &2), 6); - add(&mut map, 2, 5); - assert!(length(&map) == 2, 7); - assert!(contains_key(&map, &2), 8); - assert!(borrow(&map, &2) == &5, 9); - *borrow_mut(&mut map, &2) = 9; - assert!(borrow(&map, &2) == &9, 10); - - remove(&mut map, &2); - assert!(length(&map) == 1, 11); - assert!(!contains_key(&map, &2), 12); - assert!(borrow(&map, &3) == &2, 13); - - remove(&mut map, &3); - assert!(length(&map) == 0, 14); - assert!(!contains_key(&map, &3), 15); - - destroy_empty(map); - } - - #[test] - public fun test_several() { - let map = create(); - add(&mut map, 6, 6); - add(&mut map, 1, 1); - add(&mut map, 5, 5); - add(&mut map, 2, 2); - add(&mut map, 3, 3); - add(&mut map, 0, 0); - add(&mut map, 7, 7); - add(&mut map, 4, 4); - - let idx = 0; - while (idx < Vector::length(&map.data)) { - assert!(idx == Vector::borrow(&map.data, idx).key, idx); - idx = idx + 1; - }; - - remove(&mut map, &0); - remove(&mut map, &1); - remove(&mut map, &2); - remove(&mut map, &3); - remove(&mut map, &4); - remove(&mut map, &5); - remove(&mut map, &6); - remove(&mut map, &7); - - destroy_empty(map); - } - - #[test] - #[expected_failure] - public fun add_twice() { - let map = create(); - add(&mut map, 3, 1); - add(&mut map, 3, 1); - - remove(&mut map, &3); - destroy_empty(map); - } - - #[test] - #[expected_failure] - public fun remove_twice() { - let map = create(); - add(&mut map, 3, 1); - remove(&mut map, &3); - remove(&mut map, &3); - - destroy_empty(map); - } -} diff --git a/release/v12/sources/SnapshotUtil.move b/release/v12/sources/SnapshotUtil.move deleted file mode 100644 index 0bef2789..00000000 --- a/release/v12/sources/SnapshotUtil.move +++ /dev/null @@ -1,393 +0,0 @@ -module StarcoinFramework::SnapshotUtil{ - #[test_only] - use StarcoinFramework::Option; - use StarcoinFramework::Token; - #[test_only] - use StarcoinFramework::Debug; - use StarcoinFramework::Vector; - use StarcoinFramework::BCS; - - #[test] - fun test_snapshot_proof_deserialize() { - // barnard, block number 6201718 - let snpashot_raw_proofs = x"0145016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f64617461005704000000000000640000000000000000000000000000000145020120cc969848619e507450ebf01437155ab5f2dbb554fe611cb71958855a1b2ec664012035f2374c333a51e46b62b693ebef25b9be2cefde8d156db08bff28f9a0b87742012073837fcf4e69ae60e18ea291b9f25c86ce8053c6ee647a2b287083327c67dd7e20dac300fb581a6df034a44a99e8eb1cd55c7dd8f0a9e78f1114a6b4eda01d834e0e2078179a07914562223d40068488a0d65673b3b2681642633dc33904575f8f070b20b7c2a21de200ca82241e5e480e922258591b219dd56c24c4d94299020ee8299a204f541db82477510f699c9d75dd6d8280639a1ec9d0b90962cbc0c2b06514a78b20cacfce99bb564cfb70eec6a61bb76b9d56eb1b626d7fa231338792e1f572a8df20da6c1337ca5d8f0fa18b2db35844c610858a710edac35206ef0bf52fd32a4ac920ef6fb8f82d32ca2b7c482b7942505e6492bffa3ed14dd635bae16a14b4ac32e6202ad7b36e08e7b5d208de8eec1ef1964dc8433ccca8ac4632f36054926e858ac32027d5ccc8aa57b964ad50334f62821188b89945ae999ad0bb31cdc16df1763f8120afa983813953d6aa9563db12d5e443c9e8114c3482867c95a661a240d6f0e0ec206466ac318f5d9deb7b64b12622a0f4bed2f19379667d18b6ccfeaa84171d812f20eb45021b7b39887925a5b49018cdc8ad44c14835a42e5775666315f4a3e0ba42204c2b365a78e4615873772a0f039a7326150472b4923d40640863dbe42a2351eb20825d0c21dd1105faf528934842419f8661d695fc72ec6ef8036f5d03359126d3205d806c027eecdfbc3960e68c5997718a0709a6079f96e1af3ffe21878ada2b830120fa60f8311936961f5e9dee5ccafaea83ed91c6eaa04a7dea0b85a38cf84d8564207ef6a85019523861474cdf47f4db8087e5368171d95cc2c1e57055a72ca39cb704208db1e4e4c864882bd611b1cda02ca30c43b3c7bc56ee7cb174598188da8b49ef2063b3f1e4f05973830ba40e0c50c4e59f31d3baa5643d19676ddbacbf797bf6b720b39d31107837c1751d439706c8ddac96f8c148b8430ac4f40546f33fb9871e4320fb0ad035780bb8f1c6481bd674ccad0948cd2e8e6b97c08e582f67cc26918fb3"; - // let state_root = x"d5cd5dc44799c989a84b7d4a810259f373b13a9bf8ee21ecbed0fab264e2090d"; - // let account_address = @0x6bfb460477adf9dd0455d3de2fc7f211; - // // 0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - // let resource_struct_tag = x"00000000000000000000000000000001074163636f756e740742616c616e636501078c109349c6bd91411d6bc962e080c4a30453544152045354415200"; - - let offset = 0; - let (state_option, offset) = BCS::deserialize_option_bytes(&snpashot_raw_proofs, offset); - let state = Option::get_with_default(&mut state_option, Vector::empty()); - Debug::print(&state); -// Debug::print(&x"016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"); - Debug::print(&offset); - let (_account_state_option, offset) = BCS::deserialize_option_bytes(&snpashot_raw_proofs, offset); - let _account_state = Option::get_with_default(&mut _account_state_option, Vector::empty()); - Debug::print(&110110); - Debug::print(&_account_state); - Debug::print(&offset); - - let (_account_proof_leaf1_option, _account_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(&snpashot_raw_proofs, offset); - let _account_proof_leaf1 = Option::get_with_default(&mut _account_proof_leaf1_option, Vector::empty()); - let _account_proof_leaf2 = Option::get_with_default(&mut _account_proof_leaf2_option, Vector::empty()); - Debug::print(&offset); - - let account_proof_leaf_nodes = Vector::empty>(); - Vector::push_back(&mut account_proof_leaf_nodes, x"73837fcf4e69ae60e18ea291b9f25c86ce8053c6ee647a2b287083327c67dd7e"); - Vector::push_back(&mut account_proof_leaf_nodes, x"dac300fb581a6df034a44a99e8eb1cd55c7dd8f0a9e78f1114a6b4eda01d834e"); - Debug::print(&account_proof_leaf_nodes); - Debug::print(&_account_proof_leaf1); - Debug::print(&_account_proof_leaf2); - Debug::print(&offset); - let (_account_proof_siblings, offset) = BCS::deserialize_bytes_vector(&snpashot_raw_proofs, offset); - - let (_account_state_proof_leaf1_option, _account_state_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(&snpashot_raw_proofs, offset); - let _account_state_proof_leaf1 = Option::get_with_default(&mut _account_state_proof_leaf1_option, Vector::empty()); - let _account_state_proof_leaf2 = Option::get_with_default(&mut _account_state_proof_leaf2_option, Vector::empty()); - Debug::print(&_account_state_proof_leaf1); - Debug::print(&_account_state_proof_leaf2); - let (_account_state_proof_siblings, _offset) = BCS::deserialize_bytes_vector(&snpashot_raw_proofs, offset); - - Debug::print(&_account_state_proof_siblings); - Debug::print(&_offset); - } - - #[test] - fun test_snapshot_proof_deserialize_with_empty_state() { - let snpashot_raw_proofs = x"00012402000120161d07d221d7b31df7d29d45926b6444fa07e8b5f1021dd704fc1def6738011d0120e76e5b4bcf07c7e3864b399cfca72b0863678487813a1cfe8df48cf35729def820f135bf4b03034b8a3c21950231d3c4fe8136442064c9809d593e78ed4775f0b6042072659a01138c59e84e8e608e0d1908be7289c47f8f4080a14eaa852d1ace35f420bb3f0cc0cde2e05ba56a26bbc15161a930af6f66a65091b285870c557e8bc07a205350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000204bb30b63b4c41126a2f8c98a3d66f351160732481ae633da47d647976004942e000420fbd31ef1cbaf26c37259325e5ee71625e67f7ecf8311cbf67758431d65ae8f5c205350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000207460a35efdba40ce6ec4442b32e0bf39fee59a69887e18f118f49b325434fda820417ddaf2cf3fce9b50dd9b16e1ea545d65d480b855bfd0aed0a819a6a7d0f641"; - - let offset = 0; - let (state_option, offset) = BCS::deserialize_option_bytes(&snpashot_raw_proofs, offset); - Debug::print(&state_option); - let state = Option::get_with_default(&mut state_option, Vector::empty()); - Debug::print(&state); - Debug::print(&offset); - } - - /// Struct Tag which identify a unique Struct. - struct StructTag0 has drop,copy,store { - addr: address, - module_name: vector, - name: vector, - types: vector, - } - - struct TypeTag0 has drop,copy,store { - variant_index: u8, // struct type tag variant index, must set be 7 - struct_tag: StructTag0, - } - - struct StructTag1 has drop,copy,store { - addr: address, - module_name: vector, - name: vector, - types: vector, - } - - struct TypeTag1 has drop,copy,store { - variant_index: u8, // struct type tag variant index, must set be 7 - struct_tag: StructTag1, - } - - struct StructTag2 has drop,copy,store { - addr: address, - module_name: vector, - name: vector, - types: vector, - } - - public fun get_sturct_tag(): vector { - let struct_tags = generate_struct_tag(); - BCS::to_bytes(&struct_tags) - } - - // 0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>, 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - fun generate_struct_tag(): StructTag2{ - let dao_struct_tag = get_dao_struct_tag(); - let dao_type_tag = TypeTag0 { - variant_index: 7, - struct_tag: dao_struct_tag, - }; - let dao_type_tags = Vector::empty(); - Vector::push_back(&mut dao_type_tags, dao_type_tag); - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember - let dao_member_struct_tag = StructTag1 { - addr: @0x00000000000000000000000000000001, - module_name: b"DAOSpace", - name: b"DAOMember", - types: *&dao_type_tags - }; - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody - let dao_member_body_struct_tag = StructTag1 { - addr: @0x00000000000000000000000000000001, - module_name: b"DAOSpace", - name: b"DAOMemberBody", - types: *&dao_type_tags - }; - - let dao_member_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_struct_tag, - }; - let dao_member_body_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_body_struct_tag, - }; - let type_tags = Vector::empty(); - Vector::push_back(&mut type_tags, dao_member_type_tag); - Vector::push_back(&mut type_tags, dao_member_body_type_tag); - - StructTag2 { - addr: @0x00000000000000000000000000000001, - module_name: b"IdentifierNFT", - name: b"IdentifierNFT", - types: type_tags, - } - } - - fun get_dao_struct_tag(): StructTag0{ - // DAOT is also TokenT - let token_code = Token::token_code(); - let token_code_bcs = BCS::to_bytes(&token_code); - - let offset = 0; - let (address, offset) = BCS::deserialize_address(&token_code_bcs, offset); - let (module_name, offset) = BCS::deserialize_bytes(&token_code_bcs, offset); - let (name, _offset) = BCS::deserialize_bytes(&token_code_bcs, offset); - - StructTag0 { - addr: address, - module_name, - name, - types: Vector::empty(), - } - } - - #[test] - fun test_get_sturct_tag_bcs() { - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO - let dao_struct_tag = StructTag0 { - addr: @0x6bfb460477adf9dd0455d3de2fc7f211, - module_name: b"SBTModule", - name: b"SbtTestDAO", - types: Vector::empty(), - }; - - let dao_type_tag = TypeTag0 { - variant_index: 7, - struct_tag: dao_struct_tag, - }; - let dao_type_tags = Vector::empty(); - Vector::push_back(&mut dao_type_tags, dao_type_tag); - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember - let dao_member_struct_tag = StructTag1 { - addr: @0x6bfb460477adf9dd0455d3de2fc7f211, - module_name: b"SBTModule", - name: b"DAOMember", - types: *&dao_type_tags - }; - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody - let dao_member_body_struct_tag = StructTag1 { - addr: @0x6bfb460477adf9dd0455d3de2fc7f211, - module_name: b"SBTModule", - name: b"DAOMemberBody", - types: *&dao_type_tags - }; - - let dao_member_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_struct_tag, - }; - let dao_member_body_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_body_struct_tag, - }; - let type_tags = Vector::empty(); - Vector::push_back(&mut type_tags, dao_member_type_tag); - Vector::push_back(&mut type_tags, dao_member_body_type_tag); - - let struct_tags = StructTag2 { - addr: @0x00000000000000000000000000000001, - module_name: b"IdentifierNFT", - name: b"IdentifierNFT", - types: type_tags, - }; - - let resource_struct_tags = BCS::to_bytes(&struct_tags); - Debug::print(&resource_struct_tags); - let expect_resource_struct_tags = x"000000000000000000000000000000010d4964656e7469666965724e46540d4964656e7469666965724e465402076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650944414f4d656d62657201076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650d44414f4d656d626572426f647901076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00"; - Debug::print(&expect_resource_struct_tags); - - Debug::print(&b"IdentifierNFT"); - Debug::print(&x"6bfb460477adf9dd0455d3de2fc7f211"); - Debug::print(&b"SBTModule"); - Debug::print(&b"DAOMember"); - Debug::print(&b"DAOMemberBody"); - - assert!(expect_resource_struct_tags == resource_struct_tags, 8010); - } - - // "0x6bfb460477adf9dd0455d3de2fc7f211/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>,0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>>" - public fun get_access_path(user_addr: address): vector { - - // 0x6bfb460477adf9dd0455d3de2fc7f211/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT< - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO> - // ,0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - - let access_path_slice_0 = b"/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT"; - let access_path_bytes = Vector::empty(); - Vector::append(&mut access_path_bytes, address_to_hex_string(*&user_addr)); - Vector::append(&mut access_path_bytes, access_path_slice_0); - Vector::append(&mut access_path_bytes, b"<"); - Vector::append(&mut access_path_bytes, get_access_path_dao_member_slice()); - Vector::append(&mut access_path_bytes, b","); - Vector::append(&mut access_path_bytes, get_access_path_dao_member_body_slice()); - Vector::append(&mut access_path_bytes, b">"); - - access_path_bytes - } - - #[test] - fun test_get_access_path(){ - let user_addr = @0x6bfb460477adf9dd0455d3de2fc7f211; - - let module_addr = @0x6bfb460477adf9dd0455d3de2fc7f211; - let struct_tag_slice = Vector::empty(); - Vector::append(&mut struct_tag_slice, address_to_hex_string(*&module_addr)); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, b"SBTModule"); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, b"SbtTestDAO"); - - - let dao_member_slice_0 = b"0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember"; - let dao_member_slice = Vector::empty(); - Vector::append(&mut dao_member_slice, dao_member_slice_0); - Vector::append(&mut dao_member_slice, b"<"); - Vector::append(&mut dao_member_slice, copy struct_tag_slice); - Vector::append(&mut dao_member_slice, b">"); - - let dao_member_body_slice_0 = b"0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody"; - let dao_member_body_slice = Vector::empty(); - Vector::append(&mut dao_member_body_slice, dao_member_body_slice_0); - Vector::append(&mut dao_member_body_slice, b"<"); - Vector::append(&mut dao_member_body_slice, copy struct_tag_slice); - Vector::append(&mut dao_member_body_slice, b">"); - - - - let access_path_slice_0 = b"/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT"; - let access_path_bytes = Vector::empty(); - Vector::append(&mut access_path_bytes, address_to_hex_string(*&user_addr)); - Vector::append(&mut access_path_bytes, access_path_slice_0); - Vector::append(&mut access_path_bytes, b"<"); - Vector::append(&mut access_path_bytes, dao_member_slice); - Vector::append(&mut access_path_bytes, b","); - Vector::append(&mut access_path_bytes, dao_member_body_slice); - Vector::append(&mut access_path_bytes, b">"); - - let expect_access_path = b"0x6bfb460477adf9dd0455d3de2fc7f211/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>,0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>>"; - Debug::print(&expect_access_path); - Debug::print(&access_path_bytes); - assert!(expect_access_path == access_path_bytes, 8012); - } - - - fun get_access_path_dao_member_slice(): vector{ - let dao_member_slice_0 = b"0x00000000000000000000000000000001::DAOSpace::DAOMember"; - let slice = Vector::empty(); - Vector::append(&mut slice, dao_member_slice_0); - Vector::append(&mut slice, b"<"); - Vector::append(&mut slice, struct_tag_to_string()); - Vector::append(&mut slice, b">"); - - slice - } - - - fun get_access_path_dao_member_body_slice(): vector{ - let dao_member_body_slice_0 = b"0x00000000000000000000000000000001::DAOSpace::DAOMemberBody"; - let slice = Vector::empty(); - Vector::append(&mut slice, dao_member_body_slice_0); - Vector::append(&mut slice, b"<"); - Vector::append(&mut slice, struct_tag_to_string()); - Vector::append(&mut slice, b">"); - - slice - } - - fun struct_tag_to_string(): vector { - let struct_tag = get_dao_struct_tag(); - let struct_tag_slice = Vector::empty(); - Vector::append(&mut struct_tag_slice, address_to_hex_string(*&struct_tag.addr)); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, *&struct_tag.module_name); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, *&struct_tag.name); - - struct_tag_slice - } - - const HEX_SYMBOLS: vector = b"0123456789abcdef"; - - /// Converts a `u8` to its hexadecimal representation with fixed length (in whole bytes). - /// so the returned String is `2 * length` in size - public fun to_hex_string_without_prefix(value: u8): vector { - if (value == 0) { - return b"00" - }; - - let buffer = Vector::empty(); - let len = 1; - let i: u64 = 0; - while (i < len * 2) { - Vector::push_back(&mut buffer, *Vector::borrow(&HEX_SYMBOLS, (value & 0xf as u64))); - value = value >> 4; - i = i + 1; - }; - assert!(value == 0, 1); - Vector::reverse(&mut buffer); - buffer - } - - /// Converts a `address` to its hexadecimal representation with fixed length (in whole bytes). - /// so the returned String is `2 * length + 2`(with '0x') in size - fun address_to_hex_string(addr: address): vector{ - let hex_string = Vector::empty(); - Vector::append(&mut hex_string, b"0x"); - let addr_bytes = BCS::to_bytes
(&addr); - let i = 0; - let len = Vector::length(&addr_bytes); - while (i < len) { - let hex_slice = to_hex_string_without_prefix(*Vector::borrow(&addr_bytes, i)); - Vector::append(&mut hex_string, hex_slice); - i = i + 1; - }; - hex_string - } - - #[test] - fun test_address_to_byte(){ - let user_addr = @0x6bfb460477adf9dd0455d3de2fc7f211; - let user_addr_b = b"0x6bfb460477adf9dd0455d3de2fc7f211"; - let user_addr_hex = address_to_hex_string(user_addr); - Debug::print(&user_addr); - Debug::print(&user_addr_b); - Debug::print(&user_addr_hex); - - let str1 = b"0x6bfb460477adf9dd0455d3de2fc7f211/1/"; - let str2 = Vector::empty(); - Vector::append(&mut str2, user_addr_hex); - Vector::append(&mut str2, b"/1/"); - Debug::print(&str1); - Debug::print(&str2); - assert!(str1 == str2, 8013) - } - - -} \ No newline at end of file diff --git a/release/v12/sources/StakeToSBTPlugin.move b/release/v12/sources/StakeToSBTPlugin.move deleted file mode 100644 index 0cf1b71d..00000000 --- a/release/v12/sources/StakeToSBTPlugin.move +++ /dev/null @@ -1,605 +0,0 @@ -module StarcoinFramework::StakeToSBTPlugin { - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Vector; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::InstallPluginProposalPlugin; - - const ERR_PLUGIN_USER_IS_MEMBER: u64 = 1001; - const ERR_PLUGIN_HAS_STAKED: u64 = 1002; - const ERR_PLUGIN_NOT_STAKE: u64 = 1003; - const ERR_PLUGIN_STILL_LOCKED: u64 = 1004; - const ERR_PLUGIN_CONFIG_INIT_REPEATE: u64 = 1005; - const ERR_PLUGIN_ITEM_CANT_FOUND: u64 = 1006; - const ERR_PLUGIN_NO_MATCH_LOCKTIME: u64 = 1007; - - struct StakeToSBTPlugin has store, drop {} - - public fun initialize(_sender: &signer) { - let witness = StakeToSBTPlugin {}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::StakeToSBTPlugin", - b"The plugin for stake to SBT", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://stake-to-sbt-plugin", - ); - } - - struct Stake has key, store { - id: u64, - token: Token::Token, - // The timestamp when user stake - stake_time: u64, - // How long where the user locked - lock_time: u64, - // Which multiplier by the user stake - weight: u64, - // The SBT amount that user swap in the token - sbt_amount: u128, - } - - struct StakeList has key, store { - items: vector>, - next_id: u64 - } - - struct LockWeightConfig has copy, store, drop { - weight_vec: vector> - } - - struct LockWeight has copy, drop, store { - lock_time: u64, - weight: u64, - } - - struct AcceptTokenCap has store, drop {} - - /// Events - /// - struct SBTTokenAcceptedEvent has copy, drop, store { - dao_id: u64, - token_code: Token::TokenCode - } - - struct SBTWeightChangedEvent has copy, drop, store { - dao_id: u64, - token_code: Token::TokenCode, - lock_time: u64, - weight: u64, - } - - struct SBTStakeEvent has copy, drop, store { - dao_id: u64, - stake_id: u64, - token_code: Token::TokenCode, - amount: u128, - lock_time: u64, - weight: u64, - sbt_amount: u128, - member: address, - } - - struct SBTUnstakeEvent has copy, drop, store { - dao_id: u64, - stake_id: u64, - token_code: Token::TokenCode, - amount: u128, - lock_time: u64, - weight: u64, - sbt_amount: u128, - member: address, - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type()); - Vector::push_back(&mut caps, DAOSpace::plugin_event_cap_type()); - caps - } - - /// Accept token with token type by given DAO - public fun accept_token_by_dao(_witness: &DAOT) { - install_event(); - accept_token(AcceptTokenCap {}); - } - - public fun install_event() { - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - - DAOSpace::init_plugin_event(&plugin_event_cap); - DAOSpace::init_plugin_event(&plugin_event_cap); - DAOSpace::init_plugin_event(&plugin_event_cap); - DAOSpace::init_plugin_event(&plugin_event_cap); - } - - /// Set sbt weight by given DAO - public fun set_sbt_weight_by_dao( - _witness: &DAOT, - lock_time: u64, - weight: u64 - ) { - set_sbt_weight(lock_time, weight); - } - - /// Accept token with token type - public fun accept_token(cap: AcceptTokenCap) { - let AcceptTokenCap {} = cap; - assert!( - !DAOSpace::exists_custom_config>(), - Errors::invalid_state(ERR_PLUGIN_CONFIG_INIT_REPEATE) - ); - - let witness = StakeToSBTPlugin {}; - let modify_config_cap = - DAOSpace::acquire_modify_config_cap(&witness); - - DAOSpace::set_custom_config< - DAOT, - StakeToSBTPlugin, - LockWeightConfig - >(&mut modify_config_cap, LockWeightConfig { - weight_vec: Vector::empty>() - }); - - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - - DAOSpace::emit_plugin_event( - &plugin_event_cap, - SBTTokenAcceptedEvent { - dao_id: DAOSpace::dao_id(DAOSpace::dao_address()), - token_code: Token::token_code(), - } - ); - } - - public fun stake( - sender: &signer, - token: Token::Token, - lock_time: u64 - ): u64 acquires StakeList { - let sender_addr = Signer::address_of(sender); - // Increase SBT - let witness = StakeToSBTPlugin {}; - let member_cap = - DAOSpace::acquire_member_cap(&witness); - - if (!DAOSpace::is_member(sender_addr) ) { - DAOSpace::issue_member_offer( - &member_cap, - sender_addr, - Option::none>(), - Option::none>(), - 0 - ); - DAOSpace::accept_member_offer(sender); - }; - - if (!exists>(sender_addr)) { - move_to(sender, StakeList { - items: Vector::empty(), - next_id: 0 - }); - }; - - let weight_opt = get_sbt_weight(lock_time); - assert!(Option::is_some(&weight_opt), Errors::invalid_state(ERR_PLUGIN_NO_MATCH_LOCKTIME)); - - let weight = Option::destroy_some(weight_opt); - let sbt_amount = compute_token_to_sbt(weight, &token); - DAOSpace::increase_member_sbt(&member_cap, sender_addr, sbt_amount); - - let stake_list = borrow_global_mut>(sender_addr); - let id = stake_list.next_id + 1; - Vector::push_back( - &mut stake_list.items, - Stake { - id, - token, - lock_time, - stake_time: Timestamp::now_seconds(), - weight, - sbt_amount - }); - stake_list.next_id = id; - - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - DAOSpace::emit_plugin_event( - &plugin_event_cap, - SBTStakeEvent { - dao_id: DAOSpace::dao_id(DAOSpace::dao_address()), - stake_id: id, - token_code: Token::token_code(), - amount: sbt_amount, - lock_time, - weight, - sbt_amount, - member: sender_addr, - } - ); - id - } - - public(script) fun stake_entry( - sender: signer, - amount: u128, - lock_time: u64 - ) acquires StakeList { - let token = Account::withdraw(&sender, amount); - stake(&sender, token, lock_time); - } - - public fun query_stake( - member: address, - id: u64 - ): (u64, u64, u64, u128, u128) acquires StakeList { - assert!(exists>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global_mut>(member); - let item_index = find_item(id, &stake_list.items); - - // Check item in item container - assert!(Option::is_some(&item_index), Errors::invalid_state(ERR_PLUGIN_ITEM_CANT_FOUND)); - - let stake = - Vector::borrow(&mut stake_list.items, Option::destroy_some(item_index)); - ( - stake.stake_time, - stake.lock_time, - stake.weight, - stake.sbt_amount, - Token::value(&stake.token), - ) - } - - /// Query stake count from stake list - public fun query_stake_count(member: address): u64 acquires StakeList { - assert!(exists>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global>(member); - Vector::length(&stake_list.items) - } - - /// Unstake from staking - public fun unstake_by_id(sender: &signer, id: u64) acquires StakeList { - let member = Signer::address_of(sender); - assert!(exists>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global_mut>(member); - let item_index = find_item(id, &stake_list.items); - - // Check item in item container - assert!(Option::is_some(&item_index), Errors::invalid_state(ERR_PLUGIN_ITEM_CANT_FOUND)); - - let poped_item = - Vector::remove(&mut stake_list.items, Option::destroy_some(item_index)); - - let amount = Token::value(&poped_item.token); - let lock_time = poped_item.lock_time; - let weight = poped_item.weight; - let sbt_amount = poped_item.sbt_amount; - - Account::deposit(member, unstake_item(member, poped_item)); - - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - DAOSpace::emit_plugin_event( - &plugin_event_cap, - SBTUnstakeEvent { - dao_id: DAOSpace::dao_id(DAOSpace::dao_address()), - stake_id: id, - token_code: Token::token_code(), - amount, - lock_time, - weight, - sbt_amount, - member, - } - ); - } - - public(script) fun unstake_by_id_entry( - sender: signer, - id: u64 - ) acquires StakeList { - unstake_by_id(&sender, id); - } - - /// Unstake all staking items from sender, - /// No care whether the sender is member or not - public fun unstake_all(sender: &signer) acquires StakeList { - let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global_mut>(sender_addr); - let len = Vector::length(&mut stake_list.items); - - let idx = 0; - while (idx < len) { - let item = Vector::remove(&mut stake_list.items, idx); - Account::deposit(sender_addr, unstake_item(sender_addr, item)); - idx = idx + 1; - }; - } - - public(script) fun unstake_all_entry(sender: signer) acquires StakeList { - unstake_all(&sender); - } - - /// Unstake a item from a item object - fun unstake_item( - member: address, - item: Stake - ): Token::Token { - let Stake { - id: _, - token, - lock_time, - stake_time, - weight: _, - sbt_amount, - } = item; - - assert!((Timestamp::now_seconds() - stake_time) > lock_time, Errors::invalid_state(ERR_PLUGIN_STILL_LOCKED)); - - // Deduct the corresponding SBT amount if the signer account is a DAO member while unstake - if (DAOSpace::is_member(member)) { - let witness = StakeToSBTPlugin {}; - let member_cap = - DAOSpace::acquire_member_cap(&witness); - - // Decrease the SBT using `sbt_amount` which from unwrapped Stake data, - // rather than the value that calculate a SBT amount from lock time and weight, - // because of the `weight` could change at any time - DAOSpace::decrease_member_sbt(&member_cap, member, sbt_amount); - }; - - token - } - - fun get_sbt_weight(lock_time: u64): Option::Option { - let config = - DAOSpace::get_custom_config>(); - let c = - &mut config.weight_vec; - let len = Vector::length(c); - let idx = 0; - - while (idx < len) { - let e = Vector::borrow(c, idx); - if (e.lock_time == lock_time) { - return Option::some(e.weight) - }; - idx = idx + 1; - }; - - Option::none() - } - - fun set_sbt_weight(lock_time: u64, weight: u64) { - let config = - DAOSpace::get_custom_config>(); - let c = &mut config.weight_vec; - let len = Vector::length(c); - let idx = 0; - let new_el = true; - while (idx < len) { - let lock_weight = Vector::borrow_mut(c, idx); - if (lock_weight.lock_time == lock_time) { - lock_weight.weight = weight; - new_el = false; - break - }; - idx = idx + 1; - }; - - if (new_el) { - Vector::push_back(c, LockWeight { - lock_time, - weight, - }); - }; - - let witness = StakeToSBTPlugin {}; - let modify_config_cap = - DAOSpace::acquire_modify_config_cap(&witness); - - DAOSpace::set_custom_config< - DAOT, - StakeToSBTPlugin, - LockWeightConfig - >(&mut modify_config_cap, LockWeightConfig { - weight_vec: *&config.weight_vec - }); - } - - fun find_item( - id: u64, - c: &vector> - ): Option::Option { - let len = Vector::length(c); - let idx = 0; - while (idx < len) { - let item = Vector::borrow(c, idx); - if (item.id == id) { - return Option::some(idx) - }; - idx = idx + 1; - }; - Option::none() - } - - fun compute_token_to_sbt(weight: u64, token: &Token::Token): u128 { - (weight as u128) * Token::value(token) / Token::scaling_factor() - } - - /// Create proposal that to specific a weight for a locktime - public fun create_weight_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - lock_time: u64, - weight: u64, - action_delay: u64 - ) { - let witness = StakeToSBTPlugin {}; - - let cap = - DAOSpace::acquire_proposal_cap(&witness); - DAOSpace::create_proposal(&cap, sender, LockWeight { - lock_time, - weight, - }, - title, - introduction, - extend, - action_delay, - Option::none()); - } - - public(script) fun create_weight_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - lock_time: u64, - weight: u64, - action_delay: u64 - ) { - create_weight_proposal(&sender,title, introduction, extend, lock_time, weight, action_delay); - } - - public fun execute_weight_proposal( - sender: &signer, - proposal_id: u64 - ) { - let witness = StakeToSBTPlugin {}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - - let LockWeight { - lock_time, - weight - } = DAOSpace::execute_proposal< - DAOT, - StakeToSBTPlugin, - LockWeight - >(&proposal_cap, sender, proposal_id); - - set_sbt_weight(lock_time, weight); - } - - public(script) fun execute_weight_proposal_entry( - sender: signer, - proposal_id: u64 - ) { - execute_weight_proposal(&sender, proposal_id); - } - - /// Create proposal that to accept a token type, which allow user to convert amount of token to SBT - public fun create_token_accept_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - let witness = StakeToSBTPlugin {}; - - let cap = - DAOSpace::acquire_proposal_cap(&witness); - DAOSpace::create_proposal( - &cap, - sender, - AcceptTokenCap {}, - title, - introduction, - extend, - action_delay, - Option::none() - ); - } - - public(script) fun create_token_accept_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - create_token_accept_proposal(&sender, title, introduction, extend, action_delay); - } - - public fun execute_token_accept_proposal( - sender: &signer, - proposal_id: u64 - ) { - let witness = StakeToSBTPlugin {}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - - let cap = DAOSpace::execute_proposal< - DAOT, - StakeToSBTPlugin, - AcceptTokenCap - >(&proposal_cap, sender, proposal_id); - - accept_token(cap); - } - - - public(script) fun execute_token_accept_proposal_entry( - sender: signer, - proposal_id: u64 - ) { - execute_token_accept_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - InstallPluginProposalPlugin::create_proposal( - sender, - required_caps(), - title, - introduction, - extend, - action_delay - ); - } - - public(script) fun install_plugin_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} diff --git a/release/v12/sources/StarcoinDAO.move b/release/v12/sources/StarcoinDAO.move deleted file mode 100644 index 42de91af..00000000 --- a/release/v12/sources/StarcoinDAO.move +++ /dev/null @@ -1,67 +0,0 @@ -module StarcoinFramework::StarcoinDAO { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::Account; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::UpgradeModulePlugin::{Self, UpgradeModulePlugin}; - use StarcoinFramework::ConfigProposalPlugin::{Self, ConfigProposalPlugin}; - use StarcoinFramework::StakeToSBTPlugin::{Self, StakeToSBTPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Option; - use StarcoinFramework::GasOracleProposalPlugin::GasOracleProposalPlugin; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::TreasuryPlugin::{Self, TreasuryPlugin}; - use StarcoinFramework::Config; - use StarcoinFramework::PackageTxnManager; - - friend StarcoinFramework::Genesis; - friend StarcoinFramework::StdlibUpgradeScripts; - - struct StarcoinDAO has store, drop {} - - const NAME: vector = b"StarcoinDAO"; - - public(friend) fun create_dao( - signer_cap: Account::SignerCapability, - upgrade_plan_cap: PackageTxnManager::UpgradePlanCapability, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128 - ) { - let dao_account_cap = DAOAccount::upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap, upgrade_plan_cap); - - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - - - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let witness = StarcoinDAO {}; - let install_cap = DAOSpace::acquire_install_plugin_cap(&witness); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, UpgradeModulePlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, ConfigProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, StakeToSBTPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, GasOracleProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, TreasuryPlugin::required_caps()); - - StakeToSBTPlugin::accept_token_by_dao(&witness); - StakeToSBTPlugin::set_sbt_weight_by_dao(&witness, 60000, 1000); - } - - public(friend) fun delegate_config_capability(cap: Config::ModifyConfigCapability) { - DAOSpace::set_custom_config_cap(cap); - } - - /// scale up the quorum votes for treasury withdraw proposal. - public(friend) fun set_treasury_withdraw_proposal_scale(scale: u8) { - TreasuryPlugin::set_scale_factor(scale, &StarcoinDAO {}); - } -} \ No newline at end of file diff --git a/release/v12/sources/StarcoinVerifier.move b/release/v12/sources/StarcoinVerifier.move deleted file mode 100644 index 3493be95..00000000 --- a/release/v12/sources/StarcoinVerifier.move +++ /dev/null @@ -1,351 +0,0 @@ -address StarcoinFramework { -module StarcoinVerifier { - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::BCS; - use StarcoinFramework::StructuredHash; - use StarcoinFramework::Hash; - - const HASH_LEN_IN_BITS: u64 = 32 * 8; - const SPARSE_MERKLE_LEAF_NODE: vector = b"SparseMerkleLeafNode"; - const SPARSE_MERKLE_INTERNAL_NODE: vector = b"SparseMerkleInternalNode"; - const BLOB_HASH_PREFIX: vector = b"Blob"; - const DEFAULT_VALUE: vector = x""; - const ACCOUNT_STORAGE_INDEX_RESOURCE: u64 = 1; - const ERROR_ACCOUNT_STORAGE_ROOTS: u64 = 101; - const ERROR_LITERAL_HASH_WRONG_LENGTH: u64 = 102; - const SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL: vector = b"SPARSE_MERKLE_PLACEHOLDER_HASH"; - - - struct AccountState has store, drop, copy { - storage_roots: vector>>, - } - - public fun bcs_deserialize_account_state(data: &vector): AccountState { - let (vec, _) = BCS::deserialize_option_bytes_vector(data, 0); - AccountState{ - storage_roots: vec - } - } - - struct StateProof has store, drop, copy { - /** - * Account state's proof for global state root. - */ - account_proof: SparseMerkleProof, - /** - * Account state including storage roots. - */ - account_state: vector, - /** - * State's proof for account storage root. - */ - proof: SparseMerkleProof, - } - - public fun new_state_proof(account_proof: SparseMerkleProof, account_state: vector, proof: SparseMerkleProof): StateProof { - StateProof{ - account_proof, - account_state, - proof, - } - } - - struct SparseMerkleProof has store, drop, copy { - siblings: vector>, - leaf: SMTNode, - } - - public fun new_sparse_merkle_proof(siblings: vector>, leaf: SMTNode): SparseMerkleProof { - SparseMerkleProof{ - siblings, - leaf, - } - } - - struct SMTNode has store, drop, copy { - hash1: vector, - hash2: vector, - } - - public fun new_smt_node(hash1: vector, hash2: vector): SMTNode { - SMTNode{ - hash1, - hash2, - } - } - - public fun empty_smt_node(): SMTNode { - SMTNode{ - hash1: Vector::empty(), - hash2: Vector::empty(), - } - } - - public fun verify_state_proof(state_proof: &StateProof, state_root: &vector, - account_address: address, resource_struct_tag: &vector, - state: &vector): bool { - let accountState: AccountState = bcs_deserialize_account_state(&state_proof.account_state); - assert!(Vector::length(&accountState.storage_roots) > ACCOUNT_STORAGE_INDEX_RESOURCE, ERROR_ACCOUNT_STORAGE_ROOTS); - - // First, verify state for storage root. - let storageRoot = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE)); - let ok: bool = verify_smp(&state_proof.proof.siblings, - &state_proof.proof.leaf, - storageRoot, - resource_struct_tag, // resource struct tag BCS serialized as key - state); - if (!ok) { - return false - }; - - // Then, verify account state for global state root. - ok = verify_smp(&state_proof.account_proof.siblings, - &state_proof.account_proof.leaf, - state_root, - &BCS::to_bytes
(&account_address), // account address as key - &state_proof.account_state, - ); - ok - } - - #[test] - fun test_verify_state_proof() { - // miannet, block number 6495396 - let state_root = x"d337896a5cd8bae3d0130e09409c0f5eede159d93af38a642528acb15c1204b8"; - let account_address = @0x47d36856884d7fb9e91a475ea3472341; -// let state = x""; - let state = x"00000000000000000000000000000000"; - // 0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - let resource_struct_tag = x"00000000000000000000000000000001074163636f756e740742616c616e636501078c109349c6bd91411d6bc962e080c4a30453544152045354415200"; - - let account_proof_sibling_nodes = Vector::empty>(); - Vector::push_back(&mut account_proof_sibling_nodes, x"b81050a469dbe041f915cda6942143c691b1735599815142c895f77cf088a656"); - Vector::push_back(&mut account_proof_sibling_nodes, x"5350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000"); - Vector::push_back(&mut account_proof_sibling_nodes, x"1c0cbf70e7474e739db9ca9958470f605f37a5a0f322c7c854b24866c4330577"); - Vector::push_back(&mut account_proof_sibling_nodes, x"68dde7ba4f4a9cf6329675e598a1ab7b545f8de36e5cb8151be8ff167e479c26"); - Vector::push_back(&mut account_proof_sibling_nodes, x"3c59423b2956d25cdacf638540e39dbc53238d36ca1420d31c4321580aeff633"); - Vector::push_back(&mut account_proof_sibling_nodes, x"5befec9a99ad40f1cb6d5b44c87ca6ad26841535cd7fac27f2f88205088b55e3"); - Vector::push_back(&mut account_proof_sibling_nodes, x"32f4d82b78b1339fb5d9c60ac2e49780c87b9e9c675bee9d1cb3ace3f34a63d6"); - Vector::push_back(&mut account_proof_sibling_nodes, x"a60429524592cac0170763196269c4997e08b6a09b2ad45647775486a81559af"); - Vector::push_back(&mut account_proof_sibling_nodes, x"6b6bc4e16bad1fbc6c6df21a923a9be06ae8508827cdd3dbdd4e0e6607abdb6d"); - Vector::push_back(&mut account_proof_sibling_nodes, x"5e6165bc60b30f46611d52f9779668e0fa79eeb60bf3a0d90346b33331156155"); - Vector::push_back(&mut account_proof_sibling_nodes, x"dfc42240b0d542457748e873e3ab0ee362c68dedd91df13532cd85a1a6ea6f00"); - Vector::push_back(&mut account_proof_sibling_nodes, x"610cba3b3c467b137ddbda0f5783ef269357ca4e30aaa2cfecb96e2ee8b2c5e7"); - Vector::push_back(&mut account_proof_sibling_nodes, x"179235bb93b8ece25921f7405a2f797f80630d90f71e763e8a700734d6945b99"); - Vector::push_back(&mut account_proof_sibling_nodes, x"85d80d435c4cb8b8034d32aff6b05230efc43b583154428a0990e1f752adcf3a"); - Vector::push_back(&mut account_proof_sibling_nodes, x"a2f4a3e6f11e6b42d700c920c06a89ffe6d086d5411aa578d56d8de000704669"); - Vector::push_back(&mut account_proof_sibling_nodes, x"ee57409d642877366ac26b2bf8948f7daae3c45a545b931b28a6d902e01bdc1f"); - - let state_proof_sibling_nodes = Vector::empty>(); - Vector::push_back(&mut state_proof_sibling_nodes, x"2a3c2096fbd5a1a2e81077e4b2156c7232b9291ad3d85ea7451eb8b7cda828fd"); - Vector::push_back(&mut state_proof_sibling_nodes, x"4cc4f038091aba95645a5b8153dc088ffdbfb7c7e82dd6b166f187b33eea7432"); - Vector::push_back(&mut state_proof_sibling_nodes, x"aa140a1627b5385e108f6580062110463d09768bce681bbb88c3d9c59680d75d"); - Vector::push_back(&mut state_proof_sibling_nodes, x"7c8f59d557168dd5667fcc950ed444cfa0cbce778e032c918a8b2a2084c48c03"); - Vector::push_back(&mut state_proof_sibling_nodes, x"a0718e77be611f67f880f5fc4d7c801940aae65890f02b38a663458ed924c2f9"); - - let proof = new_state_proof( - new_sparse_merkle_proof( - account_proof_sibling_nodes, - new_smt_node( - x"3fe0547cb3576cad025fb5cfa98b85a3545a41e5b14e844fd8cad5edaa619c05", - x"ed0e07d03371a130b84bea8245f84bf546955e5a190afc20ef34f310614c6d10", - ), - ), - x"02000120ceaafd667b54252bba61993770d87bbb997b1a689b0e08899543e3c8f82adca7", - new_sparse_merkle_proof( - state_proof_sibling_nodes, - new_smt_node( - x"1de0d92e4e770fa53ceaa12c83edb8c0e51c1d19499d769c572ffd9d38cef40f", - x"6493204f1b87055adb8937a385daa238b3c08c491026f2ac50ebe4dab9133030", - ), - ), - ); - - let b = verify_state_proof( - &proof, - &state_root, - account_address, - &resource_struct_tag, - &state, - ); - assert!(b, 1110); - } - - /// Verify sparse merkle proof by key and value. - public fun verify_smp(sibling_nodes: &vector>, leaf_data: &SMTNode, expected_root: &vector, key: &vector, value: &vector): bool { - let path = hash_key(key); - let current_hash: vector; - if (*value == DEFAULT_VALUE) { - // Non-membership proof. - if (empty_smt_node() == *leaf_data) { - current_hash = placeholder(); - } else { - if (*&leaf_data.hash1 == *&path) { - return false - }; - if (!(count_common_prefix(&leaf_data.hash1, &path) >= Vector::length(sibling_nodes))) { - return false - }; - current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data); - }; - } else { - // Membership proof. - if (empty_smt_node() == *leaf_data) { - return false - }; - if (*&leaf_data.hash1 != *&path) { - return false - }; - let value_hash = hash_value(value); - if (*&leaf_data.hash2 != value_hash) { - return false - }; - current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data); - }; - - current_hash = compute_smp_root_by_path_and_node_hash(sibling_nodes, &path, ¤t_hash); - current_hash == *expected_root - } - -// #[test] -// fun test_print_storage_root(){ -// let account_state = x"02000120ceaafd667b54252bba61993770d87bbb997b1a689b0e08899543e3c8f82adca7"; -// let accountState: AccountState = bcs_deserialize_account_state(&account_state); -// let storageRoot = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE)); -// Debug::print(storageRoot); -// } - - #[test] - fun test_verify_smp() { - let sibling_nodes = Vector::empty>(); - Vector::push_back(&mut sibling_nodes, x"2a3c2096fbd5a1a2e81077e4b2156c7232b9291ad3d85ea7451eb8b7cda828fd"); - Vector::push_back(&mut sibling_nodes, x"4cc4f038091aba95645a5b8153dc088ffdbfb7c7e82dd6b166f187b33eea7432"); - Vector::push_back(&mut sibling_nodes, x"aa140a1627b5385e108f6580062110463d09768bce681bbb88c3d9c59680d75d"); - Vector::push_back(&mut sibling_nodes, x"7c8f59d557168dd5667fcc950ed444cfa0cbce778e032c918a8b2a2084c48c03"); - Vector::push_back(&mut sibling_nodes, x"a0718e77be611f67f880f5fc4d7c801940aae65890f02b38a663458ed924c2f9"); - - let leaf_node = new_smt_node( - x"1de0d92e4e770fa53ceaa12c83edb8c0e51c1d19499d769c572ffd9d38cef40f", - x"6493204f1b87055adb8937a385daa238b3c08c491026f2ac50ebe4dab9133030", - ); - let account_state = x"02000120ceaafd667b54252bba61993770d87bbb997b1a689b0e08899543e3c8f82adca7"; - let accountState: AccountState = bcs_deserialize_account_state(&account_state); - let expected_root = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE)); -// let expected_root = x"0f30a41872208c6324fa842889315b14f9be6f3dd0d5050686317adfdd0cda60"; - let key = x"00000000000000000000000000000001074163636f756e740742616c616e636501078c109349c6bd91411d6bc962e080c4a30453544152045354415200"; - // Above key is this StructTag BCS serialized bytes: - let value = x"00000000000000000000000000000000"; - - let b = verify_smp(&sibling_nodes, &leaf_node, expected_root, &key, &value); - assert!(b, 1112) - } - - #[test] - fun test_verify_smp_2() { - let sibling_nodes: vector> = Vector::empty(); - let leaf_data: SMTNode = empty_smt_node(); - let expected_root: vector = placeholder(); - let key: vector = b"random key"; - let value: vector = Vector::empty(); //x"" - let b = verify_smp(&sibling_nodes, &leaf_data, &expected_root, &key, &value); - assert!(b, 1113); - - value = b"random value"; - b = verify_smp(&sibling_nodes, &leaf_data, &expected_root, &key, &value); - assert!(!b, 1114); - } - - public fun compute_smp_root_by_path_and_node_hash(sibling_nodes: &vector>, path: &vector, node_hash: &vector): vector { - let current_hash = *node_hash; - let i = 0; - let proof_length = Vector::length(sibling_nodes); - while (i < proof_length) { - let sibling = *Vector::borrow(sibling_nodes, i); - let bit = get_bit_at_from_msb(path, proof_length - i - 1); - let internal_node = if (bit) { - SMTNode{ hash1: sibling, hash2: current_hash } - } else { - SMTNode{ hash1: current_hash, hash2: sibling } - }; - current_hash = StructuredHash::hash(SPARSE_MERKLE_INTERNAL_NODE, &internal_node); - i = i + 1; - }; - current_hash - } - - public fun placeholder(): vector { - create_literal_hash(&SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL) - } - - public fun create_literal_hash(word: &vector): vector { - if (Vector::length(word) <= 32) { - let lenZero = 32 - Vector::length(word); - let i = 0; - let r = *word; - while (i < lenZero) { - Vector::push_back(&mut r, 0); - i = i + 1; - }; - return r - }; - abort ERROR_LITERAL_HASH_WRONG_LENGTH - } - - #[test] - fun test_create_literal_hash() { - let word = b"SPARSE_MERKLE_PLACEHOLDER_HASH"; - let r = create_literal_hash(&word); - assert!(r == x"5350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000", 1115); - } - - fun hash_key(key: &vector): vector { - Hash::sha3_256(*key) - } - - fun hash_value(value: &vector): vector { - StructuredHash::hash(BLOB_HASH_PREFIX, value) - } - - fun count_common_prefix(data1: &vector, data2: &vector): u64 { - let count = 0; - let i = 0; - while ( i < Vector::length(data1) * 8) { - if (get_bit_at_from_msb(data1, i) == get_bit_at_from_msb(data2, i)) { - count = count + 1; - } else { - break - }; - i = i + 1; - }; - count - } - - fun get_bit_at_from_msb(data: &vector, index: u64): bool { - let pos = index / 8; - let bit = (7 - index % 8); - (*Vector::borrow(data, pos) >> (bit as u8)) & 1u8 != 0 - } -} - -module StructuredHash { - use StarcoinFramework::Hash; - use StarcoinFramework::Vector; - use StarcoinFramework::BCS; - - const STARCOIN_HASH_PREFIX: vector = b"STARCOIN::"; - - public fun hash(structure: vector, data: &MoveValue): vector { - let prefix_hash = Hash::sha3_256(concat(&STARCOIN_HASH_PREFIX, structure)); - let bcs_bytes = BCS::to_bytes(data); - Hash::sha3_256(concat(&prefix_hash, bcs_bytes)) - } - - fun concat(v1: &vector, v2: vector): vector { - let data = *v1; - Vector::append(&mut data, v2); - data - } -} - -} \ No newline at end of file diff --git a/release/v12/sources/StdlibUpgradeScripts.move b/release/v12/sources/StdlibUpgradeScripts.move deleted file mode 100644 index 8308f9a2..00000000 --- a/release/v12/sources/StdlibUpgradeScripts.move +++ /dev/null @@ -1,181 +0,0 @@ -address StarcoinFramework { -/// The module for StdlibUpgrade init scripts -module StdlibUpgradeScripts { - - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::STC::{Self, STC}; - use StarcoinFramework::Token::{Self, LinearTimeMintKey}; - use StarcoinFramework::TreasuryWithdrawDaoProposal; - use StarcoinFramework::Treasury::{Self, LinearWithdrawCapability}; - use StarcoinFramework::Offer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Collection; - use StarcoinFramework::Oracle; - use StarcoinFramework::STCUSDOracle; - use StarcoinFramework::NFT; - use StarcoinFramework::GenesisNFT; - use StarcoinFramework::LanguageVersion; - use StarcoinFramework::OnChainConfigDao; - use StarcoinFramework::Config; - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::Account; - use StarcoinFramework::Block; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::DAOExtensionPoint; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::AnyMemberPlugin; - use StarcoinFramework::ConfigProposalPlugin; - use StarcoinFramework::GrantProposalPlugin; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::MemberProposalPlugin; - use StarcoinFramework::MintProposalPlugin; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::UpgradeModulePlugin; - use StarcoinFramework::StarcoinDAO; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::Dao; - use StarcoinFramework::TreasuryPlugin; - use StarcoinFramework::TransactionPublishOption; - use StarcoinFramework::VMConfig; - use StarcoinFramework::ConsensusConfig; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::TransactionTimeoutConfig; - use StarcoinFramework::UpgradeModuleDaoProposal; - use StarcoinFramework::ModifyDaoConfigProposal; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Stdlib upgrade script from v2 to v3 - public(script) fun upgrade_from_v2_to_v3(account: signer, total_stc_amount: u128) { - CoreAddresses::assert_genesis_address(&account); - - let withdraw_cap = STC::upgrade_from_v1_to_v2(&account, total_stc_amount); - - let mint_keys = Collection::borrow_collection>(CoreAddresses::ASSOCIATION_ROOT_ADDRESS()); - let mint_key = Collection::borrow(&mint_keys, 0); - let (total, minted, start_time, period) = Token::read_linear_time_key(mint_key); - Collection::return_collection(mint_keys); - - let now = Timestamp::now_seconds(); - let linear_withdraw_cap = Treasury::issue_linear_withdraw_capability(&mut withdraw_cap, total - minted, period - (now - start_time)); - // Lock the TreasuryWithdrawCapability to Dao - TreasuryWithdrawDaoProposal::plugin(&account, withdraw_cap); - // Give a LinearWithdrawCapability Offer to association, association need to take the offer, and destroy old LinearTimeMintKey. - Offer::create(&account, linear_withdraw_cap, CoreAddresses::ASSOCIATION_ROOT_ADDRESS(), 0); - } - - /// association account should call this script after upgrade from v2 to v3. - public(script) fun take_linear_withdraw_capability(signer: signer) { - let offered = Offer::redeem>(&signer, CoreAddresses::GENESIS_ADDRESS()); - Treasury::add_linear_withdraw_capability(&signer, offered); - let mint_key = Collection::take>(&signer); - Token::destroy_linear_time_key(mint_key); - } - - public fun do_upgrade_from_v5_to_v6(sender: &signer) { - CoreAddresses::assert_genesis_address(sender); - Oracle::initialize(sender); - //register oracle - STCUSDOracle::register(sender); - NFT::initialize(sender); - let merkle_root = x"5969f0e8e19f8769276fb638e6060d5c02e40088f5fde70a6778dd69d659ee6d"; - let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY"; - GenesisNFT::initialize(sender, merkle_root, 1639u64, image); - } - - public(script) fun upgrade_from_v5_to_v6(sender: signer) { - Self::do_upgrade_from_v5_to_v6(&sender) - } - - public(script) fun upgrade_from_v6_to_v7(sender: signer) { - Self::do_upgrade_from_v6_to_v7_with_language_version(&sender, 2); - } - - /// deprecated, use `do_upgrade_from_v6_to_v7_with_language_version`. - public fun do_upgrade_from_v6_to_v7(sender: &signer) { - do_upgrade_from_v6_to_v7_with_language_version(sender, 2); - } - - public fun do_upgrade_from_v6_to_v7_with_language_version(sender: &signer, language_version: u64) { - // initialize the language version config. - Config::publish_new_config(sender, LanguageVersion::new(language_version)); - // use STC Dao to upgrade onchain's move-language-version configuration. - OnChainConfigDao::plugin(sender); - // upgrade genesis NFT - GenesisNFT::upgrade_to_nft_type_info_v2(sender); - } - - public(script) fun upgrade_from_v7_to_v8(sender: signer) { - do_upgrade_from_v7_to_v8(&sender); - } - - public fun do_upgrade_from_v7_to_v8(sender: &signer) { - { - let cap = Oracle::extract_signer_cap(sender); - GenesisSignerCapability::initialize(sender, cap); - }; - - { - let cap = NFT::extract_signer_cap(sender); - Account::destroy_signer_cap(cap); - }; - } - - public(script) fun upgrade_from_v11_to_v12() { - do_upgrade_from_v11_to_v12(); - } - - public fun do_upgrade_from_v11_to_v12() { - let genessis_signer = GenesisSignerCapability::get_genesis_signer(); - Block::checkpoints_init(); - DAORegistry::initialize(); - - DAOExtensionPoint::initialize(); - DAOPluginMarketplace::initialize(); - - AnyMemberPlugin::initialize(&genessis_signer); - ConfigProposalPlugin::initialize(&genessis_signer); - GrantProposalPlugin::initialize(&genessis_signer); - InstallPluginProposalPlugin::initialize(&genessis_signer); - MemberProposalPlugin::initialize(&genessis_signer); - MintProposalPlugin::initialize(&genessis_signer); - StakeToSBTPlugin::initialize(&genessis_signer); - UpgradeModulePlugin::initialize(&genessis_signer); - GasOracleProposalPlugin::initialize(&genessis_signer); - TreasuryPlugin::initialize(&genessis_signer); - - //TODO : config rate need mind - // voting_delay: 60000 ms - // voting_period: 3600000 ms - // voting_quorum_rate: 4 - // min_action_delay: 3600000 ms - let signer_cap = Account::get_genesis_capability(); - let upgrade_plan_cap = UpgradeModuleDaoProposal::get_genesis_upgrade_cap(); - StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, Dao::voting_delay(), Dao::voting_period(), Dao::voting_quorum_rate(), Dao::min_action_delay(), 1000 * 1000 * 1000 * 1000); - - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - - let signer = GenesisSignerCapability::get_genesis_signer(); - let cap = TreasuryWithdrawDaoProposal::takeout_withdraw_capability(&signer); - TreasuryPlugin::delegate_capability(&signer, cap); - StarcoinDAO::set_treasury_withdraw_proposal_scale(100); - - // clean old DAO resources - ModifyDaoConfigProposal::destroy_modify_config_capability(&genessis_signer); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/Timestamp.move b/release/v12/sources/Timestamp.move deleted file mode 100644 index 0dd5da96..00000000 --- a/release/v12/sources/Timestamp.move +++ /dev/null @@ -1,131 +0,0 @@ -address StarcoinFramework { -/// The module implements onchain timestamp oracle. -/// Timestamp is updated on each block. It always steps forward, and never come backward. -module Timestamp { - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - - // A singleton resource holding the current Unix time in milliseconds - struct CurrentTimeMilliseconds has key { - milliseconds: u64, - } - - /// A singleton resource used to determine whether time has started. This - /// is called at the end of genesis. - struct TimeHasStarted has key {} - - /// Conversion factor between seconds and milliseconds - const MILLI_CONVERSION_FACTOR: u64 = 1000; - - const ENOT_GENESIS: u64 = 12; - const EINVALID_TIMESTAMP: u64 = 14; - const ENOT_INITIALIZED: u64 = 101; - // Initialize the global wall clock time resource. - public fun initialize(account: &signer, genesis_timestamp: u64) { - // Only callable by the Genesis address - CoreAddresses::assert_genesis_address(account); - let milli_timer = CurrentTimeMilliseconds {milliseconds: genesis_timestamp}; - move_to(account, milli_timer); - } - spec initialize { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if exists(Signer::address_of(account)); - ensures exists(Signer::address_of(account)); - } - - // Update the wall clock time by consensus. Requires VM privilege and will be invoked during block prologue. - public fun update_global_time(account: &signer, timestamp: u64) acquires CurrentTimeMilliseconds { - CoreAddresses::assert_genesis_address(account); - //Do not update time before time start. - let global_milli_timer = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - assert!(timestamp > global_milli_timer.milliseconds, Errors::invalid_argument(EINVALID_TIMESTAMP)); - global_milli_timer.milliseconds = timestamp; - } - spec update_global_time { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if timestamp <= global(CoreAddresses::GENESIS_ADDRESS()).milliseconds; - ensures global(CoreAddresses::GENESIS_ADDRESS()).milliseconds == timestamp; - } - - // Get the timestamp representing `now` in seconds. - public fun now_seconds(): u64 acquires CurrentTimeMilliseconds { - now_milliseconds() / MILLI_CONVERSION_FACTOR - } - spec now_seconds { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures result == now_milliseconds() / MILLI_CONVERSION_FACTOR; - } - spec fun spec_now_seconds(): u64 { - global(CoreAddresses::GENESIS_ADDRESS()).milliseconds / MILLI_CONVERSION_FACTOR - } - - // Get the timestamp representing `now` in milliseconds. - public fun now_milliseconds(): u64 acquires CurrentTimeMilliseconds { - borrow_global(CoreAddresses::GENESIS_ADDRESS()).milliseconds - } - - spec now_milliseconds { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - ensures result == global(CoreAddresses::GENESIS_ADDRESS()).milliseconds; - } - - spec fun spec_now_millseconds(): u64 { - global(CoreAddresses::GENESIS_ADDRESS()).milliseconds - } - - /// Marks that time has started and genesis has finished. This can only be called from genesis. - public fun set_time_has_started(account: &signer) { - CoreAddresses::assert_genesis_address(account); - - // Current time must have been initialized. - assert!( - exists(CoreAddresses::GENESIS_ADDRESS()), - Errors::invalid_state(ENOT_INITIALIZED) - ); - move_to(account, TimeHasStarted{}); - } - - spec set_time_has_started { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(Signer::address_of(account)); - aborts_if exists(Signer::address_of(account)); - ensures exists(Signer::address_of(account)); - } - - /// Helper function to determine if the blockchain is in genesis state. - public fun is_genesis(): bool { - !exists(CoreAddresses::GENESIS_ADDRESS()) - } - - spec is_genesis { - aborts_if false; - ensures result == !exists(CoreAddresses::GENESIS_ADDRESS()); - } - - /// Helper function to assert genesis state. - public fun assert_genesis() { - assert!(is_genesis(), Errors::invalid_state(ENOT_GENESIS)); - } - spec assert_genesis { - pragma opaque = true; - include AbortsIfNotGenesis; - } - - /// Helper schema to specify that a function aborts if not in genesis. - spec schema AbortsIfNotGenesis { - aborts_if !is_genesis(); - } - - spec schema AbortsIfTimestampNotExists { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - } -} -} diff --git a/release/v12/sources/Token.move b/release/v12/sources/Token.move deleted file mode 100644 index 290b9843..00000000 --- a/release/v12/sources/Token.move +++ /dev/null @@ -1,545 +0,0 @@ -address StarcoinFramework { -/// Token implementation of Starcoin. -module Token { - use StarcoinFramework::Event; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::Math; - - friend StarcoinFramework::TypeInfo; - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// The token has a `TokenType` color that tells us what token the - /// `value` inside represents. - struct Token has store { - value: u128, - } - - /// Token Code which identify a unique Token. - struct TokenCode has copy, drop, store { - /// address who define the module contains the Token Type. - addr: address, - /// module which contains the Token Type. - module_name: vector, - /// name of the token. may nested if the token is an instantiated generic token type. - name: vector, - } - - /// A minting capability allows tokens of type `TokenType` to be minted - struct MintCapability has key, store {} - - /// A fixed time mint key which can mint token until global time > end_time - struct FixedTimeMintKey has key, store { - total: u128, - end_time: u64, - } - - /// A linear time mint key which can mint token in a period by time-based linear release. - struct LinearTimeMintKey has key, store { - total: u128, - minted: u128, - start_time: u64, - period: u64, - } - - /// A burn capability allows tokens of type `TokenType` to be burned. - struct BurnCapability has key, store {} - - - /// Event emitted when token minted. - struct MintEvent has drop, store { - /// funds added to the system - amount: u128, - /// full info of Token. - token_code: TokenCode, - } - - /// Event emitted when token burned. - struct BurnEvent has drop, store { - /// funds removed from the system - amount: u128, - /// full info of Token - token_code: TokenCode, - } - - /// Token information. - struct TokenInfo has key { - /// The total value for the token represented by - /// `TokenType`. Mutable. - total_value: u128, - /// The scaling factor for the coin (i.e. the amount to divide by - /// to get to the human-readable representation for this currency). - /// e.g. 10^6 for `Coin1` - scaling_factor: u128, - /// event stream for minting - mint_events: Event::EventHandle, - /// event stream for burning - burn_events: Event::EventHandle, - } - - const EDEPRECATED_FUNCTION: u64 = 19; - - const EDESTROY_TOKEN_NON_ZERO: u64 = 16; - const EINVALID_ARGUMENT: u64 = 18; - - /// Token register's address should same as TokenType's address. - const ETOKEN_REGISTER: u64 = 101; - - const EAMOUNT_EXCEEDS_COIN_VALUE: u64 = 102; - // Mint key time limit - const EMINT_KEY_TIME_LIMIT: u64 = 103; - - const EDESTROY_KEY_NOT_EMPTY: u64 = 104; - const EPRECISION_TOO_LARGE: u64 = 105; - const EEMPTY_KEY: u64 = 106; - const ESPLIT: u64 = 107; - const EPERIOD_NEW: u64 = 108; - const EMINT_AMOUNT_EQUAL_ZERO: u64 = 109; - - /// 2^128 < 10**39 - const MAX_PRECISION: u8 = 38; - - /// Register the type `TokenType` as a Token and got MintCapability and BurnCapability. - public fun register_token( - account: &signer, - precision: u8, - ) { - assert!(precision <= MAX_PRECISION, Errors::invalid_argument(EPRECISION_TOO_LARGE)); - let scaling_factor = Math::pow(10, (precision as u64)); - let token_address = token_address(); - assert!(Signer::address_of(account) == token_address, Errors::requires_address(ETOKEN_REGISTER)); - move_to(account, MintCapability {}); - move_to(account, BurnCapability {}); - move_to( - account, - TokenInfo { - total_value: 0, - scaling_factor, - mint_events: Event::new_event_handle(account), - burn_events: Event::new_event_handle(account), - }, - ); - } - - spec register_token { - include RegisterTokenAbortsIf; - include RegisterTokenEnsures; - } - - spec schema RegisterTokenAbortsIf { - precision: u8; - account: signer; - aborts_if precision > MAX_PRECISION; - aborts_if Signer::address_of(account) != SPEC_TOKEN_TEST_ADDRESS(); - aborts_if exists>(Signer::address_of(account)); - aborts_if exists>(Signer::address_of(account)); - aborts_if exists>(Signer::address_of(account)); - } - - spec schema RegisterTokenEnsures { - account: signer; - ensures exists>(Signer::address_of(account)); - ensures exists>(Signer::address_of(account)); - ensures exists>(Signer::address_of(account)); - } - - /// Remove mint capability from `signer`. - public fun remove_mint_capability(signer: &signer): MintCapability - acquires MintCapability { - move_from>(Signer::address_of(signer)) - } - - spec remove_mint_capability { - aborts_if !exists>(Signer::address_of(signer)); - ensures !exists>(Signer::address_of(signer)); - } - - /// Add mint capability to `signer`. - public fun add_mint_capability(signer: &signer, cap: MintCapability) { - move_to(signer, cap) - } - - spec add_mint_capability { - aborts_if exists>(Signer::address_of(signer)); - ensures exists>(Signer::address_of(signer)); - } - - /// Destroy the given mint capability. - public fun destroy_mint_capability(cap: MintCapability) { - let MintCapability {} = cap; - } - - spec destroy_mint_capability { - } - - /// remove the token burn capability from `signer`. - public fun remove_burn_capability(signer: &signer): BurnCapability - acquires BurnCapability { - move_from>(Signer::address_of(signer)) - } - - spec remove_burn_capability { - aborts_if !exists>(Signer::address_of(signer)); - ensures !exists>(Signer::address_of(signer)); - } - - /// Add token burn capability to `signer`. - public fun add_burn_capability(signer: &signer, cap: BurnCapability) { - move_to(signer, cap) - } - - spec add_burn_capability { - aborts_if exists>(Signer::address_of(signer)); - ensures exists>(Signer::address_of(signer)); - } - - /// Destroy the given burn capability. - public fun destroy_burn_capability(cap: BurnCapability) { - let BurnCapability {} = cap; - } - - spec destroy_burn_capability { - } - - /// Return `amount` tokens. - /// Fails if the sender does not have a published MintCapability. - public fun mint(account: &signer, amount: u128): Token - acquires TokenInfo, MintCapability { - mint_with_capability( - borrow_global>(Signer::address_of(account)), - amount, - ) - } - - spec mint { - aborts_if spec_abstract_total_value() + amount > MAX_U128; - aborts_if !exists>(Signer::address_of(account)); - } - - /// Mint a new Token::Token worth `amount`. - /// The caller must have a reference to a MintCapability. - /// Only the Association account can acquire such a reference, and it can do so only via - /// `borrow_sender_mint_capability` - public fun mint_with_capability( - _capability: &MintCapability, - amount: u128, - ): Token acquires TokenInfo { - do_mint(amount) - } - - spec mint_with_capability { - aborts_if spec_abstract_total_value() + amount > MAX_U128; - ensures spec_abstract_total_value() == - old(global>(SPEC_TOKEN_TEST_ADDRESS()).total_value) + amount; - } - - fun do_mint(amount: u128): Token acquires TokenInfo { - // update market cap resource to reflect minting - let (token_address, module_name, token_name) = name_of_token(); - let info = borrow_global_mut>(token_address); - info.total_value = info.total_value + amount; - Event::emit_event( - &mut info.mint_events, - MintEvent { - amount, - token_code: TokenCode { addr: token_address, module_name, name: token_name }, - }, - ); - Token { value: amount } - } - - spec do_mint { - aborts_if !exists>(SPEC_TOKEN_TEST_ADDRESS()); - aborts_if spec_abstract_total_value() + amount > MAX_U128; - } - - /// Deprecated since @v3 - /// Issue a `FixedTimeMintKey` with given `MintCapability`. - public fun issue_fixed_mint_key( - _capability: &MintCapability, - _amount: u128, - _period: u64, - ): FixedTimeMintKey { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - spec issue_fixed_mint_key { - aborts_if true; - } - - /// Deprecated since @v3 - /// Issue a `LinearTimeMintKey` with given `MintCapability`. - public fun issue_linear_mint_key( - _capability: &MintCapability, - _amount: u128, - _period: u64, - ): LinearTimeMintKey { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - spec issue_linear_mint_key { - aborts_if true; - } - - /// Destroy `LinearTimeMintKey`, for deprecated - public fun destroy_linear_time_key(key: LinearTimeMintKey): (u128, u128, u64, u64) { - let LinearTimeMintKey { total, minted, start_time, period } = key; - (total, minted, start_time, period) - } - - public fun read_linear_time_key(key: &LinearTimeMintKey): (u128, u128, u64, u64) { - (key.total, key.minted, key.start_time, key.period) - } - - /// Burn some tokens of `signer`. - public fun burn(account: &signer, tokens: Token) - acquires TokenInfo, BurnCapability { - burn_with_capability( - borrow_global>(Signer::address_of(account)), - tokens, - ) - } - - spec burn { - aborts_if spec_abstract_total_value() - tokens.value < 0; - aborts_if !exists>(Signer::address_of(account)); - } - - /// Burn tokens with the given `BurnCapability`. - public fun burn_with_capability( - _capability: &BurnCapability, - tokens: Token, - ) acquires TokenInfo { - let (token_address, module_name, token_name) = name_of_token(); - let info = borrow_global_mut>(token_address); - let Token { value } = tokens; - info.total_value = info.total_value - value; - Event::emit_event( - &mut info.burn_events, - BurnEvent { - amount: value, - token_code: TokenCode { addr: token_address, module_name, name: token_name }, - }, - ); - } - - spec burn_with_capability { - aborts_if spec_abstract_total_value() - tokens.value < 0; - ensures spec_abstract_total_value() == - old(global>(SPEC_TOKEN_TEST_ADDRESS()).total_value) - tokens.value; - } - - /// Create a new Token::Token with a value of 0 - public fun zero(): Token { - Token { value: 0 } - } - - spec zero { - ensures result.value == 0; - } - - - /// Public accessor for the value of a token - public fun value(token: &Token): u128 { - token.value - } - - spec value { - aborts_if false; - ensures result == token.value; - } - - /// Splits the given token into two and returns them both - public fun split( - token: Token, - value: u128, - ): (Token, Token) { - let rest = withdraw(&mut token, value); - (token, rest) - } - - spec split { - aborts_if token.value < value; - // N.B. spec translator regards `token` as a pure expression - ensures token.value == result_1.value + result_2.value; - } - - /// "Divides" the given token into two, where the original token is modified in place. - /// The original token will have value = original value - `value` - /// The new token will have a value = `value` - /// Fails if the tokens value is less than `value` - public fun withdraw( - token: &mut Token, - value: u128, - ): Token { - // Check that `value` is less than the token's value - assert!(token.value >= value, Errors::limit_exceeded(EAMOUNT_EXCEEDS_COIN_VALUE)); - token.value = token.value - value; - Token { value: value } - } - - spec withdraw { - aborts_if token.value < value; - ensures result.value == value; - ensures token.value == old(token).value - value; - } - - /// Merges two tokens of the same token and returns a new token whose - /// value is equal to the sum of the two inputs - public fun join( - token1: Token, - token2: Token, - ): Token { - deposit(&mut token1, token2); - token1 - } - - spec join { - aborts_if token1.value + token2.value > max_u128(); - ensures token1.value + token2.value == result.value; - } - - /// "Merges" the two tokens - /// The token passed in by reference will have a value equal to the sum of the two tokens - /// The `check` token is consumed in the process - public fun deposit(token: &mut Token, check: Token) { - let Token { value } = check; - token.value = token.value + value; - } - - spec deposit { - aborts_if token.value + check.value > max_u128(); - ensures old(token).value + check.value == token.value; - } - - /// Destroy a token - /// Fails if the value is non-zero - /// The amount of Token in the system is a tightly controlled property, - /// so you cannot "burn" any non-zero amount of Token - public fun destroy_zero(token: Token) { - let Token { value } = token; - assert!(value == 0, Errors::invalid_state(EDESTROY_TOKEN_NON_ZERO)) - } - - spec destroy_zero { - aborts_if token.value > 0; - } - - /// Returns the scaling_factor for the `TokenType` token. - public fun scaling_factor(): u128 acquires TokenInfo { - let token_address = token_address(); - borrow_global>(token_address).scaling_factor - } - - spec scaling_factor { - aborts_if false; - ensures result == global>(SPEC_TOKEN_TEST_ADDRESS()).scaling_factor; - } - - /// Return the total amount of token of type `TokenType`. - public fun market_cap(): u128 acquires TokenInfo { - let token_address = token_address(); - borrow_global>(token_address).total_value - } - - spec market_cap { - aborts_if false; - ensures result == global>(SPEC_TOKEN_TEST_ADDRESS()).total_value; - } - - /// Return true if the type `TokenType` is a registered in `token_address`. - public fun is_registered_in(token_address: address): bool { - exists>(token_address) - } - - spec is_registered_in { - aborts_if false; - ensures result == exists>(token_address); - } - - /// Return true if the type `TokenType1` is same with `TokenType2` - public fun is_same_token(): bool { - return token_code() == token_code() - } - - spec is_same_token { - aborts_if false; - } - - /// Return the TokenType's address - public fun token_address(): address { - let (addr, _, _) = name_of(); - addr - } - - // The specification of this function is abstracted to avoid the complexity to - // return a real address to caller - spec token_address { - pragma opaque = true; - aborts_if false; - ensures [abstract] exists>(result); - ensures [abstract] result == SPEC_TOKEN_TEST_ADDRESS(); - ensures [abstract] global>(result).total_value == 100000000u128; - } - - /// Return the token code for the registered token. - public fun token_code(): TokenCode { - let (addr, module_name, name) = name_of(); - TokenCode { - addr, - module_name, - name - } - } - - spec token_code { - pragma opaque = true; - aborts_if false; - // ensures [abstract] result == spec_token_code(); - } - - /// We use an uninterpreted function to represent the result of derived address. The actual value - /// does not matter for the verification of callers. - spec fun spec_token_code(): TokenCode; - - public (friend) fun type_of(): (address, vector, vector){ - name_of() - } - - /// Return Token's module address, module name, and type name of `TokenType`. - native fun name_of(): (address, vector, vector); - - spec name_of { - pragma opaque = true; - aborts_if false; - } - - fun name_of_token(): (address, vector, vector) { - name_of() - } - - // The specification of this function is abstracted to avoid the complexity to - // return a real address to caller - spec name_of_token { - pragma opaque = true; - aborts_if false; - ensures [abstract] exists>(result_1); - ensures [abstract] result_1 == SPEC_TOKEN_TEST_ADDRESS(); - ensures [abstract] global>(result_1).total_value == 100000000u128; - } - - - spec fun SPEC_TOKEN_TEST_ADDRESS(): address { - @0x2 - } - - spec fun spec_abstract_total_value(): num { - global>(SPEC_TOKEN_TEST_ADDRESS()).total_value - } - - -} -} \ No newline at end of file diff --git a/release/v12/sources/TransactionFee.move b/release/v12/sources/TransactionFee.move deleted file mode 100644 index 47a2fb5c..00000000 --- a/release/v12/sources/TransactionFee.move +++ /dev/null @@ -1,95 +0,0 @@ -address StarcoinFramework { -/// `TransactionFee` collect gas fees used by transactions in blocks temporarily. -/// Then they are distributed in `TransactionManager`. -module TransactionFee { - use StarcoinFramework::Token::{Self, Token}; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Signer; - use StarcoinFramework::STC::{STC}; - use StarcoinFramework::Timestamp; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// The `TransactionFee` resource holds a preburn resource for each - /// fiat `TokenType` that can be collected as a transaction fee. - struct TransactionFee has key { - fee: Token, - } - - /// Called in genesis. Sets up the needed resources to collect transaction fees from the - /// `TransactionFee` resource with the TreasuryCompliance account. - public fun initialize( - account: &signer, - ) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - - // accept fees in all the currencies - add_txn_fee_token(account); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if exists>(Signer::address_of(account)); - } - - /// publishing a wrapper of the `Preburn` resource under `fee_account` - fun add_txn_fee_token( - account: &signer, - ) { - move_to( - account, - TransactionFee { - fee: Token::zero(), - } - ) - } - - spec add_txn_fee_token { - aborts_if exists>(Signer::address_of(account)); - } - - /// Deposit `token` into the transaction fees bucket - public fun pay_fee(token: Token) acquires TransactionFee { - let txn_fees = borrow_global_mut>( - CoreAddresses::GENESIS_ADDRESS() - ); - Token::deposit(&mut txn_fees.fee, token) - } - - spec pay_fee { - aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - aborts_if global>(CoreAddresses::GENESIS_ADDRESS()).fee.value + token.value > max_u128(); - } - - /// Distribute the transaction fees collected in the `TokenType` token. - /// If the `TokenType` is STC, it unpacks the token and preburns the - /// underlying fiat. - public fun distribute_transaction_fees( - account: &signer, - ): Token acquires TransactionFee { - let fee_address = CoreAddresses::GENESIS_ADDRESS(); - CoreAddresses::assert_genesis_address(account); - - // extract fees - let txn_fees = borrow_global_mut>(fee_address); - let value = Token::value(&txn_fees.fee); - if (value > 0) { - Token::withdraw(&mut txn_fees.fee, value) - }else { - Token::zero() - } - } - - spec distribute_transaction_fees { - pragma verify = false; -// aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); -// aborts_if !exists>(CoreAddresses::GENESIS_ADDRESS()); - - } - } -} diff --git a/release/v12/sources/TransactionManager.move b/release/v12/sources/TransactionManager.move deleted file mode 100644 index 5ea13eee..00000000 --- a/release/v12/sources/TransactionManager.move +++ /dev/null @@ -1,256 +0,0 @@ -address StarcoinFramework { -/// `TransactionManager` manages: -/// 1. prologue and epilogue of transactions. -/// 2. prologue of blocks. -module TransactionManager { - use StarcoinFramework::TransactionTimeout; - use StarcoinFramework::Signer; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Account; - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::BlockReward; - use StarcoinFramework::Block; - use StarcoinFramework::STC::STC; - use StarcoinFramework::TransactionFee; - use StarcoinFramework::Timestamp; - use StarcoinFramework::ChainId; - use StarcoinFramework::Errors; - use StarcoinFramework::TransactionPublishOption; - use StarcoinFramework::Epoch; - use StarcoinFramework::Hash; - use StarcoinFramework::Vector; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::GasOracle; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - const TXN_PAYLOAD_TYPE_SCRIPT: u8 = 0; - const TXN_PAYLOAD_TYPE_PACKAGE: u8 = 1; - const TXN_PAYLOAD_TYPE_SCRIPT_FUNCTION: u8 = 2; - - const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0; - const EPROLOGUE_TRANSACTION_EXPIRED: u64 = 5; - const EPROLOGUE_BAD_CHAIN_ID: u64 = 6; - const EPROLOGUE_MODULE_NOT_ALLOWED: u64 = 7; - const EPROLOGUE_SCRIPT_NOT_ALLOWED: u64 = 8; - - - /// The prologue is invoked at the beginning of every transaction - /// It verifies: - /// - The account's auth key matches the transaction's public key - /// - That the account has enough balance to pay for all of the gas - /// - That the sequence number matches the transaction's sequence key - public fun prologue( - account: signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - txn_expiration_time: u64, - chain_id: u8, - txn_payload_type: u8, - txn_script_or_package_hash: vector, - txn_package_address: address, - ) { - // Can only be invoked by genesis account - assert!( - Signer::address_of(&account) == CoreAddresses::GENESIS_ADDRESS(), - Errors::requires_address(EPROLOGUE_ACCOUNT_DOES_NOT_EXIST), - ); - // Check that the chain ID stored on-chain matches the chain ID - // specified by the transaction - assert!(ChainId::get() == chain_id, Errors::invalid_argument(EPROLOGUE_BAD_CHAIN_ID)); - let (stc_price,scaling_factor)= if (!STC::is_stc()){ - (GasOracleProposalPlugin::gas_oracle_read(),GasOracle::get_scaling_factor()) - }else{ - (1,1) - }; - - Account::txn_prologue_v2( - &account, - txn_sender, - txn_sequence_number, - txn_authentication_key_preimage, - txn_gas_price, - txn_max_gas_units, - stc_price, - scaling_factor, - ); - assert!( - TransactionTimeout::is_valid_transaction_timestamp(txn_expiration_time), - Errors::invalid_argument(EPROLOGUE_TRANSACTION_EXPIRED), - ); - if (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE) { - // stdlib upgrade is not affected by PublishOption - if (txn_package_address != CoreAddresses::GENESIS_ADDRESS()) { - assert!( - TransactionPublishOption::is_module_allowed(Signer::address_of(&account)), - Errors::invalid_argument(EPROLOGUE_MODULE_NOT_ALLOWED), - ); - }; - PackageTxnManager::package_txn_prologue_v2( - &account, - txn_sender, - txn_package_address, - txn_script_or_package_hash, - ); - } else if (txn_payload_type == TXN_PAYLOAD_TYPE_SCRIPT) { - assert!( - TransactionPublishOption::is_script_allowed( - Signer::address_of(&account), - ), - Errors::invalid_argument(EPROLOGUE_SCRIPT_NOT_ALLOWED), - ); - }; - // do nothing for TXN_PAYLOAD_TYPE_SCRIPT_FUNCTION - } - - spec prologue { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if ChainId::get() != chain_id; - aborts_if !exists(txn_sender); - aborts_if Hash::sha3_256(txn_authentication_key_preimage) != global(txn_sender).authentication_key; - aborts_if txn_gas_price * txn_max_gas_units > max_u64(); - include Timestamp::AbortsIfTimestampNotExists; - include Block::AbortsIfBlockMetadataNotExist; - aborts_if txn_gas_price * txn_max_gas_units > 0 && !exists>(txn_sender); - aborts_if txn_gas_price * txn_max_gas_units > 0 && txn_sequence_number >= max_u64(); - aborts_if txn_sequence_number < global(txn_sender).sequence_number; - aborts_if txn_sequence_number != global(txn_sender).sequence_number; - include TransactionTimeout::AbortsIfTimestampNotValid; - aborts_if !TransactionTimeout::spec_is_valid_transaction_timestamp(txn_expiration_time); - include TransactionPublishOption::AbortsIfTxnPublishOptionNotExistWithBool { - is_script_or_package: (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE || txn_payload_type == TXN_PAYLOAD_TYPE_SCRIPT), - }; - aborts_if txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE && txn_package_address != CoreAddresses::GENESIS_ADDRESS() && !TransactionPublishOption::spec_is_module_allowed(Signer::address_of(account)); - aborts_if txn_payload_type == TXN_PAYLOAD_TYPE_SCRIPT && !TransactionPublishOption::spec_is_script_allowed(Signer::address_of(account)); - include PackageTxnManager::CheckPackageTxnAbortsIfWithType{is_package: (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE), sender:txn_sender, package_address: txn_package_address, package_hash: txn_script_or_package_hash}; - } - - /// The epilogue is invoked at the end of transactions. - /// It collects gas and bumps the sequence number - public fun epilogue( - account: signer, - txn_sender: address, - txn_sequence_number: u64, - txn_gas_price: u64, - txn_max_gas_units: u64, - gas_units_remaining: u64, - txn_payload_type: u8, - _txn_script_or_package_hash: vector, - txn_package_address: address, - // txn execute success or fail. - success: bool, - ) { - epilogue_v2(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining, txn_payload_type, _txn_script_or_package_hash, txn_package_address, success) - } - - /// The epilogue is invoked at the end of transactions. - /// It collects gas and bumps the sequence number - public fun epilogue_v2( - account: signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - gas_units_remaining: u64, - txn_payload_type: u8, - _txn_script_or_package_hash: vector, - txn_package_address: address, - // txn execute success or fail. - success: bool, - ) { - CoreAddresses::assert_genesis_address(&account); - let (stc_price,scaling_factor) = - if (!STC::is_stc()){ - (GasOracleProposalPlugin::gas_oracle_read(),GasOracle::get_scaling_factor()) - }else{ - (1,1) - }; - Account::txn_epilogue_v3( - &account, - txn_sender, - txn_sequence_number, - txn_authentication_key_preimage, - txn_gas_price, - txn_max_gas_units, - gas_units_remaining, - stc_price, - scaling_factor - ); - if (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE) { - PackageTxnManager::package_txn_epilogue( - &account, - txn_sender, - txn_package_address, - success, - ); - } - } - - spec epilogue { - pragma verify = false;//fixme : timeout - include CoreAddresses::AbortsIfNotGenesisAddress; - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(txn_sender); - aborts_if !exists>(txn_sender); - aborts_if txn_max_gas_units < gas_units_remaining; - aborts_if txn_sequence_number + 1 > max_u64(); - aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u64(); - include PackageTxnManager::AbortsIfPackageTxnEpilogue { - is_package: (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE), - package_address: txn_package_address, - success: success, - }; - } - - /// Set the metadata for the current block and distribute transaction fees and block rewards. - /// The runtime always runs this before executing the transactions in a block. - public fun block_prologue( - account: signer, - parent_hash: vector, - timestamp: u64, - author: address, - auth_key_vec: vector, - uncles: u64, - number: u64, - chain_id: u8, - parent_gas_used: u64, - ) { - // Can only be invoked by genesis account - CoreAddresses::assert_genesis_address(&account); - // Check that the chain ID stored on-chain matches the chain ID - // specified by the transaction - assert!(ChainId::get() == chain_id, Errors::invalid_argument(EPROLOGUE_BAD_CHAIN_ID)); - - // deal with previous block first. - let txn_fee = TransactionFee::distribute_transaction_fees(&account); - - // then deal with current block. - Timestamp::update_global_time(&account, timestamp); - Block::process_block_metadata( - &account, - parent_hash, - author, - timestamp, - uncles, - number, - ); - let reward = Epoch::adjust_epoch(&account, number, timestamp, uncles, parent_gas_used); - // pass in previous block gas fees. - BlockReward::process_block_reward(&account, number, reward, author, auth_key_vec, txn_fee); - } - - spec block_prologue { - pragma verify = false;//fixme : timeout - } -} -} \ No newline at end of file diff --git a/release/v12/sources/TransactionPublishOption.move b/release/v12/sources/TransactionPublishOption.move deleted file mode 100644 index 285f55ec..00000000 --- a/release/v12/sources/TransactionPublishOption.move +++ /dev/null @@ -1,120 +0,0 @@ -address StarcoinFramework { -/// `TransactionPublishOption` provide an option to limit: -/// - whether user can use script or publish custom modules on chain. -module TransactionPublishOption { - use StarcoinFramework::Config; - use StarcoinFramework::Timestamp; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Signer; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_strict = true; - - } - spec fun spec_is_script_allowed(addr: address) : bool{ - let publish_option = Config::get_by_address(addr); - publish_option.script_allowed - } - - spec fun spec_is_module_allowed(addr: address) : bool{ - let publish_option = Config::get_by_address(addr); - publish_option.module_publishing_allowed - } - - const SCRIPT_HASH_LENGTH: u64 = 32; - - const EPROLOGUE_ACCOUNT_DOES_NOT_EXIST: u64 = 0; - const EINVALID_ARGUMENT: u64 = 18; - /// The script hash has an invalid length - const EINVALID_SCRIPT_HASH: u64 = 1001; - /// The script hash already exists in the allowlist - const EALLOWLIST_ALREADY_CONTAINS_SCRIPT: u64 = 1002; - - /// Defines and holds the publishing policies for the VM. There are three possible configurations: - /// 1. !script_allowed && !module_publishing_allowed No module publishing, only script function in module are allowed. - /// 2. script_allowed && !module_publishing_allowed No module publishing, custom scripts are allowed. - /// 3. script_allowed && module_publishing_allowed Both module publishing and custom scripts are allowed. - /// We represent these as the following resource. - struct TransactionPublishOption has copy, drop, store { - // Anyone can use script if this flag is set to true. - script_allowed: bool, - // Anyone can publish new module if this flag is set to true. - module_publishing_allowed: bool, - } - - /// Module initialization. - public fun initialize( - account: &signer, - script_allowed: bool, - module_publishing_allowed: bool, - ) { - Timestamp::assert_genesis(); - assert!( - Signer::address_of(account) == CoreAddresses::GENESIS_ADDRESS(), - Errors::requires_address(EPROLOGUE_ACCOUNT_DOES_NOT_EXIST), - ); - let transaction_publish_option = Self::new_transaction_publish_option(script_allowed, module_publishing_allowed); - Config::publish_new_config( - account, - transaction_publish_option, - ); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - include Config::PublishNewConfigAbortsIf; - include Config::PublishNewConfigEnsures; - } - - /// Create a new option. Mainly used in DAO. - public fun new_transaction_publish_option( - script_allowed: bool, - module_publishing_allowed: bool, - ): TransactionPublishOption { - TransactionPublishOption { script_allowed, module_publishing_allowed } - } - - spec new_transaction_publish_option { - aborts_if false; - } - - /// Check if sender can execute script with - public fun is_script_allowed(account: address): bool { - let publish_option = Config::get_by_address(account); - publish_option.script_allowed - } - - spec is_script_allowed { - include Config::AbortsIfConfigNotExist{ - addr: account - }; - } - - /// Check if a sender can publish a module - public fun is_module_allowed(account: address): bool { - let publish_option = Config::get_by_address(account); - publish_option.module_publishing_allowed - } - - spec is_module_allowed { - include Config::AbortsIfConfigNotExist{ - addr: account - }; - } - - spec schema AbortsIfTxnPublishOptionNotExist { - include Config::AbortsIfConfigNotExist{ - addr: CoreAddresses::GENESIS_ADDRESS() - }; - } - - spec schema AbortsIfTxnPublishOptionNotExistWithBool { - is_script_or_package : bool; - aborts_if is_script_or_package && !exists>(CoreAddresses::GENESIS_ADDRESS()); - } - -} -} \ No newline at end of file diff --git a/release/v12/sources/TransactionTimeout.move b/release/v12/sources/TransactionTimeout.move deleted file mode 100644 index 0f8e55e5..00000000 --- a/release/v12/sources/TransactionTimeout.move +++ /dev/null @@ -1,53 +0,0 @@ -address StarcoinFramework { -/// A module used to check expiration time of transactions. -module TransactionTimeout { - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Block; - use StarcoinFramework::TransactionTimeoutConfig; - use StarcoinFramework::Config; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - - } - - spec fun spec_is_valid_transaction_timestamp(txn_timestamp: u64):bool { - if (Block::get_current_block_number() == 0) { - txn_timestamp > Timestamp::now_seconds() - } else { - Timestamp::now_seconds() < txn_timestamp && txn_timestamp < - (Timestamp::now_seconds() + TransactionTimeoutConfig::duration_seconds()) - } - } - - /// Check whether the given timestamp is valid for transactions. - public fun is_valid_transaction_timestamp(txn_timestamp: u64): bool { - let current_block_time = Timestamp::now_seconds(); - let block_number = Block::get_current_block_number(); - // before first block, just require txn_timestamp > genesis timestamp. - if (block_number == 0) { - return txn_timestamp > current_block_time - }; - let timeout = TransactionTimeoutConfig::duration_seconds(); - let max_txn_time = current_block_time + timeout; - current_block_time < txn_timestamp && txn_timestamp < max_txn_time - } - spec is_valid_transaction_timestamp { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - include Timestamp::AbortsIfTimestampNotExists; - aborts_if Block::get_current_block_number() != 0 && Timestamp::now_seconds() + TransactionTimeoutConfig::duration_seconds() > max_u64(); - aborts_if Block::get_current_block_number() != 0 && !exists>(CoreAddresses::GENESIS_ADDRESS()); - } - - spec schema AbortsIfTimestampNotValid { - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - include Timestamp::AbortsIfTimestampNotExists; - aborts_if Block::get_current_block_number() != 0 && Timestamp::now_seconds() + TransactionTimeoutConfig::duration_seconds() > max_u64(); - aborts_if Block::get_current_block_number() != 0 && !exists>(CoreAddresses::GENESIS_ADDRESS()); - } -} -} diff --git a/release/v12/sources/TransactionTimeoutConfig.move b/release/v12/sources/TransactionTimeoutConfig.move deleted file mode 100644 index 57ddf4b0..00000000 --- a/release/v12/sources/TransactionTimeoutConfig.move +++ /dev/null @@ -1,76 +0,0 @@ -address StarcoinFramework { -/// Onchain configuration for timeout setting of transaction. -module TransactionTimeoutConfig { - use StarcoinFramework::Timestamp; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Config; - use StarcoinFramework::Signer; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// config structs. - struct TransactionTimeoutConfig has copy, drop, store { - /// timeout in second. - duration_seconds: u64, - } - - /// Initialize function. Should only be called in genesis. - public fun initialize(account: &signer, duration_seconds: u64) { - Timestamp::assert_genesis(); - CoreAddresses::assert_genesis_address(account); - - Config::publish_new_config( - account, - new_transaction_timeout_config(duration_seconds) - ); - } - - spec initialize { - aborts_if !Timestamp::is_genesis(); - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - include Config::PublishNewConfigAbortsIf; - include Config::PublishNewConfigEnsures; - } - - /// Create a new timeout config used in dao proposal. - public fun new_transaction_timeout_config(duration_seconds: u64) : TransactionTimeoutConfig { - TransactionTimeoutConfig {duration_seconds: duration_seconds} - } - - spec new_transaction_timeout_config { - aborts_if false; - } - - /// Get current timeout config. - public fun get_transaction_timeout_config(): TransactionTimeoutConfig { - Config::get_by_address(CoreAddresses::GENESIS_ADDRESS()) - } - - spec get_transaction_timeout_config { - include Config::AbortsIfConfigNotExist{ - addr: CoreAddresses::GENESIS_ADDRESS() - }; - } - - /// Get current txn timeout in seconds. - public fun duration_seconds() :u64 { - let config = get_transaction_timeout_config(); - config.duration_seconds - } - - spec duration_seconds { - include Config::AbortsIfConfigNotExist{ - addr: CoreAddresses::GENESIS_ADDRESS() - }; - } - - spec schema AbortsIfTxnTimeoutConfigNotExist { - include Config::AbortsIfConfigNotExist{ - addr: CoreAddresses::GENESIS_ADDRESS() - }; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/TransferScripts.move b/release/v12/sources/TransferScripts.move deleted file mode 100644 index cdd3073e..00000000 --- a/release/v12/sources/TransferScripts.move +++ /dev/null @@ -1,69 +0,0 @@ -address StarcoinFramework { - -module TransferScripts { - use StarcoinFramework::Account; - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - const EADDRESS_AND_AUTH_KEY_MISMATCH: u64 = 101; - const ELENGTH_MISMATCH: u64 = 102; - const EDEPRECATED_FUNCTION: u64 = 19; - - public(script) fun peer_to_peer(account: signer, payee: address, _payee_auth_key: vector, amount: u128) { - peer_to_peer_v2(account, payee, amount) - } - - public(script) fun peer_to_peer_v2(account: signer, payee: address, amount: u128) { - if (!Account::exists_at(payee)) { - Account::create_account_with_address(payee); - }; - Account::pay_from(&account, payee, amount) - } - - /// Batch transfer token to others. - public(script) fun batch_peer_to_peer(account: signer, payeees: vector
, _payee_auth_keys: vector>, amounts: vector) { - batch_peer_to_peer_v2(account, payeees, amounts) - } - - /// Batch transfer token to others. - public(script) fun batch_peer_to_peer_v2(account: signer, payeees: vector
, amounts: vector) { - let len = Vector::length(&payeees); - assert!(len == Vector::length(&amounts), ELENGTH_MISMATCH); - let i = 0; - while (i < len){ - let payee = *Vector::borrow(&payeees, i); - if (!Account::exists_at(payee)) { - Account::create_account_with_address(payee); - }; - let amount = *Vector::borrow(&amounts, i); - Account::pay_from(&account, payee, amount); - i = i + 1; - } - } - - public(script) fun peer_to_peer_batch(_account: signer, _payeees: vector, _payee_auth_keys: vector, _amount: u128) { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - public(script) fun peer_to_peer_with_metadata( - account: signer, - payee: address, - _payee_auth_key: vector, - amount: u128, - metadata: vector, - ) { - peer_to_peer_with_metadata_v2(account, payee, amount, metadata) - } - - public(script) fun peer_to_peer_with_metadata_v2( - account: signer, - payee: address, - amount: u128, - metadata: vector, - ) { - if (!Account::exists_at(payee)) { - Account::create_account_with_address(payee); - }; - Account::pay_from_with_metadata(&account,payee, amount, metadata) - } -} -} \ No newline at end of file diff --git a/release/v12/sources/Treasury.move b/release/v12/sources/Treasury.move deleted file mode 100644 index f2ca3e3e..00000000 --- a/release/v12/sources/Treasury.move +++ /dev/null @@ -1,388 +0,0 @@ -address StarcoinFramework { -/// The module for the Treasury of DAO, which can hold the token of DAO. -module Treasury { - use StarcoinFramework::Event; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Math; - use StarcoinFramework::Token::{Self, Token}; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - struct Treasury has store, key { - balance: Token, - /// event handle for treasury withdraw event - withdraw_events: Event::EventHandle, - /// event handle for treasury deposit event - deposit_events: Event::EventHandle, - } - - spec Treasury { - // invariant [abstract] balance.value <= Token::spec_abstract_total_value(); - } - - /// A withdraw capability allows tokens of type `TokenT` to be withdraw from Treasury. - struct WithdrawCapability has key, store {} - - /// A linear time withdraw capability which can withdraw token from Treasury in a period by time-based linear release. - struct LinearWithdrawCapability has key, store { - /// The total amount of tokens that can be withdrawn by this capability - total: u128, - /// The amount of tokens that have been withdrawn by this capability - withdraw: u128, - /// The time-based linear release start time, timestamp in seconds. - start_time: u64, - /// The time-based linear release period in seconds - period: u64, - } - - /// Message for treasury withdraw event. - struct WithdrawEvent has drop, store { - amount: u128, - } - /// Message for treasury deposit event. - struct DepositEvent has drop, store { - amount: u128, - } - - const ERR_INVALID_PERIOD: u64 = 101; - const ERR_ZERO_AMOUNT: u64 = 102; - const ERR_TOO_BIG_AMOUNT: u64 = 103; - const ERR_NOT_AUTHORIZED: u64 = 104; - const ERR_TREASURY_NOT_EXIST: u64 = 105; - - - /// Init a Treasury for TokenT. Can only be called by token issuer. - public fun initialize(signer: &signer, init_token: Token): WithdrawCapability { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - let treasure = Treasury { - balance: init_token, - withdraw_events: Event::new_event_handle(signer), - deposit_events: Event::new_event_handle(signer), - }; - move_to(signer, treasure); - WithdrawCapability{} - } - - spec initialize { - aborts_if Signer::address_of(signer) != Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - ensures exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - ensures result == WithdrawCapability{}; - } - - /// Check the Treasury of TokenT is exists. - public fun exists_at(): bool { - let token_issuer = Token::token_address(); - exists>(token_issuer) - } - - spec exists_at { - aborts_if false; - ensures result == exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - } - - /// Get the balance of TokenT's Treasury - /// if the Treasury do not exists, return 0. - public fun balance(): u128 acquires Treasury { - let token_issuer = Token::token_address(); - if (!exists>(token_issuer)) { - return 0 - }; - let treasury = borrow_global>(token_issuer); - Token::value(&treasury.balance) - } - - spec balance { - aborts_if false; - ensures if (exists>(Token::SPEC_TOKEN_TEST_ADDRESS())) - result == spec_balance() - else - result == 0; - } - - public fun deposit(token: Token) acquires Treasury { - assert!(exists_at(), Errors::not_published(ERR_TREASURY_NOT_EXIST)); - let token_address = Token::token_address(); - let treasury = borrow_global_mut>(token_address); - let amount = Token::value(&token); - Event::emit_event( - &mut treasury.deposit_events, - DepositEvent { amount }, - ); - Token::deposit(&mut treasury.balance, token); - } - - spec deposit { - aborts_if !exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - aborts_if spec_balance() + token.value > MAX_U128; - ensures spec_balance() == old(spec_balance()) + token.value; - } - - fun do_withdraw(amount: u128): Token acquires Treasury { - assert!(amount > 0, Errors::invalid_argument(ERR_ZERO_AMOUNT)); - assert!(exists_at(), Errors::not_published(ERR_TREASURY_NOT_EXIST)); - let token_address = Token::token_address(); - let treasury = borrow_global_mut>(token_address); - assert!(amount <= Token::value(&treasury.balance) , Errors::invalid_argument(ERR_TOO_BIG_AMOUNT)); - Event::emit_event( - &mut treasury.withdraw_events, - WithdrawEvent { amount }, - ); - Token::withdraw(&mut treasury.balance, amount) - } - - spec do_withdraw { - include WithdrawSchema; - } - - spec schema WithdrawSchema { - amount: u64; - - aborts_if amount <= 0; - aborts_if !exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - aborts_if spec_balance() < amount; - ensures spec_balance() == - old(spec_balance()) - amount; - } - - /// Withdraw tokens with given `LinearWithdrawCapability`. - public fun withdraw_with_capability( - _cap: &mut WithdrawCapability, - amount: u128, - ): Token acquires Treasury { - do_withdraw(amount) - } - - spec withdraw_with_capability { - include WithdrawSchema; - } - - /// Withdraw from TokenT's treasury, the signer must have WithdrawCapability - public fun withdraw( - signer: &signer, - amount: u128 - ): Token acquires Treasury, WithdrawCapability { - let cap = borrow_global_mut>(Signer::address_of(signer)); - Self::withdraw_with_capability(cap, amount) - } - - spec withdraw { - aborts_if !exists>(Signer::address_of(signer)); - include WithdrawSchema; - } - - /// Issue a `LinearWithdrawCapability` with given `WithdrawCapability`. - public fun issue_linear_withdraw_capability( - _capability: &mut WithdrawCapability, - amount: u128, - period: u64 - ): LinearWithdrawCapability { - assert!(period > 0, Errors::invalid_argument(ERR_INVALID_PERIOD)); - assert!(amount > 0, Errors::invalid_argument(ERR_ZERO_AMOUNT)); - let start_time = Timestamp::now_seconds(); - LinearWithdrawCapability { - total: amount, - withdraw: 0, - start_time, - period, - } - } - - spec issue_linear_withdraw_capability { - aborts_if period == 0; - aborts_if amount == 0; - aborts_if !exists(StarcoinFramework::CoreAddresses::GENESIS_ADDRESS()); - } - - /// Withdraw tokens with given `LinearWithdrawCapability`. - public fun withdraw_with_linear_capability( - cap: &mut LinearWithdrawCapability, - ): Token acquires Treasury { - let amount = withdraw_amount_of_linear_cap(cap); - let token = do_withdraw(amount); - cap.withdraw = cap.withdraw + amount; - token - } - - spec withdraw_with_linear_capability { - pragma aborts_if_is_partial; - // TODO: See [MUL_DIV] - // include WithdrawSchema {amount: ?}; - } - - /// Withdraw from TokenT's treasury, the signer must have LinearWithdrawCapability - public fun withdraw_by_linear( - signer: &signer, - ): Token acquires Treasury, LinearWithdrawCapability { - let cap = borrow_global_mut>(Signer::address_of(signer)); - Self::withdraw_with_linear_capability(cap) - } - - spec withdraw_by_linear { - pragma aborts_if_is_partial; - aborts_if !exists>(Signer::address_of(signer)); - // TODO: See [MUL_DIV] - // include WithdrawSchema {amount: ?}; - } - - /// Split the given `LinearWithdrawCapability`. - public fun split_linear_withdraw_cap( - cap: &mut LinearWithdrawCapability, - amount: u128, - ): (Token, LinearWithdrawCapability) acquires Treasury { - assert!(amount > 0, Errors::invalid_argument(ERR_ZERO_AMOUNT)); - let token = Self::withdraw_with_linear_capability(cap); - assert!((cap.withdraw + amount) <= cap.total, Errors::invalid_argument(ERR_TOO_BIG_AMOUNT)); - cap.total = cap.total - amount; - let start_time = Timestamp::now_seconds(); - let new_period = cap.start_time + cap.period - start_time; - let new_key = LinearWithdrawCapability { - total: amount, - withdraw: 0, - start_time, - period: new_period - }; - (token, new_key) - } - - spec split_linear_withdraw_cap { - pragma aborts_if_is_partial; - ensures old(cap.total - cap.withdraw) == - result_1.value + (result_2.total - result_2.withdraw) + (cap.total - cap.withdraw); - } - - - /// Returns the amount of the LinearWithdrawCapability can mint now. - public fun withdraw_amount_of_linear_cap(cap: &LinearWithdrawCapability): u128 { - let now = Timestamp::now_seconds(); - let elapsed_time = now - cap.start_time; - if (elapsed_time >= cap.period) { - cap.total - cap.withdraw - } else { - Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw - } - } - - spec withdraw_amount_of_linear_cap { - // TODO: [MUL_DIV] The most important property is the amount of value. - // However, Math::mul_div remains to be uninterpreted - pragma aborts_if_is_partial; - aborts_if !exists(StarcoinFramework::CoreAddresses::GENESIS_ADDRESS()); - aborts_if Timestamp::spec_now_seconds() < cap.start_time; - aborts_if Timestamp::spec_now_seconds() - cap.start_time >= cap.period && cap.total < cap.withdraw; - aborts_if [abstract] - Timestamp::spec_now_seconds() - cap.start_time < cap.period && Math::spec_mul_div() < cap.withdraw; - ensures [abstract] result <= cap.total - cap.withdraw; - } - - /// Check if the given `LinearWithdrawCapability` is empty. - public fun is_empty_linear_withdraw_cap(key: &LinearWithdrawCapability) : bool { - key.total == key.withdraw - } - - spec is_empty_linear_withdraw_cap { - aborts_if false; - ensures result == (key.total == key.withdraw); - } - - // Improvement: Make move prover support the following definition. - // Following specs contains lots of duplication - //spec schema AddCapability { - // signer: signer; - - // aborts_if exists(Signer::address_of(signer)); - // ensures exists(Signer::address_of(signer)); - //} - - /// Remove mint capability from `signer`. - public fun remove_withdraw_capability(signer: &signer): WithdrawCapability - acquires WithdrawCapability { - move_from>(Signer::address_of(signer)) - } - - spec remove_withdraw_capability { - aborts_if !exists>(Signer::address_of(signer)); - ensures !exists>(Signer::address_of(signer)); - } - - /// Save mint capability to `signer`. - public fun add_withdraw_capability(signer: &signer, cap: WithdrawCapability) { - move_to(signer, cap) - } - - spec add_withdraw_capability { - aborts_if exists>(Signer::address_of(signer)); - ensures exists>(Signer::address_of(signer)); - } - - /// Destroy the given mint capability. - public fun destroy_withdraw_capability(cap: WithdrawCapability) { - let WithdrawCapability {} = cap; - } - - spec destroy_withdraw_capability { - } - - /// Add LinearWithdrawCapability to `signer`, a address only can have one LinearWithdrawCapability - public fun add_linear_withdraw_capability(signer: &signer, cap: LinearWithdrawCapability) { - move_to(signer, cap) - } - - spec add_linear_withdraw_capability { - aborts_if exists>(Signer::address_of(signer)); - ensures exists>(Signer::address_of(signer)); - } - - /// Remove LinearWithdrawCapability from `signer`. - public fun remove_linear_withdraw_capability(signer: &signer): LinearWithdrawCapability - acquires LinearWithdrawCapability { - move_from>(Signer::address_of(signer)) - } - - spec remove_linear_withdraw_capability { - aborts_if !exists>(Signer::address_of(signer)); - ensures !exists>(Signer::address_of(signer)); - } - - /// Destroy LinearWithdrawCapability. - public fun destroy_linear_withdraw_capability(cap: LinearWithdrawCapability) { - let LinearWithdrawCapability{ total: _, withdraw: _, start_time: _, period: _ } = cap; - } - - public fun is_empty_linear_withdraw_capability(cap: &LinearWithdrawCapability): bool { - cap.total == cap.withdraw - } - - /// Get LinearWithdrawCapability total amount - public fun get_linear_withdraw_capability_total(cap: &LinearWithdrawCapability): u128 { - cap.total - } - - /// Get LinearWithdrawCapability withdraw amount - public fun get_linear_withdraw_capability_withdraw(cap: &LinearWithdrawCapability): u128 { - cap.withdraw - } - - /// Get LinearWithdrawCapability period in seconds - public fun get_linear_withdraw_capability_period(cap: &LinearWithdrawCapability): u64 { - cap.period - } - - /// Get LinearWithdrawCapability start_time in seconds - public fun get_linear_withdraw_capability_start_time(cap: &LinearWithdrawCapability): u64 { - cap.start_time - } - - - spec fun spec_balance(): num { - global>(Token::SPEC_TOKEN_TEST_ADDRESS()).balance.value - } - -} -} \ No newline at end of file diff --git a/release/v12/sources/TreasuryPlugin.move b/release/v12/sources/TreasuryPlugin.move deleted file mode 100644 index dbc8d672..00000000 --- a/release/v12/sources/TreasuryPlugin.move +++ /dev/null @@ -1,170 +0,0 @@ -module StarcoinFramework::TreasuryPlugin { - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::Token; - use StarcoinFramework::Treasury; - use StarcoinFramework::Token::Token; - use StarcoinFramework::CoreAddresses; - - const ERR_NOT_AUTHORIZED: u64 = 101; - /// Only receiver can execute treasury withdraw proposal - const ERR_NOT_RECEIVER: u64 = 102; - /// The withdraw amount of propose is too many. - const ERR_TOO_MANY_WITHDRAW_AMOUNT: u64 = 103; - const ERR_CAPABILITY_NOT_EXIST: u64 = 104; - const ERR_INVALID_SCALE_FACTOR: u64 = 105; - - struct TreasuryPlugin has store, drop {} - - /// A wrapper of Token MintCapability. - struct WithdrawCapabilityHolder has key { - cap: Treasury::WithdrawCapability, - } - - /// Scale up quorum_votes for withdraw proposal. - /// `scale` must be in [0, 100]. - /// The final quorum_votes = (1.0 + scale / 100) * base_quorum_votes - struct QuorumScale has copy, drop, store { - scale: u8, - } - - /// WithdrawToken request. - struct WithdrawTokenAction has copy, drop, store { - /// the receiver of withdraw tokens. - receiver: address, - /// how many tokens to mint. - amount: u128, - /// How long in milliseconds does it take for the token to be released - period: u64, - } - - public fun initialize(_sender: &signer) { - let witness = TreasuryPlugin {}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::TreasuryPlugin", - b"The plugin for withdraw token from Treasury.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://treasury-plugin", - ); - } - - /// Delegate Treasury::WithdrawCapability to DAO - /// Should be called by token issuer. - public fun delegate_capability(sender: &signer, cap: Treasury::WithdrawCapability) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - move_to(sender, WithdrawCapabilityHolder { cap }); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type()); - caps - } - - fun withdraw_limitation(): u128 { - let market_cap = Token::market_cap(); - let balance_in_treasury = Treasury::balance(); - let supply = market_cap - balance_in_treasury; - let rate = DAOSpace::voting_quorum_rate(); - let rate = (rate as u128); - supply * rate / 100 - } - - public fun create_withdraw_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - receiver: address, - amount: u128, - period: u64, - action_delay: u64) - { - let limit = withdraw_limitation(); - assert!(amount <= limit, Errors::invalid_argument(ERR_TOO_MANY_WITHDRAW_AMOUNT)); - let witness = TreasuryPlugin {}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = WithdrawTokenAction { - receiver, - amount, - period, - }; - - if (!DAOSpace::exists_custom_config()) { - set_scale_factor_inner(0u8); - }; - let scale = DAOSpace::get_custom_config().scale; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::some(scale)); - } - - public(script) fun create_withdraw_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - receiver: address, - amount: u128, - period: u64, - action_delay: u64) - { - create_withdraw_proposal(&sender, title, introduction, extend, receiver, amount, period, action_delay); - } - - public fun execute_withdraw_proposal(sender: &signer, proposal_id: u64) acquires WithdrawCapabilityHolder { - let witness = TreasuryPlugin {}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let WithdrawTokenAction { receiver, amount, period } = - DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - assert!(receiver == Signer::address_of(sender), Errors::not_published(ERR_NOT_RECEIVER)); - let token_issuer = Token::token_address(); - assert!(exists>(token_issuer), Errors::not_published(ERR_CAPABILITY_NOT_EXIST)); - let cap = borrow_global_mut>(token_issuer); - let linear_cap = Treasury::issue_linear_withdraw_capability(&mut cap.cap, amount, period); - Treasury::add_linear_withdraw_capability(sender, linear_cap); - } - - public(script) fun execute_withdraw_proposal_entry(sender: signer, proposal_id: u64) acquires WithdrawCapabilityHolder { - execute_withdraw_proposal(&sender, proposal_id); - } - - /// Provider a port for get block reward STC from Treasury, only genesis account can invoke this function. - /// The TreasuryWithdrawCapability is locked in TreasuryWithdrawDaoProposal, and only can withdraw by DAO proposal. - /// This approach is not graceful, but restricts the operation to genesis accounts only, so there are no security issues either. - public fun withdraw_for_block_reward(signer: &signer, reward: u128): Token - acquires WithdrawCapabilityHolder { - CoreAddresses::assert_genesis_address(signer); - let cap = borrow_global_mut>(Signer::address_of(signer)); - Treasury::withdraw_with_capability(&mut cap.cap, reward) - } - - public fun set_scale_factor(scale: u8, _witness: &DAOT) { - assert!( - scale >= 0 && scale <= 100, - Errors::invalid_argument(ERR_INVALID_SCALE_FACTOR), - ); - set_scale_factor_inner(scale); - } - - fun set_scale_factor_inner(scale: u8) { - let plugin = TreasuryPlugin {}; - let cap = DAOSpace::acquire_modify_config_cap(&plugin); - DAOSpace::set_custom_config(&mut cap, QuorumScale { scale }); - } -} \ No newline at end of file diff --git a/release/v12/sources/TreasuryScripts.move b/release/v12/sources/TreasuryScripts.move deleted file mode 100644 index b014da0c..00000000 --- a/release/v12/sources/TreasuryScripts.move +++ /dev/null @@ -1,79 +0,0 @@ -address StarcoinFramework { -module TreasuryScripts { - use StarcoinFramework::Treasury; - use StarcoinFramework::Account; - use StarcoinFramework::Offer; - use StarcoinFramework::TreasuryWithdrawDaoProposal; - - public(script) fun withdraw_and_split_lt_withdraw_cap( - signer: signer, - for_address: address, - amount: u128, - lock_period: u64, - ) { - // 1. take cap: LinearWithdrawCapability - let cap = Treasury::remove_linear_withdraw_capability(&signer); - - // 2. withdraw token and split - let (tokens, new_cap) = Treasury::split_linear_withdraw_cap(&mut cap, amount); - - // 3. deposit - Account::deposit_to_self(&signer, tokens); - - // 4. put or destroy key - if (Treasury::is_empty_linear_withdraw_capability(&cap)) { - Treasury::destroy_linear_withdraw_capability(cap); - } else { - Treasury::add_linear_withdraw_capability(&signer, cap); - }; - - // 5. offer - Offer::create(&signer, new_cap, for_address, lock_period); - } - - spec withdraw_and_split_lt_withdraw_cap { - pragma verify = false; - } - - public(script) fun withdraw_token_with_linear_withdraw_capability( - signer: signer, - ) { - // 1. take cap - let cap = Treasury::remove_linear_withdraw_capability(&signer); - - // 2. withdraw token - let tokens = Treasury::withdraw_with_linear_capability(&mut cap); - - // 3. deposit - Account::deposit_to_self(&signer, tokens); - - // 4. put or destroy key - if (Treasury::is_empty_linear_withdraw_capability(&cap)) { - Treasury::destroy_linear_withdraw_capability(cap); - } else { - Treasury::add_linear_withdraw_capability(&signer, cap); - }; - } - - spec withdraw_token_with_linear_withdraw_capability { - pragma verify = false; - } - - public(script) fun propose_withdraw(signer: signer, receiver: address, amount: u128, period: u64, exec_delay: u64){ - TreasuryWithdrawDaoProposal::propose_withdraw(&signer, receiver, amount, period, exec_delay) - } - - spec propose_withdraw { - pragma verify = false; - } - - public(script) fun execute_withdraw_proposal(signer: signer, proposer_address: address, - proposal_id: u64,){ - TreasuryWithdrawDaoProposal::execute_withdraw_proposal(&signer, proposer_address, proposal_id); - } - - spec execute_withdraw_proposal { - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/TreasuryWithdrawDaoProposal.move b/release/v12/sources/TreasuryWithdrawDaoProposal.move deleted file mode 100644 index 1053cb12..00000000 --- a/release/v12/sources/TreasuryWithdrawDaoProposal.move +++ /dev/null @@ -1,131 +0,0 @@ -address StarcoinFramework { -/// TreasuryWithdrawDaoProposal is a dao proposal for withdraw Token from Treasury. -module TreasuryWithdrawDaoProposal { - use StarcoinFramework::Token::{Self,Token}; - use StarcoinFramework::Signer; - use StarcoinFramework::Dao; - use StarcoinFramework::Errors; - use StarcoinFramework::Treasury; - use StarcoinFramework::CoreAddresses; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_strict; - pragma aborts_if_is_partial; - } - - /// A wrapper of Token MintCapability. - struct WrappedWithdrawCapability has key { - cap: Treasury::WithdrawCapability, - } - - /// WithdrawToken request. - struct WithdrawToken has copy, drop, store { - /// the receiver of withdraw tokens. - receiver: address, - /// how many tokens to mint. - amount: u128, - /// How long in milliseconds does it take for the token to be released - period: u64, - } - - const ERR_NOT_AUTHORIZED: u64 = 101; - /// Only receiver can execute TreasuryWithdrawDaoProposal - const ERR_NEED_RECEIVER_TO_EXECUTE: u64 = 102; - /// The withdraw amount of propose is too many. - const ERR_TOO_MANY_WITHDRAW_AMOUNT: u64 = 103; - const ERR_CAPABILITY_NOT_EXIST: u64 = 104; - - /// Plugin method of the module. - /// Should be called by token issuer. - public fun plugin(signer: &signer, cap: Treasury::WithdrawCapability) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - move_to(signer, WrappedWithdrawCapability { cap: cap }); - } - - /// withdraw Treasury::WithdrawCapability - public fun takeout_withdraw_capability(sender: &signer): Treasury::WithdrawCapability - acquires WrappedWithdrawCapability { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - - assert!(exists>(Signer::address_of(sender)), Errors::not_published(ERR_CAPABILITY_NOT_EXIST)); - let WrappedWithdrawCapability { cap } = move_from>(Signer::address_of(sender)); - cap - } - - spec plugin { - pragma aborts_if_is_partial = false; - let sender = Signer::address_of(signer); - aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if !exists>(sender); - aborts_if exists>(sender); - - ensures !exists>(sender); - ensures exists>(sender); - } - - - /// Entrypoint for the proposal. - public fun propose_withdraw(signer: &signer, receiver: address, amount: u128, period: u64, exec_delay: u64) { - let quorum_votes = Dao::quorum_votes(); - assert!(amount <= quorum_votes, Errors::invalid_argument(ERR_TOO_MANY_WITHDRAW_AMOUNT)); - Dao::propose( - signer, - WithdrawToken { receiver, amount, period }, - exec_delay, - ); - } - spec propose_withdraw { - use StarcoinFramework::Timestamp; - use StarcoinFramework::CoreAddresses; - pragma aborts_if_is_partial = false; - let quorum_votes = Dao::spec_quorum_votes(); - aborts_if amount > quorum_votes; - // copy from Dao::propose spec. - include Dao::AbortIfDaoConfigNotExist; - include Dao::AbortIfDaoInfoNotExist; - aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); - aborts_if exec_delay > 0 && exec_delay < Dao::spec_dao_config().min_action_delay; - include Dao::CheckQuorumVotes; - let sender = Signer::address_of(signer); - aborts_if exists>(sender); - } - - /// Once the proposal is agreed, anyone can call the method to make the proposal happen. - public fun execute_withdraw_proposal( - signer: &signer, - proposer_address: address, - proposal_id: u64, - ) acquires WrappedWithdrawCapability { - let WithdrawToken { receiver, amount, period } = Dao::extract_proposal_action( - proposer_address, - proposal_id, - ); - assert!(receiver == Signer::address_of(signer), Errors::requires_address(ERR_NEED_RECEIVER_TO_EXECUTE)); - let cap = borrow_global_mut>(Token::token_address()); - let linear_cap = Treasury::issue_linear_withdraw_capability(&mut cap.cap, amount, period); - Treasury::add_linear_withdraw_capability(signer, linear_cap); - } - - spec execute_withdraw_proposal { - use StarcoinFramework::Option; - pragma aborts_if_is_partial = true; - let expected_states = vec(6); - include Dao::CheckProposalStates{expected_states}; - let proposal = global>(proposer_address); - aborts_if Option::is_none(proposal.action); - aborts_if !exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); - } - - /// Provider a port for get block reward STC from Treasury, only genesis account can invoke this function. - /// The TreasuryWithdrawCapability is locked in TreasuryWithdrawDaoProposal, and only can withdraw by DAO proposal. - /// This approach is not graceful, but restricts the operation to genesis accounts only, so there are no security issues either. - public fun withdraw_for_block_reward(signer: &signer, reward: u128):Token acquires WrappedWithdrawCapability { - CoreAddresses::assert_genesis_address(signer); - let cap = borrow_global_mut>(Signer::address_of(signer)); - Treasury::withdraw_with_capability(&mut cap.cap, reward) - } -} -} \ No newline at end of file diff --git a/release/v12/sources/TypeInfo.move b/release/v12/sources/TypeInfo.move deleted file mode 100644 index 933e43ec..00000000 --- a/release/v12/sources/TypeInfo.move +++ /dev/null @@ -1,30 +0,0 @@ -module StarcoinFramework::TypeInfo{ - use StarcoinFramework::Token; - - struct TypeInfo has copy, drop, store{ - account_address: address, - module_name: vector, - struct_name: vector - } - - public fun account_address(type_info: &TypeInfo):address{ - type_info.account_address - } - - public fun module_name(type_info: &TypeInfo):vector{ - *&type_info.module_name - } - - public fun struct_name(type_info: &TypeInfo):vector{ - *&type_info.struct_name - } - - public fun type_of():TypeInfo{ - let (account_address, module_name, struct_name) = Token::type_of(); - TypeInfo { - account_address, - module_name, - struct_name - } - } -} \ No newline at end of file diff --git a/release/v12/sources/U256.move b/release/v12/sources/U256.move deleted file mode 100644 index f83dfdfb..00000000 --- a/release/v12/sources/U256.move +++ /dev/null @@ -1,438 +0,0 @@ -address StarcoinFramework { -/// Helper module to do u64 arith. -module Arith { - use StarcoinFramework::Errors; - const ERR_INVALID_CARRY: u64 = 301; - const ERR_INVALID_BORROW: u64 = 302; - - const P32: u64 = 0x100000000; - const P64: u128 = 0x10000000000000000; - - spec module { - pragma verify = true; - pragma aborts_if_is_strict; - } - - /// split u64 to (high, low) - public fun split_u64(i: u64): (u64, u64) { - (i >> 32, i & 0xFFFFFFFF) - } - - spec split_u64 { - pragma opaque; // MVP cannot reason about bitwise operation - ensures result_1 == i / P32; - ensures result_2 == i % P32; - } - - /// combine (high, low) to u64, - /// any lower bits of `high` will be erased, any higher bits of `low` will be erased. - public fun combine_u64(hi: u64, lo: u64): u64 { - (hi << 32) | (lo & 0xFFFFFFFF) - } - - spec combine_u64 { - pragma opaque; // MVP cannot reason about bitwise operation - let hi_32 = hi % P32; - let lo_32 = lo % P32; - ensures result == hi_32 * P32 + lo_32; - } - - /// a + b, with carry - public fun adc(a: u64, b: u64, carry: &mut u64) : u64 { - assert!(*carry <= 1, Errors::invalid_argument(ERR_INVALID_CARRY)); - let (a1, a0) = split_u64(a); - let (b1, b0) = split_u64(b); - let (c, r0) = split_u64(a0 + b0 + *carry); - let (c, r1) = split_u64(a1 + b1 + c); - *carry = c; - combine_u64(r1, r0) - } - - spec adc { - // Carry has either to be 0 or 1 - aborts_if !(carry == 0 || carry == 1); - ensures carry == 0 || carry == 1; - // Result with or without carry - ensures carry == 0 ==> result == a + b + old(carry); - ensures carry == 1 ==> P64 + result == a + b + old(carry); - } - - /// a - b, with borrow - public fun sbb(a: u64, b: u64, borrow: &mut u64): u64 { - assert!(*borrow <= 1, Errors::invalid_argument(ERR_INVALID_BORROW)); - let (a1, a0) = split_u64(a); - let (b1, b0) = split_u64(b); - let (b, r0) = split_u64(P32 + a0 - b0 - *borrow); - let borrowed = 1 - b; - let (b, r1) = split_u64(P32 + a1 - b1 - borrowed); - *borrow = 1 - b; - - combine_u64(r1, r0) - } - - spec sbb { - // Borrow has either to be 0 or 1 - aborts_if !(borrow == 0 || borrow == 1); - ensures borrow == 0 || borrow == 1; - // Result with or without borrow - ensures borrow == 0 ==> result == a - b - old(borrow); - ensures borrow == 1 ==> result == P64 + a - b - old(borrow); - } -} - -/// Implementation u256. -module U256 { - - spec module { - pragma verify = true; - } - - use StarcoinFramework::Vector; - use StarcoinFramework::Errors; - - const WORD: u8 = 4; - const P32: u64 = 0x100000000; - const P64: u128 = 0x10000000000000000; - - const ERR_INVALID_LENGTH: u64 = 100; - const ERR_OVERFLOW: u64 = 200; - /// use vector to represent data. - /// so that we can use buildin vector ops later to construct U256. - /// vector should always has two elements. - struct U256 has copy, drop, store { - /// little endian representation - bits: vector, - } - - spec U256 { - invariant len(bits) == 4; - } - - spec fun value_of_U256(a: U256): num { - a.bits[0] + - a.bits[1] * P64 + - a.bits[2] * P64 * P64 + - a.bits[3] * P64 * P64 * P64 - } - - public fun zero(): U256 { - from_u128(0u128) - } - - public fun one(): U256 { - from_u128(1u128) - } - - public fun from_u64(v: u64): U256 { - from_u128((v as u128)) - } - - public fun from_u128(v: u128): U256 { - let low = ((v & 0xffffffffffffffff) as u64); - let high = ((v >> 64) as u64); - let bits = Vector::singleton(low); - Vector::push_back(&mut bits, high); - Vector::push_back(&mut bits, 0u64); - Vector::push_back(&mut bits, 0u64); - U256 { bits } - } - - spec from_u128 { - pragma opaque; // Original function has bitwise operator - ensures value_of_U256(result) == v; - } - - #[test] - fun test_from_u128() { - // 2^64 + 1 - let v = from_u128(18446744073709551617u128); - assert!(*Vector::borrow(&v.bits, 0) == 1, 0); - assert!(*Vector::borrow(&v.bits, 1) == 1, 1); - assert!(*Vector::borrow(&v.bits, 2) == 0, 2); - assert!(*Vector::borrow(&v.bits, 3) == 0, 3); - } - - public fun from_big_endian(data: vector): U256 { - // TODO: define error code. - assert!(Vector::length(&data) <= 32, Errors::invalid_argument(ERR_INVALID_LENGTH)); - from_bytes(&data, true) - } - - spec from_big_endian { - pragma verify = false; // TODO: How to interpret the value of vector data of bytes - } - - public fun from_little_endian(data: vector): U256 { - // TODO: define error code. - assert!(Vector::length(&data) <= 32, Errors::invalid_argument(ERR_INVALID_LENGTH)); - from_bytes(&data, false) - } - - spec from_little_endian { - pragma verify = false; // TODO: How to interpret the value of vector data of bytes - } - - public fun to_u128(v: &U256): u128 { - assert!(*Vector::borrow(&v.bits, 3) == 0, Errors::invalid_state(ERR_OVERFLOW)); - assert!(*Vector::borrow(&v.bits, 2) == 0, Errors::invalid_state(ERR_OVERFLOW)); - ((*Vector::borrow(&v.bits, 1) as u128) << 64) | (*Vector::borrow(&v.bits, 0) as u128) - } - - spec to_u128 { - pragma opaque; // Original function has bitwise operator - aborts_if value_of_U256(v) >= P64 * P64; - ensures value_of_U256(v) == result; - } - - #[test] - fun test_to_u128() { - // 2^^128 - 1 - let i = 340282366920938463463374607431768211455u128; - let v = from_u128(i); - assert!(to_u128(&v) == i, 128); - } - #[test] - #[expected_failure] - fun test_to_u128_overflow() { - // 2^^128 - 1 - let i = 340282366920938463463374607431768211455u128; - let v = from_u128(i); - let v = add(v, one()); - to_u128(&v); - } - - const EQUAL: u8 = 0; - const LESS_THAN: u8 = 1; - const GREATER_THAN: u8 = 2; - - public fun compare(a: &U256, b: &U256): u8 { - let i = (WORD as u64); - while (i > 0) { - i = i - 1; - let a_bits = *Vector::borrow(&a.bits, i); - let b_bits = *Vector::borrow(&b.bits, i); - if (a_bits != b_bits) { - if (a_bits < b_bits) { - return LESS_THAN - } else { - return GREATER_THAN - } - } - }; - return EQUAL - } - - // TODO: MVP interprets it wrong - // spec compare { - // let va = value_of_U256(a); - // let vb = value_of_U256(b); - // ensures (va > vb) ==> (result == GREATER_THAN); - // ensures (va < vb) ==> (result == LESS_THAN); - // ensures (va == vb) ==> (result == EQUAL); - // } - - #[test] - fun test_compare() { - let a = from_u64(111); - let b = from_u64(111); - let c = from_u64(112); - let d = from_u64(110); - assert!(compare(&a, &b) == EQUAL, 0); - assert!(compare(&a, &c) == LESS_THAN, 1); - assert!(compare(&a, &d) == GREATER_THAN, 2); - } - - - public fun add(a: U256, b: U256): U256 { - native_add(&mut a, &b); - a - } - - spec add { - aborts_if value_of_U256(a) + value_of_U256(b) >= P64 * P64 * P64 * P64; - ensures value_of_U256(result) == value_of_U256(a) + value_of_U256(b); - } - - #[test] - fun test_add() { - let a = Self::one(); - let b = Self::from_u128(10); - let ret = Self::add(a, b); - assert!(compare(&ret, &from_u64(11)) == EQUAL, 0); - } - - public fun sub(a: U256, b: U256): U256 { - native_sub(&mut a, &b); - a - } - - spec sub { - aborts_if value_of_U256(a) < value_of_U256(b); - ensures value_of_U256(result) == value_of_U256(a) - value_of_U256(b); - } - - #[test] - #[expected_failure] - fun test_sub_overflow() { - let a = Self::one(); - let b = Self::from_u128(10); - let _ = Self::sub(a, b); - } - - #[test] - fun test_sub_ok() { - let a = Self::from_u128(10); - let b = Self::one(); - let ret = Self::sub(a, b); - assert!(compare(&ret, &from_u64(9)) == EQUAL, 0); - } - - public fun mul(a: U256, b: U256): U256 { - native_mul(&mut a, &b); - a - } - - spec mul { - pragma verify = false; - pragma timeout = 200; // Take longer time - aborts_if value_of_U256(a) * value_of_U256(b) >= P64 * P64 * P64 * P64; - ensures value_of_U256(result) == value_of_U256(a) * value_of_U256(b); - } - - #[test] - fun test_mul() { - let a = Self::from_u128(10); - let b = Self::from_u64(10); - let ret = Self::mul(a, b); - assert!(compare(&ret, &from_u64(100)) == EQUAL, 0); - } - - public fun div(a: U256, b: U256): U256 { - native_div(&mut a, &b); - a - } - - spec div { - pragma verify = false; - pragma timeout = 160; // Might take longer time - aborts_if value_of_U256(b) == 0; - ensures value_of_U256(result) == value_of_U256(a) / value_of_U256(b); - } - - #[test] - fun test_div() { - let a = Self::from_u128(10); - let b = Self::from_u64(2); - let c = Self::from_u64(3); - // as U256 cannot be implicitly copied, we need to add copy keyword. - assert!(compare(&Self::div(copy a, b), &from_u64(5)) == EQUAL, 0); - assert!(compare(&Self::div(copy a, c), &from_u64(3)) == EQUAL, 0); - } - - public fun rem(a: U256, b: U256): U256 { - native_rem(&mut a, &b); - a - } - - spec rem { - pragma verify = false; - pragma timeout = 160; // Might take longer time - aborts_if value_of_U256(b) == 0; - ensures value_of_U256(result) == value_of_U256(a) % value_of_U256(b); - } - - #[test] - fun test_rem() { - let a = Self::from_u128(10); - let b = Self::from_u64(2); - let c = Self::from_u64(3); - assert!(compare(&Self::rem(copy a, b), &from_u64(0)) == EQUAL, 0); - assert!(compare(&Self::rem(copy a, c), &from_u64(1)) == EQUAL, 0); - } - - public fun pow(a: U256, b: U256): U256 { - native_pow(&mut a, &b); - a - } - - spec pow { - // Verfication of Pow takes enormous amount of time - // Don't verify it, and make it opaque so that the caller - // can make use of the properties listed here. - pragma verify = false; - pragma opaque; - pragma timeout = 600; - let p = pow_spec(value_of_U256(a), value_of_U256(b)); - aborts_if p >= P64 * P64 * P64 * P64; - ensures value_of_U256(result) == p; - } - - #[test] - fun test_pow() { - let a = Self::from_u128(10); - let b = Self::from_u64(1); - let c = Self::from_u64(2); - let d = Self::zero(); - assert!(compare(&Self::pow(copy a, b), &from_u64(10)) == EQUAL, 0); - assert!(compare(&Self::pow(copy a, c), &from_u64(100)) == EQUAL, 0); - assert!(compare(&Self::pow(copy a, d), &from_u64(1)) == EQUAL, 0); - } - - native fun from_bytes(data: &vector, be: bool): U256; - native fun native_add(a: &mut U256, b: &U256); - native fun native_sub(a: &mut U256, b: &U256); - native fun native_mul(a: &mut U256, b: &U256); - native fun native_div(a: &mut U256, b: &U256); - native fun native_rem(a: &mut U256, b: &U256); - native fun native_pow(a: &mut U256, b: &U256); - - spec native_add { - pragma opaque; - aborts_if value_of_U256(a) + value_of_U256(b) >= P64 * P64 * P64 * P64; - ensures value_of_U256(a) == value_of_U256(old(a)) + value_of_U256(b); - } - - spec native_sub { - pragma opaque; - aborts_if value_of_U256(a) - value_of_U256(b) < 0; - ensures value_of_U256(a) == value_of_U256(old(a)) - value_of_U256(b); - } - - spec native_mul { - pragma opaque; - aborts_if value_of_U256(a) * value_of_U256(b) >= P64 * P64 * P64 * P64; - ensures value_of_U256(a) == value_of_U256(old(a)) * value_of_U256(b); - } - - spec native_div { - pragma opaque; - aborts_if value_of_U256(b) == 0; - ensures value_of_U256(a) == value_of_U256(old(a)) / value_of_U256(b); - } - - spec native_rem { - pragma opaque; - aborts_if value_of_U256(b) == 0; - ensures value_of_U256(a) == value_of_U256(old(a)) % value_of_U256(b); - } - - spec native_pow { - pragma opaque; - aborts_if pow_spec(value_of_U256(a), value_of_U256(b)) >= P64 * P64 * P64 * P64; - ensures value_of_U256(a) == pow_spec(value_of_U256(old(a)), value_of_U256(b)); - } - - spec fun pow_spec(base: num, expon: num): num { - // This actually doesn't follow a strict definition as 0^0 is undefined - // mathematically. But the U256::pow of Rust is defined to be like this: - // Link: https://docs.rs/uint/0.9.3/src/uint/uint.rs.html#1000-1003 - if (expon > 0) { - let x = pow_spec(base, expon / 2); - if (expon % 2 == 0) { x * x } else { x * x * base } - } else { - 1 - } - } - -} -} diff --git a/release/v12/sources/UpgradeModuleDaoProposal.move b/release/v12/sources/UpgradeModuleDaoProposal.move deleted file mode 100644 index 7bbd37dc..00000000 --- a/release/v12/sources/UpgradeModuleDaoProposal.move +++ /dev/null @@ -1,126 +0,0 @@ -address StarcoinFramework { -/// UpgradeModuleDaoProposal is a proposal moudle used to upgrade contract codes under a token. -module UpgradeModuleDaoProposal { - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - use StarcoinFramework::Option; - use StarcoinFramework::Dao; - use StarcoinFramework::Errors; - - friend StarcoinFramework::StdlibUpgradeScripts; - - spec module { - pragma verify = false; // break after enabling v2 compilation scheme - pragma aborts_if_is_strict; - pragma aborts_if_is_partial; - } - - const ERR_UNABLE_TO_UPGRADE: u64 = 400; - const ERR_NOT_AUTHORIZED: u64 = 401; - const ERR_ADDRESS_MISSMATCH: u64 = 402; - - /// A wrapper of `PackageTxnManager::UpgradePlanCapability`. - struct UpgradeModuleCapability has key { - cap: PackageTxnManager::UpgradePlanCapability, - } - - /// request of upgrading module contract code. - struct UpgradeModule has copy, drop, store { - module_address: address, - package_hash: vector, - version: u64, - } - - struct UpgradeModuleV2 has copy, drop, store { - module_address: address, - package_hash: vector, - version: u64, - enforced: bool, - } - - /// If this goverment can upgrade module, call this to register capability. - public fun plugin( - signer: &signer, - cap: PackageTxnManager::UpgradePlanCapability, - ) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(signer) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - move_to(signer, UpgradeModuleCapability { cap }) - } - - spec plugin { - pragma aborts_if_is_partial = false; - - let sender = Signer::address_of(signer); - aborts_if sender != Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if exists>(sender); - } - - public (friend) fun get_genesis_upgrade_cap():PackageTxnManager::UpgradePlanCapability acquires UpgradeModuleCapability{ - let UpgradeModuleCapability{ - cap - } = move_from(Token::token_address()); - cap - } - - spec schema AbortIfUnableUpgrade { - module_address: address; - let token_issuer = Token::SPEC_TOKEN_TEST_ADDRESS(); - aborts_if !exists>(token_issuer); - let cap = global>(token_issuer).cap; - aborts_if PackageTxnManager::account_address(cap) != module_address; - } - - public fun propose_module_upgrade_v2( - signer: &signer, - module_address: address, - package_hash: vector, - version: u64, - exec_delay: u64, - enforced: bool, - ) acquires UpgradeModuleCapability { - let cap = borrow_global>(Token::token_address()); - let account_address = PackageTxnManager::account_address(&cap.cap); - assert!(account_address == module_address, Errors::requires_capability(ERR_ADDRESS_MISSMATCH)); - Dao::propose( - signer, - UpgradeModuleV2 { module_address, package_hash, version, enforced }, - exec_delay, - ); - } - - spec propose_module_upgrade_v2 { - pragma aborts_if_is_partial = true; - include AbortIfUnableUpgrade; - } - - /// Once the proposal is agreed, anyone can call this method to generate the upgrading plan. - public fun submit_module_upgrade_plan( - proposer_address: address, - proposal_id: u64, - ) acquires UpgradeModuleCapability { - let UpgradeModuleV2 { module_address, package_hash, version, enforced } = Dao::extract_proposal_action< - TokenT, - UpgradeModuleV2, - >(proposer_address, proposal_id); - let cap = borrow_global>(Token::token_address()); - let account_address = PackageTxnManager::account_address(&cap.cap); - assert!(account_address == module_address, Errors::requires_capability(ERR_ADDRESS_MISSMATCH)); - PackageTxnManager::submit_upgrade_plan_with_cap_v2( - &cap.cap, - package_hash, - version, - enforced, - ); - } - spec submit_module_upgrade_plan { - let expected_states = vec(6); - include Dao::CheckProposalStates{expected_states}; - let proposal = global>(proposer_address); - aborts_if Option::is_none(proposal.action); - let action = proposal.action.vec[0]; - include AbortIfUnableUpgrade{module_address: action.module_address}; - } -} -} \ No newline at end of file diff --git a/release/v12/sources/UpgradeModulePlugin.move b/release/v12/sources/UpgradeModulePlugin.move deleted file mode 100644 index 23f546de..00000000 --- a/release/v12/sources/UpgradeModulePlugin.move +++ /dev/null @@ -1,91 +0,0 @@ -module StarcoinFramework::UpgradeModulePlugin { - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct UpgradeModulePlugin has store, drop{} - - struct UpgradeModuleAction has store, drop { - package_hash: vector, - version: u64, - enforced: bool - } - - public fun initialize(_sender: &signer) { - let witness = UpgradeModulePlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::UpgradeModulePlugin", - b"The plugin for upgrade module.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://upgrade-module-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::upgrade_module_cap_type()); - caps - } - - public fun create_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, action_delay:u64, package_hash: vector, version: u64, enforced: bool) { - let witness = UpgradeModulePlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = UpgradeModuleAction{ - package_hash, - version, - enforced - }; - DAOSpace::create_proposal< - DAOT, - UpgradeModulePlugin, - UpgradeModuleAction>(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_proposal_entry (sender: signer, title:vector, introduction:vector, extend: vector, action_delay:u64, package_hash: vector, version: u64, enforced: bool) { - create_proposal(&sender, title, introduction, extend, action_delay, package_hash, version, enforced); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64) { - let witness = UpgradeModulePlugin{}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - let upgrade_module_cap = - DAOSpace::acquire_upgrade_module_cap(&witness); - - let UpgradeModuleAction{ - package_hash, - version, - enforced - } = DAOSpace::execute_proposal< - DAOT, - UpgradeModulePlugin, - UpgradeModuleAction>(&proposal_cap, sender, proposal_id); - DAOSpace::submit_upgrade_plan(&mut upgrade_module_cap, package_hash, version, enforced); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64) { - execute_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender,required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} \ No newline at end of file diff --git a/release/v12/sources/VMConfig.move b/release/v12/sources/VMConfig.move deleted file mode 100644 index 6a938d2d..00000000 --- a/release/v12/sources/VMConfig.move +++ /dev/null @@ -1,413 +0,0 @@ -address StarcoinFramework { -/// `VMConfig` keep track of VM related configuration, like gas schedule. -module VMConfig { - use StarcoinFramework::Config; - use StarcoinFramework::Signer; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Vector; - use StarcoinFramework::ChainId; - spec module { - pragma verify = false; - pragma aborts_if_is_strict; - } - - /// The struct to hold all config data needed to operate the VM. - /// * gas_schedule: Cost of running the VM. - struct VMConfig has copy, drop, store { - gas_schedule: GasSchedule, - } - - /// The gas schedule keeps two separate schedules for the gas: - /// * The instruction_schedule: This holds the gas for each bytecode instruction. - /// * The native_schedule: This holds the gas for used (per-byte operated over) for each native - /// function. - /// A couple notes: - /// 1. In the case that an instruction is deleted from the bytecode, that part of the cost schedule - /// still needs to remain the same; once a slot in the table is taken by an instruction, that is its - /// slot for the rest of time (since that instruction could already exist in a module on-chain). - /// 2. The initialization of the module will publish the instruction table to the genesis - /// address, and will preload the vector with the gas schedule for instructions. The VM will then - /// load this into memory at the startup of each block. - struct GasSchedule has copy, drop, store { - instruction_schedule: vector, - native_schedule: vector, - gas_constants: GasConstants, - } - - /// The gas constants contains all kind of constants used in gas calculation. - struct GasConstants has copy, drop, store { - /// The cost per-byte written to global storage. - global_memory_per_byte_cost: u64, - /// The cost per-byte written to storage. - global_memory_per_byte_write_cost: u64, - /// We charge one unit of gas per-byte for the first 600 bytes - min_transaction_gas_units: u64, - /// Any transaction over this size will be charged `INTRINSIC_GAS_PER_BYTE` per byte - large_transaction_cutoff: u64, - /// The units of gas that should be charged per byte for every transaction. - instrinsic_gas_per_byte: u64, - /// 1 nanosecond should equal one unit of computational gas. We bound the maximum - /// computational time of any given transaction at 10 milliseconds. We want this number and - /// `MAX_PRICE_PER_GAS_UNIT` to always satisfy the inequality that - /// MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits::MAX) - maximum_number_of_gas_units: u64, - /// The minimum gas price that a transaction can be submitted with. - min_price_per_gas_unit: u64, - /// The maximum gas unit price that a transaction can be submitted with. - max_price_per_gas_unit: u64, - /// The max transaction size in bytes that a transaction can have. - max_transaction_size_in_bytes: u64, - /// gas unit scaling factor. - gas_unit_scaling_factor: u64, - /// default account size. - default_account_size: u64, - } - - /// The `GasCost` tracks: - /// - instruction cost: how much time/computational power is needed to perform the instruction - /// - memory cost: how much memory is required for the instruction, and storage overhead - struct GasCost has copy, drop, store { - instruction_gas: u64, - memory_gas: u64, - } - - public fun instruction_schedule(): vector { - let table = Vector::empty(); - - // POP - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // RET - Vector::push_back(&mut table, new_gas_cost(638, 1)); - // BR_TRUE - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // BR_FALSE - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // BRANCH - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LD_U64 - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LD_CONST - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LD_TRUE - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LD_FALSE - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // COPY_LOC - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // MOVE_LOC - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // ST_LOC - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // MUT_BORROW_LOC - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // IMM_BORROW_LOC - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // MUT_BORROW_FIELD - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // IMM_BORROW_FIELD - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // CALL - Vector::push_back(&mut table, new_gas_cost(1132, 1)); - // PACK - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // UNPACK - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // READ_REF - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // WRITE_REF - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // ADD - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // SUB - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // MUL - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // MOD - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // DIV - Vector::push_back(&mut table, new_gas_cost(3, 1)); - // BIT_OR - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // BIT_AND - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // XOR - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // OR - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // AND - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // NOT - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // EQ - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // NEQ - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LT - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // GT - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LE - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // GE - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // ABORT - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // NOP - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // EXISTS - Vector::push_back(&mut table, new_gas_cost(41, 1)); - // MUT_BORROW_GLOBAL - Vector::push_back(&mut table, new_gas_cost(21, 1)); - // IML_BORROW_GLOBAL - Vector::push_back(&mut table, new_gas_cost(23, 1)); - // MOVE_FROM - Vector::push_back(&mut table, new_gas_cost(459, 1)); - // MOVE_TO - Vector::push_back(&mut table, new_gas_cost(13, 1)); - // FREEZE_REF - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // SHL - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // SHR - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LD_U8 - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // LD_U128 - Vector::push_back(&mut table, new_gas_cost(1, 1)); - - // CAST_U8 - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // CAST_U64 - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // CAST_U128 - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // MUT_BORORW_FIELD_GENERIC - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // IMM_BORORW_FIELD_GENERIC - Vector::push_back(&mut table, new_gas_cost(1, 1)); - // CALL_GENERIC - Vector::push_back(&mut table, new_gas_cost(582, 1)); - // PACK_GENERIC - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // UNPACK_GENERIC - Vector::push_back(&mut table, new_gas_cost(2, 1)); - // EXISTS_GENERIC - Vector::push_back(&mut table, new_gas_cost(34, 1)); - // MUT_BORROW_GLOBAL_GENERIC - Vector::push_back(&mut table, new_gas_cost(15, 1)); - // IMM_BORROW_GLOBAL_GENERIC - Vector::push_back(&mut table, new_gas_cost(14, 1)); - // MOVE_FROM_GENERIC - Vector::push_back(&mut table, new_gas_cost(13, 1)); - // MOVE_TO_GENERIC - Vector::push_back(&mut table, new_gas_cost(27, 1)); - - // VEC_PACK - Vector::push_back(&mut table, new_gas_cost(84, 1)); - // VEC_LEN - Vector::push_back(&mut table, new_gas_cost(98, 1)); - // VEC_IMM_BORROW - Vector::push_back(&mut table, new_gas_cost(1334, 1)); - // VEC_MUT_BORROW - Vector::push_back(&mut table, new_gas_cost(1902, 1)); - // VEC_PUSH_BACK - Vector::push_back(&mut table, new_gas_cost(53, 1)); - // VEC_POP_BACK - Vector::push_back(&mut table, new_gas_cost(227, 1)); - // VEC_UNPACK - Vector::push_back(&mut table, new_gas_cost(572, 1)); - // VEC_SWAP - Vector::push_back(&mut table, new_gas_cost(1436, 1)); - table - } - - public fun native_schedule(): vector { - let table = Vector::empty(); - //Hash::sha2_256 0 - Vector::push_back(&mut table, new_gas_cost(21, 1)); - //Hash::sha3_256 1 - Vector::push_back(&mut table, new_gas_cost(64, 1)); - //Signature::ed25519_verify 2 - Vector::push_back(&mut table, new_gas_cost(61, 1)); - //ED25519_THRESHOLD_VERIFY 3 this native funciton is deprecated - Vector::push_back(&mut table, new_gas_cost(3351, 1)); - //BSC::to_bytes 4 - Vector::push_back(&mut table, new_gas_cost(181, 1)); - //Vector::length 5 - Vector::push_back(&mut table, new_gas_cost(98, 1)); - //Vector::empty 6 - Vector::push_back(&mut table, new_gas_cost(84, 1)); - //Vector::borrow 7 - Vector::push_back(&mut table, new_gas_cost(1334, 1)); - //Vector::borrow_mut 8 - Vector::push_back(&mut table, new_gas_cost(1902, 1)); - //Vector::push_back 9 - Vector::push_back(&mut table, new_gas_cost(53, 1)); - //Vector::pop_back 10 - Vector::push_back(&mut table, new_gas_cost(227, 1)); - //Vector::destory_empty 11 - Vector::push_back(&mut table, new_gas_cost(572, 1)); - //Vector::swap 12 - Vector::push_back(&mut table, new_gas_cost(1436, 1)); - //Signature::ed25519_validate_pubkey 13 - Vector::push_back(&mut table, new_gas_cost(26, 1)); - //Signer::borrow_address 14 - Vector::push_back(&mut table, new_gas_cost(353, 1)); - //Account::creator_signer 15 - Vector::push_back(&mut table, new_gas_cost(24, 1)); - //Account::destroy_signer 16 - Vector::push_back(&mut table, new_gas_cost(212, 1)); - //Event::emit_event 17 - Vector::push_back(&mut table, new_gas_cost(52, 1)); - //BCS::to_address 18 - Vector::push_back(&mut table, new_gas_cost(26, 1)); - //Token::name_of 19 - Vector::push_back(&mut table, new_gas_cost(2002, 1)); - //Hash::keccak_256 20 - Vector::push_back(&mut table, new_gas_cost(64, 1)); - //Hash::ripemd160 21 - Vector::push_back(&mut table, new_gas_cost(64, 1)); - //Signature::native_ecrecover 22 - Vector::push_back(&mut table, new_gas_cost(128, 1)); - //U256::from_bytes 23 - Vector::push_back(&mut table, new_gas_cost(2, 1)); - //U256::add 24 - Vector::push_back(&mut table, new_gas_cost(4, 1)); - //U256::sub 25 - Vector::push_back(&mut table, new_gas_cost(4, 1)); - //U256::mul 26 - Vector::push_back(&mut table, new_gas_cost(4, 1)); - //U256::div 27 - Vector::push_back(&mut table, new_gas_cost(10, 1)); - // U256::rem 28 - Vector::push_back(&mut table, new_gas_cost(4, 1)); - // U256::pow 29 - Vector::push_back(&mut table, new_gas_cost(8, 1)); - // TODO: settle down the gas cost - // Vector::append 30 - Vector::push_back(&mut table, new_gas_cost(40, 1)); - // Vector::remove 31 - Vector::push_back(&mut table, new_gas_cost(20, 1)); - // Vector::reverse 32 - Vector::push_back(&mut table, new_gas_cost(10, 1)); - - table - } - - public fun gas_constants(): GasConstants { - let min_price_per_gas_unit: u64 = if (ChainId::is_test()) { 0 } else { 1 }; - let maximum_number_of_gas_units: u64 = 40000000;//must less than base_block_gas_limit - - if (ChainId::is_test() || ChainId::is_dev() || ChainId::is_halley()) { - maximum_number_of_gas_units = maximum_number_of_gas_units * 10 - }; - GasConstants { - global_memory_per_byte_cost: 4, - global_memory_per_byte_write_cost: 9, - min_transaction_gas_units: 600, - large_transaction_cutoff: 600, - instrinsic_gas_per_byte: 8, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit: 10000, - max_transaction_size_in_bytes: 1024 * 128, - gas_unit_scaling_factor: 1, - default_account_size: 800, - } - } - - fun new_gas_cost(instr_gas: u64, mem_gas: u64): GasCost { - GasCost { - instruction_gas: instr_gas, - memory_gas: mem_gas, - } - } - - - /// Create a new vm config, mainly used in DAO. - public fun new_vm_config( - instruction_schedule: vector, - native_schedule: vector, - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - ): VMConfig { - let gas_constants = GasConstants { - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size, - }; - VMConfig { - gas_schedule: GasSchedule { instruction_schedule, native_schedule, gas_constants }, - } - } - - /// Initialize the table under the genesis account - public fun initialize( - account: &signer, - instruction_schedule: vector, - native_schedule: vector, - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - ) { - CoreAddresses::assert_genesis_address(account); - Config::publish_new_config( - account, - new_vm_config( - instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size, - ), - ); - } - - spec initialize { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if exists>(Signer::address_of(account)); - aborts_if - exists>( - Signer::address_of(account), - ); - ensures exists>(Signer::address_of(account)); - ensures - exists>( - Signer::address_of(account), - ); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/Vector.move b/release/v12/sources/Vector.move deleted file mode 100644 index fc225a63..00000000 --- a/release/v12/sources/Vector.move +++ /dev/null @@ -1,229 +0,0 @@ -address StarcoinFramework { - -/// A variable-sized container that can hold any type. Indexing is 0-based, and -/// vectors are growable. This module has many native functions. -/// Verification of modules that use this one uses model functions that are implemented -/// directly in Boogie. The specification language has built-in functions operations such -/// as `vec`. There are some helper functions defined here for specifications in other -/// modules as well. -/// -/// >Note: We did not verify most of the -/// Move functions here because many have loops, requiring loop invariants to prove, and -/// the return on investment didn't seem worth it for these simple functions. -module Vector { - - /// The index into the vector is out of bounds - const EINDEX_OUT_OF_BOUNDS: u64 = 0; - - /// Create an empty vector. - native public fun empty(): vector; - - /// Return the length of the vector. - native public fun length(v: &vector): u64; - - /// Acquire an immutable reference to the `i`th element of the vector `v`. - /// Aborts if `i` is out of bounds. - native public fun borrow(v: &vector, i: u64): ∈ - - /// Add element `e` to the end of the vector `v`. - native public fun push_back(v: &mut vector, e: Element); - - /// Return a mutable reference to the `i`th element in the vector `v`. - /// Aborts if `i` is out of bounds. - native public fun borrow_mut(v: &mut vector, i: u64): &mut Element; - - /// Pop an element from the end of vector `v`. - /// Aborts if `v` is empty. - native public fun pop_back(v: &mut vector): Element; - - /// Destroy the vector `v`. - /// Aborts if `v` is not empty. - native public fun destroy_empty(v: vector); - - /// Swaps the elements at the `i`th and `j`th indices in the vector `v`. - /// Aborts if `i`or `j` is out of bounds. - native public fun swap(v: &mut vector, i: u64, j: u64); - - /// Return an vector of size one containing element `e`. - public fun singleton(e: Element): vector { - let v = empty(); - push_back(&mut v, e); - v - } - spec singleton { - // TODO: when using opaque here, we get verification errors. - // pragma opaque; - aborts_if false; - ensures result == vec(e); - } - spec fun spec_singleton(e: Element): vector { - vec(e) - } - - - /// Reverses the order of the elements in the vector `v` in place. - public fun reverse(v: &mut vector) { - native_reverse(v) - } - spec reverse { - pragma intrinsic = true; - } - native fun native_reverse(this: &mut vector); - - /// Pushes all of the elements of the `other` vector into the `lhs` vector. - public fun append(lhs: &mut vector, other: vector) { - native_append(lhs, other); - } - native fun native_append(lhs: &mut vector, other: vector); - - spec append { - pragma intrinsic = true; - } - spec is_empty { - pragma intrinsic = true; - } - - - /// Return `true` if the vector `v` has no elements and `false` otherwise. - public fun is_empty(v: &vector): bool { - length(v) == 0 - } - - /// Return true if `e` is in the vector `v`. - public fun contains(v: &vector, e: &Element): bool { - let i = 0; - let len = length(v); - while (i < len) { - if (borrow(v, i) == e) return true; - i = i + 1; - }; - false - } - spec contains { - pragma intrinsic = true; - } - - /// Return `(true, i)` if `e` is in the vector `v` at index `i`. - /// Otherwise, returns `(false, 0)`. - public fun index_of(v: &vector, e: &Element): (bool, u64) { - let i = 0; - let len = length(v); - while (i < len) { - if (borrow(v, i) == e) return (true, i); - i = i + 1; - }; - (false, 0) - } - spec index_of { - pragma intrinsic = true; - } - - /// Remove the `i`th element of the vector `v`, shifting all subsequent elements. - /// This is O(n) and preserves ordering of elements in the vector. - /// Aborts if `i` is out of bounds. - public fun remove(v: &mut vector, i: u64): Element { - let len = length(v); - // i out of bounds; abort - if (i >= len) abort EINDEX_OUT_OF_BOUNDS; - - native_remove(v, i) - } - spec remove { - pragma intrinsic = true; - } - native fun native_remove(this: &mut vector, i: u64): Element; - - /// Swap the `i`th element of the vector `v` with the last element and then pop the vector. - /// This is O(1), but does not preserve ordering of elements in the vector. - /// Aborts if `i` is out of bounds. - public fun swap_remove(v: &mut vector, i: u64): Element { - let last_idx = length(v) - 1; - swap(v, i, last_idx); - pop_back(v) - } - spec swap_remove { - pragma intrinsic = true; - } - - /// Split a vector into sub-vectors of size sub_len, - public fun split(v: &vector, sub_len: u64): vector> { - let result = empty>(); - let len = length(v) / sub_len; - - let rem = 0; - if (len * sub_len < length(v)) { - rem = length(v) - len * sub_len; - }; - - let i = 0; - while (i < len) { - let sub = empty(); - let j = 0; - while (j < sub_len) { - let index = sub_len * i + j; - push_back(&mut sub, *borrow(v, index)); - j = j + 1; - }; - push_back>(&mut result, sub); - i = i + 1; - }; - - if (rem > 0) { - let sub = empty(); - let index = length(v) - rem; - while (index < length(v)) { - push_back(&mut sub, *borrow(v, index)); - index = index + 1; - }; - push_back>(&mut result, sub); - }; - result - } - - spec split { - pragma verify = false; // timeout, skip - aborts_if sub_len == 0; - } - // ================================================================= - // Module Specification - - spec module {} // Switch to module documentation context - - /// # Helper Functions - - - /// Check whether a vector contains an element. - spec fun spec_contains(v: vector, e: Element): bool { - exists x in v: x == e - } - - /// Check if `v1` is equal to the result of adding `e` at the end of `v2` - spec fun eq_push_back(v1: vector, v2: vector, e: Element): bool { - len(v1) == len(v2) + 1 && - v1[len(v1)-1] == e && - v1[0..len(v1)-1] == v2[0..len(v2)] - } - - /// Check if `v` is equal to the result of concatenating `v1` and `v2` - spec fun eq_append(v: vector, v1: vector, v2: vector): bool { - len(v) == len(v1) + len(v2) && - v[0..len(v1)] == v1 && - v[len(v1)..len(v)] == v2 - } - - /// Check `v1` is equal to the result of removing the first element of `v2` - spec fun eq_pop_front(v1: vector, v2: vector): bool { - len(v1) + 1 == len(v2) && - v1 == v2[1..len(v2)] - } - - /// Check that `v1` is equal to the result of removing the element at index `i` from `v2`. - spec fun eq_remove_elem_at_index(i: u64, v1: vector, v2: vector): bool { - len(v1) + 1 == len(v2) && - v1[0..i] == v2[0..i] && - v1[i..len(v1)] == v2[i + 1..len(v2)] - } - -} - -} diff --git a/release/v12/sources/Version.move b/release/v12/sources/Version.move deleted file mode 100644 index 86330627..00000000 --- a/release/v12/sources/Version.move +++ /dev/null @@ -1,38 +0,0 @@ -address StarcoinFramework { -/// `Version` tracks version of something, like current VM version. -module Version { - use StarcoinFramework::Config; - - const EMAJOR_TO_OLD: u64 = 101; - - spec module { - pragma verify; - pragma aborts_if_is_strict; - } - - /// Version. - struct Version has copy, drop, store { - /// major number. - major: u64, - } - - /// Create a new version. - public fun new_version(major: u64): Version { - Version { major } - } - - spec new_version { - aborts_if false; - } - - /// Get version under `addr`. - public fun get(addr: address): u64 { - let version = Config::get_by_address(addr); - version.major - } - - spec get { - aborts_if !exists>(addr); - } -} -} \ No newline at end of file diff --git a/release/v12/sources/YieldFarming.move b/release/v12/sources/YieldFarming.move deleted file mode 100644 index 7ca65bb5..00000000 --- a/release/v12/sources/YieldFarming.move +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) The Starcoin Core Contributors -// SPDX-License-Identifier: Apache-2.0 - -address StarcoinFramework { -module YieldFarming { - use StarcoinFramework::Token; - use StarcoinFramework::Errors; - - const EDEPRECATED_FUNCTION: u64 = 19; - const ERR_FARMING_INIT_REPEATE: u64 = 101; - const ERR_FARMING_NOT_STILL_FREEZE: u64 = 102; - const ERR_FARMING_STAKE_EXISTS: u64 = 103; - const ERR_FARMING_STAKE_NOT_EXISTS: u64 = 104; - const ERR_FARMING_HAVERST_NO_GAIN: u64 = 105; - const ERR_FARMING_TOTAL_WEIGHT_IS_ZERO: u64 = 106; - const ERR_EXP_DIVIDE_BY_ZERO: u64 = 107; - const ERR_FARMING_BALANCE_EXCEEDED: u64 = 108; - const ERR_FARMING_NOT_ENOUGH_ASSET: u64 = 109; - const ERR_FARMING_TIMESTAMP_INVALID: u64 = 110; - - spec module { - pragma verify = false; - } - - /// The object of yield farming - /// RewardTokenT meaning token of yield farming - struct Farming has key, store { - treasury_token: Token::Token, - } - - struct FarmingAsset has key, store { - asset_total_weight: u128, - harvest_index: u128, - last_update_timestamp: u64, - // Release count per seconds - release_per_second: u128, - // Start time, by seconds, user can operate stake only after this timestamp - start_time: u64, - } - - /// Capability to modify parameter such as period and release amount - struct ParameterModifyCapability has key, store {} - - /// To store user's asset token - struct Stake has key, store { - asset: AssetT, - asset_weight: u128, - last_harvest_index: u128, - gain: u128, - } - - ////////////////////////////////////////////////////////////////////// - // Exponential functions - - const EXP_SCALE: u128 = 1000000000000000000;// e18 - - struct Exp has copy, store, drop { - mantissa: u128 - } - - fun exp(num: u128, denom: u128): Exp { - // if overflow move will abort - let scaledNumerator = mul_u128(num, EXP_SCALE); - let rational = div_u128(scaledNumerator, denom); - Exp { - mantissa: rational - } - } - - fun mul_u128(a: u128, b: u128): u128 { - if (a == 0 || b == 0) { - return 0 - }; - - a * b - } - - fun div_u128(a: u128, b: u128): u128 { - if ( b == 0) { - abort Errors::invalid_argument(ERR_EXP_DIVIDE_BY_ZERO) - }; - if (a == 0) { - return 0 - }; - a / b - } - - fun truncate(exp: Exp): u128 { - return exp.mantissa / EXP_SCALE - } - - /// Called by token issuer - /// this will declare a yield farming pool - public fun initialize< - PoolType: store, - RewardTokenT: store>(_account: &signer, - _treasury_token: Token::Token) { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - // Initialize asset pools - public fun initialize_asset( - _account: &signer, - _release_per_second: u128, - _delay: u64): ParameterModifyCapability { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - public fun modify_parameter( - _cap: &ParameterModifyCapability, - _broker: address, - _release_per_second: u128) { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - /// Call by stake user, staking amount of asset in order to get yield farming token - public fun stake( - _account: &signer, - _broker: address, - _asset: AssetT, - _asset_weight: u128) { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - /// Unstake asset from farming pool - public fun unstake(_account: &signer, _broker: address) - : (AssetT, Token::Token) { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - /// Harvest yield farming token from stake - public fun harvest( - _account: &signer, - _broker: address, - _amount: u128): Token::Token { - abort Errors::deprecated(EDEPRECATED_FUNCTION) - } - - /// The user can quering all yield farming amount in any time and scene - public fun query_gov_token_amount(_account: &signer, _broker: address): u128 { - 0 - } - - /// Query total stake count from yield farming resource - public fun query_total_stake(_broker: address): u128 { - 0 - } - - /// Query stake weight from user staking objects. - public fun query_stake(_account: &signer): u128 { - 0 - } - - /// Update farming asset - fun calculate_harvest_index_with_asset(_farming_asset: &FarmingAsset, _now_seconds: u64): u128 { - 0 - } - - /// There is calculating from harvest index and global parameters without asset_total_weight - public fun calculate_harvest_index_weight_zero(_harvest_index: u128, - _last_update_timestamp: u64, - _now_seconds: u64, - _release_per_second: u128): u128 { - 0 - } - - /// There is calculating from harvest index and global parameters - public fun calculate_harvest_index(_harvest_index: u128, - _asset_total_weight: u128, - _last_update_timestamp: u64, - _now_seconds: u64, - _release_per_second: u128): u128 { - 0 - } - - /// This function will return a gain index - public fun calculate_withdraw_amount(_harvest_index: u128, - _last_harvest_index: u128, - _asset_weight: u128): u128 { - 0 - } - - /// Check the Farming of TokenT is exists. - public fun exists_at(broker: address): bool { - exists>(broker) - } - - /// Check the Farming of AsssetT is exists. - public fun exists_asset_at(broker: address): bool { - exists>(broker) - } - - /// Check stake at address exists. - public fun exists_stake_at_address(account: address): bool { - exists>(account) - } -} -} \ No newline at end of file diff --git a/release/v12/sources/YieldFarmingV2.move b/release/v12/sources/YieldFarmingV2.move deleted file mode 100644 index db8845bc..00000000 --- a/release/v12/sources/YieldFarmingV2.move +++ /dev/null @@ -1,492 +0,0 @@ -// Copyright (c) The Starcoin Core Contributors -// SPDX-License-Identifier: Apache-2.0 - -address StarcoinFramework { -module YieldFarmingV2 { - use StarcoinFramework::Token; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Errors; - use StarcoinFramework::Math; - - const ERR_FARMING_INIT_REPEATE: u64 = 101; - const ERR_FARMING_NOT_STILL_FREEZE: u64 = 102; - const ERR_FARMING_STAKE_EXISTS: u64 = 103; - const ERR_FARMING_STAKE_NOT_EXISTS: u64 = 104; - const ERR_FARMING_HAVERST_NO_GAIN: u64 = 105; - const ERR_FARMING_TOTAL_WEIGHT_IS_ZERO: u64 = 106; - const ERR_EXP_DIVIDE_BY_ZERO: u64 = 107; - const ERR_FARMING_BALANCE_EXCEEDED: u64 = 108; - const ERR_FARMING_NOT_ENOUGH_ASSET: u64 = 109; - const ERR_FARMING_TIMESTAMP_INVALID: u64 = 110; - const ERR_FARMING_TOKEN_SCALE_OVERFLOW: u64 = 111; - const ERR_FARMING_CALC_LAST_IDX_BIGGER_THAN_NOW: u64 = 112; - const ERR_FARMING_NOT_ALIVE: u64 = 113; - const ERR_FARMING_ALIVE_STATE_INVALID: u64 = 114; - - const EXP_MAX_SCALE: u128 = 9; - - spec module { - pragma verify = false; - } - - ////////////////////////////////////////////////////////////////////// - // Exponential functions - - const EXP_SCALE: u128 = 1000000000000000000;// e18 - - struct Exp has copy, store, drop { - mantissa: u128 - } - - fun exp_direct(num: u128): Exp { - Exp { - mantissa: num - } - } - - fun exp_direct_expand(num: u128): Exp { - Exp { - mantissa: mul_u128(num, EXP_SCALE) - } - } - - - fun mantissa(a: Exp): u128 { - a.mantissa - } - - fun add_exp(a: Exp, b: Exp): Exp { - Exp { - mantissa: add_u128(a.mantissa, b.mantissa) - } - } - - fun exp(num: u128, denom: u128): Exp { - // if overflow move will abort - let scaledNumerator = mul_u128(num, EXP_SCALE); - let rational = div_u128(scaledNumerator, denom); - Exp { - mantissa: rational - } - } - - fun add_u128(a: u128, b: u128): u128 { - a + b - } - - fun sub_u128(a: u128, b: u128): u128 { - a - b - } - - fun mul_u128(a: u128, b: u128): u128 { - if (a == 0 || b == 0) { - return 0 - }; - a * b - } - - fun div_u128(a: u128, b: u128): u128 { - if (b == 0) { - abort Errors::invalid_argument(ERR_EXP_DIVIDE_BY_ZERO) - }; - if (a == 0) { - return 0 - }; - a / b - } - - fun truncate(exp: Exp): u128 { - return exp.mantissa / EXP_SCALE - } - - /// The object of yield farming - /// RewardTokenT meaning token of yield farming - struct Farming has key, store { - treasury_token: Token::Token, - } - - struct FarmingAsset has key, store { - asset_total_weight: u128, - harvest_index: u128, - last_update_timestamp: u64, - // Release count per seconds - release_per_second: u128, - // Start time, by seconds, user can operate stake only after this timestamp - start_time: u64, - // Representing the pool is alive, false: not alive, true: alive. - alive: bool, - } - - /// To store user's asset token - struct Stake has key, store { - asset: AssetT, - asset_weight: u128, - last_harvest_index: u128, - gain: u128, - } - - /// Capability to modify parameter such as period and release amount - struct ParameterModifyCapability has key, store {} - - /// Harvest ability to harvest - struct HarvestCapability has key, store { - trigger: address, - } - - /// Called by token issuer - /// this will declare a yield farming pool - public fun initialize< - PoolType: store, - RewardTokenT: store>(signer: &signer, treasury_token: Token::Token) { - let scaling_factor = Math::pow(10, (EXP_MAX_SCALE as u64)); - let token_scale = Token::scaling_factor(); - assert!(token_scale <= scaling_factor, Errors::limit_exceeded(ERR_FARMING_TOKEN_SCALE_OVERFLOW)); - assert!(!exists_at( - Signer::address_of(signer)), Errors::invalid_state(ERR_FARMING_INIT_REPEATE)); - - move_to(signer, Farming { - treasury_token, - }); - } - - /// Add asset pools - public fun add_asset( - signer: &signer, - release_per_second: u128, - delay: u64): ParameterModifyCapability { - assert!(!exists_asset_at( - Signer::address_of(signer)), - Errors::invalid_state(ERR_FARMING_INIT_REPEATE)); - - let now_seconds = Timestamp::now_seconds(); - - move_to(signer, FarmingAsset { - asset_total_weight: 0, - harvest_index: 0, - last_update_timestamp: now_seconds, - release_per_second, - start_time: now_seconds + delay, - alive: true - }); - ParameterModifyCapability {} - } - - /// Remove asset for make this pool to the state of not alive - /// Please make sure all user unstaking from this pool -// public fun remove_asset( -// broker: address, -// cap: ParameterModifyCapability) acquires FarmingAsset { -// let ParameterModifyCapability {} = cap; -// let FarmingAsset { -// asset_total_weight: _, -// harvest_index: _, -// last_update_timestamp: _, -// release_per_second: _, -// start_time: _, -// alive: _, -// } = move_from>(broker); -// } - - public fun modify_parameter( - _cap: &ParameterModifyCapability, - broker: address, - release_per_second: u128, - alive: bool) acquires FarmingAsset { - - // Not support to shuttingdown alive state. - assert!(alive, Errors::invalid_state(ERR_FARMING_ALIVE_STATE_INVALID)); - - let farming_asset = borrow_global_mut>(broker); - // assert!(farming_asset.alive != alive, Errors::invalid_state(ERR_FARMING_ALIVE_STATE_INVALID)); - - let now_seconds = Timestamp::now_seconds(); - - farming_asset.release_per_second = release_per_second; - farming_asset.last_update_timestamp = now_seconds; - - // if the pool is alive, then update index - if (farming_asset.alive) { - farming_asset.harvest_index = calculate_harvest_index_with_asset(farming_asset, now_seconds); - }; - farming_asset.alive = alive; - } - - /// Call by stake user, staking amount of asset in order to get yield farming token - public fun stake( - signer: &signer, - broker: address, - asset: AssetT, - asset_weight: u128, - _cap: &ParameterModifyCapability) acquires FarmingAsset { - let harvest_cap = stake_for_cap< - PoolType, - RewardTokenT, - AssetT>(signer, broker, asset, asset_weight, _cap); - - move_to(signer, harvest_cap); - } - - public fun stake_for_cap( - signer: &signer, - broker: address, - asset: AssetT, - asset_weight: u128, - _cap: &ParameterModifyCapability) - : HarvestCapability acquires FarmingAsset { - let account = Signer::address_of(signer); - assert!(!exists_stake_at_address(account), - Errors::invalid_state(ERR_FARMING_STAKE_EXISTS)); - - let farming_asset = borrow_global_mut>(broker); - assert!(farming_asset.alive, Errors::invalid_state(ERR_FARMING_NOT_ALIVE)); - - // Check locking time - let now_seconds = Timestamp::now_seconds(); - assert!(farming_asset.start_time <= now_seconds, Errors::invalid_state(ERR_FARMING_NOT_STILL_FREEZE)); - - let time_period = now_seconds - farming_asset.last_update_timestamp; - - if (farming_asset.asset_total_weight <= 0) { - // Stake as first user - let gain = farming_asset.release_per_second * (time_period as u128); - move_to(signer, Stake { - asset, - asset_weight, - last_harvest_index: 0, - gain, - }); - farming_asset.harvest_index = 0; - farming_asset.asset_total_weight = asset_weight; - } else { - let new_harvest_index = calculate_harvest_index_with_asset(farming_asset, now_seconds); - move_to(signer, Stake { - asset, - asset_weight, - last_harvest_index: new_harvest_index, - gain: 0, - }); - farming_asset.asset_total_weight = farming_asset.asset_total_weight + asset_weight; - farming_asset.harvest_index = new_harvest_index; - }; - farming_asset.last_update_timestamp = now_seconds; - HarvestCapability { trigger: account } - } - - /// Unstake asset from farming pool - public fun unstake( - signer: &signer, - broker: address) - : (AssetT, Token::Token) acquires HarvestCapability, Farming, FarmingAsset, Stake { - let account = Signer::address_of(signer); - let cap = move_from>(account); - unstake_with_cap(broker, cap) - } - - public fun unstake_with_cap( - broker: address, - cap: HarvestCapability) - : (AssetT, Token::Token) acquires Farming, FarmingAsset, Stake { - // Destroy capability - let HarvestCapability { trigger } = cap; - - let farming = borrow_global_mut>(broker); - let farming_asset = borrow_global_mut>(broker); - - let Stake { last_harvest_index, asset_weight, asset, gain } = - move_from>(trigger); - - let now_seconds = Timestamp::now_seconds(); - let new_harvest_index = calculate_harvest_index_with_asset(farming_asset, now_seconds); - - let period_gain = calculate_withdraw_amount(new_harvest_index, last_harvest_index, asset_weight); - let total_gain = gain + period_gain; - let withdraw_token = Token::withdraw(&mut farming.treasury_token, total_gain); - - // Dont update harvest index that because the `Stake` object has droped. - // let new_index = calculate_harvest_index_with_asset(farming_asset, now_seconds); - assert!(farming_asset.asset_total_weight >= asset_weight, Errors::invalid_state(ERR_FARMING_NOT_ENOUGH_ASSET)); - - // Update farm asset - farming_asset.asset_total_weight = farming_asset.asset_total_weight - asset_weight; - farming_asset.last_update_timestamp = now_seconds; - - if (farming_asset.alive) { - farming_asset.harvest_index = new_harvest_index; - }; - - (asset, withdraw_token) - } - - /// Harvest yield farming token from stake - public fun harvest( - signer: &signer, - broker: address, - amount: u128) : Token::Token acquires HarvestCapability, Farming, FarmingAsset, Stake { - let account = Signer::address_of(signer); - let cap = borrow_global_mut>(account); - harvest_with_cap(broker, amount, cap) - } - - public fun harvest_with_cap( - broker: address, - amount: u128, - _cap: &HarvestCapability): Token::Token acquires Farming, FarmingAsset, Stake { - let farming = borrow_global_mut>(broker); - let farming_asset = borrow_global_mut>(broker); - let stake = borrow_global_mut>(_cap.trigger); - - let now_seconds = Timestamp::now_seconds(); - let new_harvest_index = calculate_harvest_index_with_asset(farming_asset, now_seconds); - - let period_gain = calculate_withdraw_amount( - new_harvest_index, - stake.last_harvest_index, - stake.asset_weight - ); - - let total_gain = stake.gain + period_gain; - //assert!(total_gain > 0, Errors::limit_exceeded(ERR_FARMING_HAVERST_NO_GAIN)); - assert!(total_gain >= amount, Errors::limit_exceeded(ERR_FARMING_BALANCE_EXCEEDED)); - - let withdraw_amount = if (amount <= 0) { - total_gain - } else { - amount - }; - - let withdraw_token = Token::withdraw(&mut farming.treasury_token, withdraw_amount); - stake.gain = total_gain - withdraw_amount; - stake.last_harvest_index = new_harvest_index; - - if (farming_asset.alive) { - farming_asset.harvest_index = new_harvest_index; - }; - farming_asset.last_update_timestamp = now_seconds; - - withdraw_token - } - - /// The user can quering all yield farming amount in any time and scene - public fun query_gov_token_amount(account: address, broker: address): u128 acquires FarmingAsset, Stake { - let farming_asset = borrow_global_mut>(broker); - let stake = borrow_global_mut>(account); - let now_seconds = Timestamp::now_seconds(); - - let new_harvest_index = calculate_harvest_index_with_asset( - farming_asset, - now_seconds - ); - - let new_gain = calculate_withdraw_amount( - new_harvest_index, - stake.last_harvest_index, - stake.asset_weight - ); - stake.gain + new_gain - } - - /// Query total stake count from yield farming resource - public fun query_total_stake(broker: address): u128 acquires FarmingAsset { - let farming_asset = borrow_global_mut>(broker); - farming_asset.asset_total_weight - } - - /// Query stake weight from user staking objects. - public fun query_stake(account: address): u128 acquires Stake { - let stake = borrow_global_mut>(account); - stake.asset_weight - } - - /// Queyry pool info from pool type - /// return value: (alive, release_per_second, asset_total_weight, harvest_index) - public fun query_info(broker: address): (bool, u128, u128, u128) acquires FarmingAsset { - let asset = borrow_global_mut>(broker); - ( - asset.alive, - asset.release_per_second, - asset.asset_total_weight, - asset.harvest_index - ) - } - - /// Update farming asset - fun calculate_harvest_index_with_asset(farming_asset: &FarmingAsset, now_seconds: u64): u128 { - // Recalculate harvest index - if (farming_asset.asset_total_weight <= 0) { - calculate_harvest_index_weight_zero( - farming_asset.harvest_index, - farming_asset.last_update_timestamp, - now_seconds, - farming_asset.release_per_second - ) - } else { - calculate_harvest_index( - farming_asset.harvest_index, - farming_asset.asset_total_weight, - farming_asset.last_update_timestamp, - now_seconds, - farming_asset.release_per_second - ) - } - } - - /// There is calculating from harvest index and global parameters without asset_total_weight - public fun calculate_harvest_index_weight_zero(harvest_index: u128, - last_update_timestamp: u64, - now_seconds: u64, - release_per_second: u128): u128 { - assert!(last_update_timestamp <= now_seconds, Errors::invalid_argument(ERR_FARMING_TIMESTAMP_INVALID)); - let time_period = now_seconds - last_update_timestamp; - let addtion_index = release_per_second * ((time_period as u128)); - harvest_index + mantissa(exp_direct_expand(addtion_index)) - } - - /// There is calculating from harvest index and global parameters - public fun calculate_harvest_index(harvest_index: u128, - asset_total_weight: u128, - last_update_timestamp: u64, - now_seconds: u64, - release_per_second: u128): u128 { - assert!(asset_total_weight > 0, Errors::invalid_argument(ERR_FARMING_TOTAL_WEIGHT_IS_ZERO)); - assert!(last_update_timestamp <= now_seconds, Errors::invalid_argument(ERR_FARMING_TIMESTAMP_INVALID)); - - let time_period = now_seconds - last_update_timestamp; - let numr = (release_per_second * (time_period as u128)); - let denom = asset_total_weight; - harvest_index + mantissa(exp(numr, denom)) - } - - /// This function will return a gain index - public fun calculate_withdraw_amount(harvest_index: u128, - last_harvest_index: u128, - asset_weight: u128): u128 { - assert!(harvest_index >= last_harvest_index, Errors::invalid_argument(ERR_FARMING_CALC_LAST_IDX_BIGGER_THAN_NOW)); - let amount = asset_weight * (harvest_index - last_harvest_index); - truncate(exp_direct(amount)) - } - - /// Check the Farming of TokenT is exists. - public fun exists_at(broker: address): bool { - exists>(broker) - } - - /// Check the Farming of AsssetT is exists. - public fun exists_asset_at(broker: address): bool { - exists>(broker) - } - - /// Check stake at address exists. - public fun exists_stake_at_address(account: address): bool { - exists>(account) - } -} -} \ No newline at end of file diff --git a/rust-toolchain b/rust-toolchain index 59790a70..84c7d0ba 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1 +1 @@ -1.62.0 \ No newline at end of file +1.61.0 \ No newline at end of file diff --git a/scripts/dev_setup.sh b/scripts/dev_setup.sh index 2a7f3c97..d05228e2 100755 --- a/scripts/dev_setup.sh +++ b/scripts/dev_setup.sh @@ -19,7 +19,7 @@ Z3_VERSION=4.8.13 CVC5_VERSION=0.0.3 DOTNET_VERSION=5.0 BOOGIE_VERSION=2.9.6 -MPM_VERSION=v1.12.5 +MPM_VERSION=v1.11.11 SCRIPT_PATH="$( cd "$( dirname "$0" )" >/dev/null 2>&1 && pwd )" @@ -161,26 +161,17 @@ function install_mpm { if [[ $(uname -s) == "Darwin" ]]; then mpm_file="mpm-macos-latest"; else - if [ "$(. /etc/os-release; echo $NAME)" = "Ubuntu" ]; then - if [[ $(lsb_release -r | cut -f 2) == '18.04' ]]; then - mpm_file="mpm-ubuntu-18.04"; - else - mpm_file="mpm-ubuntu-latest"; - fi + if [[ $(lsb_release -r | cut -f 2) == '18.04' ]]; then + mpm_file="mpm-ubuntu-18.04"; else - mpm_file=""; + mpm_file="mpm-ubuntu-latest"; fi fi - if [[ $mpm_file != "" ]]; then - curl -sL -o "${INSTALL_DIR}${mpm_file}.zip" "https://github.com/starcoinorg/starcoin/releases/download/${MPM_VERSION}/${mpm_file}.zip" - unzip -q "${INSTALL_DIR}${mpm_file}.zip" -d "${INSTALL_DIR}" - mv "${INSTALL_DIR}${mpm_file}/mpm" "${INSTALL_DIR}mpm" - chmod +x "${INSTALL_DIR}mpm" - rmdir "${INSTALL_DIR}${mpm_file}" - else - echo "Install mpm from source" - cargo install --git https://github.com/starcoinorg/starcoin move-package-manager --tag $MPM_VERSION --bin mpm --root $HOME - fi + curl -sL -o "${INSTALL_DIR}${mpm_file}.zip" "https://github.com/starcoinorg/starcoin/releases/download/${MPM_VERSION}/${mpm_file}.zip" + unzip -q "${INSTALL_DIR}${mpm_file}.zip" -d "${INSTALL_DIR}" + mv "${INSTALL_DIR}${mpm_file}/mpm" "${INSTALL_DIR}mpm" + chmod +x "${INSTALL_DIR}mpm" + rmdir "${INSTALL_DIR}${mpm_file}" fi } diff --git a/sources/ASCII.move b/sources/ASCII.move deleted file mode 100644 index 0e118f95..00000000 --- a/sources/ASCII.move +++ /dev/null @@ -1,138 +0,0 @@ -module StarcoinFramework::ASCII { - use StarcoinFramework::Vector; - use StarcoinFramework::Errors; - use StarcoinFramework::Option::{Self, Option}; - - /// An invalid ASCII character was encountered when creating an ASCII string. - const EINVALID_ASCII_CHARACTER: u64 = 101; - - /// The `String` struct holds a vector of bytes that all represent - /// valid ASCII characters. Note that these ASCII characters may not all - /// be printable. To determine if a `String` contains only "printable" - /// characters you should use the `all_characters_printable` predicate - /// defined in this module. - struct String has copy, drop, store { - bytes: vector, - } - - - /// An ASCII character. - struct Char has copy, drop, store { - byte: u8, - } - - /// Convert a `byte` into a `Char` that is checked to make sure it is valid ASCII. - public fun char(byte: u8): Char { - assert!(is_valid_char(byte), Errors::invalid_argument(EINVALID_ASCII_CHARACTER)); - Char { byte } - } - - - /// Convert a vector of bytes `bytes` into an `String`. Aborts if - /// `bytes` contains non-ASCII characters. - public fun string(bytes: vector): String { - let x = try_string(bytes); - assert!( - Option::is_some(&x), - Errors::invalid_argument(EINVALID_ASCII_CHARACTER) - ); - Option::destroy_some(x) - } - - /// Convert a vector of bytes `bytes` into an `String`. Returns - /// `Some()` if the `bytes` contains all valid ASCII - /// characters. Otherwise returns `None`. - public fun try_string(bytes: vector): Option { - let len = Vector::length(&bytes); - let i = 0; - while ( i < len ) { - let possible_byte = *Vector::borrow(&bytes, i); - if (!is_valid_char(possible_byte)) return Option::none(); - i = i + 1; - }; - Option::some(String { bytes }) - } - - /// Returns `true` if all characters in `string` are printable characters - /// Returns `false` otherwise. Not all `String`s are printable strings. - public fun all_characters_printable(string: &String): bool { - let len = Vector::length(&string.bytes); - let i = 0; - while ( i < len ) { - let byte = *Vector::borrow(&string.bytes, i); - if (!is_printable_char(byte)) return false; - i = i + 1; - }; - true - } - - public fun push_char(string: &mut String, char: Char) { - Vector::push_back(&mut string.bytes, char.byte); - } - - - public fun pop_char(string: &mut String): Char { - Char { byte: Vector::pop_back(&mut string.bytes) } - } - - - public fun length(string: &String): u64 { - Vector::length(as_bytes(string)) - } - - /// Get the inner bytes of the `string` as a reference - public fun as_bytes(string: &String): &vector { - &string.bytes - } - - /// Unpack the `string` to get its backing bytes - public fun into_bytes(string: String): vector { - let String { bytes } = string; - bytes - } - - /// Unpack the `char` into its underlying byte. - public fun byte(char: Char): u8 { - let Char { byte } = char; - byte - } - - /// Returns `true` if `byte` is a valid ASCII character. Returns `false` otherwise. - public fun is_valid_char(byte: u8): bool { - byte <= 0x7F - } - - /// Returns `true` if `byte` is an printable ASCII character. Returns `false` otherwise. - public fun is_printable_char(byte: u8): bool { - byte >= 0x20 && // Disallow metacharacters - byte <= 0x7E // Don't allow DEL metacharacter - } - - /// split string by char. Returns vector - public fun split_by_char(string: String, char: Char): vector { - let result = Vector::empty(); - let len = length(&string); - let i = 0; - let buffer = Vector::empty(); - while ( i < len ) { - let byte = *Vector::borrow(&string.bytes, i); - if (byte != char.byte) { - Vector::push_back(&mut buffer, byte); - } else { - Vector::push_back(&mut result, string(buffer)); - buffer = Vector::empty(); - if (i != 0 && i == len - 1) { - // special - Vector::push_back(&mut result, string(copy buffer)); - }; - }; - - i = i + 1; - }; - - if (len == 0 || Vector::length(&buffer) != 0) { - Vector::push_back(&mut result, string(buffer)); - }; - result - } -} \ No newline at end of file diff --git a/sources/Account.move b/sources/Account.move index 71817eb5..73a89857 100644 --- a/sources/Account.move +++ b/sources/Account.move @@ -13,12 +13,8 @@ module Account { use StarcoinFramework::TransactionFee; use StarcoinFramework::CoreAddresses; use StarcoinFramework::Errors; - use StarcoinFramework::STC::{Self, STC, is_stc}; + use StarcoinFramework::STC::{Self, STC}; use StarcoinFramework::BCS; - use StarcoinFramework::Math; - - friend StarcoinFramework::Genesis; - friend StarcoinFramework::StdlibUpgradeScripts; spec module { pragma verify = false; @@ -163,7 +159,7 @@ module Account { const DUMMY_AUTH_KEY:vector = x"0000000000000000000000000000000000000000000000000000000000000000"; // cannot be dummy key, or empty key const CONTRACT_ACCOUNT_AUTH_KEY_PLACEHOLDER:vector = x"0000000000000000000000000000000000000000000000000000000000000001"; - + /// The address bytes length const ADDRESS_LENGTH: u64 = 16; @@ -186,7 +182,7 @@ module Account { Event::emit_event( &mut event_store.signer_delegate_events, SignerDelegateEvent { - account_address: signer_addr + account_address: signer_addr } ); }; @@ -195,17 +191,6 @@ module Account { signer_cap } - //TODO: Create StarcoinDAO , need modify or remove get_genesis_capability soon - public (friend) fun get_genesis_capability():SignerCapability{ - let signer_cap = SignerCapability {addr: Token::token_address() }; - signer_cap - } - - #[test_only] - public fun get_genesis_capability_for_test(): SignerCapability { - get_genesis_capability() - } - public fun create_signer_with_cap(cap: &SignerCapability): signer { create_signer(cap.addr) } @@ -317,17 +302,12 @@ module Account { native fun create_signer(addr: address): signer; - public(script) fun create_account_with_initial_amount(account: signer, fresh_address: address, _auth_key: vector, initial_amount: u128) + public(script) fun create_account_with_initial_amount(account: signer, fresh_address: address, _auth_key: vector, initial_amount: u128) acquires Account, Balance, AutoAcceptToken { - create_account_with_initial_amount_entry(account, fresh_address, initial_amount); + create_account_with_initial_amount_v2(account, fresh_address, initial_amount) } public(script) fun create_account_with_initial_amount_v2(account: signer, fresh_address: address, initial_amount: u128) - acquires Account, Balance, AutoAcceptToken { - create_account_with_initial_amount_entry(account, fresh_address, initial_amount); - } - - public(script) fun create_account_with_initial_amount_entry(account: signer, fresh_address: address, initial_amount: u128) acquires Account, Balance, AutoAcceptToken { create_account_with_address(fresh_address); if (initial_amount > 0) { @@ -345,50 +325,32 @@ module Account { /// Generate an new address and create a new account, then delegate the account and return the new account address and `SignerCapability` public fun create_delegate_account(sender: &signer) : (address, SignerCapability) acquires Balance, Account, EventStore { - let new_address = generate_fresh_address(sender); + let sender_address = Signer::address_of(sender); + let sequence_number = Self::sequence_number(sender_address); + // use stc balance as part of seed, just for new address more random. + let stc_balance = Self::balance(sender_address); + + let seed_bytes = BCS::to_bytes(&sender_address); + Vector::append(&mut seed_bytes, BCS::to_bytes(&sequence_number)); + Vector::append(&mut seed_bytes, BCS::to_bytes(&stc_balance)); + + let seed_hash = Hash::sha3_256(seed_bytes); + let i = 0; + let address_bytes = Vector::empty(); + while (i < ADDRESS_LENGTH) { + Vector::push_back(&mut address_bytes, *Vector::borrow(&seed_hash,i)); + i = i + 1; + }; + let new_address = BCS::to_address(address_bytes); Self::create_account_with_address(new_address); let new_signer = Self::create_signer(new_address); (new_address, Self::remove_signer_capability(&new_signer)) } - /// Generate a fresh address from the sender address and the sender's sequence number, and ensure the generated address is not exists onchain. - public fun generate_fresh_address(sender: &signer) : address acquires Balance, Account { - let try_times = 0u64; - while(true){ - let sender_address = Signer::address_of(sender); - let sequence_number = Self::sequence_number(sender_address); - // use stc balance as part of seed, just for new address more random. - let stc_balance = Self::balance(sender_address); - - let seed_bytes = BCS::to_bytes(&sender_address); - Vector::append(&mut seed_bytes, BCS::to_bytes(&sequence_number)); - Vector::append(&mut seed_bytes, BCS::to_bytes(&stc_balance)); - Vector::append(&mut seed_bytes, BCS::to_bytes(&try_times)); - - let seed_hash = Hash::sha3_256(seed_bytes); - - let i = 0; - let address_bytes = Vector::empty(); - while (i < ADDRESS_LENGTH) { - Vector::push_back(&mut address_bytes, *Vector::borrow(&seed_hash,i)); - i = i + 1; - }; - let new_address = BCS::to_address(address_bytes); - if (Self::exists_at(new_address)){ - try_times = try_times + 1; - continue - }else{ - return new_address - } - }; - //unreachable - abort 0 - } - spec create_delegate_account { pragma verify = false; //TODO write spec - } + } /// Deposits the `to_deposit` token into the self's account balance public fun deposit_to_self(account: &signer, to_deposit: Token) @@ -428,11 +390,11 @@ module Account { to_deposit: Token, metadata: vector, ) acquires Account, Balance, AutoAcceptToken { - + if (!exists_at(receiver)) { create_account_with_address(receiver); }; - + try_accept_token(receiver); let deposit_value = Token::value(&to_deposit); @@ -768,20 +730,12 @@ module Account { } public(script) fun rotate_authentication_key(account: signer, new_key: vector) acquires Account, EventStore { - rotate_authentication_key_entry(account, new_key); - } - - public(script) fun rotate_authentication_key_entry(account: signer, new_key: vector) acquires Account, EventStore { - do_rotate_authentication_key(&account, new_key); - } - - public fun do_rotate_authentication_key(account: &signer, new_key: vector) acquires Account, EventStore { - let key_rotation_capability = extract_key_rotation_capability(account); + let key_rotation_capability = extract_key_rotation_capability(&account); rotate_authentication_key_with_capability(&key_rotation_capability, copy new_key); restore_key_rotation_capability(key_rotation_capability); - make_event_store_if_not_exist(account); - let signer_addr = Signer::address_of(account); + make_event_store_if_not_exist(&account); + let signer_addr = Signer::address_of(&account); let event_store = borrow_global_mut(signer_addr); Event::emit_event( &mut event_store.rotate_auth_key_events, @@ -836,10 +790,6 @@ module Account { } public(script) fun accept_token(account: signer) acquires Account { - accept_token_entry(account); - } - - public(script) fun accept_token_entry(account: signer) acquires Account { do_accept_token(&account); } @@ -878,10 +828,6 @@ module Account { } } - public(script) fun set_auto_accept_token_entry(account: signer, enable: bool) acquires AutoAcceptToken { - set_auto_accept_token(&account, enable); - } - /// Configure whether auto-accept tokens. public fun set_auto_accept_token(account: &signer, enable: bool) acquires AutoAcceptToken { let addr = Signer::address_of(account); @@ -1001,35 +947,6 @@ module Account { txn_authentication_key_preimage: vector, txn_gas_price: u64, txn_max_gas_units: u64, - ) acquires Account, Balance { - txn_prologue_v2( - account, - txn_sender, - txn_sequence_number, - txn_authentication_key_preimage, - txn_gas_price, - txn_max_gas_units, - 1, - 1, - ) - } - spec txn_prologue { - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(txn_sender); - aborts_if global(txn_sender).authentication_key == DUMMY_AUTH_KEY && Authenticator::spec_derived_address(Hash::sha3_256(txn_authentication_key_preimage)) != txn_sender; - aborts_if global(txn_sender).authentication_key != DUMMY_AUTH_KEY && Hash::sha3_256(txn_authentication_key_preimage) != global(txn_sender).authentication_key; - aborts_if txn_sequence_number < global(txn_sender).sequence_number; - } - - public fun txn_prologue_v2( - account: &signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - stc_price: u128, - stc_price_scaling: u128 ) acquires Account, Balance { CoreAddresses::assert_genesis_address(account); @@ -1054,30 +971,47 @@ module Account { Errors::invalid_argument(EPROLOGUE_INVALID_ACCOUNT_AUTH_KEY) ); }; + // Check that the account has enough balance for all of the gas - let (max_transaction_fee_stc,max_transaction_fee_token) = transaction_fee_simulate(txn_gas_price,txn_max_gas_units,0, stc_price, stc_price_scaling); assert!( - max_transaction_fee_stc <= MAX_U64, + (txn_gas_price as u128) * (txn_max_gas_units as u128) <= MAX_U64, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT), ); - if (max_transaction_fee_stc > 0) { + let max_transaction_fee = txn_gas_price * txn_max_gas_units; + if (max_transaction_fee > 0) { + assert!( + STC::is_stc(), + Errors::invalid_argument(EBAD_TRANSACTION_FEE_TOKEN) + ); + + let balance_amount = balance(txn_sender); + assert!(balance_amount >= (max_transaction_fee as u128), Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT)); + assert!( (txn_sequence_number as u128) < MAX_U64, Errors::limit_exceeded(EPROLOGUE_SEQUENCE_NUMBER_TOO_BIG) ); - let balance_amount_token = balance(txn_sender); - assert!(balance_amount_token >= max_transaction_fee_token, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT)); - if (!is_stc()){ - let balance_amount_stc= balance(CoreAddresses::GENESIS_ADDRESS()); - assert!(balance_amount_stc >= max_transaction_fee_stc, Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT)); - } }; + // Check that the transaction sequence number matches the sequence number of the account assert!(txn_sequence_number >= sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_OLD)); assert!(txn_sequence_number == sender_account.sequence_number, Errors::invalid_argument(EPROLOGUE_SEQUENCE_NUMBER_TOO_NEW)); - } + spec txn_prologue { + aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); + aborts_if !exists(txn_sender); + aborts_if global(txn_sender).authentication_key == DUMMY_AUTH_KEY && Authenticator::spec_derived_address(Hash::sha3_256(txn_authentication_key_preimage)) != txn_sender; + aborts_if global(txn_sender).authentication_key != DUMMY_AUTH_KEY && Hash::sha3_256(txn_authentication_key_preimage) != global(txn_sender).authentication_key; + aborts_if txn_gas_price * txn_max_gas_units > max_u64(); + aborts_if txn_gas_price * txn_max_gas_units > 0 && !exists>(txn_sender); + aborts_if txn_gas_price * txn_max_gas_units > 0 && Token::spec_token_code() != Token::spec_token_code(); + //abort condition for assert!(balance_amount >= max_transaction_fee) + aborts_if txn_gas_price * txn_max_gas_units > 0 && global>(txn_sender).token.value < txn_gas_price * txn_max_gas_units; + aborts_if txn_gas_price * txn_max_gas_units > 0 && txn_sequence_number >= max_u64(); + aborts_if txn_sequence_number < global(txn_sender).sequence_number; + aborts_if txn_sequence_number != global(txn_sender).sequence_number; + } /// The epilogue is invoked at the end of transactions. /// It collects gas and bumps the sequence number @@ -1089,25 +1023,13 @@ module Account { txn_max_gas_units: u64, gas_units_remaining: u64, ) acquires Account, Balance { - txn_epilogue_v3(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining,1,1) + txn_epilogue_v2(account, txn_sender, txn_sequence_number, Vector::empty(), txn_gas_price, txn_max_gas_units, gas_units_remaining) } spec txn_epilogue { pragma verify = false; } - public fun transaction_fee_simulate( - txn_gas_price:u64, - txn_max_gas_units: u64, - gas_units_remaining:u64, - stc_price: u128, - stc_price_scaling: u128, - ): (u128, u128){ - let transaction_fee_stc =(txn_gas_price * (txn_max_gas_units - gas_units_remaining) as u128); - let transaction_fee_token= Math::mul_div((transaction_fee_stc as u128), stc_price, stc_price_scaling); - transaction_fee_token = if (transaction_fee_token == 0 && transaction_fee_stc > 0 ) { 1 } else { transaction_fee_token}; - (transaction_fee_stc, transaction_fee_token) - } /// The epilogue is invoked at the end of transactions. /// It collects gas and bumps the sequence number public fun txn_epilogue_v2( @@ -1119,81 +1041,31 @@ module Account { txn_max_gas_units: u64, gas_units_remaining: u64, ) acquires Account, Balance { - txn_epilogue_v3( - account, - txn_sender, - txn_sequence_number, - txn_authentication_key_preimage, - txn_gas_price, - txn_max_gas_units, - gas_units_remaining,1,1) - } + CoreAddresses::assert_genesis_address(account); - spec txn_epilogue_v2 { - pragma verify = false; // Todo: fix me, cost too much time - aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); - aborts_if !exists(txn_sender); - aborts_if !exists>(txn_sender); - aborts_if txn_max_gas_units < gas_units_remaining; - let transaction_fee_amount = txn_gas_price * (txn_max_gas_units - gas_units_remaining); - aborts_if transaction_fee_amount > max_u128(); - aborts_if global>(txn_sender).token.value < transaction_fee_amount; - aborts_if txn_sequence_number + 1 > max_u64(); - aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && - global>(txn_sender).token.value < txn_gas_price * (txn_max_gas_units - gas_units_remaining); - aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && - !exists>(CoreAddresses::GENESIS_ADDRESS()); - aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && - global>(CoreAddresses::GENESIS_ADDRESS()).fee.value + txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u128(); - } + // Load the transaction sender's account and balance resources + let sender_account = borrow_global_mut(txn_sender); + let sender_balance = borrow_global_mut>(txn_sender); - /// The epilogue is invoked at the end of transactions. - /// It collects gas and bumps the sequence number - public fun txn_epilogue_v3( - account: &signer, - txn_sender: address, - txn_sequence_number: u64, - txn_authentication_key_preimage: vector, - txn_gas_price: u64, - txn_max_gas_units: u64, - gas_units_remaining: u64, - stc_price: u128, - stc_price_scaling: u128, - ) acquires Account, Balance { - CoreAddresses::assert_genesis_address(account); // Charge for gas - let (transaction_fee_amount_stc,transaction_fee_amount_token) = transaction_fee_simulate( - txn_gas_price, - txn_max_gas_units, - gas_units_remaining, - stc_price, - stc_price_scaling); + let transaction_fee_amount =(txn_gas_price * (txn_max_gas_units - gas_units_remaining) as u128); assert!( - balance(txn_sender) >= transaction_fee_amount_token, + balance_for(sender_balance) >= transaction_fee_amount, Errors::limit_exceeded(EINSUFFICIENT_BALANCE) ); - if (!is_stc()){ - let genesis_balance_amount_stc=balance(CoreAddresses::GENESIS_ADDRESS()); - assert!(genesis_balance_amount_stc >= transaction_fee_amount_stc, - Errors::invalid_argument(EPROLOGUE_CANT_PAY_GAS_DEPOSIT) - ); - }; - // Load the transaction sender's account and balance resources - let sender_account = borrow_global_mut(txn_sender); + // Bump the sequence number sender_account.sequence_number = txn_sequence_number + 1; // Set auth key when user send transaction first. if (is_dummy_auth_key(sender_account) && !Vector::is_empty(&txn_authentication_key_preimage)){ sender_account.authentication_key = Hash::sha3_256(txn_authentication_key_preimage); }; - if (transaction_fee_amount_stc > 0) { - let transaction_fee_token = withdraw_from_balance( - borrow_global_mut>(txn_sender), - transaction_fee_amount_token + if (transaction_fee_amount > 0) { + let transaction_fee = withdraw_from_balance( + sender_balance, + transaction_fee_amount ); - deposit_to_balance(borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_token); - let stc_fee_token = withdraw_from_balance(borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()), transaction_fee_amount_stc); - TransactionFee::pay_fee(stc_fee_token); + TransactionFee::pay_fee(transaction_fee); }; } @@ -1202,13 +1074,17 @@ module Account { aborts_if Signer::address_of(account) != CoreAddresses::GENESIS_ADDRESS(); aborts_if !exists(txn_sender); aborts_if !exists>(txn_sender); - aborts_if txn_sequence_number + 1 > max_u64(); - aborts_if !exists>(txn_sender); aborts_if txn_max_gas_units < gas_units_remaining; - } - - public(script) fun remove_zero_balance_entry(account: signer) acquires Balance { - remove_zero_balance(&account); + let transaction_fee_amount = txn_gas_price * (txn_max_gas_units - gas_units_remaining); + aborts_if transaction_fee_amount > max_u128(); + aborts_if global>(txn_sender).token.value < transaction_fee_amount; + aborts_if txn_sequence_number + 1 > max_u64(); + aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && + global>(txn_sender).token.value < txn_gas_price * (txn_max_gas_units - gas_units_remaining); + aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && + !exists>(CoreAddresses::GENESIS_ADDRESS()); + aborts_if txn_gas_price * (txn_max_gas_units - gas_units_remaining) > 0 && + global>(CoreAddresses::GENESIS_ADDRESS()).fee.value + txn_gas_price * (txn_max_gas_units - gas_units_remaining) > max_u128(); } /// Remove zero Balance diff --git a/sources/AccountScripts.move b/sources/AccountScripts.move index 6c77bf97..97e777d5 100644 --- a/sources/AccountScripts.move +++ b/sources/AccountScripts.move @@ -4,18 +4,18 @@ module AccountScripts { /// Enable account's auto-accept-token feature. /// The script function is reenterable. public(script) fun enable_auto_accept_token(account: signer) { - Account::set_auto_accept_token_entry(account, true); + Account::set_auto_accept_token(&account, true); } /// Disable account's auto-accept-token feature. /// The script function is reenterable. public(script) fun disable_auto_accept_token(account: signer) { - Account::set_auto_accept_token_entry(account, false); + Account::set_auto_accept_token(&account, false); } /// Remove zero Balance public(script) fun remove_zero_balance(account: signer) { - Account::remove_zero_balance_entry(account); + Account::remove_zero_balance(&account); } } } \ No newline at end of file diff --git a/sources/BCS.move b/sources/BCS.move index a2f56a5b..b188e50c 100644 --- a/sources/BCS.move +++ b/sources/BCS.move @@ -3,24 +3,12 @@ address StarcoinFramework { /// Serialization). BCS is the binary encoding for Move resources and other non-module values /// published on-chain. module BCS { - - use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::BCS; - - const ERR_INPUT_NOT_LARGE_ENOUGH: u64 = 201; - const ERR_UNEXPECTED_BOOL_VALUE: u64 = 205; - const ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32: u64 = 206; - const ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT: u64 = 207; - const INTEGER32_MAX_VALUE: u64 = 2147483647; - spec module { pragma verify; pragma aborts_if_is_strict; } /// Return the binary representation of `v` in BCS (Starcoin Canonical Serialization) format - native public fun to_bytes(v: &MoveValue): vector; + native public fun to_bytes(v: &MoveValue): vector; /// Return the address of key bytes native public fun to_address(key_bytes: vector): address; @@ -30,713 +18,5 @@ module BCS { spec native fun serialize(v: &MoveValue): vector; - - - public fun deserialize_option_bytes_vector(input: &vector, offset: u64): (vector>>, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty>>(); - while (i < len) { - let (opt_bs, o) = deserialize_option_bytes(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - spec deserialize_option_bytes_vector { - pragma verify = false; - } - - public fun deserialize_option_tuple(input: &vector, offset: u64): (Option::Option>, Option::Option>, u64) { - let (tag, new_offset) = deserialize_option_tag(input, offset); - if (!tag) { - return (Option::none>(), Option::none>(), new_offset) - } else { - let (bs1, new_offset) = deserialize_bytes(input, new_offset); - let (bs2, new_offset) = deserialize_bytes(input, new_offset); - - (Option::some>(bs1), Option::some>(bs2), new_offset) - } - } - spec deserialize_option_tuple { - pragma verify = false; - } - - #[test] - fun test_deserialize_option_tuple() { - let tuple_bytes = Vector::empty(); - let tuple1_bytes = x"01020304"; - let tuple2_bytes = x"05060708"; - let tuple1_bcs = to_bytes(&tuple1_bytes); - let tuple2_bcs = to_bytes(&tuple2_bytes); - Vector::append(&mut tuple_bytes, tuple1_bcs); - Vector::append(&mut tuple_bytes, tuple2_bcs); - - let tuple_option_bcs = Vector::empty(); - Vector::append(&mut tuple_option_bcs, x"01"); - Vector::append(&mut tuple_option_bcs, tuple_bytes); - - let offset = 0; - let (tuple1, tuple2, _offset) = deserialize_option_tuple(&tuple_option_bcs, offset); - let tuple1_option = Option::some(tuple1_bytes); - let tuple2_option = Option::some(tuple2_bytes); - assert!(tuple1 == tuple1_option, 999); - assert!(tuple2 == tuple2_option, 1000); - } - - public fun deserialize_bytes_vector(input: &vector, offset: u64): (vector>, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty>(); - while (i < len) { - let (opt_bs, o) = deserialize_bytes(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - - spec deserialize_bytes_vector { - pragma verify = false; - } - - #[test] - public fun test_deserialize_bytes_array() { - let hello = b"hello"; - let world = b"world"; - let hello_world = Vector::empty>(); - Vector::push_back(&mut hello_world, hello); - Vector::push_back(&mut hello_world, world); - let bs = BCS::to_bytes>>(&hello_world); - let (r, _) = deserialize_bytes_vector(&bs, 0); - assert!(hello_world == r, 1001); - } - - public fun deserialize_u64_vector(input: &vector, offset: u64): (vector, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty(); - while (i < len) { - let (opt_bs, o) = deserialize_u64(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - - spec deserialize_u64_vector { - pragma verify = false; - } - - public fun deserialize_u128_vector(input: &vector, offset: u64): (vector, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - let vec = Vector::empty(); - while (i < len) { - let (opt_bs, o) = deserialize_u128(input, new_offset); - Vector::push_back(&mut vec, opt_bs); - new_offset = o; - i = i + 1; - }; - (vec, new_offset) - } - - spec deserialize_u128_vector { - pragma verify = false; - } - - #[test] - public fun test_deserialize_u128_array() { - let hello:u128 = 1111111; - let world:u128 = 2222222; - let hello_world = Vector::empty(); - Vector::push_back(&mut hello_world, hello); - Vector::push_back(&mut hello_world, world); - let bs = BCS::to_bytes>(&hello_world); - let (r, _) = deserialize_u128_vector(&bs, 0); - assert!(hello_world == r, 1002); - } - - public fun deserialize_option_bytes(input: &vector, offset: u64): (Option::Option>, u64) { - let (tag, new_offset) = deserialize_option_tag(input, offset); - if (!tag) { - return (Option::none>(), new_offset) - } else { - let (bs, new_offset) = deserialize_bytes(input, new_offset); - return (Option::some>(bs), new_offset) - } - } - - spec deserialize_option_bytes { - pragma verify = false; - } - - public fun deserialize_address(input: &vector, offset: u64): (address, u64) { - let (content, new_offset) = deserialize_16_bytes(input, offset); - (BCS::to_address(content), new_offset) - } - - spec deserialize_address { - pragma verify = false; - } - - #[test] - fun test_deserialize_address() { - let addr = @0x18351d311d32201149a4df2a9fc2db8a; - let bs = BCS::to_bytes
(&addr); - let (r, offset) = deserialize_address(&bs, 0); - assert!(addr == r, 1003); - assert!(offset == 16, 1004); - } - - public fun deserialize_16_bytes(input: &vector, offset: u64): (vector, u64) { - let content = get_n_bytes(input, offset, 16); - (content, offset + 16) - } - - spec deserialize_16_bytes { - pragma verify = false; - } - - public fun deserialize_bytes(input: &vector, offset: u64): (vector, u64) { - let (len, new_offset) = deserialize_len(input, offset); - let content = get_n_bytes(input, new_offset, len); - (content, new_offset + len) - } - - spec deserialize_bytes { - pragma verify = false; - } - - #[test] - public fun test_deserialize_bytes() { - let hello = b"hello world"; - let bs = BCS::to_bytes>(&hello); - let (r, _) = deserialize_bytes(&bs, 0); - assert!(hello == r, 1005); - } - - public fun deserialize_u128(input: &vector, offset: u64): (u128, u64) { - let u = get_n_bytes_as_u128(input, offset, 16); - (u, offset + 16) - } - - spec deserialize_u128 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u128() { - let max_int128 = 170141183460469231731687303715884105727; - let u: u128 = max_int128; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u128(&bs, 0); - assert!(u == r, 1006); - assert!(offset == 16, 1007); - } - - - public fun deserialize_u64(input: &vector, offset: u64): (u64, u64) { - let u = get_n_bytes_as_u128(input, offset, 8); - ((u as u64), offset + 8) - } - - spec deserialize_u64 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u64() { - let u: u64 = 12811111111111; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u64(&bs, 0); - assert!(u == r, 1008); - assert!(offset == 8, 1009); - } - - public fun deserialize_u32(input: &vector, offset: u64): (u64, u64) { - let u = get_n_bytes_as_u128(input, offset, 4); - ((u as u64), offset + 4) - } - - spec deserialize_u32 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u32() { - let u: u64 = 1281111; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u32(&bs, 0); - _ = r; - assert!(u == r, 1010); - assert!(offset == 4, 1011); - } - - public fun deserialize_u16(input: &vector, offset: u64): (u64, u64) { - let u = get_n_bytes_as_u128(input, offset, 2); - ((u as u64), offset + 2) - } - - spec deserialize_u16 { - pragma verify = false; - } - - public fun deserialize_u8(input: &vector, offset: u64): (u8, u64) { - let u = get_byte(input, offset); - (u, offset + 1) - } - - spec deserialize_u8 { - pragma verify = false; - } - - #[test] - fun test_deserialize_u8() { - let u: u8 = 128; - let bs = BCS::to_bytes(&u); - let (r, offset) = deserialize_u8(&bs, 0); - assert!(u == r, 1012); - assert!(offset == 1, 1013); - } - - public fun deserialize_option_tag(input: &vector, offset: u64): (bool, u64) { - deserialize_bool(input, offset) - } - - spec deserialize_option_tag { - pragma verify = false; - } - - public fun deserialize_len(input: &vector, offset: u64): (u64, u64) { - deserialize_uleb128_as_u32(input, offset) - } - - spec deserialize_len { - pragma verify = false; - } - - public fun deserialize_bool(input: &vector, offset: u64): (bool, u64) { - let b = get_byte(input, offset); - if (b == 1) { - return (true, offset + 1) - } else if (b == 0) { - return (false, offset + 1) - } else { - abort ERR_UNEXPECTED_BOOL_VALUE - } - } - - spec deserialize_bool { - pragma verify = false; - } - - #[test] - public fun test_deserialize_bool() { - let t = true; - let bs = BCS::to_bytes(&t); - let (d, _) = deserialize_bool(&bs, 0); - assert!(d, 1014); - - let f = false; - bs = BCS::to_bytes(&f); - (d, _) = deserialize_bool(&bs, 0); - assert!(!d, 1015); - } - - fun get_byte(input: &vector, offset: u64): u8 { - assert!(((offset + 1) <= Vector::length(input)) && (offset < offset + 1), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - *Vector::borrow(input, offset) - } - - spec get_byte { - pragma verify = false; - } - - fun get_n_bytes(input: &vector, offset: u64, n: u64): vector { - assert!(((offset + n) <= Vector::length(input)) && (offset <= offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - let i = 0; - let content = Vector::empty(); - while (i < n) { - let b = *Vector::borrow(input, offset + i); - Vector::push_back(&mut content, b); - i = i + 1; - }; - content - } - - spec get_n_bytes { - pragma verify = false; - } - - fun get_n_bytes_as_u128(input: &vector, offset: u64, n: u64): u128 { - assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - let number: u128 = 0; - let i = 0; - while (i < n) { - let byte = *Vector::borrow(input, offset + i); - let s = (i as u8) * 8; - number = number + ((byte as u128) << s); - i = i + 1; - }; - number - } - - spec get_n_bytes_as_u128 { - pragma verify = false; - } - - public fun deserialize_uleb128_as_u32(input: &vector, offset: u64): (u64, u64) { - let value: u64 = 0; - let shift = 0; - let new_offset = offset; - while (shift < 32) { - let x = get_byte(input, new_offset); - new_offset = new_offset + 1; - let digit: u8 = x & 0x7F; - value = value | (digit as u64) << shift; - if ((value < 0) || (value > INTEGER32_MAX_VALUE)) { - abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32 - }; - if (digit == x) { - if (shift > 0 && digit == 0) { - abort ERR_INVALID_ULEB128_NUMBER_UNEXPECTED_ZERO_DIGIT - }; - return (value, new_offset) - }; - shift = shift + 7 - }; - abort ERR_OVERFLOW_PARSING_ULEB128_ENCODED_UINT32 - } - - spec deserialize_uleb128_as_u32 { - pragma verify = false; - } - - #[test] - public fun test_deserialize_uleb128_as_u32() { - let i: u64 = 0x7F; - let bs = serialize_u32_as_uleb128(i); - let (len, _) = deserialize_uleb128_as_u32(&bs, 0); - assert!(len == i, 1016); - - let i2: u64 = 0x8F; - let bs2 = serialize_u32_as_uleb128(i2); - (len, _) = deserialize_uleb128_as_u32(&bs2, 0); - assert!(len == i2, 1017); - } - - - #[test] - public fun test_deserialize_uleb128_as_u32_max_int() { - let max_int: u64 = 2147483647; - - let bs = serialize_u32_as_uleb128(max_int); - let (len, _) = deserialize_uleb128_as_u32(&bs, 0); - assert!(len == max_int, 1018); - } - - #[test] - #[expected_failure(abort_code = 206)] - public fun test_deserialize_uleb128_as_u32_exceeded_max_int() { - let max_int: u64 = 2147483647; - let exceeded_max_int: u64 = max_int + 1; - - let bs = serialize_u32_as_uleb128(exceeded_max_int); - let (_, _) = deserialize_uleb128_as_u32(&bs, 0); - } - - - fun serialize_u32_as_uleb128(value: u64): vector { - let output = Vector::empty(); - while ((value >> 7) != 0) { - Vector::push_back(&mut output, (((value & 0x7f) | 0x80) as u8)); - value = value >> 7; - }; - Vector::push_back(&mut output, (value as u8)); - output - } - - spec serialize_u32_as_uleb128 { - pragma verify = false; - } - - // skip Vector>> - public fun skip_option_bytes_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - while (i < len) { - new_offset = skip_option_bytes(input, new_offset); - i = i + 1; - }; - new_offset - } - - spec skip_option_bytes_vector { - pragma verify = false; - } - - #[test] - fun test_skip_option_bytes_vector(){ - let vec = Vector::empty>>(); - Vector::push_back(&mut vec, Option::some(x"01020304")); - Vector::push_back(&mut vec, Option::some(x"04030201")); - let vec = to_bytes(&vec); - //vec : [2, 1, 4, 1, 2, 3, 4, 1, 4, 4, 3, 2, 1] - assert!(skip_option_bytes_vector(&vec, 0) == 13,2000); - } - - // skip Option::Option> - public fun skip_option_bytes(input: &vector, offset: u64): u64 { - let (tag, new_offset) = deserialize_option_tag(input, offset); - if (!tag) { - new_offset - } else { - skip_bytes(input, new_offset) - } - } - - spec skip_option_bytes { - pragma verify = false; - } - - #[test] - fun test_skip_none_option_bytes(){ - let op = Option::none>(); - let op = to_bytes(&op); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut op, vec); - // op : [0, 4, 1, 2, 3, 4] - assert!(skip_option_bytes(&op, 0) == 1,2007); - } - - #[test] - fun test_skip_some_option_bytes(){ - let op = Option::some(x"01020304"); - let op = to_bytes(&op); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut op, vec); - // op : [1, 4, 1, 2, 3, 4, 4, 1, 2, 3, 4] - assert!(skip_option_bytes(&op, 0) == 6,2008); - } - - // skip vector> - public fun skip_bytes_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - let i = 0; - while (i < len) { - new_offset = skip_bytes(input, new_offset); - i = i + 1; - }; - new_offset - } - - spec skip_bytes_vector { - pragma verify = false; - } - - // skip vector - public fun skip_bytes(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - new_offset + len - } - - spec skip_bytes { - pragma verify = false; - } - - #[test] - fun test_skip_bytes(){ - let vec = to_bytes(&x"01020304"); - let u_64 = to_bytes(&10); - Vector::append(&mut vec, u_64); - // vec : [4, 1, 2, 3, 4, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_bytes(&vec, 0) == 5,2001); - } - - // skip some bytes - public fun skip_n_bytes(input: &vector, offset: u64, n:u64): u64 { - can_skip(input, offset, n ); - offset + n - } - - spec skip_n_bytes { - pragma verify = false; - } - - #[test] - fun test_skip_n_bytes(){ - let vec = to_bytes(&x"01020304"); - let u_64 = to_bytes(&10); - Vector::append(&mut vec, u_64); - // vec : [4, 1, 2, 3, 4, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_n_bytes(&vec, 0, 1) == 1,2002); - } - - // skip vector - public fun skip_u64_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - can_skip(input, new_offset, len * 8); - new_offset + len * 8 - } - - spec skip_u64_vector { - pragma verify = false; - } - - #[test] - fun test_skip_u64_vector(){ - let vec = Vector::empty(); - Vector::push_back(&mut vec, 11111); - Vector::push_back(&mut vec, 22222); - let u_64 = to_bytes(&10); - let vec = to_bytes(&vec); - Vector::append(&mut vec, u_64); - // vec : [2, 103, 43, 0, 0, 0, 0, 0, 0, 206, 86, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_u64_vector(&vec, 0) == 17,2004); - } - - // skip vector - public fun skip_u128_vector(input: &vector, offset: u64): u64 { - let (len, new_offset) = deserialize_len(input, offset); - can_skip(input, new_offset, len * 16); - new_offset + len * 16 - } - - spec skip_u128_vector { - pragma verify = false; - } - - #[test] - fun test_skip_u128_vector(){ - let vec = Vector::empty(); - Vector::push_back(&mut vec, 11111); - Vector::push_back(&mut vec, 22222); - let u_64 = to_bytes(&10); - let vec = to_bytes(&vec); - Vector::append(&mut vec, u_64); - // vec : [2, 103, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 206, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0] - assert!(skip_u128_vector(&vec, 0) == 33,2003); - } - - // skip u256 - public fun skip_u256(input: &vector, offset: u64): u64 { - can_skip(input, offset, 32 ); - offset + 32 - } - - spec skip_u256 { - pragma verify = false; - } - - // skip u128 - public fun skip_u128(input: &vector, offset: u64): u64 { - can_skip(input, offset, 16 ); - offset + 16 - } - - spec skip_u128 { - pragma verify = false; - } - - #[test] - fun test_skip_u128(){ - let u_128:u128 = 100; - let u_128 = to_bytes(&u_128); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut u_128, vec); - // u_128 : [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4] - assert!(skip_u128(&u_128, 0) == 16,2005); - } - - // skip u64 - public fun skip_u64(input: &vector, offset: u64): u64 { - can_skip(input, offset, 8 ); - offset + 8 - } - - spec skip_u64 { - pragma verify = false; - } - - #[test] - fun test_skip_u64(){ - let u_64:u64 = 100; - let u_64 = to_bytes(&u_64); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut u_64, vec); - // u_64 : [100, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4] - assert!(skip_u64(&u_64, 0) == 8,2006); - } - - // skip u32 - public fun skip_u32(input: &vector, offset: u64): u64 { - can_skip(input, offset, 4 ); - offset + 4 - } - - spec skip_u32 { - pragma verify = false; - } - - // skip u16 - public fun skip_u16(input: &vector, offset: u64): u64 { - can_skip(input, offset, 2 ); - offset + 2 - } - - spec skip_u16 { - pragma verify = false; - } - - // skip u8 - public fun skip_u8(input: &vector, offset: u64): u64 { - can_skip(input, offset, 1 ); - offset + 1 - } - - spec skip_u8 { - pragma verify = false; - } - - // skip address - public fun skip_address(input: &vector, offset: u64): u64 { - skip_n_bytes(input, offset, 16) - } - - spec skip_address { - pragma verify = false; - } - - #[test] - fun test_address(){ - let addr:address = @0x1; - let addr = to_bytes(&addr); - let vec = to_bytes(&x"01020304"); - Vector::append(&mut addr, vec); - // addr : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 1, 2, 3, 4] - assert!(skip_address(&addr, 0) == 16,2006); - } - - // skip bool - public fun skip_bool(input: &vector, offset: u64): u64{ - can_skip(input, offset, 1); - offset + 1 - } - - spec skip_bool { - pragma verify = false; - } - - fun can_skip(input: &vector, offset: u64, n: u64){ - assert!(((offset + n) <= Vector::length(input)) && (offset < offset + n), Errors::invalid_state(ERR_INPUT_NOT_LARGE_ENOUGH)); - } - - spec can_skip { - pragma verify = false; - } } } diff --git a/sources/Block.move b/sources/Block.move index d1e841fa..c1e115c3 100644 --- a/sources/Block.move +++ b/sources/Block.move @@ -6,12 +6,6 @@ module Block { use StarcoinFramework::Signer; use StarcoinFramework::CoreAddresses; use StarcoinFramework::Errors; - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::Ring; - use StarcoinFramework::BCS; - use StarcoinFramework::Hash; - use StarcoinFramework::GenesisSignerCapability; spec module { pragma verify; @@ -40,33 +34,7 @@ module Block { uncles: u64, } - // - struct Checkpoint has copy,drop,store{ - //number of the block - block_number: u64, - //Hash of the block - block_hash: vector, - //State root of the block - state_root: Option::Option>, - } - - // - struct Checkpoints has key,store{ - //all checkpoints - checkpoints : Ring::Ring, - index : u64, - last_number : u64, - } - - const EBLOCK_NUMBER_MISMATCH : u64 = 17; - const ERROR_NO_HAVE_CHECKPOINT: u64 = 18; - const ERROR_NOT_BLOCK_HEADER : u64 = 19; - const ERROR_INTERVAL_TOO_LITTLE: u64 = 20; - const ERR_ALREADY_INITIALIZED : u64 = 21; - - const CHECKPOINT_LENGTH : u64 = 60; - const BLOCK_HEADER_LENGTH : u64 = 247; - const BLOCK_INTERVAL_NUMBER : u64 = 5; + const EBLOCK_NUMBER_MISMATCH: u64 = 17; /// This can only be invoked by the GENESIS_ACCOUNT at genesis public fun initialize(account: &signer, parent_hash: vector) { @@ -148,306 +116,5 @@ module Block { spec schema AbortsIfBlockMetadataNotExist { aborts_if !exists(CoreAddresses::GENESIS_ADDRESS()); } - - public fun checkpoints_init(){ - - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - - let checkpoints = Ring::create_with_capacity(CHECKPOINT_LENGTH); - move_to( - &signer, - Checkpoints { - checkpoints : checkpoints, - index : 0, - last_number : 0, - }); - } - - spec checkpoints_init { - pragma verify = false; - } - - public (script) fun checkpoint_entry(_account: signer) acquires BlockMetadata, Checkpoints { - checkpoint(); - } - - spec checkpoint_entry { - pragma verify = false; - } - - public fun checkpoint() acquires BlockMetadata, Checkpoints{ - let parent_block_number = get_current_block_number() - 1; - let parent_block_hash = get_parent_hash(); - - let checkpoints = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - base_checkpoint(checkpoints, parent_block_number, parent_block_hash); - - } - - spec checkpoint { - pragma verify = false; - } - - fun base_checkpoint(checkpoints: &mut Checkpoints, parent_block_number: u64, parent_block_hash:vector){ - assert!(checkpoints.last_number + BLOCK_INTERVAL_NUMBER <= parent_block_number || checkpoints.last_number == 0, Errors::invalid_argument(ERROR_INTERVAL_TOO_LITTLE)); - - checkpoints.index = checkpoints.index + 1; - checkpoints.last_number = parent_block_number; - let op_checkpoint = Ring::push(&mut checkpoints.checkpoints, Checkpoint { - block_number: parent_block_number, - block_hash: parent_block_hash, - state_root: Option::none>(), - } ); - if(Option::is_some(&op_checkpoint)){ - Option::destroy_some(op_checkpoint); - }else{ - Option::destroy_none(op_checkpoint); - } - } - - spec base_checkpoint { - pragma verify = false; - } - - public fun latest_state_root():(u64,vector) acquires Checkpoints{ - let checkpoints = borrow_global(CoreAddresses::GENESIS_ADDRESS()); - base_latest_state_root(checkpoints) - } - - spec latest_state_root { - pragma verify = false; - } - - fun base_latest_state_root(checkpoints: &Checkpoints):(u64,vector){ - let len = Ring::capacity(&checkpoints.checkpoints); - let j = if(checkpoints.index < len - 1){ - checkpoints.index - }else{ - len - }; - let i = checkpoints.index; - while( j > 0){ - let op_checkpoint = Ring::borrow(&checkpoints.checkpoints, i - 1 ); - if( Option::is_some(op_checkpoint) && Option::is_some(&Option::borrow(op_checkpoint).state_root) ) { - let state_root = Option::borrow(&Option::borrow(op_checkpoint).state_root); - return (Option::borrow(op_checkpoint).block_number, *state_root) - }; - j = j - 1; - i = i - 1; - }; - - abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT) - } - - spec base_latest_state_root { - pragma verify = false; - } - - public (script) fun update_state_root_entry(_account: signer , header: vector) - acquires Checkpoints { - update_state_root(header); - } - - spec update_state_root_entry { - pragma verify = false; - } - - public fun update_state_root(header: vector) acquires Checkpoints { - let checkpoints = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - base_update_state_root(checkpoints, header); - } - - spec update_state_root { - pragma verify = false; - } - - fun base_update_state_root(checkpoints: &mut Checkpoints, header: vector){ - let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader"); - - //parent_hash - let new_offset = BCS::skip_bytes(&header,0); - //timestamp - let new_offset = BCS::skip_u64(&header,new_offset); - //number - let (number,new_offset) = BCS::deserialize_u64(&header,new_offset); - //author - new_offset = BCS::skip_address(&header,new_offset); - //author_auth_key - new_offset = BCS::skip_option_bytes(&header,new_offset); - //txn_accumulator_root - new_offset = BCS::skip_bytes(&header,new_offset); - //block_accumulator_root - new_offset = BCS::skip_bytes(&header,new_offset); - //state_root - let (state_root,_new_offset) = BCS::deserialize_bytes(&header,new_offset); - - Vector::append(&mut prefix,header); - let block_hash = Hash::sha3_256(prefix); - - let len = Ring::capacity(&checkpoints.checkpoints); - let j = if(checkpoints.index < len - 1){ - checkpoints.index - }else{ - len - }; - let i = checkpoints.index; - while( j > 0){ - let op_checkpoint = Ring::borrow_mut(&mut checkpoints.checkpoints, i - 1); - - if( Option::is_some(op_checkpoint) && &Option::borrow(op_checkpoint).block_hash == &block_hash && Option::borrow(op_checkpoint).block_number == number) { - - let op_state_root = &mut Option::borrow_mut(op_checkpoint).state_root; - if(Option::is_some(op_state_root)){ - Option::swap(op_state_root, state_root); - }else{ - Option::fill(op_state_root, state_root); - }; - return - }; - j = j - 1; - i = i - 1; - }; - - abort Errors::invalid_state(ERROR_NO_HAVE_CHECKPOINT) - } - - spec base_update_state_root { - pragma verify = false; - } - - #[test] - fun test_header(){ - // Block header Unit test - // Use Main Genesis BlockHeader in Rust - // BlockHeader { - // id: Some(HashValue(0x80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d)), - // parent_hash: HashValue(0xb82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529a), - // timestamp: 1621311100863, - // number: 0, - // author: 0x00000000000000000000000000000001, - // author_auth_key: None, - // txn_accumulator_root: HashValue(0x43609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae), - // block_accumulator_root: HashValue(0x414343554d554c41544f525f504c414345484f4c4445525f4841534800000000), - // state_root: HashValue(0x61125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d), - // gas_used: 0, - // difficulty: 11660343, - // body_hash: HashValue(0x7564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b), - // chain_id: ChainId { id: 1 }, - // nonce: 0, - // extra: BlockHeaderExtra([0, 0, 0, 0]) - // } - // Blockheader BCS : 20b82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529abf17ac7d79010000000000000000000000000000000000000000000000000001002043609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae20414343554d554c41544f525f504c414345484f4c4445525f48415348000000002061125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d00000000000000000000000000000000000000000000000000000000000000000000000000b1ec37207564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b010000000000000000 - - let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader"); - let header = x"20b82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529abf17ac7d79010000000000000000000000000000000000000000000000000001002043609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae20414343554d554c41544f525f504c414345484f4c4445525f48415348000000002061125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d00000000000000000000000000000000000000000000000000000000000000000000000000b1ec37207564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b010000000000000000"; - let (_parent_hash,new_offset) = BCS::deserialize_bytes(&header,0); - let (_timestamp,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (number,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_author,new_offset) = BCS::deserialize_address(&header,new_offset); - let (_author_auth_key,new_offset) = BCS::deserialize_option_bytes(&header,new_offset); - let (_txn_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_block_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (state_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_gas_used,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_difficultyfirst,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_difficultylast,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_body_hash,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_chain_id,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_nonce,new_offset) = BCS::deserialize_u32(&header,new_offset); - let (_extra1,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra2,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra3,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra4,_new_offset) = BCS::deserialize_u8(&header,new_offset); - - Vector::append(&mut prefix,header); - let block_hash = Hash::sha3_256(prefix); - assert!(block_hash == x"80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d" ,1001); - assert!(number == 0,1002); - assert!(state_root == x"61125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d",1003); - } - - #[test] - fun test_header2(){ - // Block header Unit test - // Use BlockHeader in integration test - //"number":"2", - //"block_hash":"0x9433bb7b56333dfc33e012f3b22b67277a3026448eb5043747d59284f648343d" - //"parent_hash":"0x9be97e678afa8a0a4cf9ca612be6f64810a6f7d5f8b4b4ddf5e4971ef4b5eb48" - //"state_root":"0xd2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a" - //"header":"0x209be97e678afa8a0a4cf9ca612be6f64810a6f7d5f8b4b4ddf5e4971ef4b5eb4820aa26050000000002000000000000000000000000000000000000000000000200205c79e9493845327132ab3011c7c6c9d8bddcfde5553abb90cf5ef7fdfb39a4aa20c4d8e6cdb52520794dad5241f51a4eed46a5e5264dd148032cc3bdb8e3bdbe7a20d2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a0000000000000000000000000000000000000000000000000000000000000000000000000000000020c01e0329de6d899348a8ef4bd51db56175b3fa0988e57c3dcec8eaf13a164d97fe0000000000000000" - - let prefix = Hash::sha3_256(b"STARCOIN::BlockHeader"); - let header = x"209be97e678afa8a0a4cf9ca612be6f64810a6f7d5f8b4b4ddf5e4971ef4b5eb4820aa26050000000002000000000000000000000000000000000000000000000200205c79e9493845327132ab3011c7c6c9d8bddcfde5553abb90cf5ef7fdfb39a4aa20c4d8e6cdb52520794dad5241f51a4eed46a5e5264dd148032cc3bdb8e3bdbe7a20d2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a0000000000000000000000000000000000000000000000000000000000000000000000000000000020c01e0329de6d899348a8ef4bd51db56175b3fa0988e57c3dcec8eaf13a164d97fe0000000000000000"; - let (_parent_hash,new_offset) = BCS::deserialize_bytes(&header,0); - let (_timestamp,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (number,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_author,new_offset) = BCS::deserialize_address(&header,new_offset); - let (_author_auth_key,new_offset) = BCS::deserialize_option_bytes(&header,new_offset); - let (_txn_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_block_accumulator_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (state_root,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_gas_used,new_offset) = BCS::deserialize_u64(&header,new_offset); - let (_difficultyfirst,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_difficultylast,new_offset) = BCS::deserialize_u128(&header,new_offset); - let (_body_hash,new_offset) = BCS::deserialize_bytes(&header,new_offset); - let (_chain_id,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_nonce,new_offset) = BCS::deserialize_u32(&header,new_offset); - let (_extra1,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra2,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra3,new_offset) = BCS::deserialize_u8(&header,new_offset); - let (_extra4,_new_offset) = BCS::deserialize_u8(&header,new_offset); - - Vector::append(&mut prefix,header); - let block_hash = Hash::sha3_256(prefix); - assert!(block_hash == x"9433bb7b56333dfc33e012f3b22b67277a3026448eb5043747d59284f648343d" ,1001); - assert!(number == 2,1002); - assert!(state_root == x"d2df4c8c579f9e05b0adf14b53785379fb245465d703834eb19fba74d9114a9a",1003); - } - - #[test] - fun test_checkpoint(){ - let checkpoints = Checkpoints { - checkpoints : Ring::create_with_capacity(3), - index : 0, - last_number : 0 - }; - - base_checkpoint(&mut checkpoints, 0, x"80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d"); - - let Checkpoints{ - checkpoints: ring, - index : index, - last_number: last_number - } = checkpoints; - assert!( index == 1 && last_number == 0 , 10020); - Ring::destroy(ring); - } - - #[test] - fun test_latest_state_root(){ - let header = x"20b82a2c11f2df62bf87c2933d0281e5fe47ea94d5f0049eec1485b682df29529abf17ac7d79010000000000000000000000000000000000000000000000000001002043609d52fdf8e4a253c62dfe127d33c77e1fb4afdefb306d46ec42e21b9103ae20414343554d554c41544f525f504c414345484f4c4445525f48415348000000002061125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d00000000000000000000000000000000000000000000000000000000000000000000000000b1ec37207564db97ee270a6c1f2f73fbf517dc0777a6119b7460b7eae2890d1ce504537b010000000000000000"; - - let checkpoints = Checkpoints { - checkpoints : Ring::create_with_capacity(3), - index : 0, - last_number : 0 - }; - - base_checkpoint(&mut checkpoints, 0, x"80848150abee7e9a3bfe9542a019eb0b8b01f124b63b011f9c338fdb935c417d"); - - base_update_state_root(&mut checkpoints, copy header); - - let (number , state_root ) = base_latest_state_root(&checkpoints); - let Checkpoints{ - checkpoints: ring, - index : index, - last_number: last_number - } = checkpoints; - assert!( index == 1 && last_number == 0 , 10020); - assert!( number == 0 && state_root == x"61125a3ab755b993d72accfea741f8537104db8e022098154f3a66d5c23e828d" , 10020); - Ring::destroy(ring); - } - } } \ No newline at end of file diff --git a/sources/BlockReward.move b/sources/BlockReward.move index de9a96bd..c5bd5078 100644 --- a/sources/BlockReward.move +++ b/sources/BlockReward.move @@ -13,7 +13,7 @@ module BlockReward { use StarcoinFramework::Config; use StarcoinFramework::Event; use StarcoinFramework::Treasury; - use StarcoinFramework::TreasuryPlugin; + use StarcoinFramework::TreasuryWithdrawDaoProposal; spec module { pragma verify = false; @@ -122,7 +122,7 @@ module BlockReward { block_reward = treasury_balance; }; if (block_reward > 0) { - let reward = TreasuryPlugin::withdraw_for_block_reward(account, block_reward); + let reward = TreasuryWithdrawDaoProposal::withdraw_for_block_reward(account, block_reward); Token::deposit(&mut total_reward, reward); }; }; diff --git a/sources/Compare.move b/sources/Compare.move index 41110b9b..b4ee466a 100644 --- a/sources/Compare.move +++ b/sources/Compare.move @@ -46,11 +46,7 @@ module Compare { while (i1 > 0 && i2 > 0) { i1 = i1 - 1; i2 = i2 - 1; - let v1 = *Vector::borrow(v1, i1); - let v2 = *Vector::borrow(v2, i2); - let elem_cmp = if (v1 == v2) EQUAL - else if (v1 < v2) LESS_THAN - else GREATER_THAN; + let elem_cmp = cmp_u8(*Vector::borrow(v1, i1), *Vector::borrow(v2, i2)); if (elem_cmp != 0) return elem_cmp // else, compare next element }; @@ -62,18 +58,16 @@ module Compare { let l1 = Vector::length(v1); let l2 = Vector::length(v2); let len_cmp = cmp_u64(l1, l2); - let i = 0; - while (i < l1 && i < l2) { - let v1 = *Vector::borrow(v1, i); - let v2 = *Vector::borrow(v2, i); - let elem_cmp = if (v1 == v2) EQUAL - else if (v1 < v2) LESS_THAN - else GREATER_THAN; + let i1 = 0; + let i2 = 0; + while (i1 < l1 && i2 < l2) { + let elem_cmp = cmp_u8(*Vector::borrow(v1, i1), *Vector::borrow(v2, i2)); if (elem_cmp != 0) { return elem_cmp }; // else, compare next element - i = i + 1; + i1 = i1 + 1; + i2 = i2 + 1; }; // all compared elements equal; use length comparison to break the tie len_cmp @@ -81,46 +75,35 @@ module Compare { spec cmp_bytes { pragma verify = false; + //cmp_u8(*Vector::borrow(v1, i1), *Vector::borrow(v2, i2)) is not covered } spec cmp_bcs_bytes { pragma verify = false; + //cmp_u8(*Vector::borrow(v1, i1), *Vector::borrow(v2, i2)) is not covered } - - // Compare two `u64`'s - fun cmp_u64(i1: u64, i2: u64): u8 { + // Compare two `u8`'s + fun cmp_u8(i1: u8, i2: u8): u8 { if (i1 == i2) EQUAL else if (i1 < i2) LESS_THAN else GREATER_THAN } - spec cmp_u64 { - aborts_if false; - } - - public fun is_equal(result: u8): bool { - result == EQUAL - } - - spec is_equal { + spec cmp_u8 { aborts_if false; } - public fun is_less_than(result: u8): bool { - result == LESS_THAN + // Compare two `u64`'s + fun cmp_u64(i1: u64, i2: u64): u8 { + if (i1 == i2) EQUAL + else if (i1 < i2) LESS_THAN + else GREATER_THAN } - spec is_less_than { + spec cmp_u64 { aborts_if false; } - public fun is_greater_than(result: u8): bool { - result == GREATER_THAN - } - - spec is_greater_than { - aborts_if false; - } } } diff --git a/sources/EventUtil.move b/sources/EventUtil.move deleted file mode 100644 index 1ecfceb5..00000000 --- a/sources/EventUtil.move +++ /dev/null @@ -1,36 +0,0 @@ -module StarcoinFramework::EventUtil { - use StarcoinFramework::Event; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - - const ERR_INIT_REPEATE: u64 = 101; - const ERR_RESOURCE_NOT_EXISTS: u64 = 102; - - struct EventHandleWrapper has key { - handle: Event::EventHandle, - } - - public fun init_event(sender: &signer) { - let broker = Signer::address_of(sender); - assert!(!exists>(broker), Errors::invalid_state(ERR_INIT_REPEATE)); - move_to(sender, EventHandleWrapper { - handle: Event::new_event_handle(sender) - }); - } - - public fun uninit_event(sender: &signer) acquires EventHandleWrapper { - let broker = Signer::address_of(sender); - assert!(exists>(broker), Errors::invalid_state(ERR_RESOURCE_NOT_EXISTS)); - let EventHandleWrapper { handle } = move_from>(broker); - Event::destroy_handle(handle); - } - - public fun emit_event(broker: address, event: EventT) acquires EventHandleWrapper { - let event_handle = borrow_global_mut>(broker); - Event::emit_event(&mut event_handle.handle, event); - } - - public fun exist_event(broker: address): bool { - exists>(broker) - } -} diff --git a/sources/Genesis.move b/sources/Genesis.move index f62efea5..faab286c 100644 --- a/sources/Genesis.move +++ b/sources/Genesis.move @@ -1,10 +1,12 @@ +address StarcoinFramework { /// The module for init Genesis -module StarcoinFramework::Genesis { +module Genesis { use StarcoinFramework::CoreAddresses; use StarcoinFramework::Account; use StarcoinFramework::Signer; use StarcoinFramework::Timestamp; + use StarcoinFramework::Token; use StarcoinFramework::STC::{Self, STC}; use StarcoinFramework::DummyToken; use StarcoinFramework::PackageTxnManager; @@ -17,33 +19,18 @@ module StarcoinFramework::Genesis { use StarcoinFramework::ChainId; use StarcoinFramework::ConsensusStrategy; use StarcoinFramework::TransactionPublishOption; + use StarcoinFramework::Collection; use StarcoinFramework::TransactionTimeoutConfig; use StarcoinFramework::Epoch; use StarcoinFramework::Version; use StarcoinFramework::Config; use StarcoinFramework::Option; use StarcoinFramework::Treasury; + use StarcoinFramework::TreasuryWithdrawDaoProposal; + use StarcoinFramework::StdlibUpgradeScripts; use StarcoinFramework::GenesisSignerCapability; use StarcoinFramework::STCUSDOracle; use StarcoinFramework::GenesisNFT; - use StarcoinFramework::StarcoinDAO; - use StarcoinFramework::TreasuryPlugin; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::AnyMemberPlugin; - use StarcoinFramework::DAOExtensionPoint; - use StarcoinFramework::ConfigProposalPlugin; - use StarcoinFramework::GrantProposalPlugin; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::MemberProposalPlugin; - use StarcoinFramework::MintProposalPlugin; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::UpgradeModulePlugin; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::LanguageVersion; - use StarcoinFramework::Errors; - use StarcoinFramework::WithdrawPlugin; spec module { pragma verify = false; // break after enabling v2 compilation scheme @@ -51,63 +38,13 @@ module StarcoinFramework::Genesis { pragma aborts_if_is_strict = true; } - public(script) fun initialize( - _stdlib_version: u64, - // block reward config - _reward_delay: u64, - _pre_mine_stc_amount: u128, - _time_mint_stc_amount: u128, - _time_mint_stc_period: u64, - _parent_hash: vector, - _association_auth_key: vector, - _genesis_auth_key: vector, - _chain_id: u8, - _genesis_timestamp: u64, - //consensus config - _uncle_rate_target: u64, - _epoch_block_count: u64, - _base_block_time_target: u64, - _base_block_difficulty_window: u64, - _base_reward_per_block: u128, - _base_reward_per_uncle_percent: u64, - _min_block_time_target: u64, - _max_block_time_target: u64, - _base_max_uncles_per_block: u64, - _base_block_gas_limit: u64, - _strategy: u8, - //vm config - _script_allowed: bool, - _module_publishing_allowed: bool, - _instruction_schedule: vector, - _native_schedule: vector, - //gas constants - _global_memory_per_byte_cost: u64, - _global_memory_per_byte_write_cost: u64, - _min_transaction_gas_units: u64, - _large_transaction_cutoff: u64, - _instrinsic_gas_per_byte: u64, - _maximum_number_of_gas_units: u64, - _min_price_per_gas_unit: u64, - _max_price_per_gas_unit: u64, - _max_transaction_size_in_bytes: u64, - _gas_unit_scaling_factor: u64, - _default_account_size: u64, - // dao config - _voting_delay: u64, - _voting_period: u64, - _voting_quorum_rate: u8, - _min_action_delay: u64, - // transaction timeout config - _transaction_timeout: u64, - ) { - abort Errors::deprecated(1) - } - public(script) fun initialize_v2( + public(script) fun initialize( stdlib_version: u64, - // block reward and stc config + + // block reward config reward_delay: u64, - total_stc_amount: u128, + pre_mine_stc_amount: u128, time_mint_stc_amount: u128, time_mint_stc_period: u64, @@ -116,6 +53,7 @@ module StarcoinFramework::Genesis { genesis_auth_key: vector, chain_id: u8, genesis_timestamp: u64, + //consensus config uncle_rate_target: u64, epoch_block_count: u64, @@ -128,11 +66,13 @@ module StarcoinFramework::Genesis { base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, + //vm config script_allowed: bool, module_publishing_allowed: bool, instruction_schedule: vector, native_schedule: vector, + //gas constants global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, @@ -145,39 +85,32 @@ module StarcoinFramework::Genesis { max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, + // dao config voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, + // transaction timeout config transaction_timeout: u64, ) { - Self::do_initialize( - stdlib_version, - reward_delay, - total_stc_amount, - pre_mine_stc_amount, - time_mint_stc_amount, - time_mint_stc_period, - parent_hash, - association_auth_key, - genesis_auth_key, - chain_id, - genesis_timestamp, - uncle_rate_target, - epoch_block_count, - base_block_time_target, - base_block_difficulty_window, - base_reward_per_block, - base_reward_per_uncle_percent, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, + assert!(Timestamp::is_genesis(), 1); + // create genesis account + let genesis_account = Account::create_genesis_account(CoreAddresses::GENESIS_ADDRESS()); + //Init global time + Timestamp::initialize(&genesis_account, genesis_timestamp); + ChainId::initialize(&genesis_account, chain_id); + ConsensusStrategy::initialize(&genesis_account, strategy); + Block::initialize(&genesis_account, parent_hash); + TransactionPublishOption::initialize( + &genesis_account, script_allowed, module_publishing_allowed, + ); + // init config + VMConfig::initialize( + &genesis_account, instruction_schedule, native_schedule, global_memory_per_byte_cost, @@ -191,27 +124,83 @@ module StarcoinFramework::Genesis { max_transaction_size_in_bytes, gas_unit_scaling_factor, default_account_size, - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - transaction_timeout, ); + TransactionTimeoutConfig::initialize(&genesis_account, transaction_timeout); + ConsensusConfig::initialize( + &genesis_account, + uncle_rate_target, + epoch_block_count, + base_block_time_target, + base_block_difficulty_window, + base_reward_per_block, + base_reward_per_uncle_percent, + min_block_time_target, + max_block_time_target, + base_max_uncles_per_block, + base_block_gas_limit, + strategy, + ); + Epoch::initialize(&genesis_account); + BlockReward::initialize(&genesis_account, reward_delay); + TransactionFee::initialize(&genesis_account); + let association = Account::create_genesis_account( + CoreAddresses::ASSOCIATION_ROOT_ADDRESS(), + ); + Config::publish_new_config(&genesis_account, Version::new_version(stdlib_version)); + // stdlib use two phase upgrade strategy. + PackageTxnManager::update_module_upgrade_strategy( + &genesis_account, + PackageTxnManager::get_strategy_two_phase(), + Option::some(0u64), + ); + // stc should be initialized after genesis_account's module upgrade strategy set. + { + STC::initialize(&genesis_account, voting_delay, voting_period, voting_quorum_rate, min_action_delay); + Account::do_accept_token(&genesis_account); + DummyToken::initialize(&genesis_account); + Account::do_accept_token(&association); + }; + if (pre_mine_stc_amount > 0) { + let stc = Token::mint(&genesis_account, pre_mine_stc_amount); + Account::deposit(Signer::address_of(&association), stc); + }; + if (time_mint_stc_amount > 0) { + let cap = Token::remove_mint_capability(&genesis_account); + let key = Token::issue_linear_mint_key(&cap, time_mint_stc_amount, time_mint_stc_period); + Token::add_mint_capability(&genesis_account, cap); + Collection::put(&association, key); + }; + // only dev network set genesis auth key. + if (!Vector::is_empty(&genesis_auth_key)) { + let genesis_rotate_key_cap = Account::extract_key_rotation_capability(&genesis_account); + Account::rotate_authentication_key_with_capability(&genesis_rotate_key_cap, genesis_auth_key); + Account::restore_key_rotation_capability(genesis_rotate_key_cap); + }; + let assoc_rotate_key_cap = Account::extract_key_rotation_capability(&association); + Account::rotate_authentication_key_with_capability(&assoc_rotate_key_cap, association_auth_key); + Account::restore_key_rotation_capability(assoc_rotate_key_cap); + //Start time, Timestamp::is_genesis() will return false. this call should at the end of genesis init. + Timestamp::set_time_has_started(&genesis_account); + Account::release_genesis_signer(genesis_account); + Account::release_genesis_signer(association); } - fun do_initialize( + public(script) fun initialize_v2( stdlib_version: u64, + // block reward and stc config reward_delay: u64, total_stc_amount: u128, pre_mine_stc_amount: u128, time_mint_stc_amount: u128, time_mint_stc_period: u64, + parent_hash: vector, association_auth_key: vector, genesis_auth_key: vector, chain_id: u8, genesis_timestamp: u64, + //consensus config uncle_rate_target: u64, epoch_block_count: u64, @@ -224,11 +213,13 @@ module StarcoinFramework::Genesis { base_max_uncles_per_block: u64, base_block_gas_limit: u64, strategy: u8, + //vm config script_allowed: bool, module_publishing_allowed: bool, instruction_schedule: vector, native_schedule: vector, + //gas constants global_memory_per_byte_cost: u64, global_memory_per_byte_write_cost: u64, @@ -241,14 +232,119 @@ module StarcoinFramework::Genesis { max_transaction_size_in_bytes: u64, gas_unit_scaling_factor: u64, default_account_size: u64, + // dao config voting_delay: u64, voting_period: u64, voting_quorum_rate: u8, min_action_delay: u64, + // transaction timeout config transaction_timeout: u64, ) { + Self::do_initialize( + stdlib_version, + reward_delay, + total_stc_amount, + pre_mine_stc_amount, + time_mint_stc_amount, + time_mint_stc_period, + parent_hash, + association_auth_key, + genesis_auth_key, + chain_id, + genesis_timestamp, + uncle_rate_target, + epoch_block_count, + base_block_time_target, + base_block_difficulty_window, + base_reward_per_block, + base_reward_per_uncle_percent, + min_block_time_target, + max_block_time_target, + base_max_uncles_per_block, + base_block_gas_limit, + strategy, + script_allowed, + module_publishing_allowed, + instruction_schedule, + native_schedule, + global_memory_per_byte_cost, + global_memory_per_byte_write_cost, + min_transaction_gas_units, + large_transaction_cutoff, + instrinsic_gas_per_byte, + maximum_number_of_gas_units, + min_price_per_gas_unit, + max_price_per_gas_unit, + max_transaction_size_in_bytes, + gas_unit_scaling_factor, + default_account_size, + voting_delay, + voting_period, + voting_quorum_rate, + min_action_delay, + transaction_timeout, + ); + } + + fun do_initialize( + stdlib_version: u64, + + // block reward and stc config + reward_delay: u64, + total_stc_amount: u128, + pre_mine_stc_amount: u128, + time_mint_stc_amount: u128, + time_mint_stc_period: u64, + + parent_hash: vector, + association_auth_key: vector, + genesis_auth_key: vector, + chain_id: u8, + genesis_timestamp: u64, + + //consensus config + uncle_rate_target: u64, + epoch_block_count: u64, + base_block_time_target: u64, + base_block_difficulty_window: u64, + base_reward_per_block: u128, + base_reward_per_uncle_percent: u64, + min_block_time_target: u64, + max_block_time_target: u64, + base_max_uncles_per_block: u64, + base_block_gas_limit: u64, + strategy: u8, + + //vm config + script_allowed: bool, + module_publishing_allowed: bool, + instruction_schedule: vector, + native_schedule: vector, + + //gas constants + global_memory_per_byte_cost: u64, + global_memory_per_byte_write_cost: u64, + min_transaction_gas_units: u64, + large_transaction_cutoff: u64, + instrinsic_gas_per_byte: u64, + maximum_number_of_gas_units: u64, + min_price_per_gas_unit: u64, + max_price_per_gas_unit: u64, + max_transaction_size_in_bytes: u64, + gas_unit_scaling_factor: u64, + default_account_size: u64, + + // dao config + voting_delay: u64, + voting_period: u64, + voting_quorum_rate: u8, + min_action_delay: u64, + + // transaction timeout config + transaction_timeout: u64, + ){ Timestamp::assert_genesis(); // create genesis account let genesis_account = Account::create_genesis_account(CoreAddresses::GENESIS_ADDRESS()); @@ -308,7 +404,7 @@ module StarcoinFramework::Genesis { BlockReward::initialize(&genesis_account, reward_delay); // stc should be initialized after genesis_account's module upgrade strategy set and all on chain config init. - let withdraw_cap = STC::initialize_v3(&genesis_account, total_stc_amount); + let withdraw_cap = STC::initialize_v2(&genesis_account, total_stc_amount, voting_delay, voting_period, voting_quorum_rate, min_action_delay); Account::do_accept_token(&genesis_account); Account::do_accept_token(&association); @@ -324,7 +420,7 @@ module StarcoinFramework::Genesis { }; // Lock the TreasuryWithdrawCapability to Dao - TreasuryPlugin::delegate_capability(&genesis_account, withdraw_cap); + TreasuryWithdrawDaoProposal::plugin(&genesis_account, withdraw_cap); TransactionFee::initialize(&genesis_account); @@ -349,48 +445,7 @@ module StarcoinFramework::Genesis { let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY"; GenesisNFT::initialize(&genesis_account, merkle_root, 1639u64, image); }; - Config::publish_new_config(&genesis_account, LanguageVersion::new(4)); - - //v11 -> v12 - Block::checkpoints_init(); - DAORegistry::initialize(); - - DAOExtensionPoint::initialize(); - DAOPluginMarketplace::initialize(); - - AnyMemberPlugin::initialize(&genesis_account); - ConfigProposalPlugin::initialize(&genesis_account); - GrantProposalPlugin::initialize(&genesis_account); - InstallPluginProposalPlugin::initialize(&genesis_account); - MemberProposalPlugin::initialize(&genesis_account); - MintProposalPlugin::initialize(&genesis_account); - StakeToSBTPlugin::initialize(&genesis_account); - UpgradeModulePlugin::initialize(&genesis_account); - GasOracleProposalPlugin::initialize(&genesis_account); - TreasuryPlugin::initialize(&genesis_account); - - let signer_cap = Account::get_genesis_capability(); - let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(&genesis_account); - StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, voting_delay, voting_period, voting_quorum_rate, min_action_delay, 1000 * 1000 * 1000 * 1000); - - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::delegate_config_capability( - Config::extract_modify_config_capability(&genesis_account)); - StarcoinDAO::set_treasury_withdraw_proposal_scale(100); - - // v12 -> v13 - WithdrawPlugin::initialize(&genesis_account); - StarcoinDAO::upgrade_dao(); - + StdlibUpgradeScripts::do_upgrade_from_v6_to_v7_with_language_version(&genesis_account, 4); //Start time, Timestamp::is_genesis() will return false. this call should at the end of genesis init. Timestamp::set_time_has_started(&genesis_account); Account::release_genesis_signer(genesis_account); @@ -398,19 +453,19 @@ module StarcoinFramework::Genesis { } /// Init the genesis for unit tests - public fun initialize_for_unit_tests() { + public fun initialize_for_unit_tests(){ let stdlib_version: u64 = 6; let reward_delay: u64 = 7; let total_stc_amount: u128 = 3185136000000000000u128; let pre_mine_stc_amount: u128 = 159256800000000000u128; - let time_mint_stc_amount: u128 = (85043130u128 * 3u128 + 74213670u128 * 3u128) * 1000000000u128; + let time_mint_stc_amount: u128 = (85043130u128 * 3u128 + 74213670u128 * 3u128)*1000000000u128; let time_mint_stc_period: u64 = 1000000000; let parent_hash: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; let association_auth_key: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; let genesis_auth_key: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; let chain_id: u8 = 255; - let genesis_timestamp: u64 = 0; + let genesis_timestamp: u64 =0; //consensus config let uncle_rate_target: u64 = 80; @@ -441,13 +496,13 @@ module StarcoinFramework::Genesis { let maximum_number_of_gas_units: u64 = 1; let min_price_per_gas_unit: u64 = 1; let max_price_per_gas_unit: u64 = 10000; - let max_transaction_size_in_bytes: u64 = 1024 * 1024; + let max_transaction_size_in_bytes: u64 = 1024*1024; let gas_unit_scaling_factor: u64 = 1; let default_account_size: u64 = 600; // dao config let voting_delay: u64 = 1000; - let voting_period: u64 = 6000; + let voting_period: u64 = 6000; let voting_quorum_rate: u8 = 4; let min_action_delay: u64 = 1000; @@ -500,3 +555,4 @@ module StarcoinFramework::Genesis { ); } } +} \ No newline at end of file diff --git a/sources/GenesisNFT.move b/sources/GenesisNFT.move index 6e86a397..b18f9f74 100644 --- a/sources/GenesisNFT.move +++ b/sources/GenesisNFT.move @@ -24,7 +24,8 @@ module StarcoinFramework::GenesisNFT { public fun initialize(sender: &signer, merkle_root: vector, leafs: u64, image: vector){ CoreAddresses::assert_genesis_address(sender); let metadata = NFT::new_meta_with_image(b"StarcoinGenesisNFT", image, b"The starcoin genesis NFT"); - let cap = MerkleNFTDistributor::register_v2(sender, merkle_root, leafs, metadata); + let nft_info = GenesisNFTInfo{merkle_root: *&merkle_root, total_supply: leafs}; + let cap = MerkleNFTDistributor::register(sender, merkle_root, leafs, nft_info, metadata); move_to(sender, GenesisNFTMintCapability{cap}); } @@ -36,13 +37,8 @@ module StarcoinFramework::GenesisNFT { move_to(sender, nft_info); } - public(script) fun mint_entry(sender: signer, index: u64, merkle_proof:vector>) - acquires GenesisNFTMintCapability { - mint(&sender, index, merkle_proof); - } - public fun mint(sender: &signer, index: u64, merkle_proof:vector>) - acquires GenesisNFTMintCapability { + acquires GenesisNFTMintCapability{ let metadata = NFT::empty_meta(); let cap = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); let nft = MerkleNFTDistributor::mint_with_cap(sender, &mut cap.cap, CoreAddresses::GENESIS_ADDRESS(), index, metadata, GenesisNFTMeta{index}, GenesisNFT{}, merkle_proof); @@ -76,6 +72,6 @@ module StarcoinFramework::GenesisNFTScripts { /// Mint a GenesisNFT public(script) fun mint(sender: signer, index: u64, merkle_proof:vector>) { - GenesisNFT::mint_entry(sender, index, merkle_proof); + GenesisNFT::mint(&sender, index, merkle_proof); } } diff --git a/sources/GenesisSignerCapability.move b/sources/GenesisSignerCapability.move index 46cee13e..07daa754 100644 --- a/sources/GenesisSignerCapability.move +++ b/sources/GenesisSignerCapability.move @@ -7,13 +7,7 @@ module StarcoinFramework::GenesisSignerCapability { friend StarcoinFramework::Oracle; friend StarcoinFramework::Genesis; friend StarcoinFramework::StdlibUpgradeScripts; - friend StarcoinFramework::DAORegistry; - friend StarcoinFramework::DAOExtensionPoint; - friend StarcoinFramework::DAOPluginMarketplace; - friend StarcoinFramework::Block; - friend StarcoinFramework::DAOAccount; - friend StarcoinFramework::GasOracleProposalPlugin; const ENOT_GENESIS_ACCOUNT: u64 = 11; @@ -34,14 +28,4 @@ module StarcoinFramework::GenesisSignerCapability { let cap = borrow_global(CoreAddresses::GENESIS_ADDRESS()); Account::create_signer_with_cap(&cap.cap) } - - #[test_only] - public fun initialize_for_test(signer: &signer, cap: Account::SignerCapability) { - initialize(signer, cap); - } - - #[test_only] - public fun get_genesis_signer_for_test(): signer acquires GenesisSignerCapability { - get_genesis_signer() - } } \ No newline at end of file diff --git a/sources/MerkleNFT.move b/sources/MerkleNFT.move index 959a8b3b..36da5d84 100644 --- a/sources/MerkleNFT.move +++ b/sources/MerkleNFT.move @@ -47,14 +47,7 @@ module StarcoinFramework::MerkleNFTDistributor { claimed_bitmap: vector, } - /// Deprecated, use `register_v2` instead. - public fun register( - signer: &signer, - merkle_root: vector, - leafs: u64, - info: Info, - meta: Metadata - ): MintCapability { + public fun register(signer: &signer, merkle_root: vector, leafs: u64, info: Info, meta: Metadata): MintCapability { let bitmap_count = leafs / 128; if (bitmap_count * 128 < leafs) { bitmap_count = bitmap_count + 1; @@ -74,26 +67,6 @@ module StarcoinFramework::MerkleNFTDistributor { NFT::remove_mint_capability(signer) } - public fun register_v2(signer: &signer, merkle_root: vector, leafs: u64, meta: Metadata): MintCapability { - let bitmap_count = leafs / 128; - if (bitmap_count * 128 < leafs) { - bitmap_count = bitmap_count + 1; - }; - let claimed_bitmap = Vector::empty(); - let j = 0; - while (j < bitmap_count) { - Vector::push_back( &mut claimed_bitmap, 0u128); - j = j + 1; - }; - let distribution = MerkleNFTDistribution{ - merkle_root, - claimed_bitmap - }; - NFT::register_v2(signer, meta); - move_to(signer, distribution); - NFT::remove_mint_capability(signer) - } - public fun mint_with_cap(sender: &signer, cap:&mut MintCapability, creator: address, index: u64, base_meta: Metadata, type_meta: NFTMeta, body: NFTBody, merkle_proof:vector>): NFT acquires MerkleNFTDistribution { let addr = Signer::address_of(sender); diff --git a/sources/ModifyDaoConfigProposal.move b/sources/ModifyDaoConfigProposal.move index c9feca3e..17b8a747 100644 --- a/sources/ModifyDaoConfigProposal.move +++ b/sources/ModifyDaoConfigProposal.move @@ -1,13 +1,13 @@ address StarcoinFramework { /// A proposal module which is used to modify Token's DAO configuration. module ModifyDaoConfigProposal { + // use StarcoinFramework::Config; use StarcoinFramework::Token; use StarcoinFramework::Signer; use StarcoinFramework::Config; use StarcoinFramework::Dao; use StarcoinFramework::Errors; use StarcoinFramework::Option; - use StarcoinFramework::Dao::DaoConfig; spec module { pragma verify = false; // break after enabling v2 compilation scheme @@ -61,20 +61,6 @@ module ModifyDaoConfigProposal { ensures exists>(sender); } - /// Destroy ModifyConfigCapability - public fun destroy_modify_config_capability(sender: &signer) - acquires DaoConfigModifyCapability { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - - let DaoConfigModifyCapability {cap} = move_from>(token_issuer); - Config::destroy_modify_config_capability>(cap); - } - - spec destroy_modify_config_capability { - pragma verify = false; - } - /// Entrypoint for the proposal. public(script) fun propose( signer: signer, diff --git a/sources/ModuleUpgradeScripts.move b/sources/ModuleUpgradeScripts.move index 498f86d7..b276ff1e 100644 --- a/sources/ModuleUpgradeScripts.move +++ b/sources/ModuleUpgradeScripts.move @@ -6,9 +6,6 @@ module ModuleUpgradeScripts { use StarcoinFramework::Version; use StarcoinFramework::Option; use StarcoinFramework::UpgradeModuleDaoProposal; - use StarcoinFramework::Errors; - - const ERR_WRONG_UPGRADE_STRATEGY: u64 = 100; spec module { pragma verify = false; // break after enabling v2 compilation scheme @@ -54,23 +51,6 @@ module ModuleUpgradeScripts { ); } - /// Update `sender`'s module upgrade strategy to `strategy` with min_time_limit. - /// This can only be invoked when strategy is STRATEGY_TWO_PHASE. - public(script) fun update_module_upgrade_strategy_with_min_time( - sender: signer, - strategy: u8, - min_time_limit: u64, - ){ - // 1. check version - assert!(strategy == PackageTxnManager::get_strategy_two_phase(), Errors::invalid_argument(ERR_WRONG_UPGRADE_STRATEGY)); - // 2. update strategy - PackageTxnManager::update_module_upgrade_strategy( - &sender, - strategy, - Option::some(min_time_limit), - ); - } - /// a alias of execute_module_upgrade_plan_propose, will deprecated in the future. public(script) fun submit_module_upgrade_plan( sender: signer, diff --git a/sources/NFT.move b/sources/NFT.move index b32f3a2e..0a6f06a3 100644 --- a/sources/NFT.move +++ b/sources/NFT.move @@ -585,10 +585,6 @@ module IdentifierNFT { } /// Accept NFT, prepare an empty IdentifierNFT for `sender` - public(script) fun accept_entry(sender: signer) { - accept(&sender); - } - public fun accept(sender: &signer) { let addr = Signer::address_of(sender); if (!is_accept(addr)) { @@ -599,10 +595,6 @@ module IdentifierNFT { } /// Destroy the empty IdentifierNFT - public(script) fun destroy_empty_entry(sender: signer) acquires IdentifierNFT { - destroy_empty(&sender); - } - public fun destroy_empty(sender: &signer) acquires IdentifierNFT { let addr = Signer::address_of(sender); if (exists>(addr)) { @@ -730,12 +722,11 @@ module IdentifierNFTScripts { /// Init IdentifierNFT for accept NFT as Identifier. public(script) fun accept(sender: signer) { - IdentifierNFT::accept_entry(sender); + IdentifierNFT::accept(&sender); } - /// Destroy empty IdentifierNFT public(script) fun destroy_empty(sender: signer) { - IdentifierNFT::destroy_empty_entry(sender); + IdentifierNFT::destroy_empty(&sender); } } @@ -750,8 +741,6 @@ module NFTGallery { const ERR_NFT_NOT_EXISTS: u64 = 101; - const ERR_NFTGALLERY_NOT_EXISTS:u64 = 102; - spec module { pragma verify = false; } @@ -778,10 +767,6 @@ module NFTGallery { } /// Init a NFTGallery to accept NFT for `sender` - public(script) fun accept_entry(sender: signer) { - accept(&sender); - } - public fun accept(sender: &signer) { let sender_addr = Signer::address_of(sender); if (!is_accept(sender_addr)) { @@ -795,13 +780,6 @@ module NFTGallery { } /// Transfer NFT from `sender` to `receiver` - public(script) fun transfer_entry( - sender: signer, - id: u64, receiver: address - ) acquires NFTGallery { - transfer(&sender, id, receiver); - } - public fun transfer( sender: &signer, id: u64, @@ -818,9 +796,6 @@ module NFTGallery { owner: address, id: u64 ): Option> acquires NFTGallery { - if(!is_accept(owner)){ - return Option::none>() - }; let gallery = borrow_global_mut>(owner); let idx = find_by_id(&gallery.items, id); @@ -839,7 +814,6 @@ module NFTGallery { owner: address, idx: u64 ): NFT::NFTInfo acquires NFTGallery { - assert!(exists>(owner), Errors::not_published(ERR_NFTGALLERY_NOT_EXISTS)); let gallery = borrow_global_mut>(owner); let nft = Vector::borrow>(&gallery.items, idx); NFT::get_info(nft) @@ -849,9 +823,6 @@ module NFTGallery { public fun get_nft_infos( owner: address ): vector> acquires NFTGallery { - if(!is_accept(owner)){ - return Vector::empty>() - }; let gallery = borrow_global_mut>(owner); let infos = Vector::empty(); let len = Vector::length(&gallery.items); @@ -879,7 +850,6 @@ module NFTGallery { receiver: address, nft: NFT ) acquires NFTGallery { - assert!(exists>(receiver), Errors::not_published(ERR_NFTGALLERY_NOT_EXISTS)); let gallery = borrow_global_mut>(receiver); Event::emit_event(&mut gallery.deposit_events, DepositEvent { id: NFT::get_id(&nft), owner: receiver }); Vector::push_back(&mut gallery.items, nft); @@ -890,7 +860,6 @@ module NFTGallery { sender: &signer ): NFT acquires NFTGallery { let nft = do_withdraw(sender, Option::none()); - assert!(Option::is_some(&nft), Errors::not_published(ERR_NFT_NOT_EXISTS)); Option::destroy_some(nft) } @@ -908,9 +877,6 @@ module NFTGallery { id: Option ): Option> acquires NFTGallery { let sender_addr = Signer::address_of(sender); - if(!is_accept(sender_addr)){ - return Option::none>() - }; let gallery = borrow_global_mut>(sender_addr); let len = Vector::length(&gallery.items); let nft = if (len == 0) { @@ -962,21 +928,13 @@ module NFTGallery { /// Count all NFTs assigned to an owner public fun count_of(owner: address): u64 acquires NFTGallery { - if(!is_accept(owner)){ - return 0 - }; let gallery = borrow_global_mut>(owner); Vector::length(&gallery.items) } /// Remove empty NFTGallery. - public(script) fun remove_empty_gallery_entry(sender: signer) acquires NFTGallery { - remove_empty_gallery(&sender); - } - public fun remove_empty_gallery(sender: &signer) acquires NFTGallery{ let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::not_published(ERR_NFTGALLERY_NOT_EXISTS)); let NFTGallery {withdraw_events, deposit_events, items} = move_from>(sender_addr); Event::destroy_handle>(withdraw_events); @@ -1005,19 +963,20 @@ module NFTGalleryScripts { /// Init a NFTGallery for accept NFT public(script) fun accept(sender: signer) { - NFTGallery::accept_entry(sender); + NFTGallery::accept(&sender); } + /// Transfer NFT with `id` from `sender` to `receiver` public(script) fun transfer( sender: signer, id: u64, receiver: address ) { - NFTGallery::transfer_entry(sender, id, receiver); + NFTGallery::transfer(&sender, id, receiver); } /// Remove empty NFTGallery. public(script) fun remove_empty_gallery(sender: signer) { - NFTGallery::remove_empty_gallery_entry(sender); + NFTGallery::remove_empty_gallery(&sender); } } } diff --git a/sources/Offer.move b/sources/Offer.move index 40ad8ed1..e33895e7 100644 --- a/sources/Offer.move +++ b/sources/Offer.move @@ -3,27 +3,15 @@ module Offer { use StarcoinFramework::Timestamp; use StarcoinFramework::Signer; use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::Vector; + use StarcoinFramework::Collection2; spec module { - pragma verify = false; + pragma verify = true; pragma aborts_if_is_strict = true; } /// A wrapper around value `offered` that can be claimed by the address stored in `for` when after lock time. - struct Offer has key, store { offered: Offered, for: address, time_lock: u64 } - - struct Offers has key { - offers: vector> - } - - struct OfferInfo has drop, copy, store{ - for: address, - time_lock: u64 - } - - const ERR_DEPRECATED: u64 = 1; + struct Offer has key { offered: Offered, for: address, time_lock: u64 } /// An offer of the specified type for the account does not match const EOFFER_DNE_FOR_ACCOUNT: u64 = 101; @@ -31,32 +19,12 @@ module Offer { /// Offer is not unlocked yet. const EOFFER_NOT_UNLOCKED: u64 = 102; - const EOFFER_OFFERS_ZERO: u64 = 103; - - const EOFFER_OFFERS_ARG_LEN_NOT_SAME: u64 = 104; - - const EOFFER_NOT_HAVE_OFFER: u64 = 105; - - const EOFFER_HAVE_OFFER: u64 = 106; - - const EOFFER_OFFERS_EMPTY: u64 = 107; - /// Publish a value of type `Offered` under the sender's account. The value can be claimed by /// either the `for` address or the transaction sender. - public fun create(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offer, Offers{ + public fun create(account: &signer, offered: Offered, for: address, lock_period: u64) { let time_lock = Timestamp::now_seconds() + lock_period; - let account_address = Signer::address_of(account); - if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - Vector::push_back(offers, Offer { offered, for, time_lock }); - }else { - let offers = Vector::empty>(); - if(exists>(account_address)){ - Vector::push_back(&mut offers, move_from>(account_address)); - }; - Vector::push_back(&mut offers, Offer { offered, for, time_lock }); - move_to(account, Offers { offers }); - } + //TODO should support multi Offer? + move_to(account, Offer { offered, for, time_lock }); } spec create { @@ -65,100 +33,15 @@ module Offer { aborts_if exists>(Signer::address_of(account)); } - public fun create_v2(account: &signer, offered: Offered, for: address, lock_period: u64) acquires Offers, Offer{ - let account_address = Signer::address_of(account); - let time_lock = Timestamp::now_seconds() + lock_period; - - if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - Vector::push_back(offers, Offer { offered, for, time_lock }); - }else { - let offers = Vector::empty>(); - if(exists>(account_address)){ - Vector::push_back(&mut offers, move_from>(account_address)); - }; - Vector::push_back(&mut offers, Offer { offered, for, time_lock }); - move_to(account, Offers { offers }); - }; - } - - spec create_v2 { - pragma verify = false; - } - - public fun create_offers(account: &signer, offereds: vector, for: vector
, lock_periods: vector) acquires Offers, Offer { - let offer_length = Vector::length(&offereds); - assert!(offer_length > 0, Errors::invalid_argument(EOFFER_OFFERS_ZERO)); - assert!(offer_length == Vector::length(&for) && offer_length == Vector::length(&lock_periods), Errors::invalid_argument(EOFFER_OFFERS_ARG_LEN_NOT_SAME)); - let account_address = Signer::address_of(account); - - if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - push(offers, offereds, for, lock_periods); - }else { - let offers = Vector::empty>(); - if(exists>(account_address)){ - Vector::push_back(&mut offers, move_from>(account_address)); - }; - push(&mut offers, offereds, for, lock_periods); - move_to(account, Offers { offers }); - }; - } - - spec create_offers { - pragma verify = false; - } - - fun push(offers: &mut vector>, offereds: vector, for: vector
, lock_periods: vector){ - let now = Timestamp::now_seconds(); - let offer_length = Vector::length(&offereds); - - let i = offer_length - 1; - loop{ - Vector::push_back(offers, Offer { - offered: Vector::remove(&mut offereds, i), - for: Vector::remove(&mut for, i), - time_lock: now + Vector::remove(&mut lock_periods, i) - }); - if(i == 0){ - break - }; - i = i - 1; - }; - Vector::destroy_empty(offereds); - Vector::destroy_empty(for); - Vector::destroy_empty(lock_periods); - } - - spec push { - pragma verify = false; - } - /// Claim the value of type `Offered` published at `offer_address`. /// Only succeeds if the sender is the intended recipient stored in `for` or the original /// publisher `offer_address`, and now >= time_lock /// Also fails if no such value exists. - public fun redeem(account: &signer, offer_address: address): Offered acquires Offer, Offers { - let account_address = Signer::address_of(account); - let Offer { offered, for, time_lock } = if(exists>(offer_address)){ - let op_index = find_offer(offer_address, account_address); - assert!(Option::is_some(&op_index),Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT)); - let offers = &mut borrow_global_mut>(offer_address).offers; - let index = Option::destroy_some(op_index); - let offer = Vector::remove(offers , index); - if(Vector::length(offers) == 0){ - let Offers { offers } = move_from>(offer_address); - Vector::destroy_empty(offers); - }; - offer - }else if(exists>(offer_address)){ - move_from>(offer_address) - }else{ - abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER) - }; - + public fun redeem(account: &signer, offer_address: address): Offered acquires Offer { + let Offer { offered, for, time_lock } = move_from>(offer_address); + let sender = Signer::address_of(account); let now = Timestamp::now_seconds(); - assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT)); + assert!(sender == for || sender == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT)); assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED)); offered } @@ -170,191 +53,32 @@ module Offer { include Timestamp::AbortsIfTimestampNotExists; } - public fun redeem_v2(account: &signer, offer_address: address, idx: u64): Offered acquires Offer, Offers { - let account_address = Signer::address_of(account); - let Offer { offered, for, time_lock } = if(exists>(offer_address)){ - let offers = &mut borrow_global_mut>(offer_address).offers; - assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offer = Vector::remove(offers, idx); - if(Vector::length(offers) == 0){ - let Offers { offers } = move_from>(offer_address); - Vector::destroy_empty(offers); - }; - offer - }else if(exists>(offer_address)){ - move_from>(offer_address) - }else{ - abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER) - }; - - let now = Timestamp::now_seconds(); - assert!(account_address == for || account_address == offer_address, Errors::invalid_argument(EOFFER_DNE_FOR_ACCOUNT)); - assert!(now >= time_lock, Errors::not_published(EOFFER_NOT_UNLOCKED)); - offered - } - - spec redeem_v2 {pragma verify = false;} - /// Returns true if an offer of type `Offered` exists at `offer_address`. public fun exists_at(offer_address: address): bool { - exists>(offer_address) || exists>(offer_address) + exists>(offer_address) } - spec exists_at {pragma verify = false;} - - public fun exists_at_v2(offer_address: address): bool{ - exists>(offer_address) - } - - spec exists_at_v2 {pragma verify = false;} + spec exists_at {aborts_if false;} /// Returns the address of the `Offered` type stored at `offer_address`. /// Fails if no such `Offer` exists. - public fun address_of(offer_address: address): address acquires Offer, Offers { - if(exists>(offer_address)){ - borrow_global>(offer_address).for - }else{ - assert!(!is_offers_empty(offer_address), Errors::invalid_argument(EOFFER_OFFERS_EMPTY)); - address_of_v2(offer_address, get_offers_length(offer_address) - 1) - } - - } - - spec address_of { - aborts_if !exists>(offer_address); - aborts_if !exists>(offer_address); - } - - public fun address_of_v2(offer_address: address, idx: u64): address acquires Offers { - assert!(exists>(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offers = & borrow_global>(offer_address).offers; - assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - Vector::borrow(offers, idx).for - } - - spec address_of_v2 { - pragma verify = false; - } - - public fun retake(account: &signer, idx: u64): Offered acquires Offer, Offers { - let account_address = Signer::address_of(account); - let Offer { offered: offered, for: _, time_lock: time_lock } = if(exists>(account_address)){ - let offers = &mut borrow_global_mut>(account_address).offers; - assert!(Vector::length(offers) - 1 >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offer = Vector::remove(offers, idx); - if(Vector::length(offers) == 0){ - let Offers { offers } = move_from>(account_address); - Vector::destroy_empty(offers); - }; - offer - }else if(exists>(account_address)){ - move_from>(account_address) - }else{ - abort Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER) - }; - let now = Timestamp::now_seconds(); - assert!(now >= time_lock + ( 3600 * 24 * 30 * 3 ), Errors::not_published(EOFFER_NOT_UNLOCKED)); - offered - } - - spec retake { - pragma verify = false; - } - - public fun get_offers_infos(offer_address: address): Option::Option> acquires Offers{ - if(!exists_at_v2(offer_address)){ - return Option::none>() - }; - let offers = & borrow_global>(offer_address).offers; - let offer_infos = Vector::empty(); - let i = 0; - let length = Vector::length(offers); - while(i < length){ - Vector::push_back(&mut offer_infos, OfferInfo { for: Vector::borrow(offers, i).for, time_lock: Vector::borrow(offers, i).time_lock }); - i = i + 1; - }; - Option::some(offer_infos) - } - - spec get_offers_infos { - pragma verify = false; - } - - public fun get_offers_info(offer_address: address, idx: u64): Option::Option acquires Offers{ - if(!exists_at_v2(offer_address)){ - return Option::none() - }; - let offers = & borrow_global>(offer_address).offers; - assert!(Vector::length(offers) >= idx, Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - Option::some(OfferInfo { for: Vector::borrow(offers, idx).for, time_lock: Vector::borrow(offers, idx).time_lock }) - } - - spec get_offers_info { - pragma verify = false; - } - - public fun unpack_offer_info(offer_info: OfferInfo):(address, u64){ - let OfferInfo{ for, time_lock } = offer_info; - ( for, time_lock ) - } - - spec unpack_offer_info { - pragma verify = false; - } - - public fun get_offers_length(offer_address: address): u64 acquires Offers{ - assert!(exists_at_v2(offer_address), Errors::invalid_argument(EOFFER_NOT_HAVE_OFFER)); - let offers = & borrow_global>(offer_address).offers; - Vector::length(offers) - } - - spec get_offers_length { - pragma verify = false; - } - - public fun is_offers_empty(offer_address: address): bool acquires Offers{ - if( get_offers_length(offer_address) == 0){ - true - }else{ - false - } - } - - spec is_offers_empty { - pragma verify = false; + public fun address_of(offer_address: address): address acquires Offer { + borrow_global>(offer_address).for } + spec address_of {aborts_if !exists>(offer_address);} /// Take Offer and put to signer's Collection. - public(script) fun take_offer(_signer: signer, _offer_address: address){ - abort Errors::invalid_state(ERR_DEPRECATED) + public(script) fun take_offer( + signer: signer, + offer_address: address, + ) acquires Offer { + let offered = redeem(&signer, offer_address); + Collection2::put(&signer, Signer::address_of(&signer), offered); } spec take_offer { pragma verify = false; } - - - - public fun find_offer(offer_address: address, for: address):Option::Option acquires Offers { - if(!exists_at_v2(offer_address)){ - return Option::none() - }; - let offers = & borrow_global>(offer_address).offers; - let length = Vector::length(offers); - let i = 0; - while(i < length){ - let offer = Vector::borrow(offers, i); - if( offer.for == for ){ - return Option::some(i) - }; - i = i + 1; - }; - Option::none() - } - - spec find_offer { - pragma verify = false; - } } } \ No newline at end of file diff --git a/sources/OnChainConfigDao.move b/sources/OnChainConfigDao.move index e6e1c96c..a92e9889 100644 --- a/sources/OnChainConfigDao.move +++ b/sources/OnChainConfigDao.move @@ -6,9 +6,6 @@ module OnChainConfigDao { use StarcoinFramework::Config; use StarcoinFramework::Dao; use StarcoinFramework::Errors; - use StarcoinFramework::CoreAddresses; - - friend StarcoinFramework::StdlibUpgradeScripts; spec module { pragma verify = false; // break after enabling v2 compilation scheme @@ -96,11 +93,5 @@ module OnChainConfigDao { include Dao::CheckProposalStates>{expected_states}; aborts_if !exists>(Token::SPEC_TOKEN_TEST_ADDRESS()); } - - //StarcoinDAO init need Config Cap - public (friend) fun config_cap():Config::ModifyConfigCapabilityacquires WrappedConfigModifyCapability{ - let WrappedConfigModifyCapability {cap} = move_from>(CoreAddresses::GENESIS_ADDRESS()); - cap - } } } \ No newline at end of file diff --git a/sources/OnChainStarcoinDAOConfig.move b/sources/OnChainStarcoinDAOConfig.move deleted file mode 100644 index a18df76b..00000000 --- a/sources/OnChainStarcoinDAOConfig.move +++ /dev/null @@ -1,232 +0,0 @@ -module StarcoinFramework::OnChainStarcoinDAOConfig { - use StarcoinFramework::ConsensusConfig; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::TransactionPublishOption; - use StarcoinFramework::TransactionTimeoutConfig; - use StarcoinFramework::VMConfig; - use StarcoinFramework::LanguageVersion; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::ConfigProposalPlugin; - - public fun propose_update_consensus_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - uncle_rate_target: u64, - base_block_time_target: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - epoch_block_count: u64, - base_block_difficulty_window: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - exec_delay: u64) { - let consensus_config = ConsensusConfig::new_consensus_config(uncle_rate_target, - base_block_time_target, - base_reward_per_block, - base_reward_per_uncle_percent, - epoch_block_count, - base_block_difficulty_window, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, consensus_config); - } - - public ( script ) fun propose_update_consensus_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - uncle_rate_target: u64, - base_block_time_target: u64, - base_reward_per_block: u128, - base_reward_per_uncle_percent: u64, - epoch_block_count: u64, - base_block_difficulty_window: u64, - min_block_time_target: u64, - max_block_time_target: u64, - base_max_uncles_per_block: u64, - base_block_gas_limit: u64, - strategy: u8, - exec_delay: u64) { - propose_update_consensus_config(&account, - title, - introduction, - description, - uncle_rate_target, - base_block_time_target, - base_reward_per_block, - base_reward_per_uncle_percent, - epoch_block_count, - base_block_difficulty_window, - min_block_time_target, - max_block_time_target, - base_max_uncles_per_block, - base_block_gas_limit, - strategy, - exec_delay); - } - - spec propose_update_consensus_config { - pragma verify = false; - } - - public fun propose_update_reward_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - reward_delay: u64, - exec_delay: u64) { - let reward_config = RewardConfig::new_reward_config(reward_delay); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, reward_config); - } - - public ( script ) fun propose_update_reward_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - reward_delay: u64, - exec_delay: u64) { - propose_update_reward_config(&account, title, introduction, description, reward_delay, exec_delay); - } - spec propose_update_reward_config { - pragma verify = false; - } - - public fun propose_update_txn_publish_option(account: &signer, - title:vector, - introduction:vector, - description: vector, - script_allowed: bool, - module_publishing_allowed: bool, - exec_delay: u64) { - let txn_publish_option = TransactionPublishOption::new_transaction_publish_option(script_allowed, module_publishing_allowed); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, txn_publish_option); - } - - public ( script ) fun propose_update_txn_publish_option_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - script_allowed: bool, - module_publishing_allowed: bool, - exec_delay: u64) { - propose_update_txn_publish_option(&account, title, introduction, description, script_allowed, module_publishing_allowed, exec_delay); - } - spec propose_update_txn_publish_option { - pragma verify = false; - } - - public fun propose_update_txn_timeout_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - duration_seconds: u64, - exec_delay: u64) { - let txn_timeout_config = TransactionTimeoutConfig::new_transaction_timeout_config(duration_seconds); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, txn_timeout_config); - } - - public ( script ) fun propose_update_txn_timeout_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - duration_seconds: u64, - exec_delay: u64) { - propose_update_txn_timeout_config(&account, title, introduction,description,duration_seconds,exec_delay); - } - - spec propose_update_txn_timeout_config { - pragma verify = false; - } - - public fun propose_update_vm_config(account: &signer, - title:vector, - introduction:vector, - description: vector, - instruction_schedule: vector, - native_schedule: vector, - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - exec_delay: u64, ) { - let vm_config = VMConfig::new_vm_config(instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, vm_config); - } - - public (script) fun propose_update_vm_config_entry(account: signer, - title:vector, - introduction:vector, - description: vector, - instruction_schedule: vector, - native_schedule: vector, - global_memory_per_byte_cost: u64, - global_memory_per_byte_write_cost: u64, - min_transaction_gas_units: u64, - large_transaction_cutoff: u64, - instrinsic_gas_per_byte: u64, - maximum_number_of_gas_units: u64, - min_price_per_gas_unit: u64, - max_price_per_gas_unit: u64, - max_transaction_size_in_bytes: u64, - gas_unit_scaling_factor: u64, - default_account_size: u64, - exec_delay: u64, ) { - propose_update_vm_config(&account, - title, - introduction, - description, - instruction_schedule, - native_schedule, - global_memory_per_byte_cost, - global_memory_per_byte_write_cost, - min_transaction_gas_units, - large_transaction_cutoff, - instrinsic_gas_per_byte, - maximum_number_of_gas_units, - min_price_per_gas_unit, - max_price_per_gas_unit, - max_transaction_size_in_bytes, - gas_unit_scaling_factor, - default_account_size, - exec_delay) ; - } - - spec propose_update_vm_config { - pragma verify = false; - } - - public fun propose_update_move_language_version(account: &signer, title:vector, introduction:vector, description: vector, new_version: u64, exec_delay: u64) { - let lang_version = LanguageVersion::new(new_version); - ConfigProposalPlugin::create_proposal(account, title, introduction, description, exec_delay, lang_version); - } - - public(script) fun propose_update_move_language_version_entry(account: signer, title:vector, introduction:vector, description: vector, new_version: u64, exec_delay: u64) { - propose_update_move_language_version(&account, title, introduction, description, new_version, exec_delay); - } -} \ No newline at end of file diff --git a/sources/Oracle.move b/sources/Oracle.move index 44e5db5e..0964f6cf 100644 --- a/sources/Oracle.move +++ b/sources/Oracle.move @@ -56,7 +56,7 @@ module Oracle { const ERR_NO_UPDATE_CAPABILITY: u64 = 102; const ERR_NO_DATA_SOURCE: u64 = 103; const ERR_CAPABILITY_ACCOUNT_MISS_MATCH: u64 = 104; - const ERR_NO_ORACLE_FEED:u64 =105; + /// deprecated. public fun initialize(_sender: &signer) { } @@ -143,14 +143,12 @@ module Oracle { /// Read the Oracle's value from `ds_addr` public fun read(ds_addr: address): ValueT acquires OracleFeed{ - assert!(exists>(ds_addr), Errors::invalid_state(ERR_NO_ORACLE_FEED)); let oracle_feed = borrow_global>(ds_addr); *&oracle_feed.record.value } /// Read the Oracle's DataRecord from `ds_addr` public fun read_record(ds_addr: address): DataRecord acquires OracleFeed{ - assert!(exists>(ds_addr), Errors::invalid_state(ERR_NO_ORACLE_FEED)); let oracle_feed = borrow_global>(ds_addr); *&oracle_feed.record } @@ -187,105 +185,54 @@ module Oracle { (record.version,*&record.value,record.updated_at) } } -module PriceOracle { +module PriceOracle{ use StarcoinFramework::Math; use StarcoinFramework::Oracle::{Self, DataRecord, UpdateCapability}; - struct PriceOracleInfo has copy, store, drop { + struct PriceOracleInfo has copy,store,drop{ scaling_factor: u128, } - public(script) fun register_oracle_entry(sender: signer, precision: u8){ - register_oracle(&sender, precision); - } - public fun register_oracle(sender: &signer, precision: u8){ let scaling_factor = Math::pow(10, (precision as u64)); Oracle::register_oracle(sender, PriceOracleInfo{ scaling_factor, }); } - public(script) fun init_data_source_entry(sender: signer, init_value: u128){ - init_data_source(&sender, init_value); - } public fun init_data_source(sender: &signer, init_value: u128){ Oracle::init_data_source(sender, init_value); } - public fun is_data_source_initialized(ds_addr: address): bool { + public fun is_data_source_initialized(ds_addr: address): bool{ Oracle::is_data_source_initialized(ds_addr) } - public fun get_scaling_factor(): u128 { + public fun get_scaling_factor() : u128 { let info = Oracle::get_oracle_info(); info.scaling_factor } - public(script) fun update_entry(sender: signer, value: u128){ - update(&sender, value); - } public fun update(sender: &signer, value: u128){ Oracle::update(sender, value); } - public fun update_with_cap(cap: &mut UpdateCapability, value: u128) { + public fun update_with_cap(cap: &mut UpdateCapability, value: u128) { Oracle::update_with_cap(cap, value); } - public fun read(addr: address): u128 { + public fun read(addr: address) : u128{ Oracle::read(addr) } - public fun read_record(addr: address): DataRecord { + public fun read_record(addr: address): DataRecord{ Oracle::read_record(addr) } - public fun read_records(addrs: &vector
): vector> { + public fun read_records(addrs: &vector
): vector>{ Oracle::read_records(addrs) } - public fun remove_update_capability(sender: &signer): UpdateCapability { - Oracle::remove_update_capability(sender) - } - - public fun add_update_capability(sender: &signer, update_cap: UpdateCapability) { - Oracle::add_update_capability(sender, update_cap) - } -} - -module GasOracle { - use StarcoinFramework::PriceOracle; - - struct STCToken has copy, store, drop { - } - - public fun register(sender: &signer, precision: u8){ - PriceOracle::register_oracle>(sender, precision); - } - public(script) fun register_entry(sender: signer, precision: u8){ - register(&sender, precision); - } - - public fun init_data_source(sender: &signer, init_value: u128){ - PriceOracle::init_data_source>(sender, init_value); - } - - public(script) fun init_data_source_entry(sender: signer, init_value: u128){ - init_data_source(&sender, init_value); - } - - public fun update(sender: &signer, value: u128){ - PriceOracle::update>(sender, value); - } - - public(script) fun update_entry(sender: signer, value: u128){ - update(&sender, value); - } - - public fun get_scaling_factor(): u128 { - PriceOracle::get_scaling_factor>() - } } module STCUSDOracle{ @@ -316,15 +263,15 @@ module PriceOracleScripts{ use StarcoinFramework::PriceOracle; public(script) fun register_oracle(sender: signer, precision: u8){ - PriceOracle::register_oracle_entry(sender, precision); + PriceOracle::register_oracle(&sender, precision) } public(script) fun init_data_source(sender: signer, init_value: u128){ - PriceOracle::init_data_source_entry(sender, init_value); + PriceOracle::init_data_source(&sender, init_value); } public(script) fun update(sender: signer, value: u128){ - PriceOracle::update_entry(sender, value); + PriceOracle::update(&sender, value); } } diff --git a/sources/PackageTxnManager.move b/sources/PackageTxnManager.move index e0036d40..7cfd2ce4 100644 --- a/sources/PackageTxnManager.move +++ b/sources/PackageTxnManager.move @@ -86,7 +86,7 @@ address StarcoinFramework { config: TwoPhaseUpgradeConfig, plan: Option, version_cap: Config::ModifyConfigCapability, - upgrade_event: Event::EventHandle, + upgrade_event: Event::EventHandle, } /// module upgrade event. @@ -96,19 +96,8 @@ address StarcoinFramework { version: u64, } - struct UpgradePlanEventHolder has key { - upgrade_plan_event: Event::EventHandle - } - - /// module upgrade plan event when submitting a module upgrade plan - struct UpgradePlanEvent has drop, store { - package_address: address, - plan: UpgradePlanV2, - } - /// Update account's ModuleUpgradeStrategy - public fun update_module_upgrade_strategy(account: &signer, strategy: u8, min_time: Option) - acquires ModuleUpgradeStrategy, TwoPhaseUpgrade, TwoPhaseUpgradeV2, UpgradePlanCapability, UpgradePlanEventHolder{ + public fun update_module_upgrade_strategy(account: &signer, strategy: u8, min_time: Option) acquires ModuleUpgradeStrategy, TwoPhaseUpgrade, TwoPhaseUpgradeV2, UpgradePlanCapability{ assert!(strategy == STRATEGY_ARBITRARY || strategy == STRATEGY_TWO_PHASE || strategy == STRATEGY_NEW_MODULE || strategy == STRATEGY_FREEZE, Errors::invalid_argument(EUNKNOWN_STRATEGY)); let account_address = Signer::address_of(account); let previous_strategy = get_module_upgrade_strategy(account_address); @@ -121,16 +110,13 @@ address StarcoinFramework { if (strategy == STRATEGY_TWO_PHASE){ let version_cap = Config::extract_modify_config_capability(account); let min_time_limit = Option::get_with_default(&min_time, DEFAULT_MIN_TIME_LIMIT); - move_to(account, UpgradePlanCapability{ account_address}); - move_to(account, TwoPhaseUpgradeV2 { - config: TwoPhaseUpgradeConfig { min_time_limit }, + move_to(account, UpgradePlanCapability{ account_address: account_address}); + move_to(account, TwoPhaseUpgradeV2{ + config: TwoPhaseUpgradeConfig{min_time_limit: min_time_limit}, plan: Option::none(), - version_cap, - upgrade_event: Event::new_event_handle(account) - }); - move_to(account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(account) - }); + version_cap: version_cap, + upgrade_event: Event::new_event_handle(account)} + ); }; //clean two phase upgrade resource if (previous_strategy == STRATEGY_TWO_PHASE){ @@ -142,12 +128,8 @@ address StarcoinFramework { }; if (exists(account_address)) { let tpu = move_from(account_address); - let TwoPhaseUpgradeV2{config: _, plan: _, version_cap, upgrade_event } = tpu; - Event::destroy_handle(upgrade_event); - if (exists(account_address)) { - let UpgradePlanEventHolder{ upgrade_plan_event } = move_from(account_address); - Event::destroy_handle(upgrade_plan_event); - }; + let TwoPhaseUpgradeV2{plan:_, version_cap, upgrade_event, config: _} = tpu; + Event::destroy_handle(upgrade_event); Config::destroy_modify_config_capability(version_cap); }; // UpgradePlanCapability may be extracted @@ -210,27 +192,21 @@ address StarcoinFramework { if (Option::is_some(&plan)) { let old_plan = Option::borrow(&plan); move_to(&account, TwoPhaseUpgradeV2{ - config, + config: config, plan: Option::some(UpgradePlanV2 { package_hash: *&old_plan.package_hash, active_after_time: old_plan.active_after_time, version: old_plan.version, enforced: false }), - version_cap, - upgrade_event - }); - move_to(&account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(&account) + version_cap: version_cap, + upgrade_event: upgrade_event }); } else { - move_to(&account, TwoPhaseUpgradeV2 { - config, + move_to(&account, TwoPhaseUpgradeV2{ + config: config, plan: Option::none(), - version_cap, - upgrade_event - }); - move_to(&account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(&account) + version_cap: version_cap, + upgrade_event: upgrade_event }); }; } @@ -239,16 +215,9 @@ address StarcoinFramework { pragma verify = false; } - public fun submit_upgrade_plan_v2(account: &signer, package_hash: vector, version:u64, enforced: bool) - acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy,UpgradePlanEventHolder{ + public fun submit_upgrade_plan_v2(account: &signer, package_hash: vector, version:u64, enforced: bool) acquires TwoPhaseUpgradeV2,UpgradePlanCapability,ModuleUpgradeStrategy{ let account_address = Signer::address_of(account); let cap = borrow_global(account_address); - assert!(get_module_upgrade_strategy(cap.account_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE)); - if (!exists(account_address)) { - move_to(account, UpgradePlanEventHolder { - upgrade_plan_event: Event::new_event_handle(account) - }) - }; submit_upgrade_plan_with_cap_v2(cap, package_hash, version, enforced); } @@ -258,27 +227,12 @@ address StarcoinFramework { include SubmitUpgradePlanWithCapAbortsIf{account: global(Signer::address_of(account)).account_address}; ensures Option::is_some(global(global(Signer::address_of(account)).account_address).plan); } - public fun submit_upgrade_plan_with_cap_v2(cap: &UpgradePlanCapability, package_hash: vector, version: u64, enforced: bool) - acquires TwoPhaseUpgradeV2, ModuleUpgradeStrategy, UpgradePlanEventHolder{ + public fun submit_upgrade_plan_with_cap_v2(cap: &UpgradePlanCapability, package_hash: vector, version: u64, enforced: bool) acquires TwoPhaseUpgradeV2,ModuleUpgradeStrategy{ let package_address = cap.account_address; assert!(get_module_upgrade_strategy(package_address) == STRATEGY_TWO_PHASE, Errors::invalid_argument(ESTRATEGY_NOT_TWO_PHASE)); - let tpu = borrow_global_mut(package_address); let active_after_time = Timestamp::now_milliseconds() + tpu.config.min_time_limit; - let plan = UpgradePlanV2 { package_hash, active_after_time, version, enforced }; - tpu.plan = Option::some(copy plan); - - // TODO - // if UpgradePlanCapability was delegated to DAO or contract, - // it's hard to upgrade the address to claim an UpgradePlanEventHolder. - // Try to fix this! - if (exists(package_address)) { - let event_holder = borrow_global_mut(package_address); - Event::emit_event(&mut event_holder.upgrade_plan_event, UpgradePlanEvent { - package_address, - plan - }); - } + tpu.plan = Option::some(UpgradePlanV2 { package_hash, active_after_time, version, enforced }); } spec submit_upgrade_plan_with_cap_v2 { pragma verify = false; @@ -451,7 +405,7 @@ address StarcoinFramework { let plan = Option::borrow(&tpu.plan); Config::set_with_capability(&mut tpu.version_cap, Version::new_version(plan.version)); Event::emit_event(&mut tpu.upgrade_event, UpgradeEvent { - package_address, + package_address: package_address, package_hash: *&plan.package_hash, version: plan.version}); }; @@ -511,12 +465,5 @@ address StarcoinFramework { && !exists>(global(package_address).version_cap.account_address); } - public fun exists_upgrade_plan_cap(addr :address):bool{ - exists(addr) - } - - spec exists_upgrade_plan_cap { - aborts_if false; - } } } \ No newline at end of file diff --git a/sources/Ring.move b/sources/Ring.move deleted file mode 100644 index 4ec1d26f..00000000 --- a/sources/Ring.move +++ /dev/null @@ -1,154 +0,0 @@ -address StarcoinFramework { - -/// A ring-shaped container that can hold any type, indexed from 0 -/// The capacity is fixed at creation time, and the accessible index is constantly growing -module Ring { - - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::Errors; - - - /// The index into the vector is out of bounds - const ERROR_RING_INDEX_OUT_OF_BOUNDS:u64 = 101; - - struct Ring has store{ - data : vector>, - insertion_index : u64, - external_index : u64 - } - - /// Create a Ring with capacity. - public fun create_with_capacity( len: u64 ):Ring{ - let data = Vector::empty>(); - let i = 0; - while(i < len){ - Vector::push_back(&mut data , Option::none()); - i = i + 1; - }; - Ring { - data : data, - insertion_index : 0, - external_index : 0, - } - } - - spec create_with_capacity{ - pragma verify = false; - } - - ///is Ring full - public fun is_full(r: &Ring):bool{ - Option::is_some(Vector::borrow(&r.data, r.insertion_index)) - } - - spec is_full{ - pragma verify = false; - } - - ///Return the capacity of the Ring. - public fun capacity(r: &Ring): u64{ - Vector::length( &r.data ) - } - - spec capacity{ - pragma verify = false; - } - - /// Add element `e` to the insertion_index of the Ring `r`. - public fun push (r: &mut Ring , e: Element):Option::Option{ - let op_e = Vector::borrow_mut>(&mut r.data, r.insertion_index); - let res = if( Option::is_none(op_e) ){ - Option::fill( op_e, e); - Option::none() - }else{ - Option::some( Option::swap( op_e, e) ) - }; - r.insertion_index = ( r.insertion_index + 1 ) % Vector::length(&r.data); - r.external_index = r.external_index + 1; - res - } - - spec push{ - pragma verify = false; - } - - /// Return a reference to the `i`th element in the Ring `r`. - public fun borrow(r:& Ring, i: u64):&Option::Option{ - let len = capacity(r); - if( r.external_index > len - 1) { - assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow(&r.data, i % len) - }else { - assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow(&r.data, i ) - } - } - - spec borrow{ - pragma verify = false; - } - - /// Return a mutable reference to the `i`th element in the Ring `r`. - public fun borrow_mut(r: &mut Ring, i: u64):&mut Option::Option{ - let len = capacity(r); - if( r.external_index > len - 1) { - assert!( i >= r.external_index - len && i < r.external_index , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow_mut(&mut r.data, i % len) - }else { - assert!( i < len , Errors::invalid_argument(ERROR_RING_INDEX_OUT_OF_BOUNDS)); - Vector::borrow_mut(&mut r.data, i ) - } - - } - - spec borrow_mut{ - pragma verify = false; - } - - - /// Return `Option::Option` if `e` is in the Ring `r` at index `i`. - /// Otherwise, returns `Option::none`. - public fun index_of(r: &Ring, e: &Element):Option::Option{ - let i = 0; - let len = capacity(r); - while ( i < len ) { - if ( Option::borrow(Vector::borrow( &r.data, i )) == e) return Option::some(i + r.external_index - len); - i = i + 1; - }; - Option::none() - } - - spec index_of{ - pragma verify = false; - } - - /// Destroy the Ring `r`. - /// Returns the vector saved by ring - public fun destroy(r: Ring):vector{ - let Ring { - data : data , - insertion_index : _, - external_index : _, - } = r ; - let len = Vector::length(&data); - let i = 0; - let vec = Vector::empty(); - while ( i < len ) { - let op_e = Vector::pop_back( &mut data ); - if ( Option::is_some(&op_e) ) { - Vector::push_back(&mut vec, Option::destroy_some(op_e)) - }else { - Option::destroy_none(op_e) - }; - i = i + 1; - }; - Vector::destroy_empty(data); - vec - } - - spec destroy{ - pragma verify = false; - } -} -} \ No newline at end of file diff --git a/sources/STC.move b/sources/STC.move index 5307041f..92fc837d 100644 --- a/sources/STC.move +++ b/sources/STC.move @@ -1,10 +1,20 @@ +address StarcoinFramework { /// STC is the token of Starcoin blockchain. /// It uses apis defined in the `Token` module. -module StarcoinFramework::STC { +module STC { use StarcoinFramework::Token::{Self, Token}; + use StarcoinFramework::Dao; + use StarcoinFramework::ModifyDaoConfigProposal; + use StarcoinFramework::UpgradeModuleDaoProposal; + use StarcoinFramework::PackageTxnManager; + use StarcoinFramework::OnChainConfigDao; + use StarcoinFramework::TransactionPublishOption; + use StarcoinFramework::VMConfig; + use StarcoinFramework::ConsensusConfig; + use StarcoinFramework::RewardConfig; + use StarcoinFramework::TransactionTimeoutConfig; use StarcoinFramework::Treasury; use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; spec module { pragma verify = false; @@ -12,7 +22,7 @@ module StarcoinFramework::STC { } /// STC token marker. - struct STC has copy, drop, store {} + struct STC has copy, drop, store { } /// precision of STC token. const PRECISION: u8 = 9; @@ -24,24 +34,45 @@ module StarcoinFramework::STC { /// STC initialization. public fun initialize( - _account: &signer, - _voting_delay: u64, - _voting_period: u64, - _voting_quorum_rate: u8, - _min_action_delay: u64, + account: &signer, + voting_delay: u64, + voting_period: u64, + voting_quorum_rate: u8, + min_action_delay: u64, ) { - abort Errors::deprecated(1) + Token::register_token(account, PRECISION); + let burn_cap = Token::remove_burn_capability(account); + move_to(account, SharedBurnCapability { cap: burn_cap }); + Dao::plugin( + account, + voting_delay, + voting_period, + voting_quorum_rate, + min_action_delay, + ); + ModifyDaoConfigProposal::plugin(account); + let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(account); + UpgradeModuleDaoProposal::plugin( + account, + upgrade_plan_cap, + ); + // the following configurations are gov-ed by Dao. + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); } spec initialize { - pragma verify = false; + include Token::RegisterTokenAbortsIf{precision: PRECISION}; } - public fun upgrade_from_v1_to_v2(account: &signer, total_amount: u128, ): Treasury::WithdrawCapability { + public fun upgrade_from_v1_to_v2(account: &signer,total_amount: u128,): Treasury::WithdrawCapability { CoreAddresses::assert_genesis_address(account); // Mint all stc, and destroy mint capability - let total_stc = Token::mint(account, total_amount - Token::market_cap()); + let total_stc = Token::mint(account, total_amount-Token::market_cap()); let withdraw_cap = Treasury::initialize(account, total_stc); let mint_cap = Token::remove_mint_capability(account); Token::destroy_mint_capability(mint_cap); @@ -52,27 +83,14 @@ module StarcoinFramework::STC { pragma verify = false; } - /// STC initialization. public fun initialize_v2( - _account: &signer, - _total_amount: u128, - _voting_delay: u64, - _voting_period: u64, - _voting_quorum_rate: u8, - _min_action_delay: u64, - ): Treasury::WithdrawCapability { - abort Errors::deprecated(1) - } - - spec initialize_v2 { - pragma verify = false; - } - - /// STC initialization. - public fun initialize_v3( account: &signer, total_amount: u128, + voting_delay: u64, + voting_period: u64, + voting_quorum_rate: u8, + min_action_delay: u64, ): Treasury::WithdrawCapability { Token::register_token(account, PRECISION); @@ -85,11 +103,30 @@ module StarcoinFramework::STC { let burn_cap = Token::remove_burn_capability(account); move_to(account, SharedBurnCapability { cap: burn_cap }); + Dao::plugin( + account, + voting_delay, + voting_period, + voting_quorum_rate, + min_action_delay, + ); + ModifyDaoConfigProposal::plugin(account); + let upgrade_plan_cap = PackageTxnManager::extract_submit_upgrade_plan_cap(account); + UpgradeModuleDaoProposal::plugin( + account, + upgrade_plan_cap, + ); + // the following configurations are gov-ed by Dao. + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); + OnChainConfigDao::plugin(account); withdraw_cap } - spec initialize_v3 { - include Token::RegisterTokenAbortsIf { precision: PRECISION }; + spec initialize_v2 { + include Token::RegisterTokenAbortsIf{precision: PRECISION}; } /// Returns true if `TokenType` is `STC::STC` @@ -97,7 +134,8 @@ module StarcoinFramework::STC { Token::is_same_token() } - spec is_stc {} + spec is_stc { + } /// Burn STC tokens. /// It can be called by anyone. @@ -116,5 +154,7 @@ module StarcoinFramework::STC { Token::token_address() } - spec token_address {} + spec token_address { + } +} } \ No newline at end of file diff --git a/sources/Signature.move b/sources/Signature.move index 044636e4..1cba7ad7 100644 --- a/sources/Signature.move +++ b/sources/Signature.move @@ -23,24 +23,9 @@ module Signature { } } - // verify eth secp256k1 sign and compare addr, if add equal return true - public fun secp256k1_verify(signature: vector, addr: vector, message: vector) : bool{ - let receover_address_opt:Option = ecrecover(message, signature); - let expect_address = EVMAddress::new(addr); - &Option::destroy_some(receover_address_opt) == &expect_address - } - spec module { pragma intrinsic = true; } - - #[test] - fun test_ecrecover_invalid(){ - let h = b"00"; - let s = b"00"; - let addr = ecrecover(h, s); - assert!(Option::is_none(&addr), 1001); - } } module EVMAddress{ @@ -67,7 +52,6 @@ module EVMAddress{ let i = 0; while (i < EVM_ADDR_LENGTH) { Vector::push_back(&mut new_bytes, *Vector::borrow(&bytes, i)); - i = i + 1; }; new_bytes }else if (len == EVM_ADDR_LENGTH){ @@ -78,7 +62,6 @@ module EVMAddress{ while (i < EVM_ADDR_LENGTH - len) { // pad zero to address Vector::push_back(&mut new_bytes, 0); - i = i + 1; }; Vector::append(&mut new_bytes, bytes); new_bytes @@ -113,19 +96,5 @@ module EVMAddress{ pragma verify = false; //TODO } - - #[test] - fun test_evm_address_padding(){ - let addr1 = new(x"00"); - let addr2 = new(x"0000"); - assert!(&addr1.bytes == &addr2.bytes, 1001); - } - - #[test] - fun test_evm_address_crop(){ - let addr1 = new(x"01234567890123456789012345678901234567891111"); - let addr2 = new(x"01234567890123456789012345678901234567892222"); - assert!(&addr1.bytes == &addr2.bytes, 1001); - } } } diff --git a/sources/SignedInteger64.move b/sources/SignedInteger64.move index 5258cc78..b61c83ba 100644 --- a/sources/SignedInteger64.move +++ b/sources/SignedInteger64.move @@ -16,44 +16,43 @@ module SignedInteger64 { /// Multiply a u64 integer by a signed integer number. public fun multiply_u64(num: u64, multiplier: SignedInteger64): SignedInteger64 { let product = multiplier.value * num; - SignedInteger64 { value: product, is_negative: multiplier.is_negative } + SignedInteger64 { value: (product as u64), is_negative: multiplier.is_negative } } /// Divide a u64 integer by a signed integer number. public fun divide_u64(num: u64, divisor: SignedInteger64): SignedInteger64 { let quotient = num / divisor.value; - SignedInteger64 { value: quotient, is_negative: divisor.is_negative } + SignedInteger64 { value: (quotient as u64), is_negative: divisor.is_negative } } /// Sub: `num - minus` public fun sub_u64(num: u64, minus: SignedInteger64): SignedInteger64 { if (minus.is_negative) { let result = num + minus.value; - SignedInteger64 { value: result, is_negative: false } + SignedInteger64 { value: (result as u64), is_negative: false } } else { - if (num >= minus.value) { + if (num > minus.value) { let result = num - minus.value; - SignedInteger64 { value: result, is_negative: false } + SignedInteger64 { value: (result as u64), is_negative: false } }else { let result = minus.value - num; - SignedInteger64 { value: result, is_negative: true } + SignedInteger64 { value: (result as u64), is_negative: true } } } } - /// Add: `num + addend` public fun add_u64(num: u64, addend: SignedInteger64): SignedInteger64 { if (addend.is_negative) { - if (num >= addend.value) { - let result = num - addend.value; - SignedInteger64 { value: result, is_negative: false } - }else { - let result = addend.value - num; - SignedInteger64 { value: result, is_negative: true } - } + if (num > addend.value) { + let result = num - addend.value; + SignedInteger64 { value: (result as u64), is_negative: false } + }else { + let result = addend.value - num; + SignedInteger64 { value: (result as u64), is_negative: true } + } } else { - let result = num + addend.value; - SignedInteger64 { value: result, is_negative: false } + let result = num + addend.value; + SignedInteger64 { value: (result as u64), is_negative: false } } } @@ -74,8 +73,10 @@ module SignedInteger64 { // **************** SPECIFICATIONS **************** + + spec multiply_u64 { - aborts_if multiplier.value * num > max_u64(); + aborts_if multiplier.value * num > max_u64(); } spec divide_u64 { @@ -87,7 +88,7 @@ module SignedInteger64 { } spec add_u64 { - aborts_if !addend.is_negative && num + addend.value > max_u64(); + aborts_if !addend.is_negative && num + addend.value > max_u64(); } spec create_from_raw_value { @@ -104,6 +105,6 @@ module SignedInteger64 { aborts_if false; ensures result == num.is_negative; } - } + } diff --git a/sources/SimpleMap.move b/sources/SimpleMap.move deleted file mode 100644 index 8a8df0c1..00000000 --- a/sources/SimpleMap.move +++ /dev/null @@ -1,229 +0,0 @@ -/// This module provides a solution for sorted maps, that is it has the properties that -/// 1) Keys point to Values -/// 2) Each Key must be unique -/// 3) A Key can be found within O(Log N) time -/// 4) The data is stored as sorted by Key -/// 5) Adds and removals take O(N) time -module StarcoinFramework::SimpleMap { - - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::Vector; - use StarcoinFramework::Compare; - use StarcoinFramework::BCS; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Map key already exists - const EKEY_ALREADY_EXISTS: u64 = 1; - /// Map key is not found - const EKEY_NOT_FOUND: u64 = 2; - - struct SimpleMap has copy, drop, store { - data: vector>, - } - - struct Element has copy, drop, store { - key: Key, - value: Value, - } - - public fun length(map: &SimpleMap): u64 { - Vector::length(&map.data) - } - - public fun create(): SimpleMap { - SimpleMap { - data: Vector::empty(), - } - } - - public fun borrow( - map: &SimpleMap, - key: &Key, - ): &Value { - let (maybe_idx, _) = find(map, key); - assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND)); - let idx = Option::extract(&mut maybe_idx); - &Vector::borrow(&map.data, idx).value - } - - public fun borrow_mut( - map: &mut SimpleMap, - key: &Key, - ): &mut Value { - let (maybe_idx, _) = find(map, key); - assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND)); - let idx = Option::extract(&mut maybe_idx); - &mut Vector::borrow_mut(&mut map.data, idx).value - } - - public fun contains_key( - map: &SimpleMap, - key: &Key, - ): bool { - let (maybe_idx, _) = find(map, key); - Option::is_some(&maybe_idx) - } - - public fun destroy_empty(map: SimpleMap) { - let SimpleMap { data } = map; - Vector::destroy_empty(data); - } - - public fun add( - map: &mut SimpleMap, - key: Key, - value: Value, - ) { - let (maybe_idx, maybe_placement) = find(map, &key); - assert!(Option::is_none(&maybe_idx), Errors::invalid_argument(EKEY_ALREADY_EXISTS)); - - // Append to the end and then swap elements until the list is ordered again - Vector::push_back(&mut map.data, Element { key, value }); - - let placement = Option::extract(&mut maybe_placement); - let end = Vector::length(&map.data) - 1; - while (placement < end) { - Vector::swap(&mut map.data, placement, end); - placement = placement + 1; - }; - } - - public fun remove( - map: &mut SimpleMap, - key: &Key, - ): (Key, Value) { - let (maybe_idx, _) = find(map, key); - assert!(Option::is_some(&maybe_idx), Errors::invalid_argument(EKEY_NOT_FOUND)); - - let placement = Option::extract(&mut maybe_idx); - let end = Vector::length(&map.data) - 1; - - while (placement < end) { - Vector::swap(&mut map.data, placement, placement + 1); - placement = placement + 1; - }; - - let Element { key, value } = Vector::pop_back(&mut map.data); - (key, value) - } - - fun find( - map: &SimpleMap, - key: &Key, - ): (Option::Option, Option::Option) { - let length = Vector::length(&map.data); - - if (length == 0) { - return (Option::none(), Option::some(0)) - }; - - let left = 0; - let right = length; - - while (left != right) { - let mid = left + (right - left) / 2; - let potential_key = &Vector::borrow(&map.data, mid).key; - if (Compare::is_less_than(Compare::cmp_bytes(&BCS::to_bytes(potential_key), &BCS::to_bytes(key)))) { - left = mid + 1; - } else { - right = mid; - }; - }; - - if (left != length && key == &Vector::borrow(&map.data, left).key) { - (Option::some(left), Option::none()) - } else { - (Option::none(), Option::some(left)) - } - } - - #[test] - public fun add_remove_many() { - let map = create(); - - assert!(length(&map) == 0, 0); - assert!(!contains_key(&map, &3), 1); - add(&mut map, 3, 1); - assert!(length(&map) == 1, 2); - assert!(contains_key(&map, &3), 3); - assert!(borrow(&map, &3) == &1, 4); - *borrow_mut(&mut map, &3) = 2; - assert!(borrow(&map, &3) == &2, 5); - - assert!(!contains_key(&map, &2), 6); - add(&mut map, 2, 5); - assert!(length(&map) == 2, 7); - assert!(contains_key(&map, &2), 8); - assert!(borrow(&map, &2) == &5, 9); - *borrow_mut(&mut map, &2) = 9; - assert!(borrow(&map, &2) == &9, 10); - - remove(&mut map, &2); - assert!(length(&map) == 1, 11); - assert!(!contains_key(&map, &2), 12); - assert!(borrow(&map, &3) == &2, 13); - - remove(&mut map, &3); - assert!(length(&map) == 0, 14); - assert!(!contains_key(&map, &3), 15); - - destroy_empty(map); - } - - #[test] - public fun test_several() { - let map = create(); - add(&mut map, 6, 6); - add(&mut map, 1, 1); - add(&mut map, 5, 5); - add(&mut map, 2, 2); - add(&mut map, 3, 3); - add(&mut map, 0, 0); - add(&mut map, 7, 7); - add(&mut map, 4, 4); - - let idx = 0; - while (idx < Vector::length(&map.data)) { - assert!(idx == Vector::borrow(&map.data, idx).key, idx); - idx = idx + 1; - }; - - remove(&mut map, &0); - remove(&mut map, &1); - remove(&mut map, &2); - remove(&mut map, &3); - remove(&mut map, &4); - remove(&mut map, &5); - remove(&mut map, &6); - remove(&mut map, &7); - - destroy_empty(map); - } - - #[test] - #[expected_failure] - public fun add_twice() { - let map = create(); - add(&mut map, 3, 1); - add(&mut map, 3, 1); - - remove(&mut map, &3); - destroy_empty(map); - } - - #[test] - #[expected_failure] - public fun remove_twice() { - let map = create(); - add(&mut map, 3, 1); - remove(&mut map, &3); - remove(&mut map, &3); - - destroy_empty(map); - } -} diff --git a/sources/StarcoinDAO.move b/sources/StarcoinDAO.move deleted file mode 100644 index 77516012..00000000 --- a/sources/StarcoinDAO.move +++ /dev/null @@ -1,74 +0,0 @@ -module StarcoinFramework::StarcoinDAO { - use StarcoinFramework::DAOAccount; - use StarcoinFramework::Account; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::UpgradeModulePlugin::{Self, UpgradeModulePlugin}; - use StarcoinFramework::ConfigProposalPlugin::{Self, ConfigProposalPlugin}; - use StarcoinFramework::StakeToSBTPlugin::{Self, StakeToSBTPlugin}; - use StarcoinFramework::InstallPluginProposalPlugin::{Self, InstallPluginProposalPlugin}; - use StarcoinFramework::STC::STC; - use StarcoinFramework::Option; - use StarcoinFramework::GasOracleProposalPlugin::GasOracleProposalPlugin; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::TreasuryPlugin::{Self, TreasuryPlugin}; - use StarcoinFramework::Config; - use StarcoinFramework::PackageTxnManager; - use StarcoinFramework::WithdrawPlugin::{Self, WithdrawPlugin}; - - friend StarcoinFramework::Genesis; - friend StarcoinFramework::StdlibUpgradeScripts; - - struct StarcoinDAO has store, drop {} - - const NAME: vector = b"StarcoinDAO"; - - public(friend) fun create_dao( - signer_cap: Account::SignerCapability, - upgrade_plan_cap: PackageTxnManager::UpgradePlanCapability, - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128 - ) { - let dao_account_cap = DAOAccount::upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap, upgrade_plan_cap); - - let config = DAOSpace::new_dao_config( - voting_delay, - voting_period, - voting_quorum_rate, - min_action_delay, - min_proposal_deposit, - ); - - - DAOSpace::create_dao(dao_account_cap, *&NAME, Option::none>(), Option::none>(), b"ipfs://description", config); - - let witness = StarcoinDAO {}; - let install_cap = DAOSpace::acquire_install_plugin_cap(&witness); - DAOSpace::install_plugin(&install_cap, InstallPluginProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, UpgradeModulePlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, ConfigProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, StakeToSBTPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, GasOracleProposalPlugin::required_caps()); - DAOSpace::install_plugin(&install_cap, TreasuryPlugin::required_caps()); - - StakeToSBTPlugin::accept_token_by_dao(&witness); - StakeToSBTPlugin::set_sbt_weight_by_dao(&witness, 60000, 1000); - } - - public(friend) fun delegate_config_capability(cap: Config::ModifyConfigCapability) { - DAOSpace::set_custom_config_cap(cap); - } - - /// scale up the quorum votes for treasury withdraw proposal. - public(friend) fun set_treasury_withdraw_proposal_scale(scale: u8) { - TreasuryPlugin::set_scale_factor(scale, &StarcoinDAO {}); - } - - public(friend) fun upgrade_dao() { - let witness = StarcoinDAO {}; - let install_cap = DAOSpace::acquire_install_plugin_cap(&witness); - DAOSpace::install_plugin(&install_cap, WithdrawPlugin::required_caps()); - } -} \ No newline at end of file diff --git a/sources/StarcoinVerifier.move b/sources/StarcoinVerifier.move deleted file mode 100644 index 3493be95..00000000 --- a/sources/StarcoinVerifier.move +++ /dev/null @@ -1,351 +0,0 @@ -address StarcoinFramework { -module StarcoinVerifier { - use StarcoinFramework::Vector; - use StarcoinFramework::Option; - use StarcoinFramework::BCS; - use StarcoinFramework::StructuredHash; - use StarcoinFramework::Hash; - - const HASH_LEN_IN_BITS: u64 = 32 * 8; - const SPARSE_MERKLE_LEAF_NODE: vector = b"SparseMerkleLeafNode"; - const SPARSE_MERKLE_INTERNAL_NODE: vector = b"SparseMerkleInternalNode"; - const BLOB_HASH_PREFIX: vector = b"Blob"; - const DEFAULT_VALUE: vector = x""; - const ACCOUNT_STORAGE_INDEX_RESOURCE: u64 = 1; - const ERROR_ACCOUNT_STORAGE_ROOTS: u64 = 101; - const ERROR_LITERAL_HASH_WRONG_LENGTH: u64 = 102; - const SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL: vector = b"SPARSE_MERKLE_PLACEHOLDER_HASH"; - - - struct AccountState has store, drop, copy { - storage_roots: vector>>, - } - - public fun bcs_deserialize_account_state(data: &vector): AccountState { - let (vec, _) = BCS::deserialize_option_bytes_vector(data, 0); - AccountState{ - storage_roots: vec - } - } - - struct StateProof has store, drop, copy { - /** - * Account state's proof for global state root. - */ - account_proof: SparseMerkleProof, - /** - * Account state including storage roots. - */ - account_state: vector, - /** - * State's proof for account storage root. - */ - proof: SparseMerkleProof, - } - - public fun new_state_proof(account_proof: SparseMerkleProof, account_state: vector, proof: SparseMerkleProof): StateProof { - StateProof{ - account_proof, - account_state, - proof, - } - } - - struct SparseMerkleProof has store, drop, copy { - siblings: vector>, - leaf: SMTNode, - } - - public fun new_sparse_merkle_proof(siblings: vector>, leaf: SMTNode): SparseMerkleProof { - SparseMerkleProof{ - siblings, - leaf, - } - } - - struct SMTNode has store, drop, copy { - hash1: vector, - hash2: vector, - } - - public fun new_smt_node(hash1: vector, hash2: vector): SMTNode { - SMTNode{ - hash1, - hash2, - } - } - - public fun empty_smt_node(): SMTNode { - SMTNode{ - hash1: Vector::empty(), - hash2: Vector::empty(), - } - } - - public fun verify_state_proof(state_proof: &StateProof, state_root: &vector, - account_address: address, resource_struct_tag: &vector, - state: &vector): bool { - let accountState: AccountState = bcs_deserialize_account_state(&state_proof.account_state); - assert!(Vector::length(&accountState.storage_roots) > ACCOUNT_STORAGE_INDEX_RESOURCE, ERROR_ACCOUNT_STORAGE_ROOTS); - - // First, verify state for storage root. - let storageRoot = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE)); - let ok: bool = verify_smp(&state_proof.proof.siblings, - &state_proof.proof.leaf, - storageRoot, - resource_struct_tag, // resource struct tag BCS serialized as key - state); - if (!ok) { - return false - }; - - // Then, verify account state for global state root. - ok = verify_smp(&state_proof.account_proof.siblings, - &state_proof.account_proof.leaf, - state_root, - &BCS::to_bytes
(&account_address), // account address as key - &state_proof.account_state, - ); - ok - } - - #[test] - fun test_verify_state_proof() { - // miannet, block number 6495396 - let state_root = x"d337896a5cd8bae3d0130e09409c0f5eede159d93af38a642528acb15c1204b8"; - let account_address = @0x47d36856884d7fb9e91a475ea3472341; -// let state = x""; - let state = x"00000000000000000000000000000000"; - // 0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - let resource_struct_tag = x"00000000000000000000000000000001074163636f756e740742616c616e636501078c109349c6bd91411d6bc962e080c4a30453544152045354415200"; - - let account_proof_sibling_nodes = Vector::empty>(); - Vector::push_back(&mut account_proof_sibling_nodes, x"b81050a469dbe041f915cda6942143c691b1735599815142c895f77cf088a656"); - Vector::push_back(&mut account_proof_sibling_nodes, x"5350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000"); - Vector::push_back(&mut account_proof_sibling_nodes, x"1c0cbf70e7474e739db9ca9958470f605f37a5a0f322c7c854b24866c4330577"); - Vector::push_back(&mut account_proof_sibling_nodes, x"68dde7ba4f4a9cf6329675e598a1ab7b545f8de36e5cb8151be8ff167e479c26"); - Vector::push_back(&mut account_proof_sibling_nodes, x"3c59423b2956d25cdacf638540e39dbc53238d36ca1420d31c4321580aeff633"); - Vector::push_back(&mut account_proof_sibling_nodes, x"5befec9a99ad40f1cb6d5b44c87ca6ad26841535cd7fac27f2f88205088b55e3"); - Vector::push_back(&mut account_proof_sibling_nodes, x"32f4d82b78b1339fb5d9c60ac2e49780c87b9e9c675bee9d1cb3ace3f34a63d6"); - Vector::push_back(&mut account_proof_sibling_nodes, x"a60429524592cac0170763196269c4997e08b6a09b2ad45647775486a81559af"); - Vector::push_back(&mut account_proof_sibling_nodes, x"6b6bc4e16bad1fbc6c6df21a923a9be06ae8508827cdd3dbdd4e0e6607abdb6d"); - Vector::push_back(&mut account_proof_sibling_nodes, x"5e6165bc60b30f46611d52f9779668e0fa79eeb60bf3a0d90346b33331156155"); - Vector::push_back(&mut account_proof_sibling_nodes, x"dfc42240b0d542457748e873e3ab0ee362c68dedd91df13532cd85a1a6ea6f00"); - Vector::push_back(&mut account_proof_sibling_nodes, x"610cba3b3c467b137ddbda0f5783ef269357ca4e30aaa2cfecb96e2ee8b2c5e7"); - Vector::push_back(&mut account_proof_sibling_nodes, x"179235bb93b8ece25921f7405a2f797f80630d90f71e763e8a700734d6945b99"); - Vector::push_back(&mut account_proof_sibling_nodes, x"85d80d435c4cb8b8034d32aff6b05230efc43b583154428a0990e1f752adcf3a"); - Vector::push_back(&mut account_proof_sibling_nodes, x"a2f4a3e6f11e6b42d700c920c06a89ffe6d086d5411aa578d56d8de000704669"); - Vector::push_back(&mut account_proof_sibling_nodes, x"ee57409d642877366ac26b2bf8948f7daae3c45a545b931b28a6d902e01bdc1f"); - - let state_proof_sibling_nodes = Vector::empty>(); - Vector::push_back(&mut state_proof_sibling_nodes, x"2a3c2096fbd5a1a2e81077e4b2156c7232b9291ad3d85ea7451eb8b7cda828fd"); - Vector::push_back(&mut state_proof_sibling_nodes, x"4cc4f038091aba95645a5b8153dc088ffdbfb7c7e82dd6b166f187b33eea7432"); - Vector::push_back(&mut state_proof_sibling_nodes, x"aa140a1627b5385e108f6580062110463d09768bce681bbb88c3d9c59680d75d"); - Vector::push_back(&mut state_proof_sibling_nodes, x"7c8f59d557168dd5667fcc950ed444cfa0cbce778e032c918a8b2a2084c48c03"); - Vector::push_back(&mut state_proof_sibling_nodes, x"a0718e77be611f67f880f5fc4d7c801940aae65890f02b38a663458ed924c2f9"); - - let proof = new_state_proof( - new_sparse_merkle_proof( - account_proof_sibling_nodes, - new_smt_node( - x"3fe0547cb3576cad025fb5cfa98b85a3545a41e5b14e844fd8cad5edaa619c05", - x"ed0e07d03371a130b84bea8245f84bf546955e5a190afc20ef34f310614c6d10", - ), - ), - x"02000120ceaafd667b54252bba61993770d87bbb997b1a689b0e08899543e3c8f82adca7", - new_sparse_merkle_proof( - state_proof_sibling_nodes, - new_smt_node( - x"1de0d92e4e770fa53ceaa12c83edb8c0e51c1d19499d769c572ffd9d38cef40f", - x"6493204f1b87055adb8937a385daa238b3c08c491026f2ac50ebe4dab9133030", - ), - ), - ); - - let b = verify_state_proof( - &proof, - &state_root, - account_address, - &resource_struct_tag, - &state, - ); - assert!(b, 1110); - } - - /// Verify sparse merkle proof by key and value. - public fun verify_smp(sibling_nodes: &vector>, leaf_data: &SMTNode, expected_root: &vector, key: &vector, value: &vector): bool { - let path = hash_key(key); - let current_hash: vector; - if (*value == DEFAULT_VALUE) { - // Non-membership proof. - if (empty_smt_node() == *leaf_data) { - current_hash = placeholder(); - } else { - if (*&leaf_data.hash1 == *&path) { - return false - }; - if (!(count_common_prefix(&leaf_data.hash1, &path) >= Vector::length(sibling_nodes))) { - return false - }; - current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data); - }; - } else { - // Membership proof. - if (empty_smt_node() == *leaf_data) { - return false - }; - if (*&leaf_data.hash1 != *&path) { - return false - }; - let value_hash = hash_value(value); - if (*&leaf_data.hash2 != value_hash) { - return false - }; - current_hash = StructuredHash::hash(SPARSE_MERKLE_LEAF_NODE, leaf_data); - }; - - current_hash = compute_smp_root_by_path_and_node_hash(sibling_nodes, &path, ¤t_hash); - current_hash == *expected_root - } - -// #[test] -// fun test_print_storage_root(){ -// let account_state = x"02000120ceaafd667b54252bba61993770d87bbb997b1a689b0e08899543e3c8f82adca7"; -// let accountState: AccountState = bcs_deserialize_account_state(&account_state); -// let storageRoot = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE)); -// Debug::print(storageRoot); -// } - - #[test] - fun test_verify_smp() { - let sibling_nodes = Vector::empty>(); - Vector::push_back(&mut sibling_nodes, x"2a3c2096fbd5a1a2e81077e4b2156c7232b9291ad3d85ea7451eb8b7cda828fd"); - Vector::push_back(&mut sibling_nodes, x"4cc4f038091aba95645a5b8153dc088ffdbfb7c7e82dd6b166f187b33eea7432"); - Vector::push_back(&mut sibling_nodes, x"aa140a1627b5385e108f6580062110463d09768bce681bbb88c3d9c59680d75d"); - Vector::push_back(&mut sibling_nodes, x"7c8f59d557168dd5667fcc950ed444cfa0cbce778e032c918a8b2a2084c48c03"); - Vector::push_back(&mut sibling_nodes, x"a0718e77be611f67f880f5fc4d7c801940aae65890f02b38a663458ed924c2f9"); - - let leaf_node = new_smt_node( - x"1de0d92e4e770fa53ceaa12c83edb8c0e51c1d19499d769c572ffd9d38cef40f", - x"6493204f1b87055adb8937a385daa238b3c08c491026f2ac50ebe4dab9133030", - ); - let account_state = x"02000120ceaafd667b54252bba61993770d87bbb997b1a689b0e08899543e3c8f82adca7"; - let accountState: AccountState = bcs_deserialize_account_state(&account_state); - let expected_root = Option::borrow(Vector::borrow(&accountState.storage_roots, ACCOUNT_STORAGE_INDEX_RESOURCE)); -// let expected_root = x"0f30a41872208c6324fa842889315b14f9be6f3dd0d5050686317adfdd0cda60"; - let key = x"00000000000000000000000000000001074163636f756e740742616c616e636501078c109349c6bd91411d6bc962e080c4a30453544152045354415200"; - // Above key is this StructTag BCS serialized bytes: - let value = x"00000000000000000000000000000000"; - - let b = verify_smp(&sibling_nodes, &leaf_node, expected_root, &key, &value); - assert!(b, 1112) - } - - #[test] - fun test_verify_smp_2() { - let sibling_nodes: vector> = Vector::empty(); - let leaf_data: SMTNode = empty_smt_node(); - let expected_root: vector = placeholder(); - let key: vector = b"random key"; - let value: vector = Vector::empty(); //x"" - let b = verify_smp(&sibling_nodes, &leaf_data, &expected_root, &key, &value); - assert!(b, 1113); - - value = b"random value"; - b = verify_smp(&sibling_nodes, &leaf_data, &expected_root, &key, &value); - assert!(!b, 1114); - } - - public fun compute_smp_root_by_path_and_node_hash(sibling_nodes: &vector>, path: &vector, node_hash: &vector): vector { - let current_hash = *node_hash; - let i = 0; - let proof_length = Vector::length(sibling_nodes); - while (i < proof_length) { - let sibling = *Vector::borrow(sibling_nodes, i); - let bit = get_bit_at_from_msb(path, proof_length - i - 1); - let internal_node = if (bit) { - SMTNode{ hash1: sibling, hash2: current_hash } - } else { - SMTNode{ hash1: current_hash, hash2: sibling } - }; - current_hash = StructuredHash::hash(SPARSE_MERKLE_INTERNAL_NODE, &internal_node); - i = i + 1; - }; - current_hash - } - - public fun placeholder(): vector { - create_literal_hash(&SPARSE_MERKLE_PLACEHOLDER_HASH_LITERAL) - } - - public fun create_literal_hash(word: &vector): vector { - if (Vector::length(word) <= 32) { - let lenZero = 32 - Vector::length(word); - let i = 0; - let r = *word; - while (i < lenZero) { - Vector::push_back(&mut r, 0); - i = i + 1; - }; - return r - }; - abort ERROR_LITERAL_HASH_WRONG_LENGTH - } - - #[test] - fun test_create_literal_hash() { - let word = b"SPARSE_MERKLE_PLACEHOLDER_HASH"; - let r = create_literal_hash(&word); - assert!(r == x"5350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000", 1115); - } - - fun hash_key(key: &vector): vector { - Hash::sha3_256(*key) - } - - fun hash_value(value: &vector): vector { - StructuredHash::hash(BLOB_HASH_PREFIX, value) - } - - fun count_common_prefix(data1: &vector, data2: &vector): u64 { - let count = 0; - let i = 0; - while ( i < Vector::length(data1) * 8) { - if (get_bit_at_from_msb(data1, i) == get_bit_at_from_msb(data2, i)) { - count = count + 1; - } else { - break - }; - i = i + 1; - }; - count - } - - fun get_bit_at_from_msb(data: &vector, index: u64): bool { - let pos = index / 8; - let bit = (7 - index % 8); - (*Vector::borrow(data, pos) >> (bit as u8)) & 1u8 != 0 - } -} - -module StructuredHash { - use StarcoinFramework::Hash; - use StarcoinFramework::Vector; - use StarcoinFramework::BCS; - - const STARCOIN_HASH_PREFIX: vector = b"STARCOIN::"; - - public fun hash(structure: vector, data: &MoveValue): vector { - let prefix_hash = Hash::sha3_256(concat(&STARCOIN_HASH_PREFIX, structure)); - let bcs_bytes = BCS::to_bytes(data); - Hash::sha3_256(concat(&prefix_hash, bcs_bytes)) - } - - fun concat(v1: &vector, v2: vector): vector { - let data = *v1; - Vector::append(&mut data, v2); - data - } -} - -} \ No newline at end of file diff --git a/sources/StdlibUpgradeScripts.move b/sources/StdlibUpgradeScripts.move index 31f75d4a..d6355d6c 100644 --- a/sources/StdlibUpgradeScripts.move +++ b/sources/StdlibUpgradeScripts.move @@ -2,191 +2,102 @@ address StarcoinFramework { /// The module for StdlibUpgrade init scripts module StdlibUpgradeScripts { - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::STC::{Self, STC}; - use StarcoinFramework::Token::{Self, LinearTimeMintKey}; - use StarcoinFramework::TreasuryWithdrawDaoProposal; - use StarcoinFramework::Treasury::{Self, LinearWithdrawCapability}; - use StarcoinFramework::Offer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Collection; - use StarcoinFramework::Oracle; - use StarcoinFramework::STCUSDOracle; - use StarcoinFramework::NFT; - use StarcoinFramework::GenesisNFT; - use StarcoinFramework::LanguageVersion; - use StarcoinFramework::OnChainConfigDao; - use StarcoinFramework::Config; - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::Account; - use StarcoinFramework::Block; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::DAOExtensionPoint; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::AnyMemberPlugin; - use StarcoinFramework::ConfigProposalPlugin; - use StarcoinFramework::GrantProposalPlugin; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::MemberProposalPlugin; - use StarcoinFramework::MintProposalPlugin; - use StarcoinFramework::StakeToSBTPlugin; - use StarcoinFramework::UpgradeModulePlugin; - use StarcoinFramework::StarcoinDAO; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::Dao; - use StarcoinFramework::TreasuryPlugin; - use StarcoinFramework::TransactionPublishOption; - use StarcoinFramework::VMConfig; - use StarcoinFramework::ConsensusConfig; - use StarcoinFramework::RewardConfig; - use StarcoinFramework::TransactionTimeoutConfig; - use StarcoinFramework::UpgradeModuleDaoProposal; - use StarcoinFramework::ModifyDaoConfigProposal; - use StarcoinFramework::WithdrawPlugin; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - /// Stdlib upgrade script from v2 to v3 - public(script) fun upgrade_from_v2_to_v3(account: signer, total_stc_amount: u128) { - CoreAddresses::assert_genesis_address(&account); - - let withdraw_cap = STC::upgrade_from_v1_to_v2(&account, total_stc_amount); - - let mint_keys = Collection::borrow_collection>(CoreAddresses::ASSOCIATION_ROOT_ADDRESS()); - let mint_key = Collection::borrow(&mint_keys, 0); - let (total, minted, start_time, period) = Token::read_linear_time_key(mint_key); - Collection::return_collection(mint_keys); - - let now = Timestamp::now_seconds(); - let linear_withdraw_cap = Treasury::issue_linear_withdraw_capability(&mut withdraw_cap, total - minted, period - (now - start_time)); - // Lock the TreasuryWithdrawCapability to Dao - TreasuryWithdrawDaoProposal::plugin(&account, withdraw_cap); - // Give a LinearWithdrawCapability Offer to association, association need to take the offer, and destroy old LinearTimeMintKey. - Offer::create(&account, linear_withdraw_cap, CoreAddresses::ASSOCIATION_ROOT_ADDRESS(), 0); - } - - /// association account should call this script after upgrade from v2 to v3. - public(script) fun take_linear_withdraw_capability(signer: signer) { - let offered = Offer::redeem>(&signer, CoreAddresses::GENESIS_ADDRESS()); - Treasury::add_linear_withdraw_capability(&signer, offered); - let mint_key = Collection::take>(&signer); - Token::destroy_linear_time_key(mint_key); - } - - public fun do_upgrade_from_v5_to_v6(sender: &signer) { - CoreAddresses::assert_genesis_address(sender); - Oracle::initialize(sender); - //register oracle - STCUSDOracle::register(sender); - NFT::initialize(sender); - let merkle_root = x"5969f0e8e19f8769276fb638e6060d5c02e40088f5fde70a6778dd69d659ee6d"; - let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY"; - GenesisNFT::initialize(sender, merkle_root, 1639u64, image); - } - - public(script) fun upgrade_from_v5_to_v6(sender: signer) { - Self::do_upgrade_from_v5_to_v6(&sender) - } - - public(script) fun upgrade_from_v6_to_v7(sender: signer) { - Self::do_upgrade_from_v6_to_v7_with_language_version(&sender, 2); - } - - /// deprecated, use `do_upgrade_from_v6_to_v7_with_language_version`. - public fun do_upgrade_from_v6_to_v7(sender: &signer) { - do_upgrade_from_v6_to_v7_with_language_version(sender, 2); - } - - public fun do_upgrade_from_v6_to_v7_with_language_version(sender: &signer, language_version: u64) { - // initialize the language version config. - Config::publish_new_config(sender, LanguageVersion::new(language_version)); - // use STC Dao to upgrade onchain's move-language-version configuration. - OnChainConfigDao::plugin(sender); - // upgrade genesis NFT - GenesisNFT::upgrade_to_nft_type_info_v2(sender); - } - - public(script) fun upgrade_from_v7_to_v8(sender: signer) { - do_upgrade_from_v7_to_v8(&sender); - } - - public fun do_upgrade_from_v7_to_v8(sender: &signer) { - { - let cap = Oracle::extract_signer_cap(sender); - GenesisSignerCapability::initialize(sender, cap); - }; - - { - let cap = NFT::extract_signer_cap(sender); - Account::destroy_signer_cap(cap); - }; - } - - public(script) fun upgrade_from_v11_to_v12() { - do_upgrade_from_v11_to_v12(); - } - - public fun do_upgrade_from_v11_to_v12() { - let genessis_signer = GenesisSignerCapability::get_genesis_signer(); - Block::checkpoints_init(); - DAORegistry::initialize(); - - DAOExtensionPoint::initialize(); - DAOPluginMarketplace::initialize(); - - AnyMemberPlugin::initialize(&genessis_signer); - ConfigProposalPlugin::initialize(&genessis_signer); - GrantProposalPlugin::initialize(&genessis_signer); - InstallPluginProposalPlugin::initialize(&genessis_signer); - MemberProposalPlugin::initialize(&genessis_signer); - MintProposalPlugin::initialize(&genessis_signer); - StakeToSBTPlugin::initialize(&genessis_signer); - UpgradeModulePlugin::initialize(&genessis_signer); - GasOracleProposalPlugin::initialize(&genessis_signer); - TreasuryPlugin::initialize(&genessis_signer); - - //TODO : config rate need mind - // voting_delay: 60000 ms - // voting_period: 3600000 ms - // voting_quorum_rate: 4 - // min_action_delay: 3600000 ms - let signer_cap = Account::get_genesis_capability(); - let upgrade_plan_cap = UpgradeModuleDaoProposal::get_genesis_upgrade_cap(); - StarcoinDAO::create_dao(signer_cap, upgrade_plan_cap, Dao::voting_delay(), Dao::voting_period(), Dao::voting_quorum_rate(), Dao::min_action_delay(), 1000 * 1000 * 1000 * 1000); - - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - StarcoinDAO::delegate_config_capability( - OnChainConfigDao::config_cap()); - - let signer = GenesisSignerCapability::get_genesis_signer(); - let cap = TreasuryWithdrawDaoProposal::takeout_withdraw_capability(&signer); - TreasuryPlugin::delegate_capability(&signer, cap); - StarcoinDAO::set_treasury_withdraw_proposal_scale(100); - - // clean old DAO resources - ModifyDaoConfigProposal::destroy_modify_config_capability(&genessis_signer); - } - - public(script) fun upgrade_from_v12_to_v13() { - do_upgrade_from_v12_to_v13(); - } - - public fun do_upgrade_from_v12_to_v13() { - let genessis_signer = GenesisSignerCapability::get_genesis_signer(); - WithdrawPlugin::initialize(&genessis_signer); - StarcoinDAO::upgrade_dao(); - } + use StarcoinFramework::CoreAddresses; + use StarcoinFramework::STC::{Self, STC}; + use StarcoinFramework::Token::{Self, LinearTimeMintKey}; + use StarcoinFramework::TreasuryWithdrawDaoProposal; + use StarcoinFramework::Treasury::{Self, LinearWithdrawCapability}; + use StarcoinFramework::Offer; + use StarcoinFramework::Timestamp; + use StarcoinFramework::Collection; + use StarcoinFramework::Oracle; + use StarcoinFramework::STCUSDOracle; + use StarcoinFramework::NFT; + use StarcoinFramework::GenesisNFT; + use StarcoinFramework::LanguageVersion; + use StarcoinFramework::OnChainConfigDao; + use StarcoinFramework::Config; + use StarcoinFramework::GenesisSignerCapability; + use StarcoinFramework::Account; + + spec module { + pragma verify = false; + pragma aborts_if_is_strict = true; + } + + /// Stdlib upgrade script from v2 to v3 + public(script) fun upgrade_from_v2_to_v3(account: signer, total_stc_amount: u128 ) { + CoreAddresses::assert_genesis_address(&account); + + let withdraw_cap = STC::upgrade_from_v1_to_v2(&account, total_stc_amount); + + let mint_keys = Collection::borrow_collection>(CoreAddresses::ASSOCIATION_ROOT_ADDRESS()); + let mint_key = Collection::borrow(&mint_keys, 0); + let (total, minted, start_time, period) = Token::read_linear_time_key(mint_key); + Collection::return_collection(mint_keys); + + let now = Timestamp::now_seconds(); + let linear_withdraw_cap = Treasury::issue_linear_withdraw_capability(&mut withdraw_cap, total-minted, period - (now - start_time)); + // Lock the TreasuryWithdrawCapability to Dao + TreasuryWithdrawDaoProposal::plugin(&account, withdraw_cap); + // Give a LinearWithdrawCapability Offer to association, association need to take the offer, and destroy old LinearTimeMintKey. + Offer::create(&account, linear_withdraw_cap, CoreAddresses::ASSOCIATION_ROOT_ADDRESS(), 0); + } + + /// association account should call this script after upgrade from v2 to v3. + public(script) fun take_linear_withdraw_capability(signer: signer){ + let offered = Offer::redeem>(&signer, CoreAddresses::GENESIS_ADDRESS()); + Treasury::add_linear_withdraw_capability(&signer, offered); + let mint_key = Collection::take>(&signer); + Token::destroy_linear_time_key(mint_key); + } + + public fun do_upgrade_from_v5_to_v6(sender: &signer) { + CoreAddresses::assert_genesis_address(sender); + Oracle::initialize(sender); + //register oracle + STCUSDOracle::register(sender); + NFT::initialize(sender); + let merkle_root = x"5969f0e8e19f8769276fb638e6060d5c02e40088f5fde70a6778dd69d659ee6d"; + let image = b"ipfs://QmSPcvcXgdtHHiVTAAarzTeubk5X3iWymPAoKBfiRFjPMY"; + GenesisNFT::initialize(sender, merkle_root, 1639u64, image); + } + + public(script) fun upgrade_from_v5_to_v6(sender: signer) { + Self::do_upgrade_from_v5_to_v6(&sender) + } + + public(script) fun upgrade_from_v6_to_v7(sender: signer) { + Self::do_upgrade_from_v6_to_v7_with_language_version(&sender, 2); + } + + /// deprecated, use `do_upgrade_from_v6_to_v7_with_language_version`. + public fun do_upgrade_from_v6_to_v7(sender: &signer) { + do_upgrade_from_v6_to_v7_with_language_version(sender, 2); + } + + public fun do_upgrade_from_v6_to_v7_with_language_version(sender: &signer, language_version: u64) { + // initialize the language version config. + Config::publish_new_config(sender, LanguageVersion::new(language_version)); + // use STC Dao to upgrade onchain's move-language-version configuration. + OnChainConfigDao::plugin(sender); + // upgrade genesis NFT + GenesisNFT::upgrade_to_nft_type_info_v2(sender); + } + + public(script) fun upgrade_from_v7_to_v8(sender: signer) { + do_upgrade_from_v7_to_v8(&sender); + } + public fun do_upgrade_from_v7_to_v8(sender: &signer) { + { + let cap = Oracle::extract_signer_cap(sender); + GenesisSignerCapability::initialize(sender, cap); + }; + + { + let cap = NFT::extract_signer_cap(sender); + Account::destroy_signer_cap(cap); + }; + } } } \ No newline at end of file diff --git a/sources/Token.move b/sources/Token.move index 290b9843..5aa1cecd 100644 --- a/sources/Token.move +++ b/sources/Token.move @@ -6,7 +6,6 @@ module Token { use StarcoinFramework::Errors; use StarcoinFramework::Math; - friend StarcoinFramework::TypeInfo; spec module { pragma verify; pragma aborts_if_is_strict; @@ -505,12 +504,8 @@ module Token { /// does not matter for the verification of callers. spec fun spec_token_code(): TokenCode; - public (friend) fun type_of(): (address, vector, vector){ - name_of() - } - /// Return Token's module address, module name, and type name of `TokenType`. - native fun name_of(): (address, vector, vector); + native fun name_of(): (address, vector, vector); spec name_of { pragma opaque = true; diff --git a/sources/TransactionManager.move b/sources/TransactionManager.move index 5ea13eee..70aa0b2b 100644 --- a/sources/TransactionManager.move +++ b/sources/TransactionManager.move @@ -19,10 +19,6 @@ module TransactionManager { use StarcoinFramework::Epoch; use StarcoinFramework::Hash; use StarcoinFramework::Vector; - use StarcoinFramework::StarcoinDAO::StarcoinDAO; - use StarcoinFramework::GasOracleProposalPlugin; - use StarcoinFramework::STC; - use StarcoinFramework::GasOracle; spec module { pragma verify = false; @@ -66,21 +62,13 @@ module TransactionManager { // Check that the chain ID stored on-chain matches the chain ID // specified by the transaction assert!(ChainId::get() == chain_id, Errors::invalid_argument(EPROLOGUE_BAD_CHAIN_ID)); - let (stc_price,scaling_factor)= if (!STC::is_stc()){ - (GasOracleProposalPlugin::gas_oracle_read(),GasOracle::get_scaling_factor()) - }else{ - (1,1) - }; - - Account::txn_prologue_v2( + Account::txn_prologue( &account, txn_sender, txn_sequence_number, txn_authentication_key_preimage, txn_gas_price, txn_max_gas_units, - stc_price, - scaling_factor, ); assert!( TransactionTimeout::is_valid_transaction_timestamp(txn_expiration_time), @@ -121,6 +109,8 @@ module TransactionManager { include Timestamp::AbortsIfTimestampNotExists; include Block::AbortsIfBlockMetadataNotExist; aborts_if txn_gas_price * txn_max_gas_units > 0 && !exists>(txn_sender); + aborts_if txn_gas_price * txn_max_gas_units > 0 && StarcoinFramework::Token::spec_token_code() != StarcoinFramework::Token::spec_token_code(); + aborts_if txn_gas_price * txn_max_gas_units > 0 && global>(txn_sender).token.value < txn_gas_price * txn_max_gas_units; aborts_if txn_gas_price * txn_max_gas_units > 0 && txn_sequence_number >= max_u64(); aborts_if txn_sequence_number < global(txn_sender).sequence_number; aborts_if txn_sequence_number != global(txn_sender).sequence_number; @@ -169,13 +159,7 @@ module TransactionManager { success: bool, ) { CoreAddresses::assert_genesis_address(&account); - let (stc_price,scaling_factor) = - if (!STC::is_stc()){ - (GasOracleProposalPlugin::gas_oracle_read(),GasOracle::get_scaling_factor()) - }else{ - (1,1) - }; - Account::txn_epilogue_v3( + Account::txn_epilogue_v2( &account, txn_sender, txn_sequence_number, @@ -183,8 +167,6 @@ module TransactionManager { txn_gas_price, txn_max_gas_units, gas_units_remaining, - stc_price, - scaling_factor ); if (txn_payload_type == TXN_PAYLOAD_TYPE_PACKAGE) { PackageTxnManager::package_txn_epilogue( diff --git a/sources/TreasuryWithdrawDaoProposal.move b/sources/TreasuryWithdrawDaoProposal.move index 1053cb12..5b3668c1 100644 --- a/sources/TreasuryWithdrawDaoProposal.move +++ b/sources/TreasuryWithdrawDaoProposal.move @@ -34,7 +34,6 @@ module TreasuryWithdrawDaoProposal { const ERR_NEED_RECEIVER_TO_EXECUTE: u64 = 102; /// The withdraw amount of propose is too many. const ERR_TOO_MANY_WITHDRAW_AMOUNT: u64 = 103; - const ERR_CAPABILITY_NOT_EXIST: u64 = 104; /// Plugin method of the module. /// Should be called by token issuer. @@ -44,17 +43,6 @@ module TreasuryWithdrawDaoProposal { move_to(signer, WrappedWithdrawCapability { cap: cap }); } - /// withdraw Treasury::WithdrawCapability - public fun takeout_withdraw_capability(sender: &signer): Treasury::WithdrawCapability - acquires WrappedWithdrawCapability { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - - assert!(exists>(Signer::address_of(sender)), Errors::not_published(ERR_CAPABILITY_NOT_EXIST)); - let WrappedWithdrawCapability { cap } = move_from>(Signer::address_of(sender)); - cap - } - spec plugin { pragma aborts_if_is_partial = false; let sender = Signer::address_of(signer); diff --git a/sources/TypeInfo.move b/sources/TypeInfo.move deleted file mode 100644 index 933e43ec..00000000 --- a/sources/TypeInfo.move +++ /dev/null @@ -1,30 +0,0 @@ -module StarcoinFramework::TypeInfo{ - use StarcoinFramework::Token; - - struct TypeInfo has copy, drop, store{ - account_address: address, - module_name: vector, - struct_name: vector - } - - public fun account_address(type_info: &TypeInfo):address{ - type_info.account_address - } - - public fun module_name(type_info: &TypeInfo):vector{ - *&type_info.module_name - } - - public fun struct_name(type_info: &TypeInfo):vector{ - *&type_info.struct_name - } - - public fun type_of():TypeInfo{ - let (account_address, module_name, struct_name) = Token::type_of(); - TypeInfo { - account_address, - module_name, - struct_name - } - } -} \ No newline at end of file diff --git a/sources/U256.move b/sources/U256.move index f83dfdfb..6c70e296 100644 --- a/sources/U256.move +++ b/sources/U256.move @@ -378,6 +378,115 @@ module U256 { assert!(compare(&Self::pow(copy a, d), &from_u64(1)) == EQUAL, 0); } + /// move implementation of native_add. + fun add_nocarry(a: &mut U256, b: &U256) { + let carry = 0; + let idx = 0; + let len = (WORD as u64); + while (idx < len) { + let a_bit = Vector::borrow_mut(&mut a.bits, idx); + let b_bit = Vector::borrow(&b.bits, idx); + *a_bit = StarcoinFramework::Arith::adc(*a_bit, *b_bit, &mut carry); + idx = idx + 1; + }; + + // check overflow + assert!(carry == 0, 100); + } + + // TODO: MVP find false examples that violate the spec + // spec add_nocarry { + // aborts_if value_of_U256(a) + value_of_U256(b) >= P64 * P64 * P64 * P64; + // ensures value_of_U256(a) == value_of_U256(old(a)) + value_of_U256(b); + // } + + #[test] + #[expected_failure] + fun test_add_nocarry_overflow() { + let va = Vector::empty(); + Vector::push_back(&mut va, 15891); + Vector::push_back(&mut va, 0); + Vector::push_back(&mut va, 0); + Vector::push_back(&mut va, 0); + + let vb = Vector::empty(); + Vector::push_back(&mut vb, 18446744073709535725); + Vector::push_back(&mut vb, 18446744073709551615); + Vector::push_back(&mut vb, 18446744073709551615); + Vector::push_back(&mut vb, 18446744073709551615); + + let a = U256 { bits: va }; + let b = U256 { bits: vb }; + add_nocarry(&mut a, &b); // MVP thinks this won't abort + } + + #[test] + fun test_add_nocarry_like_native_1() { + let va = Vector::empty(); + Vector::push_back(&mut va, 15891); + Vector::push_back(&mut va, 0); + Vector::push_back(&mut va, 0); + Vector::push_back(&mut va, 0); + + let vb = Vector::empty(); + Vector::push_back(&mut vb, 18446744073709535724); + Vector::push_back(&mut vb, 18446744073709551615); + Vector::push_back(&mut vb, 18446744073709551615); + Vector::push_back(&mut vb, 18446744073709551615); + + let a1 = U256 { bits: va }; + let a2 = copy a1; + let b = U256 { bits: vb }; + add_nocarry(&mut a1, &b); + native_add(&mut a2, &b); + assert!(compare(&a1, &a2) == EQUAL, 0); // MVP thinks this doesn't hold + } + + #[test] + fun test_add_nocarry_like_native_2() { + let va = Vector::empty(); + Vector::push_back(&mut va, 26962); + Vector::push_back(&mut va, 24464); + Vector::push_back(&mut va, 6334); + Vector::push_back(&mut va, 19169); + + let vb = Vector::empty(); + Vector::push_back(&mut vb, 29358); + Vector::push_back(&mut vb, 26500); + Vector::push_back(&mut vb, 15724); + Vector::push_back(&mut vb, 11478); + + let a1 = U256 { bits: va }; + let a2 = copy a1; + let b = U256 { bits: vb }; + add_nocarry(&mut a1, &b); // MVP thinks this abort + native_add(&mut a2, &b); + assert!(compare(&a1, &a2) == EQUAL, 0); + } + + /// move implementation of native_sub. + fun sub_noborrow(a: &mut U256, b: &U256) { + let borrow = 0; + let idx = 0; + let len = (WORD as u64); + while (idx < len) { + let a_bit = Vector::borrow_mut(&mut a.bits, idx); + let b_bit = Vector::borrow(&b.bits, idx); + *a_bit = StarcoinFramework::Arith::sbb(*a_bit, *b_bit, &mut borrow); + idx = idx + 1; + }; + + // check overflow + assert!(borrow == 0, 100); + + } + + // TODO: Similar situation with `add_nocarry` + // spec sub_noborrow { + // aborts_if value_of_U256(a) < value_of_U256(b); + // ensures value_of_U256(a) == value_of_U256(old(a)) - value_of_U256(b); + // } + native fun from_bytes(data: &vector, be: bool): U256; native fun native_add(a: &mut U256, b: &U256); native fun native_sub(a: &mut U256, b: &U256); diff --git a/sources/UpgradeModuleDaoProposal.move b/sources/UpgradeModuleDaoProposal.move index 7bbd37dc..d4cb99c8 100644 --- a/sources/UpgradeModuleDaoProposal.move +++ b/sources/UpgradeModuleDaoProposal.move @@ -8,8 +8,6 @@ module UpgradeModuleDaoProposal { use StarcoinFramework::Dao; use StarcoinFramework::Errors; - friend StarcoinFramework::StdlibUpgradeScripts; - spec module { pragma verify = false; // break after enabling v2 compilation scheme pragma aborts_if_is_strict; @@ -57,13 +55,6 @@ module UpgradeModuleDaoProposal { aborts_if exists>(sender); } - public (friend) fun get_genesis_upgrade_cap():PackageTxnManager::UpgradePlanCapability acquires UpgradeModuleCapability{ - let UpgradeModuleCapability{ - cap - } = move_from(Token::token_address()); - cap - } - spec schema AbortIfUnableUpgrade { module_address: address; let token_issuer = Token::SPEC_TOKEN_TEST_ADDRESS(); diff --git a/sources/daospace/DAOAccount.move b/sources/daospace/DAOAccount.move deleted file mode 100644 index b297dfa0..00000000 --- a/sources/daospace/DAOAccount.move +++ /dev/null @@ -1,121 +0,0 @@ -module StarcoinFramework::DAOAccount{ - use StarcoinFramework::Account::{Self, SignerCapability}; - use StarcoinFramework::PackageTxnManager::{Self, UpgradePlanCapability}; - use StarcoinFramework::Option; - use StarcoinFramework::Signer; - use StarcoinFramework::Errors; - use StarcoinFramework::Version; - use StarcoinFramework::Config; - - - friend StarcoinFramework::StarcoinDAO; - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - const ERR_ACCOUNT_CAP_NOT_EXISTS:u64 = 100; - const ERR_ACCOUNT_CAP_EXISTS: u64 = 101; - const ERR_ACCOUNT_IS_NOT_SAME: u64 = 102; - const ERR_UPGARDE_PLAN_CAP_NOT_EXISTS: u64 = 103; - - /// DAOAccount - struct DAOAccount has key{ - dao_address: address, - signer_cap: SignerCapability, - upgrade_plan_cap: UpgradePlanCapability, - } - - /// This capability can control the DAO account - struct DAOAccountCap has store, key{ - dao_address: address, - } - - /// Create a new DAO Account and return DAOAccountCap - /// DAO Account is a delegate account, the `creator` has the `DAOAccountCap` - public fun create_account(creator: &signer): DAOAccountCap { - let (_dao_address, signer_cap) = Account::create_delegate_account(creator); - upgrade_to_dao_with_signer_cap(signer_cap) - } - - /// Entry function for create dao account, the `DAOAccountCap` save to the `creator` account - public(script) fun create_account_entry(sender: signer){ - let cap = create_account(&sender); - assert!(!exists(Signer::address_of(&sender)), Errors::already_published(ERR_ACCOUNT_CAP_EXISTS)); - move_to(&sender, cap); - } - - /// Extract the DAOAccountCap from the `sender` - public fun extract_dao_account_cap(sender: &signer): DAOAccountCap acquires DAOAccountCap { - let sender_addr = Signer::address_of(sender); - assert!(exists(sender_addr), Errors::not_published(ERR_ACCOUNT_CAP_NOT_EXISTS)); - move_from(sender_addr) - } - - /// Restore the DAOAccountCap to the `sender` - public fun restore_dao_account_cap(sender: &signer, cap: DAOAccountCap) { - let sender_addr = Signer::address_of(sender); - assert!(!exists(sender_addr), Errors::already_published(ERR_ACCOUNT_CAP_EXISTS)); - move_to(sender, cap) - } - - /// Upgrade `sender` account to DAO account - public fun upgrade_to_dao(sender: signer): DAOAccountCap { - let signer_cap = Account::remove_signer_capability(&sender); - upgrade_to_dao_with_signer_cap(signer_cap) - } - - /// Upgrade the account which have the `signer_cap` to a DAO Account - public fun upgrade_to_dao_with_signer_cap(signer_cap: SignerCapability): DAOAccountCap { - let dao_signer = Account::create_signer_with_cap(&signer_cap); - let dao_address = Signer::address_of(&dao_signer); - - let upgrade_plan_cap = if(Config::config_exist_by_address(dao_address)){ - assert!(PackageTxnManager::exists_upgrade_plan_cap(dao_address), Errors::not_published(ERR_UPGARDE_PLAN_CAP_NOT_EXISTS)); - PackageTxnManager::extract_submit_upgrade_plan_cap(&dao_signer) - }else{ - Config::publish_new_config(&dao_signer, Version::new_version(1)); - PackageTxnManager::update_module_upgrade_strategy(&dao_signer, PackageTxnManager::get_strategy_two_phase(), Option::some(1)); - PackageTxnManager::extract_submit_upgrade_plan_cap(&dao_signer) - }; - upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap, upgrade_plan_cap) - } - - /// Upgrade the account which have the `signer_cap` to a DAO Account - public fun upgrade_to_dao_with_signer_cap_and_upgrade_plan_cap(signer_cap: SignerCapability, upgrade_plan_cap:UpgradePlanCapability): DAOAccountCap { - let dao_signer = Account::create_signer_with_cap(&signer_cap); - let dao_address = Signer::address_of(&dao_signer); - - assert!(Account::signer_address(&signer_cap) == PackageTxnManager::account_address(&upgrade_plan_cap), Errors::already_published(ERR_ACCOUNT_IS_NOT_SAME)); - - move_to(&dao_signer, DAOAccount{ - dao_address, - signer_cap, - upgrade_plan_cap, - }); - - DAOAccountCap{ - dao_address - } - } - - /// Provide a function to create signer with `DAOAccountCap` - public fun dao_signer(cap: &DAOAccountCap): signer acquires DAOAccount { - let signer_cap = &borrow_global(cap.dao_address).signer_cap; - Account::create_signer_with_cap(signer_cap) - } - - /// Sumbit upgrade plan for the DAO account - /// This function is a shortcut for create signer with DAOAccountCap and invoke `PackageTxnManager::submit_upgrade_plan_v2` - public fun submit_upgrade_plan(cap: &DAOAccountCap, package_hash: vector, version:u64, enforced: bool) acquires DAOAccount{ - let upgrade_plan_cap = &borrow_global(cap.dao_address).upgrade_plan_cap; - PackageTxnManager::submit_upgrade_plan_with_cap_v2(upgrade_plan_cap, package_hash, version, enforced); - } - - /// Sumbit upgrade plan for the DAO account, sender must hold the `DAOAccountCap` - public(script) fun submit_upgrade_plan_entry(sender: signer, package_hash: vector, version:u64, enforced: bool) acquires DAOAccount, DAOAccountCap{ - let addr = Signer::address_of(&sender); - let cap = borrow_global(addr); - submit_upgrade_plan(cap, package_hash, version, enforced) - } -} \ No newline at end of file diff --git a/sources/daospace/DAOExtensionPoint.move b/sources/daospace/DAOExtensionPoint.move deleted file mode 100644 index 7c88aa63..00000000 --- a/sources/daospace/DAOExtensionPoint.move +++ /dev/null @@ -1,437 +0,0 @@ -module StarcoinFramework::DAOExtensionPoint { - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Vector; - use StarcoinFramework::NFT; - use StarcoinFramework::NFTGallery; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::Event; - use StarcoinFramework::TypeInfo::{Self, TypeInfo}; - - const ERR_ALREADY_INITIALIZED: u64 = 100; - const ERR_NOT_CONTRACT_OWNER: u64 = 101; - const ERR_EXPECT_EXT_POINT_NFT: u64 = 102; - const ERR_NOT_FOUND_EXT_POINT: u64 = 103; - const ERR_ALREADY_REGISTERED: u64 = 104; - const ERR_STAR_ALREADY_STARED: u64 = 105; - const ERR_STAR_NOT_FOUND_STAR: u64 = 106; - const ERR_TAG_DUPLICATED: u64 = 107; - - const ERR_VERSION_COUNT_LIMIT: u64 = 108; - const ERR_ITEMS_COUNT_LIMIT: u64 = 109; - const ERR_STRING_TOO_LONG: u64 = 110; - - const MAX_VERSION_COUNT: u64 = 256; // Max version count for extension point. - const MAX_LABELS_COUNT: u64 = 20; // Max labels count for extension point. - - const MAX_INPUT_LEN: u64 = 64; - const MAX_TEXT_LEN: u64 = 256; - - struct Version has store { - number: u64, - tag: vector, - types_d_ts: vector, - document: vector, - created_at: u64, - } - - struct Registry has key, store { - next_id: u64, - } - - struct Entry has key, store { - id: u64, - name: vector, - description: vector, - labels: vector>, - next_version_number: u64, - versions: vector, - star_count: u64, - created_at: u64, - updated_at: u64, - } - - struct Star has key, store { - created_at: u64, - } - - struct OwnerNFTMeta has copy, store, drop { - extpoint_id: u64, - registry_address: address, - } - - struct OwnerNFTBody has store{} - - struct NFTMintCapHolder has key { - cap: NFT::MintCapability, - nft_metadata: NFT::Metadata, - } - - /// registry event handlers - struct RegistryEventHandlers has key, store{ - register: Event::EventHandle, - } - - struct ExtensionPointRegisterEvent has drop, store{ - id: u64, - type: TypeInfo, - name: vector, - description:vector, - labels: vector> - } - - /// extension point event handlers - struct ExtensionPointEventHandlers has key, store{ - publish_version: Event::EventHandle>, - star: Event::EventHandle>, - unstar: Event::EventHandle>, - update: Event::EventHandle>, - } - - struct PublishVersionEvent has drop, store{ - sender: address, - version_number: u64, - } - - struct StarEvent has drop, store{ - sender: address, - } - - struct UnstarEvent has drop, store{ - sender: address, - } - - struct UpdateInfoEvent has drop, store{ - sender: address, - id: u64, - name: vector, - description:vector, - labels: vector> - } - - fun next_extpoint_id(registry: &mut Registry): u64 { - let extpoint_id = registry.next_id; - registry.next_id = extpoint_id + 1; - extpoint_id - } - - fun next_extpoint_version_number(extpoint: &mut Entry): u64 { - let version_number = extpoint.next_version_number; - extpoint.next_version_number = version_number + 1; - version_number - } - - fun has_extpoint_nft(sender_addr: address, extpoint_id: u64): bool { - if (!NFTGallery::is_accept(sender_addr)) { - return false - }; - - let nft_infos = NFTGallery::get_nft_infos(sender_addr); - let len = Vector::length(&nft_infos); - if (len == 0) { - return false - }; - - let idx = len - 1; - loop { - let nft_info = Vector::borrow(&nft_infos, idx); - let (_, _, _, type_meta) = NFT::unpack_info(*nft_info); - if (type_meta.extpoint_id == extpoint_id) { - return true - }; - - if (idx == 0) { - return false - }; - - idx = idx - 1; - } - } - - fun ensure_exists_extpoint_nft(sender_addr: address, extpoint_id: u64) { - assert!(has_extpoint_nft(sender_addr, extpoint_id), Errors::invalid_state(ERR_EXPECT_EXT_POINT_NFT)); - } - - fun assert_tag_no_repeat(v: &vector, tag:vector) { - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert!(*&e.tag != *&tag, Errors::invalid_argument(ERR_TAG_DUPLICATED)); - i = i + 1; - }; - } - - fun assert_string_length(s: &vector, max_len: u64) { - let len = Vector::length(s); - assert!(len <= max_len, Errors::invalid_argument(ERR_STRING_TOO_LONG)); - } - - fun assert_string_array_length(v: &vector>, max_item_len: u64, max_string_len: u64) { - assert!(Vector::length(v) <= max_item_len, Errors::limit_exceeded(ERR_ITEMS_COUNT_LIMIT)); - - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert_string_length(e, max_string_len); - i = i + 1; - }; - } - - public fun initialize() { - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - - let nft_name = b"ExtPointOwnerNFT"; - let nft_image = b"ipfs://QmdTwdhFi61zhRM3MtPLxuKyaqv3ePECLGsMg9pMrePv4i"; - let nft_description = b"The extension point owner NFT"; - let basemeta = NFT::new_meta_with_image_data(nft_name, nft_image, nft_description); - let basemeta_bak = *&basemeta; - NFT::register_v2(&signer, basemeta); - - let nft_mint_cap = NFT::remove_mint_capability(&signer); - move_to(&signer, NFTMintCapHolder{ - cap: nft_mint_cap, - nft_metadata: basemeta_bak, - }); - - move_to(&signer, Registry{ - next_id: 1, - }); - - move_to(&signer, RegistryEventHandlers { - register: Event::new_event_handle(&signer), - }); - } - - public fun register(sender: &signer, name: vector, description: vector, types_d_ts:vector, dts_doc:vector, - option_labels: Option>>):u64 acquires Registry, NFTMintCapHolder, RegistryEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - assert_string_length(&types_d_ts, MAX_TEXT_LEN); - assert_string_length(&dts_doc, MAX_TEXT_LEN); - - assert!(!exists>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_REGISTERED)); - let registry = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let extpoint_id = next_extpoint_id(registry); - - let version = Version { - number: 1, - tag: b"v0.1.0", - types_d_ts: types_d_ts, - document: dts_doc, - created_at: Timestamp::now_seconds(), - }; - - let labels = if(Option::is_some(&option_labels)){ - Option::destroy_some(option_labels) - } else { - Vector::empty>() - }; - - assert_string_array_length(&labels, MAX_LABELS_COUNT, MAX_INPUT_LEN); - - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - move_to(&genesis_account, Entry{ - id: copy extpoint_id, - name: copy name, - description: copy description, - labels: copy labels, - next_version_number: 2, - versions: Vector::singleton(version), - star_count: 0, - created_at: Timestamp::now_seconds(), - updated_at: Timestamp::now_seconds(), - }); - - move_to(&genesis_account, ExtensionPointEventHandlers{ - publish_version: Event::new_event_handle>(&genesis_account), - star: Event::new_event_handle>(&genesis_account), - unstar: Event::new_event_handle>(&genesis_account), - update: Event::new_event_handle>(&genesis_account), - }); - - // grant owner NFT to sender - let nft_mint_cap = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let meta = OwnerNFTMeta{ - registry_address: CoreAddresses::GENESIS_ADDRESS(), - extpoint_id: extpoint_id, - }; - - let nft = NFT::mint_with_cap_v2(CoreAddresses::GENESIS_ADDRESS(), &mut nft_mint_cap.cap, *&nft_mint_cap.nft_metadata, meta, OwnerNFTBody{}); - NFTGallery::deposit(sender, nft); - - // registry register event emit - let registry_event_handlers = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut registry_event_handlers.register, - ExtensionPointRegisterEvent { - id: copy extpoint_id, - type: TypeInfo::type_of(), - name: copy name, - description: copy description, - labels: copy labels, - }, - ); - - extpoint_id - } - - public fun publish_version( - sender: &signer, - tag: vector, - types_d_ts:vector, - dts_doc: vector, - ) acquires Entry, ExtensionPointEventHandlers { - assert_string_length(&tag, MAX_INPUT_LEN); - assert_string_length(&types_d_ts, MAX_TEXT_LEN); - assert_string_length(&dts_doc, MAX_TEXT_LEN); - - let sender_addr = Signer::address_of(sender); - let extp = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - - ensure_exists_extpoint_nft(sender_addr, extp.id); - assert!(Vector::length(&extp.versions) <= MAX_VERSION_COUNT, Errors::limit_exceeded(ERR_VERSION_COUNT_LIMIT)); - assert_tag_no_repeat(&extp.versions, copy tag); - - let number = next_extpoint_version_number(extp); - Vector::push_back(&mut extp.versions, Version{ - number: number, - tag: tag, - types_d_ts: types_d_ts, - document: dts_doc, - created_at: Timestamp::now_seconds(), - }); - - extp.updated_at = Timestamp::now_seconds(); - - // publish version event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.publish_version, - PublishVersionEvent { - sender: copy sender_addr, - version_number: copy number, - }, - ); - } - - public fun update(sender: &signer, name: vector, description: vector, option_labels: Option>>) acquires Entry, ExtensionPointEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - - let sender_addr = Signer::address_of(sender); - let extp = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - ensure_exists_extpoint_nft(sender_addr, extp.id); - - extp.name = name; - extp.description = description; - - if(Option::is_some(&option_labels)){ - let labels = Option::destroy_some(option_labels); - assert_string_array_length(&labels, MAX_LABELS_COUNT, MAX_INPUT_LEN); - extp.labels = labels; - }; - - extp.updated_at = Timestamp::now_seconds(); - - // update extpoint entry event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.update, - UpdateInfoEvent { - sender: sender_addr, - id: *&extp.id, - name: *&extp.name, - description: *&extp.description, - labels: *&extp.labels, - }, - ); - } - - public fun has_star_plugin(sender: &signer): bool { - let sender_addr = Signer::address_of(sender); - return exists>(sender_addr) - } - - public fun star(sender: &signer) acquires Entry, ExtensionPointEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(!exists>(sender_addr), Errors::invalid_state(ERR_STAR_ALREADY_STARED)); - - move_to(sender, Star{ - created_at: Timestamp::now_seconds(), - }); - - let entry = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - entry.star_count = entry.star_count + 1; - entry.updated_at = Timestamp::now_seconds(); - - // star event emit - let extpoint_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut extpoint_event_handlers.star, - StarEvent { - sender: sender_addr, - }, - ); - } - - public fun unstar(sender: &signer) acquires Star, Entry, ExtensionPointEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::invalid_state(ERR_STAR_NOT_FOUND_STAR)); - - let star = move_from>(sender_addr); - let Star {created_at:_} = star; - - let entry = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - entry.star_count = entry.star_count - 1; - entry.updated_at = Timestamp::now_seconds(); - - // unstar event emit - let extpoint_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut extpoint_event_handlers.unstar, - UnstarEvent { - sender: sender_addr, - }, - ); - } - - // public entrys - public(script) fun register_entry(sender: signer, name: vector, description: vector, types_d_ts:vector, dts_doc:vector, - labels: vector>) acquires Registry, NFTMintCapHolder, RegistryEventHandlers { - let option_labels = if(Vector::length(&labels) == 0){ - Option::none>>() - } else { - Option::some(labels) - }; - - register(&sender, name, description, types_d_ts, dts_doc, option_labels); - } - - public(script) fun publish_version_entry( - sender: signer, - tag: vector, - types_d_ts:vector, - dts_doc: vector, - ) acquires Entry, ExtensionPointEventHandlers { - publish_version(&sender, tag, types_d_ts, dts_doc); - } - - public(script) fun update_entry(sender: signer, name: vector, description: vector, labels: vector>) acquires Entry, ExtensionPointEventHandlers { - let option_labels = if(Vector::length(&labels) == 0){ - Option::none>>() - } else { - Option::some(labels) - }; - - update(&sender, name, description, option_labels); - } - - public(script) fun star_entry(sender: signer) acquires Entry, ExtensionPointEventHandlers { - star(&sender); - } - - public(script) fun unstar_entry(sender: signer) acquires Star, Entry, ExtensionPointEventHandlers { - unstar(&sender); - } -} diff --git a/sources/daospace/DAOPluginMarketplace.move b/sources/daospace/DAOPluginMarketplace.move deleted file mode 100644 index 00afaeec..00000000 --- a/sources/daospace/DAOPluginMarketplace.move +++ /dev/null @@ -1,359 +0,0 @@ -module StarcoinFramework::DAOPluginMarketplace { - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Vector; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::Event; - use StarcoinFramework::TypeInfo::{Self, TypeInfo}; - - const ERR_ALREADY_INITIALIZED: u64 = 100; - const ERR_NOT_CONTRACT_OWNER: u64 = 101; - const ERR_NOT_FOUND_PLUGIN: u64 = 102; - const ERR_EXPECT_PLUGIN_NFT: u64 = 103; - const ERR_PLUGIN_ALREADY_EXISTS: u64 = 104; - const ERR_STAR_ALREADY_STARED: u64 = 105; - const ERR_STAR_NOT_FOUND_STAR: u64 = 106; - const ERR_TAG_DUPLICATED: u64 = 107; - - const ERR_VERSION_COUNT_LIMIT: u64 = 108; - const ERR_ITEMS_COUNT_LIMIT: u64 = 109; - const ERR_STRING_TOO_LONG: u64 = 110; - - const MAX_VERSION_COUNT: u64 = 5; // Max version count for extension point. - const MAX_ITEMS_COUNT: u64 = 20; // Max items count for vector. - - const MAX_INPUT_LEN: u64 = 64; - const MAX_TEXT_LEN: u64 = 256; - - struct PluginVersion has store { - number: u64, //Numeric version number, such as 1, 2, 3 - tag: vector, //Plugin tag, e.g. v0.1.1 - implement_extpoints: vector>, //Implemented extension points - depend_extpoints: vector>, //Dependent extension points - js_entry_uri: vector, //Front-end JS code resource URI, for example: "https://cdn.xxxx.xxxx/xxxx/xxxxx.js" - created_at: u64, //Plugin creation time - } - - struct PluginRegistry has key, store { - next_plugin_id: u64, - } - - struct PluginEntry has key, store { - id: u64, //Plugin ID - name: vector, //plugin name - description: vector, //Plugin description - labels: vector>, //Plugin label - next_version_number: u64, //next version number - versions: vector, //All versions of the plugin - star_count: u64, //Star count - created_at: u64, //Plugin creation time - updated_at: u64, //Plugin last update time - } - - struct Star has key, store { - created_at: u64, //creation time - } - - fun next_plugin_id(plugin_registry: &mut PluginRegistry): u64 { - let plugin_id = plugin_registry.next_plugin_id; - plugin_registry.next_plugin_id = plugin_id + 1; - plugin_id - } - - fun next_plugin_version_number(plugin: &mut PluginEntry): u64 { - let version_number = plugin.next_version_number; - plugin.next_version_number = version_number + 1; - version_number - } - - fun assert_tag_no_repeat(v: &vector, tag:vector) { - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert!(*&e.tag != *&tag, Errors::invalid_argument(ERR_TAG_DUPLICATED)); - i = i + 1; - }; - } - - fun assert_string_length(s: &vector, max_len: u64) { - let len = Vector::length(s); - assert!(len <= max_len, Errors::invalid_argument(ERR_STRING_TOO_LONG)); - } - - fun assert_string_array_length(v: &vector>, max_item_len: u64, max_string_len: u64) { - assert!(Vector::length(v) <= max_item_len, Errors::limit_exceeded(ERR_ITEMS_COUNT_LIMIT)); - - let i = 0; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - assert_string_length(e, max_string_len); - i = i + 1; - }; - } - - /// registry event handlers - struct RegistryEventHandlers has key, store{ - register: Event::EventHandle, - } - - struct PluginRegisterEvent has drop, store{ - id: u64, - type: TypeInfo, - name: vector, - description:vector, - labels: vector> - } - - /// plugin event handlers - struct PluginEventHandlers has key, store{ - publish_version: Event::EventHandle>, - star: Event::EventHandle>, - unstar: Event::EventHandle>, - update_plugin: Event::EventHandle>, - } - - struct PluginPublishVersionEvent has drop, store{ - plugin_type: TypeInfo, - version_number: u64, - } - - struct StarPluginEvent has drop, store{ - sender: address, - } - - struct UnstarPluginEvent has drop, store{ - sender: address, - } - - struct UpdatePluginInfoEvent has drop, store{ - id: u64, - type: TypeInfo, - name: vector, - description:vector, - labels: vector> - } - - public fun initialize() { - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - - move_to(&signer, PluginRegistry{ - next_plugin_id: 1, - }); - - move_to(&signer, RegistryEventHandlers { - register: Event::new_event_handle(&signer), - }); - } - - public fun register_plugin(_witness: &PluginT, name: vector, description: vector, option_labels: Option>>): u64 - acquires PluginRegistry, RegistryEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - - assert!(!exists>(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_PLUGIN_ALREADY_EXISTS)); - let plugin_registry = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let plugin_id = next_plugin_id(plugin_registry); - - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - - let labels = if(Option::is_some(&option_labels)){ - Option::destroy_some(option_labels) - } else { - Vector::empty>() - }; - - assert_string_array_length(&labels, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - - move_to(&genesis_account, PluginEntry{ - id: copy plugin_id, - name: copy name, - description: copy description, - labels: copy labels, - next_version_number: 1, - versions: Vector::empty(), - star_count: 0, - created_at: Timestamp::now_seconds(), - updated_at: Timestamp::now_seconds(), - }); - - move_to(&genesis_account, PluginEventHandlers{ - publish_version: Event::new_event_handle>(&genesis_account), - star: Event::new_event_handle>(&genesis_account), - unstar: Event::new_event_handle>(&genesis_account), - update_plugin: Event::new_event_handle>(&genesis_account), - }); - - // registry register event emit - let registry_event_handlers = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut registry_event_handlers.register, - PluginRegisterEvent { - id: copy plugin_id, - type: TypeInfo::type_of(), - name: copy name, - description: copy description, - labels: copy labels, - }, - ); - - plugin_id - } - - public fun exists_plugin(): bool { - return exists>(CoreAddresses::GENESIS_ADDRESS()) - } - - public fun take_plugin_id(): u64 acquires PluginEntry { - let plugin = borrow_global>(CoreAddresses::GENESIS_ADDRESS()); - return plugin.id - } - - public fun publish_plugin_version( - _witness: &PluginT, - tag: vector, - implement_extpoints: vector>, - depend_extpoints: vector>, - js_entry_uri: vector, - ) acquires PluginEntry, PluginEventHandlers { - assert_string_length(&tag, MAX_INPUT_LEN); - assert_string_array_length(&implement_extpoints, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - assert_string_array_length(&depend_extpoints, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - assert_string_length(&js_entry_uri, MAX_TEXT_LEN); - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - - assert_tag_no_repeat(&plugin.versions, copy tag); - - // Remove the old version when the number of versions is greater than MAX_VERSION_COUNT - if (Vector::length(&plugin.versions) >= MAX_VERSION_COUNT) { - let oldest_version = Vector::remove(&mut plugin.versions, 0); - let PluginVersion { - number: _, - tag: _, - implement_extpoints: _, - depend_extpoints: _, - js_entry_uri: _, - created_at: _, - } = oldest_version; - }; - - let version_number = next_plugin_version_number(plugin); - Vector::push_back(&mut plugin.versions, PluginVersion{ - number: copy version_number, - tag: tag, - implement_extpoints: implement_extpoints, - depend_extpoints: depend_extpoints, - js_entry_uri: js_entry_uri, - created_at: Timestamp::now_seconds(), - }); - - plugin.updated_at = Timestamp::now_seconds(); - - // plugin register event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.publish_version, - PluginPublishVersionEvent { - plugin_type: TypeInfo::type_of(), - version_number: copy version_number, - }, - ); - } - - public fun exists_plugin_version( - version_number: u64, - ): bool acquires PluginEntry { - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - return version_number > 0 && version_number < plugin.next_version_number - } - - public fun star_plugin(sender: &signer) acquires PluginEntry, PluginEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(!exists>(sender_addr), Errors::invalid_state(ERR_STAR_ALREADY_STARED)); - - move_to(sender, Star{ - created_at: Timestamp::now_seconds(), - }); - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - plugin.star_count = plugin.star_count + 1; - plugin.updated_at = Timestamp::now_seconds(); - - // star plugin event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.star, - StarPluginEvent { - sender: sender_addr, - }, - ); - } - - public fun unstar_plugin(sender: &signer) acquires PluginEntry, Star, PluginEventHandlers { - let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::invalid_state(ERR_STAR_NOT_FOUND_STAR)); - - let star = move_from>(sender_addr); - let Star { created_at:_} = star; - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - plugin.star_count = plugin.star_count - 1; - plugin.updated_at = Timestamp::now_seconds(); - - // unstar plugin event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.unstar, - UnstarPluginEvent { - sender: sender_addr, - }, - ); - } - - public fun has_star_plugin(sender: &signer): bool { - let sender_addr = Signer::address_of(sender); - return exists>(sender_addr) - } - - public fun update_plugin(_witness: &PluginT, name: vector, description: vector, option_labels: Option>>) acquires PluginEntry, PluginEventHandlers { - assert_string_length(&name, MAX_INPUT_LEN); - assert_string_length(&description, MAX_TEXT_LEN); - - let plugin = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - - plugin.name = name; - plugin.description = description; - - if(Option::is_some(&option_labels)){ - let labels = Option::destroy_some(option_labels); - assert_string_array_length(&labels, MAX_ITEMS_COUNT, MAX_INPUT_LEN); - plugin.labels = labels; - }; - - plugin.updated_at = Timestamp::now_seconds(); - - // update plugin event emit - let plugin_event_handlers = borrow_global_mut>(CoreAddresses::GENESIS_ADDRESS()); - Event::emit_event(&mut plugin_event_handlers.update_plugin, - UpdatePluginInfoEvent { - id: *&plugin.id, - type: TypeInfo::type_of(), - name: *&plugin.name, - description: *&plugin.description, - labels: *&plugin.labels, - }, - ); - } - - // public entrys - public(script) fun star_plugin_entry(sender: signer) acquires PluginEntry, PluginEventHandlers { - star_plugin(&sender); - } - - public(script) fun unstar_plugin_entry(sender: signer) acquires PluginEntry, Star, PluginEventHandlers { - unstar_plugin(&sender); - } -} - diff --git a/sources/daospace/DAORegistry.move b/sources/daospace/DAORegistry.move deleted file mode 100644 index 6195ab6c..00000000 --- a/sources/daospace/DAORegistry.move +++ /dev/null @@ -1,57 +0,0 @@ -module StarcoinFramework::DAORegistry{ - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::Errors; - - friend StarcoinFramework::Genesis; - friend StarcoinFramework::StdlibUpgradeScripts; - friend StarcoinFramework::DAOSpace; - - spec module { - pragma verify = false; - pragma aborts_if_is_strict = true; - } - - const ERR_ALREADY_INITIALIZED: u64 = 100; - - /// Global DAO registry info - struct DAORegistry has key{ - next_dao_id: u64, - } - - /// Registry Entry for record the mapping between `DAOT` and `dao_address` - struct DAORegistryEntry has key{ - dao_id: u64, - dao_address: address, - } - - public(friend) fun initialize(){ - assert!(!exists(CoreAddresses::GENESIS_ADDRESS()), Errors::already_published(ERR_ALREADY_INITIALIZED)); - let signer = GenesisSignerCapability::get_genesis_signer(); - move_to(&signer, DAORegistry{next_dao_id: 1}) - } - - // This function should call from DAOSpace module - public(friend) fun register(dao_address: address): u64 acquires DAORegistry{ - let genesis_account = GenesisSignerCapability::get_genesis_signer(); - let dao_id = next_dao_id(); - move_to(&genesis_account, DAORegistryEntry{ - dao_id, - dao_address, - }); - dao_id - } - - fun next_dao_id(): u64 acquires DAORegistry { - let dao_registry = borrow_global_mut(CoreAddresses::GENESIS_ADDRESS()); - let dao_id = dao_registry.next_dao_id; - dao_registry.next_dao_id = dao_id + 1; - dao_id - - } - - public fun dao_address():address acquires DAORegistryEntry{ - *&borrow_global>(CoreAddresses::GENESIS_ADDRESS()).dao_address - } - -} \ No newline at end of file diff --git a/sources/daospace/DAOSpace.move b/sources/daospace/DAOSpace.move deleted file mode 100644 index 480d6636..00000000 --- a/sources/daospace/DAOSpace.move +++ /dev/null @@ -1,2608 +0,0 @@ -module StarcoinFramework::DAOSpace { - use StarcoinFramework::DAOAccount::{Self, DAOAccountCap}; - use StarcoinFramework::Account; - use StarcoinFramework::Vector; - use StarcoinFramework::NFT::{Self, NFT}; - use StarcoinFramework::NFTGallery; - use StarcoinFramework::IdentifierNFT; - use StarcoinFramework::Signer; - use StarcoinFramework::DAORegistry; - use StarcoinFramework::Token::{Self, Token}; - use StarcoinFramework::Errors; - use StarcoinFramework::Option::{Self, Option}; - use StarcoinFramework::STC::{Self, STC}; - use StarcoinFramework::Timestamp; - use StarcoinFramework::Config; - use StarcoinFramework::Event; - use StarcoinFramework::Math; - use StarcoinFramework::StarcoinVerifier; - use StarcoinFramework::StarcoinVerifier::StateProof; - use StarcoinFramework::BCS; - use StarcoinFramework::SBTVoteStrategy; - use StarcoinFramework::SnapshotUtil; - use StarcoinFramework::Block; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::EventUtil; - use StarcoinFramework::ASCII; - use StarcoinFramework::Offer; - use StarcoinFramework::TypeInfo; - - friend StarcoinFramework::StarcoinDAO; - - const MAX_PROPOSALS: u64 = 1000; - - const ERR_NO_GRANTED: u64 = 100; - const ERR_REPEAT_ELEMENT: u64 = 101; - const ERR_STORAGE_ERROR: u64 = 102; - const ERR_NFT_ERROR: u64 = 103; - const ERR_ALREADY_INIT: u64 = 104; - const ERR_TOKEN_ERROR: u64 = 105; - const ERR_DAO_EXT: u64 = 106; - - /// member - const ERR_EXPECT_MEMBER: u64 = 200; - const ERR_EXPECT_NOT_MEMBER: u64 = 201; - - /// config or arguments - const ERR_ACTION_DELAY_TOO_SMALL: u64 = 300; - const ERR_CONFIG_PARAM_INVALID: u64 = 301; - const ERR_INVALID_AMOUNT:u64 = 302; - const ERR_TOO_SMALL_TOTAL:u64 = 303; - const ERR_HAVE_SAME_GRANT:u64 = 304; - const ERR_NOT_HAVE_GRANT:u64 = 305; - - /// proposal - const ERR_PROPOSAL_STATE_INVALID: u64 = 400; - const ERR_PROPOSAL_ID_MISMATCH: u64 = 401; - const ERR_PROPOSER_MISMATCH: u64 = 402; - const ERR_PROPOSAL_NOT_EXIST: u64 = 403; - const ERR_QUORUM_RATE_INVALID: u64 = 404; - const ERR_PROPOSAL_ACTION_INDEX_NOT_EXIST: u64 = 405; - const ERR_PROPOSAL_OUT_OF_LIMIT: u64 = 406; - - /// action - const ERR_ACTION_MUST_EXIST: u64 = 500; - const ERR_ACTION_INDEX_INVALID: u64 = 501; - const ERR_PROPOSAL_ACTIONS_NOT_EXIST: u64 = 502; - - /// vote - const ERR_VOTE_STATE_MISMATCH: u64 = 600; - const ERR_VOTED_OTHERS_ALREADY: u64 = 601; - const ERR_VOTED_ALREADY: u64 = 602; - const ERR_VOTE_PARAM_INVALID: u64 = 603; - const ERR_SNAPSHOT_PROOF_PARAM_INVALID: u64 = 604; - const ERR_STATE_PROOF_VERIFY_INVALID: u64 = 605; - - /// plugin - const ERR_PLUGIN_NOT_EXIST: u64 = 700; - const ERR_PLUGIN_VERSION_NOT_EXIST: u64 = 701; - const ERR_PLUGIN_HAS_INSTALLED: u64 = 702; - const ERR_PLUGIN_NOT_INSTALLED: u64 = 703; - - /// grant - const ERR_OFFER_NOT_EXIST: u64 = 800; - const ERR_OFFER_NOT_RECEIPTOR: u64 = 801; - - /// DAO resource, every DAO has this resource at it's DAO account - struct DAO has key { - id: u64, - name: vector, - // description ipfs://xxxxx - description:vector, - dao_address: address, - next_member_id: u64, - next_proposal_id: u64, - } - - /// Configuration of the DAO. - struct DAOConfig has copy, drop, store { - /// after proposal created, how long use should wait before he can vote (in milliseconds) - voting_delay: u64, - /// how long the voting window is (in milliseconds). - voting_period: u64, - /// the quorum rate to agree on the proposal. - /// if 50% votes needed, then the voting_quorum_rate should be 50. - /// it should between (0, 100]. - voting_quorum_rate: u8, - /// how long the proposal should wait before it can be executed (in milliseconds). - min_action_delay: u64, - /// how many STC should be deposited to create a proposal. - min_proposal_deposit: u128, - } - - struct DAOCustomConfig has copy, drop, store { - config: ConfigT - } - - struct DAOAccountCapHolder has key { - cap: DAOAccountCap, - } - - - /// Capability for minting SBT. - struct DAOSBTMintCapHolder has key { - cap: Token::MintCapability, - } - - /// Capability for burning SBT. - struct DAOSBTBurnCapHolder has key { - cap: Token::BurnCapability, - } - - /// Capability for minting any tokens. - struct DAOTokenMintCapHolder has key { - cap: Token::MintCapability, - } - - /// Capability for burning any tokens. - struct DAOTokenBurnCapHolder has key { - cap: Token::BurnCapability, - } - - struct DAONFTMintCapHolder has key { - cap: NFT::MintCapability>, - } - - struct DAONFTBurnCapHolder has key { - cap: NFT::BurnCapability>, - } - - struct DAONFTUpdateCapHolder has key { - cap: NFT::UpdateCapability>, - } - - struct DAOConfigModifyCapHolder has key { - cap: Config::ModifyConfigCapability - } - - struct DAOCustomConfigModifyCapHolder has key { - cap: Config::ModifyConfigCapability - } - - /// A type describing a capability. - struct CapType has copy, drop, store { code: u8 } - - /// Create a install plugin capability type. - public fun install_plugin_cap_type(): CapType { CapType{ code: 0 } } - - /// Create a upgrade module capability type. - public fun upgrade_module_cap_type(): CapType { CapType{ code: 1 } } - - /// Create a modify dao config capability type. - public fun modify_config_cap_type(): CapType { CapType{ code: 2 } } - - /// Create a withdraw Token capability type. - public fun withdraw_token_cap_type(): CapType { CapType{ code: 3 } } - - /// Create a withdraw NFT capability type. - public fun withdraw_nft_cap_type(): CapType { CapType{ code: 4 } } - - /// Create a write data to DAO account capability type. - public fun storage_cap_type(): CapType { CapType{ code: 5 } } - - /// Create a member capability type. - /// This cap can issue DAO member NFT or update member's SBT - public fun member_cap_type(): CapType { CapType{ code: 6 } } - - /// Create a vote capability type. - public fun proposal_cap_type(): CapType { CapType{ code: 7 } } - - /// Create a grant capability type. - public fun grant_cap_type(): CapType { CapType{ code: 8 } } - - /// Create a token minting capability type. - public fun token_mint_cap_type(): CapType { CapType{code: 9 } } - - /// Create a token burning capability type. - public fun token_burn_cap_type(): CapType { CapType{code: 10 } } - - /// Creates a grant capability type. - public fun plugin_event_cap_type(): CapType { CapType{ code: 11 } } - - /// Create all capability types. - public fun all_caps(): vector { - let caps = Vector::singleton(install_plugin_cap_type()); - Vector::push_back(&mut caps, upgrade_module_cap_type()); - Vector::push_back(&mut caps, modify_config_cap_type()); - Vector::push_back(&mut caps, withdraw_token_cap_type()); - Vector::push_back(&mut caps, withdraw_nft_cap_type()); - Vector::push_back(&mut caps, storage_cap_type()); - Vector::push_back(&mut caps, member_cap_type()); - Vector::push_back(&mut caps, proposal_cap_type()); - Vector::push_back(&mut caps, grant_cap_type()); - Vector::push_back(&mut caps, token_mint_cap_type()); - Vector::push_back(&mut caps, token_burn_cap_type()); - Vector::push_back(&mut caps, plugin_event_cap_type()); - caps - } - - struct DAOInstallPluginCap has drop {} - - struct DAOUpgradeModuleCap has drop {} - - struct DAOModifyConfigCap has drop {} - - struct DAOWithdrawTokenCap has drop {} - - struct DAOWithdrawNFTCap has drop {} - - struct DAOStorageCap has drop {} - - struct DAOMemberCap has drop {} - - struct DAOProposalCap has drop {} - - struct DAOGrantCap has drop {} - - struct DAOPluginEventCap has drop {} - - struct DAOGrantWithdrawTokenKey has key, store{ - /// The total amount of tokens that can be withdrawn by this capability - total: u128, - /// The amount of tokens that have been withdrawn by this capability - withdraw: u128, - /// The time-based linear release start time, timestamp in seconds. - start_time: u64, - /// The time-based linear release period in seconds - period: u64, - } - - /// The info for DAO installed Plugin - struct InstalledPluginInfo has key { - plugin_id: u64, // The plugin id of plugin marketplace - granted_caps: vector, // The granted capabilities - } - - /// The DAO member NFT metadata - struct DAOMember has copy, store, drop { - //Member id - id: u64, - } - - /// The DAO member NFT Body, hold the SBT token - struct DAOMemberBody has store { - sbt: Token, - } - - /// Create a dao with a exists DAO account - public fun create_dao( - cap: DAOAccountCap, - name: vector, - image_data:Option::Option>, - image_url:Option::Option>, - description: vector, - config: DAOConfig - ) acquires DAOEvent { - let dao_signer = DAOAccount::dao_signer(&cap); - - let dao_address = Signer::address_of(&dao_signer); - let id = DAORegistry::register(dao_address); - ASCII::string(copy name); - let dao = DAO{ - id, - name: copy name, - description: copy description, - dao_address, - next_member_id: 1, - next_proposal_id: 1, - }; - - move_to(&dao_signer, dao); - move_to(&dao_signer, DAOAccountCapHolder{ - cap - }); - - Token::register_token(&dao_signer, 1); - let token_mint_cap = Token::remove_mint_capability(&dao_signer); - let token_burn_cap = Token::remove_burn_capability(&dao_signer); - - move_to(&dao_signer, DAOSBTMintCapHolder{ - cap: token_mint_cap, - }); - move_to(&dao_signer, DAOSBTBurnCapHolder{ - cap: token_burn_cap, - }); - - let nft_name = copy name; - let nft_description = copy name; - let basemeta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(nft_name, Option::destroy_some(image_data), nft_description) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(nft_name, Option::destroy_some(image_url), nft_description) - }else{ - NFT::new_meta(nft_name, nft_description) - }; - - - NFT::register_v2>(&dao_signer, basemeta); - let nft_mint_cap = NFT::remove_mint_capability>(&dao_signer); - move_to(&dao_signer, DAONFTMintCapHolder{ - cap: nft_mint_cap, - }); - - let nft_burn_cap = NFT::remove_burn_capability>(&dao_signer); - move_to(&dao_signer, DAONFTBurnCapHolder{ - cap: nft_burn_cap, - }); - - let nft_update_cap = NFT::remove_update_capability>(&dao_signer); - move_to(&dao_signer, DAONFTUpdateCapHolder{ - cap: nft_update_cap, - }); - - let config_modify_cap = Config::publish_new_config_with_capability(&dao_signer, config); - move_to(&dao_signer, DAOConfigModifyCapHolder{ - cap: config_modify_cap, - }); - - move_to(&dao_signer, DAOEvent { - dao_create_event: Event::new_event_handle(&dao_signer), - }); - move_to(&dao_signer ,MemberEvent{ - member_offer_event_handler: Event::new_event_handle(&dao_signer), - member_join_event_handler:Event::new_event_handle(&dao_signer), - member_quit_event_handler:Event::new_event_handle(&dao_signer), - member_revoke_event_handler:Event::new_event_handle(&dao_signer), - member_increase_sbt_event_handler:Event::new_event_handle(&dao_signer), - member_decrease_sbt_event_handler:Event::new_event_handle(&dao_signer), - }); - move_to(&dao_signer, ProposalEvent { - proposal_create_event: Event::new_event_handle(&dao_signer), - vote_event: Event::new_event_handle(&dao_signer), - proposal_action_event: Event::new_event_handle(&dao_signer), - }); - - // dao event emit - let dao_event = borrow_global_mut >(dao_address); - Event::emit_event(&mut dao_event.dao_create_event, - DAOCreatedEvent { - id, - name: copy name, - description:copy description, - dao_address, - }, - ); - } - - /// Upgrade account to DAO account and create DAO - public fun upgrade_to_dao( - sender: signer, - name: vector, - image_data:Option::Option>, - image_url:Option::Option>, - description:vector, - config: DAOConfig - ) acquires DAOEvent{ - let cap = DAOAccount::upgrade_to_dao(sender); - create_dao(cap, name, image_data, image_url, description, config) - } - - /// dao event - struct DAOEvent has key, store{ - dao_create_event:Event::EventHandle, - } - - struct DAOCreatedEvent has drop, store{ - id: u64, - name: vector, - description:vector, - dao_address: address, - } - - /// member event - struct MemberEvent has key, store{ - member_offer_event_handler:Event::EventHandle, - member_join_event_handler:Event::EventHandle, - member_quit_event_handler:Event::EventHandle, - member_revoke_event_handler:Event::EventHandle, - member_increase_sbt_event_handler:Event::EventHandle, - member_decrease_sbt_event_handler:Event::EventHandle, - } - - const MEMBER_OFFER_CREATE: u8 = 0; - const MEMBER_OFFER_REBACK: u8 = 1; - const MEMBER_OFFER_USE: u8 = 2; - - struct MemberOfferEvent has drop, store{ - /// dao id - dao_id: u64, - //type: Create: 0 / Reback: 1 / Use: 2 - type: u8, - //address - addr: address, - //image_data - image_data:Option::Option>, - //image_url - image_url:Option::Option>, - // SBT - sbt: u128, - } - - - const MEMBERJOIN_DIRECT :u8 = 0; - const MEMBERJOIN_OFFER :u8 = 1; - - struct MemberJoinEvent has drop, store{ - /// dao id - dao_id: u64, - // type: direct/offer - type: u8, - //Member id - member_id : u64, - //address - addr: address, - // SBT - sbt: u128, - } - - struct MemberRevokeEvent has drop, store{ - /// dao id - dao_id: u64, - //Member id - member_id : u64, - //address - addr: address, - // SBT - sbt: u128, - } - - struct MemberQuitEvent has drop, store{ - /// dao id - dao_id: u64, - //Member id - member_id : u64, - //address - addr: address, - // SBT - sbt: u128, - } - - struct MemberIncreaseSBTEvent has drop, store{ - //Member id - member_id : u64, - //address - addr: address, - //increase sbt amount - increase_sbt:u128 , - // SBT - sbt: u128, - } - - struct MemberDecreaseSBTEvent has drop, store{ - //Member id - member_id : u64, - //address - addr: address, - //decrease sbt amount - decrease_sbt:u128 , - // SBT - sbt: u128, - } - - // Capability support function - - /// Install plugin with DAOInstallPluginCap - public fun install_plugin(_cap: &DAOInstallPluginCap, granted_caps: vector) acquires DAOAccountCapHolder { - do_install_plugin(granted_caps); - } - - fun do_install_plugin(granted_caps: vector) acquires DAOAccountCapHolder { - assert!(DAOPluginMarketplace::exists_plugin(), Errors::invalid_state(ERR_PLUGIN_NOT_EXIST)); - assert_no_repeat(&granted_caps); - let dao_signer = dao_signer(); - let plugin_id = DAOPluginMarketplace::take_plugin_id(); - - assert!(!exists>(Signer::address_of(&dao_signer)), Errors::already_published(ERR_PLUGIN_HAS_INSTALLED)); - move_to(&dao_signer, InstalledPluginInfo{ - plugin_id: plugin_id, - granted_caps, - }); - } - - /// Uninstall plugin with DAOInstallPluginCap - public fun uninstall_plugin(_cap: &DAOInstallPluginCap) acquires DAOAccountCapHolder, InstalledPluginInfo { - do_uninstall_plugin(); - } - - fun do_uninstall_plugin() acquires DAOAccountCapHolder, InstalledPluginInfo { - assert!(DAOPluginMarketplace::exists_plugin(), Errors::invalid_state(ERR_PLUGIN_NOT_EXIST)); - - let dao_signer = dao_signer(); - let dao_address = Signer::address_of(&dao_signer); - - assert!(exists>(dao_address), Errors::already_published(ERR_PLUGIN_NOT_INSTALLED)); - let installed_plugin = move_from>(dao_address); - - let InstalledPluginInfo { - plugin_id:_, - granted_caps:_, - } = installed_plugin; - } - - // ModuleUpgrade functions - - /// Submit upgrade module plan - public fun submit_upgrade_plan(_cap: &DAOUpgradeModuleCap, package_hash: vector, version: u64, enforced: bool) acquires DAOAccountCapHolder { - let dao_account_cap = &mut borrow_global_mut(dao_address()).cap; - DAOAccount::submit_upgrade_plan(dao_account_cap, package_hash, version, enforced); - } - - // Storage capability function - - struct StorageItem has key { - item: V, - } - - /// Save the item to the storage - public fun save_to_storage(_cap: &DAOStorageCap, item: V) acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - assert!(!exists>(Signer::address_of(&dao_signer)), Errors::already_published(ERR_STORAGE_ERROR)); - move_to(&dao_signer, StorageItem{ - item - }); - } - - /// Get the item from the storage - public fun take_from_storage(_cap: &DAOStorageCap): V acquires StorageItem { - let dao_address = dao_address(); - assert!(exists>(dao_address), Errors::not_published(ERR_STORAGE_ERROR)); - let StorageItem{ item } = move_from>(dao_address); - item - } - - /// Check the item has exists in storage - public fun exists_in_storage(): bool { - exists>(dao_address()) - } - - /// Copy the item from the storage - public fun copy_from_storage(_cap: &DAOStorageCap): V acquires StorageItem { - let dao_address = dao_address(); - assert!(exists>(dao_address), Errors::not_published(ERR_STORAGE_ERROR)); - let storage_item = borrow_global>(dao_address); - *&storage_item.item - } - - // Withdraw Token capability function - - /// Withdraw the token from the DAO account - public fun withdraw_token(_cap: &DAOWithdrawTokenCap, amount: u128): Token acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - //we should extract the WithdrawCapability from account, and invoke the withdraw_with_cap ? - Account::withdraw(&dao_signer, amount) - } - - // NFT capability function - - /// Withdraw the NFT from the DAO account - public fun withdraw_nft(_cap: &DAOWithdrawNFTCap, id: u64): NFT acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - let nft = NFTGallery::withdraw(&dao_signer, id); - assert!(Option::is_some(&nft), Errors::not_published(ERR_NFT_ERROR)); - Option::destroy_some(nft) - } - - // Membership function - - struct MemeberOffer has drop, store{ - to_address: address, - image_data:Option::Option>, - image_url:Option::Option>, - init_sbt: u128 - } - - /// invite a new member to the DAO - public fun issue_member_offer(_cap: &DAOMemberCap, to_address: address, image_data:Option::Option>, image_url:Option::Option>, init_sbt: u128) acquires DAOAccountCapHolder, MemberEvent, DAO { - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let memeber_event = borrow_global_mut(dao_address); - if(is_member(to_address)){ - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_REBACK, - image_data, - image_url, - sbt: init_sbt, - }); - return - }; - - let op_index = Offer::find_offer>(dao_address, to_address); - if(Option::is_some(&op_index)){ - let MemeberOffer{ - to_address, - image_data, - image_url, - init_sbt - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_REBACK, - image_data, - image_url, - sbt: init_sbt, - }); - return - }; - - let offered = MemeberOffer { - to_address, - image_data: copy image_data, - image_url: copy image_url, - init_sbt - }; - Offer::create_v2>(&dao_signer, offered, to_address, 0); - - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_CREATE, - image_data, - image_url, - sbt: init_sbt, - }); - } - - /// Review the member offer - public fun revoke_member_offer(_cap: &DAOMemberCap, to_address: address) acquires DAOAccountCapHolder, MemberEvent, DAO { - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let op_index = Offer::find_offer>(dao_address, to_address); - let memeber_event = borrow_global_mut(dao_address); - if(Option::is_some(&op_index)){ - let MemeberOffer{ - to_address, - image_data, - image_url, - init_sbt - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_REBACK, - image_data, - image_url, - sbt: init_sbt, - }); - } - } - - /// Accept the MemberOffer and become a member - public fun accept_member_offer(sender: &signer) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent, DAONFTUpdateCapHolder { - let dao_address = dao_address(); - let op_index = Offer::find_offer>(dao_address, Signer::address_of(sender)); - assert!(Option::is_some(&op_index),1003); - let memeber_event = borrow_global_mut(dao_address); - let MemeberOffer { - to_address, - image_data, - image_url, - init_sbt - }= Offer::redeem_v2>(sender, dao_address, Option::destroy_some(op_index)); - assert!(to_address == Signer::address_of(sender), Errors::invalid_argument(ERR_OFFER_NOT_RECEIPTOR)); - Event::emit_event(&mut memeber_event.member_offer_event_handler, MemberOfferEvent { - dao_id: dao_id(dao_address), - addr:to_address, - type:MEMBER_OFFER_USE, - image_data: copy image_data, - image_url: copy image_url, - sbt: init_sbt, - }); - if(is_member(to_address)){ - increase_member_sbt(&DAOMemberCap{}, to_address, init_sbt); - }else{ - do_join_member(sender, image_data, image_url, init_sbt); - Event::emit_event(&mut memeber_event.member_join_event_handler, MemberJoinEvent { - dao_id: dao_id(dao_address), - type:MEMBERJOIN_OFFER, - member_id:Option::destroy_some(query_member_id(to_address)), - addr:to_address, - sbt: init_sbt, - }); - } - } - - public (script) fun accept_member_offer_entry(sender: signer) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent , DAONFTUpdateCapHolder { - accept_member_offer(&sender) - } - - fun do_join_member(sender: &signer, image_data:Option::Option>, image_url:Option::Option>, init_sbt: u128) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO { - let to_address = Signer::address_of(sender); - ensure_not_member(to_address); - IdentifierNFT::accept, DAOMemberBody>(sender); - let member_id = next_member_id(); - - let meta = DAOMember{ - id: member_id, - }; - - let dao_address = dao_address(); - - let token_mint_cap = &borrow_global_mut>(dao_address).cap; - let sbt = Token::mint_with_capability(token_mint_cap, init_sbt); - - let body = DAOMemberBody{ - sbt, - }; - - let dao = borrow_global(dao_address); - let nft_name = *&dao.name; - let nft_description = *&dao.name; - - let basemeta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(nft_name, Option::destroy_some(image_data), nft_description) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(nft_name, Option::destroy_some(image_url), nft_description) - }else{ - NFT::new_meta(nft_name, nft_description) - }; - let nft_mint_cap = &mut borrow_global_mut>(dao_address).cap; - - let nft = NFT::mint_with_cap_v2(dao_address, nft_mint_cap, basemeta, meta, body); - IdentifierNFT::grant_to(nft_mint_cap, to_address, nft); - } - - /// Member quit DAO by self - public (script) fun quit_member_entry(sender: signer) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO, DAOAccountCapHolder { - quit_member(&sender); - } - - /// Member quit DAO by self - public fun quit_member(sender: &signer) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO, DAOAccountCapHolder { - let member_addr = Signer::address_of(sender); - if(!is_member(member_addr)){ - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let op_index = Offer::find_offer>(dao_address, member_addr); - if(Option::is_some(&op_index)){ - Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - }; - return - }; - - let (member_id , sbt) = do_remove_member(member_addr); - let dao_address = dao_address(); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_quit_event_handler, MemberQuitEvent { - dao_id: dao_id(dao_address), - member_id, - addr:member_addr, - sbt, - }); - } - - /// Revoke membership with cap - public fun revoke_member(_cap: &DAOMemberCap, member_addr: address) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder, MemberEvent, DAO { - let (member_id , sbt) = do_remove_member(member_addr); - let dao_address = dao_address(); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_revoke_event_handler, MemberRevokeEvent { - dao_id: dao_id(dao_address), - member_id, - addr:member_addr, - sbt: sbt, - }); - } - - public fun ensure_member(member_addr:address){ - assert!(is_member(member_addr), Errors::invalid_state(ERR_EXPECT_MEMBER)); - } - - public fun ensure_not_member(member_addr:address){ - assert!(!is_member(member_addr), Errors::invalid_state(ERR_EXPECT_NOT_MEMBER)); - } - - fun do_remove_member(member_addr: address):(u64,u128) acquires DAONFTBurnCapHolder, DAOSBTBurnCapHolder { - ensure_member(member_addr); - let dao_address = dao_address(); - - let nft_burn_cap = &mut borrow_global_mut>(dao_address).cap; - let nft = IdentifierNFT::revoke, DAOMemberBody>(nft_burn_cap, member_addr); - let member_id = NFT::get_type_meta, DAOMemberBody>(&nft).id; - let DAOMemberBody{ sbt } = NFT::burn_with_cap(nft_burn_cap, nft); - let sbt_amount = Token::value(&sbt); - let token_burn_cap = &mut borrow_global_mut>(dao_address).cap; - Token::burn_with_capability(token_burn_cap, sbt); - (member_id, sbt_amount) - } - - // join member - public fun join_member_with_member_cap( - _cap: &DAOMemberCap, - sender: &signer, - image_data:Option::Option>, - image_url:Option::Option>, - init_sbt: u128 - ) acquires DAONFTMintCapHolder, DAOSBTMintCapHolder, DAO, MemberEvent { - let dao_address = dao_address(); - let memeber_event = borrow_global_mut(dao_address); - do_join_member(sender, image_data, image_url, init_sbt); - let to_address = Signer::address_of(sender); - Event::emit_event(&mut memeber_event.member_join_event_handler, MemberJoinEvent { - dao_id: dao_id(dao_address), - type:MEMBERJOIN_DIRECT, - member_id:Option::destroy_some(query_member_id(to_address)), - addr:to_address, - sbt: init_sbt, - }); - } - - /// Increment the member SBT - public fun increase_member_sbt(_cap: &DAOMemberCap, member_addr: address, amount: u128) acquires DAONFTUpdateCapHolder, DAOSBTMintCapHolder, MemberEvent { - ensure_member(member_addr); - let dao_address = dao_address(); - - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft); - let member_id = NFT::get_type_meta, DAOMemberBody>(nft).id; - - let body = NFT::borrow_body_mut_with_cap(nft_update_cap, nft); - - let token_mint_cap = &mut borrow_global_mut>(dao_address).cap; - let increase_sbt = Token::mint_with_capability(token_mint_cap, amount); - Token::deposit(&mut body.sbt, increase_sbt); - - let sbt_amount = Token::value(&body.sbt); - IdentifierNFT::return_back(borrow_nft); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_increase_sbt_event_handler, MemberIncreaseSBTEvent { - member_id, - addr:member_addr, - increase_sbt:amount, - sbt: sbt_amount, - }); - } - - /// Decrement the member SBT - public fun decrease_member_sbt(_cap: &DAOMemberCap, member_addr: address, amount: u128) acquires DAONFTUpdateCapHolder, DAOSBTBurnCapHolder, MemberEvent { - ensure_member(member_addr); - let dao_address = dao_address(); - - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft); - let member_id = NFT::get_type_meta, DAOMemberBody>(nft).id; - - let body = NFT::borrow_body_mut_with_cap(nft_update_cap, nft); - - let token_burn_cap = &mut borrow_global_mut>(dao_address).cap; - let decrease_sbt = Token::withdraw(&mut body.sbt, amount); - let sbt_amount = Token::value(&body.sbt); - - Token::burn_with_capability(token_burn_cap, decrease_sbt); - IdentifierNFT::return_back(borrow_nft); - - let memeber_event = borrow_global_mut(dao_address); - Event::emit_event(&mut memeber_event.member_decrease_sbt_event_handler, MemberDecreaseSBTEvent { - member_id, - addr:member_addr, - decrease_sbt:amount, - sbt: sbt_amount, - }); - } - - public fun set_member_image( - _cap: &DAOMemberCap, - member_addr: address, - image_data: Option::Option>, - image_url: Option::Option> - ) acquires DAONFTUpdateCapHolder { - ensure_member(member_addr); - - let dao_address = dao_address(); - - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft_mut(&mut borrow_nft); - let metadata = *NFT::get_type_meta, DAOMemberBody>(nft); - let old_basemeta = NFT::get_base_meta, DAOMemberBody>(nft); - let new_basemeta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(NFT::meta_name(old_basemeta), Option::destroy_some(image_data), NFT::meta_description(old_basemeta)) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(NFT::meta_name(old_basemeta), Option::destroy_some(image_url), NFT::meta_description(old_basemeta)) - }else{ - NFT::new_meta(NFT::meta_name(old_basemeta), NFT::meta_description(old_basemeta)) - }; - NFT::update_meta_with_cap(nft_update_cap, nft, new_basemeta, metadata); - - IdentifierNFT::return_back(borrow_nft); - } - - /// Query amount of the member SBT - public fun query_sbt(member_addr: address) - : u128 acquires DAONFTUpdateCapHolder { - if (!is_member(member_addr)) { - return 0 - }; - let dao_address = dao_address(); - - let nft_update_cap = - &mut borrow_global_mut>(dao_address).cap; - let borrow_nft = - IdentifierNFT::borrow_out, DAOMemberBody>(nft_update_cap, member_addr); - let nft = IdentifierNFT::borrow_nft(&mut borrow_nft); - let body = NFT::borrow_body(nft); - - let result = Token::value(&body.sbt); - IdentifierNFT::return_back(borrow_nft); - result - } - - /// Query member id of the member - public fun query_member_id(member_addr: address): Option::Option{ - if(!is_member(member_addr)){ - return Option::none() - }; - let nft_info = Option::destroy_some(IdentifierNFT::get_nft_info, DAOMemberBody>(member_addr)); - let (_, _, _, type_meta) = NFT::unpack_info(nft_info); - Option::some(type_meta.id) - } - /// Check the `member_addr` account is a member of DAOT - public fun is_member(member_addr: address): bool { - IdentifierNFT::owns, DAOMemberBody>(member_addr) - } - - public fun is_exist_member_offer(member_addr: address):bool{ - let dao_address = dao_address(); - Option::is_some(&Offer::find_offer>(dao_address, member_addr)) - } - - struct PluginEvent has key, store { - event_handle: Event::EventHandle, - } - - /// Plugin event - public fun init_plugin_event< - DAOT: store, - PluginT: store, - EventT: store + drop - >(_cap: &DAOPluginEventCap) acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - EventUtil::init_event(&dao_signer); - } - - public fun exist_plugin_event(): bool { - EventUtil::exist_event(dao_address()) - } - - public fun emit_plugin_event< - DAOT: store, - PluginT: store, - EventT: store + drop - >( - _cap: &DAOPluginEventCap, - event: EventT - ) { - EventUtil::emit_event(dao_address(), event); - } - - - /// Grant Event - - struct GrantEvent has key, store{ - create_grant_event_handler:Event::EventHandle, - revoke_grant_event_handler:Event::EventHandle, - withdraw_grant_event_handler:Event::EventHandle, - refund_grant_event_handler:Event::EventHandle, - } - - struct GrantCreateEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - start_time:u64, - period:u64, - now_time:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantRevokeEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantRefundEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantConfigEvent has drop, store{ - dao_id: u64, - old_grantee:address, - new_grantee:address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - struct GrantWithdrawEvent has drop, store{ - dao_id: u64, - grantee: address, - total:u128, - withdraw:u128, - start_time:u64, - period:u64, - withdraw_value:u128, - plugin: TypeInfo::TypeInfo, - token: Token::TokenCode - } - - - struct GrantInfo has copy, drop ,store{ - total:u128, - grantee: address, - withdraw:u128, - start_time:u64, - period:u64 - } - - /// Grant function - - - /// Accept grant offer by self - public fun grant_accept_offer(sender: &signer) { - let dao_address = dao_address(); - let op_index = Offer::find_offer>(dao_address, Signer::address_of(sender)); - assert!(Option::is_some(&op_index),1003); - let grant_key = Offer::redeem_v2>(sender, dao_address, Option::destroy_some(op_index)); - move_to(sender, grant_key) - } - - /// Accept grant offer by self entry - public (script) fun grant_accept_offer_entry(sender: signer) { - grant_accept_offer(&sender) - } - - /// Grant offer and init/emit a event - public fun grant_offer(_cap:&DAOGrantCap, grantee: address, total:u128, start_time:u64, period:u64) acquires DAOAccountCapHolder, GrantEvent, DAO { - let dao_signer = dao_signer(); - let dao_address = dao_address(); - - if (!exists(dao_address)){ - move_to(&dao_signer, GrantEvent{ - create_grant_event_handler:Event::new_event_handle(&dao_signer), - revoke_grant_event_handler:Event::new_event_handle(&dao_signer), - withdraw_grant_event_handler:Event::new_event_handle(&dao_signer), - refund_grant_event_handler:Event::new_event_handle(&dao_signer), - }); - }; - let grant_event = borrow_global_mut(dao_address); - - Event::emit_event(&mut grant_event.create_grant_event_handler, GrantCreateEvent { - dao_id:dao_id(dao_address), - grantee, - total, - start_time, - period, - now_time:Timestamp::now_seconds(), - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - - Offer::create_v2>( - &dao_signer, - DAOGrantWithdrawTokenKey{ - total, - withdraw: 0 , - start_time, - period - }, - grantee, - 0 - ); - } - - /// Grant offer refund - public fun grant_offer_refund(sender: &signer)acquires DAOAccountCapHolder, GrantEvent, DAO { - let dao_address = dao_address(); - let dao_signer = dao_signer(); - let grantee = Signer::address_of(sender); - let op_index = Offer::find_offer>(dao_address, grantee); - assert!(Option::is_some(&op_index), Errors::not_published(ERR_OFFER_NOT_EXIST)); - let grant_event = borrow_global_mut(dao_address); - let DAOGrantWithdrawTokenKey{ - total, - withdraw, - start_time, - period - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent { - dao_id:dao_id(dao_address), - grantee, - total, - withdraw, - start_time, - period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - } - - /// Grant offer refund entry - public (script) fun grant_offer_refund_entry(sender: signer)acquires DAOAccountCapHolder, GrantEvent, DAO{ - grant_offer_refund(&sender); - } - - /// Withdraw token with grant - public (script) fun grant_withdraw_entry(sender: signer, amount:u128) acquires DAOAccountCapHolder, DAOGrantWithdrawTokenKey, GrantEvent, DAO{ - grant_withdraw(&sender, amount); - } - - /// Withdraw token with grant - public fun grant_withdraw(sender: &signer, amount:u128) acquires DAOAccountCapHolder, DAOGrantWithdrawTokenKey, GrantEvent, DAO{ - let account_address = Signer::address_of(sender); - assert!(exists>(account_address) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - - let cap = borrow_global_mut>(account_address); - let now = Timestamp::now_seconds(); - let elapsed_time = now - cap.start_time; - let can_amount = if (elapsed_time >= cap.period) { - cap.total - cap.withdraw - } else { - Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw - }; - - assert!(can_amount > 0, Errors::invalid_argument(ERR_INVALID_AMOUNT)); - assert!(can_amount >= amount, Errors::invalid_argument(ERR_INVALID_AMOUNT)); - - let dao_signer = dao_signer(); - let dao_address = dao_address(); - - assert!(amount <= Account::balance(dao_address) , Errors::invalid_argument(ERR_INVALID_AMOUNT)); - cap.withdraw = cap.withdraw + amount; - - let grant_event = borrow_global_mut(dao_address); - Event::emit_event(&mut grant_event.withdraw_grant_event_handler, GrantWithdrawEvent { - dao_id:dao_id(dao_address), - grantee: account_address, - total:cap.total, - withdraw:cap.withdraw, - start_time:cap.start_time, - period:cap.period, - withdraw_value:amount, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - let token = Account::withdraw(&dao_signer, amount); - Account::deposit(account_address, token); - } - - public fun query_grant_withdrawable_amount(addr: address):u128 acquires DAOGrantWithdrawTokenKey{ - assert!(exists>(addr) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - let cap = borrow_global>(addr); - let now = Timestamp::now_seconds(); - let elapsed_time = now - cap.start_time; - if (elapsed_time >= cap.period) { - cap.total - cap.withdraw - } else { - Math::mul_div(cap.total, (elapsed_time as u128), (cap.period as u128)) - cap.withdraw - } - } - /// Is exist DAOGrantWithdrawTokenKey - public fun is_exist_grant(addr:address):bool{ - exists>(addr) - } - /// Revoke grant - public fun grant_revoke(_cap:&DAOGrantCap, grantee: address ) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO { - let dao_address = dao_address(); - let grant_event = borrow_global_mut(dao_address); - if(exists>(grantee)){ - let DAOGrantWithdrawTokenKey{ - total, - withdraw, - start_time, - period - } = move_from>(grantee); - - Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent { - dao_id:dao_id(dao_address), - grantee, - total, - withdraw, - start_time, - period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - }; - } - - /// Revoke grant offer - public fun grant_offer_revoke(_cap:&DAOGrantCap, grantee: address ) acquires GrantEvent, DAO, DAOAccountCapHolder { - let dao_signer = dao_signer(); - let dao_address = dao_address(); - let grant_event = borrow_global_mut(dao_address); - let op_index = Offer::find_offer>(dao_address, grantee); - if(Option::is_some(&op_index)) { - let DAOGrantWithdrawTokenKey { - total, - withdraw, - start_time, - period - } = Offer::retake>(&dao_signer, Option::destroy_some(op_index)); - Event::emit_event(&mut grant_event.revoke_grant_event_handler, GrantRevokeEvent { - dao_id: dao_id(dao_address), - grantee, - total, - withdraw, - start_time, - period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - }; - } - - /// Refund the grant - public fun refund_grant(sender: &signer) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO { - let dao_address = dao_address(); - let grantee = Signer::address_of(sender); - assert!(exists>(grantee) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - let DAOGrantWithdrawTokenKey{ - total:total, - withdraw:withdraw, - start_time:start_time, - period:period - } = move_from>(grantee); - - let grant_event = borrow_global_mut(dao_address); - Event::emit_event(&mut grant_event.refund_grant_event_handler, GrantRefundEvent { - dao_id:dao_id(dao_address), - grantee, - total:total, - withdraw:withdraw, - start_time:start_time, - period:period, - plugin: TypeInfo::type_of(), - token: Token::token_code() - }); - } - - /// Refund the grant entry - public (script) fun refund_grant_entry(sender: signer) acquires DAOGrantWithdrawTokenKey, GrantEvent, DAO { - refund_grant(&sender); - } - - /// Query address grant - public fun query_grant(addr: address): GrantInfo acquires DAOGrantWithdrawTokenKey{ - assert!(exists>(addr) , Errors::invalid_state(ERR_NOT_HAVE_GRANT)); - let cap = borrow_global>(addr); - GrantInfo{ - total : cap.total, - grantee : addr, - withdraw : cap.withdraw, - start_time : cap.start_time, - period : cap.period - } - } - - /// Query grant info total - public fun query_grant_info_total(grant_info: &GrantInfo):u128{ - grant_info.total - } - - /// Query grant info withdraw - public fun query_grant_info_withdraw(grant_info: &GrantInfo):u128{ - grant_info.withdraw - } - - /// Query grant info start_time - public fun query_grant_info_start_time(grant_info: &GrantInfo):u64{ - grant_info.start_time - } - - /// Query grant info period - public fun query_grant_info_period(grant_info: &GrantInfo):u64{ - grant_info.period - } - - /// Acquiring Capabilities - fun validate_cap(cap: CapType) acquires InstalledPluginInfo { - let addr = dao_address(); - // When create a new DAO, one can pass a `DAOT` type as the `PluginT` type, - // in this case, the signer is equal to have the root cap. - if (TypeInfo::type_of() != TypeInfo::type_of()) { - if (exists>(addr)) { - let plugin_info = borrow_global>(addr); - assert!(Vector::contains(&plugin_info.granted_caps, &cap), Errors::requires_capability(ERR_NO_GRANTED)); - } else { - abort (Errors::requires_capability(ERR_NO_GRANTED)) - } - } - } - - /// Acquire the installed plugin capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_install_plugin_cap(_witness: &PluginT): DAOInstallPluginCap acquires InstalledPluginInfo { - validate_cap(install_plugin_cap_type()); - DAOInstallPluginCap{} - } - - /// Acquire the upgrade module capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_upgrade_module_cap(_witness: &PluginT): DAOUpgradeModuleCap acquires InstalledPluginInfo { - validate_cap(upgrade_module_cap_type()); - DAOUpgradeModuleCap{} - } - - /// Acquire the modify config capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_modify_config_cap(_witness: &PluginT): DAOModifyConfigCap acquires InstalledPluginInfo { - validate_cap(modify_config_cap_type()); - DAOModifyConfigCap{} - } - - /// Acquires the withdraw Token capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_withdraw_token_cap(_witness: &PluginT): DAOWithdrawTokenCap acquires InstalledPluginInfo { - validate_cap(withdraw_token_cap_type()); - DAOWithdrawTokenCap{} - } - - /// Acquires the withdraw NFT capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_withdraw_nft_cap(_witness: &PluginT): DAOWithdrawNFTCap acquires InstalledPluginInfo { - validate_cap(withdraw_nft_cap_type()); - DAOWithdrawNFTCap{} - } - - /// Acquires the storage capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_storage_cap(_witness: &PluginT): DAOStorageCap acquires InstalledPluginInfo { - validate_cap(storage_cap_type()); - DAOStorageCap{} - } - - /// Acquires the membership capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_member_cap(_witness: &PluginT): DAOMemberCap acquires InstalledPluginInfo { - validate_cap(member_cap_type()); - DAOMemberCap{} - } - - /// Acquire the proposql capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_proposal_cap(_witness: &PluginT): DAOProposalCap acquires InstalledPluginInfo { - validate_cap(proposal_cap_type()); - DAOProposalCap{} - } - - /// Acquire the grant capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_grant_cap(_witness: &PluginT): DAOGrantCap acquires InstalledPluginInfo { - validate_cap(grant_cap_type()); - DAOGrantCap{} - } - - - /// Acquire the plugin event capability - /// _witness parameter ensures that the caller is the module which define PluginT - public fun acquire_plugin_event_cap(_witness: &PluginT): DAOPluginEventCap acquires InstalledPluginInfo { - validate_cap(plugin_event_cap_type()); - DAOPluginEventCap {} - } - - /// Delegate the token mint capability to DAO - /// _witness parameter ensures that the caller is the module which define PluginT - public fun delegate_token_mint_cap(cap: Token::MintCapability, _witness: &PluginT) - acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - move_to>( - &dao_signer, - DAOTokenMintCapHolder { cap }, - ); - } - - /// Delegate the token burn capability to DAO - /// _witness parameter ensures that the caller is the module which define PluginT - public fun delegate_token_burn_cap(cap: Token::BurnCapability, _witness: &PluginT) - acquires DAOAccountCapHolder { - let dao_signer = dao_signer(); - move_to>( - &dao_signer, - DAOTokenBurnCapHolder { cap }, - ); - } - - /// Mint token - public fun mint_token(amount: u128, _witness: &PluginT): Token - acquires InstalledPluginInfo, DAOTokenMintCapHolder { - validate_cap(token_mint_cap_type()); - let dao_addr = dao_address(); - assert!(exists>(dao_addr), Errors::not_published(ERR_TOKEN_ERROR)); - let DAOTokenMintCapHolder { cap } = - borrow_global>(dao_addr); - let tokens = Token::mint_with_capability(cap, amount); - tokens - } - - /// Burn token - public fun burn_token(tokens: Token, _witness: &PluginT) - acquires InstalledPluginInfo, DAOTokenBurnCapHolder { - validate_cap(token_burn_cap_type()); - let dao_addr = dao_address(); - assert!(exists>(dao_addr), Errors::not_published(ERR_TOKEN_ERROR)); - let DAOTokenBurnCapHolder { cap } = - borrow_global>(dao_addr); - Token::burn_with_capability(cap, tokens); - } - - /// Proposal - /// -------------------------------------------------- - /// Proposal state - const PENDING: u8 = 1; - const ACTIVE: u8 = 2; - const REJECTED: u8 = 3; - const DEFEATED: u8 = 4; - const AGREED: u8 = 5; - const QUEUED: u8 = 6; - const EXECUTABLE: u8 = 7; - const EXTRACTED: u8 = 8; - - struct ProposalState has copy, drop, store { state: u8 } - - /// voting choice: 1:yes, 2:no, 3: no_with_veto, 4:abstain - const VOTING_CHOICE_YES: u8 = 1; - const VOTING_CHOICE_NO: u8 = 2; - // Review: How to prevent spam, cosmos provide a NO_WITH_VETO option, and the proposer need deposit some Token when create proposal. - // this choice from https://docs.cosmos.network/master/modules/gov/01_concepts.html - const VOTING_CHOICE_NO_WITH_VETO: u8 = 3; - const VOTING_CHOICE_ABSTAIN: u8 = 4; - - struct VotingChoice has copy, drop, store { - choice: u8, - } - - public fun choice_yes(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_YES } } - - public fun choice_no(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_NO } } - - /// no_with_veto counts as no but also adds a veto vote - public fun choice_no_with_veto(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_NO_WITH_VETO } } - - public fun choice_abstain(): VotingChoice { VotingChoice{ choice: VOTING_CHOICE_ABSTAIN } } - - /// Proposal data struct. - /// review: it is safe to has `copy` and `drop`? - struct Proposal has store, copy, drop { - /// id of the proposal - id: u64, - /// creator of the proposal - proposer: address, - /// title of proposal - title: vector, - /// introduction of proposal , short introduction - introduction:vector, - /// extend of proposal , ipfs:// | { "title":"xxxxx",........ } - extend:vector, - /// when voting begins. - start_time: u64, - /// when voting ends. - end_time: u64, - /// count of voters who `yes|no|abstain` with the proposal - yes_votes: u128, - no_votes: u128, - abstain_votes: u128, - /// no_with_veto counts as no but also adds a veto vote - no_with_veto_votes: u128, - /// executable after this time. - eta: u64, - /// after how long, the agreed proposal can be executed. - action_delay: u64, - /// how many votes to reach to make the proposal valid. - quorum_votes: u128, - /// the block number when submit proposal - block_number: u64, - /// the state root of the block which has the block_number - state_root: vector, - } - - struct ProposalAction has store { - /// id of the proposal - proposal_id: u64, - //To prevent spam, proposals must be submitted with a deposit - deposit: Token, - /// proposal action. - action: Action, - } - - struct ProposalActionIndex has store, drop { - /// id of the proposal - proposal_id: u64, - } - - /// Keep a global proposal record for query proposal by id. - /// Replace with Table when support Table. - struct GlobalProposals has key { - proposals: vector, - } - - /// Every ActionT keep a vector in the DAO account - struct ProposalActions has key { - actions: vector>, - } - - - /// Keep a global proposal action record for query action by proposal_id. - /// Replace with Table when support Table. - struct GlobalProposalActions has key { - proposal_action_indexs: vector, - } - - /// User vote. - struct Vote has store { - /// proposal id. - proposal_id: u64, - /// vote weight - vote_weight: u128, - /// vote choise - choice: u8, - } - - /// User vote info. has drop cap - struct VoteInfo has store, drop { - /// proposal id. - proposal_id: u64, - /// vote weight - vote_weight: u128, - /// vote choise - choice: u8, - } - - /// Every voter keep a vector Vote for per DAO - struct MyVotes has key { - votes: vector, - } - - /// use bcs se/de for Snapshot proofs - struct SnapshotProof has store, drop, copy { - state: vector, - account_state: vector, - account_proof_leaf: HashNode, - account_proof_siblings: vector>, - account_state_proof_leaf: HashNode, - account_state_proof_siblings: vector>, - } - - struct HashNode has store, drop, copy { - hash1: vector, - hash2: vector, - } - - /// proposal event - struct ProposalEvent has key, store { - /// proposal creating event. - proposal_create_event: Event::EventHandle, - /// voting event. - vote_event: Event::EventHandle, - /// proposal action event. - proposal_action_event: Event::EventHandle, - } - - /// emitted when proposal created. - struct ProposalCreatedEvent has drop, store { - /// dao id - dao_id: u64, - /// title - title: vector, - /// the proposal id. - proposal_id: u64, - /// introduction of proposal , short introduction - introduction:vector, - /// extend of proposal , ipfs:// | { "title":"xxxxx",........ } - extend: vector, - /// proposer is the user who create the proposal. - proposer: address, - } - - /// emitted when user vote/revoke_vote. - struct VotedEvent has drop, store { - /// dao id - dao_id: u64, - /// the proposal id. - proposal_id: u64, - /// the voter. - voter: address, - /// 1:yes, 2:no, 3:no_with_veto, 4:abstain - choice: u8, - /// latest vote count of the voter. - // vote_amount: u128, - vote_weight: u128, - } - - /// emitted when proposal executed. - struct ProposalActionEvent has drop, store { - /// dao id - dao_id: u64, - /// the proposal id. - proposal_id: u64, - /// the sender. - sender: address, - /// proposal state after the action: EXTRACTED or REJECTED - state: u8, - } - - /// propose a proposal. - /// `title`: title of the proposal - /// `introduction`: short introduction of the proposal - /// `extend`: extend of proposal , ipfs:// | { "title":"xxxxx",........ } - /// `action`: the actual action to execute. - /// `action_delay`: the delay to execute after the proposal is agreed - /// `quorum_scale_factor`: used to scale up the base quorum_votes_rate. - /// The final quorum_votes_rate = (1.0 + scale / 100) * quorum_votes_rate - public fun create_proposal( - _cap: &DAOProposalCap, - sender: &signer, - action: ActionT, - title: vector, - introduction: vector, - extend: vector, - action_delay: u64, - quorum_scale_factor: Option::Option, - ): u64 acquires DAO, GlobalProposals, DAOAccountCapHolder, ProposalActions, ProposalEvent, GlobalProposalActions { - // check DAO member - let sender_addr = Signer::address_of(sender); - ensure_member(sender_addr); - - if (action_delay == 0) { - action_delay = min_action_delay(); - } else { - assert!(action_delay >= min_action_delay(), Errors::invalid_argument(ERR_ACTION_DELAY_TOO_SMALL)); - }; - - let min_proposal_deposit = min_proposal_deposit(); - let deposit = Account::withdraw(sender, min_proposal_deposit); - - let proposal_id = next_proposal_id(); - let proposer = Signer::address_of(sender); - let start_time = Timestamp::now_milliseconds() + voting_delay(); - let quorum_votes = quorum_votes(quorum_scale_factor); - let voting_period = voting_period(); - - let (block_number,state_root) = block_number_and_state_root(); - - let proposal = Proposal { - id: proposal_id, - proposer, - title: copy title, - introduction: copy introduction, - extend: copy extend, - start_time, - end_time: start_time + voting_period, - yes_votes: 0, - no_votes: 0, - abstain_votes: 0, - no_with_veto_votes: 0, - eta: 0, - action_delay, - quorum_votes, - block_number, - state_root, - }; - let proposal_action = ProposalAction{ - proposal_id, - deposit, - action, - }; - let proposal_action_index = ProposalActionIndex{ - proposal_id, - }; - - let dao_signer = dao_signer(); - let dao_address = dao_address(); - - let actions = Vector::singleton(proposal_action); - // check ProposalActions is exists - if(exists>(dao_address)){ - let current_actions = borrow_global_mut>(dao_address); - assert!(Vector::length(¤t_actions.actions) < MAX_PROPOSALS, Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT)); - Vector::append(&mut current_actions.actions, actions); - }else{ - move_to(&dao_signer, ProposalActions{ - actions, - }); - }; - - let proposal_action_indexs = Vector::singleton(proposal_action_index); - // check GlobalProposalActions is exists - if(exists(dao_address)){ - let current_global_proposal_actions = borrow_global_mut(dao_address); - assert!(Vector::length(¤t_global_proposal_actions.proposal_action_indexs) < MAX_PROPOSALS, - Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT)); - Vector::append(&mut current_global_proposal_actions.proposal_action_indexs, proposal_action_indexs); - }else{ - move_to(&dao_signer, GlobalProposalActions{ - proposal_action_indexs, - }); - }; - - let proposals = Vector::singleton(proposal); - // check GlobalProposals is exists - if(exists(dao_address)){ - let current_global_proposals = borrow_global_mut(dao_address); - assert!(Vector::length(¤t_global_proposals.proposals) < MAX_PROPOSALS, - Errors::limit_exceeded(ERR_PROPOSAL_OUT_OF_LIMIT)); - Vector::append(&mut current_global_proposals.proposals, proposals); - }else{ - move_to(&dao_signer, GlobalProposals{ - proposals, - }); - }; - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut>(dao_address); - Event::emit_event(&mut proposal_event.proposal_create_event, - ProposalCreatedEvent { dao_id, proposal_id, title, introduction: copy introduction, extend: copy extend, proposer }, - ); - - proposal_id - } - - /// get lastest block number and state root - fun block_number_and_state_root(): (u64, vector) { - Block::latest_state_root() - } - - - /// votes for a proposal. - /// User can only vote once, then the stake is locked, - /// The voting power depends on the strategy of the proposal configuration and the user's token amount at the time of the snapshot - public fun cast_vote( - sender: &signer, - proposal_id: u64, - snpashot_raw_proofs: vector, - choice: VotingChoice, - ) acquires GlobalProposals, MyVotes, ProposalEvent, GlobalProposalActions, DAO { - let sender_addr = Signer::address_of(sender); - ensure_member(sender_addr); - - let dao_address = dao_address(); - let proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal_mut(proposals, proposal_id); - - { - let state = proposal_state_with_proposal(proposal); - // only when proposal is active, use can cast vote. - assert!(state == ACTIVE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - }; - - // verify snapshot state proof - let snapshot_proof = deserialize_snapshot_proofs(&snpashot_raw_proofs); - let state_proof = new_state_proof_from_proofs(&snapshot_proof); - let resource_struct_tag = SnapshotUtil::get_sturct_tag(); - // verify state_proof according to proposal snapshot proofs, and state root - let verify = StarcoinVerifier::verify_state_proof(&state_proof, &proposal.state_root, sender_addr, &resource_struct_tag, &snapshot_proof.state); - assert!(verify, Errors::invalid_state(ERR_STATE_PROOF_VERIFY_INVALID)); - - // decode sbt value from snapshot state - let vote_weight = SBTVoteStrategy::get_voting_power(&snapshot_proof.state); - - assert!(!has_voted(sender_addr, proposal_id), Errors::invalid_state(ERR_VOTED_ALREADY)); - - let vote = Vote{ - proposal_id, - vote_weight, - choice: choice.choice, - }; - - do_cast_vote(proposal, &mut vote); - - if (exists>(sender_addr)) { - assert!(vote.proposal_id == proposal_id, Errors::invalid_argument(ERR_VOTED_OTHERS_ALREADY)); - let my_votes = borrow_global_mut>(sender_addr); - Vector::push_back(&mut my_votes.votes, vote); - } else { - move_to(sender, MyVotes{ - votes: Vector::singleton(vote), - }); - }; - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut >(DAORegistry::dao_address()); - Event::emit_event(&mut proposal_event.vote_event, - VotedEvent { - dao_id, - proposal_id, - voter: sender_addr, - choice: choice.choice, - vote_weight, - }, - ); - } - -// pub struct StateWithProofView { -// pub state: Option>>, -// pub account_state: Option>>, -// pub account_proof: SparseMerkleProofView, -// pub account_state_proof: SparseMerkleProofView, -// } - -// pub struct SparseMerkleProofView { -// /// This proof can be used to authenticate whether a given leaf exists in the tree or not. -// /// - If this is `Some(HashValue, HashValue)` -// /// - If the first `HashValue` equals requested key, this is an inclusion proof and the -// /// second `HashValue` equals the hash of the corresponding account blob. -// /// - Otherwise this is a non-inclusion proof. The first `HashValue` is the only key -// /// that exists in the subtree and the second `HashValue` equals the hash of the -// /// corresponding account blob. -// /// - If this is `None`, this is also a non-inclusion proof which indicates the subtree is -// /// empty. -// pub leaf: Option<(HashValue, HashValue)>, -// -// /// All siblings in this proof, including the default ones. Siblings are ordered from the bottom -// /// level to the root level. -// pub siblings: Vec, -// } - fun deserialize_snapshot_proofs(snpashot_raw_proofs: &vector): SnapshotProof{ - assert!(Vector::length(snpashot_raw_proofs) > 0, Errors::invalid_argument(ERR_SNAPSHOT_PROOF_PARAM_INVALID)); - let offset= 0; - let (state_option, offset) = BCS::deserialize_option_bytes(snpashot_raw_proofs, offset); - let (account_state_option, offset) = BCS::deserialize_option_bytes(snpashot_raw_proofs, offset); - - let (account_proof_leaf1_option, account_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(snpashot_raw_proofs, offset); - let account_proof_leaf1 = Option::get_with_default(&mut account_proof_leaf1_option, Vector::empty()); - let account_proof_leaf2 = Option::get_with_default(&mut account_proof_leaf2_option, Vector::empty()); - let (account_proof_siblings, offset) = BCS::deserialize_bytes_vector(snpashot_raw_proofs, offset); - - let (account_state_proof_leaf1_option, account_state_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(snpashot_raw_proofs, offset); - let account_state_proof_leaf1 = Option::get_with_default(&mut account_state_proof_leaf1_option, Vector::empty()); - let account_state_proof_leaf2 = Option::get_with_default(&mut account_state_proof_leaf2_option, Vector::empty()); - let (account_state_proof_siblings, _offset) = BCS::deserialize_bytes_vector(snpashot_raw_proofs, offset); - - SnapshotProof { - state: Option::get_with_default(&mut state_option, Vector::empty()), - account_state: Option::get_with_default(&mut account_state_option, Vector::empty()), - account_proof_leaf: HashNode { - hash1: account_proof_leaf1, - hash2: account_proof_leaf2, - }, - account_proof_siblings, - account_state_proof_leaf: HashNode { - hash1: account_state_proof_leaf1, - hash2: account_state_proof_leaf2, - }, - account_state_proof_siblings, - } - } - - fun new_state_proof_from_proofs(snpashot_proofs: &SnapshotProof): StateProof{ - let state_proof = StarcoinVerifier::new_state_proof( - StarcoinVerifier::new_sparse_merkle_proof( - *&snpashot_proofs.account_proof_siblings, - StarcoinVerifier::new_smt_node( - *&snpashot_proofs.account_proof_leaf.hash1, - *&snpashot_proofs.account_proof_leaf.hash2, - ), - ), - *&snpashot_proofs.account_state, - StarcoinVerifier::new_sparse_merkle_proof( - *&snpashot_proofs.account_state_proof_siblings, - StarcoinVerifier::new_smt_node( - *&snpashot_proofs.account_state_proof_leaf.hash1, - *&snpashot_proofs.account_state_proof_leaf.hash2, - ), - ), - ); - state_proof - } - - #[test] - fun test_snapshot_proof() { - // barnard, block number 6201718 - let snpashot_raw_proofs = x"0145016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f64617461005704000000000000640000000000000000000000000000000145020120cc969848619e507450ebf01437155ab5f2dbb554fe611cb71958855a1b2ec664012035f2374c333a51e46b62b693ebef25b9be2cefde8d156db08bff28f9a0b87742012073837fcf4e69ae60e18ea291b9f25c86ce8053c6ee647a2b287083327c67dd7e20dac300fb581a6df034a44a99e8eb1cd55c7dd8f0a9e78f1114a6b4eda01d834e0e2078179a07914562223d40068488a0d65673b3b2681642633dc33904575f8f070b20b7c2a21de200ca82241e5e480e922258591b219dd56c24c4d94299020ee8299a204f541db82477510f699c9d75dd6d8280639a1ec9d0b90962cbc0c2b06514a78b20cacfce99bb564cfb70eec6a61bb76b9d56eb1b626d7fa231338792e1f572a8df20da6c1337ca5d8f0fa18b2db35844c610858a710edac35206ef0bf52fd32a4ac920ef6fb8f82d32ca2b7c482b7942505e6492bffa3ed14dd635bae16a14b4ac32e6202ad7b36e08e7b5d208de8eec1ef1964dc8433ccca8ac4632f36054926e858ac32027d5ccc8aa57b964ad50334f62821188b89945ae999ad0bb31cdc16df1763f8120afa983813953d6aa9563db12d5e443c9e8114c3482867c95a661a240d6f0e0ec206466ac318f5d9deb7b64b12622a0f4bed2f19379667d18b6ccfeaa84171d812f20eb45021b7b39887925a5b49018cdc8ad44c14835a42e5775666315f4a3e0ba42204c2b365a78e4615873772a0f039a7326150472b4923d40640863dbe42a2351eb20825d0c21dd1105faf528934842419f8661d695fc72ec6ef8036f5d03359126d3205d806c027eecdfbc3960e68c5997718a0709a6079f96e1af3ffe21878ada2b830120fa60f8311936961f5e9dee5ccafaea83ed91c6eaa04a7dea0b85a38cf84d8564207ef6a85019523861474cdf47f4db8087e5368171d95cc2c1e57055a72ca39cb704208db1e4e4c864882bd611b1cda02ca30c43b3c7bc56ee7cb174598188da8b49ef2063b3f1e4f05973830ba40e0c50c4e59f31d3baa5643d19676ddbacbf797bf6b720b39d31107837c1751d439706c8ddac96f8c148b8430ac4f40546f33fb9871e4320fb0ad035780bb8f1c6481bd674ccad0948cd2e8e6b97c08e582f67cc26918fb3"; - let state_root = x"d5cd5dc44799c989a84b7d4a810259f373b13a9bf8ee21ecbed0fab264e2090d"; - let account_address = @0x6bfb460477adf9dd0455d3de2fc7f211; - // 0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - let resource_struct_tag = x"000000000000000000000000000000010d4964656e7469666965724e46540d4964656e7469666965724e465402076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650944616f4d656d62657201076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650d44616f4d656d626572426f647901076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00"; - - let snapshot_proof = deserialize_snapshot_proofs(&snpashot_raw_proofs); - let state_proof = new_state_proof_from_proofs(&snapshot_proof); - - let b = StarcoinVerifier::verify_state_proof( - &state_proof, - &state_root, - account_address, - &resource_struct_tag, - &snapshot_proof.state, - ); - assert!(b, 8006); - } - - - // Execute the proposal and return the action. - public fun execute_proposal( - _cap: &DAOProposalCap, - sender: &signer, - proposal_id: u64, - ): ActionT acquires ProposalActions, GlobalProposals, GlobalProposalActions, ProposalEvent, DAO { - // Only executable proposal's action can be extracted. - assert!(proposal_state(proposal_id) == EXECUTABLE, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - let dao_address = dao_address(); - let sender_addr = Signer::address_of(sender); - assert!(exists>(dao_address), Errors::invalid_state(ERR_PROPOSAL_ACTIONS_NOT_EXIST)); - - let (actionT, deposit) = take_proposal_action(dao_address, proposal_id); - - let global_proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal(global_proposals, proposal_id); - - Account::deposit(proposal.proposer, deposit); - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut>(dao_address); - Event::emit_event(&mut proposal_event.proposal_action_event, - ProposalActionEvent { dao_id, proposal_id, sender: sender_addr, state: EXTRACTED } - ); - - actionT - } - - // Clean proposals that have been rejected or executed. - public fun clean_proposals(_sender: &signer) - acquires GlobalProposals, GlobalProposalActions { - let dao_address = dao_address(); - let global_proposals = borrow_global_mut(dao_address); - - let i = 0; - let len = Vector::length(&global_proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&global_proposals.proposals, i); - let state = proposal_state_with_proposal(proposal); - if (state == EXTRACTED || state == REJECTED) { - let _ = Vector::remove(&mut global_proposals.proposals, i); - len = len - 1; - } else { - i = i + 1; - } - }; - } - - public (script) fun clean_proposals_entry(sender: signer) - acquires GlobalProposals, GlobalProposalActions { - clean_proposals(&sender); - } - - // Clean specific proposal by proposal id, only for rejected or executed proposals - public fun clean_proposal_by_id(_sender: &signer, proposal_id: u64) - acquires GlobalProposals, GlobalProposalActions { - let dao_address = dao_address(); - let global_proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal(global_proposals, proposal_id); - let state = proposal_state_with_proposal(proposal); - assert!(state == EXTRACTED || state == REJECTED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - - let _ = remove_proposal(global_proposals, proposal_id); - } - - public (script) fun clean_proposal_by_id_entry(sender: signer, proposal_id: u64) - acquires GlobalProposals, GlobalProposalActions { - clean_proposal_by_id(&sender, proposal_id) - } - - fun take_proposal_action(dao_address: address, proposal_id: u64): (ActionT, Token) - acquires ProposalActions, GlobalProposalActions { - let actions = borrow_global_mut>(dao_address); - let index_opt = find_action(&actions.actions, proposal_id); - assert!(Option::is_some(&index_opt), Errors::invalid_argument(ERR_ACTION_INDEX_INVALID)); - - let index = Option::extract(&mut index_opt); - let ProposalAction{ proposal_id:_, deposit, action} = Vector::remove(&mut actions.actions, index); - - // remove proposal action index - let global_proposal_actions = borrow_global_mut(dao_address); - let proposal_action_index_opt = find_proposal_action_index(global_proposal_actions, proposal_id); - assert!(Option::is_some(&proposal_action_index_opt), Errors::invalid_argument(ERR_PROPOSAL_ACTION_INDEX_NOT_EXIST)); - let propopsal_action_index = Option::extract(&mut proposal_action_index_opt); - let ProposalActionIndex{ proposal_id:_,} = Vector::remove(&mut global_proposal_actions.proposal_action_indexs, propopsal_action_index); - - (action, deposit) - } - - fun remove_proposal(proposals: &mut GlobalProposals, proposal_id: u64): Proposal { - let i = 0; - let len = Vector::length(&proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&proposals.proposals, i); - if(proposal.id == proposal_id){ - let proposal = Vector::remove(&mut proposals.proposals, i); - return proposal - }; - i = i + 1; - }; - abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST) - } - - fun find_action(actions: &vector>, proposal_id: u64): Option{ - let i = 0; - let len = Vector::length(actions); - while(i < len){ - let action = Vector::borrow(actions, i); - if(action.proposal_id == proposal_id){ - return Option::some(i) - }; - i = i + 1; - }; - Option::none() - } - - fun do_cast_vote(proposal: &mut Proposal, vote: &mut Vote){ - if (choice_yes().choice == vote.choice) { - proposal.yes_votes = proposal.yes_votes + vote.vote_weight; - } else if (choice_no().choice == vote.choice) { - proposal.no_votes = proposal.no_votes + vote.vote_weight; - } else if ( choice_no_with_veto().choice == vote.choice) { - proposal.no_with_veto_votes = proposal.no_with_veto_votes + vote.vote_weight; - } else if (choice_abstain().choice == vote.choice) { - proposal.abstain_votes = proposal.abstain_votes + vote.vote_weight; - } else { - abort Errors::invalid_argument(ERR_VOTE_PARAM_INVALID) - }; - } - - fun has_voted(sender: address, proposal_id: u64): bool acquires MyVotes{ - if(exists>(sender)){ - let my_votes = borrow_global>(sender); - let vote = vote_info(my_votes, proposal_id); - Option::is_some(&vote) - }else{ - false - } - } - - /// vote info by proposal_id - fun vote_info(my_votes: &MyVotes, proposal_id: u64): Option{ - let len = Vector::length(&my_votes.votes); - let idx = 0; - loop { - if (idx >= len) { - break - }; - let vote = Vector::borrow(&my_votes.votes, idx); - if (proposal_id == vote.proposal_id) { - let vote_info = VoteInfo { - proposal_id: vote.proposal_id, - vote_weight: vote.vote_weight, - choice: vote.choice, - }; - return Option::some(vote_info) - }; - idx = idx + 1; - }; - Option::none() - } - - /// Proposals are rejected when their nowithveto option reaches a certain threshold - /// A portion of the pledged tokens will be rewarded to the executor who executes the proposal - public fun reject_proposal(sender: &signer, proposal_id: u64) - acquires DAO, ProposalEvent, ProposalActions, GlobalProposals, GlobalProposalActions{ - // Only REJECTED proposal's action can be burn token. - assert!(proposal_state(proposal_id) == REJECTED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - let dao_address = dao_address(); - assert!(exists>(dao_address), Errors::invalid_state(ERR_PROPOSAL_ACTIONS_NOT_EXIST)); - let (_, token) = take_proposal_action(dao_address, proposal_id); - // Part of the token is awarded to whoever executes this method , current: 10 % - let award_amount = Token::value(&token) / 10; - let (burn_token , award_token) = Token::split(token, award_amount); - Account::deposit(Signer::address_of(sender), award_token); - STC::burn(burn_token); - - // emit event - let dao_id = dao_id(dao_address); - let proposal_event = borrow_global_mut>(dao_address); - Event::emit_event(&mut proposal_event.proposal_action_event, - ProposalActionEvent { dao_id, proposal_id, sender: Signer::address_of(sender), state: REJECTED } - ); - } - - public (script) fun reject_proposal_entry(sender: signer, proposal_id: u64) - acquires DAO, ProposalEvent, ProposalActions, GlobalProposals, GlobalProposalActions{ - reject_proposal(&sender, proposal_id); - } - - /// get vote info by proposal_id - public fun get_vote_info(voter: address, proposal_id: u64): (u64, u8, u128)acquires MyVotes { - if(exists>(voter)){ - let my_votes = borrow_global>(voter); - let vote_option = vote_info(my_votes, proposal_id); - if(!Option::is_some(&vote_option)){ - return (0, 0, 0) - }; - let vote = Option::extract(&mut vote_option); - (vote.proposal_id, vote.choice, vote.vote_weight) - }else{ - (0, 0, 0) - } - } - - public fun proposal_state(proposal_id: u64) : u8 acquires GlobalProposalActions, GlobalProposals { - let dao_address = dao_address(); - let proposals = borrow_global(dao_address); - let proposal = borrow_proposal(proposals, proposal_id); - - proposal_state_with_proposal(proposal) - } - - fun proposal_state_with_proposal(proposal: &Proposal) : u8 acquires GlobalProposalActions { - let dao_address = dao_address(); - let current_time = Timestamp::now_milliseconds(); - - let global_proposal_actions = borrow_global(dao_address); - let action_index_opt = find_proposal_action_index(global_proposal_actions, proposal.id); - - do_proposal_state(proposal, current_time, action_index_opt) - } - - fun do_proposal_state(proposal: &Proposal, current_time: u64, action_index_opt: Option): u8 { - if (current_time < proposal.start_time) { - // Pending - PENDING - } else if (current_time <= proposal.end_time) { - // Active - ACTIVE - } else if (proposal.no_with_veto_votes >= (proposal.no_votes + proposal.yes_votes) ){ - // rejected - REJECTED - } else if (proposal.yes_votes <= (proposal.no_votes + proposal.no_with_veto_votes) || - ( proposal.yes_votes + proposal.no_votes + proposal.abstain_votes + proposal.no_with_veto_votes ) < proposal.quorum_votes) { - // Defeated - DEFEATED - } else if (proposal.eta == 0) { - // Agreed. - AGREED - } else if (current_time < proposal.eta) { - // Queued, waiting to execute - QUEUED - } else if (Option::is_some(&action_index_opt)) { - EXECUTABLE - } else { - EXTRACTED - } - } - - fun borrow_proposal_mut(proposals: &mut GlobalProposals, proposal_id: u64): &mut Proposal{ - let i = 0; - let len = Vector::length(&proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&proposals.proposals, i); - if(proposal.id == proposal_id){ - return Vector::borrow_mut(&mut proposals.proposals, i) - }; - i = i + 1; - }; - abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST) - } - - fun borrow_proposal(proposals: &GlobalProposals, proposal_id: u64): &Proposal { - let i = 0; - let len = Vector::length(&proposals.proposals); - while(i < len){ - let proposal = Vector::borrow(&proposals.proposals, i); - if(proposal.id == proposal_id){ - return proposal - }; - i = i + 1; - }; - abort Errors::invalid_argument(ERR_PROPOSAL_NOT_EXIST) - } - - fun find_proposal_action_index(global_proposal_action: &GlobalProposalActions, proposal_id: u64): Option { - let i = 0; - let len = Vector::length(&global_proposal_action.proposal_action_indexs); - while(i < len){ - let proposal_action_index = Vector::borrow(&global_proposal_action.proposal_action_indexs, i); - if(proposal_action_index.proposal_id == proposal_id){ - return Option::some(i) - }; - i = i + 1; - }; - Option::none() - } - - /// Return a copy of Proposal of proposal_id - public fun proposal(proposal_id: u64): Proposal acquires GlobalProposals{ - let dao_address = dao_address(); - let global_proposals = borrow_global(dao_address); - *borrow_proposal(global_proposals, proposal_id) - } - - /// get proposal's id. - public fun proposal_id(proposal: &Proposal): u64 { - proposal.id - } - - /// get proposal's proposer. - public fun proposal_proposer(proposal: &Proposal): address { - proposal.proposer - } - - /// get proposal's time(start_time/end_time). - public fun proposal_time(proposal: &Proposal): (u64, u64) { - (proposal.start_time,proposal.end_time) - } - - /// get proposal's votes(Yes/No/Abstain/Veto). - public fun proposal_votes(proposal: &Proposal): (u128, u128, u128, u128) { - (proposal.yes_votes, proposal.no_votes, proposal.abstain_votes, proposal.no_with_veto_votes) - } - - /// get proposal's block number. - public fun proposal_block_number(proposal: &Proposal): u64 { - proposal.block_number - } - - /// get proposal's state root. - public fun proposal_state_root(proposal: &Proposal): vector { - *&proposal.state_root - } - - /// queue agreed proposal to execute. - public(script) fun queue_proposal_action_entry( - _signer: signer, - proposal_id: u64, - ) acquires GlobalProposalActions, GlobalProposals { - queue_proposal_action(proposal_id) - } - - /// queue agreed proposal to execute. - public fun queue_proposal_action( - proposal_id: u64, - ) acquires GlobalProposalActions, GlobalProposals { - // Only agreed proposal can be submitted. - assert!(proposal_state(proposal_id) == AGREED, Errors::invalid_state(ERR_PROPOSAL_STATE_INVALID)); - let dao_address = dao_address(); - let proposals = borrow_global_mut(dao_address); - let proposal = borrow_proposal_mut(proposals, proposal_id); - proposal.eta = Timestamp::now_milliseconds() + proposal.action_delay; - } - - public(script) fun cast_vote_entry( - sender: signer, - proposal_id: u64, - snpashot_raw_proofs: vector, - choice: u8, - ) acquires MyVotes, GlobalProposals, ProposalEvent, GlobalProposalActions, DAO { - let sender_addr = Signer::address_of(&sender); - if (has_voted(sender_addr, proposal_id)) { - abort Errors::invalid_state(ERR_VOTED_ALREADY) - }; - - let vote_choice = VotingChoice { - choice, - }; - cast_vote(&sender, proposal_id, snpashot_raw_proofs, vote_choice) - } - - /// DAOConfig - /// --------------------------------------------------- - - /// create a dao config - public fun new_dao_config( - voting_delay: u64, - voting_period: u64, - voting_quorum_rate: u8, - min_action_delay: u64, - min_proposal_deposit: u128, - ): DAOConfig{ - assert!(voting_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - assert!(voting_period > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - assert!( - voting_quorum_rate > 0 && voting_quorum_rate <= 100, - Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID), - ); - assert!(min_action_delay > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - DAOConfig { voting_delay, voting_period, voting_quorum_rate, min_action_delay, min_proposal_deposit } - } - - // Get config - public fun get_custom_config(): ConfigT { - let dao_address = dao_address(); - Config::get_by_address(dao_address) - } - - // Get config - public fun exists_custom_config(): bool { - let dao_address = dao_address(); - Config::config_exist_by_address(dao_address) - } - - /// Update, save function of custom plugin configuration - public fun set_custom_config( - _cap: &mut DAOModifyConfigCap, - config: ConfigT) - acquires DAOCustomConfigModifyCapHolder, DAOAccountCapHolder { - let dao_address = dao_address(); - if (Config::config_exist_by_address(dao_address)) { - let cap_holder = - borrow_global_mut>(dao_address); - let modify_config_cap = &mut cap_holder.cap; - Config::set_with_capability(modify_config_cap, config); - } else { - let signer = dao_signer(); - move_to(&signer, DAOCustomConfigModifyCapHolder { - cap: Config::publish_new_config_with_capability(&signer, config) - }); - } - } - - //StarcoinDAO add Config cap - public (friend) fun set_custom_config_cap( - config_cap: Config::ModifyConfigCapability) - acquires DAOAccountCapHolder{ - let signer = dao_signer(); - move_to(&signer, DAOCustomConfigModifyCapHolder { - cap: config_cap - }); - } - - /// Update DAO description - public fun set_dao_description( - _cap: &mut DAOModifyConfigCap, - description: vector) - acquires DAO{ - let dao_address = dao_address(); - let dao = borrow_global_mut(dao_address); - dao.description = description; - } - - - /// Update DAO NFT image - public fun set_dao_image( - _cap: &mut DAOModifyConfigCap, - image_data:Option::Option>, - image_url:Option::Option>) - acquires DAONFTUpdateCapHolder{ - let dao_address = dao_address(); - let nft_update_cap = &mut borrow_global_mut>(dao_address).cap; - let old_meta = NFT::nft_type_info_meta>(); - let new_meta = if(Option::is_some(&image_data)){ - NFT::new_meta_with_image_data(NFT::meta_name(&old_meta), Option::destroy_some(image_data), NFT::meta_description(&old_meta)) - }else if(Option::is_some(&image_url)){ - NFT::new_meta_with_image(NFT::meta_name(&old_meta), Option::destroy_some(image_url), NFT::meta_description(&old_meta)) - }else{ - NFT::new_meta(NFT::meta_name(&old_meta), NFT::meta_description(&old_meta)) - }; - NFT::update_nft_type_info_meta_with_cap>(nft_update_cap, new_meta); - } - - /// get default voting delay of the DAO. - public fun voting_delay(): u64 { - get_config().voting_delay - } - - /// get the default voting period of the DAO. - public fun voting_period(): u64 { - get_config().voting_period - } - - /// Quorum votes to make proposal valid. - public fun quorum_votes(scale_factor: Option::Option): u128 { - let scale_factor = if (Option::is_none(&scale_factor)) { - 0u8 - } else { - Option::extract(&mut scale_factor) - }; - assert!( - scale_factor >= 0 && scale_factor <= 100, - Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID), - ); - - let market_cap = Token::market_cap(); - let rate = (voting_quorum_rate() as u128); - let rate = rate + rate * (scale_factor as u128) / 100; - assert!( - rate > 0 && rate <= 100, - Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID), - ); - market_cap * rate / 100 - } - - /// Get the quorum rate in percent. - public fun voting_quorum_rate(): u8 { - get_config().voting_quorum_rate - } - - /// Get the min action delay of the DAO. - public fun min_action_delay(): u64 { - get_config().min_action_delay - } - - /// Get the min proposal deposit of the DAO. - public fun min_proposal_deposit(): u128{ - get_config().min_proposal_deposit - } - - fun get_config(): DAOConfig { - let dao_address= dao_address(); - Config::get_by_address(dao_address) - } - - /// Update function, modify dao config. - public fun modify_dao_config( - _cap: &mut DAOModifyConfigCap, - new_config: DAOConfig, - ) acquires DAOConfigModifyCapHolder { - let modify_config_cap = &mut borrow_global_mut( - dao_address(), - ).cap; - Config::set_with_capability(modify_config_cap, new_config); - } - - /// set voting delay - public fun set_voting_delay( - config: &mut DAOConfig, - value: u64, - ) { - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - config.voting_delay = value; - } - - /// set voting period - public fun set_voting_period( - config: &mut DAOConfig, - value: u64, - ) { - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - config.voting_period = value; - } - - /// set voting quorum rate - public fun set_voting_quorum_rate( - config: &mut DAOConfig, - value: u8, - ) { - assert!(value <= 100 && value > 0, Errors::invalid_argument(ERR_QUORUM_RATE_INVALID)); - config.voting_quorum_rate = value; - } - - /// set min action delay - public fun set_min_action_delay( - config: &mut DAOConfig, - value: u64, - ) { - assert!(value > 0, Errors::invalid_argument(ERR_CONFIG_PARAM_INVALID)); - config.min_action_delay = value; - } - - /// set min action delay - public fun set_min_proposal_deposit( - config: &mut DAOConfig, - value: u128, - ) { - config.min_proposal_deposit = value; - } - - - /// Helpers - /// --------------------------------------------------- - - - fun next_member_id(): u64 acquires DAO { - let dao_address = dao_address(); - let dao = borrow_global_mut(dao_address); - let member_id = dao.next_member_id; - dao.next_member_id = member_id + 1; - member_id - } - - fun next_proposal_id(): u64 acquires DAO { - let dao_address = dao_address(); - let dao = borrow_global_mut(dao_address); - let proposal_id = dao.next_proposal_id; - dao.next_proposal_id = proposal_id + 1; - proposal_id - } - - fun assert_no_repeat(v: &vector) { - let i = 1; - let len = Vector::length(v); - while (i < len) { - let e = Vector::borrow(v, i); - let j = 0; - while (j < i) { - let f = Vector::borrow(v, j); - assert!(e != f, Errors::invalid_argument(ERR_REPEAT_ELEMENT)); - j = j + 1; - }; - i = i + 1; - }; - } - - #[test] - fun test_assert_no_repeat() { - let v = Vector::singleton(1); - Vector::push_back(&mut v, 2); - Vector::push_back(&mut v, 3); - assert_no_repeat(&v); - } - - #[test] - #[expected_failure] - fun test_assert_no_repeat_fail() { - let v = Vector::singleton(1); - Vector::push_back(&mut v, 2); - Vector::push_back(&mut v, 3); - Vector::push_back(&mut v, 1); - assert_no_repeat(&v); - } - - /// Helper to remove an element from a vector. - fun remove_element(v: &mut vector, x: &E) { - let (found, index) = Vector::index_of(v, x); - if (found) { - Vector::remove(v, index); - } - } - - /// Helper to add an element to a vector. - fun add_element(v: &mut vector, x: E) { - if (!Vector::contains(v, &x)) { - Vector::push_back(v, x) - } - } - - fun convert_option_bytes_vector(input: &vector>>): vector> { - let len = Vector::length(input); - let i = 0; - let output = Vector::empty>(); - while (i < len) { - let option = Vector::borrow(input, i); - if (Option::is_some(option)){ - Vector::push_back(&mut output, Option::extract(&mut *option)); - }; - i = i + 1; - }; - output - } - - fun dao_signer(): signer acquires DAOAccountCapHolder { - let cap = &borrow_global(dao_address()).cap; - DAOAccount::dao_signer(cap) - } - - public fun dao_address(): address { - DAORegistry::dao_address() - } - - public fun dao_id(dao_address: address): u64 acquires DAO { - if (exists(dao_address)){ - let dao = borrow_global(dao_address); - dao.id - }else{ - 0 - } - } -} \ No newline at end of file diff --git a/sources/daospace/SBTVoteStrategy.move b/sources/daospace/SBTVoteStrategy.move deleted file mode 100644 index 8279771e..00000000 --- a/sources/daospace/SBTVoteStrategy.move +++ /dev/null @@ -1,100 +0,0 @@ -module StarcoinFramework::SBTVoteStrategy{ - use StarcoinFramework::BCS; - #[test_only] - use StarcoinFramework::Debug; - use StarcoinFramework::Vector; - - const ERR_BCS_STATE_NTFS_LENGHT_TYPE_INVALID: u64 = 1413; - - /// deserialize snapshot vote value from state - public fun get_voting_power(state: &vector) : u128 { - let sbt_value = deserialize_sbt_value_from_bcs_state(state); - sbt_value - } - -// struct NFT has store { -// /// The creator of NFT -// creator: address, -// /// The unique id of NFT under NFTMeta type -// id: u64, -// /// The metadata of NFT -// base_meta: Metadata, -// /// The extension metadata of NFT -// type_meta: NFTMeta, -// /// The body of NFT, NFT is a box for NFTBody -// body: NFTBody, -// } -// -// struct Metadata has copy, store, drop { -// /// NFT name's utf8 bytes. -// name: vector, -// /// Image link, such as ipfs://xxxx -// image: vector, -// /// Image bytes data, image or image_data can not empty for both. -// image_data: vector, -// /// NFT description utf8 bytes. -// description: vector, -// } - - /// deserialize sbt value from bcs state - public fun deserialize_sbt_value_from_bcs_state(state: &vector) : u128{ - let len = Vector::length(state); - if (len == 0) { - return 0u128 - }; - - // nfts array length - let offset = 0; - let (nfts_len, offset) = BCS::deserialize_u8(state, offset); - // user has no sbt yet - if (nfts_len == 0) { - return 0u128 - }; - - offset = BCS::skip_address(state, offset); - offset = BCS::skip_u64(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_bytes(state, offset); - offset = BCS::skip_u64(state, offset); - let (value, _offset) = BCS::deserialize_u128(state, offset); - - value - } - - - #[test] - fun test_deserialize_sbt_value_from_bcs_state() { - // https://stcscan.io/barnard/address/0x6bfb460477adf9dd0455d3de2fc7f211/resources - // 0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>, 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - // {"json":{"nft":{"vec":[{"base_meta":{"description":"0x","image":"0x","image_data":"0x69616d67655f64617461","name":"0x64616f313031"},"body":{"sbt":{"value":100}},"creator":"0x6bfb460477adf9dd0455d3de2fc7f211","id":1,"type_meta":{"id":1111}}]}},"raw":"0x016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"} - let bs = x"016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"; - Debug::print>(&bs); - let offset = 0; - - // array length - offset = BCS::skip_u8(&bs, offset); - // creator - offset = BCS::skip_address(&bs, offset); - // id - offset = BCS::skip_u64(&bs, offset); - Debug::print(&offset); - // base_meta - offset = BCS::skip_bytes(&bs, offset); - offset = BCS::skip_bytes(&bs, offset); - offset = BCS::skip_bytes(&bs, offset); - offset = BCS::skip_bytes(&bs, offset); - // type_meta - offset = BCS::skip_u64(&bs, offset); - Debug::print(&offset); - // body - let (sbt_value, offset) = BCS::deserialize_u128(&bs, offset); - Debug::print(&sbt_value); - Debug::print(&offset); - let expect_sb_value = 100; - assert!(expect_sb_value == sbt_value, 8003); - Debug::print(&b"testdao02"); - } - -} \ No newline at end of file diff --git a/sources/daospace/SnapshotUtil.move b/sources/daospace/SnapshotUtil.move deleted file mode 100644 index 0bef2789..00000000 --- a/sources/daospace/SnapshotUtil.move +++ /dev/null @@ -1,393 +0,0 @@ -module StarcoinFramework::SnapshotUtil{ - #[test_only] - use StarcoinFramework::Option; - use StarcoinFramework::Token; - #[test_only] - use StarcoinFramework::Debug; - use StarcoinFramework::Vector; - use StarcoinFramework::BCS; - - #[test] - fun test_snapshot_proof_deserialize() { - // barnard, block number 6201718 - let snpashot_raw_proofs = x"0145016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f64617461005704000000000000640000000000000000000000000000000145020120cc969848619e507450ebf01437155ab5f2dbb554fe611cb71958855a1b2ec664012035f2374c333a51e46b62b693ebef25b9be2cefde8d156db08bff28f9a0b87742012073837fcf4e69ae60e18ea291b9f25c86ce8053c6ee647a2b287083327c67dd7e20dac300fb581a6df034a44a99e8eb1cd55c7dd8f0a9e78f1114a6b4eda01d834e0e2078179a07914562223d40068488a0d65673b3b2681642633dc33904575f8f070b20b7c2a21de200ca82241e5e480e922258591b219dd56c24c4d94299020ee8299a204f541db82477510f699c9d75dd6d8280639a1ec9d0b90962cbc0c2b06514a78b20cacfce99bb564cfb70eec6a61bb76b9d56eb1b626d7fa231338792e1f572a8df20da6c1337ca5d8f0fa18b2db35844c610858a710edac35206ef0bf52fd32a4ac920ef6fb8f82d32ca2b7c482b7942505e6492bffa3ed14dd635bae16a14b4ac32e6202ad7b36e08e7b5d208de8eec1ef1964dc8433ccca8ac4632f36054926e858ac32027d5ccc8aa57b964ad50334f62821188b89945ae999ad0bb31cdc16df1763f8120afa983813953d6aa9563db12d5e443c9e8114c3482867c95a661a240d6f0e0ec206466ac318f5d9deb7b64b12622a0f4bed2f19379667d18b6ccfeaa84171d812f20eb45021b7b39887925a5b49018cdc8ad44c14835a42e5775666315f4a3e0ba42204c2b365a78e4615873772a0f039a7326150472b4923d40640863dbe42a2351eb20825d0c21dd1105faf528934842419f8661d695fc72ec6ef8036f5d03359126d3205d806c027eecdfbc3960e68c5997718a0709a6079f96e1af3ffe21878ada2b830120fa60f8311936961f5e9dee5ccafaea83ed91c6eaa04a7dea0b85a38cf84d8564207ef6a85019523861474cdf47f4db8087e5368171d95cc2c1e57055a72ca39cb704208db1e4e4c864882bd611b1cda02ca30c43b3c7bc56ee7cb174598188da8b49ef2063b3f1e4f05973830ba40e0c50c4e59f31d3baa5643d19676ddbacbf797bf6b720b39d31107837c1751d439706c8ddac96f8c148b8430ac4f40546f33fb9871e4320fb0ad035780bb8f1c6481bd674ccad0948cd2e8e6b97c08e582f67cc26918fb3"; - // let state_root = x"d5cd5dc44799c989a84b7d4a810259f373b13a9bf8ee21ecbed0fab264e2090d"; - // let account_address = @0x6bfb460477adf9dd0455d3de2fc7f211; - // // 0x00000000000000000000000000000001::Account::Balance<0x8c109349c6bd91411d6bc962e080c4a3::STAR::STAR> - // let resource_struct_tag = x"00000000000000000000000000000001074163636f756e740742616c616e636501078c109349c6bd91411d6bc962e080c4a30453544152045354415200"; - - let offset = 0; - let (state_option, offset) = BCS::deserialize_option_bytes(&snpashot_raw_proofs, offset); - let state = Option::get_with_default(&mut state_option, Vector::empty()); - Debug::print(&state); -// Debug::print(&x"016bfb460477adf9dd0455d3de2fc7f21101000000000000000664616f313031000a69616d67655f6461746100570400000000000064000000000000000000000000000000"); - Debug::print(&offset); - let (_account_state_option, offset) = BCS::deserialize_option_bytes(&snpashot_raw_proofs, offset); - let _account_state = Option::get_with_default(&mut _account_state_option, Vector::empty()); - Debug::print(&110110); - Debug::print(&_account_state); - Debug::print(&offset); - - let (_account_proof_leaf1_option, _account_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(&snpashot_raw_proofs, offset); - let _account_proof_leaf1 = Option::get_with_default(&mut _account_proof_leaf1_option, Vector::empty()); - let _account_proof_leaf2 = Option::get_with_default(&mut _account_proof_leaf2_option, Vector::empty()); - Debug::print(&offset); - - let account_proof_leaf_nodes = Vector::empty>(); - Vector::push_back(&mut account_proof_leaf_nodes, x"73837fcf4e69ae60e18ea291b9f25c86ce8053c6ee647a2b287083327c67dd7e"); - Vector::push_back(&mut account_proof_leaf_nodes, x"dac300fb581a6df034a44a99e8eb1cd55c7dd8f0a9e78f1114a6b4eda01d834e"); - Debug::print(&account_proof_leaf_nodes); - Debug::print(&_account_proof_leaf1); - Debug::print(&_account_proof_leaf2); - Debug::print(&offset); - let (_account_proof_siblings, offset) = BCS::deserialize_bytes_vector(&snpashot_raw_proofs, offset); - - let (_account_state_proof_leaf1_option, _account_state_proof_leaf2_option, offset) = BCS::deserialize_option_tuple(&snpashot_raw_proofs, offset); - let _account_state_proof_leaf1 = Option::get_with_default(&mut _account_state_proof_leaf1_option, Vector::empty()); - let _account_state_proof_leaf2 = Option::get_with_default(&mut _account_state_proof_leaf2_option, Vector::empty()); - Debug::print(&_account_state_proof_leaf1); - Debug::print(&_account_state_proof_leaf2); - let (_account_state_proof_siblings, _offset) = BCS::deserialize_bytes_vector(&snpashot_raw_proofs, offset); - - Debug::print(&_account_state_proof_siblings); - Debug::print(&_offset); - } - - #[test] - fun test_snapshot_proof_deserialize_with_empty_state() { - let snpashot_raw_proofs = x"00012402000120161d07d221d7b31df7d29d45926b6444fa07e8b5f1021dd704fc1def6738011d0120e76e5b4bcf07c7e3864b399cfca72b0863678487813a1cfe8df48cf35729def820f135bf4b03034b8a3c21950231d3c4fe8136442064c9809d593e78ed4775f0b6042072659a01138c59e84e8e608e0d1908be7289c47f8f4080a14eaa852d1ace35f420bb3f0cc0cde2e05ba56a26bbc15161a930af6f66a65091b285870c557e8bc07a205350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000204bb30b63b4c41126a2f8c98a3d66f351160732481ae633da47d647976004942e000420fbd31ef1cbaf26c37259325e5ee71625e67f7ecf8311cbf67758431d65ae8f5c205350415253455f4d45524b4c455f504c414345484f4c4445525f484153480000207460a35efdba40ce6ec4442b32e0bf39fee59a69887e18f118f49b325434fda820417ddaf2cf3fce9b50dd9b16e1ea545d65d480b855bfd0aed0a819a6a7d0f641"; - - let offset = 0; - let (state_option, offset) = BCS::deserialize_option_bytes(&snpashot_raw_proofs, offset); - Debug::print(&state_option); - let state = Option::get_with_default(&mut state_option, Vector::empty()); - Debug::print(&state); - Debug::print(&offset); - } - - /// Struct Tag which identify a unique Struct. - struct StructTag0 has drop,copy,store { - addr: address, - module_name: vector, - name: vector, - types: vector, - } - - struct TypeTag0 has drop,copy,store { - variant_index: u8, // struct type tag variant index, must set be 7 - struct_tag: StructTag0, - } - - struct StructTag1 has drop,copy,store { - addr: address, - module_name: vector, - name: vector, - types: vector, - } - - struct TypeTag1 has drop,copy,store { - variant_index: u8, // struct type tag variant index, must set be 7 - struct_tag: StructTag1, - } - - struct StructTag2 has drop,copy,store { - addr: address, - module_name: vector, - name: vector, - types: vector, - } - - public fun get_sturct_tag(): vector { - let struct_tags = generate_struct_tag(); - BCS::to_bytes(&struct_tags) - } - - // 0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>, 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - fun generate_struct_tag(): StructTag2{ - let dao_struct_tag = get_dao_struct_tag(); - let dao_type_tag = TypeTag0 { - variant_index: 7, - struct_tag: dao_struct_tag, - }; - let dao_type_tags = Vector::empty(); - Vector::push_back(&mut dao_type_tags, dao_type_tag); - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember - let dao_member_struct_tag = StructTag1 { - addr: @0x00000000000000000000000000000001, - module_name: b"DAOSpace", - name: b"DAOMember", - types: *&dao_type_tags - }; - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody - let dao_member_body_struct_tag = StructTag1 { - addr: @0x00000000000000000000000000000001, - module_name: b"DAOSpace", - name: b"DAOMemberBody", - types: *&dao_type_tags - }; - - let dao_member_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_struct_tag, - }; - let dao_member_body_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_body_struct_tag, - }; - let type_tags = Vector::empty(); - Vector::push_back(&mut type_tags, dao_member_type_tag); - Vector::push_back(&mut type_tags, dao_member_body_type_tag); - - StructTag2 { - addr: @0x00000000000000000000000000000001, - module_name: b"IdentifierNFT", - name: b"IdentifierNFT", - types: type_tags, - } - } - - fun get_dao_struct_tag(): StructTag0{ - // DAOT is also TokenT - let token_code = Token::token_code(); - let token_code_bcs = BCS::to_bytes(&token_code); - - let offset = 0; - let (address, offset) = BCS::deserialize_address(&token_code_bcs, offset); - let (module_name, offset) = BCS::deserialize_bytes(&token_code_bcs, offset); - let (name, _offset) = BCS::deserialize_bytes(&token_code_bcs, offset); - - StructTag0 { - addr: address, - module_name, - name, - types: Vector::empty(), - } - } - - #[test] - fun test_get_sturct_tag_bcs() { - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO - let dao_struct_tag = StructTag0 { - addr: @0x6bfb460477adf9dd0455d3de2fc7f211, - module_name: b"SBTModule", - name: b"SbtTestDAO", - types: Vector::empty(), - }; - - let dao_type_tag = TypeTag0 { - variant_index: 7, - struct_tag: dao_struct_tag, - }; - let dao_type_tags = Vector::empty(); - Vector::push_back(&mut dao_type_tags, dao_type_tag); - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMember - let dao_member_struct_tag = StructTag1 { - addr: @0x6bfb460477adf9dd0455d3de2fc7f211, - module_name: b"SBTModule", - name: b"DAOMember", - types: *&dao_type_tags - }; - - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DAOMemberBody - let dao_member_body_struct_tag = StructTag1 { - addr: @0x6bfb460477adf9dd0455d3de2fc7f211, - module_name: b"SBTModule", - name: b"DAOMemberBody", - types: *&dao_type_tags - }; - - let dao_member_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_struct_tag, - }; - let dao_member_body_type_tag = TypeTag1 { - variant_index: 7, - struct_tag: dao_member_body_struct_tag, - }; - let type_tags = Vector::empty(); - Vector::push_back(&mut type_tags, dao_member_type_tag); - Vector::push_back(&mut type_tags, dao_member_body_type_tag); - - let struct_tags = StructTag2 { - addr: @0x00000000000000000000000000000001, - module_name: b"IdentifierNFT", - name: b"IdentifierNFT", - types: type_tags, - }; - - let resource_struct_tags = BCS::to_bytes(&struct_tags); - Debug::print(&resource_struct_tags); - let expect_resource_struct_tags = x"000000000000000000000000000000010d4964656e7469666965724e46540d4964656e7469666965724e465402076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650944414f4d656d62657201076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650d44414f4d656d626572426f647901076bfb460477adf9dd0455d3de2fc7f211095342544d6f64756c650a5362745465737444414f00"; - Debug::print(&expect_resource_struct_tags); - - Debug::print(&b"IdentifierNFT"); - Debug::print(&x"6bfb460477adf9dd0455d3de2fc7f211"); - Debug::print(&b"SBTModule"); - Debug::print(&b"DAOMember"); - Debug::print(&b"DAOMemberBody"); - - assert!(expect_resource_struct_tags == resource_struct_tags, 8010); - } - - // "0x6bfb460477adf9dd0455d3de2fc7f211/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>,0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>>" - public fun get_access_path(user_addr: address): vector { - - // 0x6bfb460477adf9dd0455d3de2fc7f211/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT< - // 0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO> - // ,0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>> - - let access_path_slice_0 = b"/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT"; - let access_path_bytes = Vector::empty(); - Vector::append(&mut access_path_bytes, address_to_hex_string(*&user_addr)); - Vector::append(&mut access_path_bytes, access_path_slice_0); - Vector::append(&mut access_path_bytes, b"<"); - Vector::append(&mut access_path_bytes, get_access_path_dao_member_slice()); - Vector::append(&mut access_path_bytes, b","); - Vector::append(&mut access_path_bytes, get_access_path_dao_member_body_slice()); - Vector::append(&mut access_path_bytes, b">"); - - access_path_bytes - } - - #[test] - fun test_get_access_path(){ - let user_addr = @0x6bfb460477adf9dd0455d3de2fc7f211; - - let module_addr = @0x6bfb460477adf9dd0455d3de2fc7f211; - let struct_tag_slice = Vector::empty(); - Vector::append(&mut struct_tag_slice, address_to_hex_string(*&module_addr)); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, b"SBTModule"); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, b"SbtTestDAO"); - - - let dao_member_slice_0 = b"0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember"; - let dao_member_slice = Vector::empty(); - Vector::append(&mut dao_member_slice, dao_member_slice_0); - Vector::append(&mut dao_member_slice, b"<"); - Vector::append(&mut dao_member_slice, copy struct_tag_slice); - Vector::append(&mut dao_member_slice, b">"); - - let dao_member_body_slice_0 = b"0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody"; - let dao_member_body_slice = Vector::empty(); - Vector::append(&mut dao_member_body_slice, dao_member_body_slice_0); - Vector::append(&mut dao_member_body_slice, b"<"); - Vector::append(&mut dao_member_body_slice, copy struct_tag_slice); - Vector::append(&mut dao_member_body_slice, b">"); - - - - let access_path_slice_0 = b"/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT"; - let access_path_bytes = Vector::empty(); - Vector::append(&mut access_path_bytes, address_to_hex_string(*&user_addr)); - Vector::append(&mut access_path_bytes, access_path_slice_0); - Vector::append(&mut access_path_bytes, b"<"); - Vector::append(&mut access_path_bytes, dao_member_slice); - Vector::append(&mut access_path_bytes, b","); - Vector::append(&mut access_path_bytes, dao_member_body_slice); - Vector::append(&mut access_path_bytes, b">"); - - let expect_access_path = b"0x6bfb460477adf9dd0455d3de2fc7f211/1/0x00000000000000000000000000000001::IdentifierNFT::IdentifierNFT<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMember<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>,0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::DaoMemberBody<0x6bfb460477adf9dd0455d3de2fc7f211::SBTModule::SbtTestDAO>>"; - Debug::print(&expect_access_path); - Debug::print(&access_path_bytes); - assert!(expect_access_path == access_path_bytes, 8012); - } - - - fun get_access_path_dao_member_slice(): vector{ - let dao_member_slice_0 = b"0x00000000000000000000000000000001::DAOSpace::DAOMember"; - let slice = Vector::empty(); - Vector::append(&mut slice, dao_member_slice_0); - Vector::append(&mut slice, b"<"); - Vector::append(&mut slice, struct_tag_to_string()); - Vector::append(&mut slice, b">"); - - slice - } - - - fun get_access_path_dao_member_body_slice(): vector{ - let dao_member_body_slice_0 = b"0x00000000000000000000000000000001::DAOSpace::DAOMemberBody"; - let slice = Vector::empty(); - Vector::append(&mut slice, dao_member_body_slice_0); - Vector::append(&mut slice, b"<"); - Vector::append(&mut slice, struct_tag_to_string()); - Vector::append(&mut slice, b">"); - - slice - } - - fun struct_tag_to_string(): vector { - let struct_tag = get_dao_struct_tag(); - let struct_tag_slice = Vector::empty(); - Vector::append(&mut struct_tag_slice, address_to_hex_string(*&struct_tag.addr)); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, *&struct_tag.module_name); - Vector::append(&mut struct_tag_slice, b"::"); - Vector::append(&mut struct_tag_slice, *&struct_tag.name); - - struct_tag_slice - } - - const HEX_SYMBOLS: vector = b"0123456789abcdef"; - - /// Converts a `u8` to its hexadecimal representation with fixed length (in whole bytes). - /// so the returned String is `2 * length` in size - public fun to_hex_string_without_prefix(value: u8): vector { - if (value == 0) { - return b"00" - }; - - let buffer = Vector::empty(); - let len = 1; - let i: u64 = 0; - while (i < len * 2) { - Vector::push_back(&mut buffer, *Vector::borrow(&HEX_SYMBOLS, (value & 0xf as u64))); - value = value >> 4; - i = i + 1; - }; - assert!(value == 0, 1); - Vector::reverse(&mut buffer); - buffer - } - - /// Converts a `address` to its hexadecimal representation with fixed length (in whole bytes). - /// so the returned String is `2 * length + 2`(with '0x') in size - fun address_to_hex_string(addr: address): vector{ - let hex_string = Vector::empty(); - Vector::append(&mut hex_string, b"0x"); - let addr_bytes = BCS::to_bytes
(&addr); - let i = 0; - let len = Vector::length(&addr_bytes); - while (i < len) { - let hex_slice = to_hex_string_without_prefix(*Vector::borrow(&addr_bytes, i)); - Vector::append(&mut hex_string, hex_slice); - i = i + 1; - }; - hex_string - } - - #[test] - fun test_address_to_byte(){ - let user_addr = @0x6bfb460477adf9dd0455d3de2fc7f211; - let user_addr_b = b"0x6bfb460477adf9dd0455d3de2fc7f211"; - let user_addr_hex = address_to_hex_string(user_addr); - Debug::print(&user_addr); - Debug::print(&user_addr_b); - Debug::print(&user_addr_hex); - - let str1 = b"0x6bfb460477adf9dd0455d3de2fc7f211/1/"; - let str2 = Vector::empty(); - Vector::append(&mut str2, user_addr_hex); - Vector::append(&mut str2, b"/1/"); - Debug::print(&str1); - Debug::print(&str2); - assert!(str1 == str2, 8013) - } - - -} \ No newline at end of file diff --git a/sources/daospaceplugin/AnyMemberPlugin.move b/sources/daospaceplugin/AnyMemberPlugin.move deleted file mode 100644 index 36fb4c45..00000000 --- a/sources/daospaceplugin/AnyMemberPlugin.move +++ /dev/null @@ -1,73 +0,0 @@ -/// This plugin let every can join the DAO, and auto get 1 sbt. -module StarcoinFramework::AnyMemberPlugin{ - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::Signer; - use StarcoinFramework::Option; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct AnyMemberPlugin has store, drop{} - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::member_cap_type()); - caps - } - - public fun initialize(_sender: &signer) { - let witness = AnyMemberPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::AnyMemberPlugin", - b"The member plugin that allow all member to do join.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://any-member-plugin", - ); - } - - public fun join(sender: &signer, image_data:vector, image_url:vector){ - let witness = AnyMemberPlugin{}; - let sender_addr = Signer::address_of(sender); - if (DAOSpace::is_member(sender_addr) ) { - return - }; - let member_cap = DAOSpace::acquire_member_cap(&witness); - let op_image_data = if(Vector::is_empty(&image_data)){ - Option::none>() - }else{ - Option::some(image_data) - }; - let op_image_url = if(Vector::is_empty(&image_url)){ - Option::none>() - }else{ - Option::some(image_url) - }; - - DAOSpace::issue_member_offer(&member_cap, sender_addr, op_image_data, op_image_url, 1); - DAOSpace::accept_member_offer(sender); - } - - public (script) fun join_entry(sender: signer, image_data:vector, image_url:vector){ - join(&sender, image_data, image_url); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/sources/daospaceplugin/ConfigProposalPlugin.move b/sources/daospaceplugin/ConfigProposalPlugin.move deleted file mode 100644 index be9d43af..00000000 --- a/sources/daospaceplugin/ConfigProposalPlugin.move +++ /dev/null @@ -1,81 +0,0 @@ -/// Called by other contract which need proposal config -module StarcoinFramework::ConfigProposalPlugin { - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct ConfigProposalPlugin has store, drop{} - - struct ConfigProposalAction has store, drop { - config: ConfigT, - } - - public fun initialize(_sender: &signer) { - let witness = ConfigProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::ConfigProposalPlugin", - b"The config proposal plugin", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://config-proposal-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type()); - caps - } - - public fun create_proposal(sender: &signer, title:vector, introduction:vector, extend: vector,action_delay: u64, config: ConfigT) { - let witness = ConfigProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = ConfigProposalAction{ - config - }; - DAOSpace::create_proposal< - DAOT, - ConfigProposalPlugin, - ConfigProposalAction>(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64) { - let witness = ConfigProposalPlugin{}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - let modify_config_cap = - DAOSpace::acquire_modify_config_cap(&witness); - - let ConfigProposalAction{ config } = DAOSpace::execute_proposal< - DAOT, - ConfigProposalPlugin, - ConfigProposalAction>(&proposal_cap, sender, proposal_id); - DAOSpace::set_custom_config(&mut modify_config_cap, config); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64) { - execute_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/sources/daospaceplugin/GasOracleProposalPlugin.move b/sources/daospaceplugin/GasOracleProposalPlugin.move deleted file mode 100644 index e6e7825b..00000000 --- a/sources/daospaceplugin/GasOracleProposalPlugin.move +++ /dev/null @@ -1,128 +0,0 @@ -module StarcoinFramework::GasOracleProposalPlugin { - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::GasOracle::STCToken; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::Option; - use StarcoinFramework::GenesisSignerCapability; - use StarcoinFramework::Errors; - use StarcoinFramework::PriceOracleAggregator; - use StarcoinFramework::Account; - - const ERR_PLUGIN_ORACLE_EXIST: u64 = 1001; - const ERR_PLUGIN_ORACLE_NOT_EXIST: u64 = 1002; - - const ORACLE_UPDATED_IN: u64 = 600000; - - struct GasOracleProposalPlugin has store, drop {} - - struct OracleCreateAction has store { - precision: u8 - } - - struct OracleSourceAddAction has store, drop { - source_address: address - } - - struct OracleSourceRemoveAction has store, drop { - source_address: address - } - - struct OracleSources has copy, store { - source_addresses: vector
- } - - public fun initialize(_sender: &signer) { - let witness = GasOracleProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::GasOraclePlugin", - b"The plugin for gas oracle.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://gas-oracle-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::storage_cap_type()); - caps - } - - public(script) fun create_oracle_add_proposal(sender: signer, title:vector, introduction:vector, extend: vector, action_delay: u64, source_address: address) { - let witness = GasOracleProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = OracleSourceAddAction{ - source_address - }; - DAOSpace::create_proposal(&cap, &sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public(script) fun execute_oracle_add_proposal(sender: signer, proposal_id: u64) { - let witness = GasOracleProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let OracleSourceAddAction{ source_address } = DAOSpace::execute_proposal>(&proposal_cap, &sender, proposal_id); - let storage_cap = DAOSpace::acquire_storage_cap(&witness); - let source_addresses = if (!DAOSpace::exists_in_storage>()) { - let genesis_singer= GenesisSignerCapability::get_genesis_signer(); - Account::accept_token(genesis_singer); - Vector::singleton(source_address) - }else { - let OracleSources{ source_addresses } = DAOSpace::take_from_storage>(&storage_cap); - assert!(Vector::contains(&source_addresses, &source_address) == false, Errors::invalid_state(ERR_PLUGIN_ORACLE_EXIST)); - Vector::push_back(&mut source_addresses, source_address); - source_addresses - }; - - DAOSpace::save_to_storage(&storage_cap, OracleSources{ source_addresses }); - } - - public(script) fun create_oracle_remove_proposal(sender: signer, title:vector, introduction:vector, extend: vector, action_delay: u64, source_address: address) { - let witness = GasOracleProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = OracleSourceRemoveAction{ - source_address - }; - DAOSpace::create_proposal(&cap, &sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public(script) fun execute_oracle_remove_proposal(sender: signer, proposal_id: u64) { - let witness = GasOracleProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let OracleSourceRemoveAction{ source_address } = DAOSpace::execute_proposal>(&proposal_cap, &sender, proposal_id); - let storage_cap = DAOSpace::acquire_storage_cap(&witness); - assert!(DAOSpace::exists_in_storage>(), ERR_PLUGIN_ORACLE_NOT_EXIST); - let OracleSources{ source_addresses } = DAOSpace::take_from_storage>(&storage_cap); - let (exist,index)= Vector::index_of(&source_addresses, &source_address); - assert!(exist, Errors::invalid_state(ERR_PLUGIN_ORACLE_NOT_EXIST)); - Vector::remove(&mut source_addresses,index); - DAOSpace::save_to_storage(&storage_cap, OracleSources{ source_addresses }); - } - - public fun gas_oracle_read(): u128 { - let witness = GasOracleProposalPlugin{}; - let storage_cap = DAOSpace::acquire_storage_cap(&witness); - let OracleSources{ source_addresses } = DAOSpace::copy_from_storage>(&storage_cap); - PriceOracleAggregator::latest_price_average_aggregator>(&source_addresses, ORACLE_UPDATED_IN) - } - - public fun install_plugin_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, action_delay: u64) { - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public(script) fun install_plugin_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, action_delay: u64) { - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} \ No newline at end of file diff --git a/sources/daospaceplugin/GrantProposalPlugin.move b/sources/daospaceplugin/GrantProposalPlugin.move deleted file mode 100644 index 8160dd35..00000000 --- a/sources/daospaceplugin/GrantProposalPlugin.move +++ /dev/null @@ -1,123 +0,0 @@ -module StarcoinFramework::GrantProposalPlugin{ - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct GrantProposalPlugin has store, drop{} - - struct GrantCreateAction has store, drop { - grantee: address, - total: u128, - start_time:u64, - period:u64 - } - - struct GrantConfigAction has store, drop { - old_grantee: address, - new_grantee:address, - total: u128, - start_time:u64, - period:u64 - } - - struct GrantRevokeAction has store, drop { - grantee:address - } - - public fun initialize(_sender: &signer) { - let witness = GrantProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::GrantProposalPlugin", - b"The plugin for grant proposal", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://grant-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::grant_cap_type()); - caps - } - - const ERR_GRANTTREASURY_WITHDRAW_NOT_GRANTEE :u64 = 101; - const ERR_GRANTTREASURY_WITHDRAW_TOO_MORE :u64 = 102; - const ERR_SENDER_NOT_SAME :u64 = 103; - - public fun create_grant_proposal(sender: &signer, title:vector, introduction:vector, extend: vector,grantee: address, total: u128, start_time:u64, period: u64, action_delay:u64){ - let witness = GrantProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = GrantCreateAction{ - grantee:grantee, - total:total, - start_time:start_time, - period:period - }; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_grant_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector,grantee: address, total: u128, start_time:u64, period: u64, action_delay:u64){ - create_grant_proposal(&sender, title, introduction, extend, grantee, total, start_time, period, action_delay); - } - - public fun execute_grant_proposal(sender: &signer, proposal_id: u64){ - let witness = GrantProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let GrantCreateAction{grantee, total, start_time, period} = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - assert!(grantee == Signer::address_of(sender),Errors::not_published(ERR_SENDER_NOT_SAME)); - let grant_cap = DAOSpace::acquire_grant_cap(&witness); - DAOSpace::grant_offer(&grant_cap, Signer::address_of(sender), total, start_time, period); - } - - public (script) fun execute_grant_proposal_entry(sender: signer, proposal_id: u64){ - execute_grant_proposal(&sender, proposal_id); - } - - public fun create_grant_revoke_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, grantee:address, action_delay:u64){ - let witness = GrantProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = GrantRevokeAction{ grantee }; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_grant_revoke_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, grantee:address, action_delay:u64){ - create_grant_revoke_proposal(&sender, title, introduction, extend, grantee, action_delay); - } - - public fun execute_grant_revoke_proposal(sender: &signer, proposal_id: u64){ - let witness = GrantProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let GrantRevokeAction{ grantee } = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - let grant_cap = DAOSpace::acquire_grant_cap(&witness); - DAOSpace::grant_revoke(&grant_cap , grantee); - } - - public (script) fun execute_grant_revoke_proposal_entry(sender: signer, proposal_id: u64){ - execute_grant_revoke_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/sources/daospaceplugin/InstallPluginProposalPlugin.move b/sources/daospaceplugin/InstallPluginProposalPlugin.move deleted file mode 100644 index 0d6982db..00000000 --- a/sources/daospaceplugin/InstallPluginProposalPlugin.move +++ /dev/null @@ -1,68 +0,0 @@ -module StarcoinFramework::InstallPluginProposalPlugin{ - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - - struct InstallPluginProposalPlugin has store, drop{} - - struct InstallPluginAction has store, drop { - required_caps: vector, - } - - public fun initialize(_sender: &signer) { - let witness = InstallPluginProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::InstallPluginProposalPlugin", - b"The plugin for install plugin proposal", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://install-plugin-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::install_plugin_cap_type()); - caps - } - - /// Create a proposal to install a plugin. - /// We do not provide a entry function for create_proposal, because we can not use CapType as an entry function parameter, - /// every plugin should provide a entry function to create proposal to install self. - public fun create_proposal(sender: &signer, required_caps: vector, title:vector, introduction:vector, extend: vector, action_delay: u64){ - let witness = InstallPluginProposalPlugin{}; - - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = InstallPluginAction{ - required_caps, - }; - - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64){ - let witness = InstallPluginProposalPlugin{}; - - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let InstallPluginAction{required_caps} = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - - let install_plugin_cap = DAOSpace::acquire_install_plugin_cap(&witness); - DAOSpace::install_plugin(&install_plugin_cap, required_caps); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64) { - execute_proposal(&sender, proposal_id); - } -} \ No newline at end of file diff --git a/sources/daospaceplugin/MemberProposalPlugin.move b/sources/daospaceplugin/MemberProposalPlugin.move deleted file mode 100644 index 53e1146a..00000000 --- a/sources/daospaceplugin/MemberProposalPlugin.move +++ /dev/null @@ -1,97 +0,0 @@ -module StarcoinFramework::MemberProposalPlugin{ - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::Errors; - - const ERR_MEMBER_EXIST:u64 = 101; - const ERR_MEMBER_OFFER_EXIST:u64 = 102; - - struct MemberProposalPlugin has store, drop{} - - struct MemberJoinAction has store, drop { - member: address, - init_sbt: u128, - image_url: vector , - image_data: vector - } - - public fun initialize(_sender: &signer) { - let witness = MemberProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::MemberProposalPlugin", - b"The plugin for member proposal", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://member-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::proposal_cap_type()); - caps - } - - public fun create_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, member: address, image_data:vector, image_url:vector, init_sbt: u128, action_delay: u64){ - let witness = MemberProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = MemberJoinAction{ - member, - init_sbt, - image_data, - image_url - }; - assert!(!DAOSpace::is_exist_member_offer(member), Errors::already_published(ERR_MEMBER_OFFER_EXIST)); - assert!(!DAOSpace::is_member(member), Errors::already_published(ERR_MEMBER_EXIST)); - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, member: address, image_data:vector, image_url:vector, init_sbt: u128, action_delay: u64){ - create_proposal(&sender, title, introduction, extend, member, image_data, image_url, init_sbt, action_delay); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64){ - let witness = MemberProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let MemberJoinAction{member, init_sbt, image_data, image_url} = DAOSpace::execute_proposal(&proposal_cap, sender, proposal_id); - let member_cap = DAOSpace::acquire_member_cap(&witness); - let op_image_data = if(Vector::length(&image_data) == 0){ - Option::none>() - }else{ - Option::some(image_data) - }; - let op_image_url = if(Vector::length(&image_url) == 0){ - Option::none>() - }else{ - Option::some(image_url) - }; - DAOSpace::issue_member_offer(&member_cap, member,op_image_data , op_image_url , init_sbt); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64){ - execute_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector,action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender, required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/sources/daospaceplugin/MintProposalPlugin.move b/sources/daospaceplugin/MintProposalPlugin.move deleted file mode 100644 index 1d6a0180..00000000 --- a/sources/daospaceplugin/MintProposalPlugin.move +++ /dev/null @@ -1,98 +0,0 @@ -module StarcoinFramework::MintProposalPlugin{ - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - - struct MintProposalPlugin has store, drop{} - - /// MintToken request. - struct MintTokenAction has copy, drop, store { - /// the receiver of minted tokens. - receiver: address, - /// how many tokens to mint. - amount: u128, - } - - public fun initialize(_sender: &signer) { - let witness = MintProposalPlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::MintProposalPlugin", - b"The plugin for minting tokens.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://mint-proposal-plugin", - ); - } - - public fun required_caps():vector{ - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::token_mint_cap_type()); - caps - } - - const ERR_NOT_RECEIVER :u64 = 101; - const ERR_NO_MINT_CAP: u64 = 102; - - public fun delegate_token_mint_cap(sender: &signer) { - let witness = MintProposalPlugin {}; - let mint_cap = Token::remove_mint_capability(sender); - DAOSpace::delegate_token_mint_cap(mint_cap, &witness); - } - - public (script) fun delegate_token_mint_cap_entry(sender: signer) { - delegate_token_mint_cap(&sender); - } - - public fun create_mint_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, receiver: address, amount: u128, action_delay: u64){ - let witness = MintProposalPlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = MintTokenAction{ - receiver, - amount, - }; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_mint_proposal_entry(sender: signer, title:vector, introduction:vector, extend: vector, receiver: address, amount: u128, action_delay: u64){ - create_mint_proposal(&sender, extend, title, introduction, receiver, amount, action_delay); - } - - public fun execute_mint_proposal(sender: &signer, proposal_id: u64){ - let witness = MintProposalPlugin{}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let MintTokenAction{receiver, amount} = DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - assert!(receiver == Signer::address_of(sender),Errors::not_published(ERR_NOT_RECEIVER)); - let tokens = DAOSpace::mint_token(amount, &witness); - Account::deposit(receiver, tokens); - } - - public (script) fun execute_mint_proposal_entry(sender: signer, proposal_id: u64){ - execute_mint_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender,required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } - -} \ No newline at end of file diff --git a/sources/daospaceplugin/StakeToSBTPlugin.move b/sources/daospaceplugin/StakeToSBTPlugin.move deleted file mode 100644 index 365815b2..00000000 --- a/sources/daospaceplugin/StakeToSBTPlugin.move +++ /dev/null @@ -1,635 +0,0 @@ -module StarcoinFramework::StakeToSBTPlugin { - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::Token; - use StarcoinFramework::Account; - use StarcoinFramework::DAOSpace; - use StarcoinFramework::Vector; - use StarcoinFramework::Signer; - use StarcoinFramework::Timestamp; - use StarcoinFramework::InstallPluginProposalPlugin; - - const ERR_PLUGIN_USER_IS_MEMBER: u64 = 1001; - const ERR_PLUGIN_HAS_STAKED: u64 = 1002; - const ERR_PLUGIN_NOT_STAKE: u64 = 1003; - const ERR_PLUGIN_STILL_LOCKED: u64 = 1004; - const ERR_PLUGIN_CONFIG_INIT_REPEATE: u64 = 1005; - const ERR_PLUGIN_ITEM_CANT_FOUND: u64 = 1006; - const ERR_PLUGIN_NO_MATCH_LOCKTIME: u64 = 1007; - const ERR_DEPRECATED_METHOD: u64 = 1008; - - struct StakeToSBTPlugin has store, drop {} - - public fun initialize(_sender: &signer) { - let witness = StakeToSBTPlugin {}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::StakeToSBTPlugin", - b"The plugin for stake to SBT", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://stake-to-sbt-plugin", - ); - } - - struct Stake has key, store { - id: u64, - token: Token::Token, - // The timestamp when user stake - stake_time: u64, - // How long where the user locked - lock_time: u64, - // Which multiplier by the user stake - weight: u64, - // The SBT amount that user swap in the token - sbt_amount: u128, - } - - struct StakeList has key, store { - items: vector>, - next_id: u64 - } - - struct LockWeightConfig has copy, store, drop { - weight_vec: vector> - } - - struct LockWeight has copy, drop, store { - lock_time: u64, - weight: u64, - } - - struct AcceptTokenCap has store, drop {} - - /// Events - /// - struct SBTTokenAcceptedEvent has copy, drop, store { - dao_id: u64, - token_code: Token::TokenCode - } - - struct SBTWeightChangedEvent has copy, drop, store { - dao_id: u64, - token_code: Token::TokenCode, - lock_time: u64, - weight: u64, - } - - struct SBTStakeEvent has copy, drop, store { - dao_id: u64, - stake_id: u64, - token_code: Token::TokenCode, - amount: u128, - lock_time: u64, - weight: u64, - sbt_amount: u128, - member: address, - } - - struct SBTUnstakeEvent has copy, drop, store { - dao_id: u64, - stake_id: u64, - token_code: Token::TokenCode, - amount: u128, - lock_time: u64, - weight: u64, - sbt_amount: u128, - member: address, - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::member_cap_type()); - Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type()); - Vector::push_back(&mut caps, DAOSpace::plugin_event_cap_type()); - caps - } - - /// Accept token with token type by given DAO - public fun accept_token_by_dao(_witness: &DAOT) { - accept_token(AcceptTokenCap {}); - } - - /// Deprecated - public fun install_event() { - abort Errors::deprecated(ERR_DEPRECATED_METHOD) - } - - fun install_event_inner() { - if (!DAOSpace::exist_plugin_event()) { - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - DAOSpace::init_plugin_event(&plugin_event_cap); - } - } - - /// Set sbt weight by given DAO - public fun set_sbt_weight_by_dao( - _witness: &DAOT, - lock_time: u64, - weight: u64 - ) { - set_sbt_weight(lock_time, weight); - } - - /// Accept token with token type - public fun accept_token(cap: AcceptTokenCap) { - let AcceptTokenCap {} = cap; - assert!( - !DAOSpace::exists_custom_config>(), - Errors::invalid_state(ERR_PLUGIN_CONFIG_INIT_REPEATE) - ); - - let witness = StakeToSBTPlugin {}; - let modify_config_cap = - DAOSpace::acquire_modify_config_cap(&witness); - - DAOSpace::set_custom_config< - DAOT, - StakeToSBTPlugin, - LockWeightConfig - >(&mut modify_config_cap, LockWeightConfig { - weight_vec: Vector::empty>() - }); - - install_event_inner(); - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - - DAOSpace::emit_plugin_event( - &plugin_event_cap, - SBTTokenAcceptedEvent { - dao_id: DAOSpace::dao_id(DAOSpace::dao_address()), - token_code: Token::token_code(), - } - ); - } - - public fun stake( - sender: &signer, - token: Token::Token, - lock_time: u64 - ): u64 acquires StakeList { - let sender_addr = Signer::address_of(sender); - // Increase SBT - let witness = StakeToSBTPlugin {}; - let member_cap = - DAOSpace::acquire_member_cap(&witness); - - if (!DAOSpace::is_member(sender_addr) ) { - DAOSpace::issue_member_offer( - &member_cap, - sender_addr, - Option::none>(), - Option::none>(), - 0 - ); - DAOSpace::accept_member_offer(sender); - }; - - if (!exists>(sender_addr)) { - move_to(sender, StakeList { - items: Vector::empty(), - next_id: 0 - }); - }; - - let weight_opt = get_sbt_weight(lock_time); - assert!(Option::is_some(&weight_opt), Errors::invalid_state(ERR_PLUGIN_NO_MATCH_LOCKTIME)); - - let weight = Option::destroy_some(weight_opt); - let sbt_amount = compute_token_to_sbt(weight, &token); - DAOSpace::increase_member_sbt(&member_cap, sender_addr, sbt_amount); - - let stake_list = borrow_global_mut>(sender_addr); - let id = stake_list.next_id + 1; - Vector::push_back( - &mut stake_list.items, - Stake { - id, - token, - lock_time, - stake_time: Timestamp::now_seconds(), - weight, - sbt_amount - }); - stake_list.next_id = id; - - install_event_inner(); - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - DAOSpace::emit_plugin_event( - &plugin_event_cap, - SBTStakeEvent { - dao_id: DAOSpace::dao_id(DAOSpace::dao_address()), - stake_id: id, - token_code: Token::token_code(), - amount: sbt_amount, - lock_time, - weight, - sbt_amount, - member: sender_addr, - } - ); - id - } - - public(script) fun stake_entry( - sender: signer, - amount: u128, - lock_time: u64 - ) acquires StakeList { - let token = Account::withdraw(&sender, amount); - stake(&sender, token, lock_time); - } - - public fun query_stake( - member: address, - id: u64 - ): (u64, u64, u64, u128, u128) acquires StakeList { - assert!(exists>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global_mut>(member); - let item_index = find_item(id, &stake_list.items); - - // Check item in item container - assert!(Option::is_some(&item_index), Errors::invalid_state(ERR_PLUGIN_ITEM_CANT_FOUND)); - - let stake = - Vector::borrow(&mut stake_list.items, Option::destroy_some(item_index)); - ( - stake.stake_time, - stake.lock_time, - stake.weight, - stake.sbt_amount, - Token::value(&stake.token), - ) - } - - /// Query stake count from stake list - public fun query_stake_count(member: address): u64 acquires StakeList { - assert!(exists>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global>(member); - Vector::length(&stake_list.items) - } - - /// Unstake from staking - public fun unstake_by_id(sender: &signer, id: u64) acquires StakeList { - let member = Signer::address_of(sender); - assert!(exists>(member), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global_mut>(member); - let item_index = find_item(id, &stake_list.items); - - // Check item in item container - assert!(Option::is_some(&item_index), Errors::invalid_state(ERR_PLUGIN_ITEM_CANT_FOUND)); - - let poped_item = - Vector::remove(&mut stake_list.items, Option::destroy_some(item_index)); - - let amount = Token::value(&poped_item.token); - let lock_time = poped_item.lock_time; - let weight = poped_item.weight; - let sbt_amount = poped_item.sbt_amount; - - Account::deposit(member, unstake_item(member, poped_item)); - - install_event_inner(); - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - DAOSpace::emit_plugin_event( - &plugin_event_cap, - SBTUnstakeEvent { - dao_id: DAOSpace::dao_id(DAOSpace::dao_address()), - stake_id: id, - token_code: Token::token_code(), - amount, - lock_time, - weight, - sbt_amount, - member, - } - ); - } - - public(script) fun unstake_by_id_entry( - sender: signer, - id: u64 - ) acquires StakeList { - unstake_by_id(&sender, id); - } - - /// Unstake all expired items. - /// No care whether the sender is member or not - public fun unstake_all(sender: &signer) acquires StakeList { - let sender_addr = Signer::address_of(sender); - assert!(exists>(sender_addr), Errors::not_published(ERR_PLUGIN_NOT_STAKE)); - let stake_list = borrow_global_mut>(sender_addr); - let len = Vector::length(&mut stake_list.items); - - let idx = 0; - while (idx < len) { - let item = Vector::borrow(&stake_list.items, idx); - if (can_item_unstake(item)) { - let item = Vector::remove(&mut stake_list.items, idx); - Account::deposit(sender_addr, unstake_item(sender_addr, item)); - len = len - 1; - } else { - idx = idx + 1; - }; - }; - } - - /// Unstake all expired items. - public(script) fun unstake_all_entry(sender: signer) acquires StakeList { - unstake_all(&sender); - } - - /// Check if an item is available to unstake. - fun can_item_unstake(item: &Stake): bool { - Timestamp::now_seconds() - item.stake_time >= item.lock_time - } - - /// Unstake an item from an item object - fun unstake_item( - member: address, - item: Stake - ): Token::Token { - let Stake { - id: _, - token, - lock_time, - stake_time, - weight: _, - sbt_amount, - } = item; - - assert!((Timestamp::now_seconds() - stake_time) >= lock_time, Errors::invalid_state(ERR_PLUGIN_STILL_LOCKED)); - - // Deduct the corresponding SBT amount if the signer account is a DAO member while unstake - if (DAOSpace::is_member(member)) { - let witness = StakeToSBTPlugin {}; - let member_cap = - DAOSpace::acquire_member_cap(&witness); - - // Decrease the SBT using `sbt_amount` which from unwrapped Stake data, - // rather than the value that calculate a SBT amount from lock time and weight, - // because of the `weight` could change at any time - DAOSpace::decrease_member_sbt(&member_cap, member, sbt_amount); - }; - - token - } - - fun get_sbt_weight(lock_time: u64): Option::Option { - let config = - DAOSpace::get_custom_config>(); - let c = - &mut config.weight_vec; - let len = Vector::length(c); - let idx = 0; - - while (idx < len) { - let e = Vector::borrow(c, idx); - if (e.lock_time == lock_time) { - return Option::some(e.weight) - }; - idx = idx + 1; - }; - - Option::none() - } - - fun set_sbt_weight(lock_time: u64, weight: u64) { - let config = - DAOSpace::get_custom_config>(); - let c = &mut config.weight_vec; - let len = Vector::length(c); - let idx = 0; - let new_el = true; - while (idx < len) { - let lock_weight = Vector::borrow_mut(c, idx); - if (lock_weight.lock_time == lock_time) { - lock_weight.weight = weight; - new_el = false; - break - }; - idx = idx + 1; - }; - - if (new_el) { - Vector::push_back(c, LockWeight { - lock_time, - weight, - }); - }; - - install_event_inner(); - let witness = StakeToSBTPlugin {}; - let plugin_event_cap = - DAOSpace::acquire_plugin_event_cap(&witness); - DAOSpace::emit_plugin_event( - &plugin_event_cap, - SBTWeightChangedEvent { - dao_id: DAOSpace::dao_id(DAOSpace::dao_address()), - token_code: Token::token_code(), - lock_time, - weight, - } - ); - - let modify_config_cap = - DAOSpace::acquire_modify_config_cap(&witness); - - DAOSpace::set_custom_config< - DAOT, - StakeToSBTPlugin, - LockWeightConfig - >(&mut modify_config_cap, LockWeightConfig { - weight_vec: *&config.weight_vec - }); - } - - fun find_item( - id: u64, - c: &vector> - ): Option::Option { - let len = Vector::length(c); - let idx = 0; - while (idx < len) { - let item = Vector::borrow(c, idx); - if (item.id == id) { - return Option::some(idx) - }; - idx = idx + 1; - }; - Option::none() - } - - fun compute_token_to_sbt(weight: u64, token: &Token::Token): u128 { - (weight as u128) * Token::value(token) / Token::scaling_factor() - } - - /// Create proposal that to specific a weight for a locktime - public fun create_weight_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - lock_time: u64, - weight: u64, - action_delay: u64 - ) { - let witness = StakeToSBTPlugin {}; - - let cap = - DAOSpace::acquire_proposal_cap(&witness); - DAOSpace::create_proposal(&cap, sender, LockWeight { - lock_time, - weight, - }, - title, - introduction, - extend, - action_delay, - Option::none()); - } - - public(script) fun create_weight_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - lock_time: u64, - weight: u64, - action_delay: u64 - ) { - create_weight_proposal(&sender,title, introduction, extend, lock_time, weight, action_delay); - } - - public fun execute_weight_proposal( - sender: &signer, - proposal_id: u64 - ) { - let witness = StakeToSBTPlugin {}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - - let LockWeight { - lock_time, - weight - } = DAOSpace::execute_proposal< - DAOT, - StakeToSBTPlugin, - LockWeight - >(&proposal_cap, sender, proposal_id); - - set_sbt_weight(lock_time, weight); - } - - public(script) fun execute_weight_proposal_entry( - sender: signer, - proposal_id: u64 - ) { - execute_weight_proposal(&sender, proposal_id); - } - - /// Create proposal that to accept a token type, which allow user to convert amount of token to SBT - public fun create_token_accept_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - let witness = StakeToSBTPlugin {}; - - let cap = - DAOSpace::acquire_proposal_cap(&witness); - DAOSpace::create_proposal( - &cap, - sender, - AcceptTokenCap {}, - title, - introduction, - extend, - action_delay, - Option::none() - ); - } - - public(script) fun create_token_accept_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - create_token_accept_proposal(&sender, title, introduction, extend, action_delay); - } - - public fun execute_token_accept_proposal( - sender: &signer, - proposal_id: u64 - ) { - let witness = StakeToSBTPlugin {}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - - let cap = DAOSpace::execute_proposal< - DAOT, - StakeToSBTPlugin, - AcceptTokenCap - >(&proposal_cap, sender, proposal_id); - - accept_token(cap); - } - - - public(script) fun execute_token_accept_proposal_entry( - sender: signer, - proposal_id: u64 - ) { - execute_token_accept_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - InstallPluginProposalPlugin::create_proposal( - sender, - required_caps(), - title, - introduction, - extend, - action_delay - ); - } - - public(script) fun install_plugin_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} diff --git a/sources/daospaceplugin/TreasuryPlugin.move b/sources/daospaceplugin/TreasuryPlugin.move deleted file mode 100644 index 511f87fd..00000000 --- a/sources/daospaceplugin/TreasuryPlugin.move +++ /dev/null @@ -1,198 +0,0 @@ -module StarcoinFramework::TreasuryPlugin { - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::Token; - use StarcoinFramework::Treasury; - use StarcoinFramework::Token::Token; - use StarcoinFramework::CoreAddresses; - use StarcoinFramework::InstallPluginProposalPlugin; - - const ERR_NOT_AUTHORIZED: u64 = 101; - /// Only receiver can execute treasury withdraw proposal - const ERR_NOT_RECEIVER: u64 = 102; - /// The withdraw amount of propose is too many. - const ERR_TOO_MANY_WITHDRAW_AMOUNT: u64 = 103; - const ERR_CAPABILITY_NOT_EXIST: u64 = 104; - const ERR_INVALID_SCALE_FACTOR: u64 = 105; - - struct TreasuryPlugin has store, drop {} - - /// A wrapper of Token MintCapability. - struct WithdrawCapabilityHolder has key { - cap: Treasury::WithdrawCapability, - } - - /// Scale up quorum_votes for withdraw proposal. - /// `scale` must be in [0, 100]. - /// The final quorum_votes = (1.0 + scale / 100) * base_quorum_votes - struct QuorumScale has copy, drop, store { - scale: u8, - } - - /// WithdrawToken request. - struct WithdrawTokenAction has copy, drop, store { - /// the receiver of withdraw tokens. - receiver: address, - /// how many tokens to mint. - amount: u128, - /// How long in milliseconds does it take for the token to be released - period: u64, - } - - public fun initialize(_sender: &signer) { - let witness = TreasuryPlugin {}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::TreasuryPlugin", - b"The plugin for withdraw token from Treasury.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://treasury-plugin", - ); - } - - /// Delegate Treasury::WithdrawCapability to DAO - /// Should be called by token issuer. - public fun delegate_capability(sender: &signer, cap: Treasury::WithdrawCapability) { - let token_issuer = Token::token_address(); - assert!(Signer::address_of(sender) == token_issuer, Errors::requires_address(ERR_NOT_AUTHORIZED)); - move_to(sender, WithdrawCapabilityHolder { cap }); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type()); - caps - } - - fun withdraw_limitation(): u128 { - let market_cap = Token::market_cap(); - let balance_in_treasury = Treasury::balance(); - let supply = market_cap - balance_in_treasury; - let rate = DAOSpace::voting_quorum_rate(); - let rate = (rate as u128); - supply * rate / 100 - } - - public fun create_withdraw_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - receiver: address, - amount: u128, - period: u64, - action_delay: u64) - { - let limit = withdraw_limitation(); - assert!(amount <= limit, Errors::invalid_argument(ERR_TOO_MANY_WITHDRAW_AMOUNT)); - let witness = TreasuryPlugin {}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = WithdrawTokenAction { - receiver, - amount, - period, - }; - - if (!DAOSpace::exists_custom_config()) { - set_scale_factor_inner(0u8); - }; - let scale = DAOSpace::get_custom_config().scale; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::some(scale)); - } - - public(script) fun create_withdraw_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - receiver: address, - amount: u128, - period: u64, - action_delay: u64) - { - create_withdraw_proposal(&sender, title, introduction, extend, receiver, amount, period, action_delay); - } - - public fun execute_withdraw_proposal(sender: &signer, proposal_id: u64) acquires WithdrawCapabilityHolder { - let witness = TreasuryPlugin {}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let WithdrawTokenAction { receiver, amount, period } = - DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - assert!(receiver == Signer::address_of(sender), Errors::not_published(ERR_NOT_RECEIVER)); - let token_issuer = Token::token_address(); - assert!(exists>(token_issuer), Errors::not_published(ERR_CAPABILITY_NOT_EXIST)); - let cap = borrow_global_mut>(token_issuer); - let linear_cap = Treasury::issue_linear_withdraw_capability(&mut cap.cap, amount, period); - Treasury::add_linear_withdraw_capability(sender, linear_cap); - } - - public(script) fun execute_withdraw_proposal_entry(sender: signer, proposal_id: u64) acquires WithdrawCapabilityHolder { - execute_withdraw_proposal(&sender, proposal_id); - } - - /// Provider a port for get block reward STC from Treasury, only genesis account can invoke this function. - /// The TreasuryWithdrawCapability is locked in TreasuryWithdrawDaoProposal, and only can withdraw by DAO proposal. - /// This approach is not graceful, but restricts the operation to genesis accounts only, so there are no security issues either. - public fun withdraw_for_block_reward(signer: &signer, reward: u128): Token - acquires WithdrawCapabilityHolder { - CoreAddresses::assert_genesis_address(signer); - let cap = borrow_global_mut>(Signer::address_of(signer)); - Treasury::withdraw_with_capability(&mut cap.cap, reward) - } - - public fun set_scale_factor(scale: u8, _witness: &DAOT) { - assert!( - scale >= 0 && scale <= 100, - Errors::invalid_argument(ERR_INVALID_SCALE_FACTOR), - ); - set_scale_factor_inner(scale); - } - - fun set_scale_factor_inner(scale: u8) { - let plugin = TreasuryPlugin {}; - let cap = DAOSpace::acquire_modify_config_cap(&plugin); - DAOSpace::set_custom_config(&mut cap, QuorumScale { scale }); - } - - public fun install_plugin_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - InstallPluginProposalPlugin::create_proposal( - sender, - required_caps(), - title, - introduction, - extend, - action_delay - ); - } - - public(script) fun install_plugin_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - action_delay: u64 - ) { - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} \ No newline at end of file diff --git a/sources/daospaceplugin/UpgradeModulePlugin.move b/sources/daospaceplugin/UpgradeModulePlugin.move deleted file mode 100644 index 23f546de..00000000 --- a/sources/daospaceplugin/UpgradeModulePlugin.move +++ /dev/null @@ -1,91 +0,0 @@ -module StarcoinFramework::UpgradeModulePlugin { - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Vector; - use StarcoinFramework::InstallPluginProposalPlugin; - - struct UpgradeModulePlugin has store, drop{} - - struct UpgradeModuleAction has store, drop { - package_hash: vector, - version: u64, - enforced: bool - } - - public fun initialize(_sender: &signer) { - let witness = UpgradeModulePlugin{}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::UpgradeModulePlugin", - b"The plugin for upgrade module.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://upgrade-module-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::upgrade_module_cap_type()); - caps - } - - public fun create_proposal(sender: &signer, title:vector, introduction:vector, extend: vector, action_delay:u64, package_hash: vector, version: u64, enforced: bool) { - let witness = UpgradeModulePlugin{}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = UpgradeModuleAction{ - package_hash, - version, - enforced - }; - DAOSpace::create_proposal< - DAOT, - UpgradeModulePlugin, - UpgradeModuleAction>(&cap, sender, action, title, introduction, extend, action_delay, Option::none()); - } - - public (script) fun create_proposal_entry (sender: signer, title:vector, introduction:vector, extend: vector, action_delay:u64, package_hash: vector, version: u64, enforced: bool) { - create_proposal(&sender, title, introduction, extend, action_delay, package_hash, version, enforced); - } - - public fun execute_proposal(sender: &signer, proposal_id: u64) { - let witness = UpgradeModulePlugin{}; - let proposal_cap = - DAOSpace::acquire_proposal_cap(&witness); - let upgrade_module_cap = - DAOSpace::acquire_upgrade_module_cap(&witness); - - let UpgradeModuleAction{ - package_hash, - version, - enforced - } = DAOSpace::execute_proposal< - DAOT, - UpgradeModulePlugin, - UpgradeModuleAction>(&proposal_cap, sender, proposal_id); - DAOSpace::submit_upgrade_plan(&mut upgrade_module_cap, package_hash, version, enforced); - } - - public (script) fun execute_proposal_entry(sender: signer, proposal_id: u64) { - execute_proposal(&sender, proposal_id); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender,required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} \ No newline at end of file diff --git a/sources/daospaceplugin/WithdrawPlugin.move b/sources/daospaceplugin/WithdrawPlugin.move deleted file mode 100644 index a2116160..00000000 --- a/sources/daospaceplugin/WithdrawPlugin.move +++ /dev/null @@ -1,134 +0,0 @@ -/// Plugin for withdrawing tokens from DAO. -module StarcoinFramework::WithdrawPlugin { - use StarcoinFramework::Errors; - use StarcoinFramework::Option; - use StarcoinFramework::DAOPluginMarketplace; - use StarcoinFramework::DAOSpace::{Self, CapType}; - use StarcoinFramework::Signer; - use StarcoinFramework::Vector; - use StarcoinFramework::Account; - use StarcoinFramework::InstallPluginProposalPlugin; - - /// Only receiver can execute token withdraw proposal - const ERR_NOT_RECEIVER: u64 = 101; - const ERR_INVALID_SCALE_FACTOR: u64 = 102; - - struct WithdrawPlugin has store, drop {} - - /// WithdrawToken request. - struct WithdrawTokenAction has copy, drop, store { - /// the receiver of withdraw tokens. - receiver: address, - /// Withdraw amount. - amount: u128, - } - - /// Scale up quorum_votes for withdraw proposal. - /// `scale` must be in [0, 100]. - /// The final quorum_votes = (1.0 + scale / 100) * base_quorum_votes - struct QuorumScale has copy, drop, store { - scale: u8, - } - - public fun initialize(_sender: &signer) { - let witness = WithdrawPlugin {}; - - DAOPluginMarketplace::register_plugin( - &witness, - b"0x1::WithdrawPlugin", - b"The plugin for withdraw token from Treasury.", - Option::none(), - ); - - let implement_extpoints = Vector::empty>(); - let depend_extpoints = Vector::empty>(); - - DAOPluginMarketplace::publish_plugin_version( - &witness, - b"v0.1.0", - *&implement_extpoints, - *&depend_extpoints, - b"inner-plugin://withdraw-plugin", - ); - } - - public fun required_caps(): vector { - let caps = Vector::singleton(DAOSpace::proposal_cap_type()); - Vector::push_back(&mut caps, DAOSpace::modify_config_cap_type()); - Vector::push_back(&mut caps, DAOSpace::withdraw_token_cap_type()); - caps - } - - public fun create_withdraw_proposal( - sender: &signer, - title:vector, - introduction:vector, - extend: vector, - receiver: address, - amount: u128, - action_delay: u64) - { - let witness = WithdrawPlugin {}; - let cap = DAOSpace::acquire_proposal_cap(&witness); - let action = WithdrawTokenAction { - receiver, - amount, - }; - - if (!DAOSpace::exists_custom_config()) { - set_scale_factor_inner(0u8); - }; - let scale = DAOSpace::get_custom_config().scale; - DAOSpace::create_proposal(&cap, sender, action, title, introduction, extend, action_delay, Option::some(scale)); - } - - public(script) fun create_withdraw_proposal_entry( - sender: signer, - title:vector, - introduction:vector, - extend: vector, - receiver: address, - amount: u128, - action_delay: u64) - { - create_withdraw_proposal(&sender, title, introduction, extend, receiver, amount, action_delay); - } - - public fun execute_withdraw_proposal(sender: &signer, proposal_id: u64) { - let witness = WithdrawPlugin {}; - let proposal_cap = DAOSpace::acquire_proposal_cap(&witness); - let WithdrawTokenAction { receiver, amount } = - DAOSpace::execute_proposal>(&proposal_cap, sender, proposal_id); - assert!(receiver == Signer::address_of(sender), Errors::not_published(ERR_NOT_RECEIVER)); - - let withdraw_cap = DAOSpace::acquire_withdraw_token_cap(&witness); - let tokens = DAOSpace::withdraw_token(&withdraw_cap, amount); - Account::deposit(receiver, tokens); - } - - public(script) fun execute_withdraw_proposal_entry(sender: signer, proposal_id: u64) { - execute_withdraw_proposal(&sender, proposal_id); - } - - public fun set_scale_factor(scale: u8, _witness: &DAOT) { - assert!( - scale >= 0 && scale <= 100, - Errors::invalid_argument(ERR_INVALID_SCALE_FACTOR), - ); - set_scale_factor_inner(scale); - } - - fun set_scale_factor_inner(scale: u8) { - let plugin = WithdrawPlugin {}; - let cap = DAOSpace::acquire_modify_config_cap(&plugin); - DAOSpace::set_custom_config(&mut cap, QuorumScale { scale }); - } - - public fun install_plugin_proposal(sender:&signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - InstallPluginProposalPlugin::create_proposal(sender,required_caps(), title, introduction, extend, action_delay); - } - - public (script) fun install_plugin_proposal_entry(sender:signer, title:vector, introduction:vector, extend: vector, action_delay:u64){ - install_plugin_proposal(&sender, title, introduction, extend, action_delay); - } -} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 77c96c29..84fd4561 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,46 +1,17 @@ // Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 -use std::path::Path; - use include_dir::{include_dir, Dir}; use log::info; use once_cell::sync::Lazy; use tempfile::TempDir; -use walkdir::WalkDir; pub const SOURCES_DIR: Dir = include_dir!("sources"); #[derive(Debug)] pub struct SourceFiles { pub tempdir: TempDir, -} - -impl SourceFiles { - /// Filter all Move source files. - pub fn files(&self) -> Vec { - Self::filter_source_files(self.tempdir.path()) - } - - /// Filter Move source files in the given directory. - pub fn filter_source_files(source_dir: &Path) -> Vec { - WalkDir::new(source_dir) - .into_iter() - .filter_map(Result::ok) - .filter_map(|file| { - let ext = file.path().extension(); - if let Some(ext) = ext { - if ext == "move" { - Some(file.path().display().to_string()) - } else { - None - } - } else { - None - } - }) - .collect() - } + pub files: Vec, } pub static STARCOIN_FRAMEWORK_SOURCES: Lazy = @@ -53,23 +24,21 @@ fn restore_sources() -> anyhow::Result { info!("restore starcoin-framework sources in: {:?}", sources_dir); std::fs::create_dir_all(sources_dir.as_path())?; SOURCES_DIR.extract(sources_dir.as_path())?; - Ok(SourceFiles { tempdir }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_restore_sources() { - let sf = restore_sources().unwrap(); - assert_eq!( - SourceFiles::filter_source_files( - std::env::current_dir().unwrap().join("sources").as_path() - ) - .len(), - sf.files().len(), - "source file count not equal" - ); - } + let files = SOURCES_DIR + .files() + .iter() + .filter_map(|file| { + let ext = file.path().extension(); + if let Some(ext) = ext { + if ext == "move" { + Some(sources_dir.join(file.path()).display().to_string()) + } else { + None + } + } else { + None + } + }) + .collect(); + Ok(SourceFiles { tempdir, files }) }