From 737f4c125ccadccb4e7c1ef7ea392466e69e0b52 Mon Sep 17 00:00:00 2001 From: avcdsld Date: Wed, 6 Sep 2023 10:39:33 +0900 Subject: [PATCH] build info --- .../build/sakutaro_poem/BuildInfo.yaml | 33 + .../sakutaro_poem/bytecode_modules/base64.mv | Bin 0 -> 1594 bytes .../dependencies/AptosFramework/account.mv | Bin 0 -> 6131 bytes .../dependencies/AptosFramework/aggregator.mv | Bin 0 -> 251 bytes .../AptosFramework/aggregator_factory.mv | Bin 0 -> 572 bytes .../AptosFramework/aggregator_v2.mv | Bin 0 -> 297 bytes .../AptosFramework/aptos_account.mv | Bin 0 -> 1583 bytes .../dependencies/AptosFramework/aptos_coin.mv | Bin 0 -> 1701 bytes .../AptosFramework/aptos_governance.mv | Bin 0 -> 4920 bytes .../dependencies/AptosFramework/block.mv | Bin 0 -> 2068 bytes .../dependencies/AptosFramework/chain_id.mv | Bin 0 -> 273 bytes .../AptosFramework/chain_status.mv | Bin 0 -> 451 bytes .../dependencies/AptosFramework/code.mv | Bin 0 -> 3217 bytes .../dependencies/AptosFramework/coin.mv | Bin 0 -> 3986 bytes .../AptosFramework/consensus_config.mv | Bin 0 -> 439 bytes .../AptosFramework/create_signer.mv | Bin 0 -> 156 bytes .../AptosFramework/delegation_pool.mv | Bin 0 -> 10777 bytes .../dependencies/AptosFramework/event.mv | Bin 0 -> 607 bytes .../AptosFramework/execution_config.mv | Bin 0 -> 400 bytes .../AptosFramework/fungible_asset.mv | Bin 0 -> 4088 bytes .../AptosFramework/gas_schedule.mv | Bin 0 -> 775 bytes .../dependencies/AptosFramework/genesis.mv | Bin 0 -> 4607 bytes .../AptosFramework/governance_proposal.mv | Bin 0 -> 224 bytes .../dependencies/AptosFramework/guid.mv | Bin 0 -> 448 bytes .../AptosFramework/managed_coin.mv | Bin 0 -> 739 bytes .../AptosFramework/multisig_account.mv | Bin 0 -> 8060 bytes .../dependencies/AptosFramework/object.mv | Bin 0 -> 3885 bytes .../AptosFramework/optional_aggregator.mv | Bin 0 -> 1552 bytes .../AptosFramework/primary_fungible_store.mv | Bin 0 -> 2153 bytes .../AptosFramework/reconfiguration.mv | Bin 0 -> 1500 bytes .../AptosFramework/resource_account.mv | Bin 0 -> 1311 bytes .../dependencies/AptosFramework/stake.mv | Bin 0 -> 10443 bytes .../AptosFramework/staking_config.mv | Bin 0 -> 2757 bytes .../AptosFramework/staking_contract.mv | Bin 0 -> 6166 bytes .../AptosFramework/staking_proxy.mv | Bin 0 -> 1043 bytes .../AptosFramework/state_storage.mv | Bin 0 -> 718 bytes .../AptosFramework/storage_gas.mv | Bin 0 -> 2905 bytes .../AptosFramework/system_addresses.mv | Bin 0 -> 1275 bytes .../dependencies/AptosFramework/timestamp.mv | Bin 0 -> 577 bytes .../AptosFramework/transaction_context.mv | Bin 0 -> 424 bytes .../AptosFramework/transaction_fee.mv | Bin 0 -> 2320 bytes .../AptosFramework/transaction_validation.mv | Bin 0 -> 1954 bytes .../dependencies/AptosFramework/util.mv | Bin 0 -> 162 bytes .../dependencies/AptosFramework/version.mv | Bin 0 -> 584 bytes .../dependencies/AptosFramework/vesting.mv | Bin 0 -> 7538 bytes .../dependencies/AptosFramework/voting.mv | Bin 0 -> 4218 bytes .../dependencies/AptosStdlib/any.mv | Bin 0 -> 388 bytes .../dependencies/AptosStdlib/aptos_hash.mv | Bin 0 -> 562 bytes .../dependencies/AptosStdlib/big_vector.mv | Bin 0 -> 2831 bytes .../dependencies/AptosStdlib/bls12381.mv | Bin 0 -> 2089 bytes .../AptosStdlib/bls12381_algebra.mv | Bin 0 -> 397 bytes .../dependencies/AptosStdlib/capability.mv | Bin 0 -> 1039 bytes .../dependencies/AptosStdlib/comparator.mv | Bin 0 -> 513 bytes .../dependencies/AptosStdlib/copyable_any.mv | Bin 0 -> 377 bytes .../AptosStdlib/crypto_algebra.mv | Bin 0 -> 2099 bytes .../dependencies/AptosStdlib/debug.mv | Bin 0 -> 276 bytes .../dependencies/AptosStdlib/ed25519.mv | Bin 0 -> 1396 bytes .../dependencies/AptosStdlib/fixed_point64.mv | Bin 0 -> 1347 bytes .../dependencies/AptosStdlib/from_bcs.mv | Bin 0 -> 510 bytes .../dependencies/AptosStdlib/math128.mv | Bin 0 -> 1283 bytes .../dependencies/AptosStdlib/math64.mv | Bin 0 -> 900 bytes .../dependencies/AptosStdlib/math_fixed.mv | Bin 0 -> 919 bytes .../dependencies/AptosStdlib/math_fixed64.mv | Bin 0 -> 1179 bytes .../dependencies/AptosStdlib/multi_ed25519.mv | Bin 0 -> 2078 bytes .../dependencies/AptosStdlib/pool_u64.mv | Bin 0 -> 2208 bytes .../AptosStdlib/pool_u64_unbound.mv | Bin 0 -> 2351 bytes .../dependencies/AptosStdlib/ristretto255.mv | Bin 0 -> 4092 bytes .../AptosStdlib/ristretto255_bulletproofs.mv | Bin 0 -> 872 bytes .../AptosStdlib/ristretto255_elgamal.mv | Bin 0 -> 1976 bytes .../AptosStdlib/ristretto255_pedersen.mv | Bin 0 -> 1549 bytes .../dependencies/AptosStdlib/secp256k1.mv | Bin 0 -> 626 bytes .../dependencies/AptosStdlib/simple_map.mv | Bin 0 -> 1969 bytes .../dependencies/AptosStdlib/smart_table.mv | Bin 0 -> 4027 bytes .../dependencies/AptosStdlib/smart_vector.mv | Bin 0 -> 3194 bytes .../dependencies/AptosStdlib/string_utils.mv | Bin 0 -> 1135 bytes .../dependencies/AptosStdlib/table.mv | Bin 0 -> 939 bytes .../AptosStdlib/table_with_length.mv | Bin 0 -> 939 bytes .../dependencies/AptosStdlib/type_info.mv | Bin 0 -> 502 bytes .../dependencies/AptosToken/property_map.mv | Bin 0 -> 2721 bytes .../dependencies/AptosToken/token.mv | Bin 0 -> 12382 bytes .../AptosToken/token_coin_swap.mv | Bin 0 -> 1157 bytes .../AptosToken/token_event_store.mv | Bin 0 -> 2365 bytes .../AptosToken/token_transfers.mv | Bin 0 -> 1571 bytes .../dependencies/MoveStdlib/acl.mv | Bin 0 -> 454 bytes .../dependencies/MoveStdlib/bcs.mv | Bin 0 -> 92 bytes .../dependencies/MoveStdlib/bit_vector.mv | Bin 0 -> 817 bytes .../dependencies/MoveStdlib/error.mv | Bin 0 -> 626 bytes .../dependencies/MoveStdlib/features.mv | Bin 0 -> 2850 bytes .../dependencies/MoveStdlib/fixed_point32.mv | Bin 0 -> 904 bytes .../dependencies/MoveStdlib/hash.mv | Bin 0 -> 106 bytes .../dependencies/MoveStdlib/option.mv | Bin 0 -> 1194 bytes .../dependencies/MoveStdlib/signer.mv | Bin 0 -> 130 bytes .../dependencies/MoveStdlib/string.mv | Bin 0 -> 923 bytes .../dependencies/MoveStdlib/vector.mv | Bin 0 -> 1513 bytes .../bytecode_modules/sakutaro_poem.mv | Bin 0 -> 18916 bytes .../sakutaro_poem/source_maps/base64.mvsm | Bin 0 -> 23297 bytes .../dependencies/AptosFramework/account.mvsm | Bin 0 -> 45712 bytes .../AptosFramework/aggregator.mvsm | Bin 0 -> 986 bytes .../AptosFramework/aggregator_factory.mvsm | Bin 0 -> 1729 bytes .../AptosFramework/aggregator_v2.mvsm | Bin 0 -> 968 bytes .../AptosFramework/aptos_account.mvsm | Bin 0 -> 11360 bytes .../AptosFramework/aptos_coin.mvsm | Bin 0 -> 9737 bytes .../AptosFramework/aptos_governance.mvsm | Bin 0 -> 31769 bytes .../dependencies/AptosFramework/block.mvsm | Bin 0 -> 10301 bytes .../dependencies/AptosFramework/chain_id.mvsm | Bin 0 -> 784 bytes .../AptosFramework/chain_status.mvsm | Bin 0 -> 1551 bytes .../dependencies/AptosFramework/code.mvsm | Bin 0 -> 26346 bytes .../dependencies/AptosFramework/coin.mvsm | Bin 0 -> 30131 bytes .../AptosFramework/consensus_config.mvsm | Bin 0 -> 1968 bytes .../AptosFramework/create_signer.mvsm | Bin 0 -> 183 bytes .../AptosFramework/delegation_pool.mvsm | Bin 0 -> 99070 bytes .../dependencies/AptosFramework/event.mvsm | Bin 0 -> 3026 bytes .../AptosFramework/execution_config.mvsm | Bin 0 -> 1565 bytes .../AptosFramework/fungible_asset.mvsm | Bin 0 -> 34109 bytes .../AptosFramework/gas_schedule.mvsm | Bin 0 -> 3987 bytes .../dependencies/AptosFramework/genesis.mvsm | Bin 0 -> 27836 bytes .../AptosFramework/governance_proposal.mvsm | Bin 0 -> 360 bytes .../dependencies/AptosFramework/guid.mvsm | Bin 0 -> 2611 bytes .../AptosFramework/managed_coin.mvsm | Bin 0 -> 4216 bytes .../AptosFramework/multisig_account.mvsm | Bin 0 -> 67121 bytes .../dependencies/AptosFramework/object.mvsm | Bin 0 -> 30726 bytes .../AptosFramework/optional_aggregator.mvsm | Bin 0 -> 11558 bytes .../primary_fungible_store.mvsm | Bin 0 -> 13313 bytes .../AptosFramework/reconfiguration.mvsm | Bin 0 -> 7075 bytes .../AptosFramework/resource_account.mvsm | Bin 0 -> 7447 bytes .../dependencies/AptosFramework/stake.mvsm | Bin 0 -> 91960 bytes .../AptosFramework/staking_config.mvsm | Bin 0 -> 20868 bytes .../AptosFramework/staking_contract.mvsm | Bin 0 -> 52781 bytes .../AptosFramework/staking_proxy.mvsm | Bin 0 -> 8422 bytes .../AptosFramework/state_storage.mvsm | Bin 0 -> 3315 bytes .../AptosFramework/storage_gas.mvsm | Bin 0 -> 26676 bytes .../AptosFramework/system_addresses.mvsm | Bin 0 -> 5964 bytes .../AptosFramework/timestamp.mvsm | Bin 0 -> 2700 bytes .../AptosFramework/transaction_context.mvsm | Bin 0 -> 1381 bytes .../AptosFramework/transaction_fee.mvsm | Bin 0 -> 11269 bytes .../transaction_validation.mvsm | Bin 0 -> 17321 bytes .../dependencies/AptosFramework/util.mvsm | Bin 0 -> 395 bytes .../dependencies/AptosFramework/version.mvsm | Bin 0 -> 2476 bytes .../dependencies/AptosFramework/vesting.mvsm | Bin 0 -> 64984 bytes .../dependencies/AptosFramework/voting.mvsm | Bin 0 -> 35812 bytes .../dependencies/AptosStdlib/any.mvsm | Bin 0 -> 1289 bytes .../dependencies/AptosStdlib/aptos_hash.mvsm | Bin 0 -> 2666 bytes .../dependencies/AptosStdlib/big_vector.mvsm | Bin 0 -> 32615 bytes .../dependencies/AptosStdlib/bls12381.mvsm | Bin 0 -> 9000 bytes .../AptosStdlib/bls12381_algebra.mvsm | Bin 0 -> 1353 bytes .../dependencies/AptosStdlib/capability.mvsm | Bin 0 -> 7719 bytes .../dependencies/AptosStdlib/comparator.mvsm | Bin 0 -> 4985 bytes .../AptosStdlib/copyable_any.mvsm | Bin 0 -> 1298 bytes .../AptosStdlib/crypto_algebra.mvsm | Bin 0 -> 16454 bytes .../dependencies/AptosStdlib/debug.mvsm | Bin 0 -> 710 bytes .../dependencies/AptosStdlib/ed25519.mvsm | Bin 0 -> 5835 bytes .../AptosStdlib/fixed_point64.mvsm | Bin 0 -> 14477 bytes .../dependencies/AptosStdlib/from_bcs.mvsm | Bin 0 -> 2355 bytes .../dependencies/AptosStdlib/math128.mvsm | Bin 0 -> 13890 bytes .../dependencies/AptosStdlib/math64.mvsm | Bin 0 -> 11011 bytes .../dependencies/AptosStdlib/math_fixed.mvsm | Bin 0 -> 9184 bytes .../AptosStdlib/math_fixed64.mvsm | Bin 0 -> 10747 bytes .../AptosStdlib/multi_ed25519.mvsm | Bin 0 -> 11969 bytes .../dependencies/AptosStdlib/pool_u64.mvsm | Bin 0 -> 20837 bytes .../AptosStdlib/pool_u64_unbound.mvsm | Bin 0 -> 20836 bytes .../AptosStdlib/ristretto255.mvsm | Bin 0 -> 23812 bytes .../ristretto255_bulletproofs.mvsm | Bin 0 -> 3421 bytes .../AptosStdlib/ristretto255_elgamal.mvsm | Bin 0 -> 10424 bytes .../AptosStdlib/ristretto255_pedersen.mvsm | Bin 0 -> 6507 bytes .../dependencies/AptosStdlib/secp256k1.mvsm | Bin 0 -> 2859 bytes .../dependencies/AptosStdlib/simple_map.mvsm | Bin 0 -> 19868 bytes .../dependencies/AptosStdlib/smart_table.mvsm | Bin 0 -> 41858 bytes .../AptosStdlib/smart_vector.mvsm | Bin 0 -> 33968 bytes .../AptosStdlib/string_utils.mvsm | Bin 0 -> 8658 bytes .../dependencies/AptosStdlib/table.mvsm | Bin 0 -> 7658 bytes .../AptosStdlib/table_with_length.mvsm | Bin 0 -> 7288 bytes .../dependencies/AptosStdlib/type_info.mvsm | Bin 0 -> 1745 bytes .../dependencies/AptosToken/property_map.mvsm | Bin 0 -> 25540 bytes .../dependencies/AptosToken/token.mvsm | Bin 0 -> 121370 bytes .../AptosToken/token_coin_swap.mvsm | Bin 0 -> 4957 bytes .../AptosToken/token_event_store.mvsm | Bin 0 -> 13901 bytes .../AptosToken/token_transfers.mvsm | Bin 0 -> 10873 bytes .../dependencies/MoveStdlib/acl.mvsm | Bin 0 -> 2768 bytes .../dependencies/MoveStdlib/bcs.mvsm | Bin 0 -> 220 bytes .../dependencies/MoveStdlib/bit_vector.mvsm | Bin 0 -> 9546 bytes .../dependencies/MoveStdlib/error.mvsm | Bin 0 -> 3273 bytes .../dependencies/MoveStdlib/features.mvsm | Bin 0 -> 13093 bytes .../MoveStdlib/fixed_point32.mvsm | Bin 0 -> 9445 bytes .../dependencies/MoveStdlib/hash.mvsm | Bin 0 -> 267 bytes .../dependencies/MoveStdlib/option.mvsm | Bin 0 -> 10322 bytes .../dependencies/MoveStdlib/signer.mvsm | Bin 0 -> 389 bytes .../dependencies/MoveStdlib/string.mvsm | Bin 0 -> 7215 bytes .../dependencies/MoveStdlib/vector.mvsm | Bin 0 -> 16736 bytes .../source_maps/sakutaro_poem.mvsm | Bin 0 -> 17432 bytes .../build/sakutaro_poem/sources/base64.move | 88 + .../dependencies/AptosFramework/account.move | 1335 ++++++ .../AptosFramework/aggregator.move | 48 + .../AptosFramework/aggregator_factory.move | 61 + .../AptosFramework/aggregator_v2.move | 97 + .../AptosFramework/aptos_account.move | 336 ++ .../AptosFramework/aptos_coin.move | 166 + .../AptosFramework/aptos_governance.move | 1183 +++++ .../dependencies/AptosFramework/block.move | 242 + .../dependencies/AptosFramework/chain_id.move | 36 + .../AptosFramework/chain_status.move | 48 + .../dependencies/AptosFramework/code.move | 324 ++ .../dependencies/AptosFramework/coin.move | 1196 +++++ .../AptosFramework/consensus_config.move | 37 + .../AptosFramework/create_signer.move | 19 + .../AptosFramework/delegation_pool.move | 4017 +++++++++++++++++ .../dependencies/AptosFramework/event.move | 97 + .../AptosFramework/execution_config.move | 33 + .../AptosFramework/fungible_asset.move | 778 ++++ .../AptosFramework/gas_schedule.move | 76 + .../dependencies/AptosFramework/genesis.move | 512 +++ .../AptosFramework/governance_proposal.move | 23 + .../dependencies/AptosFramework/guid.move | 68 + .../AptosFramework/managed_coin.move | 205 + .../AptosFramework/multisig_account.move | 1881 ++++++++ .../dependencies/AptosFramework/object.move | 807 ++++ .../AptosFramework/optional_aggregator.move | 295 ++ .../primary_fungible_store.move | 322 ++ .../AptosFramework/reconfiguration.move | 208 + .../AptosFramework/resource_account.move | 262 ++ .../dependencies/AptosFramework/stake.move | 2759 +++++++++++ .../AptosFramework/staking_config.move | 680 +++ .../AptosFramework/staking_contract.move | 1315 ++++++ .../AptosFramework/staking_proxy.move | 228 + .../AptosFramework/state_storage.move | 90 + .../AptosFramework/storage_gas.move | 622 +++ .../AptosFramework/system_addresses.move | 82 + .../AptosFramework/timestamp.move | 88 + .../AptosFramework/transaction_context.move | 83 + .../AptosFramework/transaction_fee.move | 397 ++ .../transaction_validation.move | 300 ++ .../dependencies/AptosFramework/util.move | 16 + .../dependencies/AptosFramework/version.move | 84 + .../dependencies/AptosFramework/vesting.move | 1871 ++++++++ .../dependencies/AptosFramework/voting.move | 1108 +++++ .../sources/dependencies/AptosStdlib/any.move | 57 + .../dependencies/AptosStdlib/aptos_hash.move | 253 ++ .../dependencies/AptosStdlib/big_vector.move | 469 ++ .../dependencies/AptosStdlib/bls12381.move | 985 ++++ .../AptosStdlib/bls12381_algebra.move | 802 ++++ .../dependencies/AptosStdlib/capability.move | 193 + .../dependencies/AptosStdlib/comparator.move | 173 + .../AptosStdlib/copyable_any.move | 45 + .../AptosStdlib/crypto_algebra.move | 345 ++ .../dependencies/AptosStdlib/debug.move | 278 ++ .../dependencies/AptosStdlib/ed25519.move | 262 ++ .../AptosStdlib/fixed_point64.move | 447 ++ .../dependencies/AptosStdlib/from_bcs.move | 91 + .../dependencies/AptosStdlib/math128.move | 310 ++ .../dependencies/AptosStdlib/math64.move | 266 ++ .../dependencies/AptosStdlib/math_fixed.move | 139 + .../AptosStdlib/math_fixed64.move | 142 + .../AptosStdlib/multi_ed25519.move | 482 ++ .../dependencies/AptosStdlib/pool_u64.move | 571 +++ .../AptosStdlib/pool_u64_unbound.move | 270 ++ .../AptosStdlib/ristretto255.move | 1310 ++++++ .../ristretto255_bulletproofs.move | 253 ++ .../AptosStdlib/ristretto255_elgamal.move | 234 + .../AptosStdlib/ristretto255_pedersen.move | 158 + .../dependencies/AptosStdlib/secp256k1.move | 114 + .../dependencies/AptosStdlib/simple_map.move | 319 ++ .../dependencies/AptosStdlib/smart_table.move | 544 +++ .../AptosStdlib/smart_vector.move | 766 ++++ .../AptosStdlib/string_utils.move | 146 + .../dependencies/AptosStdlib/table.move | 152 + .../AptosStdlib/table_with_length.move | 141 + .../dependencies/AptosStdlib/type_info.move | 350 ++ .../dependencies/AptosToken/property_map.move | 383 ++ .../dependencies/AptosToken/token.move | 2700 +++++++++++ .../AptosToken/token_coin_swap.move | 162 + .../AptosToken/token_event_store.move | 340 ++ .../AptosToken/token_transfers.move | 275 ++ .../sources/dependencies/MoveStdlib/acl.move | 46 + .../sources/dependencies/MoveStdlib/bcs.move | 17 + .../dependencies/MoveStdlib/bit_vector.move | 157 + .../dependencies/MoveStdlib/error.move | 88 + .../dependencies/MoveStdlib/features.move | 339 ++ .../MoveStdlib/fixed_point32.move | 295 ++ .../sources/dependencies/MoveStdlib/hash.move | 8 + .../dependencies/MoveStdlib/option.move | 356 ++ .../dependencies/MoveStdlib/signer.move | 21 + .../dependencies/MoveStdlib/string.move | 93 + .../dependencies/MoveStdlib/vector.move | 633 +++ .../sakutaro_poem/sources/sakutaro_poem.move | 378 ++ 283 files changed, 41914 insertions(+) create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/BuildInfo.yaml create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/base64.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/account.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aggregator.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aggregator_factory.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aggregator_v2.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_account.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_coin.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_governance.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/block.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/chain_id.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/chain_status.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/code.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/coin.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/consensus_config.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/create_signer.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/delegation_pool.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/event.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/execution_config.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/fungible_asset.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/gas_schedule.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/genesis.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/governance_proposal.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/guid.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/managed_coin.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/multisig_account.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/object.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/optional_aggregator.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/primary_fungible_store.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/reconfiguration.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/resource_account.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/stake.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/staking_config.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/staking_contract.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/staking_proxy.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/state_storage.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/storage_gas.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/system_addresses.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/timestamp.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/transaction_context.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/transaction_fee.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/transaction_validation.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/util.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/version.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/vesting.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/voting.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/any.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/aptos_hash.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/big_vector.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/bls12381.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/bls12381_algebra.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/capability.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/comparator.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/copyable_any.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/crypto_algebra.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/debug.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ed25519.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/fixed_point64.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/from_bcs.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math128.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math64.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math_fixed.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math_fixed64.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/multi_ed25519.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/pool_u64.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/pool_u64_unbound.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255_bulletproofs.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255_elgamal.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255_pedersen.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/secp256k1.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/simple_map.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/smart_table.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/smart_vector.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/string_utils.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/table.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/table_with_length.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/type_info.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/property_map.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token_coin_swap.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token_event_store.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token_transfers.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/acl.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/bcs.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/bit_vector.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/error.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/features.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/fixed_point32.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/hash.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/option.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/signer.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/string.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/vector.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/sakutaro_poem.mv create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/base64.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/account.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aggregator.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aggregator_factory.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aggregator_v2.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_account.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_coin.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_governance.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/block.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/chain_id.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/chain_status.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/code.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/coin.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/consensus_config.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/create_signer.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/delegation_pool.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/event.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/execution_config.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/fungible_asset.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/gas_schedule.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/genesis.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/governance_proposal.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/guid.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/managed_coin.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/multisig_account.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/object.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/optional_aggregator.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/primary_fungible_store.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/reconfiguration.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/resource_account.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/stake.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/staking_config.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/staking_contract.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/staking_proxy.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/state_storage.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/storage_gas.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/system_addresses.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/timestamp.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/transaction_context.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/transaction_fee.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/transaction_validation.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/util.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/version.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/vesting.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/voting.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/any.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/aptos_hash.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/big_vector.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/bls12381.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/bls12381_algebra.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/capability.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/comparator.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/copyable_any.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/crypto_algebra.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/debug.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/ed25519.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/fixed_point64.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/from_bcs.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math128.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math64.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math_fixed.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math_fixed64.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/multi_ed25519.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/pool_u64.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/pool_u64_unbound.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/ristretto255.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/ristretto255_bulletproofs.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/ristretto255_elgamal.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/ristretto255_pedersen.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/secp256k1.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/simple_map.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/smart_table.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/smart_vector.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/string_utils.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/table.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/table_with_length.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/type_info.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/property_map.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_coin_swap.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_event_store.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_transfers.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/acl.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/bcs.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/bit_vector.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/error.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/features.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/fixed_point32.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/hash.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/option.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/signer.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/string.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/vector.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/sakutaro_poem.mvsm create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/base64.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/account.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_factory.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_v2.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_account.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_coin.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_governance.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/block.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_id.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_status.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/code.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/coin.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/consensus_config.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/create_signer.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/delegation_pool.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/event.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/execution_config.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/fungible_asset.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/gas_schedule.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/genesis.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/governance_proposal.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/guid.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/managed_coin.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/multisig_account.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/object.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/optional_aggregator.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/primary_fungible_store.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/reconfiguration.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/resource_account.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/stake.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_config.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_contract.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_proxy.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/state_storage.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/storage_gas.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/system_addresses.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/timestamp.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_context.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_fee.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_validation.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/util.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/version.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/vesting.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/voting.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/any.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/aptos_hash.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/big_vector.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381_algebra.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/capability.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/comparator.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/copyable_any.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/crypto_algebra.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/debug.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ed25519.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/fixed_point64.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/from_bcs.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math128.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math64.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed64.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/multi_ed25519.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64_unbound.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_elgamal.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_pedersen.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/secp256k1.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/simple_map.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_table.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_vector.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/string_utils.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table_with_length.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/type_info.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/property_map.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_coin_swap.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_event_store.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_transfers.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/acl.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bcs.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bit_vector.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/error.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/features.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/fixed_point32.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/hash.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/option.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/signer.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/string.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/vector.move create mode 100644 packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/sakutaro_poem.move diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/BuildInfo.yaml b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/BuildInfo.yaml new file mode 100644 index 0000000..0b47319 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/BuildInfo.yaml @@ -0,0 +1,33 @@ +--- +compiled_package_info: + package_name: sakutaro_poem + address_alias_instantiation: + Extensions: "0000000000000000000000000000000000000000000000000000000000000001" + aptos_framework: "0000000000000000000000000000000000000000000000000000000000000001" + aptos_std: "0000000000000000000000000000000000000000000000000000000000000001" + aptos_token: "0000000000000000000000000000000000000000000000000000000000000003" + core_resources: 000000000000000000000000000000000000000000000000000000000a550c18 + resource_address: 718f20ae37f309e0aa59fcbe38eb731b73f01aa1459a01d1e157f347c3c6db6d + sakutaro_poem: 718f20ae37f309e0aa59fcbe38eb731b73f01aa1459a01d1e157f347c3c6db6d + source_address: b21de0e2a7419d35d5abde4baa2a72159cd3a7cea042defd0e54b1faa022a474 + std: "0000000000000000000000000000000000000000000000000000000000000001" + vm_reserved: "0000000000000000000000000000000000000000000000000000000000000000" + source_digest: 67EE3426C175AC9E313E02ECA53E236AB30B379178713045EE56EC5A5EB199F2 + build_flags: + dev_mode: false + test_mode: false + generate_docs: false + generate_abis: false + install_dir: ~ + force_recompilation: false + additional_named_addresses: + sakutaro_poem: 718f20ae37f309e0aa59fcbe38eb731b73f01aa1459a01d1e157f347c3c6db6d + architecture: ~ + fetch_deps_only: false + skip_fetch_latest_git_deps: false + bytecode_version: ~ +dependencies: + - AptosFramework + - AptosStdlib + - AptosToken + - MoveStdlib diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/base64.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/base64.mv new file mode 100644 index 0000000000000000000000000000000000000000..28b28331beac1dfb36ea740c50e5757d88925ee3 GIT binary patch literal 1594 zcmbVM%TE(Q7@wJ)ncbb4E|kZ%U=uBbdLY`4B9BA_v;r!=5d<})KoL|ZPy{tG9z7W2 z-J6LqzWoo3iHUa)dhwz+3>Olv9{hGo7YJa2lg&Q9{e8dR_n2><#g-&T2w50WgI3Zi z!ggIX7qs;fxAR4uR&U9ojS$9&AdHaV-6(-~Mj1v1!CVjw7m?Uo1|dWc1FW{^6BWc1 zVA$rim6;ge&wMgIoXKY!8~A*7WG*+$N3$cj(JaqSc@H_A%MazohDOFSv(`j@C_6bl zcX#H=p7%{F_RrS?e?B%Z<#*+mtDhZziogEqU+Mb%<;NuC`L6|ebhLLIJ(fP++0}jG z9rM~{l1B032km(m9gHXLef zYHq1d`c?XX1!_i=TMDy~KplkBRpBbH*#4?fSYlc(5pE|%8}YD8t{IdF@QMpAWG#Jz z*=~UZ=gAMFe@X)O_im+~55lLw8 z=HL5kl)?IJWk`d*fZWzI7SyefkftsH#iX?K;g}|?%0@9tPx-#@8kkmKVJF`@CLPad615XCg^u8qJgC<=wY1p z08t4LIkLoYibRkTO%{kk5mA{Yg**GUk)_zmIDLqLCJZ#CGVGLYpz%HeJwME4e}5F| zRXMno$#SP`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akutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aggregator_v2.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aggregator_v2.mv new file mode 100644 index 0000000000000000000000000000000000000000..7731d9c87ec8d9ca7a430208098ddc5f7b5229a5 GIT binary patch literal 297 zcmaKn!41MN3`OmvNz;}BLL4}7fC~e#0Vf9N096#Cf`po?4V4&&B^ZSv;KB&F6!nOu zIDX%;m492l5(xkiLcoHUj~8OI4);#oaU~x(kDn+b!TsmFNo~H!32Vj4Uz&2AmFj0NS%Mq5uE@ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_account.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_account.mv new file mode 100644 index 0000000000000000000000000000000000000000..fa79af958da7937fe008f73e90c55357168bd5fa GIT binary patch literal 1583 zcma)6&2HpG5U%R~>F)82CzBsGOE%dJWS3 zeO4{Mx+=-B{5+nWuMRytuw8UrX!{L=JbY7ieRupGT6K9Fmb4SvQ08Y%n-jz2UC}Sj z^M0Lh{?N=L@$P6*)a1Gd)lJCDf#k4p=hY?a+Sa9uSi`ssS4~&-s~AtZK>RK)n%jSm zU^Wbrjk5B4REOJ#ew+R7U=^-t-&KUQ-@eCb|9WWKLo^>6-npTdUletD5k{+Sbwkf6-vGC zgDuLEZcdjsXEt0?Uj{1ESl^)K=K~#cTlMEW^bEZiiw#O~#Vcec5+vtH phhD!_TFl^3Oh`>VPk6>60mm}KMv($4vViPSX6fCg*EHURe*m8O9lHPk literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_coin.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_coin.mv new file mode 100644 index 0000000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poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_governance.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/aptos_governance.mv new file mode 100644 index 0000000000000000000000000000000000000000..0379c35df03348fadaae039c63c0a4494ce7e275 GIT binary patch literal 4920 zcmaJ_*?QZ?6`mE_fFwYXq9n_!r#2;oJ$6VVQ-qv^BxFqwrznQg48uAXgltGa=OoTN zPr>H`c#=&lk&BK?$R!WMmY!aQ0OX2|qh9hczgokvUB_@uL)Z1mHyR+m8DNM)OkZhY zxTT42FJO2T#H~*twh)hSRO?fFkqZB_CB=mBKVM$apD&J4e5@Z*MZ}jN3VyVBoCH5U zL5Tkox(1Z`SO&VWcQ>30d*Gatqt7iGK z!me-v%GQ33QbC{AUZGa=8GV&;QF}&TW47?F!NjctTS32XmfyhntsC|^Dq6p|gB{^7 z9ZIZU!8p#Z-y+2Rjh65BePC+8rEjk=&YE95px|<>eY}05bF#D6SwFdUa`W^>>you) zUAA6oU%jy1zIN&QmDg^*(Y|xx&aFGQ@7`SRym{%Z_WjP=?Fa4kD{EJ--g>|N!KDvx zUcF5@k(Mt#rvI6NDvvpMt@$#zGs&r>KEoPjmM=J`fbkyy;}~%S$JFsLdfek6!X9or z#MVbsC!k=!@me_CB`&pG!t6ts+AheexyExxISO+v40RN>95sb2ni`j2S`pZ)Mjfg` z2})Uj!Wqt&s@GKSE`GKP?V zD5JK+Y$wn{*j(C<)>FcW+6ADWNo1@z3%vYot-o(CwW>d9PW$9c{a|9WMB=Ga_{DKD;t;nY}ClpZZ_KK?@sbW z&#j`rJ4$n}=nuz(G#(~nRSc87jLYQlAeBX#JW1<%?2mTi=}xOCbIgL`peWN}ob-C& zT%?6GTimigOtE1&w)V3Ube+3nh_avd?mtVr6V3BsQtUz2dpV>|Kd!{QuN4U%%=Nx! zq&%`<2#U@j#V2Vo&PK)K{-9qTxSv3;y!T#u5Pml9;oRwdv&sEDD^mm2070ZFZP9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4p0HMxab77VlYbsUWm?u;p+(crbl34?h6=M!pIiPD`8&IWLw%I zBwE1R!rN~0EspPE)7e5;N1Z0wA}oMNR9pCUEG;$NEtjE%61ZesiXQ@I!5^+L-RYyb z0%drQq1mV8^;MI1%R)-W_DnQx;s*~OePSJ%dKr<;#InL9TA@@PQ|NwL@GcP)*#=RL z;WvPA!C0z2T}MbkXcn#3+1#(P0_Hl0?`T9(ZV}ZHT6>X4wP6jsrBZH)(ODMya}|o!5y;3!Wo?K>xolDq+*s%! zMYwXpcX5gFx#DNVhP+_gI+@?|WgR(!CLA(GYkCvn!bUvbhk$NFDto>yI_0~b+wu@q zZd-l{yn}31f$iB*xF$Z5pDIOdqOSqfu$ApZr;U=X?!%!d?uMovozdK;SM3v641UA? R&v0XMG}HpWbD>{ls literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/block.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/block.mv new file mode 100644 index 0000000000000000000000000000000000000000..3b520177fc436d354c6d87c90395cb45ae6f3b78 GIT binary patch literal 2068 zcmah~OLH4V5T2gLK4w;0tt`v3qu?Zj7!vZ}Ey%@{s#FmUP(>Bzt@UawZ$;V_Gbk2Qv8*H}z^tn^Gu_kuebepfpT~cyfDn=Z8PU;*J@^s$Gw6!n z;p^~M`Yeookk^7=+LJ)Bq6t3^YIDI?8 zDZASh5b%3|(e48f^&m$5J1LOhU33(^Cvf&Y&Vmn6D?jWb&X3R$n`{9D@?+G*pI``h z7!4p$q9eMU-Oji(-rn7g62X{|Oj1T5VL=iq1`&QVNCYsHj6)ca2owhfK>`B6&12&J zA`E~BVnUr-GG_`D-3UgVrx@=D{4Ye5qLPI(U29ueaWrqrr(sc+&8lvNHl{H`pX$1e zj&;$ljJ83uY^$bDjV_z|xSFj@;nu>o#Z%ou+3MW3jVWfjXTPaa%1k znk<%SYl_+yr8}A*Yu$O|0)MG(vofXbe6G*@#$y+H^wn~TULP-;^5jX~YI9o5y`t;U z=1bGeo7qZ_^rC9>HIw{Y=dmkq{b^B8=X&6cYJK*i!LHvtGgYgtZeP@lX1Fd_#vqRM z{)w(;C+&_?Xa^~;)|hguODn6oYO7*ieW&+V9`|LdMOB){nFi;cx-Wa_UBYI^uXf{^ zS$H7mPDd)gqU{HSVAbs6DJEits&IWDTXp1Pa!Yosu(N^LWj zpZo$~Q%`NbnNKef=sSQfV-CLXH4zt>WYgxSi@nNjZtdI@b5>y%8Cao z{|dRgMfH4B_t)-c^X90Sdv&j>J=wf4v(*BNOZpP@N$u6m*-J?nuJ5&2whfXs#X_Go z=Bcj~eJm-T&Y%}|7J;b&3*1!JzuLVAKe3$L9EB@gcJ4t~? zSH){=pY5`1l3o`#Bzv7vN^i0^90q(nKkJe#l04+sc^oB?NF>kVBvKJiML#5&JeZI~ zIfEN~jJjk3i3-JSlEgCZkqMP?3fl@4RSY*^paRLIkYOJZ*(InYN@g@m`NOQIc$O)p zMApx?vVjV-?Hv{O=-?KAk_}yZ0Mg66bLbKUDG9l2P=5S#a+qD{LVk#SvMUlc*l+SsBns^* z0+ZNf*F$0Jn{Y)YqEGG;ip>?saEw?lAC~^)h5#KTOaj8E+lr>xsTB0-B%s*GF*>%g K5EyoJLjDF`II&3p literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/chain_id.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/chain_id.mv new file mode 100644 index 0000000000000000000000000000000000000000..c1c9d214c5dcb3b06b764aa5e3f7d9d9c79caa69 GIT binary patch literal 273 zcmaKn!HvQ&5Jmq?5<5zQU=e}~2jGgRf)i&7h^(~%3kWE-gm&wo0h-`KEr*IbG*|BCa$m?vzyznsuJU-4`(kj3fura3N!WWD@Gc zEGi~Z$*pOOvo8PLDcjUm_uQZJ=2$DOTjQK@av8}=CtKqS+gNYa!TuYzdZ+?#eXY*^ t7wP&WC70}IY1qIy)8n4^aQQ`D9Pez*+d`&fiwF&_iBC>8(! literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/chain_status.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/chain_status.mv new file mode 100644 index 0000000000000000000000000000000000000000..ac8e45a10ec0aee59ec7adf91109595134cf71cd GIT binary patch literal 451 zcmaJ;F;c@Y5WG8CvSS;PP*721hJv9;2|r+{@&=CvU4kaDosk@vyn&Jz@CkYvK9f%% zB~GYd3u(2wz0saNu6Bh2fE+=QN<@Awr&)UUiP;V(>W%L6FOuaq&4%xS0D(Y2k^#uz zfoOy@sF1~FKmb?>0aOMCh^R^w>4F>f)|XGu+BTK%bhq)6oon65Z+*vgrHygyJ^Rt) zq4uFMGwqh_&UKJoSM@zc{jpuM)17S=x%J1pGSHJg^n5Z^+?c{_>UvwvEw9X(ZC>=s zn*CGwvTv!^UF)m4(>1@gZW)vP0~A?|7$LF{eGfV5$zNL-ABI84`gBZ*kSfKoydgX& f;#Z-lBq`m(ghb>b@?eS99LB1E!39jicL4kVXk<}w literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/code.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/code.mv new file mode 100644 index 0000000000000000000000000000000000000000..300cb11f8d08c57a28b54a30e5777d9a717edd26 GIT binary patch literal 3217 zcmai1&2Jn@6|aw1)zwusJ>BE6GtSycCbNmjW|t5MU?By?Sqq_+qFu4t3kbE^GiAG# zneL&xXOmfp%bqwOKK=yY0EhzzIIt48l@KTXk-c-^#H*h1$65ln?5g+by?XUNe)YQN zH#=V#NeD5N^jZHt|IPybOhNpG{+kAWDw;Bp`4vpt$8eN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bJyh)2jrLo1AcC(25(k9>D%rIGMd*+3j19}jI{0{EW7y1j>dGPKGlcwgC2 zd}v6}8`{u>3_nmQ-1-$wjOExHJe1o~zKNwwuvh_Wi-_@p1|RRPA&>2ie=6WQKHF{JLHj@I~jIf5hc6p5aec-t(xkNDOdymRQ7 z#5?yxWWxTX+9akE(a0p+Ac(||k@L4oUedtam>xpDL%ZRo2451}^>Owsb`KMd;1jH0 z*Qj>~o8qTP(8EEp2|uIQBaFfFMKNY1(c+h@l{FtSMS%jB27f{9BLI?sh4{+=+qVBn iK{$U*dV<*%Ns;WVNQR^!Tu}V}X81FL6Gl1ZjQkfr_>aE; literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/coin.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/coin.mv new file mode 100644 index 0000000000000000000000000000000000000000..80b7cba91abea68a6949bc1563a2cce28e795080 GIT binary patch literal 3986 zcmaJ^Npl<55q|4zZ?FsjQq)Efq9{@ewOJxTkrFM*cI+gI7ddwJ$q*P&NPrpE0JKc~ z0N+zNmnsa_aE;;0qKafhkeglAvRAm&|X!PrSdDHW!3;!|>W30;AqFDS) z{^mbI{Zro5zgOQ#_Ydwjf%k2+?EE$QI}d)>_|*KPQ4Rmy_;XPCxFqT@#EfKIakMu&@cU^Y(1P!ZRLYiw^UzyUf{kIb-6f zV(xoT{XNAUZa#GxI}2%cPDsG>iUVHI1TS&{xa1IiiIeQIM|jI8csU@rVhCOd39eQ` zz^he)Yc+!Fmj7CvPH#kWfHxaWz>RsrZ#4jJTk;*T0Q~M5g7-MVcP!=pB8fgYOK|fX zsodh{0ox6tJmePucPwT1B2gY$Q;+TG-Vz1$?j@3X!U2OHz@Yk}L}H%w!n#@7K~ToX)v4hH?>o18o1i(4B^eTm=VliQrhpWM02yq`9}^E1%=pT8rS z`-}T4%=u;O0o4791Bw`&ZVa9L*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ZRu|-e_M+tx#z+kw5&hpZFpjyC_zb?2I3(QTKchavK=PQ5DWH7s?5DN=ddLfEoYnW z2yvD=i5u#qW#xEiS>U0y!qIDK4LGCsdQ#X@x5xy+^1sx`m@#ICTrwb<~`$pgL=+NH<*SSh3bRhMDL4LIH&f|T`&P*WWdD$+AB<;vvDWc zfp6$Vh?fH|H~oOm`R#cl%iBlb1r1tGrU-fV@Nz7eq)Ql4px8{}<$~KARkgIeQ@xho L3R);7ZaDToS&Ek1 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/consensus_config.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/consensus_config.mv new file mode 100644 index 0000000000000000000000000000000000000000..17afbb8c58af64289af285be8e3b8d4066306df1 GIT binary patch literal 439 zcmaKo!Ait15Qb-xHjPc!ZWk2<4|`Aq(d*vD2PwhMEL`audn5FjCg zTmvZHpx{Gp2m~y%41_@@R8=ymDikQOC`GX#PtnEkdG90nxQZ>Sxm)BELLcft>va`u za=jnN+n8wC+O7)}BgOjc+sA@!rSmR1d+F{-MoMb!-m%Pv)Y_}m$95j&v09Q(=I1-&?Eei)%@K#mr(fc)i*uvq+!6pMB{X6aPvvL1!|Z1|9~r;`8hL2A f@Clr-fop?&%lt;00WI(dYN)tZBet7N43B*PawJG4 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/create_signer.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/create_signer.mv new file mode 100644 index 0000000000000000000000000000000000000000..3d1fd12c6acc4930f8af3888716905b17b8aa53c GIT binary patch literal 156 zcmZ1|^O~EDfq{XYk%5VsiItU|g`L}l!(V|XpM}4ei-8pg85tN^8F|==!+|rzq%;L;+m;_sXQdVkm32$;yYGO%hJWwVtwFqbrKETMp P%mk7LI)#CmfrSA8Vw)ZO literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/delegation_pool.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/delegation_pool.mv new file mode 100644 index 0000000000000000000000000000000000000000..d5f3b4d602ca5c3034439a76cd6d42a017cc5d91 GIT binary patch literal 10777 zcmbVS*>f95dhhP(p6Tfx90LM`L{SncQny80vSh=OWgV1!O19RrElaiqL&S)J1p+hx z>ah39X0y5PO|sc+j?J~XHur9>O;UNybMlb?AXWR8s=VYS`F%YDfTWJv3Z-fE^zq%- z^vpM>zi)lUnB{Cn%rw0(^M6a)#$4cluL$l8k(Aor==ZK@@vclL21@O;Pb8-@pUyx`{g;mB*TlCI^TNpdL6^j?A zu?~uS*@dw; zskuyh-y(wE)Jf?n*Yt7WpyY?5T)xXG}@>uSx{OO~@6W%Xz zh{K+NIP@>`X-xkLe+~m*Aur1L-H?_6Q>&-p&$`!D#roaKP?s_>-#ORlf6 z++XphIX2n9CJ?#r@H%*8x$p9ec^bV4N$J1gH#E!rEw48*r2mdzgB1UsUz%l>bff>l z3E_Ku85rKddh=c0$_v5FSNTUIF!LRL`zY?ce{@p$Cl1Zn>sWYZ|Kh>djx3&d`}xIF zS5IH9T|Iks@!Gj-C$62UUr0{3_TRp+a^d!oYX`5rckTUaA6&cMy|8+ueq`~z{*nHL z#p{djf3o=L;%65>Is56^&z}9X_UY-xbBiB%egy0Ed|gl;ms|;7OXUUBU{D4+P}~zr zdH4_QOWfg)R{7fF9Bskv^#R8S`p3Bu1XT%wB9tfH4$KO-m*55jJ@T+vYd|ehYqN_PAbtpu^h7F=PQKD`x*;t>-!|?ROlpr%(&Y))nTA>DuO-nUF!@?V|CE&*O$7jPBHB+ckd*Vw9OcB1-&#_c3eZL6~k44s>;W#y*A zL2D(!#LB9FCs`VFd$}{s=4D!bp3qDz_JAk3)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2GTTk zA?9Rr0p`SULfM(zfYJgNEgvG$87O?Ufy0LX2ZfW4LZhwPOyT5XD4c|4fI?KlKM;ik z3KX7n=G^UXD32%bz&-(MiK0B7Yx485MAd=uMxHq@t7VDbp1M2(U0=TX8>*$Kn}P7e{KsJ2hM z;8^AWKcZ(IpQa#l^Pre{D-;ZeiBH2RPl;0`($y~k=4iw4$irnDBwWO9ayTk2bz9 zEe?T_EwmRSd~3uvLa4(rMb#C$I{uiRWa2Lv15>`Q+UcEj(!p^I03ce?Q45j_Ra}K_ zC~1MQl&|f_V>>?ZL$tRH-$mgoNPK36=RQy1Gbenvi8CM>FsZ>&NT1OJD1HMTNR*oY E2S<3bUH||9 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/event.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/event.mv new file mode 100644 index 0000000000000000000000000000000000000000..8209b889e0d5edc361dbc5d001924f6fe5b8dad2 GIT binary patch literal 607 zcmaJ8S%5S~Bpu6J{nTy)StK?gMjIjATS0X;M{C*OGiql+!sdx=t}M4~}Zq)3xz z$^-BKJOqq4M?u3_{&wd3X2#ac-aPyj3;;|KJbBOam-5yW@1NSQc#G~QJu<(Q{=zPN zW7_-9mpJ($GQASnzZL-k27v+$SV4obr@b5?8Yqbsy^I)&5%p1=SW=v3e%~q22V4Tp z5CIQ;KrrI%*en2+fQ`5z8Kc?u(R_k@QZIkI%pW`|e@hrB9SL>mO zec$!&L#)!akAr;NHgz}|)z?*9Z=%g*v7gp)NPTy){FG^lr%m!BEORS)_3q8_K^xES z!d=#b^S()OdD_+6P24G|TMnt~$&E1Y$V= literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/execution_config.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/execution_config.mv new file mode 100644 index 0000000000000000000000000000000000000000..0884b90e9f8bd39e6bca319ea403a64d168a1d15 GIT binary patch literal 400 zcmaJ-OG?B*5Ur|CciMEuB%&@vBnv?lU3df$!CQo8re+A5M7k3{cMt?`;7vS-xNz?! z?93?crZ!cN_a4Q2Z~Nay0f0f!q$81T%d&{iUr@heslM6)?CQ^VxwHw-y;@mzZ4kJ=vUh#wtGTlcKXmRUuiJZjThA)%7DK~r zZ~lL9$hvM&X#C}6xlS0k5O&NNcDTv}3f#ntXl!#ihmn>O6RLoMj$%B9Xm3P#0vV)a S(9n)NFroP^ID)!)N^QTMM==Ks0=N5A^prDd$3gb_{zkwg&(Dm4BT z{9U6>6XN4v#XkTq#IuHHqzJD&lu$myh-iQ!s_77ZM-lc|P({fs^pY0igv>EeR|Kb; z%uB4j>L`#48r*9Y7v!SwFfRFqy<9cpiXE>9hQ1ME&1x+qWG$)_vL4M4vJo{1*|ZDV zq6wibF^lnL3!=A-x$QZ~?_2?Od)_G76<0CtEnt5Cnqk~sY!Y%HD9C$u?V**3m(1k- zWh{KKV#tTrLyV7ZK;1{HhWuDyz zhvpEk6eI#>4meon11G8-swxl}~*r3rt`YLUT_U$0Ds*1!ZjmMaC(Gs8=&W8uiDhmP|TY%UsscQs#>s zD+DoAG{OMk6c6BK;*uu13bEo6%WKeP1~{tB+Evb zOx`5vM2(JqogCwFHtCO2HSV9LNv6h=te>7bkI%F8Wpd&_NzO*&{^Sd@zS-m z^aDpK{jmuIDRG9~cm3h{P!5yqG?|$OZo|wIFO2GFs=tibv7E_Bq}^dsd6Ep0N%9ho zXUTB%rT`*Df(tvHlR@{?xA1h5cm45X9ON%kizIY%OxCM7WyJN9fTJ?o~uK@yfa^SNriqLaVr{_!a7oM(OS zEE}1=Ftl@go@LO}I_{>OGABI?lL@8PPv3M0{a&Y=ot_UN7?wgsI}MWbbn@CColiQW zlMa%3nq1BME>8}OPOIA}42n6_b(W0B4yNBE*`$^xZ*xC8uWc-qbcC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oa Q%TsD`yqLuVvtj-J0reS8761SM literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/governance_proposal.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/governance_proposal.mv new file mode 100644 index 0000000000000000000000000000000000000000..f875f4891923a8e70a855b6ed94991118020a809 GIT binary patch literal 224 zcmZ1|^O~EDfq{XOk%5VciG`Vsi&cPyT_lU6PJwG4BP-8hMq&PKj7$tbX`nJ@AkDx6 zA{aRs1QH8M@{8ls^UG3;@)GlsQ-u-C_=2MRg8bsd93gkObO2OHG`T1>u_QGcpBhYaS3`~NIOpG7~Gp7&(6OaY~%QP>< literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/guid.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/guid.mv new file mode 100644 index 0000000000000000000000000000000000000000..cb82778583f3ae4e93910a1920c828396fb1327f GIT binary patch literal 448 zcmaJ-yH3ME5S-n6*>|=QS%!)NL_^ItL_+z1)K>6W$Vk{Cj|zznQScS~5&uC$O~u+F z2^Cx1?2KksxBGtf87zQ6VCF>mD|3D67Ej3so!c++{+sgbm7nt$WhZY+gQ3K)9biC! zWd%5GfJBR)x&-iAw2+FHr50?QqC`MmBAb8|85Xoc2Z7+0b=_~fjqPvmn|h<~wr$im zi}{S_Gh45k<)%q@P_;1|ySDGDZu>A9Nx!O=F|L~R+BA=1;Wkd%Sp78?dw%rlAtS5* zSEOX0-(vFeV`isv1KH5zp300pTe-tnr-4oa2NYC*NmQ=`4U~BxCSZywm8_18OV$S# Z=z`5ICeCskEF;E@+v}2mTz(iY@B?<|IaUAw literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/managed_coin.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/managed_coin.mv new file mode 100644 index 0000000000000000000000000000000000000000..b634a5d2d3b9e8854d97da0a508214e3b4f10bae GIT binary patch literal 739 zcmaJ)~MfoN#xa|j_MBGDi!et>n!t<6fw*}6N+A}tM~r$&fh zL(iW;l!%_WO+-4jcsDyU@7-wLetqyO7yy_ec;z3_lh=HR`U7_M5B@;+ogSK>v?^^&P6#%P7bTs0G1!>L()WSKy zdoYn^<0Z={aSCW>K@x60rk4vzW1$#p?ZkQ;Y_!Tm0&Sv*MQUAOH_pEqri z&(P&|6VK{heV#A#kWyr5l}mk@uM=P8c5q$V_2}dN+G1!9U)6zwT1H zPGe>Ms)TnnH!2j)8wu|6zHXW>_5EtQp0wLxwchUAhR`z0NaF78QRK_+Vp-m-YzC}&jG&hu797QiXTVlRvB1JYKMv|SL<$hFl5L+t zh4Kg(!m*ds!Ub_ZP~b{M8^u6r)WHP%6kdRMD#Az0Fbb2WBJ6KeNmMzAtEX6z(B$=1 RtVonmepYEE6DzPX!(Z$YW$OR{ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/multisig_account.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/multisig_account.mv new file mode 100644 index 0000000000000000000000000000000000000000..8ce69926766eb4d4a0ac8000dae4877164dfe211 GIT binary patch literal 8060 zcmb_hS(h8fb*`$e>ZPjDjmBVx+mM`%+ipGx_)dZ4~=f2F)%nIF&i|2;qFe!cKtT>oV0KY940qd(tU`Nd01 zSi_lM4wFnVmwC)*0n^N|kX2a3Vpe4dtAX_t{_6Of_86PN_a2|Iy$)mh@V6g*2hcZ* zzk~QYgulZsi%xiqpLChI;Bm$(FM0yfSlp1p;f(t&$z3jfmxIw9lwk7$WC25LQGzTf zkRvY0QCfb?4;VX6WLe{J#e|HVs#F*|9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XB(q}v8+XnHv9P;y5M)?QArR; zu!#f+s9sR!9+1jnSk0tI#FFI~5QvQL(MC+v(UD!b7Vl`sK5F~me_Bf$h261_+1}BP zdt4kR^*;U>Sn~-`K?C$F^D=-p0W|=WW3-;I5Qrb3Y+wP>AT;R|Y|zt0#^XzO@p@6- zRL3J+64k#`{_1mKY5 znoN(YkFZpnAjQA^Pl!z7Y9wo@BOWHZsit&-RP&*bzX)JRbOJrRFpLBwsX2K-Eg0Os zYwlIZ%qJy>7$W!`v0IWaXdUBlk)F^RX9Wh})p5n}8cUbqwDFlcG&797sjwP}a2HCE z<~67kX#A|ODDSIxbxpfaDblft3eTJjJ-Jb-qQgs9uEQ&1DekH_O^utFN7bjqMW$K{ z(o@*@Ps^Y2ij$rJxZ58_EkrEIFSz>38f&)?jj90R8(mqzbbRaBod$^k>82K@XUWDj z&(OT1^6$C&N8G5>No#pGsk|wh;&co=Nug+7FJPRY(J-6=)FePs2a*9OURV1JfG45Q z6KE=X26L)X(-{m{L}E_>%w1gZ(+|wO>?l=CP}eY3tiaff zRrnoeoX{P`4tV3j?-JXDB-Duz0OzV#C!E%NLGD!tNl*knk%&}!lF!K{Ko0sG^i`lA zLNRuz#W64-d8Y_hS{Dc^!D|w12_P3S73WSI7wx$dr)mqf3N{052_Nw*mPi+{MSF7D zP1d-=*eDfkl;DJO^+6e{8QS?E!0w9*$R*NqF~HXr zu)AA)3vxv}2DO-;pH^p$N6tuLVw|7`0TZ=KdO_eNL*nN@tr&hv!-+;k_>sv~6%{K_ K`6}>fgZLk0HlZH? literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/object.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/object.mv new file mode 100644 index 0000000000000000000000000000000000000000..7cdfa671c6117a0f7750db2fb786d4b27b13821e GIT binary patch literal 3885 zcmai1OLG*-5w3T4SM@x4G}&ae}Y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PMf$$DNQUqg1pD`2zCAV`xaqT`rzIQUi*#y-e6qlQI@#5>TZKB6myB88!m_ zLpEPMW3#7vE?~T4Q)f34c!}eYk33F09&wG47svFujT2Ds$iium8o2nx`F#no8w*Y` zq^wfROop*LxL%_As-w&5Sle@~6^9Gj`k>7ofRqm$`5pE46u=0)AOToT0mPMv7ig5E Fe*x9y^9KL` literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/primary_fungible_store.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/primary_fungible_store.mv new file mode 100644 index 0000000000000000000000000000000000000000..245fb86e04b6878680032bc1b4e85f0d05a84db8 GIT binary patch literal 2153 zcmaJ@yOP{Q6zzx9YDqnsku)>=e%kx6ch@#=rGSgfWeSt4v^$zb)UL)QX)z||3y26v z_yQ8D_y7|Ag^Y-h(=Cm>>jEZdb>G)H=U$b1e%}1k7laUx62(-)pMKA*KiCudZ}uB= zezAWS@-Kha`#}lyqx#7j{5oO?ri2krEMgNO33D7uD0Ky)K28I;0$7MWbO;R*9K*9J z2)l>peMI0)Br+uN7$-y#3)_*6Z6vUa9V`=LoDvDwiVMSLXR90P(LOs0e$t|EXPts{>e`(vyRHZ}=+xV25#$qpyNB5q9rHZ^LioKO_Jc*_&>ycR5iT7d_?Z@}x`|)AyN7ML0ETWV6 zG(L+T#mx56WkNX@lA&7^N68%_E#Ib=6jCs=*wR6S#Dh{Ml!=1DwK=togIdPw5}R8( z&_+ca<`OV$bGZhRTti?3JOhUI`5L^9wWTE$(1rADDvXWUI6yWs&`*VjVw#_+q9}Yq zI&C`G0bBDiUYI)$FuR&=3&Ox|8AElZ8^TkX&H-XN1 zc9oSEx%0_QRl;MP<2m@OgLt74#urtdHF>(kZ(%=Ol&E@hfe56D=Plj~19b9l8EIZ- zU_E=o-w^JxKGyV|S^jcS7mfdAm6i28*R@BTEqzrqU!_$(-^k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ecode_modules/dependencies/AptosFramework/resource_account.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/resource_account.mv new file mode 100644 index 0000000000000000000000000000000000000000..3490724400242a97784e50fa45a6b352bc7286e7 GIT binary patch literal 1311 zcmaJ>OONA35U%RCyE}>P%wr$3Y-SHE%R}M<$`#F-)BXU<>-1!-P3*|-jCTGE5;so3 zm0tq?fCE2(Bb1$tK)Wz~sOqlzx?bw9zrXmyDFAQ?Im=J@$M3{2h_i@zqt8T zE!3ZCX@Anz|Du0nliw3YcmxI<1V~Vz!9ZdFC$!D<;02Z&081!vjD+VTra}VD6areK zLCh^8s1xfzoO;^wvk8JcpUpr&%5o-zd_3%*%ui^qpPtSJb#aEI@R>o-AK}?xdj4oI znZ=WwB44_vpc0d~bdpZfS(>GJI)BWSx6CpS2hES#TE>)@XpjuvARS4P$ucw?l}AZ8 zB|luZOloRU8p0!Iq?vMzC6J&>0Fmi`PNNm?-FS4!p$Lj0CBMfGw~?W;6v48z3w^uq zs!)_w)$W_9kJ^^I*!D%$){UszRUlC}GIU+rslHw}p|gFx-EBg#EqCfRRI%-ntG0<{ zO}_K03uO$&`_UKwV=u~PRb20z)n^X@cKbJ*y1yxQW%agPhxGMW$5pv2-_)Br-aYF= z?CNm)Vcw!DcVBmH9BMi?Sd{yC6Pj38Wvtt#cpL77V%w^G;J)dY04{K9VXQeY16v7EjRV5 zD7*E3OC_l;Y}?zQHlbO^o5?Elv1{*&u-(PG7x!I!Sbg14Els&mhZ%CJ%GCYg+Sxk9 z|LAxi&I1cMz52uAW@H&1EW2DBY!66=DLp}Yv4Dbz<1EoVlU{i4z;P!W%LK#GmmhuP zor)zzoE(vCM9%(=bj`D|E!56qaK6pvHCSxtETMFCBgkb683Tlr43ViQ!8+ z|747>t$qay;T@=wy}- GBmNs#bLkHN literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/stake.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/stake.mv new file mode 100644 index 0000000000000000000000000000000000000000..54e477d69f336a0ee89e09ca054b1f5aa65cbbc6 GIT binary patch literal 10443 zcma)CS)3cmS+ATXqatGlI^#xvuwXFOwje6GD-dzE#v@p!!6^{&14c(2@AdDLUe z)<_dcW3QJRLb#6v!c8DRfIxsiLV$1t2oSC(9(m-)3qPLVi61ZU|EeX8*5mL)c30Q= z)pvhiRnKSk{=0D*V*zIe#DPz6=ZpO7QvSDkQ~k61Y0vww@JqA)=a0<0|9Ir%LjTjT zuZiGOCqH{2{K}0NqmQlmOftn><}sfYm}Z6rEM!F%v6v;S#L6sX6+o~0j7{O$gZea{ z89cLi_Trff7~6;UemwJd7VsRv+(o>X@EnX7JB0ROkFjOEkKj4#GI?Bb#>EMsa8{wF z&wCtHWQMul&Lwww@h7+x4n~|m;2v}S5QYDjDA+NEi6;e$Cos%TNsjU~V6Z2tIOAf@ zQ$A|vc!9B}HEK13;#~m-o(T;-CGq2k35KwnBxT&3DIDqfyKaeWVp8`NA=(~RAu;*}XRU!~$TDqbg? z-ylNXH;dx^dr^E~4#fv)^h5hle3)t2CcX?k7AuBHy2QB96)iKn0JRp zTeFMI{2~t(lXuub&g5tKVGPP&;s>#({$;*Ajn=R5BWMMm<@_iMew809G4*TQ^O*bV z`~>H2@pJr%Y2mQqZ}3y6>HVAhNsf2?dHxiZtKXuz;cs)$D1V37u#Nr#Kl3iUewTB+ zqTl0?RPaT9%wy_HG+F*W2Lg%x)o=lC0d9sCJD zHqF$Z(jxU|RO+wt51!#H{&W5zyu82Qe3}Jc---2yuYQ%#lPdH+Q2^ed%{Ql1Mh2c#kH5#uC85Md->VdUUgnm&tG4C@%`QhlGT@;=K!h*4cf@n z3NsW9QWyGzd}9YKK|5#%)iSo3;T8vAMU?_8&?r6Jp8+18A9{YuT|0)?G^PkbyTI}; z03aYf_0H0ICP3ES5g%Ms(V4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6ePSF52vDwpX-G<^(Y^3Ac{q#0S*s@4}yX%b%#Dcw>BEV#Q+tY;Y2nPl@p*88JHeNAuzFML7*c2@I^teNg zOz+?TVitmJJ-usD3@R;_BdZr}1NF}G^qM$E5c&3m1H^0I8{ig%4q2MsgUj*q0E~YI mmnF^z^r{fIwuGlV?#YnhrHX|rFp$=u}haNuU3--SQX=!`_ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/staking_proxy.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/staking_proxy.mv new file mode 100644 index 0000000000000000000000000000000000000000..4b023ea6d7d247c7c7afba1fe096a446c3ff8c90 GIT binary patch literal 1043 zcmaJ=&2AGh5cbd5-i)0zZqi0VPyso>fh!LHFA}X16IQg@XuXv3INUh$IJ^TdfH*O; z$)-_Su(Y#de>30b8I8X^{pGC?!b*V}E0f>4@A8K(e!}zc8~!MQq)~#t&#NchW%k~%TLv2z1TMO-B+8d^(Hlj57W4Zmi4A>%4O?r zQ*J3X6>;sT;_2mb(f9AFcc`q#X!kUI6wTHD7L5@I8Bm}^6%7i{f9-`= zQ7XxxM-huSfPxNXM1wSeN&;MayTIrS7abzaU0?abx*e;Hk z8INZsFlq?JH=X)8=#dVNA5gb~LH7;<4J6t*yfR~SXx_s#6j;QF@&&vk=bUaJe1XbC zoOnY|Z?`UKyuEjlMJ$Pg*GD4uUIfsRh@mRX9Ofiq5m>~b+lgEey`z3jJsgn(k=u^k RaeaMr?Y_D68mUI5#9s=S!-fC= literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/state_storage.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/state_storage.mv new file mode 100644 index 0000000000000000000000000000000000000000..1fd5adab20e5821d2b747c993a7d065100da67dc GIT binary patch literal 718 zcmaJz`-YI9U)zD2v4~Is?z#s;s81%%Tb>w_f8^3ew zJDLg)N$IQPquTVfU;A)zthd4F^21(p)36s44ex6BDSAc|(i;8yR*8UEr zY>H2j)_}C~(?7HxV~r)0IOgqx>|RAt!)Ft$uz{JlUm>!rmu0_b7nGu2X!mHrs45OW E0CqKl2LJ#7 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/storage_gas.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/storage_gas.mv new file mode 100644 index 0000000000000000000000000000000000000000..24961764f3c4c6fe3c8fe8b46511b057d0208773 GIT binary patch literal 2905 zcmb7GJ98vO60UbuSJm`%w`SC{+6A=iY9;o;%i6Qp)fz;cb3_2aI?&N*dc_3NjOZTi zgO`D|1`*)lzy;@=MPQtD_8DjM2k_3gi2DZ@7ja~EmwHA9L{O5dGr#^SGb^hy)qlD4 zAEyW*juOMnh+it?C*M;24f{%(zv^xEPyMO=hq>+lYrYr^{x^Pp_~%VUI1xk=MYJZw zz+Yqtu?~!Y>SENPo_cIFhCiRh>$U^+VlfLas_WEF-#YR;NS+3 z=}pcFy@k_@FtL~5CF7hL!juu5au~`GsyvY>vB0;%w4lw)a7AS09jUby{HGxvRqb0z?0@lv#gGbayqT6rl}h9dfD7N ztshqMjm2!fv~PCn0Zmroz1Btib_14?->MhiFPo~k{mLI+Evm;Si+MF)&dQ_W0F8|f z%AY^4EXiiC|7^r)V7i|lMZL%Xw&D+lpa^~nOw4(8P(T++FV zP&>i+H&I&4LD6Mrgzzbb-z{o4;1=`ZEPb}AmVrBb2;Qa`b8E5D$Fn)E(#Pdve5wwn zkLi=aNmUmR=rPzSr^8<9dGfA{1TQcW6$tsIb-TMzRfT5=lK?Ak_Z0}0Ieh$t6yR;Lqe@!|8uph1k>~CQ~YVJfK zW|C@#o|UmAAtOf}NodL#dQN_%mRfREXiGeok)xhF?i0%r=5w3hjr^udG?_TEk? zJB-WXrpsxs_CiK|6i41_q6x^x+1PmPmHe98)aE^JKT7!Mig>LDdI46s*tvD8mtM#( zsm&pPvul*M7HqmB?z`Nb!~Gz5_ihk-KlHJDx(XF+oE>)VH+;5dGrMs`d@iSU1Ael+ zf4!CaF$QhNA=;1k+;|m$-;kdH;4}FiaI*af;>h~foBI)ZhOG=Sd?%d5JUHdFpZJj- z!T#+8CO1mN$W3rcQ{^x8iO>X2L5>_t)W}^(75@7>cZeDe5i4l@U=3gra+H2#NgC_u z1->n`^o~$1)8TG^;XPM(_PaafMZaUqCss_<&5&eJ&&ktp_>+{J!`J!0lamS0`kaC9 zb@%G!)6OBdJL@PI(z?9vZXI8j*Erw~uDfH7X8ab1^ssGlU%rd!5s)5teqU!s+^^*1 zTqHf2Pcn83IuV{sY?%|5R*Pq6gztxcvOzv==O-Zdem(KJnVE!FT5w6!CKGHZdD zr336yj%9>l_sqr?ifTthKqWh#Nf&wMn22SnIaok)Mp=Z$MXPXTQJGly$_nFZ>rkUZ zvgS~Q^^h5!3780Dd}AN)j}TJB-AQ*bTX2hG$W*$UW*!=bj&5+zbab6TT3HfVo^nfv zb{rIFE<@KUj;8_?C@7W;;A$c*K2wl39K%J24X47%-fk#H~ zSOQJS?DaeHde3TWcEno}+D;E&7OM`@gV0-OOd)m8SOQ!~PCKBNU?#mnLzl(%&^~y~ zq3^tiR3JbJ`^YLR+pc%rbqb3%f@#M~`MQg!Q#A6@N%2SdC%jV()4KAr>9tgVL)8jK bpea*~fC~5`goFbCNvDi6!SFJ{|2Ogr;CNxo literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/system_addresses.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/system_addresses.mv new file mode 100644 index 0000000000000000000000000000000000000000..cb6f65540340a24871251a600e036334c681018d GIT binary patch literal 1275 zcmai!&u-K(5XSAX$9Ce`Zda|)f)=ShAS4c4IB?;>1tcWI0l_(}x-MFw-Biv}#GMyG z;z2m{33v@&f^mpj@uwRfzIeX*jWe;6d|mwXMhIc0Fv>i~m&f+qCAe?u#9XTHioVz% zz-cK!C|04fAh4J$His@t1xkoIi_bz?CR`&9cm`9hmxr3G4GD=-N>#D^9*5oMZWlMr zatcs7r8b#v{eBzMttDG&*DTL>ZP%Qo^T3n-a2GklEF}3y{A@={T@jqqQ;v zs(7yVAba|{NC6h0?g5nnGXPcx;QvB@2a5sni-T`!!5tV!66;!66G(cgr;Y%RIJSYn zgPuE5xZv0YQeNrcNaH<@t3cXo{lF38Lyqe}=utm%WbiS^K9KQ7KXGL7DaRDZdaIu~ va`=MdNg(H)e&wjb*Iw9zK$Wkc;?|VEZY}SW&z(U%JOFQ;2Vb6M8bJI40h*a$ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/timestamp.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/timestamp.mv new file mode 100644 index 0000000000000000000000000000000000000000..8f1d50a3cb28e67b5ae310b4659c177ef9d37e7f GIT binary patch literal 577 zcmah`OHSl45G_~PNjeVdG-`$s0*Q|V5{M&=gka5%y=91}iRdIP+YMp~Vguq5aF;pF zTw*FsFWA7mMXCI%>e+tvw)s~l0H6gVm`KX^)Nz^q`XjPO+)m!{GJhgfJkx_%d677L zl?Vb52xJDJIESPUDY8aJ0GM-znu90=7X*ocmMe204B_iyow=lv{)&P(~d|5N)!{@(sew0{fz&dbna7PFbdT;{PB^I5>8$59QuzWGp-Y+}wI`>&X{pWFN^q{4eO=ZVC8X(AZ;o-KaD2&ndxZc*(aGFGS`Oroa41|pl zWnFHcPK)HRJ5jl+vZ_<6q{zqFWKqU-R^)@ajPoi^v>rW)r&(&uomKN#DLx3JH=dQ+f^MuR^95Xs?{ut)3j7orK*hwI`a{79>w$cG@E91rmD?X z)~~a?e&spacvMWMDydcal~UEWs(h%yODw*tW7NfVmaf%$mESvEl(_*GjmxGF&zOKZ zNSbO9^q!h!wN@hFY%1N%a)3e4&y{hUM{6eHJdM(|$jp_|)Y39ag)j3+88)p(Jo zJ6WZZH8%#i&Q^JRI#p?BhTcr6CUh__iv*-BLse=rk4iPcR;rBPpBELBae*(OUesKB zh&C^H+SVXcba5(CLqj}Yd!5j?0}ZGoo^LMZlQK?KlQ~yq0&>w;!yW>>Wuz0&ibY;` zA512I8rQlxeF)wXuk($WfR4d%QE5;Ybv%udAL0^pP2wtAfbeQvJyVHc^};5z;$jgl z8P*gONgY>PtCoh$#vzME9TnpULp)J7=69i7^$f$C)RsomGLXh)G22_t0?wp};+0m+ z@K}001~DeK#F3d{$2iT@)1rL57EenRr)QCRhI6V`XW{%8(;Qc|yD}wj?~oU{x|J03 zv(;l;a%_%#*=5tArG0ITLZYHnVKB0K8^iWi;pn+43m2ZMn5oUQj5EydoBhdDVVa9G z6TFUJXY|G|Tvkuxd88Z3rc+$@|MelE?{)JLo;cU+;koi}5BlE-#yB0AtClz&Ha8*{ zSIpgc71x}7jSFsH7dOOBaZ9|bcP8dv_32J})v|3rzTy$#A9Gync!@gUwj{kl z7#OG|bUp3@0c}e_rLNA<`+E{w2V&IXI0L-4cJGJI(6YFODaofUjeKhpPcaIten1^D zk^~e)+@}tW+LE0+M_9wD>2bw@b%KyKyOW0aFJZLC+d$K``dFd!@Bo{ydRv+sYK4yF z8GbY!9qa&Z$klx4W_s+H@!)k69TQ+`;8!+Kx8Km@+P*o$&_hLV3C69a-wlrOz}ax( J(6qt?`v;WM-5me` literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/transaction_validation.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/transaction_validation.mv new file mode 100644 index 0000000000000000000000000000000000000000..bbc1913292b37f4406847d1a84cdcdf8c440db20 GIT binary patch literal 1954 zcmaJ?OOG2x5bo~jp6;n`KgR2|y^kcjarP0C1px|*gh1LLp&&&<0>pJRYxg>%*fYyK z2n!cD@-uRQ1Al>kg7^U;yuyhaRF5AUtq5(YTwPUN-&a-b_LJ>r+9!l)N_woPysO_* z{ypX52l|!#j{PLmH)_X!qJE_CbI>)7J=(+N?_>34HR?_ z(6NsWae#sJ5JIAEB5(Q%v`BD^Hi&ndt`T|!nC4YzQDT~#O<_D-#5clyYvTa}0l)+> z+%w@DG}IsIe9krx2v(uarttjStCnHFsGz>_(T$6GR8dNq@Ms+;D3cSL+9D}>Wge$R zJSvkcjXsa3$vAeZj7OuaN=t~(%B+Y+S(2*J!#GK!WX#=8*gVg2b!y|X%5C8n$t1OT zyErdOJB#A+7>$K3f-;%eqKs!}trvk#tzG}*0{GJvuCiyzG@Demvs9u%vNYFyi*l6k5&zECRlVd%1+x!TF)tp^GP+s zvP@Q$XpgX;6B``6fxU+lk|*&rPDl3ID4S00sEp!t9F3Er%#)L@3k<@{K>z{!4zBg!w(u2Q~n<0c;c47BH6ubd!XE5t?YBsb<>KJf!ZG zBjy2c5c^yRB}oVenrqQF0eE*HxHFJ+kFSdXdh`Jv3I;|4y^Hzw`E{`;Ihw-;KLV-z{4KDB6cLh z&?XM&Uf9L%BC(s|c1=t(_uo;ko?)WNTtcYpH34!7YA&uGtZ-Q!lNi+bIP7bGSPw^I z`f#A-E^mmo^cR?mF1#ABvCaJ;Q&?Wk(fO;bvQ3tVKuB F`!5JgZ!-V@ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/util.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/util.mv new file mode 100644 index 0000000000000000000000000000000000000000..a39b8d91b27bd0eb762105cd4e64d9e97d6db567 GIT binary patch literal 162 zcmZ1|^O~EDfq{X8k%5VsiJOI&iIty|UBZ;ZSAi#&pTCBMfr){cfsug$$Y5k(WMt%G zVq|6H1oD&fQ&M@-6N}@ElQU9NN^??KN=q_xgc4Iyic*V<FvF0e8 zWHeVm6hos~K}jw@J^Pibp1)q+xC#Iqf)%!wtBroynAbnC{vocaTk*nvlXmf4()nj4 zmS2eWv&IBjRNS!lM4>-xCP=JlrfGsDnLe^Fb30N)A)QB3T+0jHf zWOGd^hd60UDW+wjZJdU%JEpEMTjj8uC^h+%3yr?(`$RcYUcaI8_K)yYcj(@QeJCe0 zGd4`2gl-=`(ZxOVLrlIf%d%~yZ13Y>bQO?zB`nd{gAqmKF0K6 zJ=5Em$a4?zn6_l+etaC-1En$K-;?;Bra*lYrfcq@_g&f@N1BSepN-h~{{_mLO}z_Q ziy7&w8T@NwlhGjxWTzznIt#6|{KG5Upo6m&Z1@JN(eR1-%Lr76^3p-8pMui5HrQ5A fjChU>tSvrPjlM9@8m6A%LO66{2@l))t`z(NH7;?4 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/vesting.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosFramework/vesting.mv new file mode 100644 index 0000000000000000000000000000000000000000..3aef6bfdaceb17d211ec11234420cee09d5e9da7 GIT binary patch literal 7538 zcmbtZ$$uO-b_P&DEdZ*jtJ&Noikl^iS}e-4+>%AxltkI`CRvgfd6`a&U6MK`yP58$ zWKNdJHkmDZCi^;>Y?oZ}N92@q{(}6H!(4JqZuuUnx=GV^F4I323U~#)^?MIh;E#^{ z#Q2Oc%h_>pyybnL|5(a@R-dTv`Tr$@|JMIL7XItpy#Jqb-xm5O^Z(23e=PoRGX9@S zm(zc_EEs2kc}z0Jd={{fMNBipEQ?vfQdVIZtFkdx3mF@SkO^FqxTbJT9-&EkFp z*HK(^xQ^kP$NU9civhFG1_IhKby9N1y_Jyh(>@E&1}uF(V8Q#6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001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/aptos_hash.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/aptos_hash.mv new file mode 100644 index 0000000000000000000000000000000000000000..2947f36cf4c12163bb76cacbb35673f83d954f03 GIT binary patch literal 562 zcmaKpOHRWu5QfKg9(K|PX;~uF9a|by#3fiFmX_1FYSc8TY!|6(R;)Pz$3t9#abF6m z#4LV&(&w>9p0AsqGy(ulfHVFaywLD<7%$!_|E81ZgC)IBwnI;V0)qevLLa^dVjtXx z@R9gPee`_vu?Ys05MVQUW$lDDB?@ODMumj Ny2Q&Mg(t`agLmv{*KsMd9s_3E%%OOLslGv7Qp!6^B zE4uHlmAdPqV%7eNuK5RD^*eW*u>q+g>)tcxp7;IE8UMWT)<%r6jI%@}nQZ;d)j#~Y zel30x@$c$4k-UvAN3Y{+=GVAp|BQuu6aVY|A8S$eW-Y4ywIf=Q;BR-7@>Q9^R? zBF4F5F}<)vX{>1!V>Joqf?2GLxio={j|}L{(rL}6SXZ3KTF=NrLlNC{B)?iC`Lz|I zTY=xUbRge6(zwAY98BbYQ zn25qIc|^g@=@@j$2N#hCHkX1!tfWgxSefg9K%8=JKypKGQVIzIrZ`ShNW%+3M%L>%AzR%tjM)G&q@)x|mExllrWGbXN3U4rb4KXT|Vj_ADwT z(+7i-$3Z9RkH^LEI64|Z;iW0J-ud%c@?G=8dS)igxaXxxc#FOGhF_{+WbTB+QD`umin!fCh zEiJuLB%O`sX~aj*pPUx6Y3(~oFOOko?D{I`yc+Q+M zD!S0B0( z(dMyAZP{zW0-|}s1dul^FFO14l$1{H4J8h-aZ6~c-N?hsK zirfeqa@=R+53E=qo#24uEW&+oZ!i|;&z{mci6vz6Fn|Nwvb$&ym}y+6Lgdb=O2G+( zNOsk(wxLKO*M{fbNwtOK5{uMOs&y+{!iuHnghoxmps7p=!U@+F#jkiff+jClup(9k zP2|m6RO|Ti#r5!dH(U>*5{9AX3oq?Fa@_ETh{o`nd8YQ^l4O=5Y3J!9f04cZI0(R1 z6=~bD+hWa1Vc|QyG0z{KAcV|AayzP9dcId#%4?;c99bTCedPnMfgh|?u3EvBaBy__ zJOIk!8)TzhmFjE(t8fAF1sWIH=n+bP0Rc)Mw}asq(3-Efl3{sZ$iJ@D^g?$)&+7FTgm6xwJi|B2POag=}gbh-Se)QFHt1btnv zoZhQn+>Dcp+M+6R6dFaQt2p=67dq4(Jm`l9_v_*;Mw6fvOOl`JEgu6JiH~e@;IrsH z+5kx1QJ;8eql5agzh%5Qp*uESV8$-_a#|a*wB+YuX-yy6Xrbd}Uaw>T(U4BX*iql= z$EZZb*vDm~#h&UPLT$O159@i&@+!%e<3Yp9M^(i{hTcvR%$0@{9&L!RCqxZ(*&A2$ z$`gcXa$!u?QVbBO8XAzFPrVX3UErofde@l?GyxGMuj8yqjM-72hpSD1_|)1%%qN0N zg7TNRG@!IsCe52J^4eJJu~#-e@Lr?fK2s=Mb#2aN`ki+V+0?p2lD5_#;<|vO#41#R zC}VYA6Du(A(U(($LA#K<{97l@-lL?5b-_CB0qO6t{o^}Sn6C@e`|I{F9exfe82{sUY8 B=6wJF literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/bls12381.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/bls12381.mv new file mode 100644 index 0000000000000000000000000000000000000000..82cfe5766884a99b00a4b9dfedc8833d831eb782 GIT binary patch literal 2089 zcmaJ?TWB0r7(SP|?ab_DHnW>#vzMfaZM}d=tgugNeegkB6AYp+GTDu@$&$^^c4oIF zP!+^fsEAKuK@eN|pi+DiD(yp|LcwA|`k*gWA6kugc~lX7@H>;8NvgXJdw%}^|Gxin z{+T`JZ1HD9A%qx|C`>8ynR8USMosx9Jx|r&+2^WuMW0l@)2~zgLvzNwVV>d1@6#qC zC}D)Fgh*I2mV%{XX)0l9m4cA~hvGkrAge=#eGqj8H~759^8Im?CsYP15SEU~c}Q z>YVKQzUM1mr`z<}_Tkl4f5AW6YjvAT&DD0T+w(&8?q={@v%9wFEn17d z=QS1@i(U}8L4e>y%*n)BpPY!3?W-Y~jwLWQG#B5)%SWG zXJyS@S)Uw6>v}tR#s$G$t#w_e)2pw$n@)sS|3-qse>_gJ-F5wTt)(pNjAoY+HyxA) zIpfH3M~uk9uM-bx&pwNT;HbqMTE@T~(f00W$^*U53A_^2=#1=vqeR6$zK9nOqBI0- zd;UhPWyc%c)56%U^X~UCH4KR7k=An2=`KK>$T{(FE>r>CV&9~lJdg9pQ^*`^N^d3pR@OFM#XSL<`3+~p! znU@Y7vfq70`$L_*ZOn|n_T#bpuU`0I>#O;X{{HpIqm69h+so_4Q*^#D{YC!zgRS>& zEnWQdjqbyLt;^s1a%b%3XGgDHIQQGx!sZVry3apgYfsW!7hg>s`Q*}@kAmrA^!j)U-L5n literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/bls12381_algebra.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/bls12381_algebra.mv new file mode 100644 index 0000000000000000000000000000000000000000..bb7d580bbb6e2ce2448a737cda89500843331563 GIT binary patch literal 397 zcmaKo!Ab)$5QdZKZg;!swtMmB!BmesuD_Xl63$6U+1+J3m! zQ+?{HUtQI9<950UXbU!!o>&N<-sz0eH*Vb-lFK>&g k#Mk_H@Y{ICISEJ|Qa}nxT~b7fNj*|R5~MyUB@IaI014MhUH||9 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/capability.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/capability.mv new file mode 100644 index 0000000000000000000000000000000000000000..60e919e97a497712c21fc3b023a0b2a00c68134e GIT binary patch literal 1039 zcmaJ=&2G~`5T2d=vv)U+lcuyq6+}X!hyzEOQc98NksA+SxyiP&NbO>~QG10K;Dp4H z$KcA516LjbjywRfZW3|AQa;aqGxN=OGW%usmsJ4JV-R7q&Bv$WJxkfaj1JPaY`GF%BdKb z1s0GKqBb$r2i|eyR1P~wh?AX{thHC-Dvl`^M97JXBtkf2978bDJIHb_r8Lw0GCwWm zMSCNCU01bgiu2OfYT>7CRr6Q*WlFyjKlkT(>)*5l5fPmczb;Cj*L2kR^xaia`(*jf z=AFmpvsp%|7rt!OwDuu+wvHPN&x+q@_n6V!auWYt-c&#CI{CiB-t(>762&ipm;>b6#|C_B-t3Evf$)X7 z4xd<@u(5C!EIV;Bp}!VsPeG)HR_qYRLP<-chJo9&@KUeJAK)<}ts_IdWpH2}H~f%` z*ivDO3GBn@fFJYDc#cnL(AC=23ngyB97sES>7!5tSpYJ*P%ll{;KEqM5ffx$yQ z77`7<;LkW)OC~sx7>3kI!U$=HDPi>3QtOVwsh|4>kN7?xb?u?(%b~_Wf6wqE+-D@9 l#E#tUD9as_k0=Sn1Nl(1LAqyYmX_{acYUc2O%`dw@D~~9i+}(C literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/comparator.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/comparator.mv new file mode 100644 index 0000000000000000000000000000000000000000..151b4188e6c09c8f56226820fb1c2fff4db31194 GIT binary patch literal 513 zcmaJ;%}N6?5T2R*Zj!FH6i*&nT2KVNcqw>NLByjMkIS|!wyKd|*Ch^Yv~ zN&q5o4ucXBKu0hPm}rBb6zK$bqXlxjP+QJG4#c1%uzX@c5HBP*SyYSj%2e$~wb0$+O4{QeAuF nlcBtf)F9NAfvCL*(o3!#z-kY>&^6HK+5WoNC;7*ve*DcJ2mU(E literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/copyable_any.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/copyable_any.mv new file mode 100644 index 0000000000000000000000000000000000000000..433f1ae5e1b3698df8ce5e6e76bb9b2a3470419a GIT binary patch literal 377 zcmaKnO-{o=427RPznP>ZpzL4)D>y=t*uWK7qiEWuRYWtX(iABYJGNYc!*B@BzzNtf zDH39ZCCh&Po-O(9>@(E>QbNX=6~&dj(dzEhJUrVEI@e$1+zTh!D_>9ESw<&;At0fk z4Wu=I0g*w%0&o<$N~DT4(BAuA zi=C>vuI=oqYnw7kz3aO=tdoA&R%IPlt+)+?-1^0%zW+mlZz{bH<6JI%?`_|f^P#VH zc^#hore2o5Tko4H^zP^K$l_!F1qu6$nG;K?cnoG3F1h6F%HG6^a+Inql*)ISitY%l3aAUL%T?PGN)>8V-;)?eEvB?atQaxszQ%-G{QI9SVHP_q{qA0doLoR0!O)7iMl8(&Ydn=GH5 zr58mxOXm3`tE!}qyeiY_^}A(!lBcurT~;Moo?c9{5l=@WiJFY_Sytxh#QsKS^hQ~g zmE&|WexHR8#zx0S<2#9J0DDx-k`J2E14W)mR0CK=Im*hmZVlL2ETFUK4dLFK_U?yb8`q4}kfFtmYR6u;)|tMEtrluy~)9MN2gXvg?E2{Lfcu@e28QF-yib)B34o zBT*GMnaHtub*ubO!A+<>c~!WB%S0FM=u1eA8GXe`NCsq6Gj{Mo;LFovG{MV5s)F2r zc;pQUJ&GnK=LB~T?pjd&wxVJxnQ%RJPGTmhC1Wn})iD8)r9{1zcpcb2FPD+wzaH(=F{9c|@8=c%POSFD;$g1|ot{tFZlyU5uF z=Yy?-S8C!#3 zT?ssFY?TfWKLEX0CfcF*-F61Ic3K{pDR=?cnH}E02KAo F{sZlCPNe_< literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/debug.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/debug.mv new file mode 100644 index 0000000000000000000000000000000000000000..54fd205df22178c043be4c0695811d07a65c1b6a GIT binary patch literal 276 zcmaJ+IS#@=47B&k*#yx+kp@u{4)G5ju*$KCB2a{q4R4|47d(QW@ClrRf{K-FkH=$c z_OW~i3IIF=#gyRwLadlv2ToGDcZ}5&=iv)uQXnwo4uBv8l7beHibILHj99_ZC7tpB zJ&=XT`bu@St(z*GitcTF>C|cBn$*@eqpu{evv1ScG(T(Grn!;hAR4p&;luGTF~ebU m@$aF}9F=ByVafq*lI?DP02s_N`VN^D0URL$#)pPSNDw|)b}@_q literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ed25519.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ed25519.mv new file mode 100644 index 0000000000000000000000000000000000000000..3686c4550791fa20721b3a523e6be8243259befa GIT binary patch literal 1396 zcmah}+iuf95S^X%WqpYgJMN9PG^N}Gyiin>zJbIGLI@--ua=u^8jHrRY^NxXd<8EE zsgHaBNc;#t!8af=>okcG4XonHT+STNu6O2q>!)J?fXl!|cZ=ViXy;7mU)XE&7yGV@ zZ)V5%VcxYrh)w5{K=-rwh>fqdN@0M&K?5BO6Tn19K0%sgg4Qs}(znU72?q{xhTswy zJiB=Y|qjh!8eO;7+RrddKq_XuBAY zyylVQdlYBa+w{%=+eT=ta%LkFz${=6Q&J#vG$y$E8P$V~kp`R|L!gb^CP9Bwo2p>Q z2(GI$>J_@o^DNhfaWOQq(=y3YtDKz5C`kvI^(r||<8qwKhSFsJ zxh#tKScY%Xv-l+G$EEDQ93Pz|y=QU~y#33yp33)8G2@5^c{YlUCZ#NbSwQxq(UkLs za*Y?f(P>2-y_1t#qVb|CaZiEgC0q`@StF=k8kJcTkISJ<%cK{pohtIp8Z1c(QmbL3 z7W*^Ou0>{bY+d4`V=QH!#wWqz7>KE=XKmp+lX)_jL`9h=y|S~!Kj+$51}N{n5)$G;ZiLN&2kT;Nn8tuxmiU1+M;k!?|HA?iZEY5`Uzzi_Ia z_goJiH%-2)8M(saOIL0u8)9<(3~5RJ-mE-W>QJe@2S`WyvKElYVc@?eOz(ydB&7(pEL t9drmp6A`#ah2kN&d;#!ymlLE>W7W``F|rVwvj~K~hOJoyLgYkC>o@;DE~Wqg literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/fixed_point64.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/fixed_point64.mv new file mode 100644 index 0000000000000000000000000000000000000000..cdf185b8fa11eba1809c730910143e2209f7afb6 GIT binary patch literal 1347 zcmaJ>UvJYe5Vz0gIJJ|e?YebLL(p}9Kth5|4Dq-p9*`>W35dd)O+jfh(sm4hD5>a*b{qB6e``x)ew|^OrF{U{K02JOpzJIK~^WWUR77x82;;sH8 zWbg&Qdf_(>cJt*CPnk=-?{XxdOM zE7t6>wsl@76@2D1?lWOm+HsD6^dlrfWP(Q#j|3uyXW3Och%bt4G3AGku`r2YawUe@C>&1n zNp_Kcs_rO@>1ZIv(|6J(MEw8n2RHoyfDdGsc+kRfvM(Q5PQ-DGfqNpt z(9nZ@H@ab}ytwAp)h0r&+`4+!e&3OE=aL;%vZmmmI_-QY^H~oz<(A^M2cRf~?=MO3 z0*wegQHNL-YgR?40{siza^5A5ZzKBZi`fiTi4ZVy38BfwDqQZ@&n(uMdRBl%~q?rXqrIavZ}VO%U#Vr z^zKmj(APP3SF?rf^Sr0C+j&o~XMLLAn69`m{e+WE*%oz~ZPWa@$Y0W3yIyoV_$Np? z+1U_E{v;$)5f)$`A+Z`EvlgghF{oJ9FpZ|McE$&|jEK!>(`-j*I2fVj?x}uyz~KlT M%asQ;l*57W2mdQZlmGw# literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math128.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math128.mv new file mode 100644 index 0000000000000000000000000000000000000000..f4fa02c753d99f88bf367057cf8d244415a423ac GIT binary patch literal 1283 zcmbVL%~BIV5bo}o+1<=Pab@Otu0tEWs;3+_&M?dK7l8_ z`w%{lFJU*y#>i3}?8EHz*MHxBGxPn~Zx;YSgb+~_srr$5zY~7?fzelL2R~`U|Dtap zCm;|g3PVseb~XE8h?fABRBHf>2Ea+c%d#fRIwIhcC<3ZS8dRNANNdze^GX;2@?auD z#YT)$I8J9DRrdL^!US#HUl#ZwNe3a)!GRiOd z{+$$knAhlg2-gXc91hety;0-gL{0N+{pE8ps}Cnv>1cSCq{YSMIGfBiPm3&_WyyJw zkCP(3PB?s-u^5jTs)!bG#Xq+&-eA+RMtgeAfh9%8(?7sxdc`~ykc)TQdJSSMu%u@;7 zN}-q#F2Om%>k9GXzr-b63iBB8*YU|6aYu&J(aGKD>d^5ynwmovpD0*H_U=VO8FBCc zsg4dSN6Q^wR6)hnB~c+Qwy!&8o$*!m1%Fz}>}VF>!nRkgn%-i)$MV)r)b9PrfI|A&;mf-v2uC%3Az>;15m@V?Y1^ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math64.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math64.mv new file mode 100644 index 0000000000000000000000000000000000000000..08b84e3cc60b2678510bbcae65d8c366523507dc GIT binary patch literal 900 zcmb7CO>YxH47EL;-DGA`u@X%}Kw{H|^q6jF;ey1CGY9UgRl5n1l5D%AA1B0L;VbNt{Ik5Tk%Ct+mxTbsiBgh@+06WDFWLBy539Au9=Sv?@05U!2&ouB*B;TillC z`9-x@Z=O%%;<~Jhd1=p<#p=S%mQ_{f%W6IiZ?x_0uP)Y#SrxZtwOE^r>V`jD)|&^5 z^>wjaoaaS7zgm^+&HhYZ zWXw;!FgOn2$)Q~8F_R2!kb8_Y#;+YD6nHyWkB)gy&Ty9YwDF;bEOp$Q1oU_sY;%7w z8h%nP!i$>v0l&1Vv)=Zz^f*{&r`obxT;nlMy>ZkH##?1$J?V$+W6vj9I`O8Pw26fa zdev{tv6nk++oLQX@1Q{r|3dCoKXTZR8FJjnArqe6Cq}w-TeT4n?VjX2l8+i>$bF#- zeW7{}4@7S8QUsx7G*DKtvO4|k2MsxDcu+G@<<77x3yY#o2jM`o|48)F4CGnBPa>sD AegFUf literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math_fixed.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math_fixed.mv new file mode 100644 index 0000000000000000000000000000000000000000..2e5e816ee6f9600ae2b4571c8ba855a347f76e19 GIT binary patch literal 919 zcmaJ<-D*=o5T5c2=lf=7X7}pwCt3jT0=)EE#h0f4*sZ<_e znuJUeqgcdVI2$ZJl_#UiYG|sup4N@EUCySX$)cA#PIvR?@iikpY=Ww~oH;sWJ-BF$ zC*^FsoR__PJjvsDdYW&2ceWgt!_i93rWcM5!}a{UUNlat1v}+xFkV)7Ki1V?QI#k4 z^z0_u7)>ZU8kX|~B{kQjdH*Lu(SA3g_pcA?Z@XYx#jjUSGY%2RIE2&}sd$zql1Z)~ zz=>A0!RGgOd1OD-iHQ!<@Ca=$8YJMosPi{j@&_=ApaYeVsF466KPSMpAw~w7+Ngp; zm4A7E{dSk!MA_`V=wzG@q1kN*bI^${xV6)XK6vDCCnl)S9HYz7=lmUZrIlfl^FP~_ zRwj8u)7VUmG`165ibq$Rp^11GDEU+QCVNq#Agxi7wsfUN8(lO7nxcuWXffF^Ia!lY z6shGH-<~{qw{3tBw+bx@y6xi#LHzTo5A=~iivP_$yah>n3()7)QAN=e9eM=l<0e!@ TFcu|^T1a=(E8Uw$?iGFmAMs>p literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math_fixed64.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/math_fixed64.mv new file mode 100644 index 0000000000000000000000000000000000000000..84f99f9a86acdbaa39d52a74ed6be0d66b13c577 GIT binary patch literal 1179 zcmah|%W4!s6s@{d)m2@$+OZKQ;}CRE#EmeIJP=$MH!fN`h#z1(m`)t%%#5AMLvZ2V zjZ3$R%Pe%|PY5caKj8=H!iBebB0`u<4%Fp7&Z$S=+iw*w#e zIfPd539h@}@JA7WGhhOwX3R${;G8iENa;-oWUL^Ak_wI-h*-ej3~kP9#xQY~JmG?X zaYGqlNN5;P0cw(Q8Py2jjRzM>dVs9C?f&FRwmCS+H&&NbUY4UWs-kQ>8Vo0^%i0sV zy&LY1=iHwrMSd{Ww6e0l9~HxFT-OTA*)bH!+@H;uh^x5zdIdtyA=*R(uc?mR6g z(N;e3LAKW~cJuR(%e+6yv(0j}{XZKGhEyGFWIGco>T2KBWqSHNa6zAXidyUN+2^mn z7RnDN3W%ySve=|CUx`ETQe9Z4dD8_pNN$~|oEEOiP&v(Fdkupnr;vmfoJ?+R|G0bQ z!TO0}$E~z<1fWC`M9If*?_OVexK2|r8x~gLzzHi*ByS&mfBEWOH4HP!4TMJbMQ6d& zZPe(lS+&q{+UhFkIAhI`7uxX1vjk7=IJAgU&!IroMqNjf`0<;EW*x)C&-pwM$tI0? z45|?clY`SqF8OlGrJ8l{{Z!8PH%98Q=KhJk&%zg|U9nk-5&SO|Hhkm+aDXO%AI&FHf^5U?X8lzfn)1g*i!+$#5G<=2 r1<1R+LzBdCnqUeLK+`U^UcH4|9=mRJPt)6I5k literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/multi_ed25519.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/multi_ed25519.mv new file mode 100644 index 0000000000000000000000000000000000000000..a76e717a95066f4597390c2d29c72cc22075ff10 GIT binary patch literal 2078 zcma)7-EQkd5T5<>I$k@8UAOt^PtyOxp%T64qWgCJOD!Cid!ClTV~xj^$`hTQ%`4SzM1)Uyx#qB?=NKmfFe+()h0XpiSS>E zD}Ezd{zCtd_76_i`q}x|`P&KH@73?z`?F^71Sl}zAix4C0c?CK5-dj&0Q!=m1cfMY z5eOb)p^9**8Bs?k_yTQ#gvi5 zqGO@0Ys8`9b%eq?snrQsr#?z{76ic0Yc{YKsEKzFL*Mm7LdnH8@@sl6uO*t|!0&{_ zp+qtC*g$MzR2y|lto$K3EKGxsWh0b1)clt73J@w0!5C#=LeYSKEYFDXikqob0dKmP zWaCH=FR!m(eaQNQR4#R)=kwXzzR_{EnCp~};&f!q?z8bMsk|BACb>EMCV7Y_<6)fX z;n$1)WIXsnKL+3a%Vd3(2Q~&HJ-CbFWEkD*EXqchcr=>~n~DA|N{gh?&3rbE`j44T zPmN>oTqC;Ai$r(&v4lD{s1=X(n6v+Zi5@P`N(FKTQ8tU>MK;n&HXg)g^``i42{uj; zQsUSu`QG+yl{^LAy*0K7Q|fsVPj=QhA1*uV&8x8Bxs^yDUq<8E^q}YCo5v{4=Ho%u z-C$qkYHb2!N2N8Fd!8(&QM%|y_jhS`17!8$FE#VCNhfc8b=axZ?!_$_=_Kw?^w2A!(hNT@ zI~~PW(dG5~-W&W*^zciartz%~iZ4eGqv?~$F5WqwE&nwLv+;P#2ea|qTWaR0G=tfA zQs#r%-IexwsZoMQE;+^{Dwi~u=76n!R)tSImpj~?fB87%l^#%sOWty&`PX(u6%@CM zQjJf&(6t;10!2^G{%Pk51-Z|nGuP$Lk)Deb( zRA9Smcy~zab5DW4Pt9s;*sD5(Sl8S%HKCR>yO@#CXS9O%np3iHs?g#Z3&#i=QqSm> zTvwz{LPdSNVi8nBN9ZZq;Sq`B!kcwv{593kW#a=0R92HWwVk1 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/pool_u64.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/pool_u64.mv new file mode 100644 index 0000000000000000000000000000000000000000..8763de5c6a18e74e887f5d7d5415f820c5d164f3 GIT binary patch literal 2208 zcma)8&2HO95Z+%dwM$u~M9K1Rti*8+1q`G}10RzhD2f6F0`vh0MxtY(k|Ku0-g(smj zKGTv*0dP`Q6Oo#84r3DTRy@hEaI3jeB%r0hBC$$oq@b1u_YXc3!vkeA8VX#ULf@BnFhdwT}_UCy%NtQ2P=&UI6!Y;D;@{hGkx; zcer5F(I{D5rA4*~(`mk(l}VY`jKM=jax*Tka9*a9WSEa<3-dmmq_bh>yQx7J*L)n*mGDewd*|z$)Qrr64GRp&b?qsCZ zsbej+!!OX_7SDudjP-V{I8!}+;0!l9>OXUy6FqCX4i~ik%8E58cB|u7mcQ+ge#fo2;7$Zee~EJtl0-eu%V{yZ=P{xrE^mKF|L!XQ{ zW(KN(2Tr%ZRa@LZI;r}VsE+$keo`w^u@jLcBZ3|w?h`+11;Q~Lgo55E^JdGBf%1WC zV^1JLVih4CD1?O2R8i^cBXUq6DivFStZOyDhL{kPlM^mUVPD8Q@O>fEWQMd{qt zhjhZKlRD$tY6NQ6>aNpBz4bPx2I>`{b6`_};gm{eE;MpfNqTq}-$0x51bqhl&d!5u z8Ep+m4LH_ec!4nlz5c#M7TU-_yN}vy@4pcEcHwISXR%fzG9mzdgtEG;(NFX0t||vq z)ep0&&z+7!cu82P#_#fj5Ule9a6b9ftbv6*7CRgIbw{+Y;Sr%j^SC;J=nJ7++cr^Z zLWCr^Rosz?!0Dn&Kef1f_jD?KTopLV7=2I|cpGt}()mJk);MJ>;x(;eflnxVbbeP4 vT0IPC6`Pio_sc|XmBSMNL06!FB?Sm=gbae!BRiT}5Y=A&RsatDU}*L)x#bOY literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/pool_u64_unbound.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/pool_u64_unbound.mv new file mode 100644 index 0000000000000000000000000000000000000000..800876ae14a4057f223fb16ea6f1f089cd6f33b0 GIT binary patch literal 2351 zcma)8&2Aev5GIG@?uuM#wc3>}%RjLa!#NZ%+8{A>&bbA8DA1#@mNu~f{TR|JfnT66 z&{NSwWc1wsfXML_lQT?E!pTg7N_wdU893}Cu(Vw;YziEU6Qjkzu(2*u3vC{YxhA;$Ji%=UO zq5x7&heFt>h8PAz%y#t}Tr@1Cgg2T3#;L>5($Hlwq`Z!y-N3MCpxc*;5FIu-094U! z!oeYc&`I7VCFB!h1fA|hkg0YM@{~kfQkr`C5gR;ZgL>B+JbPl;;OyWOQzz?YhuKkf zoIS}-vtFjcNEj_O1(8t74=fs~{Em{yHWC^tt+m9&yP6HP@>->3qS=Yjgh^r6I@H8V zC#fcCvL<9$lj_5=CJ7ONHuzw%k+d-(0@b910u+Ibi_vJXye<~yvRO=FUJa`GM$vn$Sf8%u zRWTV1=i}KjyecNeY*+?YtJ}eN77gdKs(?NiF3O@RyX$FvY&k3@-l6< zE|$Op?7=3J^~9O1Q|LWb>}2vui)B?*%MjjHU%lx2`NgYCcdridT3$yO@Hq7H73~jJ)>0IxbLl?@>qzBJk;Aqc= zZ3hEmE-k&-M82EO^p|Ttmip3Btj$X&yx??f93CPh5QP?zoM_5CCE~Yf|J?Fwo3QBV zS`;gjKuh^fkY22u(p@Lh7M!R&ZFLanjGcN7<&M%;YGdvED~N}|?=@m_0$U03bJlrn z>0ZDHICmluDn#oF$rz7^N9n85F~>L%5~_kqG0c6d&-Jl@l#N{Nx`#;4w0FMxZ?c(5o+;P8&?* zzB%F@;dc^H53Y?hDAv9;ZD&Bb4R!+cG#K=qp{2Qm0~b&Y;EuD#Bg#T!Lz$jDcOnxq zmi#dG4e_r@WWh{^%4Z$)TGo9<{9_R*&enfvNHOG-*Y`W}^D^1(!5;Uryer+BLv!Iw znjk|4&7J*$6{Npq1rQ@nu+H!_v(gW!frU&N8Lo-jP=y;nCPAE?f}zQX5_WK}&70JO zruWo`zk~KUZN7Iu7qt1QzdPt}0HHj!FMXG%?ET~;-nFS)wS%$8hjjkHwc+-_wPe?d z{ql8ffu0Dh_KLEN^bO^l8y83B)ZWUJ(;nof7oI`ibVfgB(38-x>R~T_1fG5dXdn*v bL@^_{wZH_`KF2fsc;HeI{@3CEc$D}b+KC~A literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255.mv new file mode 100644 index 0000000000000000000000000000000000000000..eceefd3d71a29c7e1de9cefa239a0b2dd30064be GIT binary patch literal 4092 zcmai1OKcn06}|7xaAr6&{0v2Xtq*C-mK@u1OiK#w*s)~!7sp?zO`SF^L5X9V0Yxh0 z(1F`UfucY+@h0dpD4GH-;!RdX(M8ZrkyX)EfEMT{=nvhb-Lxo*?t1S0IFeO&U_Rb^ z?zx|L-yQ4mgUQb=jfgBkrZfx6K(JE8&ncpytz19VQn{ zEJIcbE;Ov$L?e2JXq4$=ERA#A30@8`HmPTcrt}=qG%quGEF}j^Ifdn50m~t#%<^)0 z2yRD;!$fl<@SPupdNc*;g;AtCHi~MFj{!TOj}t8nO%R>rl3wKcPZ4+(9oXpuz!oPF zWoZi7GDmr77;1GI>KV>)mUFz!InIqC==m9x@k*&obm1V>l^H}?MU&`a9?KfH?UIK2 zE;Dw8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R2LR$vLVT7B*T{Y>_gnsx2%bGcaaySz0YXwf+fjc@sWE>^~&%-haQTV`aA_y>*u ztQ8O)-59o{#GRS4!Cp(DIoRvfLQqSl8q~tS4MO6|F5-xtzw{XPBAg3BehJgF%=Hrv$eW2xTU4;|`)#2LT*nK*!98Vlb++01pev zH+^)~nTO+?FX|Rt=3zaG&kGD82gZ(yY3Ddt#{lW*yAOqh9p}Q1gMWhgXldFx3F-oC zx=9O$bCMY+!FZ9eaFZ2qPC?(b$qF+oV4h|s_Q0>iBFpJuu`LH9l5zwlsBN?4B}dF=l{K-{TERrPnZAz literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255_bulletproofs.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255_bulletproofs.mv new file mode 100644 index 0000000000000000000000000000000000000000..de94a752d58036db339fae25eef6b24908a2d3d0 GIT binary patch literal 872 zcmaJ<&5qMB5FY==vE9&gyDI@Jv^VZ6?H$AmtXAU0!AhyS8>vky+q+_4193uJcmqy6 z0FT0zmtdTxr4k4$v1h*dzR#0rzMlUw5&$#-P4$#LdoA9*ExwVDO#R>&@+ZI4pM;y?5>G-4rM#LjN=6TZxN<&jE2P&KSVfHBbG-nFQ#4%CvKEf zn&#;PT5uc{448o#P?|$-UN~{BDeaUd+)iAR^9$_{HJRYkt4`v`$S&;Ce&Y|Ykbc? z3+q?;yJ`RAOq^ewf%k{=gYy4wIxrT*BuO!mVG)@Yaf69{i$vcNL_7ovfj}uitqdYp zLG%crnwCw}YCsG`gDBK?ZEe?4;O;7DdoHje#C_{eDyjRTk*2O-f(&?Y`N zuv~Py#E(7fo){+arN*9W?3ou5zjx%2d_Is!`Te6di4WvRko@q`7{HZtOyZ*xQ;_)h zbb|Gh36%Vz35HK4md~7X;_J|%asNb|_Rreq?F(@ho`)9~Cl_qmgh$xKs0cd}Sb$1A zLa?oDC2YJUM2Ddi_(|a!aKX+jcN%A*EhT75SG)}E?6CfaUI}K)X%HS`>+Y~-k>#S1 z26BKFaT-)wNMV++u(mH4XybBGr3E5#cQen6O$)vVrZvSmEoXI&8=J+#=ytHX$& zRo3--^1GXQJrJvUIyFjo-rN^y-q{6?56a#w{SUNrn-=lAWO0|4$)eO%VSZ5_$#9i^ zTl0_0ib{I(t7)=GHsc2dt1R9mt68>O;h=h2xh{{T=Gm%{U819dyh|>fZL6=DmQ7NN z^i5%G=C^MPqXZh|st-EY@2Z}-TcA8TZ@b@~TIGZ8RX&G4HY=a%$SQG{sF|$S>1r40 z&`PyJ%T%$MFS}*I`tzyPYt8dG&z7l$Z+MeT3#A4BCdt!nwB_BR3N)Xg^Yh~Vv~22w z@218$eAuUWmm((R|NUXq@Tn~)m;vT5ZiitNO!QO8z7pV^R;w`hjfR6ap_QRQ06!CL{o&1JOo3Y zBafR5$#~h{bT+kl507!* K5{@5t3(-H5;)Oc^ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255_pedersen.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/ristretto255_pedersen.mv new file mode 100644 index 0000000000000000000000000000000000000000..6aa23a90e34096616863d48832c54c2e4a0dfb20 GIT binary patch literal 1549 zcmaJ>JC77c5U%Q(>3QyB_HpmW9vshrz~ZD0PXZxlwrq)Xw0qkJEA7rKGqXAn0U^l| zU|B-WxR8X%sUtEF2_l2YffMA&f525eb9-|auo_iYef53S)!o`U+4$y50Pqo{kW0qK zTQuLJV|~Iu(EcX=ww#YnPyXxddM{lWymJ2%wa>mF0fGQSfRHu_ht{?YxMU+`Ov-^J z3;^4-09=#mdnRE%*Z_e;Ud<&_N6I$P1!%G&WJSyL06NqRbOSQWUJYQSPTs2Ff>>{m z*=U9!Hl+n(OH#Pqpayylc{`lF#M#S^2V&Q!@QT+4yxQqfx7U_j!0Rj2BHrk(lD%n= z-E_Cz9`2x!4$y}V2wQuAIz(CovPC4v6Q*aZ3%C(G1Wulto(GZaU8LRONZ{!`@yrQzMmTDwfGCA1858O?r2d>2#b=Rh-uk z7H%{cjk@Q~=bcN69p%_t4N+BuiaTaCCRGHeu)E$kC z@BQdMx6?cRZU4{vZ~pnJ-W{EoFY@U3*T-L;-TmAnB&WGKW|;M& z9?vz#+aNr4&ze~wD$g~B%4Swk@Q|}KDeMGT$8b&5N|KMh@QrYtbUXlCfeqnCAZnry zf#GAFb_usA*`VZdNP$k?>Z4g>P7C@}-D>oW0DTlqt}1oSLKYIxrr}L8s6n5mIl%vh C5mdGS literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/secp256k1.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/secp256k1.mv new file mode 100644 index 0000000000000000000000000000000000000000..bf0d3b680273313238bf79069661b9fbe5b06a67 GIT binary patch literal 626 zcmaKqzfRmh5XNVAcGrJ)&vy=16d@u78cIZzAUc8|N|7Q_cmT^B8)R{3pVmImNhwn0 zIp7^ADR>{=fQqq?D-tDHS*xAz`^}6ro|}yaqXEDmXrU9zcI1&%pALdw_=w?8dZVu? zi*L!=d-^fBlag5k0Tckp07MWVD~dJF=T}HfM2btsz=#PM9~c8786=!HjQ9>PM2rQ7 zfI0+TLrrfXB<0G%$ip2!7i& q!+T-G2(y%|veGCyG%|&Ku%yy`v}8ySZ-e|-Q50%b6f@or4xRukGH$~F literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/simple_map.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/simple_map.mv new file mode 100644 index 0000000000000000000000000000000000000000..4f729b6e3711368a513e257ec9f7435496b2f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bh{iH>$H1tZ?*tp%jmru%PWb zHXmL{jTuuMnMu*`yiP(FO^qRhK{h@~Cnr)8c6j$&uL@v}qG*Y6ANgf#uFDZS=`GP@8@TllO?Rnkql#oz8x1I}+eT=FVH5uyBm2RW ZO8h@1(&mb{3JZBCLK!;v*U$^e{{TT~iy;62 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/smart_vector.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/smart_vector.mv new file mode 100644 index 0000000000000000000000000000000000000000..bc7a1f711df083e91ad00fc7ea865006388b6b5f GIT binary patch literal 3194 zcmaJ^TW=gm6|QSvs=B-Eu`@lk$M)FcyAvmy&80v>u)7J77KsIc_5qMa6T9P#)}FCu zCO7^7|9~f6ct+xdU%(Sj?C(Gz{s9ksr+Pe2!ittved^RX-?`T5@gLj&vJqn}=d2J# zLw5cy)W5~A^xx#~Wc+RPXPNvb?L>bt_szFv)&9eX?4RbZdH$zXQv9WrK#?=SBvVYY zh{cLCraCcJzC|=k80U(mf>tAmWp#u#i#Zo8Pg2l@A=+VOY=Ij{E?Qa}Ne0eRPBP1R zf%R56ZN?6Cxj>jLP4o)T6k7#^Vrz>;w*!AYZ*U#0ECX5W6a`bJ1sAwk!K&;U9O1T& zRqeK5MD48sj29)`QTrQEQU`nk>!HIMH9ByIH@2{|gUGk5k5L@!2sBIp?*4l!8M% zY(UJ_QYLF1DLJeti3NWIg_p!503*2-(1AWD)hO(wfJK zisV;Ksgwm_!UzP}4FsYkQ&1xx08z68%!evcQZVGKk~8mluy?J2lRB1}i!z;A{RoGI zAUk&x+klIAHo5GNr@hzJ>2x$U&j;r-Qdi^gXdGSkr!OBph(=e_!DyIH-(6L`!SKZ> zs^#r3Ncroa8~4x7di{%wsDE`;4bP(IBLKWH^{aRJYN}5!s{S}R9Sx`b!Eh3vRg>v> z^e&&hd)4LD^qmgtVpw}`2Gf^4$iEnzCxhWx^|m*9kqjoaWOPvt&!;ctuzHhRjjnpn z`={TeSFa{70~L*{%hBs99#^lc@uW&8gW>r_H60Drhzmx+M5i1TP+NRulpARWMO>%>arS6WB585 zT~=}Rb~^5#PP6M!hofPo!V-=lMw|Rve=_Y)EA?V|C%<%ULt9249K)o*wb4vhPf`);{ z<_RUyaKD^I%GF*bHp+CS^zkgL&G1Gt{VhuIXAb2kE)k-esV>Fx1L@xXanqBx+wQcDO;n(!8m3X(U%D6ruCQ664N0SMBQQ6+lLu+Ia+@QA7 zCNg?U{RCU#*8xKZ!fz~hRhv{Tf8qpK5-g9lYwanG7M&*89FPf*Tzh)t9rp^*d(x;Y&R$tQmIJpe^l>%{MM)Lng;huu^6#Odu^ zd6uKzIQfA_#E-BGC!bh(b6av1B)-&7F<&s=Jl8)&Ha-|-4a8w$-^zH7ZomZMVhOC< zzd@SB4sI=e0if;oQDzK{EHT0)UDeR#M`?{9AML55>vEW=gkn_s1O030pcD`4;#={| zffa(yB=JJWaDRvjU}QqkAEEPNtC27K%rMbBXXP_zq*WgMY)R1Ko|ZSK{y;3l_mi({ zUsJf0epd^ii&1af%3wSA{m{l}i+TNn4<^+AuGMw@?^_+}Z_qKnw2=k$PlJj=HCD2u zQ0SItB(2abUqV{>Ho{0yu%8hdu^>nq#JAw(T^gAT*Jf7##d=<&4wUa>e_Jn6tpt5s N>VFj+cfv`>{tK)2Fb@C# literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/string_utils.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/string_utils.mv new file mode 100644 index 0000000000000000000000000000000000000000..2302c28fb78435e72898969485a62080718bc660 GIT binary patch literal 1135 zcmZ`(U2fAr5T2b~?~iBWv}vKGgsMVZfS(8RjD&=Q`oaM$leoo@CMb46y#W_MJR@$y zDG*Nx?tqwGZ>my+rO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build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/table_with_length.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosStdlib/table_with_length.mv new file mode 100644 index 0000000000000000000000000000000000000000..868c75252f8463add3867345994edf3f46d9210b GIT binary patch literal 939 zcmaJ(;k( zySj3>D!g@nnrQ8f?(AxPZT0qQV>_o7ZEHIfPR#Ld8q z_+l5?v4*G|hBy8n_`3mEq;Lub4ONiB86Ik%4C~0iDb5I4qzs&SQH4YU{ojbA`wVq`!Jbhq5ZfkM>n}2s1Ffg;VzeR<2#6p~ zAetlqk{L)y0I2awSppqPCd~+^lrTIag&<~>0?j4A$l{29)F>5T3`nR6WeO-zAu@-U zLK^lvZ>y$k#U}4#-*s)LO7FtZ`Cj&+tC~l(X3s5KW-ia$p$XO%1n`& zlY;LWSDS5H47In7+j`SiFW$DLeP*5`hddm4`EZQ?X<;-b$7b4c>2{&*Z6Aud+StEr z-?&Zfi)qzxP*t$*f>)unn|<&-Pwl@#!Nd725;9IT8BOC@DKapJ1>uNQrdE+mAWJVZ iA{y6lvfzSvo)Ad`S1`ddyb%vIzxX2k&41@xzZb9&La>lR2`vm+OXMu+#FDyT8UBbo z3AklRluAX^lA3S?Ea$8fg4&5A%7rKDgp_DLw1|of?7|#gi`*tU6SbEZ#><=&on@$; z;||fvd_lAt&DIuh$oe8)=ffG&^Ghw_%~p%l{Bnzx;;l&gvjVgV=T_p9oikX>HlUNf zq!o$FRtr*B#CqKBET3mV@(tZ4c~u*d*PtS=>zw49x<&Ga?hxOMZdW!gMuYRqTTDXT z+PDmExj0v>6syJB+WEC^aiO?Uyir^&q;=%j31Z{OI2HyOz~UKMGzkeO*fRuDdB=M_yo9yG?+};&=p8gEipmCqjT@K#=i?+alh%O~lN`H#S(0ZPJ6$ z@Sqw^4tx9k1NrdLSXZObaO573hWkCRe!RDT@U)7%W;_|~4W1;E!-J}~H+Vb@Uo^I# z_YYb}^q2jo)5<)kRb_v7*E}4;;qx$CdeJy-=x0$ieKZ_Q`g?CIcEn^AAwwlktMqiTQntkN-(@%;2)_cg%C)51Sxbr7b0k0lh6 z2X#)7HC+o;bk*J)fY}4C(Ua+ZHJG%H1mg)#m}Py?->=kk^0;)9VejGLq#B!9ZanxV zARD(3PJ(q7Oq9e>OkCf(t>aQAgW;t2csL#G`sOaAtY#uVW8J1QIs_6{ z=1be2+EilTZm5nv6NNfIyB%l_6FhKnZ58p;I!)6NLgR3YJGS z7mRsGLN{uXF%xO^(^93@TbtzTUFBUW^c*-3E)_wj!lkU2Aqi2!fz_HzrQU!fjS?B8 zy5v%&uR+p^5*3uXO=|SVk+yUBdgOv((?ATOgBcVVSsKjX zc)@iTR9a4s8DbBndq1Ncm1?i8-Bb?FbxfYl#E$N&To;ySJnyKkI;&T$0H52`9Nj%W zTV8s-p+3=D8F_hE6{*V9>_Tqp+x2a<3=*$0fo)x6Tx)eii8&f!*S|$1q>DK4g{2Gc z)~J+Muc3m29e0chDDdHFekr~TUTvs%^eRwrL?Lk=-*rW5GC6~DP2ZTo(Ln~2tJ7x@OaPSLF^;Dqi)&Q8&d_j=OrCeNLs z8|&nx?iTQ!#2c&Zr0zE7r|8BSJ*j(%JJ4M!Vt=H3JusTY={fXK-6Z+trj<&^^HAKp z65F9nQjv+&et0xK2!&}=cYH@^jU5!VSFv8Ubm5&>chLzggQk#a5;!DC_&rqrD;J}1 zuoEba0!M9sh9W?-WxS(PpGnY(x50N+rsrdyGcE{%q^p+nY7__vjv=7ZJ%+-4eG%26 z?h*32ikvc?eQguBjME$;}V1mmR^hc2@KvK}JpwoICr*Qm(bt#z*n9`%8 d5zqq1e_U5yOO9>-ucUBsPoJI?ba$L(e*;8JH8cPK literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token.mv new file mode 100644 index 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0Bu3V_pCgV?>`22Je-3&Y|AG+pb${iY+g@4Hu+GmE?2el&6W2|1U>w#@Bw zNWJNTBnf#MY=X7f*n9$KxCENGeIIK?4XkZy_jiWHSz@j8G3>%xRDt^|$2X3j@&eyP z9beIy56 zE6WE5^X5D9q%V|(yE7Z}S&CeGHLbPc(hR;EyHc9KG04>OFBIhmg0#^I#+R@Ke#-NWUJ67xj5)fdVcE;2;2W zx9If%v*uK39{KShbU%!*oWny@9E=qX>NG=``-5L$H&ah{TjM=7Zo3`Oat zUx1IH)5KH@I!}b(&1k}zQ!U^|lXivl#HMjal+HphE1kKpmx&8R2U$@ViHjuN5oo1* z0Mpkg-7{Ev>cR$r{qItG>gru!(y0q+08U*O#S54+c$Xs&fC>%TyOEB_L$1WFsV5_( z5B4bKqZZQUI2iYA@^XyUaVdI7TqZ{F;U8>42~xBwUeu7`J&NzCP3skyt3>;w{Dr=N zL3gf>y-3=j^=v4yWYT?zt0BlqigGMDt`fhGP^>LPrNsg6buuN)gV<10?nx+c4}p|~ z&KAsblonBS#6@06d_%vUDK8>N(V{Nl(25&j<}riQ{+@@%0=k01-HpEd!7B-aA}R~; u0W+5ZZ!rXt#XK0IPh4@wBYe|`ulNYRG$q0g?!pX66XJ#}#EBv>*#82l;o5Zo literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token_coin_swap.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token_coin_swap.mv new file mode 100644 index 0000000000000000000000000000000000000000..0b1758f0f8ddff782dee3dbe6091bc39d577a2f6 GIT binary patch literal 1157 zcmaJ=&2H2%5FXpH<7~Fu-L}ww3KS?j0a8y$s8TC&K(zNLP2ARMHd)1Px8=f9@Bkcm z2p)tRZ@>d^W$d^?2vHxLnfd0M8P8*g5mJ#qkWNb_z)*l#h(Rnyz?Nd*k7J0QMwB5=pG5>& zBMbyErg%+Qg!eLch85xN2j~C~V<)ZxhFeP{kXM5NFfo*ZLF7I%W|T|xmtx2`mv|T> z4jBdoRdhlhM%bclE>)csjjl5@&u3hw#k%Fy;L^JWWhC4H^>pk{t>I{rnt!KbJacdtZ6&$ny$6gd8I$9 zzY}f$0~l9vNVM#71cHm@TDLLR_M&X_`JKIOronyp{}8s+sRa0E5GDBEbnNfw29YvR-V;WlW{NM&mU}VHQixu(fnbO_7d-aY;5ArF=_@ZT5(5vK^T)%ATYH zDn$w;f!#DEl0J7gk0^QJ5lOh`?D2K>(s6LDvCJ4I$(~!vAiCuZB5wAb=xPjBS6UDS OiSESskFR@oaDd-heE)6$ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token_event_store.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/AptosToken/token_event_store.mv new file mode 100644 index 0000000000000000000000000000000000000000..295a8262ec13ecb134c68c9ae370de369a939282 GIT binary patch literal 2365 zcmaJ?OOx9~5T1u-G@2Q&ZS8vBWS6jnBoH7x&3i*a6*;6xk&vrPWzPmxYSpLrIIZj`{t&!B6yx z_>KNZ!#~+yk^0ph>woPZ)c(Hq3vc|>j+;Nkj8MubrvVjI(vT<;0fz=bE(_8CSp#W; zv_RU5kXRDA9+F@yq=baqA>r=^u$_Gd{tW`Q4g(x|p`F5seIP=pE=ng)$XM5v-vF(wqJio-3SDuA1y zcu81=RE2PhC|uPZs@5pPjEE@5Ph8fnbk99?S=lSfaqhyT-ycu1k|)_zRCYN&Ez@x( zi}Z2ka#@slnmx9s`S{f3<+L|SP7iO7heOv#)E!s!^R(J}RN3W&s_d(7l$O2z|K;`ui+X#bs^GerM`wW}sCzUSErAZtf+l&o z1dxzEWYCzm;88N1xXab9LEW6*;yrlLYe@ZW>kN@*iTa>osUhd(w&nR@0D5Uw7v}HF z>rO85?s@ypmb0H`X_+R&^n2G^89dw1T>{F$Ws(hs?$86C_jZdT5AeJhE*k!e zFWM^+FI_l<#m;kyJM%{PKbfL)Zl;lYR=TW!`Q^8=smAGWMbR6d=xWj&o-ZwISGDSW zTh$+A~a<$wiQ=cp~V~< z2Ub={0m#6}E_4);@hVbyNC8N}BqBGgp|P~gt5h1+l`KSWXS0eJ>1ZC&z+Mv?6^B+= zkt2v48r=<y>8q_5T4n8?(Y5Y^k>PkeTkjOa$*GmQm_gF2m#_M0pgyZkCaSA#}i1}0^Fs} z1Gr9`CrFzzjo%_wULvzgN|uZG0PgL~H}lOm19E;p{MRV}a0qiYKjGiL5r5*Ye20Id ze#`$5<}dx7`qfzbn>qFG%v(PB#~A=bWXMsVLp2-wvK;!~M`dgwgkpdU@9pg)@-@Xu33rH{52 zpdRn+62^|FQ&3Ov4&ws9kOzc*d3X=h)B8xMI&lvI!B4qTv{mDd9RkmL;J^ax^B=427w#PN*7Dnpwa3rE2oNEt>AE zYCB!5R-0E%FRQlQw6c0#HNEQU^QLN5*SB?ZF8kueMI~e2dB-{U^w(SBCyXgn+ZDzfC8K%;(+g|}||@^01Em%UsCULViV zwX? zt4F7;)^v^hTOagYmw8)UnboH0i@NEOX4B_qRI21nbv37FNXlPE?bEBee_2w(P>Pcb z`(i_Hz*W9})ys9&o>%n2f9%IU1`>wc&^J2#nAjWN=>vLc4L=Mg-U}zA@9(~RVC0gs zn;XBm3C2DNDD40Q^TTeB8$6;w2mtrK20Vf&%0k}#10ssI2 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/acl.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/acl.mv new file mode 100644 index 0000000000000000000000000000000000000000..2e88d68167597f00936d01b8a80653842b6f113a GIT binary patch literal 454 zcmaJ;u}%Xq47Huu$t4GEQP~)}u>oVn1cH%opgQ#eI;p)wcSi*y6AK$(zz6Xqh=0IW zREY^oaU8$rSkL}A`icSo5kW|-31{|P_~O(xxBe4n@{QB*LXyAI8}7XuQYr$0aR62$ zU{WV!032EXKcM0a0tWAaq6?bvF-Kr=;)R?CR*HH=RJt%SNytDlKtsZY^m3XosHa%2 zIJIrl$|f!QrZtyWH>N1dQPFj&?H9|Y?u)AK{4U_Me(0a2P3vZp?5gVeaaC`MRaGvE z_Wp65>fTp%nVuHSor?L-(D)r}yvqDF!YuGs`ZT}@_A#fENOPFkz@rH0U?Rs+k%-qq zsCAe{eN4zQdxwhBFf`-{V=bQp>9|z;#juC19ROKPWru$oU~YCDhCj9)%$#so$qxa5 BFy#OM literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/bcs.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/bcs.mv new file mode 100644 index 0000000000000000000000000000000000000000..3c0aa2c6c57104ed33b9b34f5edb53cf3835682b GIT binary patch literal 92 zcmZ1|^O~EDfq{XIk%5VsiH((mot>YTLq>teh6O0f$iN6hY@7^?TujVK$;BKc`SD4W QC8@|NU-q}oyrJ)~MniiCRSf=J7STTckVVO3fuT`6ou*9CrnBOk$s z@F{!&H+}%dA%UnuFw)M>jGt%bJ%8T)<_!Qi1R~PP)cjy#Pu>(?aBRNff%`~B_(b2; z;0J5Lp#>m707VKwgE&@lU|71?>K%Bo>XbsFbn}-Rm|r@8Vgy zyef~{^n4kGwr|?*Jbq~Un9L$}^K>y@Tz2!=r(BZn?RD(VV$-M7tJHS$<}|4;zE^VS z`ipj!nnj!?zV4(@<`J_tF3x57e;KMGGs~t55n~kz#Z@Gne;JWdrRXIEGZGST8>U!m z%id>sCSD32kFX-l5S{ZW5@pf$mw2o;;0^;hk}kQr$CU#|BN*#l>Bf7W%zE&hKs@l| zafg)D?7oBia!b3XnXSc%1533Id`sfrhk>4~dq9vUm0`6W^W6cKPw~cptphL1Zvkn! zQdEDXHx$INY+ZQTCKg=zYDMe5u00GP*gvz`*~2LYI7W6Fl}Z~< zkR7MRj+17`A+zIX*>U>pC|WK&SQRyfzEMhMkPM2TYQ^39wv|_kz8*Ge-YYT`3}uFr ip~`@Bcpm;5G*dH}42Ge}&@e1AEEw7hEkl=~V-UZGqEc=E literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/features.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/features.mv new file mode 100644 index 0000000000000000000000000000000000000000..68227121e38c527ffbd3b86da1b82779395a875a GIT binary patch literal 2850 zcmai$&2rl|5XVV?Ujiw~vSrzlC0nu`f5dSTId!Hv^pLdEb1pq&AQF~2p-Bx%DfJ8V zJ$mh-(^K0g>Lt@-&+RS=vTkZ882hiEfaLnMsZLYC=A6#dk?9J(xM=3 zq&1Wd$~wvhIMcc)n$kc{#E(~}=*Qw<($|$iIp*p2Del#p<6+|hu82;&& zr<+uVF+vHoiE|}IzD#9i$}~+ENqH8FMRuL!8JDq`MKb7% zC`#V*)eWD8u}E+ERg&I_oUdMv#3D~Jp5;Ll&bWUq!kC9a^;}ad!=U!EF^j}Ic`@S` zmoF=e;VjCg7yQMSQ}B^4{bGgHV0X5RBAGAJB)O`+bYYTsF1ZSaUqxb`jr=5#Jdg_+ z2Qv0=VI|UkSNYlV6Y%5bT*LtnLYOF=Epy4|A_F%vbNnREVddG-Pj4Zfc`6pyw_HSX zIZH+5Wg5r`6BH&fUnEJy7b49=5%GDll4&erU-DIwhw;36V*8^f>KHmOD?ENH)5>%_ zm$1D1N}%GL6bAPuTUj&;3rzSH(%ob$i@mb{Zow!73I(FJu}fLFhx7Q~6$`0Z#?&oIv`i6j{9scW@p!TgftoT`*6R<)WTtAIGw5 z!7pK>;|@&2g}e#)^yTwvA%}%YaUgk_rRs!Th2K|3MOE)Pf-J1}RrfzRP>1)hh@Z>g z;_`C(iZ9;rm59Os!&qHZ`|s06DqsEoXHv~Ec`%FB1jnDtr1G@&aTZlS&1Am&Ko*tB zxO}DElflY&4n>2#k%sV^;BfdCX}E$sFcAbWZN`(U4lMH~%rZRW@Fodm0Po^YHJv)U zYMeUodM+AuwrYagN%b{r+ODZv6TIn*MjgBbu~Ek>0m!Xsv!+%}y_yC!v6}3fIyJ4; z)ToKpG^(jzQ@bX-NU>1|FDh*2xcGQjbVeXP_-6!eGeBx z&ur;l@r$Eawr4Zp24c*D9b9Zt1Z}7r3dI0k;%4 zf!i1+u{E+*f=)Um5VBqZB^xCeq+5bXHcN0wuY?BKD#0b&B{0%2p+yEIw8>5h9WpFo zos3G@AiE`W$zBOPGA^M{CiufoZ((f>W)IHbC!DKw82sMx8XlyG?5l8E5YB<(HQ>Y2 z!y0*{I@{2Bq__iotau&xMDYgjDWt@G^4Vf&PhT@;JTiLbI@6}wH&A-4%h${^U1A(C l6Y8_$nw#bs;Ph{oj)w4!JXSMxVWu<1J>Vybw}D{+{{YM>KxF^` literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/fixed_point32.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/fixed_point32.mv new file mode 100644 index 0000000000000000000000000000000000000000..40e1638d392962a4749fb898ea50dcb119f9aa93 GIT binary patch literal 904 zcmaJ=&2AGx4EA_tb~ZDUKNQ*$6_GSlkq}awl5paH5aP@mtX9nit+dHjOHv9a4!j70 zcj6Tgh-UzMHVsfAti-bC`|Pnj-j9dhT?7DD03s?GJ<-qZne>y0Kj0wxjL+>?)cyy4 zlg%#?5>Xfc1OXt~Q)GZ<6-m;DftXbT6eZOJI98s~CINy_iIRR~2#kqMNtB|$Bxx@4 zt8AWJl=*7?=*+)h?`7?%^DHlV=T(-jvt&_~%cM%zdAUl9+kYRvNiNf3lePam-8`P! zd48GCvxH2&D9W;GzRK2=V@o&r>*QTlm2#P0$z{Is%T2M)FN(Jzpei@3xej@$oBxTB zF?AUjGDaE|i;UIoOzzI~)>56HTM1-VC|Z&u#J+{Do(xXBXh8>hRt#0!iOJv;otT|5 zwZ4ljfIR}HDCo$XT9{3qo_I|>j#pL%dQGhLk!tI%fw9w0^}V$6AB@A;qaHZmB?&V0 z=unOHu~B0yjXqWn^h2_poZg}xqPrvMfJ}b!xZ|h{F5e2KTJ4!Cn992o-)#wMYnS{; z8Qm~AuA>4r>wC1w!3Vl;#Mt2!dE=reOoT@fv8#fM<~Ov z;C8Ta10UVM>GOcNM^)7&9nh`URq+UAsLBzkap(HMXq;TYdmh@J$8fj9k?J|g(L(P# L=z&2H2%5FU>mdty7;>`&o>P%nsEk0o&8uUvVA)zYSArQJ=no6`1z#0j2&8xnmI zZiolrfZ!#V@%C3#Sjzl<9?y)&IlK2KSO6##7&KP<_vVu-v(M_Ia$oSLq7P=%o|*gp zn{na0!T7^`HN`K&@;4#xQ-Dq}*Pxgg)J!uYvNah~XT?pHnC3Yt1dk#IFZLKL(;|}6 zP=erliB?YReG)qGf**R3M>Z%>cS=So+Y@@1*b-?#Lkcvaf=W_0fXW%bpIeJA2V7gl zs8q5F2$RHo4P>Xkgo==ZWrGreLfC*gh{=g*?PeyLPO%aZ)wYM-v|ZSD&2HB&?d!Gn zrd=-EW4~tO`B67K7mugi+woqrKRKFpwA(Ja$#k)bd(Em_wx{DoyJ#+zRXcA+7oO|; zTyxSbC%c{5pU!5qzij7YKD|0@+<`T~}pAsnw z&1gAX9)MK+PenVFo=Cq6uniGC%5KVHKqWb0P%jB{*&RxFmL5q;@PV-zIpnM!1A6uk z2Di1My3vPG%7q^hI3ws+>17u){*YwV|UrGfIFA@~ce-hb!- literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/signer.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/signer.mv new file mode 100644 index 0000000000000000000000000000000000000000..4e4ddb18d326e339e40802887c9c0b15eb9edb58 GIT binary patch literal 130 zcmZ1|^O~EDfq{XIk%5VsiHntolU-Di!%TrEOaLg#2!sqwK*-3(!^q0W#>&7}oSB}N uTEvx@l2VjfTpXXD#+Q^|RFq#H4;2CG!Uw=6GP7_q2r`N=F)}hSFaQ9qw-5vX literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/string.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/dependencies/MoveStdlib/string.mv new file mode 100644 index 0000000000000000000000000000000000000000..cef6870675bcec6fdf4be4d7cfba21a4afef6372 GIT binary patch literal 923 zcmaJ<&2H2%5T5bBJx(^>-J*gxfKaK#q2jpLJ^=^rtajV9UC}11B(1uS!=vyFJOLLj zmAG-@!Z-`<4J#gxzxh1=;+ZcmAIJazAsAtTtUjs6>AQRT6ThMRDqorJavpw36MxGG zQT#B1$p`|Z1*|OcPVpYJU}K~Lu$uF^9P!El1kYOv>_v(Ig=DXkj7^FXAjJv5G?pM# zLQY%E90JY`p0S-H+p?NeRhdd*9q`G#1cAl@nji$P*_D!EPK?OEkiR^o91XI^94V3G zgxLyVgJ)sj_+)0~)RGf=(15bOeZOok%%&nYikf>-M%e zUv;~u^Zo65xmV;i{j$E<4m)#QHrB{tkZgAabG65=@}P3g!zCTr)sT+&-yDAaWC+B&dL&kX@5qVs0`*F)&>O2BHlZ z>}hqR3Su|eD0L!>K1z~mt`CWCf#U!tDZ~&UU{oi$NykAdQS^b+Qivw%6VhZDa)l?6 zfUQeFp5Q=e6kxblElY<&$BBBDpDu$k`{{FogvpIxJ-5h7?8C P;m4rT#^P~i~BHN~xR_YyOkWTN>KG>G$j%|4aEF=AL_R z?w0?Uj}kyp`rvR{qbT{>R*R*cA+0^R`_o8Xr=C$v) z#np9}pEv7nxms_li+bC&&6`Diwdvm2B=gn!qW*2s{NfN$w_U#4_HK7suU~er@=dc@ zyjY(9T5PVjuaf54`l`99%YIwjEHAI?tgUbAc3a2YzUYgoK7DR4SLd~Bn{L_RVA>YR zR%}=6mzQdSuhJtE*B33<(`m@U=xc2mL8RqeGuG-f5U1@Lkbd1r=yc zOavERnW*EL%vf3_d-Wui+OyZE<~!@X^88cuG&7T+C=lfw*x^uGlaj6N?FAdaS-j#s zKK%mZokPg!4l?kUK=&vt16|I%dX&l|ug^?jD*$BbfmeZ_qDZOvu027`P@l&@2ZfRy zBA8`{2_-*?d*~S#sM_NVc+>Eo^?3|%%zab#S%TTaP0QpuH9tr;&_yNR&K7iFPtT)d zeHOVw+LJNrMBt;qb1sdEXoZ>U$MQ?2Rcbpzs>gBn4d9?T{k=tB5Cyd_8*MZ^5LPCU zKni=_`+hV>HutKcXYpw~=+_ke(nt~L=Y0|$3MCJ5RX#J;7IIm7AfGdnD7$@L9H-{K z{Wh`8|7ZDjupI-9kEBRUlC+L*-2hBj9!dUD4>vb5a9+<%NKM2}LgjSA#|X=_19GSW z9k?Fx7=1gDBvT}ryL-l2FV~RCK+=P@VY~q-RZCYU0-2{jA}hIK{2k0w7$>_yLkoqK a{h%FWN6&?b@9ntK9$=sGJP@8WtN#EIyND|Q literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/sakutaro_poem.mv b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/bytecode_modules/sakutaro_poem.mv new file mode 100644 index 0000000000000000000000000000000000000000..dea24f7fbf05d00aec0fff56ed177d5faa83c24b GIT binary patch literal 18916 zcmb_^X-phho@X9F;>mCHU>eEfy7^6%tHXB274-zt_As=rA(sY?A1 zn!ik0)&AXI?f##q;o-9w1tK_Nj9dflo zqtMEB%FHmM+8D9tAMj zOK1D&u%8a^(cvd_c%Kd*C^6@UboeLya0DWrE!)_~;F)Vhv^?hEC-sR|W zI?Ohe-e`1q?H;AU=uS2dn(dy{ZkNN>g^x)+dUsEX!|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M z;-e4Q1P9(=0|W#!2f819NH6psf+8}S9c7exLUzFR{@-x&c%p_V5p z;fj(oHb43OA8r?4%lpskzpGyRjcfn>-{1a^*Gqo)f6|)o|F7$rOCGg6C7FB{zGWm; zMeo<+s~hlTENXVjzHUOT*u9H=!j#h2RHzj@we%_a1r=&Vk`iAOpjPbLdvG}G&>{Y1 z4Tlc#@59)mcX}M|Lx*f;kDh%c!C=<=QST_zl-CxwcQv)t*Vl9q9ty=Lsmh<>8%6L1 zCJM!;$(gCi^c^lK_@WW5JWZ~Vm8kZmYZdrX7FkkinygTko|e9=>T`PZ9sfSa1%E(f zu4+fRRx95rSEAN*@g%Xo#cVd7-D_8vlQz~{U(&XuT((#~1p`fp!0YyoP6eaU($%)re2R-T>?==2RZxcmXXj9HS{W%^Qqq`hjHN}jG&$?ywWQ=*(veVD#qEyK-^(%;j_ z3Ke@~U&<6a@Ets|eHK;9Z)DnC>Rr2K>F;aPLF5PNa_#OkJWZgq$?0ls5&_gI)w|PG zT7~Lk?as8F=^tv-RG(m)pW^pt_{~Vy{+7PphyBxP({>jswHiE;tlg2eqcBOU#<^0f zN>kxHRkJ%C+IuOKqAK{M*TRsZLYl iT*G*|L!;89sD8lDUEt(SjfMp9qqz7>`aUJO?EeCD!IfG7 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/base64.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/base64.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..7ec56cc3c5f78a170f30aedd2165c58ec9dbc9b7 GIT binary patch literal 23297 zcma*vXM9Zu1IO`uvyo-hCKCxFA`-Dzge;@6V@s??5SvGBZJ(lI)GRS#YmL_CK`AwA z#3*Wuma5ejr98jWob&lS&#Ql4{N8>2@3|w_b-;h;W;u%{D=7-Yj6V<&w?r)H}UTisJX752=u2pnna8ixsrlS`ju(*~^7& zHc$6|Y|Z@Gh&&svY#|Sutub*7wen;8W9?~5-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Q9LU;QcZaq&rvvXesun0>8c34ZU{fPd~+6_3PH8G3)qj908QH->%g9L3kC_|{3GFF~mP8-apJW$j!$;oPj|USvb_s1tQMK000SYe?kBN literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aggregator_factory.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aggregator_factory.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..2ad608d7e802b55a7e28792da40b479b46b4acc0 GIT binary patch literal 1729 zcma)+ODIHP6oAhi#xNzZz(#2n79QJ)M8<1K=GGVsMb|ZECeP6|NY+*)8!0Ss<7FTqfIv4eF59@TuodWQnl%wc_ii}JT# zkyjAIT^HVPKl8r$^(`4K5}5_P3!PYfpm(7OD+`5c7dEjD!K<2USVvH#n!nY3s`*8} zQpT}ZHSaK=p+q%X$=3mX)vU$}fs2OrbGDKoMwz{kNiSMS$DT{9q@5Y<{G^ClhQDqB zE%t`E$9&ZieT=er=lMG7vNy0UKp&$@W;g))VR|B8Bc?uZziZM5uAO{?pbwmhWrIF& zL98~=2W|o@4lWj7&-OHfc>cKQwLNYjZ~)xhED6l%d?_~CsObrX!_l5_C}u{j-cT2x P5i4TGtX^|C(k=1>SR#Jc literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aggregator_v2.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aggregator_v2.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..41087aa13d86f505a4b010ae89064bdc8ca27c67 GIT binary patch literal 968 zcmbO~JMVn?wO8-km9`$}nzHn%>a3&H+mbG_F^lP}x0`*V`xpZQ!(||51Y&%EkvB0t zy(l$3u_V7JzRU=yd_Dn_{{htqFab?wcg;!7P0cGIq(KmUW)ka&TR_DRK^i!U^AZb+Gx7;K`vXw*4;7Q$S3#`>y~M-vMIQ#I%ysB0|Cc2dI(}m@YxS zWm0r?baxMOb$1N$4~h@=a|{Uf@DB-&_wx^lclC30@^N)xU{G}p^$QLS2=EUIadnBu NqCP$(GQgFQ0RY(ziYovB literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_account.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_account.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..44f843e31e22d94eb197cda28c65b8aaaffbb3f5 GIT binary patch literal 11360 zcmeI2du&u?8i&8>v{PCOExlQ8Rv4ITmF($k zimSCX961j%JL64>jzqk@yGtE%4*DcWZ)~#(O#0JtXMk_mcL(?{Q6ntmA-e;-3ICL> zM-J?K=;_;Uf9r$AHL;I#%G{hh5hTx3im;9jiU0lcRmtu@~6 z4=B3}^JYlxPWu0-cCnKdM)k2+6Q_q?ZDa( zdM$0m+73GLt-&g1a`kinCFVrTOu0f1W0qi^B~54aENNavym>HOn$xlN!w92hzL{B% zL$)-X$2v!vcM@+gjFjdgtR;{uP3O_iljdsTJplRAT#L0H3Z%IP>p>`#W*^oeD3YeL z^hZhaU&MP3MoV)m);1U;O(#2ym1aNjcECCEsawSpw+@P>xdCerxR=XSH;MF)JW7;jgGr^}xwWG%uCPbt;0- zHZK*j$#7D58r@5U?4q0mMf);Uoyad~UsiJS)`4zcda>4nZeI>y9R}UL?7=z$x_#M= zH3+(W*^G4s^Q+sJ46Fd?_T?loFUHjEi!-`zUv41Y0?_Tt9ITV@d;9Wp?-{?hFUI_u z?aL!PaZiG7U;c*G54wF>g*5=WeYtPQ)a{Ft&vpByy$8B|d3VUv?aLv| zqoCWDZCJDuU=r;8#UV4Exm^rnqH z-8aP+#22agnt?tCJie~P{Pwuqv~I#p*df@CSF!(s*Joo(vlVLv==pWV*Yo>#;yn+# zOInMy6?B(mt!?09dwcOnV^)Iu*Mxhq*Fs84cT(Njb$A;ft%-LKxmCFZvmaco;OqD* z&rExLK$1$y~XZaXbb)K79E@tHMpl3M;YXazR80A=% zjIMLYBCK0M=a2@h+d$`#dMs<}PCSCOkU7=aW*6owpgZv=um(YQ;(b^FM$eW{$mf`T z%p7UHhdB{*q%@t;bETOe-U7&zrn5#0q}o2MW)Q0l&X(qStc_44&4;iahf&g8 zg0&f3Jj(rivl%?|-NtPPu?PDNNNa3uP2Qq%+kY?*gV)t3yu!2D(}cq21mAkPW8IyN z?OiSL&RA2jy(KYU4R#xc-Va4TeYkFT21oH-4(L1OO)h7ksi0HkIIK%S7ewd!b*gM4 z-h9vnaVFMW(5Z3;R{t0`sd6FaPS6SP1+14rC%`pWTRsy!MB&Hp3Wc&coUQW2O0juI8_p}97po{KTTv9crF1k~(DnS?BNm$cB zzn|oAk8(l3pByJ%9;PnOA7NTsm*=Bc*AY{f=ebxB(B;{gdHvRL8S(5hqRX=%s}6K| z?!~$bba`HiwG4E5UXHa2^!rI1>wa)?>rZ4G^98uyeK>9H9NTrf`AF%-Oa~WvAQvqk zT;_pd)Dp0dw_MvdA~u6w+r3zS2EDfL!deb`ZMR_cfnM8DtQDZwwzXD*Ny`ldtEy_R zjznXT+GuPhf2&S0#XtJT`p~R!Lo`$$s^RCD3?;i_vx4QB>o&`@18RvqThXsoI>9EnBigOP@r Uq51|o4|PDa_R7!?j_{ao0cnsn3;+NC literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_coin.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_coin.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..03d37eb2900ec88e9160f76c173e41883d885a87 GIT binary patch literal 9737 zcmb7}d2AGA7>B>@wx#r@v>dG*ZMl^zLJLw0)h-Gaicq9@WZCX+VS#pGyR}dR0Zj?{lV{$U`R3c-`+YMF zr*CXZ3R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FwFYY&=0sRUt%eqF;uizfQ8U}h9R*W?q^fIgn>p{@VumY?? z$dlt~op}W0OS1xNGB^mP9KP%H1Lxmt`ePSZN6_5lmCQw42s+8Du@-?&^2f0zflhME zTnr96cK0~m)Wh8`iUx4haBwG7)kkWbd}BI-{SzcsM}on|pp!#Rpen`XOiCxeSDToyT-EJ$f>Oi;K6%AjzU79F6wo% zr&xl#65@R|PCnYdgSr{q$t_>`9i8MyjyMa+cRu5It?%){fZ8;iOf%*@IF7xQ$ZNsL z=bzhLO$@G%yS9nL3PaIq7GXDbqHrn3+ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_governance.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/aptos_governance.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..d2154aa993c8fb5fde9610129f41c1b3f1b4a157 GIT binary patch literal 31769 zcmbWA32;?ao`+8efsoAv*%w(t*cTBJR*^s+ArO+74Ot(LM;M64Fkww188 z3!59Dh^V+RwhCgqAOea~w9P;xpr|M=C{itmFyA4$^vu-M{O*IQuWG9O&N+8E%m4h( zeVMHA=QdUh_$_i$yW4V(zteO0w7o@~&vgpG{jxSvlYRm%=V*dYsA+f%S zs`5&2QTZHypv+fR;EymSOH}?&V`C112~p3sX8}eZ2{%IjkDK< zcNFJa7v4FXhD~+5ZE<=-J$Z%CU1Q94Frn&RKE^r$%KHT;GFE%7aC$?ita0|W#w-AR zjmxl}0(Fi1alUfl#qzvcLw#A}lQG6@1Kl6@VI6`nS!b$!ieT!g`?(cszO}`uS%R|) z8c6frW|*L#`72nvK(&1k=SLUbMV!XX>F2V>RrK(6pvUWWtX-h4@gF$NylTI)yoPOdSB!GuIs1j;MQ zD}ANj;zIQT{z-|iA@mww1;yt03%xUal{5X7s$knZV|qffg6crPUsmPy&-E8nR~46+ zU9LbC?|6$b10g23V)y4WO2Bl|4`d=&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DsSP$dvnv|$ P&;8%5K=sU7jTz=I3Lpn7 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/chain_id.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/chain_id.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..a226d12e44da094181d94d2ae58beb4419c7be38 GIT binary patch literal 784 zcmb;~e0=Eqv-|SQwU50^n2cUeE=voFopkI*onpf3wUJ5kj*JWpoP-Q&%1WTB zHXvpqO63xuN+JwR1o|i&h#8pp6AMc6i{sOZ5_40_^NX?xIXnlbs~U)zGE)dCZ38On z09nGoPB=gg0u^2WV!{D31E}gE5EBlN$3Rt|fS8$J(ES6d0!14OL6u)XHUm|%5>$B` QsPYjIvk|3|85D6006c^)_5c6? literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/chain_status.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/chain_status.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..94d675c7c7e7ecc84f4fe9c64e0eb92beb9f8ec9 GIT binary patch literal 1551 zcma)*KS)AR6o=3AUlCSIyIWg-rsf=8;*gd~LqQ^yB$9?2Hc8N2Db&_tV+a*Am8}hd z(kf()EluSR)zEhX*Ume-&TRoW?Hca({PE|EnL%c<$rC++w|UcnTDHuDe8;DBjP zGkcg*m~Pb!U`>EWHHWY!!K<46)qSdI_Bag=TAHDyIWWbbC9r~%0X?fYRu%ND_OK2? z&nk;`1bSBe)%C2*9%~>jwfSX_$U2x}(6XxG)IrZ`7pnsL7Rp%0)>Ad+88}c+_^0Y% z%B}a+LhXXy*EQA+=zSUU85~@KC|g_wu|`wdrF=1&E~K_L%K1W8JCGz_<;<5(Zh8ap z7W6Lnv6`TF*~aREetIuh@1WoGd#o1dH~j;v2jcSEk!T_rvLkjp92Xh+dyOvGv0x$` H30d+B?njlh literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/code.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/code.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..38ce5b7f551d7cabbb12fd12503e76b006574111 GIT binary patch literal 26346 zcmeI4d3aUTxrcY=02u+9!W0h3JY)`K%y0;~NfS-t4x+ws8&U4 zt$-p_A7_FW#p)HS2v*uUv;u`IrTR#1rD~CS-xad#?LYl(|Gt;!dH>;g_qW&HXYIAW z^{usYr0*kl^le^y)60d|1s*-#ukp~#kYh^^^=d!A`mWhuR>eo(;5d#Cg5cl%3kt0W zRQkgm=ZFY6BGqvwf)lLFC0MnfyrvBSz7>KIU5Feayg`?&4bJ<1B;_dG78Zj?*8UNOj%UU|kQ&+kvy!h1U}5 zIPIX~EefOWfbx#u9CzU*(z8do=-t&gwJyAUI8Q^UY~jFQ#~BMwkh+#NSnUudW2Sa< zoGj2W7h_dHjJ}m|@s2YNoZ!$Uje%O#+VQAK5ZoM4YBpM~iR`$zvwp;C(4&Dd>p}PT zW~^4wzm_rALAd-48nBumLYk(XCZ>x^Y8&P_cY+ff8K|lB)t6T+S2uSX`hC!&&cDJ} z8>nol@i(bs9>ec|@X%^cO45Nd@4dA1=j+z}=5$+;@1wX$wXsi(EPmt0jcZbtoJ%_S zQcciE+5@4>JSk}^^aCEp`6-0g`0G3=$trel;`W7zy7F4TCna5l|CG=dp}V;~T&*W1 zRUJ};-UOkop5)1@J;$zQJOO8-eqg2(bQb8IIt^F{iO`3I>0Z5moX=gQLxH8QZWy-r`-kA@B zi&yMdBN)2PD?T{3zGZPubyJnEyt1;<-z3wfSdJPDp>FcB(TL+AE@Xr!N#!VKMmx^o z3A}vDD=GplbGB%hNXlE|b*dR~PwHe(y8QXS;#w|46y3e0hHjSPNy|`IwT~P21du?dNZBU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$k2O+qUL%b)0+gE}AV-mAQY`6nRUP*P zC0+!7eyZgS{13pNpK1wAV)g=?U`oJC0Ub>Bv0_07Qy`XUUk6hm)_Bmtl#MkUbTAon z4Cr7orfFRVld&d%#W#az(Jp~~FkQy}*_5!|GyQ@boJ{}v^(L(!B{IRUbxmq2-&{bb z-S5c$4D|@mPjb}xxR&vtBQFbU0_ezd?@>qIHtPE?(2;i>>m2CFJBoD-bmXna>X~A* zxT%NL5%l8b3UzkE)QcOpb-lRRPJN$&-j2P5^#Hv->cUIYCr+`h#6C+J_{=H?sy$@wy_@mXjk^U`FjKY(60Ou{mD8(HUgtW(fd zntQN5g?7^XPpr?Ny)@m{J4w@hnidzDIKpv~z zwlW_w)#?sDgZ7Q7)cO;b3)q(-&~_%jfgCcD8N=@Xx1up>3-E8*Ihqm^!H>hzcBA+* z6L`@ldvrEc&j;Q2ld%?np2yuw*7Nws)OQf{JiZ3&5a@Y)DOMxyUat!;Vn$%toP!?i#F}pyyn-bv@_SzmHc=204x*usVUBoinhqLC?;;u)Lsu!RiU_dlaUgovW~B zfu5bqu;zlEo#$aKhFIB4#aNGl#k6+uzqweC zf=+(-V?6;*beJbS*E`CS6XAqqCy($IB=oHBgx~zPxcJ^tPPAu~C)evs^=9VylC!-9 zIr(*++dVh`XHIgq$CvN*`m($^8Np6NQ|RA+k>$zB$RAkGiMb``jm%E*X8lVK=f7v> z*mxKu=nb z)1YJo8$AQ(|FF!{>t|b_TZ+GIBi`$@$4CS)NUktP5D literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/consensus_config.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/consensus_config.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..c7d41e5ac21347abc674c8947eabb599f15c28c4 GIT binary patch literal 1968 zcma*nO-Pe*0LStFvrRWw`D{+K4neU?B$8)YLg(+OyUHvJ1!NX_&|2CfAx({b2%BAgFA8)kYOkBMl zj4!oU=Q?@oS>n&>wXN3ljxpvHS#;K)70G*Uz2MfHb%+0or8QpB6^E~4D!r2}C0nRX z^65j9m<$=8ovSvyx>Ky>Duu^hZCzb*pI13F-2VWIm!Z|(MaI_esttTgmi$tlpx%*B z%Fn2;D}DMEs);LI4VhcH$_y1^lnyAF6rGoLe)s`#zR#}?o-zLbsQ`5e literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/create_signer.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/create_signer.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..b80519b5f75941a8f776434f5e5b8716f8dadc70 GIT binary patch literal 183 zcmZSgdGp}@^@9?oKFU)TbX?PkC@Mk1-W%6sTi-2xp#yw*qGk`K=+A8Ej_P2 zsAF7@v&+GIvX$p;0@dDzqJh~1#Pu8gJwp|CVBbo9Kd;N?|qmM1T%?2wx@ z!D;W{b;s%N;Eli;?chzvnF~eaInN_{F9k1`I_I5OyFqzJaZW-}X+BNQSqHjL?7=z& zYTw`ETy*dXa+fOr|5Z(ff5;#MUhV=nGWDfvji#h@F=B^RiM9FcsiHJ{)1C=kcSv(A)&!^|%?PZCP+6MiuzrU-rFj7>A7QhKG;hNy3RR_90;@7q zlV&lj;t(p$FU;9s){tg6Ru`x#%_yw?P)nM2aH%WJI<#kop?cDM`v3(Fs4vakSVy3N zG(X2W1r4S7BG&iNSem5|@?=00X%@$-3r(fj7b^vtNpm#TOlU66Raonxg*4y7`Vd-5 zvo+Q+XeG_x%=N@+ge+2eG$@pBgu7r+Y%YF@K}Oi+OtjnM~?8jIwpK!^< zOJg+$-3|Yt%@&xt8`{0=ZfK6N6*xRuUC;&@HJ8(@DGAjN!B5V{vem<8M`Zo-=DmgZ zF6f)L1M2|jn|BE7BNmCtSInWcCmGHeaK?5KMiW&tdk#)G?$vRwC#aatBs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tk#Yt#M_wtX zQQ=D7l$5*3Jo%)&Lp@W2lxL_b@=JMwvbQ%%`S-7HlJb*zB??GcKozN3%8%cfEmGQ> zzo}KqPJW*rYLl`bHB9YN_M%29C}jZEVJGD+Do34C+A2@R@=k=p^CL5%@yOV0crr9) F%nuK}r6T|U literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/fungible_asset.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/fungible_asset.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..4204da38c1250cfadaf84e20f4e5c727f22f6d3d GIT binary patch literal 34109 zcmcJYd3cu9nTJmj2mwi0!)gG5AP}PL#0o-|FC>tSERY27BP2m0Sul$j1VKcq6~s}D z(m}C`*t!tWQ7i%iZ9xPCl|doYp+i9suvja~GBWo8-_F#I^E>?ET-SYF(|Etnd6#pZ z^PKa3-$zN;1G&Q@o2Fe{)T?+^lkM-#ZXVh&`0d5NY}aw*ZTEkC$5XqFF%1v^|KI-w zgiWg{zpZ3yX|cbcs;ap98e>XC=pEt4>;)5`%#&DOL4b^z*Up$?&@ty@ErLK9b4q(- zW`K^l2x~C}$(V(0jF|~0P+j}oSoeYQR^mJljimWTD`VaT6Qp7`V4VQvg|{}QCn#?m z&aKc`n%!C&6Ak(tYp~{mYI`TnhYsEtt~UdMWyFcijVT1vShZb`^*ShTY^X8gKzaSc zjEMo|?ZNrj!5iDcnDNj=Mht6fOgQMV&>t%XLS)P-%X~t-QEW9ln@Dp9K@EAN?(Osi0@SE?8-x=d=hcYwMXR9P1v? zxnVli9MB^^18Xkm@#(d$N8Kjk?S^aQ`1BrKs5GA^o_)w+()6BZ3u*p^cz=VI(magy zHMElEIjoS*#Ox`CJ-rP&3mA9RvtGpuOnEKRTVYo(b^yzvkr%~4nr zpo=soVwFNyY35?(LpN#0U@e1Q(p-S`C|obia;(Row=})h`$%&&@zy|JX}*TF38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|cPt&!4q=Od&XV!siJl=2>Gf}*4xK%J*(DIcO9ksp6{aSmfrY2{;=#;QVE z`Ph}Rs*VDdec-CG>tDryP-KU<&$D#Y)xy^-`b5$HE=NBs#`G(&pS zucKy3kNN`YH|bITh*~5)>K{;+)}#IomBSmSM?D^uMS9e2sBF@s?mJzNx|{vHq({9N zNc&FqwbrEbyEIfztGjj#7OxK8HS9N(l=Uh zQYNuq9SxN_= zU$L}B%AcGZfJ~M02h!RzO-f6}(N-zlC@-Z;S%RvhZBp(+O;U!GH&FK}Q_6Fw%akQ$ zKk6)HOZgoY#HUS;l=DajGFM99cUPX2ZR~fN@}=xYU8U_(x=;tGK+2#{CWCfJX{i+Q z3K9=|==hb(68jIIC(JN~){MJ(VSOp1QI<&T@CP(`Gg<`+bG8q~7gvdK#Rrx~ke5 GWBvg3lWk%E literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/genesis.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/genesis.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..fb4d80d99f2b4a87d39c8d4a5530f0ad1f7c481e GIT binary patch literal 27836 zcmeI5d306Py~j@y0ttj9Ku91m80N@e5)zUibBGcdWd?`K<>nGDB=?4UlOXV*OyX1& zMUW>dsE7sov|1IBs@2!3OhQGW@E9Huj8{TniMXZ`A(g=(XTag9H%uz!9V*K zRjr;iIS zh;x?Qd%7RhG_J1)#jaI5)fSf;e+rc=zEv;=le#yS!-NRK_KLh1$!#U!@JBJe$=Qs^?$W&@{J5#G; zlDw5wp@?Tn*jwSB846EV7t@|pxsc@b`9jsfDv!6cH0+N=RJy*T83y$xd&|8+pI`YC za3?`@O#8OkN}h$d;xz1~>)?B5{XPN*x* zUtqlt^`vQYkC$d+?r8?pm*%(R+y=9OH0`}lkmilV8wm}inT0h95~Uf&S^!DXT!i%? zBun!ltkuv+nqI6&p|LbKV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=n2lFSZ6^`aK40f z4)g@4vCe~w*Dj+EGd)oI0Z=xn`k9neY}r~w5Ep`OEyiFi0^K7r)?#p?8y628Gh#?d pQUB4!p8iEe!^aF89p$7IU;eLW;PB#6o?*jBdy2=Gj2i7Y{{#0w#BKlp literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/governance_proposal.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/governance_proposal.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..feb6c82839fc413f0bd3208c894ba372240f17d6 GIT binary patch literal 360 zcmZ=<5z!RKV!QH)bm)aEmzR9K8C}if75&`zcE#rS)w9&te=smGa5FM601;lmD4d>O zmRgjTn3tRyUr>}^kYAjb1JvY5zD9eP!o$G)mX>P{a4$accV-;bEG#99G05jk^uc6&EHEe}%q27l7 zTEvG0%-I=^y42QwHZc=YdW4k)y@~J0nZpcFUuK>A2=3RbrmFpf`o;8+)|NIp*8=)a zX66det(mz7IA7KJfC)UcDTKB54E4F`A+3E!^vprGW@e13TQjrCW~-lt1t##-rVuTD zi_|2(q5goVT2X3_&pjK{hHUg*C|^CA8@up%g- zMNo?JQOC2<526nF^T+?rpKwyC0rikujCcU?q|@*8r8DV5+Rdv$drFNt3}&i+p`J7O zYY54A=@Hf_grylQIwH+kta3h-NYh|Np;Ve5SmO@Na%rx?+5#2QY{J?KmC_8J9+&1- z=DQ75(j3A%1=Z3F-uX$=e9wHJphlXXv3|g0X+FjJ2~(swGiuBnm@3T~SdB1Enk85Z zp;nr{wFoQ@{adt8VBe7m?4M9-+mX^TKHgB0bv)VLS%~!z%@@7CTt<~(8EOl}Qf@Ns zIT@LbUgT|1?d7uRLT(_DAMEeX6xDNfF{B8QSl{44HbJb^h|}2Tpkn)g>+W-HhMY&g z0x>V0E!YgWhI|7!kn&87;=Kjk!ElV1A9M%5GG7^{?qD6(T+kh?#cBZE!KGL&5S4rH zz}f<3(!9ftwqwSm8NBwo!ol0BD;%5|UEv~YJOsMJm$0sbuJC=V$Dk|x4C@u>3LnNA z2VLRaSbITN_#M`JusEQ-<;H9R`?_t$?t_SJ-8|$1#8UZ!)s5#U@-SFlt42^SL*&1% zRWBIv2L9_>b*93YixBs3*7<~AAvdKu_l^Nyfv+X`nfb+v!nnFYIStk zUnl4W)nhe)ZcsJWanNPSVjTcomTg!EL6;?Xx-QET=6eacESIrvf-XyNTy$9?mFxy| zS>jkTK$oQwYc}Yzd}lXxm=(O00FD?{^EZxpIw?B)=AI_@U3Amp_;bNuEdJv>z22+uWjGZ I-nQPDKQJE1VgLXD literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/multisig_account.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/multisig_account.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..f7553f2e15d5d1224a3748e7e9700d125a39ad85 GIT binary patch literal 67121 zcmd^|cXU?8+P8Na2!xKJfb`Itv``L0AOV7qgd}w2;UPqcq(DgMND)Pvh$4t|1+gMh zMO2WE4Ftu8A{Ic-v490d!S9+RqkQLl>-)`<^ZxgqwXU<4ddR(OSobz3)3kPOYP1#?wPO-*~o*q~A*A8bA4_vu!_I=@=w-|!F|NsAj%4FoG=cJ8E zyVK`SNy*C1%qiu0H;Bq#Z|ZqRzzb65d8}U`NY?quEuMD)ybx7qcyrGy56Y{9)5^h% z#)*euS>y2*o_7)SF_vuUc~w9iV?&&_4qkVh1PGBe`s#RI2Iyma1?vq^$Cy>m^Cp1u zj^KO*q0&6s+Vj2wFId(2Csv6_-F8cyP7o&B-guMe?E}qPpjO2Fj~k!}A(}@{(}wbnq79yy)Pa#qnzD zcAMg~bMOY^Om*-c&2XB58&sz?vzAtgUaqzk` z@A=?5Sz}yn&+~&m=NVYDK^^0IoXrki=Lpa12CBZ5IO`m|t2kwtQ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U|t42ooZUZ+7amKR0>uT z(9@|TtZ|?xNyD(lf}SMx#<~IYBq?ZJzlD&+=s6nnB&j!68tAtWnqX}Py>z<_>pti# zNAD7>`=N_8gVyz12=5Z_W9TMh{u%2P=q}BmBK44FZL&BSdYa76n7yU>E&F&2W`Ajp z!I}jFq&Wy{Hl#^2XnmkGHxO?#Tx&8P#~dWhyRjaE!P4~cw!;u<`jO^oaJ7?$7Ukzg z(layj!v%D~TH%cJ+}ymvNM?9MxG)^YALI=k9?mF?gvVwV6c$|Nt`6sE20@I>yl_Fp2l{0v5?zDr-0Z?gR#A3lBqKkZUYMPi8_6xo zsqPvC`xZ3*>n_%CjlvvXUQvEVIP%+I)m+N2%|_CFxXKezxeFn8O=Y0#^Ye0kZSc27 P&EFaYVRrwwMlJV0^M*8W literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/optional_aggregator.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/optional_aggregator.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..d9a21c0604afad1ba2fd1e2dd064374e56fba5e8 GIT binary patch literal 11558 zcmbW7drX#99LLX#0t$KIreJC+;H|VQvqUQ)1ltUzDJm@$i5U5MV~C|rZO$%JOqA{J!Tr&+`(M zd$aU(c1r&EOHWo5d>jAn_yO(f=N@@u?T`s0qpu}oEM0Dl*$6)Pzkj}{DN~CIrcBQ9 zkITu=FU-r&DVkCkWK5LkKfH-Ckzj(9*$wLfP~JeCWbjF|M>AsvfF64y)^t!~m*MP& zNUeU=#+U=Z;CGlgHPAs?o`B%u9RKt@WjA8}X~#0H^@YW^HKrfv`Rjs}3_)^UBC%4S zi8Nbcjf*v=sWfL{E{0%f7Gte|5NYOOy$7Mv{1WRRG?V6ftQu%8P4C{rq}hrY>H^`? z48!UP_eismYrG$`g)}p;o`aUs?2k19T1nHpcZaeY-PD*|FhQXOlZ*25^9oh{zl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!MB7EngSNHHDmQJxZUTChuh3;Ire5U+%srTT zmD91ZL9cRmtmi?moj1B(yOs2}74+K8#M%aWC-p{m*vwM++nihoY?UX`avt2xm+aIC zzBq#Gxx9n^_ki15_f5muj^_3ld-Xt=!>&;=Td z6%BeD^5#jGa&P*36m%(f#OepSl;>eB0R8wd4C{5!Meo&>etcL%e>*`xK9pirgMNtJ zhgA#uL1PKlVbBj6$FNR-!;{7UzJ`v0z+#+B%VM~j7;nVi0j@F5YGup|;1=U+^n43k zVqA-N3UrM3WBm#`#^qS`pkwUKgN|_&ci+*@fZRlUSoeXBu{TdT#!t{+I_Mbpz#0NN z#(u16pkq89s}OXIy*kk`UQB- haC-8H%;DoQvjz`O8=5(azr6bIe~-*a{pbIE<}WZxoE!iE literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/primary_fungible_store.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/primary_fungible_store.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..d0b68973482ddbbf2a8635bc788cd921c31ac2f5 GIT binary patch literal 13313 zcmbW7dvKK18HdkqHWwfv!2ls3RfGtX5kzjKTug=N2t}w|1W}evvVq0yZe}l9P%CN` zp))cH79|tgf~XNIw%}kSEd`x15J4?djWw+@EoeK|R-{Hcox$hRe*W3tyJqJ3?>Xn& z^PTs7&-u4P1A>9^uke)oH&<3r9}0|EE{ z{{jP>Qn7d>wKm+4O{|L5Hb%qgOfnUvU5$9e?gHobg9|A0DAu3g0^RAu<<30@fxsfw z>vpte2o^@_>XO++Mm5-h+zLhUXeLr0$wX9xeaP()$g3JYUddgE+5WtaK6;d&;C}9P zEMM|}u!8g&lx8<(9%i02{a+fA=2ZHthJ0yWg*68Xq&Ws_E)+_$9P9f~Bu#%ry`{N^ z{%(Oj()9Z@OwySPo%;-2UQul}l?bPz4JulC(9c7D^0q`YrR+XKohyTaNZbf$Oa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&TVD9NX!-Y}j(}cmJ606*YTK}^t>1lX zz6dT}zsx1Z>K)4Uu&{TOgJs7}PXmtg^oPTEq^5qzD4u~=7sJR0xq>r(SP!GKQi zc*_08uj{g1*D=t~#@Vf|jIR@K9CT&;2+N+Ju8b2{lc2v4oOSAZ-;cL5(!u!WxHKXO;ZyXkE=? zHMOC}P)mEF$qIzR+iDs^_0ihKNZq5+mQYh5!DRpU*M?U9D;Q~x2DSylEnf2v0O~jI literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/resource_account.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/resource_account.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..c1e1987f9b4f94746f2abc06886ded0636132c88 GIT binary patch literal 7447 zcmbW5ZA?{l9LN87fshLV@(ex^StyohTk92*@Cq1l4Iz^r&hEGey&(6p%OwZ4IoGPK zwe^I}&==CmW@SZL8!aoh)X{9loUE;uxY?RDO#^CbSf5)vzU+H|?epTY&+q>~_nh-IRI(TJ!y^r-5q)Bsqt}z=R zU7C+$wZS}T#;~4+3~BDhIslo{OvW05ENRBA55dI^x--w1x54#jIgI=%xEd|rAdW(I zryUCf1F?YBZAU|aZJ|E>T>hE5Yw?X*BSBkDmCSr&a=`smX~b@U*-Vv3sfz%YS6+*L zyaCWtWgpgl&{L%wYY_BQagJ0^73X~DsWQgSXF*Sub6At0r^+8#*FaB|cd)L5o+@<( z#`r-`mB+Ab&{L%w>lx5fr5|e$^i)a0dKdImiCc%j#f2|jXv`XzK}W1dZv?NC`h&r! z>N^|13zFuxM#8Z`h%Bp0UR-3%Ymi}gcEx%v*L5A#^g;T~>>O}$fW=gl!ED<6A?iYq z>OQ1*EHfStu>BZE&>Fln1vy%1J zf$q(6tQye0>0D~vo5QU473kjFhjj>aZ{EDEphNt7-p8z z4zkN9z|4_1$|+Vq13ET+hBXE{HaSPFe^C7yUymczc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u7Nbre6edR% z^omDC^ynQG5jl_mU84KMMfHw~^zpCubHw)T*dw}=zkAfcFt0>ZO#fa{z5SgcV*TdK zI>+?w62YQ{`*05&Mf7(8>%*TWX_D*d0Ru~EGuqkDC^aVp_nmH($< z+b`@@kLni_XAX*u>CbhI?$wD~(I<*Va_&%%=$_GW#k~6T8x*=hm#AJ*eWLr^Ja@mj TN}ak!^y*?xfIbuzna}$lG&+CO literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/staking_config.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/staking_config.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..e56cbea5206c2d1def4d20ca0e2a23a9cc5274cf GIT binary patch literal 20868 zcmbuHd32Q38HaBYmdF;suo?CMVU-;O0uqu*2!DO=;yKSh;koa<^Ue3Y_kHio zn6tM{?ZFQo+VR-at(R8xU6uO!r2k#@CV-B9LxiRO1 zn)f4|qYmDc3C7$FF*4$rEsaS5(@@PF*UFd#P~HZd?GE0y*2WwJ6>spF#!Lg{t;cx{ z9Hws3+nCY71#0Wvb&=5gV5GRR{_azg?Pc^2Ho_TtVVB~q1^s4JV(o%B`C>O??SKZ- zd<1JJG?b<{dn0L@KF0Kg#?thzQ@k{X5pNQl;bcz3bhx0a(6(9C#3mM1M)K}w?bQKzJqlT+Buo={dq^F`4;ishO?x3Db{#m zCP}j^)(Ge*%`Ww3Cuz2?H#GAZZT7 z^1)yy^CHZl(%ix9Va#FDyc_Et7%t7rvF?Qt(!7e%a`GN^oc_HllrG)tE-d`*2kv{{wlS9l$!|Woy!nk_hyRvt~bVs7SBwZp;dBUh@6O ztLy-mCBK5W74(v=`A-{Gm&RqhvPJgQxnAYP$k*5b1eaHN9pdAlmu$_Apc{nESg(R^ z5UjZiblJZa>s@eAhb0@64$c=W19=iOitCv?Slz?pdl>WAUR;Kr$wQ)Whbs3b7SJx` zr?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{VjPxY%d&YCI@99aPFUpVfBrp&aM0yhFj|w0?3B1I51|#(( z(0=ZEYG)t%^wh2|OYTQ{Y8Q!$Aw9JVLq(9D+S!MGJ+&LkctxbAcH>YpNKftT4=Fui zi)TFZai%A1_A}DcuqPSs8Pe0RRjA*Ro`yYwT1|QyX0NB7T!k{8`3%#OEA!#Ji}d8m z$X7{EnO;NfB|T*_azE*b(4SDdNl%3A(+xclI?Q-)k)8+{`8Mh4%`wz_q^CDVn$sdZ zX*q&AN_x^_KlkDCjAaMob>h=7OUld04#;dNKSXv!=16HT-7RGV<3&=glrgASx?jpD zR5ayD*%#H1@})FOj-vu8?eh>TI50c8$WxdYA7nL8%P(-}C1<30GLrNC_^ZB|Iir%Z zGE>d}dh(KUGSXc9V@X<`+f$I7myuTBDa=O)TCIQnKu?N0Cp|O6-)i&I<8$4aIR&>z z@a0bc|NOz80=L^UEHfj(>M$%hKQrHR+oq=FxU(~Jk_$53=6cglBW1gD+y(BO%#`G; ctYS}&JI9lnmXepoBXcr5DTR5X(tNCc1As=fEdT%j literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/system_addresses.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/system_addresses.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..4acd7ac9931dfae18091576662d633dcd3b8221b GIT binary patch literal 5964 zcma*qOKeni6vy%Z%(RpigaQRh6$y_PESiS444@V>v=@k^3{GnsYQjipjbg-vp;Aa% z0T%`}Dv0=4xP*i#@{+g!UHFL9ph=O98xu9Y5^GXIBq3J6hsljQey7PVX)>RC{`Y_G znS1XH-ncodsdMay83R*B-u~_2(No>CCqMb((>E^6_-FCWPoEgB4k0Wd339u?L}g)5 zVOQTX`K`UZJNpWSzCxHB!l0;rJQc!45)x%ww{3g2f5$F$#3$%4?1)gN%g-$dVG&8l z6RAMelBAS>v3MOaCFS?Xeq^bX?Wm{71Sy+Q+ew*}@#>Dv&q{_+PyAP5DZ0^)pbhd& zb_0iqz6!ml=ZU@w>rnfMgT4hjYcx?}v#AE`9Q0%3Tn)LkQQ#QSTf2(7M)cM$qv~mE ziCldOY6;N;cAc8{AoYO7t2^eqx-^7k#M#(JXxg}^u|vQEL^t+v)C)v6b_41v(TzQU zx`Iw97FyrV_-_ z+<}Q9>?i&{96%qmBRn(qKJYBjeK>|XM|2fYqHXfn z(V}hk*a}9Mb6D=Nbw!)@*fmAF!eh4-?Mjc`TePb@_9!+q=-d9A^y?j>2hy(EyF?FU ze0}w;=>+vo68++O24yp&C-+0tX;Lm{JU-7!E@@LZRmv|>!=zHmZ%|fqnv`FoE|cj} z+K#Mdl}p-prCQ1#QNNHmQvQLmnl)1Xiu#@0DW&bmYR+{@`$o@~a-4ceWn(L%2p!&&rDQ!nq^I?~?=ix>vUqZb~vQi#KS^WHlX+ zu2U5ud`6tFXP-mAA_>py*-yZlNz~?a)T_ogHi^}*4^}mW)UOZm`ug=@CiUhJ{rXUb zvOVe7hj{f+AveFKoQWp>U!v>LSv!K4by@yp;9;VBJAitF=-zHe9U(!#^CY=oQ;BoL zDxp=zJwJmQfK5biZ3U{8=&d!Q(nS9Zvem6-C`mPe8QAXpRx4=UuhP!ADb z?RBVW;f+7<36+zl=nSLi2Wf^r)`3`CxbyB$q^$|s>d=IsNx~O~ug##}esr&}{ z8+B9p8R`$}p|U=EjLPj;V;pUwvIQ!NHhYqNkXt-SHG40W>fbhi#NVQuR?fE4dM1%G v%%hsL>4rI!IBpEuIU}WKbBR=1q&;OMGnSpS%ppCKH7wIUl1S#Pj8FaoX7I0+ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/transaction_context.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/transaction_context.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..b157488d1cc9103a185440206d392ec2ec5e079b GIT binary patch literal 1381 zcma)+ze~eV6ov1r{SgFps6zz7Nfe5IL~T11!4z$V;t)bxp$;i%1Qj<0>(D_uIJw(F z&_Ub5v73WP2i@FscC#JS^Qu`rx$tdYPVT+$CARUh*qZ9hrz4G<%R%?-acg{dTgpF_ z`aSC|)1Ea&Bn1@suT;|CcD)_9?APj^Q?7e{bRma82M)dRXh%=ZfC6Y$_?Sd-{sjCMPOIRP_D z%^)*I&1K|mfH*bhU{yhan&zL0vts9J#zmHZt{6Yr6{r=!x0-=<0QgonVeJFH)gY5^ z^%!{da6u*? l>jQb;AjHKz!5^swMx|6Tm$vg+XVoe?>vo}Ftrc@wksr4g1uXyo literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/transaction_fee.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/transaction_fee.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..f731a05272376acd84f864784efd55f3ee694c9d GIT binary patch literal 11269 zcmb7~X>3$g7>3WZbb-PYXeniBZGo0m5LrYv1MRR`DImpw!Z1#UMPR0x4gv}WM3V+l zP*h|s0tU+uH40d?3M8l?kSI}VH7v4KcEKnVB=}tL#(%zdnmqrW^PPLo`OdlDIn$b) z11*+*QP{HfsiCtE_sR3;U8=|^7;r89=%%YRODe0EM~pFx!3F>K=Sq%*eZf+nKQcWO z^iBx`>KRibVpqi)^F0`sGEZY&1ec6iNWW7+$DD_?2x4T+_HoAa2NSEFvk5!e98Z!V) zOg(>SdQd&VK-9sI{PgT_&|4A+`vbvBucXq>kQPFrrmo3X{Iuw>CjM`iC8V5ku>d@a!a!<@eV+;G%sM?gvQc5j}?<@ zOcQCwVKsxM(u~Eb2Px7_$7%(s(oDl@4$Y)#FPSuHb|l_IR$OWJ#p(y?((HrvFtm_n z4p!S{#@Lz-8x?m(tAzs0JC`=q%at3L0ZCCz1+>6qEl zw8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ts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/util.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/util.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..92a16e7c3636653bff4797adddfee14ffc1637fe GIT binary patch literal 395 zcmdn+IZ3VHe-eu}wf?qJiUnIiQWqz4o-qt z5y44CaI%|NaF&ALBDncO7pK~x2>vXk*v039U43)m*`D*BbH498*PeLxW##$E{?*fi z@#w>M<3C<5A9?cFTAuuKcW$BabUtm2$$f!Nl2@y^)qpX!$cz$}^8>ABO-p8m z$O|`>Ie;|;E&8A@xXddsfpFn^-K{xguP{@(>3Uby!RJ}E0O3ltQm+)QIsdAo*1c!V zqQ9f*(8ufM3VT6UXNAZC%z&)p2v!1Gq_V0Lz-h)XQ7GGzYQAm35?ZQbiI<}m1=IoE0$_%6h5CuhLw;3}Dx^Z!=i=Z2~59?^Soc6T z?h@84=$E;%dq|G=8}dGYe#3KEuR*_I-~0%h?N4NwW(p z0$ZiIM&>YPw=_3)-zLq=zz%6{ypNsId_dkK*d@)|Sa)D|Q|2sYPgAD9 zd#^Ot{XBlGd!*@Gz5ZW45Kd<7oD<9EPTJYjL^5HSzGNyh9y^mtIO*6aJL`-mv*%KF M#>wQ<@nqJRzxSLOK^cn+RH(iUNWP7~rfuA)ufF3OHq2YHF62W~rH)W@e>1 zH0O|}O%7$5mDyl+Dl_wR%0{)*?_SFC)cNE0S&#kqzHircUsu=Vy}xVkwbx$jyVhR& zVa2BR(^@3WEADon%$kq9qEn@>4c<5Ksx6;yo?0~bg)z?rgjDjpS`gs<|NjdpH!-`Y zI5&S(u;;B1F~14(ydS|Ut;}+bJg+t=Z#m9G4&G**9S|TRHfrH{9YCLB3RXI(a~y?p ztAlqh&N3(^BmTyfRBOyRmQ!W7!HNduCE_GIco{f(4&E&|cRP4%a9(uq4&r>~;GM-O z--Meduef1z&ua_%KKI5-0ab@1aBg<+7T_#~GB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wq1Vg{9!k%rIw1BR{CRoEjSK(}|m7uF|BvujVDm3P1(9e}IUjc`8(NlW$J~7RlNoI} zrYrE1Ch~DR!^!*(x&{1!6--p!0*qM;Q?~$PHpJ8q(c73|n0oRs1Zyr=*z zhQy_&_b zWBSBhDyWQCJt<~TVp9L4zZ4eY)ryNt>X$y)XG5j+Oo)r^-#3m17kBZr(tLg6l6$2m z_$WOoCcS4uIsWCcogR~#?n_VM5>irzXMgc#1bP1t$%>6f literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/voting.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosFramework/voting.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..0725e3d5516943122d966cdce14e497116438873 GIT binary patch literal 35812 zcmbuId7RJH{>ML-7}>I~VK6jgmo>|n`O3sBX2x3i8Z%#Jn9Xb`OSvuLD$-T$|@7()%JpZ_Po^w8*&pDrS&ij47-|w8B z-^5?L!pynpKm7h=!MleJA2}BOO~q+7Mr`_Z?t8EP656?1dC#i@rM&nj&&|%s&P&cnnvxSxr8ZFFU8tnQIyF77F(|KMEzfHR%4<>A^V)*)=He`K@VeFW zy#Ao-+lh0?!TT2Htb>={!1HE-YPWqu&+87#i^du3;4Q>?!oe$jt>@K-(z4}nhFMSW zN~>!eiWLCmO~#oGWuzI>l(_=DvZ~IGSiL}bgK&m8cmbSD2X7kA94ISWUdbK51o}Dd z#`+l4y&S{&9$fpW6tc8uB{5Zr{; zlM**U8Fgb#cue7-ykR)EIe0s84uZoRd0(36ErsCj>@iBLGNnRtiYIt=>1(myfYN2c znsrd}@^l{Bc+aaJNY2fe;?E7_WoH!Rr)OvR^V9f0Y1tX6s*0{uF&I3DdGj}OUATH- zJA>I2Q_o;0Fq>iO`Q|8QPi|Jf%>nAm1pV%%V$B6TvWH+j0OjT2ODZ-)q-mdh1! z)80`7X)dL{_O#wmnvJlU!nM+@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m)FYnd8_%B6uB@T&< z^!cKEQRTe)mr6wpO7KNQjqoS<65|F9HEq?WqL?9rlAIIIb~i0A&Zn4I&t8c&XmVh}hV;B!55O#hT0V&lg%5k`x^m>%SyKB*n!< zM^^9}7F|O`KW-r@I>zUZ@g+q>MI=S|X}YS{=u+jrnE0d-e&29kWKmrMA`%B&b-BQW z@hJTE=6G7Zs1UD-ulT?Bk4qR5bMapjd^bh&$P#=}6}?d3pWQmQda<$6Uf5+9a>XV1 z%^k-?Bt;IO@p4|v|KmYkUYohKO5P2=%X;q86EA*510sg{{IR~_NtZ6dZ|?YN@5Vp9 a+TvnE5*Z1X288VgfBzw|k){VqdH)6iD)^`X literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/any.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/any.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..d2293fad0742c725c4e7743513ba300cce592adb GIT binary patch literal 1289 zcma*kJ4?f06o>JXr1e&;STDFpC&9tRI=F}zBx;9(mkbI*bx_2?Q4}|4S3iS87xe>( zsAv}}NEFC(z`RmA8uDO1@AKL0+=g8+b<5 zqhs|7DmAUHXm)$pruk36Fq?`p-tp)6N=UJh*_DtODJn@}=0ei`LR_NpCqA;6@@ANI$tJ8CNyBJB`v|q?SL^rL0Y7&nJJw|IzuApf{ z*paAd`sLsci|rDB{4np9GBD0evrRBL^A2D-}F{&#(AH6p%-|Z z=q~I)Ijy_UgL+PM7p|io65WLw>JiahI2}oSY#))cL?6LxRD-ai>dUprxwi0sh3{#_ zux-w>A|C-CM|+{R5e!!La}U literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/big_vector.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/big_vector.mvsm new file mode 100644 index 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G6VJdxw|eE_1JUKAY5j#Ar6bd4Ey2;z!&w zF0eEYVx0xOjl{37w~<_C*%kCQa+53Hjj6YhE0}#S^)?cpr(O^x#G3)S5#upE4$l@X z%=&^QrAB8)yk7GP&F%Li z$AFDKI@9B5I*xnF`981kJ()vquNgbD0Q8oef;9vzTjsW|wb>roH-G6Me?yKz?#eal82e~ghcYo z$M5ULFsg;T!Z>bpmAlzqpKTt)tZ}wa#a~2R0{Y%LbD0aR6 zmEZBNfp=AMN0{XSzd#$A!~J~$osYS9A zcOSSXZJCF4=N5r(FK1?fZm%4yE}+}XnLR*13Fc$n4f;v&45|0Qw6-$&zecimhg=b} z;zjiPo}bI0J0XiwM*J%|j3Fi9TgfWiCxBm|oy=wdNx$L}5Bi^>EAiJt0(mjp~U`Yu~=_dwUf)>%ab#*f${E61ZV%4$Qx;bjM zOD<-mgPUEhoZTTRaoSZQn0@<0bR_n8rT#Cxi;TJk31pSolc|C4jUIqI1iV(tGl&hK zSBf)V1-(+1W4!@-r8sjf=#}yg)@INvWh&Mdu#U2f8%LRa0g0FKJ4T&{1j=|Fy~$|* zGIqf22K)jkX=R0_Bgd3P#*S`c8KDVfV@iu6;o?al-l#*9LS4od==?j+nGS}6h#1B|P&qs5Y*xYO2apYhWgs|A;)DN(_OsDzFTBn7zLJaPO}BLN z9KyR5@c#=YE46xDOg7@(a&50#IVfkKBk;K?Sh5KET?W$JN?^y*rY{GiSzm>QrA=QB zO0zu=kCrxlnUdzy47^#|^yQE=8_RHRY15a((mX4`m8DHzj!5$`hGR>cz8sb2X9VAt zHhnoJ&3q9GmNtDkF3qE?{oT^0FVoV@Ex@#;OmNtDEO7mk4((C=0zKo=q ME5V|r@BCZx3(4_3AOHXW literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/capability.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/capability.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..b0ed6884baddf34e7e25669b05596ed7154e8fb0 GIT binary patch literal 7719 zcmb7|YfRN;9LJw?4vHK_P_6>TEpKDrouG?bH zt+kvlbYvHU)<(l+nQYyCL9JK9CQDL7S)gRSv2}qy&+^}T)%Q7WpEvIF{GR9kJHOxW z|NIH=s83y&zr5^)qkFolk5zRRUot%>{}`>V3l$w6xVU1tBh{Ff!Ds&epD*}yVi0(X-qdb zC!z=W1MsJ`#rEur?QM^>sg(4gUx4)J&VPz7dZ4AfHMV!JT6mE~LtwKh)44gzm?uCN z;2NxY&}CAB)c_7bGqQ~-2IoYUATNUi5?O}+03@8q^(?9Zr$i1R{s20W{a9B)C-OAb zb#PEm6;qMm^MzG?^q{>5e&2qj_Mx4%Q4cEfYpjdb3@j>Lt>kgUU%;i+Ch%_Az_OGl zvF?D*tGE9Q8FQF;_M|hVc^S*v$jFARybhQnpXhb0w;@%U&taW`xzcRF zYJxOrzKhij4ynIfV9YgeF7)fjKS3bCjZ+oi1mYwlT;@|On!AvCY>%rw^3V#vm(#9?Xr=jxdp2kbo+Sw>-IT8ypy2YXFt|q(9^#S>mAV3zw4f<8|@>^ z^Pn5;3f5K7jb_aopxfsH))?sa>BTw+x_y@3XG|HS%irCaD`CDg16Y}mAV#&rD?5la44oX^Nr~P=h1N%`4jNFjE;W9Pa)yaG037DV7pO1ZW41Q z8FY(Va}GH4PG6BRpMk^G^>ef@z~SmTfc6dOtLqi45gXLy>YBmjZ2`<^X>E$hTk-FN zod%bSZYEK)K<73GD;M)rdtyIMj(`ykQ1v{~2 zU34S954tK}!a54NDqqC1wtlG}!TJ#NOTG7=sbA`|>BltCm41_$KZCCHFR^|EUFqLr zT?1X|wVZJq=t{R{J?Khbjz43q`_ylNBxxJs#Sy oscKVXd$hVH65Uv{wYtJ*^8Wk(p{gz6P{sCWxNcKzq}G_f0k3_L#{d8T literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/comparator.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/comparator.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..61811dee393020c7ab9cd38e6e6b980f4f90d52a GIT binary patch literal 4985 zcma*qSx8h-9LMo{XLQuDv;-}!%oZz`_I-D<(I_KRi-^LkCX*~fZ6hLz3R)P-2a(5bC2BHl+anc_iOzA3C-Ku z5>6+sXgQMcx;}ejcTz)o*O%0WU3r#e6_QQ=`?LLPsy1#et1hdps>U{nv2Dz1H}h;I zKY_kdq#nA!Ygt8P+a+phF|33<5tX5JwMs8VE~m)qit_bRuR?~*Y`>XZx_U=#s79@@ z2Y;Aif3M)~n%nq$WX0&MIfFY#w)|y|qRx{?O6N0srEFr}bBd7iKI#QUO6h!ipOhb& z_no4o>@q7ySXQ)@?MNTe#fGkgZ8Fr|y;cRSA$RxM9^?Uv_NEURt8TIpoS{X89j9zc z6gLcE$1D5L7q%5^w<{aZ`Uw>C_iU&u)}SjX_V*Q)p-ttr>(w=NY{?z+|2t0Vk~1uE znR@)W#N9e?SmQleIr<1T;+~Q|g7v6pq>rHUJ@pa%!MtwLNALrR^XK9SI^SL&!9?aI zkv@XX{h^Pbxtp^nMjqBtsHxQco#oGB1bXq|8N`^BFH?05yktN$Gsf zL@5U`ubz{fB;{`8KI$Xo0n|b2E9GX?Axf6ADlAi^bpCVnlkzSzA5ecO8&HpEfRuHp z$CN7NwXhs0rSnfJP0Cly?4UtXzC(Sa!BTdj-qH{$TTsWjmxfB2j7p<)DPvHBX_%Cr zupBPsG-NJ~kTMTdNEuSjMFlBS%1J1*OIcFxMD3+)DL0_@(MT!RhUF+JFC(wfXen=? zZqgVj>rmHetd!?a7igT6X60KnUdl#PGfj}P71co#rF@BMp-ECY&r6e~w0Q!HrYTZ> zW@SHes+7*^)1^#hUIxvOGTVGcnki)_DvM@G={$kXmU0>MN-0Omd8jf9Na?JeE9Eif zouIi=?na%Ypp?$)`BFN+ri+Kg-n^G5oA-FzR~@R^QYl|#Q^0BF0`oYio}Z@!1Ee2s zjm#(g(7FIsNcy359%?@6_eQh2ndxHrC$LsS-ELSLxZPafX2ZS#f0EuXBfTCspEwE? zM|#5|P(IQdW>z;dT?{RUZY9?nwhg??T;OKIP65x7-Y_FClD@;PqHdGkuuG^bq&Lj0 iZf08E$l&57fdXE8@{59jl3=;vXrv&JyW)Rcj~+Q^qg~^J6>mdWv^B`t@e3`_Z=(Q?8sJrY51vo;PPj; z|GT%R%^1@~4*mCYnitmAgWUXbK9gGw(4H8a$1K{Z5hV{$#~~)3VJ^tkho>XP%#h>w z>hxLIT%DE_Ey6a*n5e$OIq<>Gm797+y-`HUXVg2nQtqQZDa7&PJjN%MB{wjIOIyoj z LnHuzmMveIeC`Z9$ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/crypto_algebra.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/crypto_algebra.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..cd60b98c64d50c864808f2656f3b01bbc7b27dc0 GIT binary patch literal 16454 zcmb7~d2m+M8HdmPB7`K61OkBw$dZL61tfxu;0OV-Ctp!9{g0e_JmX2jB``8W|wBihXPRN%T|LO1K&OHBQp8MW&&w1ao z+%Ff$4xQS1)~U#7;}Xg$_XQhs06g>mFE6}c>a5Ar zCi(M<#uesI&BMPaLLY5l%t`RP9HpK|yI@r%Rv|rruKMxCU5wcZ_NuS-y{PBFlkfEo z)+O*s^FoaoB+Z7rP$PIun*Szd1ZF*H-mWnnUTImlG0VYWs8*nrfzO+%25TkSZ*A0B z%G`$aJ1~Y+RPqtT|Jtz9>=9v1PtYS}&1XUP|8rPE@Hhd04R6czY@k${~ znt_-O^G6~@&=(w1yB}II=+qv7HPD)Fshx^C2y8Lx;ab|nnBRcIM6w)h1vo4Y2Alw87x&LhOe1BT(Bo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q8QZ2fq9MC-GRgQb`jd* zYE>Q|m!d5Ln@6$uPdf$ zErV9l1D9;C>H52jcI8or8Se=h`H2K$V!g30$^DtMS%?!`5gW+WKl$ZjCmeZL(_Zzjeq1&ldFG zL+u^%-17nU0kEr+?2{XakGFRj!aS@App)L3Q$WvDC0MgT&s5f20D8eq#aak@ryhq@ z2Bw|trbM!=54fbxvv|*eL+bQJORiRB>hwn&Xw{I~lcQP)Q_-^^r1s#b?ih~k2QII@ z?3Dd%LH-I3dy4~T2SLwmpI{xfL2DCU{!82u^b^paX0Q9Qdd;tpuY*&CgtcNgK~HiE zu$F_a5NoaiT_J0*HiNDZYwiSHA>*-jfv%8rtoOjg%4B$zv?&9JWGF{l2|5|xz*=R4 z*6~01)^N`bX!MiQk4lT(-0=Z$d2#ZEL*n`Q5gdMli9%}%`rBMIRx*Zfwm+8l%2 z7HlrbCZ{0Iw9%!x5oRJP{Zpi_B1)^0HI^6{q`g@1uV-(E+%0lIH*VcoW-nI!YZUko|hiBW` zE;8srdf>S2HNC4mfp+pyhZ!%Zaf*L%)-eC`nL{#CGE)W*OBv{yDEqg;{*>(8>~>OPB~mXEII${p9gs@IZm@XZ?kpPN7Idv?yl%!Yx1!4ZfVffyfPWKBs; zDotl#VPKdpm*D{{~ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/ed25519.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/ed25519.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..497097453a3b4410000692f40828d4a2c477743d GIT binary patch literal 5835 zcmb7|ZA_JA7{{;Y@N(dsBT$f;Bf^-Qxn4#aAM8^}XUGaN4lFIl2|Nd<$AAF0C}L@D zxYf6oIkgwtdf7Cs1>wt@HiHkXOjovIl`or#(`p(~IokT&Yp43u|K@DJFYNbR&vRYZ zeLeU6up;ur?ng4MR}XzVd~(65w-yhNRTL&#I*NumM$2A1y8p&c% z-a(whE}%4<^36Ix*I)?idB~A5_lC`mfR1?v>j$_-rxcEv-2@iowfFa>dsPW4aThw@ zB06{qaUJOXF2~A%u51_9CeZa-kJSmeva-vt4nV#%cVUe}Sel!$_CtX*vv)6)=I6xw z5+c$(iuDzEl)iPYSvLehvugh1XgyBNO||v4Df>yxL2$j24?K?eoeM3^D_GN@m&&Uy z-u2vHt9KQeCBb(L9>q;N-)9W=A&!8~Z3or|pda`k)-ljyFp6~m^ccK=6=JOQ82pIo zGS_2p95cYwW01YO9)l|4Edo6TF|5VlQKl_uyPfL!BHV-f9t1fHtE$x~oI~6bB{~reX@(l4_2fbRdF+EaR zbpv|~SWwWNNqX&v&!Ru)E};&x5aWnnfNt$ctVz(V-G_AnbZf)&&5A*{_7~!nV0!d+ zpvdecuprc(QA>Lp;&vzd>{QNh6g zeBa=|;m$apEA(q*Z;9Cv;Dz72c8yx;A7Os%Y$jN~7A6rdg07o0FT1dM>kF5fRe}=jddRMacC#jBv@1?KUQgW4rbH9pYeZ(Sv0U{f!RFpZQ$*= zHNY>3$s`V!QEl+}xcCNb0%oyZ&!S(1S)}`iyTf&~-{%Xa9I+Dk??>nAu2eduR`(L* zyMgw~(yYVV=z>dgE7o?WJu}z4Zo$Ryky^lBoIx%M+a$$?*<7VcWy$D{9yA^SplYRPd3GpY; zkL%1S(0v%g`W381CRWV8f2-U3efn@4;vG)*>BB0-R?vw#Gv&hOmBy0~H9gQ+mt5Ym z^uGAYWTO7zxLIkUzOM0}=9Z>-vazKhxpZZ7JdyL?zb0yz#T(+u`g?P&j4SW2uT8qE R|B*vBHyilhP%d_0e*w15!@>Xn literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/fixed_point64.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/fixed_point64.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..c9fe6a08a877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~ zhBX~Lm!7~{1ev%q@5U&8u5_*v#! ztQWw~GGD{m2!58i0qalTXPL{eO2N-EcVN8-ewMitYZv%g<_B1N!Ot>xW93FpO literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math64.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math64.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..472eaad34cf5fc8c7a3ffb67c71e4b0fb4ed2b9f GIT binary patch literal 11011 zcma)>X;4;W7>3XHu`eztN@56#Ag(Mbf?#HfNHI_tC~lvhid#U4V47(^YARP`$;zdi zX&Q6fQk;HRnkZ?S&1hK~n&py~Xo^!pir96U&fo6i%=Pc``OZ1-Iq&^G5AKxj8aC~# zshfIp;__6l(^0`!=hvNmx+E-Y{|lRIlXh&&Gz=pL9Poet9NtClvbl*v3}3@=i<((Z z!^j20>2NDI4{riEW+-zSmdi9fq9Ws!T#k4Kj9`7aOYmMc3(Ff@hP51=(p-x53V2A< zx>8SRuBBcDcuBJws|LKK`3}~*;3LhqvDSmHG&f;w20v+Tz}g7@(p-mC2?5fyo@YC0 zen!2|p}jN@VbwtgY1U(X2_2<*80!cGN%J_?3FsuvV_087XK5b5Itaniw4SGp&!fr1 zFz$ij;aIFb&}O_A@G5-qrGiprKf?6%#4ax>(RKi4M=(DXd4K&7V?lrYL$QW~{`ym~ zMu7hMl?ZwT60nAV-hX4Tib3zHxmbmuchw}UBG9|4_3L_9t*72m z(7UR&_JQ(yI!nECp!eVNSQkL=zdvF%fZl&kVHNt=*;VggHi6z%?_o8A-c=u9wSwMN zTd?j!7x_HzV*LqSrFj!8gL@B=W*4lk@R&41vARPyX@-~Pqn!~V?pocUEV#PtYG$&(Cfe2|%$8tkYX->s*K`&`ez?uk=(lmd02K1KZBCI7~ zV*}law%t^1q|FYzo#18X3_qAwV>@`wDkvgAWFxAk)qS@1{E94s&Y+!#<~e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 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math_fixed.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math_fixed.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..57fc382a09ea3197d2ceb8675cc62fd21f7cb3e4 GIT binary patch literal 9184 zcma*rX;4*V9LMqJa=Eg|B8rGxDX5611%`=Bnu#T%C?b+GO6(x3h=EohMX8yU3Q4(? zwoJH{LRpxaiCN8DSX?d9fvCN-um`*;myGv?SuXNTW-V|W0J^5|M$=4U65LulaiHNo|$1hjmZ;p z1MS9iA!DP_4&^7cy0&CW_qFD)ujCt|y|F-_!|SzcUJm|0k=e&8thI5~=o$};76 zFCSz4$g3o?AT_rzL;plKW`|ny=jG&P$-m~RmoeAL`yZW>UsRZ_KEU(v<>XPCx*)%( zBtrRUUt`A5zdlm=eC)jc{1D|=W7m_tJXHQIcR4VoJ#i1Kxv%jVSCGDIYEY|5-!&^y zt4QB9&ZF$YUBkQv(s#{H)MwOAe)dMxC*&dJ22?9~N%=kM40%hr3w4&-OX>XWK2qLh zo`bXRE9EVu57JLc=gs3UWk2SHQ3ojppaxNZl>JfR)KN<3lF&)Y-OSrhfl@lxz0Oje zV%|9llJX*|jk-vA9(93&rF1U0U8S_MF8EM4Dg9Bw)Llwnlppnw(z!DAl(LL@RdkP( zAv`z+(7jRypaxPeDV-0b-cn{UFONc`EJn?zP$^?kiPT5Rr%+|oSIVWR71U44#i%6| zCgtm>I_fXwDpW0nOPP- z{5BRX%DrT$p+?-exr#+<&u7* znSd%G{YJA9)kOM@<^|L)(r+}?sAke{G&fMUNx#wjiMmdn@_61w+1P*4?>={sf02Io zxrXv$rhfPN&YFjG;n2@?Hztc*xuUXhIhN%_$s@1_vzPQ0wE^`7=_~4O)HkHBs20?( zl2Y6(b!-`v$ho*>^0qxM$C%ymbx3w$x8yzs%aTv!$!K5zLIV=B6_@ zTFp&n<`dRlT#&wAuJF0qtj{K|tQOQ&($|agcQ(9_<#JRV1xmRL^)hvq(%RAAKzdJQHb;FOxo|1R^Ds%U z9w=^ljhu!{BwL|cOfpcJ)>P|GQFsTi!5S-NEvk|9`cQ+~O?rK>S?dky^?{q%v?skj z{KjwgLF)D4GBOaU*N211&PW%A&h#@Tm0UTeX}EOK=QIzMZ%KPe<~(&ymjIU$TO9JN z*5KAygQav%)#tySd7DU||81y`NT2`BsI8>W|9hzSNuU3Hs4q#M|F2L7Nk1Rm|-ekM*r<&%CU#-ZkuekOj3Y9jqi{1~;9TzDp;c9DK2zKhyV`k7dX mY9?d1$4!p38BhLCNlqCO>1KRm;*(+$#>d6aNQp_FV$9#rB+yj= literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math_fixed64.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/math_fixed64.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..3e9b19653f59b840ab28b83ae3c0bdda0aaa1d6e GIT binary patch literal 10747 zcma*tX>d(v9LMqJCXz@bu_bnj*eMdkzKf-H6+3aWNrZ$XwxC22CibmbTSr?@vD-+esy-gD0V-+RxK-1Hu`->sVxo)F2_O3ykb;j2TD{`oDh;-_g$0xQN*Ji80Zk4NXB~a>dG??#6hN zaX2O_>w_y~S>ve}b^;^GA)i7AR1~>M*&a2D+@)NN+C~MWT!q?09#W1+?Ijmp(mjs+ z6LRIKKE>sepLb;Zh*)P-YErT~5#RV2vy}?QOdOMx7?YT){=+Zei{vpTX+n%#zNW7+ zb;&z9X0$UtFgU)jmjYXF1F9QeiyG{y^W;b#amF>__8bnB@>kZoO(mqfhsvjtQrUlt$51DzmXvEz>!`Mri%`p{ zj+AM9f={E5rJRBKoa#zB9hFY?q@0V&r20}WKrN+UDd(Z)Q;3waP#M%fO8dK4Ln*Ua zZx=O^at~@Rg-W>_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/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/pool_u64.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/pool_u64.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..d9f3a16f1f3a000b1782553466a1e5c3746ae347 GIT binary patch literal 20837 zcmbW9d2m(b8Hdl!PJj?FKmtJsOW1de2&e?O!9bELS%e^X3CTr*$qi(YO~9g}5U5l{ zaBHojg^CqBgA_NA4zyCGRf~eiqELhpunfC_);=G}anL{d`>xJBGtT5W?^(X@obP?# zb1s|Cb)UWJ+nDT+x?LXs#KNgb=Yos>`u7V9Cl1KGC-FBq4^G<|?l`-_v1bIl#3+<0OdH?Fv*vN8~?wmkOd*=z$e3(P64sxA%QYq{M> zw#fx&h#s|ecq!nKQ?(OT9|)7Cdl@68nLs>q!K0+j7va&4pOY zAXb_MShdhtn(inyk>*C?ZH1=Ne67KZljaX|OPYI#`31yF^AOf4XfDkISO=knG|ynw z!41+pjrDIxkmiS21Gs$?rI~=$50a#Lm6-i8+ep*hds}Jd6K^UcOEZ8~0qvw&j8y_R zN^=C(IA|};bS$&?4$@qRwE|M4xuC)9C{6dt&{>+lCFTa`BF)#ZHbSa2U&ZaI zI2a_&RIFUMNt*87)1>(*@oM2_X)eZE3xlQk4A#qVi!^6q{SJmma~IZb7%I&jSbJcY zG(W@o3T~C=QLNK&n>06JeG9is^D0&p$<%OZx_8_tX?7-FAMi@kjX7GH?sLf^wc6Xs zagKu%W|cahKs^ObiYrQkRsN##ike`x%0Vx%fu}S3a3Xb9cnjjKptHi;vBrYV3bV1s zLAbnf#+(c~e{79)4_NHJeHW$-Se7U0s9p%^8t1UVL}*-HQC(E#zcxH-T#E3^AdI4; zzmj(&UIm+CW*6R5-8f+~6Pvgnsso*eyJw`cYj-?#c6}+8@#$)lT}NTXg3hjunFKB6XhvW~ zLMv&yXQcD+Lgw*g(0RBY>pswVcsbTA(0RBq7lO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S?V~5qp5$0yPUW z7p%%)w%SrV48=w4`#zV#FKOf)t47C{{KF{ar4*z^5dJmylo$XUN;-_Al&-+=7-+Rn;+kVG%38NaCGsY k!NZF08a#Z^ogSw}@PG6hP*m9O&e6q%qxugWHq>$c4crUDW&i*H literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/smart_table.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/smart_table.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..d7384e537428d43046adfa18741f20bf1986cadc GIT binary patch literal 41858 zcmbWAd03X!)`wq^K|m9y6o&+H#*{(8IT2nJ2T%mXkx*WhL?9Uy6)iP2%SLTJRyLYL zrr9Y^os?|)qSBL^L*~$+?V(pJ%VNp5g5sd`I~5 zHq(ye7r0u`WR!B}N2!Jgq@_U2(cQcztnFz)wcZ#hL;R z+dUPnzyy`sJq>F*1gY(*Mp_EWdj)5=gBKL+@q~ej*Bht5gZCQFUI%YLU5_UVTIfYT z(bVI48XR``Gic9(-r>(-ZGbv~m&d!>{7tA^jXu*?rQG-MK7hc={GtkMt<20 zwN7VP{|jb|3!~!`5?}f3aLwAy)zt@1+&m)hOnB_923tF3)lR&1e!{d79sdUL(yYOH2NI;Y3(MF& zr1=`w1xS?UCs-$-r!@UI=Kj!2nt@nB&|8{yumYfuG=F0qe}}$KrdfJFX|}+Mg#Pll zS8>cE$hp#_8G_Xeywd!Zn9VT$%_6K~7$wb2tjGwmD`{@P+ytYg`6$+A$d=|7tQR0h znh#@bg)!2!b;ej}9wXjokSopKuo|+L#!2&6%zwjpX*MQa6PO^)BgAWpIZ>KBG2etq zPUb<($xfzOdY&}O7=8BXSS6W7T!>v@ATmtoxoMbeyybvw+G=G|ELL9vs$0kc$^cVTUV8>P7l>rR+0 z%}T5DI}OLr*s$I!!?1P=YF$!K|?`&0Q?Q^2u5Re)Lu0raQJ zR7+(s;x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q z=)N?E(bExhUwSZB7U;foHr6=M&%_ur53ZG4l!$dbbdzUC5yxj1=)QC*mifs<-Ip%L zDgoV>o`F>ex-V@^vvmDT%w1QmwE9VxIqaeNpr3T9###dUNf(=F=qFul@}-}2@nsbg#QRRxIe}Y_7%X2D&TW5vvpEuDDrp z91N6u$%{1v9B!1>@=oh1aHwBSqkRRsemR46)&zB{U(Tamg#YT5%X&Pg9SKe!gZCmX z0J0Rl6Y<8Gz|x$Abv@|hcs$lb(8;k~Q=J?a5N|H%)3yfd4bZ3U zPOM#^Pur)kegS>r9L4$xbp81z*3Y2pPrLL`xtH4XVlDw)sRm$$fIh*E*$Q-}YD}|q zU8x!?9vmLz>D+^K5F7@1ELt4sK|TO01ss3%Bpo%w=nlVnG9B**aCPe;g? zwC+ND9Oz$7Q~jdzc;5ooP&sPu#=8&nx%B|nW1!D1yRLfrT0uOsReJhbj%93p7B0c+ z&Sz!xS-2f@2k5i#Rjl2h&%(E`-UEFWzJOH=`rP^hD}XK1=T;C_2R-mWu=2v3sE|59qvET^~^=4#d=Xpnr%pMou`SV`}W#(k01$wUX zrVP*WrlgI_^X8_H&SsZ-$9uCf^HNhrrlh84j|=iN^Llerz23CE5h=NO19MV`d9(9I zr;qpgd0KkYGsdJ0PfyFsPRSa~fBrxJw~nXHU;lS_W(vxXEbr(cnZwiaMtZYSy&2j5 Gp8o(>@{!H} literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/smart_vector.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/smart_vector.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..a2456eabed6bea422a8deaecc8c5d87a46313858 GIT binary patch literal 33968 zcmb82d3;Uhy2n=rk`N*iLlR_?5Hm5Ank6w*LJ~FG4K`9k(g>}o&bhZ*w5ru}wdR9+ zTf@;o)lfZ(Ql+%qnraHdDThO~6|@KEyK?fLd;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2)c1j!kP@aaZbT11>HCcu&xK)4()Ex z?XaC1tq0u>JFuPu-436`dLDE;w9QzzLmLI7Wb3j~pc|*Hl5U)Kp1N_`(8!VVw4sqJ zO&c1crD;QBj5KWz7%NSCI`XBNKe#^&qroR(yHl#YlOF7;gaEO;0wA!R9 zQuD144sPhmZ4M8-ZFG5+Vs|` zXm1&LGQsREL+7Vmcb%WMo;pA66OEJewD*xhY1;e9cxl@E$OLKH`$&;A?R}(Jnzp-N zCr#UJCQ0*?!Bae0nmaL1gF|b$i$hcc4)4h4q18gb*Q^4o4lM-fiPn{|a3Zo)ec%D) zddP@InpQN$qmjn=nwa{~GCr^xMmF;$TVpKT7;loFX~W+DIq{}wV@pFU9B)d5%`D|J zZRAs1fgfIIs=0lH`2{%C^(5LUaC-H98u2UeuZ}dTIh@D)70itFKUw$k7OC32#WT82 z$wjD(jjlswCtnrq0f$=bMcbED<$An_wjZ3nhxr!qJ2S3axbLyfflmKlur7d3{{gH& zL8t#EtjnO&{{+?*aQIiZI+Z&-IMn}9v{gw})<1#P0#5bcgt*y^E9<`n>s8S8e;sQ( z==$%#+6B7)Z(;2LUH?w3z2I;G8pT&;Q^BGBH=<2Ts%R-^mS)se{;Zj&$S$*HExs|iS L6*cquozMFleuaRQ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/table.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/table.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..8bd26fdcdac18264863e0235b5ad067a9abcbd33 GIT binary patch literal 7658 zcma)>ZA{ix7>Ccp0|>}lya>56TN4nn7nTXM7NgZfYp9hhwH4X}wpbPc6P!RRTVkm( z$mLqrw5Ik&G$y^RDKo3Jwdq2QmoH?rDOQ`=TCKY7im(0d|90`|+Ih~oU(Wge50kSe zKOR1}xUzS{mN&~XqlF_wYj#c4l%?eNGg~p1z0yh^xtf$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dlib/table_with_length.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosStdlib/table_with_length.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..6a8d3f6dac3769ab3f6f8ac231173de468482083 GIT binary patch literal 7288 zcma)=e@xVM7{@=yaf0FrC}f1ooWF)OSj(m0*u-&^f?9Aotrn4-;kabk;g5#Z%B``r z(zT^6mr9`-*tAHTX>Dn3twy&tN}y7y189Q~Sgp(vtWh6SiQyFICWG<{aEc&9t1jeR z5DYJriWUO>LOEEu5DfjZ#_DmWqE7RAV{DspOYlm)ySXl|+$DGsa4xJDq8@Pr1mx=0 zVl_dEG#|oBKv0^Sv9>{~G^1FLKuDU;VeNr&CUYNVx-{FcUWW0~+>dntCP;G!Rx4zf z%$=AMO{Ra&ur$5(3K$Z9%Q)wX!O$xuXp2Di$}+4%TcSr(kpSiCh%n?*I^gp z^Pua0C)Qrj_5Tvq0nqjT1Xdduf)=JZw-5|jC`Ky*orR@X%Y0B<7OGJ11WOj0@HT-d z3;PkcXv zE(mG$vGsM$@r0Tk>A0B?2+p2)vy$f^7Bg&JzV5R{xQl&Y*^wn!6`(VGJ60v=49~-= z0zGGv@1*C%x+ps={ENNcCx(wMSa~N}qG=Ie!gB)p&V2whqH2bgy;Tn^95p$}^ z^v`*%G_R+JXF{Gd^Zd~ou9N1CScQ-;%`~hcm?q6+B^%m!?<9^lVA!YI(GG&%r{BUl z?t|K<@YC?AeFa4|<|}f^{DB zL^+Ao2YR9;zg_>v$>Ic_3wrik;+w;mdiG54@j%a>=~(l@FrwSjoqG)omD+*U3A$3> z#yaIqTcy5(dIo#}$od;X{KdyMnPZr`Qvbxd3c6B%!}#rq1;} zm|y$2(j37W1wCI5dyDTjY%jaGw%QGb71)FJ0_YWZ73;7MYO8||)T3aT-932cAYi$i z`yTNJu-wgYXm%mcdH9`(8JIc`VXQ3ByTK4KvoZBOfyjc+99=kcFHlhN|LI?ym#nvnN7-ARj6He}1HF#@$U};uk-3z+2?!#IK zy0eyG)r0P=GAwWF&MNis=vduZTQRqTK07{!^%UqHY{hy8bPp!5o(0`mJy@TC?yL{7 z&V%l(eyjn|w-Mb~gP?CCl69wVBd!o{4D@ZpWvriJvaHXc|6=NU3tt@};65<2Vr8^8 mviy$d+JO7_kBXJ6R+Oi>%t%>Pb)>9(ZEa-D(wbVa$!aq_(0`rbb8v*-6d@4MVpDPN>avDA2!431{!nqDs7`p(PG z+0L~>#^sII6HzmwkiV9yO(d71W_%&G2$~bBexj6}OIjuAf$G($=!Y5BaB-LfQX@Bc z4R(jnuWysuy@!9~J!Fx8pbV(slz3h&>mW5~zm3R`@N&vMOoDD8at{+wtSw@0k5J3Q7SAo>jrCO>Rg?kH+Q>J`&{=$1!dvnn5%w&w@n}UP`%qX2=K!B0h6)BxHt$!ln^10zqRS=p*_9 D&D{z& literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/property_map.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/property_map.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..f1b126ab69e109625b89d8730865af69f796af74 GIT binary patch literal 25540 zcmeI4d309A8HaCn0)d2tKoC%}5q3fnmMGf?d?W~23<-qw6ErNEgs=)y>IxLBO9jN; z0v)?)~PyGw*zJ zvwQKRvfd*)-hSn%-#t^+`kEu>omsi{fH!ACVNKSyB})_DoD$@Dvw;79^1qO%s+rTP z%4W`o_7MgAZ0cU_q=8hBx7EPH44076>}ceLQvjvoK?_5tLf36 zmkC}-2zNjQ&cf^kA(xlUSMD&pdHh0)pi|yB%vi zgh+EG)+z{<<~*z;&_J5cV;zP_X>P!J9~w&2w%$mZjbl772BM@Hh1CoiOYFKh?izJtVz&Znzr>8(!7>+}lryInh7 zjkpVRr;WMSgw>PQ#wL8w;FguoU{-@mR=$E)VM>?Mh|{3QSR-y#Ea;RxL%cXlJsAIm`3;22VQUAB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{lSe~e=6{V231IYzh~@->xUKa G&iOxk=06tz literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_coin_swap.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_coin_swap.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..32e7b130bd3b6e8ff60183f79d0ac2d04ed1a4d3 GIT binary patch literal 4957 zcmbW4U1(cn7{{M9O_Q#jTRV%h3T}+4D1Ki#^de18yVxYBc1fo=eOJ>1c59QEr0psq zj5%gSSU2^;-3U6rHb17gi8sOorA6t$>AGDA?xs2>eq0FK5cHSyh<85kvG6Oj=l4Hv z-simMdEXq$uith$y#CC5^wxbNzt7J68F^yw;>9b)S8jU$ofC5hzPUw2?u8Ki*H3s= zt+dlCnnG!`XsT1g`5yblKAq`>^*zlO`TT`UEuZOPq5MQq8ZJ z&>7IjzKHdk#q^IwMNUGKI`;0E$U%^ZHlO#fj)UgS;Vf8q-{UM7W9wRn&{I2mYG@3@XK-3b!X#!g@jKt#P~oN~IL zFOD5p70|}si!*ECy^iyNh4&fGyoGlbX9+CS_!^Ns*sqQu?8hM7Zk9V$X{zW|v{HEB(aqcxj?o(^7{?d4aH)G!g(dANBwIU{Q`=Qf}l?pq(5kuie$4u2LsL^f2ieOd$*APDj zz5dT*9S6Ps&-$i?8e1XK4fbpQI_wS56zGB7PGS?-Kd=n;5Li|5CB!#Duj12KZ-HLL zN#C^CUpBUh+z0kmydT?vSljX`$Etx05O@UImos+Vph)1UMkqk5nj!EqbeKZL8?Kcq zRWm#?Qt_(l;(wder%<2Q*qB$Sjh2eqyY@ByB1BAacw9ZVUBLVWI!w7zDtndMw3+lO zRf}fn#Bb|EsGHFdtnWat$zk8LIMc+~UN+XZm|#=9k;vWkn9VNgAx?ol#SGRi(5Kkv zo6@4z?F&}OS+IZX=djO1EYM^BnZzXs-WJ+cid+vt+QJ?9o4~Fuq%j|a;BBEmss_Q@ z!X6T{u*Qt@Ew%Agm1eYjy3iWltK>d{|8clDN$fOOEz2lx$+e&_%U`)=x7C|>!8awU zF3a9dk?j!hoV^~@iOQ|JcV@y^mlvSHzlSP@rDkO z9*}T{|1F?#R%qpbX{Jm#AcTkT}s zoZ(l#Z?j3bscc9(ouo4`=p^DfCuuTnGM{!tu6A;6zmqj}JC!xgmc*dDH7Z^HzvJma zC!T!Rq*Gf+HOV#q{6FL7v$;kp6VD|!hh?pQrEaFOeT_@bL;MkuZvRq-0R{$B3FqHj ri`?U1OvJPG&yaD49OLG5#_jb#jOlTD-9g8s-9&$Wz~oXHr&<063wl1x literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_event_store.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_event_store.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..1e725a49749d2c5fdb5a02cbf7953fa19c5607f3 GIT binary patch literal 13901 zcmb80dvH|c9frSLHwh#m3b}9zC8XRefg+4fDHgFxBkF)4FqjgT%_UXw>&V#xv`*+WjfXzP{&e_^FxF81kO_iZ#&K| zNReAE^Evk&aOr9v16b7_;;vnc(`fKE;%qW_FX6NqysQl8dV<=&aX1qpRhm1o4uVTl zbAE_*8kF}LjxSStML5L4>1*)H zaBeYpcjJT%-h()64Bi%;T?X#}&R-4Q8Jr}pbA~*F+1*JMxGZ(9XJW-bd0TM~7`#h3 z{j&9ZOK_SD-k)(!8N6$9oEr)1I086}4BqoNdkx+h9G9!NI~(T#$dr3HAlTfviBJrY0DO zg(6`!WIX!qkQ=F~s;mmu1)`z(mT}V<6Y$1`gWpeNTrFc3K~mb4)v(&V?Wk?wdgx2) zD|9Xg^m6nfGv;FI#a^^3`9L#Rgd<*j!beHBV=4AiUi0(+pZ!yW|*1bQ6$MCj%Py4L?-sJ6aVrECg*g*V0vvvEuSKMckoZ$fPaOOQM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ro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_transfers.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/AptosToken/token_transfers.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..b622ca11563450a4168938c2c4f193e63da92ab4 GIT binary patch literal 10873 zcmb7}X>3$g7>3Vu+9^<=&_Y?omPJ-&FCc;@WQd5+U<-l^!#JIiLYaYSML`;xilRU@ zECs~WU_x0cktT{Q31A=u5u&mMsRSWV7J&d&z!)L;T*&?FdpgPU@44T-=g$4^dC$2w zYTIAjoLO4?W$N;_+1Xv03Zie7aJ$1C$+tfq0gVt<^G7G4NvzJ<35ry4wREWdb-sR!d#V|j?x zG+vLTGfsC4Zy3%fh?Cbi1uG2t8cVR2ff`E%PNjuci?bKJvf@PU&YM>E@m;J^P}f+F zQ(@s%<9rA4vf>4vh?`*I)VY(Xmu7M9-Z%rHi5||FHpXOu@%jqGk=$@hUBfiw05pk( zL*e}S`hXbnLg#?T9i5-6&QOM24)MO=oaoz;BIWzjj2RC}j|UJ4=H|*#9HIUxNO*Kn z>I`vIPlT3_hY-!Ne@cRSp3Cunxj{ z782xRoq{zIeA0C9Q=&9O)Qdn9X->e(hNjZ=V|@fIq&W|3DYTTPTQgajb=0eeR?@7+ z`Vm@7^Bb%?kRr`qJk*(xD$QnC!=Q~c-DYVk%{=NAK$>|w&)@*oEn#EWjK)N*7VO2ne zH2Y(1hpy7BWJEQX-K6PQwP5iAElV+GBN(6MlvjmZ4c1fMe&oZD7>b31MNv5$oyDz( zW}#?7K{!;DAC0If>2GvTDsSvaa86jssfg{M)!bNgZa7x7Ai%s`XmOU_95ezv)|2;a z>_RX}dd^#kx8A8P|J@B(n?TQbo3W}u&w1Oic7vYt=40&vJ?FWj*K^)U>YV{S=bgp6 z1bWW9f^`e@oc9CPZD=O%ykj+h#jW4h(wKu_yw;6!6#X<E2C#k_PGm9dM7|P!gj1Zpc`Qe)p=veOHqfD}6srn!sB+J)L)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poem/source_maps/dependencies/MoveStdlib/bcs.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..3b9a902f6e454050cdabacef37dc43af8d2067da GIT binary patch literal 220 zcmZQN_E4yA_J;K;|9|>5_cmgpH;RTG$Ny)_^ vRZIj7JP1^C5@aB!Z+=;7SYl3TDj_YWfXXj}v@n(tQhF7r>>3aQ0V4wd#6M6+ literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/bit_vector.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/bit_vector.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..24b8156e5e75eaa1325554cbfd6ecb88002d822f GIT binary patch literal 9546 zcmb8#Sx{AV0LStF1!R@gBo`3%hKz~EqToU%0?A&23aJgLT<|JeicB-5X49xRcEtsypj{d@VJSG6~kewxnc6(s8?)5 z@3D?z_)Fo_n9Jmn@($_=`AFG?3Jf#GSITS1Af%s^SCCh!my~U&D8>wuG6WS#!BW~| zhDbS*@zSWbl!>TG6e{IpQ~`xa8H*~Ua4BQDrGqd2lL%uzBja*@)o#LnVZDZnK)#n# zzz)*a;7L>`>1*&1>Q8b&4@PonQBUs5Yxut?WO3u1MGo)FNBDp!K4vdRxA9D91({fV z2IFx_*3j}?r=l`QpFvAzk-j&RQ7NSF%~(_+>3cH=RY3aQw8zx<=3K_BC4Fz&=U(5N z=NPYp^u2i%b&K@9X~`~%l;7rM)D?=7@&u~9k1@|l8I6jgzETcB4Wno&gHQ?dyp(|` zOZSt~4>gMVOF6t-#z>is%%fN-3sFThNXmRv0mVs~fy$)8Qd&nYrXf`Ob1(muh~NFB;)e0@zhl}&R08^UEsa+Y%f(&<@MB5s+Z*X7*j$4 z^Xiw>HF_2)pM*^(9~YCWD|s;ITYlsY-qLl_Q}InyC+Vs92I>#e8>-W&JEW)LTc|Gb zm!HTUGeF7!&Q&M{N*RIbM|vR$Lxq!G2%hq3h9dR!J^(d@^z?3zsi*hxj5mSw^lo2O z5%MfeXS_<%3xR!Q>xH0+@h(vxdGx#pMmuOwx(a{zI}%IoGf zLq4*Gl`@vKy&4_m7cJNUtcJs6@upb9y{#1nD{59#e1bXE0s` z>DhlO%1e6oUx;cXJ^N2YEg?Po+t-Mm{Xb;9)udwDp@Wn3< zHfAaHygNnVeIdpip#V>fr`DY^cK4Mt2R3Y3y7c#s z6-5=D5lOY-+Y?HT%x-=+wd#8E#RD}rlZ<&tF0UH7iczb{&+AS}Q^Rgx$c<#}XWc33 zif@DNAipMe%4mfvfgUmidZyXIdD}yJrrC%3h4f5g$)lv_kMB@>NzWf!QFnRlt9PXL zkuK{CmUHKAWC&94NG~9>kU>VB`%Rqp%@i!9eFcO_xsUN$DOAc`sQnZsrF}t#OWDSF z?Gz#93DhZyl=2wrI7LZ$7!{Lj?K9Pxzk|F>eWkpQdO*=q+Bd)6XO80PNF}|`OhAnw zz0VxhJ?239K0`S}VH6`}Br1wxr3^$&;P{9=ENLokN`%L?O*L%VRoTUcR4;<_X zI$q8UD;aMU4U=*WY8@pwk}b&LQm#fd(~D9rM`bfBCQ8|gJVYaU3G+9dP$ku;U z&XTeW^%iA2lGVsprCfk&pea($M|mk%%2L!c%9C;>Y8B;6xdye43LME6WRaAsQO#5= z<#JRfy)NYr)Lxn@Wh-hwl}Nb-^#hekc@lMsrb&4gb&jS>c^Y+wW=MGqb)3qiw2pk9 z%B8f|Vh5Y=F8)V{2h@{adk^uxfjxQZ(ic6596WVd23t-}p1P#tCRxMEGg6A0P5QS` z395?pQJ^?Y9Rg8#fz#Z{nW)CQ$KZSVZ6=bw{ToSjq7kKCNX foZ>0da$P2{D6_nxG;d~(j|nP!tt9)|zkSWW&Sk~J literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/error.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/error.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..308789b9c0db5875fc3f7e23f62421f73d4cb1d0 GIT binary patch literal 3273 zcma)+O-NKx7>2)b9G%h8DI+5LfhdcjKf;7|o|${p3)g$c`!iIVQEE^tvTkjJNTX=e zrcIgJwm^cQBdYTI`Pp2fg3=gxD!b8h?QJuB;L=GtnP zayu8-T^(y^J}_o1Ow7;ZPWAQQEMBRP5gh^%`u`^qD}-TBNL57b%#!cn6ahsdA?HrP zn^rDG`GprDE`tdB7kl&KEj+!d`A{ccI@0WnrP?T+eAve+2cJdIFX4Q+@|=67ah*1M4H; zccTbv8bsOiFbnG|C}qu0us(wrYrg%vrpDt(FtP_~Y#MjxA-qxL>YTB0h#vsItCO&b zfZx^Eu%>{kyQV_r|-Jyotw z*962_z<15T`U3c_H?ZabZXtJLuj7?C_~*6Azr%;%4J%itYZT&hz<0fX^%C%1Bd}fp zDrdXC;kYiTBdam5Wq3c7tJ77JBH9A@uC1`P0lq5^s}4|{?K+OJo>8OK=sF88RIX0f zHHZU%?;3H>UM7FIW)s&bKbTwfY^g_yQ4 zU0YaDN@Rqck(MQm5=z*PpKo#k+bE;Tz!o`SS|V-9Bqg1|&pSI-^>htV^q?re~SpWIZ#?D jtk#+9BExEYDXTSVaDw-xjo_Ep{- literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/features.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/features.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..1b0001d87d667ce185d7f43b40c6f88c2646be62 GIT binary patch literal 13093 zcmb7~3vg7`8OKi&AUpyIFA3qD1Q8^V1QLSU>do%WX31uEy}KLCOvfu|P%s3IfKrQ& zPVM+=XK?zW7Hz9lJL7BAsiK`ar9-Fqs3>izFBEHwqNw<4E2#Y)*lRnTY5%8Z<~PIR zm+yY}?782$-`T|fzJ1@d_w2oI>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MT}f`lddLRW%k=FT^r$m!22MG2&opKu z=p5RyE(M1NVCMQI>R@bMJH%v3;F0jKP@&l+( zT79bAO3S8lmIQVrQAQSxyGs34O|yM`G$u=qP3#rtXAhW6cNM z34K6JJEOW2ite2gd9~x+PKkP?Sk+4PC-nyEhoC>Hm$5#wf$L-r?PK|l2kdaj;k&4h zg3jRvtjBENdYQw%Dz0r+hQo7Kf!b*G*)sCYlMgk6xBlvZbNe@(Cx0E~R@^(F z%=u{SHSB}%e;ked0{u5Iv~OVj;3lqe}HKzB{ibF90d9mLxOx~usm)&h=ib(gXq^RJ-0j#rDO?jqjAJPf)k zIDqvA=(qeoVZ98qWUbqaWv{N^?4nuH?_U#{%No#cNfU~ue(RZzSqu8zWHwd<=r@Qu zta{M<{1mLIpm*a6tg$dp&ip7WyXy4sZ$vZi5cF>P%O{F0slyA&C#cn zq?@4=T~};g9dfu8^I@Uoq~p_fYd?SU8l>pyPQAH%&<4@<@o@PPb>4$(;VhvT#uwj;FC!@?C?@KKU^MU(upwTrxW?k3iD4R C9xG-5 literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/fixed_point32.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/fixed_point32.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..239b9a1033672f1c313b79700554ffe59bc86dc3 GIT binary patch literal 9445 zcmb7}S!`5Q7{||ap>(6AfY605(Au&?SxO`Z3mwW-+M%TdM6ecSfYG)CrDe5fq6TAp zU~zdc!5D=EBoGaYB`i`UK@%~cgs2E2i4UllkQfRD>+d99AN?Pi{GR%|-#z!9?|k36 zXS(*pZM*eX-<}6uQ)h0gI#O2f&bjw4oPK{;=i(c8y8ZiKTWgHj3O@M1KVRy~$i{G} zaZNPR+CI4yy-P&?HpZB1V0_B#!Fm8GI_Q={V_pQ~i*4;_QGs8=d>MSnE1RRyHiqwT z(Oxe2*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!$gRW~E)P_y3{npA FAONKTV0Zuk literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/option.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/option.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..78b6ca4ee0826b5e8ffbe490857ff8f894e1cd95 GIT binary patch literal 10322 zcmb7}YfP497{_m3P$Cr-$pfe$9wucqH57H>Oi5_QTR_q}2&gXtBH#h)gXQ?-p=p|F z{YR=-SLFctYxe}NLKkrqOVeuzswox1|&hq#J-%U=*DpZ7LeCped+ zALOB4&gDRy%-a~O2@sLy2&@9=F3nu5nUE;W5c4i+&L!SFNRnnH)&jU&nl)Ip&_kNV zSPQ|B(DnVD+XChq*owT{U!ZGXFWNpZ)j%8KdC)6+7ONfNWgdROx&?Y=FJg6oUfB>+ zuWb4N=LUmb+5T9WpjS2vYdG|jpFJLH1Q-%}GTFJ`z+3~Dkgq~S*T7$B*P+M!SXE_H z-Lmo}u_`sfl6pIr3X%Ac!^bMQ7;!HoHpk{!g6HB+1yU$;I2~^W=(+R=Rsrbh4fog8 zyMTE0kRYFPHdX_4lV-@4uJgsjTMoL;L(E?C?r#xqCnQUAH`X5LEzLDpe*ODMGd!nZ zaP;os+yF3l#6aW>Fm%K)v@GZrvy|%u%qif@Kz_m+#9GkxT8&i?x?UTxnn2fU8CEkG z3U+-a9|p|%-HyE1U!W(>ezdp24|AEZ?-73lov{;GCqZZIbF2%X`}QrLYA0Nq_7rtXl-mh^Z$`H8C4N@5+m@mVn-s zXJah|{Yn|KWO(=eraNy1VD5rb$mje8mW}fl#8xnUftH;}4T7%LG^__eSL-;e@t~{q zL9DT$Pp~OikAbe%9IQgn^EJfOb^Sc?DnQTIQmnaP7_cY$Fblz41!s|4!7vLu(f$GJ zDQ-|-1{|19adQz5f^~Wp;6}kRJxlOPLDyq3*3+QtG2CC*;|s)l8FW2XVXXi?XG6Ah zm9-FW73eApG4=G^PrL)5r|0`vAAp{oZ(#ZL*VA)zm#L>`_(X=|#%0>;CYbxC1Nn}> zK%WldI21;}4==fY=ORu5U8@tZ9tK^jqpG&@)zhlRHM~^FL0TM zort@9TxssW+6Ouh>#+8N?%B0i-qt1U_)nmTo!^@0S zV6E_Rb+fHwsa^x~GjBxR;xEuA=51)(!PFPOBDVUt^3#2b)dspAKErAU!$EA)K$;EA zdB{V~2gANP6Rp6dbhkxyqlnR%X3&Apc^=> zzuqlV2RWAx`sb@5SVN(&tdIy+2Bb(c8*3aGZr_^5m+xTi#Vg1iVCcoa(QfLLp%odzOBHn0c+pp;pPL2B6IyXUJ>Y7T7Xpyy2Hc$b%(bQZx!fMZX?!e z(C=pc@3)*47X3saxM+bvmhNg%U__+t0T}xg6VuxjacL3%1>8@6$9N< zOR<{4#V6-SpC~Pi7L^y4l$Yd}vO9-=6h%w@f8tzf_|NS8>E)%-X!)#Y(aebZ7hFDH A6aWAK literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/signer.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/signer.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..e41277f91bf37b030b5ec0482ac19d3bb7ae1003 GIT binary patch literal 389 zcmaFY5|Z;Q!usf+WoJ_FHLl}%#yg`bs{eZPtjdrrY6k6lco-NMgn*b4i17hNw&Kk6 zywoBFCI*Ig1k9WcG;ATrKt{%5LTVQQ)hz~F&P>?gi$H~!fS8e>6Al4YT?S$%f+`O} YRT5#SB~Yn55EJ7s51=|vkXn#y0aIF*%K!iX literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/string.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/string.mvsm new file mode 100644 index 0000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)P4f3Vw)~V+TYuehsTxO=RM&Jr*ZoqmBu9Rjcmi=`-)wp%)xx$+E4b^kS4y-po z&lS6|_JE!%p2V`hULv2}ty6#5SCKab*UHQfuns|`G+pLmY0i*$0j`tg-&hp9(KA2@ zD+BZl@DrJtn0f~I1~UuO<3%dqBcc#Y;Mc~BaHA0T+&l@yFKjrySKTIS@Oo{qG?Q3; zpl@{d`?`~FB5xFQCw~TO3+PV%DApM0PVUyJ`}2F`9R%HoY@$K)LVeeb@DH324+A8%~wxFgxv Wu)4i%`7MEoT>5uoOGEq~WBvhg4kt1I literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/vector.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/dependencies/MoveStdlib/vector.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..f93a184b1b9cb02294da1b9ee57f2874dcf0eed8 GIT binary patch literal 16736 zcmb80dvwnC9mju9p4`aQEol>SkB*|nv}z(!o`{l!+z{oN!;^`HWRarBSaH_6b?DkL ztSeeO<}&Rzldh{ttTfo=Y@=xBHn*aJu$HmCzD|Ds_WhM}UjI0+=kvRLzwhto`+FYs zXOB0$xnthEBc~VS`!B~nIX&jR$BGU;zhrLTiVM9@HdL(-a-5CealZb~6FMs}xvsj_ zdBkz*Ma|Puj&lJ#VZN%s^uUZd^?{4X*C5DSHFc(vuOqfVNOj%RK&`SPqaCLmI8LZO z@uv_6gGXLsFRUC0l4d#91n^4Jk2M8?r8xpC03p&eRs~pGQcZ~C%mVADHXC_91bJqu zr|=Tm0#mzEnQvhI1k5Sxo7>Doy#v1(=%<7zj(Lz9hV3G3j4qVkbkM!N#us=y3Y_CB7c6F0&lCa&Q&8()rM_YCxa zh~U_fpdUjpRut&j=3bMYZAsKihERD$X;_&MCe0MAR0x-5Jl2cQR+@vcav(yQL$HQI zq%@zw@N6S@WYE_n4?bPw&msV!qSE|Et7I?I!=l8tGT(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2x~d$P+ozx5_BlPiuEJVq3k|S9m+qa-dmtUc_Y>)(0k%{u(pHV6R*YE z0eVlo7pnpE9Ndl72o{^-i@fQ&0@l;@Dsl^0OxN3J|ADX>f!ThGUw*_e_2R(etqsWk z={XQF8|ZiBd@aNqWeQ8P2x}bZnf)wQIp~?~o~fSMRn)5kz1&Q}dI5A>_yeqkVDZ|c z8y$8(upSFfA!mWbSja{j47OuoEUw>_w)x8JhlqyO`sPAx29ec&QR|X z=taSOo_bNZLp@Iin@&9#D-86a5QOCgy(rw|=-(5?T&wzgY z8ILsp^e>HAgN3{i1XlRt-4bXy5RHvYe5_ zhx&_h3WoVSPDlP>sBf&lu(ZTqnCpMGu(V)kF?Y#V<{MH{SXAsE=_?pklIPDKUYws( JG9)j^`9ElSNsa&j literal 0 HcmV?d00001 diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/sakutaro_poem.mvsm b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/source_maps/sakutaro_poem.mvsm new file mode 100644 index 0000000000000000000000000000000000000000..3896cd071f5eac1a9ac78e807eecda193f373a8e GIT binary patch literal 17432 zcmb7~d32Q38Heu#B1@98$s!;G5;hHjB(lm9l7U3CnF)l!!Z;*Dni?`83%jV`QY@gg z+OixJYlWzRDwa~D;z6rI3P(V!2ucyFAc$}X+EzgOe9l}?PyhLS{PFz3;hFba-uvDA z-uGr`p7-f3zg;`1{=gQ0(@XKm)6ehw$GYIeonr&u)zfxlF79NENdnL8M-w*>Yif1; z1^?xp!_U-ot2y8G8Sfg;flrE?CcgRh(OC&K!Mp2fgVo_cRX8*&#+acZ@+O>ZU}BWn zh;_(C#Q)$VG~-_7wQs;21^U{Pu_{2_E#r!)om*y6%4*O-r4Fb%@V`9<`5R{T_6-_Fx?bovm$HAA-)-M_9)| zXX^;oQPA1iigglnwl+si7Y|>z(3tzd{r9y5dl`6|)yyeV$=!hXyc0f6=k{g1KRSWs zXl%gR3Ocv;`Z~9NBi?(UbNf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X+Oc77bE_rP=T9tOP!UWv61^d5K_)>EMOz<#W!LGOX>GwD6>e&T%&dJnt< z>m=ws@M)|wp!dM1u)YAj2fmEe+1c64ar1T5bkXx2!0;O646&GmAO4s+5G*a_#GpnE znZf*KG+fQuV-~&-uBA04|8TzBuc-dPX(~#2$m5g_;K;I3*a|T@D$7pc=iI`j=xxaM zUjyRys4V+`D-oXpUWUBoIJ_ zLH0IZ!8;LgWpDFAyk{b=>}`fg@km^^eabf;V~L0Os_Jl6sJeE3U{E`{wn!P(-{C=yjn2Ya!@$p$uyg=yhQQ)+*5J!eXq| zpx1@rSZhG{M(s$`M}g;vXBc9-iyGs6C!o8iyNKD=vE@o;SBppgXhnL)3pph z3f6sLyCCYma3ag*4WRqNw&F;Xqt0Hvmo&R_Wv7biEzOI(p%ly{X%5C32FcPKh&2fM zNb@{bFUIUE&52mKp!>qMz!@N8+PX=1d(Uv?Zy`m-w1u1Q_I9CANCN$*=(cjy-CkRe z>Td6gTzM<#Ztn)HKfx{X+4o@`0o@ngjdc`sU-$x6bIPgV^6F@_j*f zX6+V1_gh;N&)H1qeyiO|=q_p*@hU-gQSG)z_eSl!qPj>M`0-5br~ zYg>$|d!u`>-UZzo{VUdf(7n-* zF<4VU_ePiVG(W?fDPzvyYpcO5lcr = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + public fun encode(str: &vector): vector { + if (vector::is_empty(str)) { + return vector::empty() + }; + let size = vector::length(str); + let eq: u8 = 61; + let res = vector::empty(); + + let m = 0 ; + while (m < size ) { + vector::push_back(&mut res, *vector::borrow(&TABLE, (((*vector::borrow(str, m) & 0xfc) >> 2) as u64))); + if ( m + 3 >= size) { + if ( size % 3 == 1) { + vector::push_back(&mut res, *vector::borrow(&TABLE, (((*vector::borrow(str, m) & 0x03) << 4) as u64))); + vector::push_back(&mut res, eq); + vector::push_back(&mut res, eq); + }else if (size % 3 == 2) { + vector::push_back(&mut res, *vector::borrow(&TABLE, ((((*vector::borrow(str, m) & 0x03) << 4) + ((*vector::borrow(str, m + 1) & 0xf0) >> 4)) as u64))); + vector::push_back(&mut res, *vector::borrow(&TABLE, (((*vector::borrow(str, m + 1) & 0x0f) << 2) as u64))); + vector::push_back(&mut res, eq); + }else { + vector::push_back(&mut res, *vector::borrow(&TABLE, ((((*vector::borrow(str, m) & 0x03) << 4) + ((*vector::borrow(str, m + 1) & 0xf0) >> 4)) as u64))); + vector::push_back(&mut res, *vector::borrow(&TABLE, ((((*vector::borrow(str, m + 1) & 0x0f) << 2) + ((*vector::borrow(str, m + 2) & 0xc0) >> 6)) as u64))); + vector::push_back(&mut res, *vector::borrow(&TABLE, ((*vector::borrow(str, m + 2) & 0x3f) as u64))); + }; + }else { + vector::push_back(&mut res, *vector::borrow(&TABLE, ((((*vector::borrow(str, m) & 0x03) << 4) + ((*vector::borrow(str, m + 1) & 0xf0) >> 4)) as u64))); + vector::push_back(&mut res, *vector::borrow(&TABLE, ((((*vector::borrow(str, m + 1) & 0x0f) << 2) + ((*vector::borrow(str, m + 2) & 0xc0) >> 6)) as u64))); + vector::push_back(&mut res, *vector::borrow(&TABLE, ((*vector::borrow(str, m + 2) & 0x3f) as u64))); + }; + m = m + 3; + }; + + return res + } + + public fun decode(code: &vector): vector { + if (vector::is_empty(code) || vector::length(code) % 4 != 0) { + return vector::empty() + }; + + let size = vector::length(code); + let res = vector::empty(); + let m = 0 ; + while (m < size) { + let pos_of_char_1 = pos_of_char(*vector::borrow(code, m + 1)); + vector::push_back(&mut res, (pos_of_char(*vector::borrow(code, m)) << 2) + ((pos_of_char_1 & 0x30) >> 4)); + if ( (m + 2 < size) && (*vector::borrow(code, m + 2) != 61) && (*vector::borrow(code, m + 2) != 46)) { + let pos_of_char_2 = pos_of_char(*vector::borrow(code, m + 2)); + vector::push_back(&mut res, ((pos_of_char_1 & 0x0f) << 4) + ((pos_of_char_2 & 0x3c) >> 2)); + + if ( (m + 3 < size) && (*vector::borrow(code, m + 3) != 61) && (*vector::borrow(code, m + 3) != 46)) { + let pos_of_char_2 = pos_of_char(*vector::borrow(code, m + 2)); + vector::push_back(&mut res, ((pos_of_char_2 & 0x03) << 6) + pos_of_char(*vector::borrow(code, m + 3))); + }; + }; + + m = m + 4; + }; + + return res + } + + fun pos_of_char(char: u8): u8 { + if (char >= 65 && char <= 90) { + return char - 65 + }else if (char >= 97 && char <= 122) { + return char - 97 + (90 - 65) + 1 + }else if (char >= 48 && char <= 57) { + return char - 48 + (90 - 65) + (122 - 97) + 2 + }else if (char == 43 || char == 45) { + return 62 + }else if (char == 47 || char == 95) { + return 63 + }; + abort 1001 + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/account.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/account.move new file mode 100644 index 0000000..c6b6a0e --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/account.move @@ -0,0 +1,1335 @@ +module aptos_framework::account { + use std::bcs; + use std::error; + use std::hash; + use std::option::{Self, Option}; + use std::signer; + use std::vector; + use aptos_framework::chain_id; + use aptos_framework::create_signer::create_signer; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::guid; + use aptos_framework::system_addresses; + use aptos_std::ed25519; + use aptos_std::from_bcs; + use aptos_std::multi_ed25519; + use aptos_std::table::{Self, Table}; + use aptos_std::type_info::{Self, TypeInfo}; + + friend aptos_framework::aptos_account; + friend aptos_framework::coin; + friend aptos_framework::genesis; + friend aptos_framework::multisig_account; + friend aptos_framework::resource_account; + friend aptos_framework::transaction_validation; + + /// Resource representing an account. + struct Account has key, store { + authentication_key: vector, + sequence_number: u64, + guid_creation_num: u64, + coin_register_events: EventHandle, + key_rotation_events: EventHandle, + rotation_capability_offer: CapabilityOffer, + signer_capability_offer: CapabilityOffer, + } + + struct KeyRotationEvent has drop, store { + old_authentication_key: vector, + new_authentication_key: vector, + } + + struct CoinRegisterEvent has drop, store { + type_info: TypeInfo, + } + + struct CapabilityOffer has store { for: Option

} + + struct RotationCapability has drop, store { account: address } + + struct SignerCapability has drop, store { account: address } + + /// It is easy to fetch the authentication key of an address by simply reading it from the `Account` struct at that address. + /// The table in this struct makes it possible to do a reverse lookup: it maps an authentication key, to the address of the account which has that authentication key set. + /// + /// This mapping is needed when recovering wallets for accounts whose authentication key has been rotated. + /// + /// For example, imagine a freshly-created wallet with address `a` and thus also with authentication key `a`, derived from a PK `pk_a` with corresponding SK `sk_a`. + /// It is easy to recover such a wallet given just the secret key `sk_a`, since the PK can be derived from the SK, the authentication key can then be derived from the PK, and the address equals the authentication key (since there was no key rotation). + /// + /// However, if such a wallet rotates its authentication key to `b` derived from a different PK `pk_b` with SK `sk_b`, how would account recovery work? + /// The recovered address would no longer be 'a'; it would be `b`, which is incorrect. + /// This struct solves this problem by mapping the new authentication key `b` to the original address `a` and thus helping the wallet software during recovery find the correct address. + struct OriginatingAddress has key { + address_map: Table, + } + + /// This structs stores the challenge message that should be signed during key rotation. First, this struct is + /// signed by the account owner's current public key, which proves possession of a capability to rotate the key. + /// Second, this struct is signed by the new public key that the account owner wants to rotate to, which proves + /// knowledge of this new public key's associated secret key. These two signatures cannot be replayed in another + /// context because they include the TXN's unique sequence number. + struct RotationProofChallenge has copy, drop { + sequence_number: u64, // the sequence number of the account whose key is being rotated + originator: address, // the address of the account whose key is being rotated + current_auth_key: address, // the current authentication key of the account whose key is being rotated + new_public_key: vector, // the new public key that the account owner wants to rotate to + } + + /// Deprecated struct - newest version is `RotationCapabilityOfferProofChallengeV2` + struct RotationCapabilityOfferProofChallenge has drop { + sequence_number: u64, + recipient_address: address, + } + + /// Deprecated struct - newest version is `SignerCapabilityOfferProofChallengeV2` + struct SignerCapabilityOfferProofChallenge has drop { + sequence_number: u64, + recipient_address: address, + } + + /// This struct stores the challenge message that should be signed by the source account, when the source account + /// is delegating its rotation capability to the `recipient_address`. + /// This V2 struct adds the `chain_id` and `source_address` to the challenge message, which prevents replaying the challenge message. + struct RotationCapabilityOfferProofChallengeV2 has drop { + chain_id: u8, + sequence_number: u64, + source_address: address, + recipient_address: address, + } + + struct SignerCapabilityOfferProofChallengeV2 has copy, drop { + sequence_number: u64, + source_address: address, + recipient_address: address, + } + + const MAX_U64: u128 = 18446744073709551615; + const ZERO_AUTH_KEY: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + + /// Scheme identifier for Ed25519 signatures used to derive authentication keys for Ed25519 public keys. + const ED25519_SCHEME: u8 = 0; + /// Scheme identifier for MultiEd25519 signatures used to derive authentication keys for MultiEd25519 public keys. + const MULTI_ED25519_SCHEME: u8 = 1; + /// Scheme identifier used when hashing an account's address together with a seed to derive the address (not the + /// authentication key) of a resource account. This is an abuse of the notion of a scheme identifier which, for now, + /// serves to domain separate hashes used to derive resource account addresses from hashes used to derive + /// authentication keys. Without such separation, an adversary could create (and get a signer for) a resource account + /// whose address matches an existing address of a MultiEd25519 wallet. + const DERIVE_RESOURCE_ACCOUNT_SCHEME: u8 = 255; + + /// Account already exists + const EACCOUNT_ALREADY_EXISTS: u64 = 1; + /// Account does not exist + const EACCOUNT_DOES_NOT_EXIST: u64 = 2; + /// Sequence number exceeds the maximum value for a u64 + const ESEQUENCE_NUMBER_TOO_BIG: u64 = 3; + /// The provided authentication key has an invalid length + const EMALFORMED_AUTHENTICATION_KEY: u64 = 4; + /// Cannot create account because address is reserved + const ECANNOT_RESERVED_ADDRESS: u64 = 5; + /// Transaction exceeded its allocated max gas + const EOUT_OF_GAS: u64 = 6; + /// Specified current public key is not correct + const EWRONG_CURRENT_PUBLIC_KEY: u64 = 7; + /// Specified proof of knowledge required to prove ownership of a public key is invalid + const EINVALID_PROOF_OF_KNOWLEDGE: u64 = 8; + /// The caller does not have a digital-signature-based capability to call this function + const ENO_CAPABILITY: u64 = 9; + /// The caller does not have a valid rotation capability offer from the other account + const EINVALID_ACCEPT_ROTATION_CAPABILITY: u64 = 10; + /// Address to create is not a valid reserved address for Aptos framework + const ENO_VALID_FRAMEWORK_RESERVED_ADDRESS: u64 = 11; + /// Specified scheme required to proceed with the smart contract operation - can only be ED25519_SCHEME(0) OR MULTI_ED25519_SCHEME(1) + const EINVALID_SCHEME: u64 = 12; + /// Abort the transaction if the expected originating address is different from the originating addres on-chain + const EINVALID_ORIGINATING_ADDRESS: u64 = 13; + /// The signer capability offer doesn't exist at the given address + const ENO_SUCH_SIGNER_CAPABILITY: u64 = 14; + /// An attempt to create a resource account on a claimed account + const ERESOURCE_ACCCOUNT_EXISTS: u64 = 15; + /// An attempt to create a resource account on an account that has a committed transaction + const EACCOUNT_ALREADY_USED: u64 = 16; + /// Offerer address doesn't exist + const EOFFERER_ADDRESS_DOES_NOT_EXIST: u64 = 17; + /// The specified rotation capablity offer does not exist at the specified offerer address + const ENO_SUCH_ROTATION_CAPABILITY_OFFER: u64 = 18; + // The signer capability is not offered to any address + const ENO_SIGNER_CAPABILITY_OFFERED: u64 = 19; + // This account has exceeded the allocated GUIDs it can create. It should be impossible to reach this number for real applications. + const EEXCEEDED_MAX_GUID_CREATION_NUM: u64 = 20; + + /// Explicitly separate the GUID space between Object and Account to prevent accidental overlap. + const MAX_GUID_CREATION_NUM: u64 = 0x4000000000000; + #[test_only] + /// Create signer for testing, independently of an Aptos-style `Account`. + public fun create_signer_for_test(addr: address): signer { create_signer(addr) } + + /// Only called during genesis to initialize system resources for this module. + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, OriginatingAddress { + address_map: table::new(), + }); + } + + /// Publishes a new `Account` resource under `new_address`. A signer representing `new_address` + /// is returned. This way, the caller of this function can publish additional resources under + /// `new_address`. + public(friend) fun create_account(new_address: address): signer { + // there cannot be an Account resource under new_addr already. + assert!(!exists(new_address), error::already_exists(EACCOUNT_ALREADY_EXISTS)); + + // NOTE: @core_resources gets created via a `create_account` call, so we do not include it below. + assert!( + new_address != @vm_reserved && new_address != @aptos_framework && new_address != @aptos_token, + error::invalid_argument(ECANNOT_RESERVED_ADDRESS) + ); + + create_account_unchecked(new_address) + } + + fun create_account_unchecked(new_address: address): signer { + let new_account = create_signer(new_address); + let authentication_key = bcs::to_bytes(&new_address); + assert!( + vector::length(&authentication_key) == 32, + error::invalid_argument(EMALFORMED_AUTHENTICATION_KEY) + ); + + let guid_creation_num = 0; + + let guid_for_coin = guid::create(new_address, &mut guid_creation_num); + let coin_register_events = event::new_event_handle(guid_for_coin); + + let guid_for_rotation = guid::create(new_address, &mut guid_creation_num); + let key_rotation_events = event::new_event_handle(guid_for_rotation); + + move_to( + &new_account, + Account { + authentication_key, + sequence_number: 0, + guid_creation_num, + coin_register_events, + key_rotation_events, + rotation_capability_offer: CapabilityOffer { for: option::none() }, + signer_capability_offer: CapabilityOffer { for: option::none() }, + } + ); + + new_account + } + + #[view] + public fun exists_at(addr: address): bool { + exists(addr) + } + + #[view] + public fun get_guid_next_creation_num(addr: address): u64 acquires Account { + borrow_global(addr).guid_creation_num + } + + #[view] + public fun get_sequence_number(addr: address): u64 acquires Account { + borrow_global(addr).sequence_number + } + + public(friend) fun increment_sequence_number(addr: address) acquires Account { + let sequence_number = &mut borrow_global_mut(addr).sequence_number; + + assert!( + (*sequence_number as u128) < MAX_U64, + error::out_of_range(ESEQUENCE_NUMBER_TOO_BIG) + ); + + *sequence_number = *sequence_number + 1; + } + + #[view] + public fun get_authentication_key(addr: address): vector acquires Account { + borrow_global(addr).authentication_key + } + + /// This function is used to rotate a resource account's authentication key to 0, so that no private key can control + /// the resource account. + public(friend) fun rotate_authentication_key_internal(account: &signer, new_auth_key: vector) acquires Account { + let addr = signer::address_of(account); + assert!(exists_at(addr), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + assert!( + vector::length(&new_auth_key) == 32, + error::invalid_argument(EMALFORMED_AUTHENTICATION_KEY) + ); + let account_resource = borrow_global_mut(addr); + account_resource.authentication_key = new_auth_key; + } + + /// Generic authentication key rotation function that allows the user to rotate their authentication key from any scheme to any scheme. + /// To authorize the rotation, we need two signatures: + /// - the first signature `cap_rotate_key` refers to the signature by the account owner's current key on a valid `RotationProofChallenge`, + /// demonstrating that the user intends to and has the capability to rotate the authentication key of this account; + /// - the second signature `cap_update_table` refers to the signature by the new key (that the account owner wants to rotate to) on a + /// valid `RotationProofChallenge`, demonstrating that the user owns the new private key, and has the authority to update the + /// `OriginatingAddress` map with the new address mapping ``. + /// To verify these two signatures, we need their corresponding public key and public key scheme: we use `from_scheme` and `from_public_key_bytes` + /// to verify `cap_rotate_key`, and `to_scheme` and `to_public_key_bytes` to verify `cap_update_table`. + /// A scheme of 0 refers to an Ed25519 key and a scheme of 1 refers to Multi-Ed25519 keys. + /// `originating address` refers to an account's original/first address. + /// + /// Here is an example attack if we don't ask for the second signature `cap_update_table`: + /// Alice has rotated her account `addr_a` to `new_addr_a`. As a result, the following entry is created, to help Alice when recovering her wallet: + /// `OriginatingAddress[new_addr_a]` -> `addr_a` + /// Alice has had bad day: her laptop blew up and she needs to reset her account on a new one. + /// (Fortunately, she still has her secret key `new_sk_a` associated with her new address `new_addr_a`, so she can do this.) + /// + /// But Bob likes to mess with Alice. + /// Bob creates an account `addr_b` and maliciously rotates it to Alice's new address `new_addr_a`. Since we are no longer checking a PoK, + /// Bob can easily do this. + /// + /// Now, the table will be updated to make Alice's new address point to Bob's address: `OriginatingAddress[new_addr_a]` -> `addr_b`. + /// When Alice recovers her account, her wallet will display the attacker's address (Bob's) `addr_b` as her address. + /// Now Alice will give `addr_b` to everyone to pay her, but the money will go to Bob. + /// + /// Because we ask for a valid `cap_update_table`, this kind of attack is not possible. Bob would not have the secret key of Alice's address + /// to rotate his address to Alice's address in the first place. + public entry fun rotate_authentication_key( + account: &signer, + from_scheme: u8, + from_public_key_bytes: vector, + to_scheme: u8, + to_public_key_bytes: vector, + cap_rotate_key: vector, + cap_update_table: vector, + ) acquires Account, OriginatingAddress { + let addr = signer::address_of(account); + assert!(exists_at(addr), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + let account_resource = borrow_global_mut(addr); + + // Verify the given `from_public_key_bytes` matches this account's current authentication key. + if (from_scheme == ED25519_SCHEME) { + let from_pk = ed25519::new_unvalidated_public_key_from_bytes(from_public_key_bytes); + let from_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&from_pk); + assert!(account_resource.authentication_key == from_auth_key, error::unauthenticated(EWRONG_CURRENT_PUBLIC_KEY)); + } else if (from_scheme == MULTI_ED25519_SCHEME) { + let from_pk = multi_ed25519::new_unvalidated_public_key_from_bytes(from_public_key_bytes); + let from_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&from_pk); + assert!(account_resource.authentication_key == from_auth_key, error::unauthenticated(EWRONG_CURRENT_PUBLIC_KEY)); + } else { + abort error::invalid_argument(EINVALID_SCHEME) + }; + + // Construct a valid `RotationProofChallenge` that `cap_rotate_key` and `cap_update_table` will validate against. + let curr_auth_key_as_address = from_bcs::to_address(account_resource.authentication_key); + let challenge = RotationProofChallenge { + sequence_number: account_resource.sequence_number, + originator: addr, + current_auth_key: curr_auth_key_as_address, + new_public_key: to_public_key_bytes, + }; + + // Assert the challenges signed by the current and new keys are valid + assert_valid_rotation_proof_signature_and_get_auth_key(from_scheme, from_public_key_bytes, cap_rotate_key, &challenge); + let new_auth_key = assert_valid_rotation_proof_signature_and_get_auth_key(to_scheme, to_public_key_bytes, cap_update_table, &challenge); + + // Update the `OriginatingAddress` table. + update_auth_key_and_originating_address_table(addr, account_resource, new_auth_key); + } + + public entry fun rotate_authentication_key_with_rotation_capability( + delegate_signer: &signer, + rotation_cap_offerer_address: address, + new_scheme: u8, + new_public_key_bytes: vector, + cap_update_table: vector + ) acquires Account, OriginatingAddress { + assert!(exists_at(rotation_cap_offerer_address), error::not_found(EOFFERER_ADDRESS_DOES_NOT_EXIST)); + + // Check that there exists a rotation capability offer at the offerer's account resource for the delegate. + let delegate_address = signer::address_of(delegate_signer); + let offerer_account_resource = borrow_global(rotation_cap_offerer_address); + assert!(option::contains(&offerer_account_resource.rotation_capability_offer.for, &delegate_address), error::not_found(ENO_SUCH_ROTATION_CAPABILITY_OFFER)); + + let curr_auth_key = from_bcs::to_address(offerer_account_resource.authentication_key); + let challenge = RotationProofChallenge { + sequence_number: get_sequence_number(delegate_address), + originator: rotation_cap_offerer_address, + current_auth_key: curr_auth_key, + new_public_key: new_public_key_bytes, + }; + + // Verifies that the `RotationProofChallenge` from above is signed under the new public key that we are rotating to. l + let new_auth_key = assert_valid_rotation_proof_signature_and_get_auth_key(new_scheme, new_public_key_bytes, cap_update_table, &challenge); + + // Update the `OriginatingAddress` table, so we can find the originating address using the new address. + let offerer_account_resource = borrow_global_mut(rotation_cap_offerer_address); + update_auth_key_and_originating_address_table(rotation_cap_offerer_address, offerer_account_resource, new_auth_key); + } + + /// Offers rotation capability on behalf of `account` to the account at address `recipient_address`. + /// An account can delegate its rotation capability to only one other address at one time. If the account + /// has an existing rotation capability offer, calling this function will update the rotation capability offer with + /// the new `recipient_address`. + /// Here, `rotation_capability_sig_bytes` signature indicates that this key rotation is authorized by the account owner, + /// and prevents the classic "time-of-check time-of-use" attack. + /// For example, users usually rely on what the wallet displays to them as the transaction's outcome. Consider a contract that with 50% probability + /// (based on the current timestamp in Move), rotates somebody's key. The wallet might be unlucky and get an outcome where nothing is rotated, + /// incorrectly telling the user nothing bad will happen. But when the transaction actually gets executed, the attacker gets lucky and + /// the execution path triggers the account key rotation. + /// We prevent such attacks by asking for this extra signature authorizing the key rotation. + /// + /// @param rotation_capability_sig_bytes is the signature by the account owner's key on `RotationCapabilityOfferProofChallengeV2`. + /// @param account_scheme is the scheme of the account (ed25519 or multi_ed25519). + /// @param account_public_key_bytes is the public key of the account owner. + /// @param recipient_address is the address of the recipient of the rotation capability - note that if there's an existing rotation capability + /// offer, calling this function will replace the previous `recipient_address` upon successful verification. + public entry fun offer_rotation_capability( + account: &signer, + rotation_capability_sig_bytes: vector, + account_scheme: u8, + account_public_key_bytes: vector, + recipient_address: address, + ) acquires Account { + let addr = signer::address_of(account); + assert!(exists_at(recipient_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + + // proof that this account intends to delegate its rotation capability to another account + let account_resource = borrow_global_mut(addr); + let proof_challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: account_resource.sequence_number, + source_address: addr, + recipient_address, + }; + + // verify the signature on `RotationCapabilityOfferProofChallengeV2` by the account owner + if (account_scheme == ED25519_SCHEME) { + let pubkey = ed25519::new_unvalidated_public_key_from_bytes(account_public_key_bytes); + let expected_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!(account_resource.authentication_key == expected_auth_key, error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY)); + + let rotation_capability_sig = ed25519::new_signature_from_bytes(rotation_capability_sig_bytes); + assert!(ed25519::signature_verify_strict_t(&rotation_capability_sig, &pubkey, proof_challenge), error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE)); + } else if (account_scheme == MULTI_ED25519_SCHEME) { + let pubkey = multi_ed25519::new_unvalidated_public_key_from_bytes(account_public_key_bytes); + let expected_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!(account_resource.authentication_key == expected_auth_key, error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY)); + + let rotation_capability_sig = multi_ed25519::new_signature_from_bytes(rotation_capability_sig_bytes); + assert!(multi_ed25519::signature_verify_strict_t(&rotation_capability_sig, &pubkey, proof_challenge), error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE)); + } else { + abort error::invalid_argument(EINVALID_SCHEME) + }; + + // update the existing rotation capability offer or put in a new rotation capability offer for the current account + option::swap_or_fill(&mut account_resource.rotation_capability_offer.for, recipient_address); + } + + #[view] + /// Returns true if the account at `account_addr` has a rotation capability offer. + public fun is_rotation_capability_offered(account_addr: address): bool acquires Account { + let account_resource = borrow_global(account_addr); + option::is_some(&account_resource.rotation_capability_offer.for) + } + + #[view] + /// Returns the address of the account that has a rotation capability offer from the account at `account_addr`. + public fun get_rotation_capability_offer_for(account_addr: address): address acquires Account { + let account_resource = borrow_global(account_addr); + assert!( + option::is_some(&account_resource.rotation_capability_offer.for), + error::not_found(ENO_SIGNER_CAPABILITY_OFFERED), + ); + *option::borrow(&account_resource.rotation_capability_offer.for) + } + + /// Revoke the rotation capability offer given to `to_be_revoked_recipient_address` from `account` + public entry fun revoke_rotation_capability(account: &signer, to_be_revoked_address: address) acquires Account { + assert!(exists_at(to_be_revoked_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + let addr = signer::address_of(account); + let account_resource = borrow_global_mut(addr); + assert!(option::contains(&account_resource.rotation_capability_offer.for, &to_be_revoked_address), error::not_found(ENO_SUCH_ROTATION_CAPABILITY_OFFER)); + revoke_any_rotation_capability(account); + } + + /// Revoke any rotation capability offer in the specified account. + public entry fun revoke_any_rotation_capability(account: &signer) acquires Account { + let account_resource = borrow_global_mut(signer::address_of(account)); + option::extract(&mut account_resource.rotation_capability_offer.for); + } + + /// Offers signer capability on behalf of `account` to the account at address `recipient_address`. + /// An account can delegate its signer capability to only one other address at one time. + /// `signer_capability_key_bytes` is the `SignerCapabilityOfferProofChallengeV2` signed by the account owner's key + /// `account_scheme` is the scheme of the account (ed25519 or multi_ed25519). + /// `account_public_key_bytes` is the public key of the account owner. + /// `recipient_address` is the address of the recipient of the signer capability - note that if there's an existing + /// `recipient_address` in the account owner's `SignerCapabilityOffer`, this will replace the + /// previous `recipient_address` upon successful verification (the previous recipient will no longer have access + /// to the account owner's signer capability). + public entry fun offer_signer_capability( + account: &signer, + signer_capability_sig_bytes: vector, + account_scheme: u8, + account_public_key_bytes: vector, + recipient_address: address + ) acquires Account { + let source_address = signer::address_of(account); + assert!(exists_at(recipient_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + + // Proof that this account intends to delegate its signer capability to another account. + let proof_challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: get_sequence_number(source_address), + source_address, + recipient_address, + }; + verify_signed_message( + source_address, account_scheme, account_public_key_bytes, signer_capability_sig_bytes, proof_challenge); + + // Update the existing signer capability offer or put in a new signer capability offer for the recipient. + let account_resource = borrow_global_mut(source_address); + option::swap_or_fill(&mut account_resource.signer_capability_offer.for, recipient_address); + } + + #[view] + /// Returns true if the account at `account_addr` has a signer capability offer. + public fun is_signer_capability_offered(account_addr: address): bool acquires Account { + let account_resource = borrow_global(account_addr); + option::is_some(&account_resource.signer_capability_offer.for) + } + + #[view] + /// Returns the address of the account that has a signer capability offer from the account at `account_addr`. + public fun get_signer_capability_offer_for(account_addr: address): address acquires Account { + let account_resource = borrow_global(account_addr); + assert!( + option::is_some(&account_resource.signer_capability_offer.for), + error::not_found(ENO_SIGNER_CAPABILITY_OFFERED), + ); + *option::borrow(&account_resource.signer_capability_offer.for) + } + + /// Revoke the account owner's signer capability offer for `to_be_revoked_address` (i.e., the address that + /// has a signer capability offer from `account` but will be revoked in this function). + public entry fun revoke_signer_capability(account: &signer, to_be_revoked_address: address) acquires Account { + assert!(exists_at(to_be_revoked_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + let addr = signer::address_of(account); + let account_resource = borrow_global_mut(addr); + assert!(option::contains(&account_resource.signer_capability_offer.for, &to_be_revoked_address), error::not_found(ENO_SUCH_SIGNER_CAPABILITY)); + revoke_any_signer_capability(account); + } + + /// Revoke any signer capability offer in the specified account. + public entry fun revoke_any_signer_capability(account: &signer) acquires Account { + let account_resource = borrow_global_mut(signer::address_of(account)); + option::extract(&mut account_resource.signer_capability_offer.for); + } + + /// Return an authorized signer of the offerer, if there's an existing signer capability offer for `account` + /// at the offerer's address. + public fun create_authorized_signer(account: &signer, offerer_address: address): signer acquires Account { + assert!(exists_at(offerer_address), error::not_found(EOFFERER_ADDRESS_DOES_NOT_EXIST)); + + // Check if there's an existing signer capability offer from the offerer. + let account_resource = borrow_global(offerer_address); + let addr = signer::address_of(account); + assert!(option::contains(&account_resource.signer_capability_offer.for, &addr), error::not_found(ENO_SUCH_SIGNER_CAPABILITY)); + + create_signer(offerer_address) + } + + /////////////////////////////////////////////////////////////////////////// + /// Helper functions for authentication key rotation. + /////////////////////////////////////////////////////////////////////////// + fun assert_valid_rotation_proof_signature_and_get_auth_key(scheme: u8, public_key_bytes: vector, signature: vector, challenge: &RotationProofChallenge): vector { + if (scheme == ED25519_SCHEME) { + let pk = ed25519::new_unvalidated_public_key_from_bytes(public_key_bytes); + let sig = ed25519::new_signature_from_bytes(signature); + assert!(ed25519::signature_verify_strict_t(&sig, &pk, *challenge), std::error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE)); + ed25519::unvalidated_public_key_to_authentication_key(&pk) + } else if (scheme == MULTI_ED25519_SCHEME) { + let pk = multi_ed25519::new_unvalidated_public_key_from_bytes(public_key_bytes); + let sig = multi_ed25519::new_signature_from_bytes(signature); + assert!(multi_ed25519::signature_verify_strict_t(&sig, &pk, *challenge), std::error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE)); + multi_ed25519::unvalidated_public_key_to_authentication_key(&pk) + } else { + abort error::invalid_argument(EINVALID_SCHEME) + } + } + + /// Update the `OriginatingAddress` table, so that we can find the originating address using the latest address + /// in the event of key recovery. + fun update_auth_key_and_originating_address_table( + originating_addr: address, + account_resource: &mut Account, + new_auth_key_vector: vector, + ) acquires OriginatingAddress { + let address_map = &mut borrow_global_mut(@aptos_framework).address_map; + let curr_auth_key = from_bcs::to_address(account_resource.authentication_key); + + // Checks `OriginatingAddress[curr_auth_key]` is either unmapped, or mapped to `originating_address`. + // If it's mapped to the originating address, removes that mapping. + // Otherwise, abort if it's mapped to a different address. + if (table::contains(address_map, curr_auth_key)) { + // If account_a with address_a is rotating its keypair from keypair_a to keypair_b, we expect + // the address of the account to stay the same, while its keypair updates to keypair_b. + // Here, by asserting that we're calling from the account with the originating address, we enforce + // the standard of keeping the same address and updating the keypair at the contract level. + // Without this assertion, the dapps could also update the account's address to address_b (the address that + // is programmatically related to keypaier_b) and update the keypair to keypair_b. This causes problems + // for interoperability because different dapps can implement this in different ways. + // If the account with address b calls this function with two valid signatures, it will abort at this step, + // because address b is not the account's originating address. + assert!(originating_addr == table::remove(address_map, curr_auth_key), error::not_found(EINVALID_ORIGINATING_ADDRESS)); + }; + + // Set `OriginatingAddress[new_auth_key] = originating_address`. + let new_auth_key = from_bcs::to_address(new_auth_key_vector); + table::add(address_map, new_auth_key, originating_addr); + + event::emit_event( + &mut account_resource.key_rotation_events, + KeyRotationEvent { + old_authentication_key: account_resource.authentication_key, + new_authentication_key: new_auth_key_vector, + } + ); + + // Update the account resource's authentication key. + account_resource.authentication_key = new_auth_key_vector; + } + + /////////////////////////////////////////////////////////////////////////// + /// Basic account creation methods. + /////////////////////////////////////////////////////////////////////////// + + /// This is a helper function to compute resource addresses. Computation of the address + /// involves the use of a cryptographic hash operation and should be use thoughtfully. + public fun create_resource_address(source: &address, seed: vector): address { + let bytes = bcs::to_bytes(source); + vector::append(&mut bytes, seed); + vector::push_back(&mut bytes, DERIVE_RESOURCE_ACCOUNT_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + + /// A resource account is used to manage resources independent of an account managed by a user. + /// In Aptos a resource account is created based upon the sha3 256 of the source's address and additional seed data. + /// A resource account can only be created once, this is designated by setting the + /// `Account::signer_capability_offer::for` to the address of the resource account. While an entity may call + /// `create_account` to attempt to claim an account ahead of the creation of a resource account, if found Aptos will + /// transition ownership of the account over to the resource account. This is done by validating that the account has + /// yet to execute any transactions and that the `Account::signer_capability_offer::for` is none. The probability of a + /// collision where someone has legitimately produced a private key that maps to a resource account address is less + /// than `(1/2)^(256)`. + public fun create_resource_account(source: &signer, seed: vector): (signer, SignerCapability) acquires Account { + let resource_addr = create_resource_address(&signer::address_of(source), seed); + let resource = if (exists_at(resource_addr)) { + let account = borrow_global(resource_addr); + assert!( + option::is_none(&account.signer_capability_offer.for), + error::already_exists(ERESOURCE_ACCCOUNT_EXISTS), + ); + assert!( + account.sequence_number == 0, + error::invalid_state(EACCOUNT_ALREADY_USED), + ); + create_signer(resource_addr) + } else { + create_account_unchecked(resource_addr) + }; + + // By default, only the SignerCapability should have control over the resource account and not the auth key. + // If the source account wants direct control via auth key, they would need to explicitly rotate the auth key + // of the resource account using the SignerCapability. + rotate_authentication_key_internal(&resource, ZERO_AUTH_KEY); + + let account = borrow_global_mut(resource_addr); + account.signer_capability_offer.for = option::some(resource_addr); + let signer_cap = SignerCapability { account: resource_addr }; + (resource, signer_cap) + } + + /// create the account for system reserved addresses + public(friend) fun create_framework_reserved_account(addr: address): (signer, SignerCapability) { + assert!( + addr == @0x1 || + addr == @0x2 || + addr == @0x3 || + addr == @0x4 || + addr == @0x5 || + addr == @0x6 || + addr == @0x7 || + addr == @0x8 || + addr == @0x9 || + addr == @0xa, + error::permission_denied(ENO_VALID_FRAMEWORK_RESERVED_ADDRESS), + ); + let signer = create_account_unchecked(addr); + let signer_cap = SignerCapability { account: addr }; + (signer, signer_cap) + } + + /////////////////////////////////////////////////////////////////////////// + /// GUID management methods. + /////////////////////////////////////////////////////////////////////////// + + public fun create_guid(account_signer: &signer): guid::GUID acquires Account { + let addr = signer::address_of(account_signer); + let account = borrow_global_mut(addr); + let guid = guid::create(addr, &mut account.guid_creation_num); + assert!( + account.guid_creation_num < MAX_GUID_CREATION_NUM, + error::out_of_range(EEXCEEDED_MAX_GUID_CREATION_NUM), + ); + guid + } + + /////////////////////////////////////////////////////////////////////////// + /// GUID management methods. + /////////////////////////////////////////////////////////////////////////// + + public fun new_event_handle(account: &signer): EventHandle acquires Account { + event::new_event_handle(create_guid(account)) + } + + /////////////////////////////////////////////////////////////////////////// + /// Coin management methods. + /////////////////////////////////////////////////////////////////////////// + + public(friend) fun register_coin(account_addr: address) acquires Account { + let account = borrow_global_mut(account_addr); + event::emit_event( + &mut account.coin_register_events, + CoinRegisterEvent { + type_info: type_info::type_of(), + }, + ); + } + + /////////////////////////////////////////////////////////////////////////// + // Test-only create signerCapabilityOfferProofChallengeV2 and return it + /////////////////////////////////////////////////////////////////////////// + + #[test_only] + public fun get_signer_capability_offer_proof_challenge_v2( + source_address: address, + recipient_address: address, + ): SignerCapabilityOfferProofChallengeV2 acquires Account { + SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global_mut(source_address).sequence_number, + source_address, + recipient_address, + } + } + + /////////////////////////////////////////////////////////////////////////// + /// Capability based functions for efficient use. + /////////////////////////////////////////////////////////////////////////// + + public fun create_signer_with_capability(capability: &SignerCapability): signer { + let addr = &capability.account; + create_signer(*addr) + } + + public fun get_signer_capability_address(capability: &SignerCapability): address { + capability.account + } + + public fun verify_signed_message( + account: address, + account_scheme: u8, + account_public_key: vector, + signed_message_bytes: vector, + message: T, + ) acquires Account { + let account_resource = borrow_global_mut(account); + // Verify that the `SignerCapabilityOfferProofChallengeV2` has the right information and is signed by the account owner's key + if (account_scheme == ED25519_SCHEME) { + let pubkey = ed25519::new_unvalidated_public_key_from_bytes(account_public_key); + let expected_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!( + account_resource.authentication_key == expected_auth_key, + error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY), + ); + + let signer_capability_sig = ed25519::new_signature_from_bytes(signed_message_bytes); + assert!( + ed25519::signature_verify_strict_t(&signer_capability_sig, &pubkey, message), + error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE), + ); + } else if (account_scheme == MULTI_ED25519_SCHEME) { + let pubkey = multi_ed25519::new_unvalidated_public_key_from_bytes(account_public_key); + let expected_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!( + account_resource.authentication_key == expected_auth_key, + error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY), + ); + + let signer_capability_sig = multi_ed25519::new_signature_from_bytes(signed_message_bytes); + assert!( + multi_ed25519::signature_verify_strict_t(&signer_capability_sig, &pubkey, message), + error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE), + ); + } else { + abort error::invalid_argument(EINVALID_SCHEME) + }; + } + + #[test_only] + public fun create_account_for_test(new_address: address): signer { + create_account_unchecked(new_address) + } + + #[test] + /// Assert correct signer creation. + fun test_create_signer_for_test() { + assert!(signer::address_of(&create_signer_for_test(@aptos_framework)) == @0x1, 0); + assert!(signer::address_of(&create_signer_for_test(@0x123)) == @0x123, 0); + } + + #[test(user = @0x1)] + public entry fun test_create_resource_account(user: signer) acquires Account { + let (resource_account, resource_account_cap) = create_resource_account(&user, x"01"); + let resource_addr = signer::address_of(&resource_account); + assert!(resource_addr != signer::address_of(&user), 0); + assert!(resource_addr == get_signer_capability_address(&resource_account_cap), 1); + } + + #[test] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_cannot_control_resource_account_via_auth_key() acquires Account { + let alice_pk = x"4141414141414141414141414141414141414141414141414141414141414145"; + let alice = create_account_from_ed25519_public_key(alice_pk); + let alice_auth = get_authentication_key(signer::address_of(&alice)); // must look like a valid public key + + let (eve_sk, eve_pk) = ed25519::generate_keys(); + let eve_pk_bytes = ed25519::validated_public_key_to_bytes(&eve_pk); + let eve = create_account_from_ed25519_public_key(eve_pk_bytes); + let recipient_address = signer::address_of(&eve); + + let seed = eve_pk_bytes; // multisig public key + vector::push_back(&mut seed, 1); // multisig threshold + vector::push_back(&mut seed, 1); // signature scheme id + let (resource, _) = create_resource_account(&alice, seed); + + let resource_addr = signer::address_of(&resource); + let proof_challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global_mut(resource_addr).sequence_number, + source_address: resource_addr, + recipient_address, + }; + + let eve_sig = ed25519::sign_struct(&eve_sk, copy proof_challenge); + + // Construct a malicious 1-out-of-2 multisig PK over Alice's authentication key and Eve's Ed25519 PK. + let account_public_key_bytes = alice_auth; + vector::append(&mut account_public_key_bytes, eve_pk_bytes); + vector::push_back(&mut account_public_key_bytes, 1); // Multisig verification threshold. + let fake_pk = multi_ed25519::new_unvalidated_public_key_from_bytes(account_public_key_bytes); + + // Construct a multisig for `proof_challenge` as if it is signed by the signers behind `fake_pk`, + // Eve being the only participant. + let signer_capability_sig_bytes = x""; + vector::append(&mut signer_capability_sig_bytes, ed25519::signature_to_bytes(&eve_sig)); + vector::append(&mut signer_capability_sig_bytes, x"40000000"); // Signers bitmap. + let fake_sig = multi_ed25519::new_signature_from_bytes(signer_capability_sig_bytes); + + assert!(multi_ed25519::signature_verify_strict_t(&fake_sig, &fake_pk, proof_challenge), error::invalid_state(EINVALID_PROOF_OF_KNOWLEDGE)); + offer_signer_capability(&resource, signer_capability_sig_bytes, MULTI_ED25519_SCHEME, account_public_key_bytes, recipient_address); + } + + #[test_only] + struct DummyResource has key {} + + #[test(user = @0x1)] + public entry fun test_module_capability(user: signer) acquires Account, DummyResource { + let (resource_account, signer_cap) = create_resource_account(&user, x"01"); + assert!(signer::address_of(&resource_account) != signer::address_of(&user), 0); + + let resource_account_from_cap = create_signer_with_capability(&signer_cap); + assert!(&resource_account == &resource_account_from_cap, 1); + + move_to(&resource_account_from_cap, DummyResource {}); + borrow_global(signer::address_of(&resource_account)); + } + + #[test(user = @0x1)] + public entry fun test_resource_account_and_create_account(user: signer) acquires Account { + let resource_addr = create_resource_address(&@0x1, x"01"); + create_account_unchecked(resource_addr); + + create_resource_account(&user, x"01"); + } + + #[test(user = @0x1)] + #[expected_failure(abort_code = 0x8000f, location = Self)] + public entry fun test_duplice_create_resource_account(user: signer) acquires Account { + create_resource_account(&user, x"01"); + create_resource_account(&user, x"01"); + } + + /////////////////////////////////////////////////////////////////////////// + // Test-only sequence number mocking for extant Account resource + /////////////////////////////////////////////////////////////////////////// + + #[test_only] + /// Increment sequence number of account at address `addr` + public fun increment_sequence_number_for_test( + addr: address, + ) acquires Account { + let acct = borrow_global_mut(addr); + acct.sequence_number = acct.sequence_number + 1; + } + + #[test_only] + /// Update address `addr` to have `s` as its sequence number + public fun set_sequence_number( + addr: address, + s: u64 + ) acquires Account { + borrow_global_mut(addr).sequence_number = s; + } + + #[test_only] + public fun create_test_signer_cap(account: address): SignerCapability { + SignerCapability { account } + } + + #[test_only] + public fun set_signer_capability_offer(offerer: address, receiver: address) acquires Account { + let account_resource = borrow_global_mut(offerer); + option::swap_or_fill(&mut account_resource.signer_capability_offer.for, receiver); + } + + #[test_only] + public fun set_rotation_capability_offer(offerer: address, receiver: address) acquires Account { + let account_resource = borrow_global_mut(offerer); + option::swap_or_fill(&mut account_resource.rotation_capability_offer.for, receiver); + } + + #[test] + /// Verify test-only sequence number mocking + public entry fun mock_sequence_numbers() + acquires Account { + let addr: address = @0x1234; // Define test address + create_account(addr); // Initialize account resource + // Assert sequence number intializes to 0 + assert!(borrow_global(addr).sequence_number == 0, 0); + increment_sequence_number_for_test(addr); // Increment sequence number + // Assert correct mock value post-increment + assert!(borrow_global(addr).sequence_number == 1, 1); + set_sequence_number(addr, 10); // Set mock sequence number + // Assert correct mock value post-modification + assert!(borrow_global(addr).sequence_number == 10, 2); + } + + /////////////////////////////////////////////////////////////////////////// + // Test account helpers + /////////////////////////////////////////////////////////////////////////// + + #[test(alice = @0xa11ce)] + #[expected_failure(abort_code = 65537, location = aptos_framework::ed25519)] + public entry fun test_empty_public_key(alice: signer) acquires Account, OriginatingAddress { + create_account(signer::address_of(&alice)); + let pk = vector::empty(); + let sig = x"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + rotate_authentication_key(&alice, ED25519_SCHEME, pk, ED25519_SCHEME, pk, sig, sig); + } + + #[test(alice = @0xa11ce)] + #[expected_failure(abort_code = 262151, location = Self)] + public entry fun test_empty_signature(alice: signer) acquires Account, OriginatingAddress { + create_account(signer::address_of(&alice)); + let test_signature = vector::empty(); + let pk = x"0000000000000000000000000000000000000000000000000000000000000000"; + rotate_authentication_key(&alice, ED25519_SCHEME, pk, ED25519_SCHEME, pk, test_signature, test_signature); + } + + #[test_only] + public entry fun create_account_from_ed25519_public_key(pk_bytes: vector): signer { + let pk = ed25519::new_unvalidated_public_key_from_bytes(pk_bytes); + let curr_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&pk); + let alice_address = from_bcs::to_address(curr_auth_key); + let alice = create_account_unchecked(alice_address); + alice + } + + // + // Tests for offering & revoking signer capabilities + // + + #[test(bob = @0x345)] + #[expected_failure(abort_code = 65544, location = Self)] + public entry fun test_invalid_offer_signer_capability(bob: signer) acquires Account { + let (_alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let sig = ed25519::sign_struct(&_alice_sk, challenge); + + // Maul the signature and make sure the call would fail + let invalid_signature = ed25519::signature_to_bytes(&sig); + let first_sig_byte = vector::borrow_mut(&mut invalid_signature, 0); + *first_sig_byte = *first_sig_byte + 1; + + offer_signer_capability(&alice, invalid_signature, 0, alice_pk_bytes, bob_addr); + } + + #[test(bob = @0x345)] + public entry fun test_valid_check_signer_capability_and_create_authorized_signer(bob: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability(&alice, ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), 0, alice_pk_bytes, bob_addr); + + assert!(option::contains(&borrow_global(alice_addr).signer_capability_offer.for, &bob_addr), 0); + + let signer = create_authorized_signer(&bob, alice_addr); + assert!(signer::address_of(&signer) == signer::address_of(&alice), 0); + } + + #[test(bob = @0x345)] + public entry fun test_get_signer_cap_and_is_signer_cap(bob: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability(&alice, ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), 0, alice_pk_bytes, bob_addr); + + assert!(is_signer_capability_offered(alice_addr), 0); + assert!(get_signer_capability_offer_for(alice_addr) == bob_addr, 0); + } + + + #[test(bob = @0x345, charlie = @0x567)] + #[expected_failure(abort_code = 393230, location = Self)] + public entry fun test_invalid_check_signer_capability_and_create_authorized_signer(bob: signer, charlie: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability(&alice, ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), 0, alice_pk_bytes, bob_addr); + + let alice_account_resource = borrow_global_mut(alice_addr); + assert!(option::contains(&alice_account_resource.signer_capability_offer.for, &bob_addr), 0); + + create_authorized_signer(&charlie, alice_addr); + } + + #[test(bob = @0x345)] + public entry fun test_valid_revoke_signer_capability(bob: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability(&alice, ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), 0, alice_pk_bytes, bob_addr); + revoke_signer_capability(&alice, bob_addr); + } + + #[test(bob = @0x345, charlie = @0x567)] + #[expected_failure(abort_code = 393230, location = Self)] + public entry fun test_invalid_revoke_signer_capability(bob: signer, charlie: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + let alice_account_resource = borrow_global(alice_addr); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let charlie_addr = signer::address_of(&charlie); + create_account(charlie_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: alice_account_resource.sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + offer_signer_capability(&alice, ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), 0, alice_pk_bytes, bob_addr); + revoke_signer_capability(&alice, charlie_addr); + } + + // + // Tests for offering rotation capabilities + // + #[test(bob = @0x345, framework = @aptos_framework)] + public entry fun test_valid_offer_rotation_capability(bob: signer, framework: signer) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: get_sequence_number(alice_addr), + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability(&alice, ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), 0, alice_pk_bytes, bob_addr); + + let alice_resource = borrow_global_mut(signer::address_of(&alice)); + assert!(option::contains(&alice_resource.rotation_capability_offer.for, &bob_addr), 0); + } + + #[test(bob = @0x345, framework = @aptos_framework)] + #[expected_failure(abort_code = 65544, location = Self)] + public entry fun test_invalid_offer_rotation_capability(bob: signer, framework: signer) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + // Intentionally make the signature invalid. + sequence_number: 2, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability(&alice, ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), 0, alice_pk_bytes, signer::address_of(&bob)); + } + + #[test(bob = @0x345, framework = @aptos_framework)] + public entry fun test_valid_revoke_rotation_capability(bob: signer, framework: signer) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: get_sequence_number(alice_addr), + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability(&alice, ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), 0, alice_pk_bytes, signer::address_of(&bob)); + revoke_rotation_capability(&alice, signer::address_of(&bob)); + } + + #[test(bob = @0x345, charlie = @0x567, framework = @aptos_framework)] + #[expected_failure(abort_code = 393234, location = Self)] + public entry fun test_invalid_revoke_rotation_capability(bob: signer, charlie: signer, framework: signer) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + create_account(signer::address_of(&charlie)); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: get_sequence_number(alice_addr), + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability(&alice, ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), 0, alice_pk_bytes, signer::address_of(&bob)); + revoke_rotation_capability(&alice, signer::address_of(&charlie)); + } + + // + // Tests for key rotation + // + + #[test(account = @aptos_framework)] + public entry fun test_valid_rotate_authentication_key_multi_ed25519_to_multi_ed25519(account: signer) acquires Account, OriginatingAddress { + initialize(&account); + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let curr_pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let curr_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&curr_pk_unvalidated); + let alice_addr = from_bcs::to_address(curr_auth_key); + let alice = create_account_unchecked(alice_addr); + + let (new_sk, new_pk) = multi_ed25519::generate_keys(4, 5); + let new_pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&new_pk); + let new_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&new_pk_unvalidated); + let new_address = from_bcs::to_address(new_auth_key); + + let challenge = RotationProofChallenge { + sequence_number: borrow_global(alice_addr).sequence_number, + originator: alice_addr, + current_auth_key: alice_addr, + new_public_key: multi_ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + }; + + let from_sig = multi_ed25519::sign_struct(&curr_sk, challenge); + let to_sig = multi_ed25519::sign_struct(&new_sk, challenge); + + rotate_authentication_key( + &alice, + MULTI_ED25519_SCHEME, + multi_ed25519::unvalidated_public_key_to_bytes(&curr_pk_unvalidated), + MULTI_ED25519_SCHEME, + multi_ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + multi_ed25519::signature_to_bytes(&from_sig), + multi_ed25519::signature_to_bytes(&to_sig), + ); + let address_map = &mut borrow_global_mut(@aptos_framework).address_map; + let expected_originating_address = table::borrow(address_map, new_address); + assert!(*expected_originating_address == alice_addr, 0); + assert!(borrow_global(alice_addr).authentication_key == new_auth_key, 0); + } + + #[test(account = @aptos_framework)] + public entry fun test_valid_rotate_authentication_key_multi_ed25519_to_ed25519(account: signer) acquires Account, OriginatingAddress { + initialize(&account); + + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let curr_pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let curr_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&curr_pk_unvalidated); + let alice_addr = from_bcs::to_address(curr_auth_key); + let alice = create_account_unchecked(alice_addr); + + let account_resource = borrow_global_mut(alice_addr); + + let (new_sk, new_pk) = ed25519::generate_keys(); + let new_pk_unvalidated = ed25519::public_key_to_unvalidated(&new_pk); + let new_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&new_pk_unvalidated); + let new_addr = from_bcs::to_address(new_auth_key); + + let challenge = RotationProofChallenge { + sequence_number: account_resource.sequence_number, + originator: alice_addr, + current_auth_key: alice_addr, + new_public_key: ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + }; + + let from_sig = multi_ed25519::sign_struct(&curr_sk, challenge); + let to_sig = ed25519::sign_struct(&new_sk, challenge); + + rotate_authentication_key( + &alice, + MULTI_ED25519_SCHEME, + multi_ed25519::unvalidated_public_key_to_bytes(&curr_pk_unvalidated), + ED25519_SCHEME, + ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + multi_ed25519::signature_to_bytes(&from_sig), + ed25519::signature_to_bytes(&to_sig), + ); + + let address_map = &mut borrow_global_mut(@aptos_framework).address_map; + let expected_originating_address = table::borrow(address_map, new_addr); + assert!(*expected_originating_address == alice_addr, 0); + assert!(borrow_global(alice_addr).authentication_key == new_auth_key, 0); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x20014, location = Self)] + public entry fun test_max_guid(account: &signer) acquires Account { + let addr = signer::address_of(account); + create_account_unchecked(addr); + let account_state = borrow_global_mut(addr); + account_state.guid_creation_num = MAX_GUID_CREATION_NUM - 1; + create_guid(account); + } + + #[test_only] + struct FakeCoin { } + #[test_only] + struct SadFakeCoin { } + + #[test(account = @0x1234)] + fun test_events(account: &signer) acquires Account { + let addr = signer::address_of(account); + create_account_unchecked(addr); + register_coin(addr); + + let eventhandle = &borrow_global(addr).coin_register_events; + let event = CoinRegisterEvent { type_info: type_info::type_of() }; + + let events = event::emitted_events_by_handle(eventhandle); + assert!(vector::length(&events) == 1, 0); + assert!(vector::borrow(&events, 0) == &event, 1); + assert!(event::was_event_emitted_by_handle(eventhandle, &event), 2); + + let event = CoinRegisterEvent { type_info: type_info::type_of() }; + assert!(!event::was_event_emitted_by_handle(eventhandle, &event), 3); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator.move new file mode 100644 index 0000000..9a0baaf --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator.move @@ -0,0 +1,48 @@ +/// This module provides an interface for aggregators. Aggregators are similar to +/// unsigned integers and support addition and subtraction (aborting on underflow +/// or on overflowing a custom upper limit). The difference from integers is that +/// aggregators allow to perform both additions and subtractions in parallel across +/// multiple transactions, enabling parallel execution. For example, if the first +/// transaction is doing `add(X, 1)` for aggregator resource `X`, and the second +/// is doing `sub(X,3)`, they can be executed in parallel avoiding a read-modify-write +/// dependency. +/// However, reading the aggregator value (i.e. calling `read(X)`) is an expensive +/// operation and should be avoided as much as possible because it reduces the +/// parallelism. Moreover, **aggregators can only be created by Aptos Framework (0x1) +/// at the moment.** +module aptos_framework::aggregator { + + /// The value of aggregator overflows. Raised by native code. + const EAGGREGATOR_OVERFLOW: u64 = 1; + + /// The value of aggregator underflows (goes below zero). Raised by native code. + const EAGGREGATOR_UNDERFLOW: u64 = 2; + + /// Aggregator feature is not supported. Raised by native code. + const ENOT_SUPPORTED: u64 = 3; + + /// Represents an integer which supports parallel additions and subtractions + /// across multiple transactions. See the module description for more details. + struct Aggregator has store { + handle: address, + key: address, + limit: u128, + } + + /// Returns `limit` exceeding which aggregator overflows. + public fun limit(aggregator: &Aggregator): u128 { + aggregator.limit + } + + /// Adds `value` to aggregator. Aborts on overflowing the limit. + public native fun add(aggregator: &mut Aggregator, value: u128); + + /// Subtracts `value` from aggregator. Aborts on going below zero. + public native fun sub(aggregator: &mut Aggregator, value: u128); + + /// Returns a value stored in this aggregator. + public native fun read(aggregator: &Aggregator): u128; + + /// Destroys an aggregator and removes it from its `AggregatorFactory`. + public native fun destroy(aggregator: Aggregator); +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_factory.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_factory.move new file mode 100644 index 0000000..f13cedd --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_factory.move @@ -0,0 +1,61 @@ +/// This module provides foundations to create aggregators. Currently only +/// Aptos Framework (0x1) can create them, so this module helps to wrap +/// the constructor of `Aggregator` struct so that only a system account +/// can initialize one. In the future, this might change and aggregators +/// can be enabled for the public. +module aptos_framework::aggregator_factory { + use std::error; + + use aptos_framework::system_addresses; + use aptos_framework::aggregator::Aggregator; + use aptos_std::table::{Self, Table}; + + friend aptos_framework::genesis; + friend aptos_framework::optional_aggregator; + + /// Aggregator factory is not published yet. + const EAGGREGATOR_FACTORY_NOT_FOUND: u64 = 1; + + /// Creates new aggregators. Used to control the numbers of aggregators in the + /// system and who can create them. At the moment, only Aptos Framework (0x1) + /// account can. + struct AggregatorFactory has key { + phantom_table: Table, + } + + /// Creates a new factory for aggregators. Can only be called during genesis. + public(friend) fun initialize_aggregator_factory(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let aggregator_factory = AggregatorFactory { + phantom_table: table::new() + }; + move_to(aptos_framework, aggregator_factory); + } + + /// Creates a new aggregator instance which overflows on exceeding a `limit`. + public(friend) fun create_aggregator_internal(limit: u128): Aggregator acquires AggregatorFactory { + assert!( + exists(@aptos_framework), + error::not_found(EAGGREGATOR_FACTORY_NOT_FOUND) + ); + + let aggregator_factory = borrow_global_mut(@aptos_framework); + new_aggregator(aggregator_factory, limit) + } + + /// This is currently a function closed for public. This can be updated in the future by on-chain governance + /// to allow any signer to call. + public fun create_aggregator(account: &signer, limit: u128): Aggregator acquires AggregatorFactory { + // Only Aptos Framework (0x1) account can call this for now. + system_addresses::assert_aptos_framework(account); + create_aggregator_internal(limit) + } + + /// Returns a new aggregator. + native fun new_aggregator(aggregator_factory: &mut AggregatorFactory, limit: u128): Aggregator; + + #[test_only] + public fun initialize_aggregator_factory_for_test(aptos_framework: &signer) { + initialize_aggregator_factory(aptos_framework); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_v2.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_v2.move new file mode 100644 index 0000000..68ce8d9 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aggregator_v2.move @@ -0,0 +1,97 @@ +/// This module provides an interface for aggregators (version 2). +/// Only skeleton - for AggregagtorSnapshot - is provided at this time, +/// to allow transition of usages. +module aptos_framework::aggregator_v2 { + use std::string::String; + + /// The generic type supplied to the aggregator snapshot is not supported. + const EUNSUPPORTED_AGGREGATOR_SNAPSHOT_TYPE: u64 = 5; + + /// The aggregator snapshots feature flag is not enabled. + const EAGGREGATOR_SNAPSHOTS_NOT_ENABLED: u64 = 6; + + struct AggregatorSnapshot has store, drop { + value: Element, + } + + public native fun create_snapshot(value: Element): AggregatorSnapshot; + + public native fun copy_snapshot(snapshot: &AggregatorSnapshot): AggregatorSnapshot; + + public native fun read_snapshot(snapshot: &AggregatorSnapshot): Element; + + public native fun string_concat(before: String, snapshot: &AggregatorSnapshot, after: String): AggregatorSnapshot; + + // #[test(fx = @std)] + // public fun test_correct_read(fx: &signer) { + // use std::features; + // let feature = features::get_aggregator_snapshots_feature(); + // features::change_feature_flags(fx, vector[feature], vector[]); + + // let snapshot = create_snapshot(42); + // let snapshot2 = copy_snapshot(&snapshot); + // assert!(read_snapshot(&snapshot) == 42, 0); + // assert!(read_snapshot(&snapshot2) == 42, 0); + // } + + // #[test(fx = @std)] + // public fun test_correct_read_string(fx: &signer) { + // use std::features; + // let feature = features::get_aggregator_snapshots_feature(); + // features::change_feature_flags(fx, vector[feature], vector[]); + + // let snapshot = create_snapshot(std::string::utf8(b"42")); + // let snapshot2 = copy_snapshot(&snapshot); + // assert!(read_snapshot(&snapshot) == std::string::utf8(b"42"), 0); + // assert!(read_snapshot(&snapshot2) == std::string::utf8(b"42"), 0); + // } + + // #[test(fx = @std)] + // public fun test_string_concat1(fx: &signer) { + // use std::features; + // let feature = features::get_aggregator_snapshots_feature(); + // features::change_feature_flags(fx, vector[feature], vector[]); + + // let snapshot = create_snapshot(42); + // let snapshot2 = string_concat(std::string::utf8(b"before"), &snapshot, std::string::utf8(b"after")); + // assert!(read_snapshot(&snapshot2) == std::string::utf8(b"before42after"), 0); + // } + + // #[test(fx = @std)] + // public fun test_string_concat2(fx: &signer) { + // use std::features; + // let feature = features::get_aggregator_snapshots_feature(); + // features::change_feature_flags(fx, vector[feature], vector[]); + + // let snapshot = create_snapshot(std::string::utf8(b"42")); + // let snapshot2 = string_concat(std::string::utf8(b"before"), &snapshot, std::string::utf8(b"after")); + // assert!(read_snapshot(&snapshot2) == std::string::utf8(b"before42after"), 0); + // } + + // #[test] + // #[expected_failure(abort_code = 0x030006, location = Self)] + // public fun test_snapshot_feature_not_enabled() { + // create_snapshot(42); + // } + + // #[test(fx = @std)] + // #[expected_failure(abort_code = 0x030005, location = Self)] + // public fun test_snpashot_invalid_type1(fx: &signer) { + // use std::features; + // use std::option; + // let feature = features::get_aggregator_snapshots_feature(); + // features::change_feature_flags(fx, vector[feature], vector[]); + + // create_snapshot(option::some(42)); + // } + + // #[test(fx = @std)] + // #[expected_failure(abort_code = 0x030005, location = Self)] + // public fun test_snpashot_invalid_type2(fx: &signer) { + // use std::features; + // let feature = features::get_aggregator_snapshots_feature(); + // features::change_feature_flags(fx, vector[feature], vector[]); + + // create_snapshot(vector[42]); + // } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_account.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_account.move new file mode 100644 index 0000000..c583957 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_account.move @@ -0,0 +1,336 @@ +module aptos_framework::aptos_account { + use aptos_framework::account::{Self, new_event_handle}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, Coin}; + use aptos_framework::create_signer::create_signer; + use aptos_framework::event::{EventHandle, emit_event}; + use std::error; + use std::signer; + use std::vector; + + friend aptos_framework::genesis; + friend aptos_framework::resource_account; + + /// Account does not exist. + const EACCOUNT_NOT_FOUND: u64 = 1; + /// Account is not registered to receive APT. + const EACCOUNT_NOT_REGISTERED_FOR_APT: u64 = 2; + /// Account opted out of receiving coins that they did not register to receive. + const EACCOUNT_DOES_NOT_ACCEPT_DIRECT_COIN_TRANSFERS: u64 = 3; + /// Account opted out of directly receiving NFT tokens. + const EACCOUNT_DOES_NOT_ACCEPT_DIRECT_TOKEN_TRANSFERS: u64 = 4; + /// The lengths of the recipients and amounts lists don't match. + const EMISMATCHING_RECIPIENTS_AND_AMOUNTS_LENGTH: u64 = 5; + + /// Configuration for whether an account can receive direct transfers of coins that they have not registered. + /// + /// By default, this is enabled. Users can opt-out by disabling at any time. + struct DirectTransferConfig has key { + allow_arbitrary_coin_transfers: bool, + update_coin_transfer_events: EventHandle, + } + + /// Event emitted when an account's direct coins transfer config is updated. + struct DirectCoinTransferConfigUpdatedEvent has drop, store { + new_allow_direct_transfers: bool, + } + + /////////////////////////////////////////////////////////////////////////// + /// Basic account creation methods. + /////////////////////////////////////////////////////////////////////////// + + public entry fun create_account(auth_key: address) { + let signer = account::create_account(auth_key); + coin::register(&signer); + } + + /// Batch version of APT transfer. + public entry fun batch_transfer(source: &signer, recipients: vector
, amounts: vector) { + let recipients_len = vector::length(&recipients); + assert!( + recipients_len == vector::length(&amounts), + error::invalid_argument(EMISMATCHING_RECIPIENTS_AND_AMOUNTS_LENGTH), + ); + + vector::enumerate_ref(&recipients, |i, to| { + let amount = *vector::borrow(&amounts, i); + transfer(source, *to, amount); + }); + } + + /// Convenient function to transfer APT to a recipient account that might not exist. + /// This would create the recipient account first, which also registers it to receive APT, before transferring. + public entry fun transfer(source: &signer, to: address, amount: u64) { + if (!account::exists_at(to)) { + create_account(to) + }; + // Resource accounts can be created without registering them to receive APT. + // This conveniently does the registration if necessary. + if (!coin::is_account_registered(to)) { + coin::register(&create_signer(to)); + }; + coin::transfer(source, to, amount) + } + + /// Batch version of transfer_coins. + public entry fun batch_transfer_coins( + from: &signer, recipients: vector
, amounts: vector) acquires DirectTransferConfig { + let recipients_len = vector::length(&recipients); + assert!( + recipients_len == vector::length(&amounts), + error::invalid_argument(EMISMATCHING_RECIPIENTS_AND_AMOUNTS_LENGTH), + ); + + vector::enumerate_ref(&recipients, |i, to| { + let amount = *vector::borrow(&amounts, i); + transfer_coins(from, *to, amount); + }); + } + + /// Convenient function to transfer a custom CoinType to a recipient account that might not exist. + /// This would create the recipient account first and register it to receive the CoinType, before transferring. + public entry fun transfer_coins(from: &signer, to: address, amount: u64) acquires DirectTransferConfig { + deposit_coins(to, coin::withdraw(from, amount)); + } + + /// Convenient function to deposit a custom CoinType into a recipient account that might not exist. + /// This would create the recipient account first and register it to receive the CoinType, before transferring. + public fun deposit_coins(to: address, coins: Coin) acquires DirectTransferConfig { + if (!account::exists_at(to)) { + create_account(to); + spec { + assert coin::is_account_registered(to); + assume aptos_std::type_info::type_of() == aptos_std::type_info::type_of() ==> + coin::is_account_registered(to); + }; + }; + if (!coin::is_account_registered(to)) { + assert!( + can_receive_direct_coin_transfers(to), + error::permission_denied(EACCOUNT_DOES_NOT_ACCEPT_DIRECT_COIN_TRANSFERS), + ); + coin::register(&create_signer(to)); + }; + coin::deposit(to, coins) + } + + public fun assert_account_exists(addr: address) { + assert!(account::exists_at(addr), error::not_found(EACCOUNT_NOT_FOUND)); + } + + public fun assert_account_is_registered_for_apt(addr: address) { + assert_account_exists(addr); + assert!(coin::is_account_registered(addr), error::not_found(EACCOUNT_NOT_REGISTERED_FOR_APT)); + } + + /// Set whether `account` can receive direct transfers of coins that they have not explicitly registered to receive. + public entry fun set_allow_direct_coin_transfers(account: &signer, allow: bool) acquires DirectTransferConfig { + let addr = signer::address_of(account); + if (exists(addr)) { + let direct_transfer_config = borrow_global_mut(addr); + // Short-circuit to avoid emitting an event if direct transfer config is not changing. + if (direct_transfer_config.allow_arbitrary_coin_transfers == allow) { + return + }; + + direct_transfer_config.allow_arbitrary_coin_transfers = allow; + emit_event( + &mut direct_transfer_config.update_coin_transfer_events, + DirectCoinTransferConfigUpdatedEvent { new_allow_direct_transfers: allow }); + } else { + let direct_transfer_config = DirectTransferConfig { + allow_arbitrary_coin_transfers: allow, + update_coin_transfer_events: new_event_handle(account), + }; + emit_event( + &mut direct_transfer_config.update_coin_transfer_events, + DirectCoinTransferConfigUpdatedEvent { new_allow_direct_transfers: allow }); + move_to(account, direct_transfer_config); + }; + } + + #[view] + /// Return true if `account` can receive direct transfers of coins that they have not explicitly registered to + /// receive. + /// + /// By default, this returns true if an account has not explicitly set whether the can receive direct transfers. + public fun can_receive_direct_coin_transfers(account: address): bool acquires DirectTransferConfig { + !exists(account) || + borrow_global(account).allow_arbitrary_coin_transfers + } + + #[test_only] + use aptos_std::from_bcs; + #[test_only] + use std::string::utf8; + #[test_only] + use aptos_framework::account::create_account_for_test; + + #[test_only] + struct FakeCoin {} + + #[test(alice = @0xa11ce, core = @0x1)] + public fun test_transfer(alice: &signer, core: &signer) { + let bob = from_bcs::to_address(x"0000000000000000000000000000000000000000000000000000000000000b0b"); + let carol = from_bcs::to_address(x"00000000000000000000000000000000000000000000000000000000000ca501"); + + let (burn_cap, mint_cap) = aptos_framework::aptos_coin::initialize_for_test(core); + create_account(signer::address_of(alice)); + coin::deposit(signer::address_of(alice), coin::mint(10000, &mint_cap)); + transfer(alice, bob, 500); + assert!(coin::balance(bob) == 500, 0); + transfer(alice, carol, 500); + assert!(coin::balance(carol) == 500, 1); + transfer(alice, carol, 1500); + assert!(coin::balance(carol) == 2000, 2); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(alice = @0xa11ce, core = @0x1)] + public fun test_transfer_to_resource_account(alice: &signer, core: &signer) { + let (resource_account, _) = account::create_resource_account(alice, vector[]); + let resource_acc_addr = signer::address_of(&resource_account); + assert!(!coin::is_account_registered(resource_acc_addr), 0); + + let (burn_cap, mint_cap) = aptos_framework::aptos_coin::initialize_for_test(core); + create_account(signer::address_of(alice)); + coin::deposit(signer::address_of(alice), coin::mint(10000, &mint_cap)); + transfer(alice, resource_acc_addr, 500); + assert!(coin::balance(resource_acc_addr) == 500, 1); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(from = @0x123, core = @0x1, recipient_1 = @0x124, recipient_2 = @0x125)] + public fun test_batch_transfer(from: &signer, core: &signer, recipient_1: &signer, recipient_2: &signer) { + let (burn_cap, mint_cap) = aptos_framework::aptos_coin::initialize_for_test(core); + create_account(signer::address_of(from)); + let recipient_1_addr = signer::address_of(recipient_1); + let recipient_2_addr = signer::address_of(recipient_2); + create_account(recipient_1_addr); + create_account(recipient_2_addr); + coin::deposit(signer::address_of(from), coin::mint(10000, &mint_cap)); + batch_transfer( + from, + vector[recipient_1_addr, recipient_2_addr], + vector[100, 500], + ); + assert!(coin::balance(recipient_1_addr) == 100, 0); + assert!(coin::balance(recipient_2_addr) == 500, 1); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(from = @0x1, to = @0x12)] + public fun test_direct_coin_transfers(from: &signer, to: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + create_account_for_test(signer::address_of(to)); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + // Recipient account did not explicit register for the coin. + let to_addr = signer::address_of(to); + transfer_coins(from, to_addr, 500); + assert!(coin::balance(to_addr) == 500, 0); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } + + #[test(from = @0x1, recipient_1 = @0x124, recipient_2 = @0x125)] + public fun test_batch_transfer_coins( + from: &signer, recipient_1: &signer, recipient_2: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + let recipient_1_addr = signer::address_of(recipient_1); + let recipient_2_addr = signer::address_of(recipient_2); + create_account_for_test(recipient_1_addr); + create_account_for_test(recipient_2_addr); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + batch_transfer_coins( + from, + vector[recipient_1_addr, recipient_2_addr], + vector[100, 500], + ); + assert!(coin::balance(recipient_1_addr) == 100, 0); + assert!(coin::balance(recipient_2_addr) == 500, 1); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } + + #[test(user = @0x123)] + public fun test_set_allow_direct_coin_transfers(user: &signer) acquires DirectTransferConfig { + let addr = signer::address_of(user); + create_account_for_test(addr); + set_allow_direct_coin_transfers(user, true); + assert!(can_receive_direct_coin_transfers(addr), 0); + set_allow_direct_coin_transfers(user, false); + assert!(!can_receive_direct_coin_transfers(addr), 1); + set_allow_direct_coin_transfers(user, true); + assert!(can_receive_direct_coin_transfers(addr), 2); + } + + #[test(from = @0x1, to = @0x12)] + public fun test_direct_coin_transfers_with_explicit_direct_coin_transfer_config( + from: &signer, to: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + create_account_for_test(signer::address_of(to)); + set_allow_direct_coin_transfers(from, true); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + // Recipient account did not explicit register for the coin. + let to_addr = signer::address_of(to); + transfer_coins(from, to_addr, 500); + assert!(coin::balance(to_addr) == 500, 0); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } + + #[test(from = @0x1, to = @0x12)] + #[expected_failure(abort_code = 0x50003, location = Self)] + public fun test_direct_coin_transfers_fail_if_recipient_opted_out( + from: &signer, to: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + create_account_for_test(signer::address_of(to)); + set_allow_direct_coin_transfers(from, false); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + // This should fail as the to account has explicitly opted out of receiving arbitrary coins. + transfer_coins(from, signer::address_of(to), 500); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_coin.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_coin.move new file mode 100644 index 0000000..c3e656e --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_coin.move @@ -0,0 +1,166 @@ +/// This module defines a minimal and generic Coin and Balance. +/// modified from https://github.com/move-language/move/tree/main/language/documentation/tutorial +module aptos_framework::aptos_coin { + use std::string; + use std::error; + use std::signer; + use std::vector; + use std::option::{Self, Option}; + + use aptos_framework::coin::{Self, BurnCapability, MintCapability}; + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + + /// Account does not have mint capability + const ENO_CAPABILITIES: u64 = 1; + /// Mint capability has already been delegated to this specified address + const EALREADY_DELEGATED: u64 = 2; + /// Cannot find delegation of mint capability to this account + const EDELEGATION_NOT_FOUND: u64 = 3; + + struct AptosCoin has key {} + + struct MintCapStore has key { + mint_cap: MintCapability, + } + + /// Delegation token created by delegator and can be claimed by the delegatee as MintCapability. + struct DelegatedMintCapability has store { + to: address + } + + /// The container stores the current pending delegations. + struct Delegations has key { + inner: vector, + } + + /// Can only called during genesis to initialize the Aptos coin. + public(friend) fun initialize(aptos_framework: &signer): (BurnCapability, MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + + let (burn_cap, freeze_cap, mint_cap) = coin::initialize_with_parallelizable_supply( + aptos_framework, + string::utf8(b"Aptos Coin"), + string::utf8(b"APT"), + 8, // decimals + true, // monitor_supply + ); + + // Aptos framework needs mint cap to mint coins to initial validators. This will be revoked once the validators + // have been initialized. + move_to(aptos_framework, MintCapStore { mint_cap }); + + coin::destroy_freeze_cap(freeze_cap); + (burn_cap, mint_cap) + } + + public fun has_mint_capability(account: &signer): bool { + exists(signer::address_of(account)) + } + + /// Only called during genesis to destroy the aptos framework account's mint capability once all initial validators + /// and accounts have been initialized during genesis. + public(friend) fun destroy_mint_cap(aptos_framework: &signer) acquires MintCapStore { + system_addresses::assert_aptos_framework(aptos_framework); + let MintCapStore { mint_cap } = move_from(@aptos_framework); + coin::destroy_mint_cap(mint_cap); + } + + /// Can only be called during genesis for tests to grant mint capability to aptos framework and core resources + /// accounts. + public(friend) fun configure_accounts_for_test( + aptos_framework: &signer, + core_resources: &signer, + mint_cap: MintCapability, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + // Mint the core resource account AptosCoin for gas so it can execute system transactions. + coin::register(core_resources); + let coins = coin::mint( + 18446744073709551615, + &mint_cap, + ); + coin::deposit(signer::address_of(core_resources), coins); + + move_to(core_resources, MintCapStore { mint_cap }); + move_to(core_resources, Delegations { inner: vector::empty() }); + } + + /// Only callable in tests and testnets where the core resources account exists. + /// Create new coins and deposit them into dst_addr's account. + public entry fun mint( + account: &signer, + dst_addr: address, + amount: u64, + ) acquires MintCapStore { + let account_addr = signer::address_of(account); + + assert!( + exists(account_addr), + error::not_found(ENO_CAPABILITIES), + ); + + let mint_cap = &borrow_global(account_addr).mint_cap; + let coins_minted = coin::mint(amount, mint_cap); + coin::deposit(dst_addr, coins_minted); + } + + /// Only callable in tests and testnets where the core resources account exists. + /// Create delegated token for the address so the account could claim MintCapability later. + public entry fun delegate_mint_capability(account: signer, to: address) acquires Delegations { + system_addresses::assert_core_resource(&account); + let delegations = &mut borrow_global_mut(@core_resources).inner; + vector::for_each_ref(delegations, |element| { + let element: &DelegatedMintCapability = element; + assert!(element.to != to, error::invalid_argument(EALREADY_DELEGATED)); + }); + vector::push_back(delegations, DelegatedMintCapability { to }); + } + + /// Only callable in tests and testnets where the core resources account exists. + /// Claim the delegated mint capability and destroy the delegated token. + public entry fun claim_mint_capability(account: &signer) acquires Delegations, MintCapStore { + let maybe_index = find_delegation(signer::address_of(account)); + assert!(option::is_some(&maybe_index), EDELEGATION_NOT_FOUND); + let idx = *option::borrow(&maybe_index); + let delegations = &mut borrow_global_mut(@core_resources).inner; + let DelegatedMintCapability { to: _ } = vector::swap_remove(delegations, idx); + + // Make a copy of mint cap and give it to the specified account. + let mint_cap = borrow_global(@core_resources).mint_cap; + move_to(account, MintCapStore { mint_cap }); + } + + fun find_delegation(addr: address): Option acquires Delegations { + let delegations = &borrow_global(@core_resources).inner; + let i = 0; + let len = vector::length(delegations); + let index = option::none(); + while (i < len) { + let element = vector::borrow(delegations, i); + if (element.to == addr) { + index = option::some(i); + break + }; + i = i + 1; + }; + index + } + + #[test_only] + use aptos_framework::aggregator_factory; + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer): (BurnCapability, MintCapability) { + aggregator_factory::initialize_aggregator_factory_for_test(aptos_framework); + initialize(aptos_framework) + } + + // This is particularly useful if the aggregator_factory is already initialized via another call path. + #[test_only] + public fun initialize_for_test_without_aggregator_factory(aptos_framework: &signer): (BurnCapability, MintCapability) { + initialize(aptos_framework) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_governance.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_governance.move new file mode 100644 index 0000000..6e88f73 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/aptos_governance.move @@ -0,0 +1,1183 @@ +/// +/// AptosGovernance represents the on-chain governance of the Aptos network. Voting power is calculated based on the +/// current epoch's voting power of the proposer or voter's backing stake pool. In addition, for it to count, +/// the stake pool's lockup needs to be at least as long as the proposal's duration. +/// +/// It provides the following flow: +/// 1. Proposers can create a proposal by calling AptosGovernance::create_proposal. The proposer's backing stake pool +/// needs to have the minimum proposer stake required. Off-chain components can subscribe to CreateProposalEvent to +/// track proposal creation and proposal ids. +/// 2. Voters can vote on a proposal. Their voting power is derived from the backing stake pool. A stake pool can vote +/// on a proposal multiple times as long as the total voting power of these votes doesn't exceed its total voting power. +module aptos_framework::aptos_governance { + use std::error; + use std::option; + use std::signer; + use std::string::{Self, String, utf8}; + use std::vector; + use std::features; + + use aptos_std::math64::min; + use aptos_std::simple_map::{Self, SimpleMap}; + use aptos_std::smart_table::{Self, SmartTable}; + use aptos_std::table::{Self, Table}; + + use aptos_framework::account::{Self, SignerCapability, create_signer_with_capability}; + use aptos_framework::coin; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::governance_proposal::{Self, GovernanceProposal}; + use aptos_framework::reconfiguration; + use aptos_framework::stake; + use aptos_framework::staking_config; + use aptos_framework::system_addresses; + use aptos_framework::aptos_coin::{Self, AptosCoin}; + use aptos_framework::timestamp; + use aptos_framework::voting; + + /// The specified stake pool does not have sufficient stake to create a proposal + const EINSUFFICIENT_PROPOSER_STAKE: u64 = 1; + /// This account is not the designated voter of the specified stake pool + const ENOT_DELEGATED_VOTER: u64 = 2; + /// The specified stake pool does not have long enough remaining lockup to create a proposal or vote + const EINSUFFICIENT_STAKE_LOCKUP: u64 = 3; + /// The specified stake pool has already been used to vote on the same proposal + const EALREADY_VOTED: u64 = 4; + /// The specified stake pool must be part of the validator set + const ENO_VOTING_POWER: u64 = 5; + /// Proposal is not ready to be resolved. Waiting on time or votes + const EPROPOSAL_NOT_RESOLVABLE_YET: u64 = 6; + /// The proposal has not been resolved yet + const EPROPOSAL_NOT_RESOLVED_YET: u64 = 8; + /// Metadata location cannot be longer than 256 chars + const EMETADATA_LOCATION_TOO_LONG: u64 = 9; + /// Metadata hash cannot be longer than 256 chars + const EMETADATA_HASH_TOO_LONG: u64 = 10; + /// Account is not authorized to call this function. + const EUNAUTHORIZED: u64 = 11; + /// The stake pool is using voting power more than it has. + const EVOTING_POWER_OVERFLOW: u64 = 12; + /// Partial voting feature hasn't been properly initialized. + const EPARTIAL_VOTING_NOT_INITIALIZED: u64 = 13; + /// The proposal in the argument is not a partial voting proposal. + const ENOT_PARTIAL_VOTING_PROPOSAL: u64 = 14; + + /// This matches the same enum const in voting. We have to duplicate it as Move doesn't have support for enums yet. + const PROPOSAL_STATE_SUCCEEDED: u64 = 1; + + const MAX_U64: u64 = 18446744073709551615; + + /// Proposal metadata attribute keys. + const METADATA_LOCATION_KEY: vector = b"metadata_location"; + const METADATA_HASH_KEY: vector = b"metadata_hash"; + + /// Store the SignerCapabilities of accounts under the on-chain governance's control. + struct GovernanceResponsbility has key { + signer_caps: SimpleMap, + } + + /// Configurations of the AptosGovernance, set during Genesis and can be updated by the same process offered + /// by this AptosGovernance module. + struct GovernanceConfig has key { + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + } + + struct RecordKey has copy, drop, store { + stake_pool: address, + proposal_id: u64, + } + + /// Records to track the proposals each stake pool has been used to vote on. + struct VotingRecords has key { + votes: Table + } + + /// Records to track the voting power usage of each stake pool on each proposal. + struct VotingRecordsV2 has key { + votes: SmartTable + } + + /// Used to track which execution script hashes have been approved by governance. + /// This is required to bypass cases where the execution scripts exceed the size limit imposed by mempool. + struct ApprovedExecutionHashes has key { + hashes: SimpleMap>, + } + + /// Events generated by interactions with the AptosGovernance module. + struct GovernanceEvents has key { + create_proposal_events: EventHandle, + update_config_events: EventHandle, + vote_events: EventHandle, + } + + /// Event emitted when a proposal is created. + struct CreateProposalEvent has drop, store { + proposer: address, + stake_pool: address, + proposal_id: u64, + execution_hash: vector, + proposal_metadata: SimpleMap>, + } + + /// Event emitted when there's a vote on a proposa; + struct VoteEvent has drop, store { + proposal_id: u64, + voter: address, + stake_pool: address, + num_votes: u64, + should_pass: bool, + } + + /// Event emitted when the governance configs are updated. + struct UpdateConfigEvent has drop, store { + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + } + + /// Can be called during genesis or by the governance itself. + /// Stores the signer capability for a given address. + public fun store_signer_cap( + aptos_framework: &signer, + signer_address: address, + signer_cap: SignerCapability, + ) acquires GovernanceResponsbility { + system_addresses::assert_aptos_framework(aptos_framework); + system_addresses::assert_framework_reserved(signer_address); + + if (!exists(@aptos_framework)) { + move_to(aptos_framework, GovernanceResponsbility { signer_caps: simple_map::create() }); + }; + + let signer_caps = &mut borrow_global_mut(@aptos_framework).signer_caps; + simple_map::add(signer_caps, signer_address, signer_cap); + } + + /// Initializes the state for Aptos Governance. Can only be called during Genesis with a signer + /// for the aptos_framework (0x1) account. + /// This function is private because it's called directly from the vm. + fun initialize( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + voting::register(aptos_framework); + move_to(aptos_framework, GovernanceConfig { + voting_duration_secs, + min_voting_threshold, + required_proposer_stake, + }); + move_to(aptos_framework, GovernanceEvents { + create_proposal_events: account::new_event_handle(aptos_framework), + update_config_events: account::new_event_handle(aptos_framework), + vote_events: account::new_event_handle(aptos_framework), + }); + move_to(aptos_framework, VotingRecords { + votes: table::new(), + }); + move_to(aptos_framework, ApprovedExecutionHashes { + hashes: simple_map::create>(), + }) + } + + /// Update the governance configurations. This can only be called as part of resolving a proposal in this same + /// AptosGovernance. + public fun update_governance_config( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) acquires GovernanceConfig, GovernanceEvents { + system_addresses::assert_aptos_framework(aptos_framework); + + let governance_config = borrow_global_mut(@aptos_framework); + governance_config.voting_duration_secs = voting_duration_secs; + governance_config.min_voting_threshold = min_voting_threshold; + governance_config.required_proposer_stake = required_proposer_stake; + + let events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut events.update_config_events, + UpdateConfigEvent { + min_voting_threshold, + required_proposer_stake, + voting_duration_secs + }, + ); + } + + /// Initializes the state for Aptos Governance partial voting. Can only be called through Aptos governance + /// proposals with a signer for the aptos_framework (0x1) account. + public fun initialize_partial_voting( + aptos_framework: &signer, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, VotingRecordsV2 { + votes: smart_table::new(), + }); + } + + #[view] + public fun get_voting_duration_secs(): u64 acquires GovernanceConfig { + borrow_global(@aptos_framework).voting_duration_secs + } + + #[view] + public fun get_min_voting_threshold(): u128 acquires GovernanceConfig { + borrow_global(@aptos_framework).min_voting_threshold + } + + #[view] + public fun get_required_proposer_stake(): u64 acquires GovernanceConfig { + borrow_global(@aptos_framework).required_proposer_stake + } + + #[view] + /// Return true if a stake pool has already voted on a proposal before partial governance voting is enabled. + public fun has_entirely_voted(stake_pool: address, proposal_id: u64): bool acquires VotingRecords { + let record_key = RecordKey { + stake_pool, + proposal_id, + }; + // If a stake pool has already voted on a proposal before partial governance voting is enabled, + // there is a record in VotingRecords. + let voting_records = borrow_global(@aptos_framework); + table::contains(&voting_records.votes, record_key) + } + + #[view] + /// Return remaining voting power of a stake pool on a proposal. + /// Note: a stake pool's voting power on a proposal could increase over time(e.g. rewards/new stake). + public fun get_remaining_voting_power(stake_pool: address, proposal_id: u64): u64 acquires VotingRecords, VotingRecordsV2 { + assert_voting_initialization(); + + let proposal_expiration = voting::get_proposal_expiration_secs(@aptos_framework, proposal_id); + let lockup_until = stake::get_lockup_secs(stake_pool); + // The voter's stake needs to be locked up at least as long as the proposal's expiration. + // Also no one can vote on a expired proposal. + if (proposal_expiration > lockup_until || timestamp::now_seconds() > proposal_expiration) { + return 0 + }; + + // If a stake pool has already voted on a proposal before partial governance voting is enabled, the stake pool + // cannot vote on the proposal even after partial governance voting is enabled. + if (has_entirely_voted(stake_pool, proposal_id)) { + return 0 + }; + let record_key = RecordKey { + stake_pool, + proposal_id, + }; + let used_voting_power = 0u64; + if (features::partial_governance_voting_enabled()) { + let voting_records_v2 = borrow_global(@aptos_framework); + used_voting_power = *smart_table::borrow_with_default(&voting_records_v2.votes, record_key, &0); + }; + get_voting_power(stake_pool) - used_voting_power + } + + /// Create a single-step proposal with the backing `stake_pool`. + /// @param execution_hash Required. This is the hash of the resolution script. When the proposal is resolved, + /// only the exact script with matching hash can be successfully executed. + public entry fun create_proposal( + proposer: &signer, + stake_pool: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + ) acquires GovernanceConfig, GovernanceEvents { + create_proposal_v2(proposer, stake_pool, execution_hash, metadata_location, metadata_hash, false); + } + + /// Create a single-step or multi-step proposal with the backing `stake_pool`. + /// @param execution_hash Required. This is the hash of the resolution script. When the proposal is resolved, + /// only the exact script with matching hash can be successfully executed. + public entry fun create_proposal_v2( + proposer: &signer, + stake_pool: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + is_multi_step_proposal: bool, + ) acquires GovernanceConfig, GovernanceEvents { + create_proposal_v2_impl(proposer, stake_pool, execution_hash, metadata_location, metadata_hash, is_multi_step_proposal); + } + + /// Create a single-step or multi-step proposal with the backing `stake_pool`. + /// @param execution_hash Required. This is the hash of the resolution script. When the proposal is resolved, + /// only the exact script with matching hash can be successfully executed. + /// Return proposal_id when a proposal is sucessfully created. + public fun create_proposal_v2_impl( + proposer: &signer, + stake_pool: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + is_multi_step_proposal: bool, + ): u64 acquires GovernanceConfig, GovernanceEvents { + let proposer_address = signer::address_of(proposer); + assert!(stake::get_delegated_voter(stake_pool) == proposer_address, error::invalid_argument(ENOT_DELEGATED_VOTER)); + + // The proposer's stake needs to be at least the required bond amount. + let governance_config = borrow_global(@aptos_framework); + let stake_balance = get_voting_power(stake_pool); + assert!( + stake_balance >= governance_config.required_proposer_stake, + error::invalid_argument(EINSUFFICIENT_PROPOSER_STAKE), + ); + + // The proposer's stake needs to be locked up at least as long as the proposal's voting period. + let current_time = timestamp::now_seconds(); + let proposal_expiration = current_time + governance_config.voting_duration_secs; + assert!( + stake::get_lockup_secs(stake_pool) >= proposal_expiration, + error::invalid_argument(EINSUFFICIENT_STAKE_LOCKUP), + ); + + // Create and validate proposal metadata. + let proposal_metadata = create_proposal_metadata(metadata_location, metadata_hash); + + // We want to allow early resolution of proposals if more than 50% of the total supply of the network coins + // has voted. This doesn't take into subsequent inflation/deflation (rewards are issued every epoch and gas fees + // are burnt after every transaction), but inflation/delation is very unlikely to have a major impact on total + // supply during the voting period. + let total_voting_token_supply = coin::supply(); + let early_resolution_vote_threshold = option::none(); + if (option::is_some(&total_voting_token_supply)) { + let total_supply = *option::borrow(&total_voting_token_supply); + // 50% + 1 to avoid rounding errors. + early_resolution_vote_threshold = option::some(total_supply / 2 + 1); + }; + + let proposal_id = voting::create_proposal_v2( + proposer_address, + @aptos_framework, + governance_proposal::create_proposal(), + execution_hash, + governance_config.min_voting_threshold, + proposal_expiration, + early_resolution_vote_threshold, + proposal_metadata, + is_multi_step_proposal, + ); + + let events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut events.create_proposal_events, + CreateProposalEvent { + proposal_id, + proposer: proposer_address, + stake_pool, + execution_hash, + proposal_metadata, + }, + ); + proposal_id + } + + /// Vote on proposal with `proposal_id` and all voting power from `stake_pool`. + public entry fun vote( + voter: &signer, + stake_pool: address, + proposal_id: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, GovernanceEvents, VotingRecords, VotingRecordsV2 { + vote_internal(voter, stake_pool, proposal_id, MAX_U64, should_pass); + } + + /// Vote on proposal with `proposal_id` and specified voting power from `stake_pool`. + public entry fun partial_vote( + voter: &signer, + stake_pool: address, + proposal_id: u64, + voting_power: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, GovernanceEvents, VotingRecords, VotingRecordsV2 { + vote_internal(voter, stake_pool, proposal_id, voting_power, should_pass); + } + + /// Vote on proposal with `proposal_id` and specified voting_power from `stake_pool`. + /// If voting_power is more than all the left voting power of `stake_pool`, use all the left voting power. + /// If a stake pool has already voted on a proposal before partial governance voting is enabled, the stake pool + /// cannot vote on the proposal even after partial governance voting is enabled. + fun vote_internal( + voter: &signer, + stake_pool: address, + proposal_id: u64, + voting_power: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, GovernanceEvents, VotingRecords, VotingRecordsV2 { + let voter_address = signer::address_of(voter); + assert!(stake::get_delegated_voter(stake_pool) == voter_address, error::invalid_argument(ENOT_DELEGATED_VOTER)); + + // The voter's stake needs to be locked up at least as long as the proposal's expiration. + let proposal_expiration = voting::get_proposal_expiration_secs(@aptos_framework, proposal_id); + assert!( + stake::get_lockup_secs(stake_pool) >= proposal_expiration, + error::invalid_argument(EINSUFFICIENT_STAKE_LOCKUP), + ); + + // If a stake pool has already voted on a proposal before partial governance voting is enabled, + // `get_remaining_voting_power` returns 0. + let staking_pool_voting_power = get_remaining_voting_power(stake_pool, proposal_id); + voting_power= min(voting_power, staking_pool_voting_power); + + // Short-circuit if the voter has no voting power. + assert!(voting_power > 0, error::invalid_argument(ENO_VOTING_POWER)); + + voting::vote( + &governance_proposal::create_empty_proposal(), + @aptos_framework, + proposal_id, + voting_power, + should_pass, + ); + + let record_key = RecordKey { + stake_pool, + proposal_id, + }; + if (features::partial_governance_voting_enabled()) { + let voting_records_v2 = borrow_global_mut(@aptos_framework); + let used_voting_power = smart_table::borrow_mut_with_default(&mut voting_records_v2.votes, record_key, 0); + // This calculation should never overflow because the used voting cannot exceed the total voting power of this stake pool. + *used_voting_power = *used_voting_power + voting_power; + } else { + let voting_records = borrow_global_mut(@aptos_framework); + assert!( + !table::contains(&voting_records.votes, record_key), + error::invalid_argument(EALREADY_VOTED)); + table::add(&mut voting_records.votes, record_key, true); + }; + + let events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut events.vote_events, + VoteEvent { + proposal_id, + voter: voter_address, + stake_pool, + num_votes: voting_power, + should_pass, + }, + ); + + let proposal_state = voting::get_proposal_state(@aptos_framework, proposal_id); + if (proposal_state == PROPOSAL_STATE_SUCCEEDED) { + add_approved_script_hash(proposal_id); + } + } + + public entry fun add_approved_script_hash_script(proposal_id: u64) acquires ApprovedExecutionHashes { + add_approved_script_hash(proposal_id) + } + + /// Add the execution script hash of a successful governance proposal to the approved list. + /// This is needed to bypass the mempool transaction size limit for approved governance proposal transactions that + /// are too large (e.g. module upgrades). + public fun add_approved_script_hash(proposal_id: u64) acquires ApprovedExecutionHashes { + let approved_hashes = borrow_global_mut(@aptos_framework); + + // Ensure the proposal can be resolved. + let proposal_state = voting::get_proposal_state(@aptos_framework, proposal_id); + assert!(proposal_state == PROPOSAL_STATE_SUCCEEDED, error::invalid_argument(EPROPOSAL_NOT_RESOLVABLE_YET)); + + let execution_hash = voting::get_execution_hash(@aptos_framework, proposal_id); + + // If this is a multi-step proposal, the proposal id will already exist in the ApprovedExecutionHashes map. + // We will update execution hash in ApprovedExecutionHashes to be the next_execution_hash. + if (simple_map::contains_key(&approved_hashes.hashes, &proposal_id)) { + let current_execution_hash = simple_map::borrow_mut(&mut approved_hashes.hashes, &proposal_id); + *current_execution_hash = execution_hash; + } else { + simple_map::add(&mut approved_hashes.hashes, proposal_id, execution_hash); + } + } + + /// Resolve a successful single-step proposal. This would fail if the proposal is not successful (not enough votes or more no + /// than yes). + public fun resolve(proposal_id: u64, signer_address: address): signer acquires ApprovedExecutionHashes, GovernanceResponsbility { + voting::resolve(@aptos_framework, proposal_id); + remove_approved_hash(proposal_id); + get_signer(signer_address) + } + + /// Resolve a successful multi-step proposal. This would fail if the proposal is not successful. + public fun resolve_multi_step_proposal(proposal_id: u64, signer_address: address, next_execution_hash: vector): signer acquires GovernanceResponsbility, ApprovedExecutionHashes { + voting::resolve_proposal_v2(@aptos_framework, proposal_id, next_execution_hash); + // If the current step is the last step of this multi-step proposal, + // we will remove the execution hash from the ApprovedExecutionHashes map. + if (vector::length(&next_execution_hash) == 0) { + remove_approved_hash(proposal_id); + } else { + // If the current step is not the last step of this proposal, + // we replace the current execution hash with the next execution hash + // in the ApprovedExecutionHashes map. + add_approved_script_hash(proposal_id) + }; + get_signer(signer_address) + } + + /// Remove an approved proposal's execution script hash. + public fun remove_approved_hash(proposal_id: u64) acquires ApprovedExecutionHashes { + assert!( + voting::is_resolved(@aptos_framework, proposal_id), + error::invalid_argument(EPROPOSAL_NOT_RESOLVED_YET), + ); + + let approved_hashes = &mut borrow_global_mut(@aptos_framework).hashes; + if (simple_map::contains_key(approved_hashes, &proposal_id)) { + simple_map::remove(approved_hashes, &proposal_id); + }; + } + + /// Force reconfigure. To be called at the end of a proposal that alters on-chain configs. + public fun reconfigure(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + reconfiguration::reconfigure(); + } + + /// Update feature flags and also trigger reconfiguration. + public fun toggle_features(aptos_framework: &signer, enable: vector, disable: vector) { + system_addresses::assert_aptos_framework(aptos_framework); + features::change_feature_flags(aptos_framework, enable, disable); + reconfiguration::reconfigure(); + } + + /// Only called in testnet where the core resources account exists and has been granted power to mint Aptos coins. + public fun get_signer_testnet_only( + core_resources: &signer, signer_address: address): signer acquires GovernanceResponsbility { + system_addresses::assert_core_resource(core_resources); + // Core resources account only has mint capability in tests/testnets. + assert!(aptos_coin::has_mint_capability(core_resources), error::unauthenticated(EUNAUTHORIZED)); + get_signer(signer_address) + } + + #[view] + /// Return the voting power a stake pool has with respect to governance proposals. + public fun get_voting_power(pool_address: address): u64 { + let allow_validator_set_change = staking_config::get_allow_validator_set_change(&staking_config::get()); + if (allow_validator_set_change) { + let (active, _, pending_active, pending_inactive) = stake::get_stake(pool_address); + // We calculate the voting power as total non-inactive stakes of the pool. Even if the validator is not in the + // active validator set, as long as they have a lockup (separately checked in create_proposal and voting), their + // stake would still count in their voting power for governance proposals. + active + pending_active + pending_inactive + } else { + stake::get_current_epoch_voting_power(pool_address) + } + } + + /// Return a signer for making changes to 0x1 as part of on-chain governance proposal process. + fun get_signer(signer_address: address): signer acquires GovernanceResponsbility { + let governance_responsibility = borrow_global(@aptos_framework); + let signer_cap = simple_map::borrow(&governance_responsibility.signer_caps, &signer_address); + create_signer_with_capability(signer_cap) + } + + fun create_proposal_metadata(metadata_location: vector, metadata_hash: vector): SimpleMap> { + assert!(string::length(&utf8(metadata_location)) <= 256, error::invalid_argument(EMETADATA_LOCATION_TOO_LONG)); + assert!(string::length(&utf8(metadata_hash)) <= 256, error::invalid_argument(EMETADATA_HASH_TOO_LONG)); + + let metadata = simple_map::create>(); + simple_map::add(&mut metadata, utf8(METADATA_LOCATION_KEY), metadata_location); + simple_map::add(&mut metadata, utf8(METADATA_HASH_KEY), metadata_hash); + metadata + } + + fun assert_voting_initialization() { + if (features::partial_governance_voting_enabled()) { + assert!(exists(@aptos_framework), error::invalid_state(EPARTIAL_VOTING_NOT_INITIALIZED)); + }; + } + + #[test_only] + public entry fun create_proposal_for_test( + proposer: &signer, + multi_step: bool, + ) acquires GovernanceConfig, GovernanceEvents { + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + if (multi_step) { + create_proposal_v2( + proposer, + signer::address_of(proposer), + execution_hash, + b"", + b"", + true, + ); + } else { + create_proposal( + proposer, + signer::address_of(proposer), + execution_hash, + b"", + b"", + ); + }; + } + + #[test_only] + public entry fun resolve_proposal_for_test(proposal_id: u64, signer_address: address, multi_step: bool, finish_multi_step_execution: bool): signer acquires ApprovedExecutionHashes, GovernanceResponsbility { + if (multi_step) { + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + + if (finish_multi_step_execution) { + resolve_multi_step_proposal(proposal_id, signer_address, vector::empty()) + } else { + resolve_multi_step_proposal(proposal_id, signer_address, execution_hash) + } + } else { + resolve(proposal_id, signer_address) + } + } + + #[test_only] + /// Force reconfigure. To be called at the end of a proposal that alters on-chain configs. + public fun toggle_features_for_test(enable: vector, disable: vector) { + toggle_features(&account::create_signer_for_test(@0x1), enable, disable); + } + + #[test_only] + public entry fun test_voting_generic( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + multi_step: bool, + use_generic_resolve_function: bool, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_voting(&aptos_framework, &proposer, &yes_voter, &no_voter); + + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + + create_proposal_for_test(&proposer, multi_step); + + vote(&yes_voter, signer::address_of(&yes_voter), 0, true); + vote(&no_voter, signer::address_of(&no_voter), 0, false); + + test_resolving_proposal_generic(aptos_framework, use_generic_resolve_function, execution_hash); + } + + #[test_only] + public entry fun test_resolving_proposal_generic( + aptos_framework: signer, + use_generic_resolve_function: bool, + execution_hash: vector, + ) acquires ApprovedExecutionHashes, GovernanceResponsbility { + // Once expiration time has passed, the proposal should be considered resolve now as there are more yes votes + // than no. + timestamp::update_global_time_for_test(100001000000); + let proposal_state = voting::get_proposal_state(signer::address_of(&aptos_framework), 0); + assert!(proposal_state == PROPOSAL_STATE_SUCCEEDED, proposal_state); + + // Add approved script hash. + add_approved_script_hash(0); + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(*simple_map::borrow(&approved_hashes, &0) == execution_hash, 0); + + // Resolve the proposal. + let account = resolve_proposal_for_test(0, @aptos_framework, use_generic_resolve_function, true); + assert!(signer::address_of(&account) == @aptos_framework, 1); + assert!(voting::is_resolved(@aptos_framework, 0), 2); + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(!simple_map::contains_key(&approved_hashes, &0), 3); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_voting( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, false, false); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_voting_multi_step( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, true, true); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + #[expected_failure(abort_code=0x5000a, location = aptos_framework::voting)] + public entry fun test_voting_multi_step_cannot_use_single_step_resolve( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, true, false); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_voting_single_step_can_use_generic_resolve_function( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, false, true); + } + + #[test_only] + public entry fun test_can_remove_approved_hash_if_executed_directly_via_voting_generic( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + multi_step: bool, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_voting(&aptos_framework, &proposer, &yes_voter, &no_voter); + + create_proposal_for_test(&proposer, multi_step); + vote(&yes_voter, signer::address_of(&yes_voter), 0, true); + vote(&no_voter, signer::address_of(&no_voter), 0, false); + + // Add approved script hash. + timestamp::update_global_time_for_test(100001000000); + add_approved_script_hash(0); + + // Resolve the proposal. + if (multi_step) { + let execution_hash = vector::empty(); + let next_execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + voting::resolve_proposal_v2(@aptos_framework, 0, next_execution_hash); + assert!(voting::is_resolved(@aptos_framework, 0), 0); + if (vector::length(&next_execution_hash) == 0) { + remove_approved_hash(0); + } else { + add_approved_script_hash(0) + }; + } else { + voting::resolve(@aptos_framework, 0); + assert!(voting::is_resolved(@aptos_framework, 0), 0); + remove_approved_hash(0); + }; + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(!simple_map::contains_key(&approved_hashes, &0), 1); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_can_remove_approved_hash_if_executed_directly_via_voting( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + test_can_remove_approved_hash_if_executed_directly_via_voting_generic(aptos_framework, proposer, yes_voter, no_voter, false); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_can_remove_approved_hash_if_executed_directly_via_voting_multi_step( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + test_can_remove_approved_hash_if_executed_directly_via_voting_generic(aptos_framework, proposer, yes_voter, no_voter, true); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + #[expected_failure(abort_code = 0x10004, location = aptos_framework::voting)] + public entry fun test_cannot_double_vote( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + + create_proposal( + &proposer, + signer::address_of(&proposer), + b"", + b"", + b"", + ); + + // Double voting should throw an error. + vote(&voter_1, signer::address_of(&voter_1), 0, true); + vote(&voter_1, signer::address_of(&voter_1), 0, true); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + #[expected_failure(abort_code = 0x10004, location = aptos_framework::voting)] + public entry fun test_cannot_double_vote_with_different_voter_addresses( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + + create_proposal( + &proposer, + signer::address_of(&proposer), + b"", + b"", + b"", + ); + + // Double voting should throw an error for 2 different voters if they still use the same stake pool. + vote(&voter_1, signer::address_of(&voter_1), 0, true); + stake::set_delegated_voter(&voter_1, signer::address_of(&voter_2)); + vote(&voter_2, signer::address_of(&voter_1), 0, true); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_stake_pool_can_vote_on_partial_voting_proposal_many_times( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + + partial_vote(&voter_1, voter_1_addr, 0, 5, true); + partial_vote(&voter_1, voter_1_addr, 0, 3, true); + partial_vote(&voter_1, voter_1_addr, 0, 2, true); + + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 10, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + #[expected_failure(abort_code = 0x3, location = Self)] + public entry fun test_stake_pool_can_vote_with_partial_voting_power( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + + partial_vote(&voter_1, voter_1_addr, 0, 9, true); + + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 11, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + // No enough Yes. The proposal cannot be resolved. + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_stake_pool_can_vote_only_with_its_own_voting_power( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + + partial_vote(&voter_1, voter_1_addr, 0, 9, true); + // The total voting power of voter_1 is 20. It can only vote with 20 voting power even we pass 30 as the argument. + partial_vote(&voter_1, voter_1_addr, 0, 30, true); + + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_stake_pool_can_vote_before_and_after_partial_governance_voting_enabled( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + vote(&voter_1, voter_1_addr, 0, true); + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + initialize_partial_voting(&aptos_framework); + features::change_feature_flags(&aptos_framework, vector[features::get_partial_governance_voting()], vector[]); + + coin::register(&voter_1); + coin::register(&voter_2); + stake::add_stake(&voter_1, 20); + stake::add_stake(&voter_2, 5); + + // voter1 has already voted before partial governance voting is enalbed. So it cannot vote even after adding stake. + // voter2's voting poewr increase after adding stake. + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 15, 2); + + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_no_remaining_voting_power_about_proposal_expiration_time( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires GovernanceConfig, GovernanceEvents, GovernanceResponsbility, VotingRecords, VotingRecordsV2 { + setup_voting_with_initialized_stake(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 0, 2); + + // 500 seconds later, lockup period of voter_1 and voter_2 is reset. + timestamp::fast_forward_seconds(440); + stake::end_epoch(); + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 20, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + // 501 seconds later, the proposal expires. + timestamp::fast_forward_seconds(441); + stake::end_epoch(); + assert!(get_remaining_voting_power(proposer_addr, 0) == 0, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 0, 2); + } + + #[test_only] + public fun setup_voting( + aptos_framework: &signer, + proposer: &signer, + yes_voter: &signer, + no_voter: &signer, + ) acquires GovernanceResponsbility { + use std::vector; + use aptos_framework::account; + use aptos_framework::coin; + use aptos_framework::aptos_coin::{Self, AptosCoin}; + + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(signer::address_of(aptos_framework)); + account::create_account_for_test(signer::address_of(proposer)); + account::create_account_for_test(signer::address_of(yes_voter)); + account::create_account_for_test(signer::address_of(no_voter)); + + // Initialize the governance. + staking_config::initialize_for_test(aptos_framework, 0, 1000, 2000, true, 0, 1, 100); + initialize(aptos_framework, 10, 100, 1000); + store_signer_cap( + aptos_framework, + @aptos_framework, + account::create_test_signer_cap(@aptos_framework), + ); + + // Initialize the stake pools for proposer and voters. + let active_validators = vector::empty
(); + vector::push_back(&mut active_validators, signer::address_of(proposer)); + vector::push_back(&mut active_validators, signer::address_of(yes_voter)); + vector::push_back(&mut active_validators, signer::address_of(no_voter)); + let (_sk_1, pk_1, _pop_1) = stake::generate_identity(); + let (_sk_2, pk_2, _pop_2) = stake::generate_identity(); + let (_sk_3, pk_3, _pop_3) = stake::generate_identity(); + let pks = vector[pk_1, pk_2, pk_3]; + stake::create_validator_set(aptos_framework, active_validators, pks); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + // Spread stake among active and pending_inactive because both need to be accounted for when computing voting + // power. + coin::register(proposer); + coin::deposit(signer::address_of(proposer), coin::mint(100, &mint_cap)); + coin::register(yes_voter); + coin::deposit(signer::address_of(yes_voter), coin::mint(20, &mint_cap)); + coin::register(no_voter); + coin::deposit(signer::address_of(no_voter), coin::mint(10, &mint_cap)); + stake::create_stake_pool(proposer, coin::mint(50, &mint_cap), coin::mint(50, &mint_cap), 10000); + stake::create_stake_pool(yes_voter, coin::mint(10, &mint_cap), coin::mint(10, &mint_cap), 10000); + stake::create_stake_pool(no_voter, coin::mint(5, &mint_cap), coin::mint(5, &mint_cap), 10000); + coin::destroy_mint_cap(mint_cap); + coin::destroy_burn_cap(burn_cap); + } + + #[test_only] + public fun setup_voting_with_initialized_stake( + aptos_framework: &signer, + proposer: &signer, + yes_voter: &signer, + no_voter: &signer, + ) acquires GovernanceResponsbility { + use aptos_framework::account; + use aptos_framework::coin; + use aptos_framework::aptos_coin::AptosCoin; + + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(signer::address_of(aptos_framework)); + account::create_account_for_test(signer::address_of(proposer)); + account::create_account_for_test(signer::address_of(yes_voter)); + account::create_account_for_test(signer::address_of(no_voter)); + + // Initialize the governance. + stake::initialize_for_test_custom(aptos_framework, 0, 1000, 2000, true, 0, 1, 1000); + initialize(aptos_framework, 10, 100, 1000); + store_signer_cap( + aptos_framework, + @aptos_framework, + account::create_test_signer_cap(@aptos_framework), + ); + + // Initialize the stake pools for proposer and voters. + // Spread stake among active and pending_inactive because both need to be accounted for when computing voting + // power. + coin::register(proposer); + coin::deposit(signer::address_of(proposer), stake::mint_coins(100)); + coin::register(yes_voter); + coin::deposit(signer::address_of(yes_voter), stake::mint_coins(20)); + coin::register(no_voter); + coin::deposit(signer::address_of(no_voter), stake::mint_coins(10)); + + let (_sk_1, pk_1, pop_1) = stake::generate_identity(); + let (_sk_2, pk_2, pop_2) = stake::generate_identity(); + let (_sk_3, pk_3, pop_3) = stake::generate_identity(); + stake::initialize_test_validator(&pk_2, &pop_2, yes_voter, 20, true, false); + stake::initialize_test_validator(&pk_3, &pop_3, no_voter, 10, true, false); + stake::end_epoch(); + timestamp::fast_forward_seconds(1440); + stake::initialize_test_validator(&pk_1, &pop_1, proposer, 100, true, false); + stake::end_epoch(); + } + + #[test_only] + public fun setup_partial_voting( + aptos_framework: &signer, + proposer: &signer, + voter_1: &signer, + voter_2: &signer, + ) acquires GovernanceResponsbility { + initialize_partial_voting(aptos_framework); + features::change_feature_flags(aptos_framework, vector[features::get_partial_governance_voting()], vector[]); + setup_voting(aptos_framework, proposer, voter_1, voter_2); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_update_governance_config( + aptos_framework: signer, + ) acquires GovernanceConfig, GovernanceEvents { + account::create_account_for_test(signer::address_of(&aptos_framework)); + initialize(&aptos_framework, 1, 2, 3); + update_governance_config(&aptos_framework, 10, 20, 30); + + let config = borrow_global(@aptos_framework); + assert!(config.min_voting_threshold == 10, 0); + assert!(config.required_proposer_stake == 20, 1); + assert!(config.voting_duration_secs == 30, 3); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_governance_config_unauthorized_should_fail( + account: signer) acquires GovernanceConfig, GovernanceEvents { + initialize(&account, 1, 2, 3); + update_governance_config(&account, 10, 20, 30); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_replace_execution_hash( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires GovernanceResponsbility, GovernanceConfig, GovernanceEvents, ApprovedExecutionHashes, VotingRecords, VotingRecordsV2 { + setup_voting(&aptos_framework, &proposer, &yes_voter, &no_voter); + + create_proposal_for_test(&proposer, true); + vote(&yes_voter, signer::address_of(&yes_voter), 0, true); + vote(&no_voter, signer::address_of(&no_voter), 0, false); + + // Add approved script hash. + timestamp::update_global_time_for_test(100001000000); + add_approved_script_hash(0); + + // Resolve the proposal. + let execution_hash = vector::empty(); + let next_execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + vector::push_back(&mut next_execution_hash, 10); + + voting::resolve_proposal_v2(@aptos_framework, 0, next_execution_hash); + + if (vector::length(&next_execution_hash) == 0) { + remove_approved_hash(0); + } else { + add_approved_script_hash(0) + }; + + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(*simple_map::borrow(&approved_hashes, &0) == vector[10u8,], 1); + } + + #[test_only] + public fun initialize_for_test( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) { + initialize(aptos_framework, min_voting_threshold, required_proposer_stake, voting_duration_secs); + } + + #[verify_only] + public fun initialize_for_verification( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) { + initialize(aptos_framework, min_voting_threshold, required_proposer_stake, voting_duration_secs); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/block.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/block.move new file mode 100644 index 0000000..ad5bec4 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/block.move @@ -0,0 +1,242 @@ +/// This module defines a struct storing the metadata of the block and new block events. +module aptos_framework::block { + use std::error; + use std::features; + use std::vector; + use std::option; + + use aptos_framework::account; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::reconfiguration; + use aptos_framework::stake; + use aptos_framework::state_storage; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use aptos_framework::transaction_fee; + + friend aptos_framework::genesis; + + const MAX_U64: u64 = 18446744073709551615; + + /// Should be in-sync with BlockResource rust struct in new_block.rs + struct BlockResource has key { + /// Height of the current block + height: u64, + /// Time period between epochs. + epoch_interval: u64, + /// Handle where events with the time of new blocks are emitted + new_block_events: EventHandle, + update_epoch_interval_events: EventHandle, + } + + /// Should be in-sync with NewBlockEvent rust struct in new_block.rs + struct NewBlockEvent has drop, store { + hash: address, + epoch: u64, + round: u64, + height: u64, + previous_block_votes_bitvec: vector, + proposer: address, + failed_proposer_indices: vector, + /// On-chain time during the block at the given height + time_microseconds: u64, + } + + /// Event emitted when a proposal is created. + struct UpdateEpochIntervalEvent has drop, store { + old_epoch_interval: u64, + new_epoch_interval: u64, + } + + /// The number of new block events does not equal the current block height. + const ENUM_NEW_BLOCK_EVENTS_DOES_NOT_MATCH_BLOCK_HEIGHT: u64 = 1; + /// An invalid proposer was provided. Expected the proposer to be the VM or an active validator. + const EINVALID_PROPOSER: u64 = 2; + /// Epoch interval cannot be 0. + const EZERO_EPOCH_INTERVAL: u64 = 3; + + /// This can only be called during Genesis. + public(friend) fun initialize(aptos_framework: &signer, epoch_interval_microsecs: u64) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(epoch_interval_microsecs > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL)); + + move_to( + aptos_framework, + BlockResource { + height: 0, + epoch_interval: epoch_interval_microsecs, + new_block_events: account::new_event_handle(aptos_framework), + update_epoch_interval_events: account::new_event_handle(aptos_framework), + } + ); + } + + /// Update the epoch interval. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_epoch_interval_microsecs( + aptos_framework: &signer, + new_epoch_interval: u64, + ) acquires BlockResource { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(new_epoch_interval > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL)); + + let block_resource = borrow_global_mut(@aptos_framework); + let old_epoch_interval = block_resource.epoch_interval; + block_resource.epoch_interval = new_epoch_interval; + + event::emit_event( + &mut block_resource.update_epoch_interval_events, + UpdateEpochIntervalEvent { old_epoch_interval, new_epoch_interval }, + ); + } + + #[view] + /// Return epoch interval in seconds. + public fun get_epoch_interval_secs(): u64 acquires BlockResource { + borrow_global(@aptos_framework).epoch_interval / 1000000 + } + + /// Set the metadata for the current block. + /// The runtime always runs this before executing the transactions in a block. + fun block_prologue( + vm: signer, + hash: address, + epoch: u64, + round: u64, + proposer: address, + failed_proposer_indices: vector, + previous_block_votes_bitvec: vector, + timestamp: u64 + ) acquires BlockResource { + // Operational constraint: can only be invoked by the VM. + system_addresses::assert_vm(&vm); + + // Blocks can only be produced by a valid proposer or by the VM itself for Nil blocks (no user txs). + assert!( + proposer == @vm_reserved || stake::is_current_epoch_validator(proposer), + error::permission_denied(EINVALID_PROPOSER), + ); + + let proposer_index = option::none(); + if (proposer != @vm_reserved) { + proposer_index = option::some(stake::get_validator_index(proposer)); + }; + + let block_metadata_ref = borrow_global_mut(@aptos_framework); + block_metadata_ref.height = event::counter(&block_metadata_ref.new_block_events); + + let new_block_event = NewBlockEvent { + hash, + epoch, + round, + height: block_metadata_ref.height, + previous_block_votes_bitvec, + proposer, + failed_proposer_indices, + time_microseconds: timestamp, + }; + emit_new_block_event(&vm, &mut block_metadata_ref.new_block_events, new_block_event); + + if (features::collect_and_distribute_gas_fees()) { + // Assign the fees collected from the previous block to the previous block proposer. + // If for any reason the fees cannot be assigned, this function burns the collected coins. + transaction_fee::process_collected_fees(); + // Set the proposer of this block as the receiver of the fees, so that the fees for this + // block are assigned to the right account. + transaction_fee::register_proposer_for_fee_collection(proposer); + }; + + // Performance scores have to be updated before the epoch transition as the transaction that triggers the + // transition is the last block in the previous epoch. + stake::update_performance_statistics(proposer_index, failed_proposer_indices); + state_storage::on_new_block(reconfiguration::current_epoch()); + + if (timestamp - reconfiguration::last_reconfiguration_time() >= block_metadata_ref.epoch_interval) { + reconfiguration::reconfigure(); + }; + } + + #[view] + /// Get the current block height + public fun get_current_block_height(): u64 acquires BlockResource { + borrow_global(@aptos_framework).height + } + + /// Emit the event and update height and global timestamp + fun emit_new_block_event(vm: &signer, event_handle: &mut EventHandle, new_block_event: NewBlockEvent) { + timestamp::update_global_time(vm, new_block_event.proposer, new_block_event.time_microseconds); + assert!( + event::counter(event_handle) == new_block_event.height, + error::invalid_argument(ENUM_NEW_BLOCK_EVENTS_DOES_NOT_MATCH_BLOCK_HEIGHT), + ); + event::emit_event(event_handle, new_block_event); + } + + /// Emit a `NewBlockEvent` event. This function will be invoked by genesis directly to generate the very first + /// reconfiguration event. + fun emit_genesis_block_event(vm: signer) acquires BlockResource { + let block_metadata_ref = borrow_global_mut(@aptos_framework); + let genesis_id = @0x0; + emit_new_block_event( + &vm, + &mut block_metadata_ref.new_block_events, + NewBlockEvent { + hash: genesis_id, + epoch: 0, + round: 0, + height: 0, + previous_block_votes_bitvec: vector::empty(), + proposer: @vm_reserved, + failed_proposer_indices: vector::empty(), + time_microseconds: 0, + } + ); + } + + /// Emit a `NewBlockEvent` event. This function will be invoked by write set script directly to generate the + /// new block event for WriteSetPayload. + public fun emit_writeset_block_event(vm_signer: &signer, fake_block_hash: address) acquires BlockResource { + system_addresses::assert_vm(vm_signer); + let block_metadata_ref = borrow_global_mut(@aptos_framework); + block_metadata_ref.height = event::counter(&block_metadata_ref.new_block_events); + + event::emit_event( + &mut block_metadata_ref.new_block_events, + NewBlockEvent { + hash: fake_block_hash, + epoch: reconfiguration::current_epoch(), + round: MAX_U64, + height: block_metadata_ref.height, + previous_block_votes_bitvec: vector::empty(), + proposer: @vm_reserved, + failed_proposer_indices: vector::empty(), + time_microseconds: timestamp::now_microseconds(), + } + ); + } + + #[test_only] + public fun initialize_for_test(account: &signer, epoch_interval_microsecs: u64) { + initialize(account, epoch_interval_microsecs); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_update_epoch_interval(aptos_framework: signer) acquires BlockResource { + account::create_account_for_test(@aptos_framework); + initialize(&aptos_framework, 1); + assert!(borrow_global(@aptos_framework).epoch_interval == 1, 0); + update_epoch_interval_microsecs(&aptos_framework, 2); + assert!(borrow_global(@aptos_framework).epoch_interval == 2, 1); + } + + #[test(aptos_framework = @aptos_framework, account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_epoch_interval_unauthorized_should_fail( + aptos_framework: signer, + account: signer, + ) acquires BlockResource { + account::create_account_for_test(@aptos_framework); + initialize(&aptos_framework, 1); + update_epoch_interval_microsecs(&account, 2); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_id.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_id.move new file mode 100644 index 0000000..b23ac82 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_id.move @@ -0,0 +1,36 @@ +/// The chain id distinguishes between different chains (e.g., testnet and the main network). +/// One important role is to prevent transactions intended for one chain from being executed on another. +/// This code provides a container for storing a chain id and functions to initialize and get it. +module aptos_framework::chain_id { + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + + struct ChainId has key { + id: u8 + } + + /// Only called during genesis. + /// Publish the chain ID `id` of this instance under the SystemAddresses address + public(friend) fun initialize(aptos_framework: &signer, id: u8) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, ChainId { id }) + } + + #[view] + /// Return the chain ID of this instance. + public fun get(): u8 acquires ChainId { + borrow_global(@aptos_framework).id + } + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer, id: u8) { + initialize(aptos_framework, id); + } + + #[test(aptos_framework = @0x1)] + fun test_get(aptos_framework: &signer) acquires ChainId { + initialize_for_test(aptos_framework, 1u8); + assert!(get() == 1u8, 1); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_status.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_status.move new file mode 100644 index 0000000..32c2ea0 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/chain_status.move @@ -0,0 +1,48 @@ +/// This module code to assert that it is running in genesis (`Self::assert_genesis`) or after +/// genesis (`Self::assert_operating`). These are essentially distinct states of the system. Specifically, +/// if `Self::assert_operating` succeeds, assumptions about invariants over the global state can be made +/// which reflect that the system has been successfully initialized. +module aptos_framework::chain_status { + use aptos_framework::system_addresses; + use std::error; + + friend aptos_framework::genesis; + + /// Marker to publish at the end of genesis. + struct GenesisEndMarker has key {} + + /// The blockchain is not in the operating status. + const ENOT_OPERATING: u64 = 1; + /// The blockchain is not in the genesis status. + const ENOT_GENESIS: u64 = 2; + + /// Marks that genesis has finished. + public(friend) fun set_genesis_end(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, GenesisEndMarker {}); + } + + #[view] + /// Helper function to determine if Aptos is in genesis state. + public fun is_genesis(): bool { + !exists(@aptos_framework) + } + + #[view] + /// Helper function to determine if Aptos is operating. This is + /// the same as `!is_genesis()` and is provided for convenience. + /// Testing `is_operating()` is more frequent than `is_genesis()`. + public fun is_operating(): bool { + exists(@aptos_framework) + } + + /// Helper function to assert operating (not genesis) state. + public fun assert_operating() { + assert!(is_operating(), error::invalid_state(ENOT_OPERATING)); + } + + /// Helper function to assert genesis state. + public fun assert_genesis() { + assert!(is_genesis(), error::invalid_state(ENOT_OPERATING)); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/code.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/code.move new file mode 100644 index 0000000..809c961 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/code.move @@ -0,0 +1,324 @@ +/// This module supports functionality related to code management. +module aptos_framework::code { + use std::string::String; + use std::error; + use std::signer; + use std::vector; + use std::features; + + use aptos_framework::util; + use aptos_framework::system_addresses; + use aptos_std::copyable_any::Any; + use std::option::Option; + use std::string; + + // ---------------------------------------------------------------------- + // Code Publishing + + /// The package registry at the given address. + struct PackageRegistry has key, store, drop { + /// Packages installed at this address. + packages: vector, + } + + /// Metadata for a package. All byte blobs are represented as base64-of-gzipped-bytes + struct PackageMetadata has store, drop { + /// Name of this package. + name: String, + /// The upgrade policy of this package. + upgrade_policy: UpgradePolicy, + /// The numbers of times this module has been upgraded. Also serves as the on-chain version. + /// This field will be automatically assigned on successful upgrade. + upgrade_number: u64, + /// The source digest of the sources in the package. This is constructed by first building the + /// sha256 of each individual source, than sorting them alphabetically, and sha256 them again. + source_digest: String, + /// The package manifest, in the Move.toml format. Gzipped text. + manifest: vector, + /// The list of modules installed by this package. + modules: vector, + /// Holds PackageDeps. + deps: vector, + /// For future extension + extension: Option + } + + /// A dependency to a package published at address + struct PackageDep has store, drop, copy { + account: address, + package_name: String + } + + /// Metadata about a module in a package. + struct ModuleMetadata has store, drop { + /// Name of the module. + name: String, + /// Source text, gzipped String. Empty if not provided. + source: vector, + /// Source map, in compressed BCS. Empty if not provided. + source_map: vector, + /// For future extensions. + extension: Option, + } + + /// Describes an upgrade policy + struct UpgradePolicy has store, copy, drop { + policy: u8 + } + + /// Package contains duplicate module names with existing modules publised in other packages on this address + const EMODULE_NAME_CLASH: u64 = 0x1; + + /// Cannot upgrade an immutable package + const EUPGRADE_IMMUTABLE: u64 = 0x2; + + /// Cannot downgrade a package's upgradability policy + const EUPGRADE_WEAKER_POLICY: u64 = 0x3; + + /// Cannot delete a module that was published in the same package + const EMODULE_MISSING: u64 = 0x4; + + /// Dependency could not be resolved to any published package. + const EPACKAGE_DEP_MISSING: u64 = 0x5; + + /// A dependency cannot have a weaker upgrade policy. + const EDEP_WEAKER_POLICY: u64 = 0x6; + + /// A dependency to an `arbitrary` package must be on the same address. + const EDEP_ARBITRARY_NOT_SAME_ADDRESS: u64 = 0x7; + + /// Creating a package with incompatible upgrade policy is disabled. + const EINCOMPATIBLE_POLICY_DISABLED: u64 = 0x8; + + /// Whether unconditional code upgrade with no compatibility check is allowed. This + /// publication mode should only be used for modules which aren't shared with user others. + /// The developer is responsible for not breaking memory layout of any resources he already + /// stored on chain. + public fun upgrade_policy_arbitrary(): UpgradePolicy { + UpgradePolicy { policy: 0 } + } + + /// Whether a compatibility check should be performed for upgrades. The check only passes if + /// a new module has (a) the same public functions (b) for existing resources, no layout change. + public fun upgrade_policy_compat(): UpgradePolicy { + UpgradePolicy { policy: 1 } + } + + /// Whether the modules in the package are immutable and cannot be upgraded. + public fun upgrade_policy_immutable(): UpgradePolicy { + UpgradePolicy { policy: 2 } + } + + /// Whether the upgrade policy can be changed. In general, the policy can be only + /// strengthened but not weakened. + public fun can_change_upgrade_policy_to(from: UpgradePolicy, to: UpgradePolicy): bool { + from.policy <= to.policy + } + + /// Initialize package metadata for Genesis. + fun initialize(aptos_framework: &signer, package_owner: &signer, metadata: PackageMetadata) + acquires PackageRegistry { + system_addresses::assert_aptos_framework(aptos_framework); + let addr = signer::address_of(package_owner); + if (!exists(addr)) { + move_to(package_owner, PackageRegistry { packages: vector[metadata] }) + } else { + vector::push_back(&mut borrow_global_mut(addr).packages, metadata) + } + } + + /// Publishes a package at the given signer's address. The caller must provide package metadata describing the + /// package. + public fun publish_package(owner: &signer, pack: PackageMetadata, code: vector>) acquires PackageRegistry { + // Disallow incompatible upgrade mode. Governance can decide later if this should be reconsidered. + assert!( + pack.upgrade_policy.policy > upgrade_policy_arbitrary().policy, + error::invalid_argument(EINCOMPATIBLE_POLICY_DISABLED), + ); + + let addr = signer::address_of(owner); + if (!exists(addr)) { + move_to(owner, PackageRegistry { packages: vector::empty() }) + }; + + // Checks for valid dependencies to other packages + let allowed_deps = check_dependencies(addr, &pack); + + // Check package against conflicts + // To avoid prover compiler error on spec + // the package need to be an immutable variable + let module_names = get_module_names(&pack); + let package_immutable = &borrow_global(addr).packages; + let len = vector::length(package_immutable); + let index = len; + let upgrade_number = 0; + vector::enumerate_ref(package_immutable + , |i, old| { + let old: &PackageMetadata = old; + if (old.name == pack.name) { + upgrade_number = old.upgrade_number + 1; + check_upgradability(old, &pack, &module_names); + index = i; + } else { + check_coexistence(old, &module_names) + }; + }); + + // Assign the upgrade counter. + pack.upgrade_number = upgrade_number; + + let packages = &mut borrow_global_mut(addr).packages; + // Update registry + let policy = pack.upgrade_policy; + if (index < len) { + *vector::borrow_mut(packages, index) = pack + } else { + vector::push_back(packages, pack) + }; + + // Request publish + if (features::code_dependency_check_enabled()) + request_publish_with_allowed_deps(addr, module_names, allowed_deps, code, policy.policy) + else + // The new `request_publish_with_allowed_deps` has not yet rolled out, so call downwards + // compatible code. + request_publish(addr, module_names, code, policy.policy) + } + + /// Same as `publish_package` but as an entry function which can be called as a transaction. Because + /// of current restrictions for txn parameters, the metadata needs to be passed in serialized form. + public entry fun publish_package_txn(owner: &signer, metadata_serialized: vector, code: vector>) + acquires PackageRegistry { + publish_package(owner, util::from_bytes(metadata_serialized), code) + } + + // Helpers + // ------- + + /// Checks whether the given package is upgradable, and returns true if a compatibility check is needed. + fun check_upgradability( + old_pack: &PackageMetadata, new_pack: &PackageMetadata, new_modules: &vector) { + assert!(old_pack.upgrade_policy.policy < upgrade_policy_immutable().policy, + error::invalid_argument(EUPGRADE_IMMUTABLE)); + assert!(can_change_upgrade_policy_to(old_pack.upgrade_policy, new_pack.upgrade_policy), + error::invalid_argument(EUPGRADE_WEAKER_POLICY)); + let old_modules = get_module_names(old_pack); + + vector::for_each_ref(&old_modules, |old_module| { + assert!( + vector::contains(new_modules, old_module), + EMODULE_MISSING + ); + }); + } + + /// Checks whether a new package with given names can co-exist with old package. + fun check_coexistence(old_pack: &PackageMetadata, new_modules: &vector) { + // The modules introduced by each package must not overlap with `names`. + vector::for_each_ref(&old_pack.modules, |old_mod| { + let old_mod: &ModuleMetadata = old_mod; + let j = 0; + while (j < vector::length(new_modules)) { + let name = vector::borrow(new_modules, j); + assert!(&old_mod.name != name, error::already_exists(EMODULE_NAME_CLASH)); + j = j + 1; + }; + }); + } + + /// Check that the upgrade policies of all packages are equal or higher quality than this package. Also + /// compute the list of module dependencies which are allowed by the package metadata. The later + /// is passed on to the native layer to verify that bytecode dependencies are actually what is pretended here. + fun check_dependencies(publish_address: address, pack: &PackageMetadata): vector + acquires PackageRegistry { + let allowed_module_deps = vector::empty(); + let deps = &pack.deps; + vector::for_each_ref(deps, |dep| { + let dep: &PackageDep = dep; + assert!(exists(dep.account), error::not_found(EPACKAGE_DEP_MISSING)); + if (is_policy_exempted_address(dep.account)) { + // Allow all modules from this address, by using "" as a wildcard in the AllowedDep + let account: address = dep.account; + let module_name = string::utf8(b""); + vector::push_back(&mut allowed_module_deps, AllowedDep { account, module_name }); + } else { + let registry = borrow_global(dep.account); + let found = vector::any(®istry.packages, |dep_pack| { + let dep_pack: &PackageMetadata = dep_pack; + if (dep_pack.name == dep.package_name) { + // Check policy + assert!( + dep_pack.upgrade_policy.policy >= pack.upgrade_policy.policy, + error::invalid_argument(EDEP_WEAKER_POLICY) + ); + if (dep_pack.upgrade_policy == upgrade_policy_arbitrary()) { + assert!( + dep.account == publish_address, + error::invalid_argument(EDEP_ARBITRARY_NOT_SAME_ADDRESS) + ) + }; + // Add allowed deps + let account = dep.account; + let k = 0; + let r = vector::length(&dep_pack.modules); + while (k < r) { + let module_name = vector::borrow(&dep_pack.modules, k).name; + vector::push_back(&mut allowed_module_deps, AllowedDep { account, module_name }); + k = k + 1; + }; + true + } else { + false + } + }); + assert!(found, error::not_found(EPACKAGE_DEP_MISSING)); + }; + }); + allowed_module_deps + } + + /// Core addresses which are exempted from the check that their policy matches the referring package. Without + /// this exemption, it would not be possible to define an immutable package based on the core system, which + /// requires to be upgradable for maintenance and evolution, and is configured to be `compatible`. + fun is_policy_exempted_address(addr: address): bool { + addr == @1 || addr == @2 || addr == @3 || addr == @4 || addr == @5 || + addr == @6 || addr == @7 || addr == @8 || addr == @9 || addr == @10 + } + + /// Get the names of the modules in a package. + fun get_module_names(pack: &PackageMetadata): vector { + let module_names = vector::empty(); + vector::for_each_ref(&pack.modules, |pack_module| { + let pack_module: &ModuleMetadata = pack_module; + vector::push_back(&mut module_names, pack_module.name); + }); + module_names + } + + /// Native function to initiate module loading + native fun request_publish( + owner: address, + expected_modules: vector, + bundle: vector>, + policy: u8 + ); + + /// A helper type for request_publish_with_allowed_deps + struct AllowedDep has drop { + /// Address of the module. + account: address, + /// Name of the module. If this is the empty string, then this serves as a wildcard for + /// all modules from this address. This is used for speeding up dependency checking for packages from + /// well-known framework addresses, where we can assume that there are no malicious packages. + module_name: String + } + + /// Native function to initiate module loading, including a list of allowed dependencies. + native fun request_publish_with_allowed_deps( + owner: address, + expected_modules: vector, + allowed_deps: vector, + bundle: vector>, + policy: u8 + ); +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/coin.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/coin.move new file mode 100644 index 0000000..0251ee7 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/coin.move @@ -0,0 +1,1196 @@ +/// This module provides the foundation for typesafe Coins. +module aptos_framework::coin { + use std::string; + use std::error; + use std::option::{Self, Option}; + use std::signer; + + use aptos_framework::account; + use aptos_framework::aggregator_factory; + use aptos_framework::aggregator::{Self, Aggregator}; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::optional_aggregator::{Self, OptionalAggregator}; + use aptos_framework::system_addresses; + + use aptos_std::type_info; + + friend aptos_framework::aptos_coin; + friend aptos_framework::genesis; + friend aptos_framework::transaction_fee; + + // + // Errors. + // + + /// Address of account which is used to initialize a coin `CoinType` doesn't match the deployer of module + const ECOIN_INFO_ADDRESS_MISMATCH: u64 = 1; + + /// `CoinType` is already initialized as a coin + const ECOIN_INFO_ALREADY_PUBLISHED: u64 = 2; + + /// `CoinType` hasn't been initialized as a coin + const ECOIN_INFO_NOT_PUBLISHED: u64 = 3; + + /// Deprecated. Account already has `CoinStore` registered for `CoinType` + const ECOIN_STORE_ALREADY_PUBLISHED: u64 = 4; + + /// Account hasn't registered `CoinStore` for `CoinType` + const ECOIN_STORE_NOT_PUBLISHED: u64 = 5; + + /// Not enough coins to complete transaction + const EINSUFFICIENT_BALANCE: u64 = 6; + + /// Cannot destroy non-zero coins + const EDESTRUCTION_OF_NONZERO_TOKEN: u64 = 7; + + /// Coin amount cannot be zero + const EZERO_COIN_AMOUNT: u64 = 9; + + /// CoinStore is frozen. Coins cannot be deposited or withdrawn + const EFROZEN: u64 = 10; + + /// Cannot upgrade the total supply of coins to different implementation. + const ECOIN_SUPPLY_UPGRADE_NOT_SUPPORTED: u64 = 11; + + /// Name of the coin is too long + const ECOIN_NAME_TOO_LONG: u64 = 12; + + /// Symbol of the coin is too long + const ECOIN_SYMBOL_TOO_LONG: u64 = 13; + + /// The value of aggregatable coin used for transaction fees redistribution does not fit in u64. + const EAGGREGATABLE_COIN_VALUE_TOO_LARGE: u64 = 14; + + // + // Constants + // + + const MAX_COIN_NAME_LENGTH: u64 = 32; + const MAX_COIN_SYMBOL_LENGTH: u64 = 10; + + /// Core data structures + + /// Main structure representing a coin/token in an account's custody. + struct Coin has store { + /// Amount of coin this address has. + value: u64, + } + + /// Represents a coin with aggregator as its value. This allows to update + /// the coin in every transaction avoiding read-modify-write conflicts. Only + /// used for gas fees distribution by Aptos Framework (0x1). + struct AggregatableCoin has store { + /// Amount of aggregatable coin this address has. + value: Aggregator, + } + + /// Maximum possible aggregatable coin value. + const MAX_U64: u128 = 18446744073709551615; + + /// A holder of a specific coin types and associated event handles. + /// These are kept in a single resource to ensure locality of data. + struct CoinStore has key { + coin: Coin, + frozen: bool, + deposit_events: EventHandle, + withdraw_events: EventHandle, + } + + /// Maximum possible coin supply. + const MAX_U128: u128 = 340282366920938463463374607431768211455; + + /// Configuration that controls the behavior of total coin supply. If the field + /// is set, coin creators are allowed to upgrade to parallelizable implementations. + struct SupplyConfig has key { + allow_upgrades: bool, + } + + /// Information about a specific coin type. Stored on the creator of the coin's account. + struct CoinInfo has key { + name: string::String, + /// Symbol of the coin, usually a shorter version of the name. + /// For example, Singapore Dollar is SGD. + symbol: string::String, + /// Number of decimals used to get its user representation. + /// For example, if `decimals` equals `2`, a balance of `505` coins should + /// be displayed to a user as `5.05` (`505 / 10 ** 2`). + decimals: u8, + /// Amount of this coin type in existence. + supply: Option, + } + + /// Event emitted when some amount of a coin is deposited into an account. + struct DepositEvent has drop, store { + amount: u64, + } + + /// Event emitted when some amount of a coin is withdrawn from an account. + struct WithdrawEvent has drop, store { + amount: u64, + } + + /// Capability required to mint coins. + struct MintCapability has copy, store {} + + /// Capability required to freeze a coin store. + struct FreezeCapability has copy, store {} + + /// Capability required to burn coins. + struct BurnCapability has copy, store {} + + // + // Total supply config + // + + /// Publishes supply configuration. Initially, upgrading is not allowed. + public(friend) fun initialize_supply_config(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, SupplyConfig { allow_upgrades: false }); + } + + /// This should be called by on-chain governance to update the config and allow + /// or disallow upgradability of total supply. + public fun allow_supply_upgrades(aptos_framework: &signer, allowed: bool) acquires SupplyConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let allow_upgrades = &mut borrow_global_mut(@aptos_framework).allow_upgrades; + *allow_upgrades = allowed; + } + + // + // Aggregatable coin functions + // + + /// Creates a new aggregatable coin with value overflowing on `limit`. Note that this function can + /// only be called by Aptos Framework (0x1) account for now becuase of `create_aggregator`. + public(friend) fun initialize_aggregatable_coin(aptos_framework: &signer): AggregatableCoin { + let aggregator = aggregator_factory::create_aggregator(aptos_framework, MAX_U64); + AggregatableCoin { + value: aggregator, + } + } + + /// Returns true if the value of aggregatable coin is zero. + public(friend) fun is_aggregatable_coin_zero(coin: &AggregatableCoin): bool { + let amount = aggregator::read(&coin.value); + amount == 0 + } + + /// Drains the aggregatable coin, setting it to zero and returning a standard coin. + public(friend) fun drain_aggregatable_coin(coin: &mut AggregatableCoin): Coin { + spec { + // TODO: The data invariant is not properly assumed from CollectedFeesPerBlock. + assume aggregator::spec_get_limit(coin.value) == MAX_U64; + }; + let amount = aggregator::read(&coin.value); + assert!(amount <= MAX_U64, error::out_of_range(EAGGREGATABLE_COIN_VALUE_TOO_LARGE)); + spec { + update aggregate_supply = aggregate_supply - amount; + }; + aggregator::sub(&mut coin.value, amount); + spec { + update supply = supply + amount; + }; + Coin { + value: (amount as u64), + } + } + + /// Merges `coin` into aggregatable coin (`dst_coin`). + public(friend) fun merge_aggregatable_coin(dst_coin: &mut AggregatableCoin, coin: Coin) { + spec { + update supply = supply - coin.value; + }; + let Coin { value } = coin; + let amount = (value as u128); + spec { + update aggregate_supply = aggregate_supply + amount; + }; + aggregator::add(&mut dst_coin.value, amount); + } + + /// Collects a specified amount of coin form an account into aggregatable coin. + public(friend) fun collect_into_aggregatable_coin( + account_addr: address, + amount: u64, + dst_coin: &mut AggregatableCoin, + ) acquires CoinStore { + // Skip collecting if amount is zero. + if (amount == 0) { + return + }; + + let coin_store = borrow_global_mut>(account_addr); + let coin = extract(&mut coin_store.coin, amount); + merge_aggregatable_coin(dst_coin, coin); + } + + // + // Getter functions + // + + /// A helper function that returns the address of CoinType. + fun coin_address(): address { + let type_info = type_info::type_of(); + type_info::account_address(&type_info) + } + + #[view] + /// Returns the balance of `owner` for provided `CoinType`. + public fun balance(owner: address): u64 acquires CoinStore { + assert!( + is_account_registered(owner), + error::not_found(ECOIN_STORE_NOT_PUBLISHED), + ); + borrow_global>(owner).coin.value + } + + #[view] + /// Returns `true` if the type `CoinType` is an initialized coin. + public fun is_coin_initialized(): bool { + exists>(coin_address()) + } + + #[view] + /// Returns `true` is account_addr has frozen the CoinStore or if it's not registered at all + public fun is_coin_store_frozen(account_addr: address): bool acquires CoinStore { + if(!is_account_registered(account_addr)) { + return true + }; + + let coin_store = borrow_global>(account_addr); + coin_store.frozen + } + + #[view] + /// Returns `true` if `account_addr` is registered to receive `CoinType`. + public fun is_account_registered(account_addr: address): bool { + exists>(account_addr) + } + + #[view] + /// Returns the name of the coin. + public fun name(): string::String acquires CoinInfo { + borrow_global>(coin_address()).name + } + + #[view] + /// Returns the symbol of the coin, usually a shorter version of the name. + public fun symbol(): string::String acquires CoinInfo { + borrow_global>(coin_address()).symbol + } + + #[view] + /// Returns the number of decimals used to get its user representation. + /// For example, if `decimals` equals `2`, a balance of `505` coins should + /// be displayed to a user as `5.05` (`505 / 10 ** 2`). + public fun decimals(): u8 acquires CoinInfo { + borrow_global>(coin_address()).decimals + } + + #[view] + /// Returns the amount of coin in existence. + public fun supply(): Option acquires CoinInfo { + let maybe_supply = &borrow_global>(coin_address()).supply; + if (option::is_some(maybe_supply)) { + // We do track supply, in this case read from optional aggregator. + let supply = option::borrow(maybe_supply); + let value = optional_aggregator::read(supply); + option::some(value) + } else { + option::none() + } + } + + // + // Public functions + // + + /// Burn `coin` with capability. + /// The capability `_cap` should be passed as a reference to `BurnCapability`. + public fun burn( + coin: Coin, + _cap: &BurnCapability, + ) acquires CoinInfo { + spec { + update supply = supply - coin.value; + }; + let Coin { value: amount } = coin; + assert!(amount > 0, error::invalid_argument(EZERO_COIN_AMOUNT)); + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + if (option::is_some(maybe_supply)) { + let supply = option::borrow_mut(maybe_supply); + optional_aggregator::sub(supply, (amount as u128)); + } + } + + /// Burn `coin` from the specified `account` with capability. + /// The capability `burn_cap` should be passed as a reference to `BurnCapability`. + /// This function shouldn't fail as it's called as part of transaction fee burning. + /// + /// Note: This bypasses CoinStore::frozen -- coins within a frozen CoinStore can be burned. + public fun burn_from( + account_addr: address, + amount: u64, + burn_cap: &BurnCapability, + ) acquires CoinInfo, CoinStore { + // Skip burning if amount is zero. This shouldn't error out as it's called as part of transaction fee burning. + if (amount == 0) { + return + }; + + let coin_store = borrow_global_mut>(account_addr); + let coin_to_burn = extract(&mut coin_store.coin, amount); + burn(coin_to_burn, burn_cap); + } + + /// Deposit the coin balance into the recipient's account and emit an event. + public fun deposit(account_addr: address, coin: Coin) acquires CoinStore { + assert!( + is_account_registered(account_addr), + error::not_found(ECOIN_STORE_NOT_PUBLISHED), + ); + + let coin_store = borrow_global_mut>(account_addr); + assert!( + !coin_store.frozen, + error::permission_denied(EFROZEN), + ); + + event::emit_event( + &mut coin_store.deposit_events, + DepositEvent { amount: coin.value }, + ); + + merge(&mut coin_store.coin, coin); + } + + /// Deposit the coin balance into the recipient's account without checking if the account is frozen. + /// This is for internal use only and doesn't emit an DepositEvent. + public(friend) fun force_deposit(account_addr: address, coin: Coin) acquires CoinStore { + assert!( + is_account_registered(account_addr), + error::not_found(ECOIN_STORE_NOT_PUBLISHED), + ); + + let coin_store = borrow_global_mut>(account_addr); + + merge(&mut coin_store.coin, coin); + } + + /// Destroys a zero-value coin. Calls will fail if the `value` in the passed-in `token` is non-zero + /// so it is impossible to "burn" any non-zero amount of `Coin` without having + /// a `BurnCapability` for the specific `CoinType`. + public fun destroy_zero(zero_coin: Coin) { + spec { + update supply = supply - zero_coin.value; + }; + let Coin { value } = zero_coin; + assert!(value == 0, error::invalid_argument(EDESTRUCTION_OF_NONZERO_TOKEN)) + } + + /// Extracts `amount` from the passed-in `coin`, where the original token is modified in place. + public fun extract(coin: &mut Coin, amount: u64): Coin { + assert!(coin.value >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE)); + spec { + update supply = supply - amount; + }; + coin.value = coin.value - amount; + spec { + update supply = supply + amount; + }; + Coin { value: amount } + } + + /// Extracts the entire amount from the passed-in `coin`, where the original token is modified in place. + public fun extract_all(coin: &mut Coin): Coin { + let total_value = coin.value; + spec { + update supply = supply - coin.value; + }; + coin.value = 0; + spec { + update supply = supply + total_value; + }; + Coin { value: total_value } + } + + #[legacy_entry_fun] + /// Freeze a CoinStore to prevent transfers + public entry fun freeze_coin_store( + account_addr: address, + _freeze_cap: &FreezeCapability, + ) acquires CoinStore { + let coin_store = borrow_global_mut>(account_addr); + coin_store.frozen = true; + } + + #[legacy_entry_fun] + /// Unfreeze a CoinStore to allow transfers + public entry fun unfreeze_coin_store( + account_addr: address, + _freeze_cap: &FreezeCapability, + ) acquires CoinStore { + let coin_store = borrow_global_mut>(account_addr); + coin_store.frozen = false; + } + + /// Upgrade total supply to use a parallelizable implementation if it is + /// available. + public entry fun upgrade_supply(account: &signer) acquires CoinInfo, SupplyConfig { + let account_addr = signer::address_of(account); + + // Only coin creators can upgrade total supply. + assert!( + coin_address() == account_addr, + error::invalid_argument(ECOIN_INFO_ADDRESS_MISMATCH), + ); + + // Can only succeed once on-chain governance agreed on the upgrade. + assert!( + borrow_global_mut(@aptos_framework).allow_upgrades, + error::permission_denied(ECOIN_SUPPLY_UPGRADE_NOT_SUPPORTED) + ); + + let maybe_supply = &mut borrow_global_mut>(account_addr).supply; + if (option::is_some(maybe_supply)) { + let supply = option::borrow_mut(maybe_supply); + + // If supply is tracked and the current implementation uses an integer - upgrade. + if (!optional_aggregator::is_parallelizable(supply)) { + optional_aggregator::switch(supply); + } + } + } + + /// Creates a new Coin with given `CoinType` and returns minting/freezing/burning capabilities. + /// The given signer also becomes the account hosting the information about the coin + /// (name, supply, etc.). Supply is initialized as non-parallelizable integer. + public fun initialize( + account: &signer, + name: string::String, + symbol: string::String, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + initialize_internal(account, name, symbol, decimals, monitor_supply, false) + } + + /// Same as `initialize` but supply can be initialized to parallelizable aggregator. + public(friend) fun initialize_with_parallelizable_supply( + account: &signer, + name: string::String, + symbol: string::String, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + system_addresses::assert_aptos_framework(account); + initialize_internal(account, name, symbol, decimals, monitor_supply, true) + } + + fun initialize_internal( + account: &signer, + name: string::String, + symbol: string::String, + decimals: u8, + monitor_supply: bool, + parallelizable: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + let account_addr = signer::address_of(account); + + assert!( + coin_address() == account_addr, + error::invalid_argument(ECOIN_INFO_ADDRESS_MISMATCH), + ); + + assert!( + !exists>(account_addr), + error::already_exists(ECOIN_INFO_ALREADY_PUBLISHED), + ); + + assert!(string::length(&name) <= MAX_COIN_NAME_LENGTH, error::invalid_argument(ECOIN_NAME_TOO_LONG)); + assert!(string::length(&symbol) <= MAX_COIN_SYMBOL_LENGTH, error::invalid_argument(ECOIN_SYMBOL_TOO_LONG)); + + let coin_info = CoinInfo { + name, + symbol, + decimals, + supply: if (monitor_supply) { option::some(optional_aggregator::new(MAX_U128, parallelizable)) } else { option::none() }, + }; + move_to(account, coin_info); + + (BurnCapability {}, FreezeCapability {}, MintCapability {}) + } + + /// "Merges" the two given coins. The coin passed in as `dst_coin` will have a value equal + /// to the sum of the two tokens (`dst_coin` and `source_coin`). + public fun merge(dst_coin: &mut Coin, source_coin: Coin) { + spec { + assume dst_coin.value + source_coin.value <= MAX_U64; + }; + spec { + update supply = supply - source_coin.value; + }; + let Coin { value } = source_coin; + spec { + update supply = supply + value; + }; + dst_coin.value = dst_coin.value + value; + } + + /// Mint new `Coin` with capability. + /// The capability `_cap` should be passed as reference to `MintCapability`. + /// Returns minted `Coin`. + public fun mint( + amount: u64, + _cap: &MintCapability, + ): Coin acquires CoinInfo { + if (amount == 0) { + return Coin { + value: 0 + } + }; + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + if (option::is_some(maybe_supply)) { + let supply = option::borrow_mut(maybe_supply); + optional_aggregator::add(supply, (amount as u128)); + }; + spec { + update supply = supply + amount; + }; + Coin { value: amount } + } + + public fun register(account: &signer) { + let account_addr = signer::address_of(account); + // Short-circuit and do nothing if account is already registered for CoinType. + if (is_account_registered(account_addr)) { + return + }; + + account::register_coin(account_addr); + let coin_store = CoinStore { + coin: Coin { value: 0 }, + frozen: false, + deposit_events: account::new_event_handle(account), + withdraw_events: account::new_event_handle(account), + }; + move_to(account, coin_store); + } + + /// Transfers `amount` of coins `CoinType` from `from` to `to`. + public entry fun transfer( + from: &signer, + to: address, + amount: u64, + ) acquires CoinStore { + let coin = withdraw(from, amount); + deposit(to, coin); + } + + /// Returns the `value` passed in `coin`. + public fun value(coin: &Coin): u64 { + coin.value + } + + /// Withdraw specifed `amount` of coin `CoinType` from the signing account. + public fun withdraw( + account: &signer, + amount: u64, + ): Coin acquires CoinStore { + let account_addr = signer::address_of(account); + assert!( + is_account_registered(account_addr), + error::not_found(ECOIN_STORE_NOT_PUBLISHED), + ); + + let coin_store = borrow_global_mut>(account_addr); + assert!( + !coin_store.frozen, + error::permission_denied(EFROZEN), + ); + + event::emit_event( + &mut coin_store.withdraw_events, + WithdrawEvent { amount }, + ); + + extract(&mut coin_store.coin, amount) + } + + /// Create a new `Coin` with a value of `0`. + public fun zero(): Coin { + spec { + update supply = supply + 0; + }; + Coin { + value: 0 + } + } + + /// Destroy a freeze capability. Freeze capability is dangerous and therefore should be destroyed if not used. + public fun destroy_freeze_cap(freeze_cap: FreezeCapability) { + let FreezeCapability {} = freeze_cap; + } + + /// Destroy a mint capability. + public fun destroy_mint_cap(mint_cap: MintCapability) { + let MintCapability {} = mint_cap; + } + + /// Destroy a burn capability. + public fun destroy_burn_cap(burn_cap: BurnCapability) { + let BurnCapability {} = burn_cap; + } + + #[test_only] + struct FakeMoney {} + + #[test_only] + struct FakeMoneyCapabilities has key { + burn_cap: BurnCapability, + freeze_cap: FreezeCapability, + mint_cap: MintCapability, + } + + #[test_only] + fun initialize_fake_money( + account: &signer, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + aggregator_factory::initialize_aggregator_factory_for_test(account); + initialize( + account, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + decimals, + monitor_supply + ) + } + + #[test_only] + fun initialize_and_register_fake_money( + account: &signer, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + let (burn_cap, freeze_cap, mint_cap) = initialize_fake_money( + account, + decimals, + monitor_supply + ); + register(account); + (burn_cap, freeze_cap, mint_cap) + } + + #[test_only] + public entry fun create_fake_money( + source: &signer, + destination: &signer, + amount: u64 + ) acquires CoinInfo, CoinStore { + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(source, 18, true); + + register(destination); + let coins_minted = mint(amount, &mint_cap); + deposit(signer::address_of(source), coins_minted); + move_to(source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1, destination = @0x2)] + public entry fun end_to_end( + source: signer, + destination: signer, + ) acquires CoinInfo, CoinStore { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let destination_addr = signer::address_of(&destination); + account::create_account_for_test(destination_addr); + + let name = string::utf8(b"Fake money"); + let symbol = string::utf8(b"FMD"); + + aggregator_factory::initialize_aggregator_factory_for_test(&source); + let (burn_cap, freeze_cap, mint_cap) = initialize( + &source, + name, + symbol, + 18, + true + ); + register(&source); + register(&destination); + assert!(*option::borrow(&supply()) == 0, 0); + + assert!(name() == name, 1); + assert!(symbol() == symbol, 2); + assert!(decimals() == 18, 3); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + transfer(&source, destination_addr, 50); + + assert!(balance(source_addr) == 50, 4); + assert!(balance(destination_addr) == 50, 5); + assert!(*option::borrow(&supply()) == 100, 6); + + let coin = withdraw(&source, 10); + assert!(value(&coin) == 10, 7); + burn(coin, &burn_cap); + assert!(*option::borrow(&supply()) == 90, 8); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1, destination = @0x2)] + public entry fun end_to_end_no_supply( + source: signer, + destination: signer, + ) acquires CoinInfo, CoinStore { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let destination_addr = signer::address_of(&destination); + account::create_account_for_test(destination_addr); + + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, false); + + register(&destination); + assert!(option::is_none(&supply()), 0); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + transfer(&source, destination_addr, 50); + + assert!(balance(source_addr) == 50, 1); + assert!(balance(destination_addr) == 50, 2); + assert!(option::is_none(&supply()), 3); + + let coin = withdraw(&source, 10); + burn(coin, &burn_cap); + assert!(option::is_none(&supply()), 4); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x2, framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public fun fail_initialize(source: signer, framework: signer) { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + let (burn_cap, freeze_cap, mint_cap) = initialize( + &source, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + 1, + true, + ); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1, destination = @0x2)] + #[expected_failure(abort_code = 0x60005, location = Self)] + public entry fun fail_transfer( + source: signer, + destination: signer, + ) acquires CoinInfo, CoinStore { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let destination_addr = signer::address_of(&destination); + account::create_account_for_test(destination_addr); + + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + assert!(*option::borrow(&supply()) == 0, 0); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + transfer(&source, destination_addr, 50); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1, destination = @0x2)] + public entry fun test_burn_from_with_capability( + source: signer, + ) acquires CoinInfo, CoinStore { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + assert!(balance(source_addr) == 100, 0); + assert!(*option::borrow(&supply()) == 100, 1); + + burn_from(source_addr, 10, &burn_cap); + assert!(balance(source_addr) == 90, 2); + assert!(*option::borrow(&supply()) == 90, 3); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public fun test_destroy_non_zero( + source: signer, + ) acquires CoinInfo { + account::create_account_for_test(signer::address_of(&source)); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + let coins_minted = mint(100, &mint_cap); + destroy_zero(coins_minted); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1)] + public entry fun test_extract( + source: signer, + ) acquires CoinInfo, CoinStore { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + + let coins_minted = mint(100, &mint_cap); + + let extracted = extract(&mut coins_minted, 25); + assert!(value(&coins_minted) == 75, 0); + assert!(value(&extracted) == 25, 1); + + deposit(source_addr, coins_minted); + deposit(source_addr, extracted); + + assert!(balance(source_addr) == 100, 2); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1)] + public fun test_is_coin_initialized(source: signer) { + assert!(!is_coin_initialized(), 0); + + let (burn_cap, freeze_cap, mint_cap) = initialize_fake_money(&source, 1, true); + assert!(is_coin_initialized(), 1); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + public fun test_is_coin_store_frozen(account: signer) acquires CoinStore { + let account_addr = signer::address_of(&account); + // An non registered account is has a frozen coin store by default + assert!(is_coin_store_frozen(account_addr), 1); + + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + assert!(!is_coin_store_frozen(account_addr), 1); + + // freeze account + freeze_coin_store(account_addr, &freeze_cap); + assert!(is_coin_store_frozen(account_addr), 1); + + // unfreeze account + unfreeze_coin_store(account_addr, &freeze_cap); + assert!(!is_coin_store_frozen(account_addr), 1); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test] + fun test_zero() { + let zero = zero(); + assert!(value(&zero) == 0, 1); + destroy_zero(zero); + } + + #[test(account = @0x1)] + public entry fun burn_frozen(account: signer) acquires CoinInfo, CoinStore { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + let coins_minted = mint(100, &mint_cap); + deposit(account_addr, coins_minted); + + freeze_coin_store(account_addr, &freeze_cap); + burn_from(account_addr, 100, &burn_cap); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + #[expected_failure(abort_code = 0x5000A, location = Self)] + public entry fun withdraw_frozen(account: signer) acquires CoinInfo, CoinStore { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + freeze_coin_store(account_addr, &freeze_cap); + let coin = withdraw(&account, 10); + burn(coin, &burn_cap); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + #[expected_failure(abort_code = 0x5000A, location = Self)] + public entry fun deposit_frozen(account: signer) acquires CoinInfo, CoinStore { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + let coins_minted = mint(100, &mint_cap); + freeze_coin_store(account_addr, &freeze_cap); + deposit(account_addr, coins_minted); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + public entry fun deposit_widthdraw_unfrozen(account: signer) acquires CoinInfo, CoinStore { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + let coins_minted = mint(100, &mint_cap); + freeze_coin_store(account_addr, &freeze_cap); + unfreeze_coin_store(account_addr, &freeze_cap); + deposit(account_addr, coins_minted); + + freeze_coin_store(account_addr, &freeze_cap); + unfreeze_coin_store(account_addr, &freeze_cap); + let coin = withdraw(&account, 10); + burn(coin, &burn_cap); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test_only] + fun initialize_with_aggregator(account: &signer) { + let (burn_cap, freeze_cap, mint_cap) = initialize_with_parallelizable_supply( + account, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + 1, + true + ); + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test_only] + fun initialize_with_integer(account: &signer) { + let (burn_cap, freeze_cap, mint_cap) = initialize( + account, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + 1, + true + ); + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(framework = @aptos_framework, other = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + fun test_supply_initialize_fails(framework: signer, other: signer) { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_aggregator(&other); + } + + #[test(framework = @aptos_framework)] + fun test_supply_initialize(framework: signer) acquires CoinInfo { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_aggregator(&framework); + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + + // Supply should be parallelizable. + assert!(optional_aggregator::is_parallelizable(supply), 0); + + optional_aggregator::add(supply, 100); + optional_aggregator::sub(supply, 50); + optional_aggregator::add(supply, 950); + assert!(optional_aggregator::read(supply) == 1000, 0); + } + + #[test(framework = @aptos_framework)] + #[expected_failure(abort_code = 0x20001, location = aptos_framework::aggregator)] + fun test_supply_overflow(framework: signer) acquires CoinInfo { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_aggregator(&framework); + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + + optional_aggregator::add(supply, MAX_U128); + optional_aggregator::add(supply, 1); + optional_aggregator::sub(supply, 1); + } + + #[test(framework = @aptos_framework)] + #[expected_failure(abort_code = 0x5000B, location = aptos_framework::coin)] + fun test_supply_upgrade_fails(framework: signer) acquires CoinInfo, SupplyConfig { + initialize_supply_config(&framework); + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_integer(&framework); + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + + // Supply should be non-parallelizable. + assert!(!optional_aggregator::is_parallelizable(supply), 0); + + optional_aggregator::add(supply, 100); + optional_aggregator::sub(supply, 50); + optional_aggregator::add(supply, 950); + assert!(optional_aggregator::read(supply) == 1000, 0); + + upgrade_supply(&framework); + } + + #[test(framework = @aptos_framework)] + fun test_supply_upgrade(framework: signer) acquires CoinInfo, SupplyConfig { + initialize_supply_config(&framework); + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_integer(&framework); + + // Ensure we have a non-parellelizable non-zero supply. + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + assert!(!optional_aggregator::is_parallelizable(supply), 0); + optional_aggregator::add(supply, 100); + + // Upgrade. + allow_supply_upgrades(&framework, true); + upgrade_supply(&framework); + + // Check supply again. + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + assert!(optional_aggregator::is_parallelizable(supply), 0); + assert!(optional_aggregator::read(supply) == 100, 0); + } + + #[test_only] + fun destroy_aggregatable_coin_for_test(aggregatable_coin: AggregatableCoin) { + let AggregatableCoin { value } = aggregatable_coin; + aggregator::destroy(value); + } + + #[test(framework = @aptos_framework)] + public entry fun test_register_twice_should_not_fail(framework: &signer) { + let framework_addr = signer::address_of(framework); + account::create_account_for_test(framework_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(framework, 1, true); + + // Registering twice should not fail. + assert!(is_account_registered(@0x1), 0); + register(framework); + assert!(is_account_registered(@0x1), 1); + + move_to(framework, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(framework = @aptos_framework)] + public entry fun test_collect_from_and_drain( + framework: signer, + ) acquires CoinInfo, CoinStore { + let framework_addr = signer::address_of(&framework); + account::create_account_for_test(framework_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&framework, 1, true); + + let coins_minted = mint(100, &mint_cap); + deposit(framework_addr, coins_minted); + assert!(balance(framework_addr) == 100, 0); + assert!(*option::borrow(&supply()) == 100, 0); + + let aggregatable_coin = initialize_aggregatable_coin(&framework); + collect_into_aggregatable_coin(framework_addr, 10, &mut aggregatable_coin); + + // Check that aggregatable coin has the right amount. + let collected_coin = drain_aggregatable_coin(&mut aggregatable_coin); + assert!(is_aggregatable_coin_zero(&aggregatable_coin), 0); + assert!(value(&collected_coin) == 10, 0); + + // Supply of coins should be unchanged, but the balance on the account should decrease. + assert!(balance(framework_addr) == 90, 0); + assert!(*option::borrow(&supply()) == 100, 0); + + burn(collected_coin, &burn_cap); + destroy_aggregatable_coin_for_test(aggregatable_coin); + move_to(&framework, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/consensus_config.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/consensus_config.move new file mode 100644 index 0000000..f75410f --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/consensus_config.move @@ -0,0 +1,37 @@ +/// Maintains the consensus config for the blockchain. The config is stored in a +/// Reconfiguration, and may be updated by root. +module aptos_framework::consensus_config { + use std::error; + use std::vector; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + + struct ConsensusConfig has key { + config: vector, + } + + /// The provided on chain config bytes are empty or invalid + const EINVALID_CONFIG: u64 = 1; + + /// Publishes the ConsensusConfig config. + public(friend) fun initialize(aptos_framework: &signer, config: vector) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + move_to(aptos_framework, ConsensusConfig { config }); + } + + /// This can be called by on-chain governance to update on-chain consensus configs. + public fun set(account: &signer, config: vector) acquires ConsensusConfig { + system_addresses::assert_aptos_framework(account); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + + let config_ref = &mut borrow_global_mut(@aptos_framework).config; + *config_ref = config; + + // Need to trigger reconfiguration so validator nodes can sync on the updated configs. + reconfiguration::reconfigure(); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/create_signer.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/create_signer.move new file mode 100644 index 0000000..154c68b --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/create_signer.move @@ -0,0 +1,19 @@ +/// Provides a common place for exporting `create_signer` across the Aptos Framework. +/// +/// To use create_signer, add the module below, such that: +/// `friend aptos_framework::friend_wants_create_signer` +/// where `friend_wants_create_signer` is the module that needs `create_signer`. +/// +/// Note, that this is only available within the Aptos Framework. +/// +/// This exists to make auditing straight forward and to limit the need to depend +/// on account to have access to this. +module aptos_framework::create_signer { + friend aptos_framework::account; + friend aptos_framework::aptos_account; + friend aptos_framework::genesis; + friend aptos_framework::multisig_account; + friend aptos_framework::object; + + public(friend) native fun create_signer(addr: address): signer; +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/delegation_pool.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/delegation_pool.move new file mode 100644 index 0000000..536e5dd --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/delegation_pool.move @@ -0,0 +1,4017 @@ +/** +Allow multiple delegators to participate in the same stake pool in order to collect the minimum +stake required to join the validator set. Delegators are rewarded out of the validator rewards +proportionally to their stake and provided the same stake-management API as the stake pool owner. + +The main accounting logic in the delegation pool contract handles the following: +1. Tracks how much stake each delegator owns, privately deposited as well as earned. +Accounting individual delegator stakes is achieved through the shares-based pool defined at +aptos_std::pool_u64, hence delegators own shares rather than absolute stakes into the delegation pool. +2. Tracks rewards earned by the stake pool, implicitly by the delegation one, in the meantime +and distribute them accordingly. +3. Tracks lockup cycles on the stake pool in order to separate inactive stake (not earning rewards) +from pending_inactive stake (earning rewards) and allow its delegators to withdraw the former. +4. Tracks how much commission fee has to be paid to the operator out of incoming rewards before +distributing them to the internal pool_u64 pools. + +In order to distinguish between stakes in different states and route rewards accordingly, +separate pool_u64 pools are used for individual stake states: +1. one of active + pending_active stake +2. one of inactive stake FOR each past observed lockup cycle (OLC) on the stake pool +3. one of pending_inactive stake scheduled during this ongoing OLC + +As stake-state transitions and rewards are computed only at the stake pool level, the delegation pool +gets outdated. To mitigate this, at any interaction with the delegation pool, a process of synchronization +to the underlying stake pool is executed before the requested operation itself. + +At synchronization: + - stake deviations between the two pools are actually the rewards produced in the meantime. + - the commission fee is extracted from the rewards, the remaining stake is distributed to the internal +pool_u64 pools and then the commission stake used to buy shares for operator. + - if detecting that the lockup expired on the stake pool, the delegation pool will isolate its +pending_inactive stake (now inactive) and create a new pool_u64 to host future pending_inactive stake +scheduled this newly started lockup. +Detecting a lockup expiration on the stake pool resumes to detecting new inactive stake. + +Accounting main invariants: + - each stake-management operation (add/unlock/reactivate/withdraw) and operator change triggers +the synchronization process before executing its own function. + - each OLC maps to one or more real lockups on the stake pool, but not the opposite. Actually, only a real +lockup with 'activity' (which inactivated some unlocking stake) triggers the creation of a new OLC. + - unlocking and/or unlocked stake originating from different real lockups are never mixed together into +the same pool_u64. This invalidates the accounting of which rewards belong to whom. + - no delegator can have unlocking and/or unlocked stake (pending withdrawals) in different OLCs. This ensures +delegators do not have to keep track of the OLCs when they unlocked. When creating a new pending withdrawal, +the existing one is executed (withdrawn) if is already inactive. + - add_stake fees are always refunded, but only after the epoch when they have been charged ends. + - withdrawing pending_inactive stake (when validator had gone inactive before its lockup expired) +does not inactivate any stake additional to the requested one to ensure OLC would not advance indefinitely. + - the pending withdrawal exists at an OLC iff delegator owns some shares within the shares pool of that OLC. + +Example flow: +
    +
  1. A node operator creates a delegation pool by calling +initialize_delegation_pool and sets +its commission fee to 0% (for simplicity). A stake pool is created with no initial stake and owned by +a resource account controlled by the delegation pool.
  2. +
  3. Delegator A adds 100 stake which is converted to 100 shares into the active pool_u64
  4. +
  5. Operator joins the validator set as the stake pool has now the minimum stake
  6. +
  7. The stake pool earned rewards and now has 200 active stake. A's active shares are worth 200 coins as +the commission fee is 0%.
  8. +
  9. +
      +
    1. A requests unlock for 100 stake
    2. +
    3. Synchronization detects 200 - 100 active rewards which are entirely (0% commission) added to the active pool.
    4. +
    5. 100 coins = (100 * 100) / 200 = 50 shares are redeemed from the active pool and exchanged for 100 shares +into the pending_inactive one on A's behalf
    6. +
    +
  10. Delegator B adds 200 stake which is converted to (200 * 50) / 100 = 100 shares into the active pool
  11. +
  12. The stake pool earned rewards and now has 600 active and 200 pending_inactive stake.
  13. +
  14. +
      +
    1. A requests reactivate_stake for 100 stake
    2. +
    3. + Synchronization detects 600 - 300 active and 200 - 100 pending_inactive rewards which are both entirely + distributed to their corresponding pools +
    4. +
    5. + 100 coins = (100 * 100) / 200 = 50 shares are redeemed from the pending_inactive pool and exchanged for + (100 * 150) / 600 = 25 shares into the active one on A's behalf +
    6. +
    +
  15. The lockup expires on the stake pool, inactivating the entire pending_inactive stake
  16. +
  17. +
      +
    1. B requests unlock for 100 stake
    2. +
    3. + Synchronization detects no active or pending_inactive rewards, but 0 -> 100 inactive stake on the stake pool, + so it advances the observed lockup cycle and creates a pool_u64 for the new lockup, hence allowing previous + pending_inactive shares to be redeemed
    4. +
    5. + 100 coins = (100 * 175) / 700 = 25 shares are redeemed from the active pool and exchanged for 100 shares + into the new pending_inactive one on B's behalf +
    6. +
    +
  18. The stake pool earned rewards and now has some pending_inactive rewards.
  19. +
  20. +
      +
    1. A requests withdraw for its entire inactive stake
    2. +
    3. + Synchronization detects no new inactive stake, but some pending_inactive rewards which are distributed + to the (2nd) pending_inactive pool +
    4. +
    5. + A's 50 shares = (50 * 100) / 50 = 100 coins are redeemed from the (1st) inactive pool and 100 stake is + transferred to A +
    6. +
    +
+ */ +module aptos_framework::delegation_pool { + use std::error; + use std::features; + use std::signer; + use std::vector; + + use aptos_std::pool_u64_unbound::{Self as pool_u64, total_coins}; + use aptos_std::table::{Self, Table}; + use aptos_std::smart_table::{Self, SmartTable}; + + use aptos_framework::account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::aptos_governance; + use aptos_framework::coin; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::stake; + use aptos_framework::staking_config; + use aptos_framework::timestamp; + + const MODULE_SALT: vector = b"aptos_framework::delegation_pool"; + + /// Delegation pool owner capability does not exist at the provided account. + const EOWNER_CAP_NOT_FOUND: u64 = 1; + + /// Account is already owning a delegation pool. + const EOWNER_CAP_ALREADY_EXISTS: u64 = 2; + + /// Delegation pool does not exist at the provided pool address. + const EDELEGATION_POOL_DOES_NOT_EXIST: u64 = 3; + + /// There is a pending withdrawal to be executed before `unlock`ing any new stake. + const EPENDING_WITHDRAWAL_EXISTS: u64 = 4; + + /// Commission percentage has to be between 0 and `MAX_FEE` - 100%. + const EINVALID_COMMISSION_PERCENTAGE: u64 = 5; + + /// There is not enough `active` stake on the stake pool to `unlock`. + const ENOT_ENOUGH_ACTIVE_STAKE_TO_UNLOCK: u64 = 6; + + /// Slashing (if implemented) should not be applied to already `inactive` stake. + /// Not only it invalidates the accounting of past observed lockup cycles (OLC), + /// but is also unfair to delegators whose stake has been inactive before validator started misbehaving. + /// Additionally, the inactive stake does not count on the voting power of validator. + const ESLASHED_INACTIVE_STAKE_ON_PAST_OLC: u64 = 7; + + /// Delegator's active balance cannot be less than `MIN_COINS_ON_SHARES_POOL`. + const EDELEGATOR_ACTIVE_BALANCE_TOO_LOW: u64 = 8; + + /// Delegator's pending_inactive balance cannot be less than `MIN_COINS_ON_SHARES_POOL`. + const EDELEGATOR_PENDING_INACTIVE_BALANCE_TOO_LOW: u64 = 9; + + /// Creating delegation pools is not enabled yet. + const EDELEGATION_POOLS_DISABLED: u64 = 10; + + /// Cannot request to withdraw zero stake. + const EWITHDRAW_ZERO_STAKE: u64 = 11; + + /// Function is deprecated. + const EDEPRECATED_FUNCTION: u64 = 12; + + /// The function is disabled or hasn't been enabled. + const EDISABLED_FUNCTION: u64 = 13; + + /// Partial governance voting hasn't been enabled on this delegation pool. + const EPARTIAL_GOVERNANCE_VOTING_NOT_ENABLED: u64 = 14; + + /// The voter does not have sufficient stake to create a proposal. + const EINSUFFICIENT_PROPOSER_STAKE: u64 = 15; + + /// The voter does not have any voting power on this proposal. + const ENO_VOTING_POWER: u64 = 16; + + /// The stake pool has already voted on the proposal before enabling partial governance voting on this delegation pool. + const EALREADY_VOTED_BEFORE_ENABLE_PARTIAL_VOTING: u64 = 17; + + const MAX_U64: u64 = 18446744073709551615; + + /// Maximum operator percentage fee(of double digit precision): 22.85% is represented as 2285 + const MAX_FEE: u64 = 10000; + + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + /// Special shareholder temporarily owning the `add_stake` fees charged during this epoch. + /// On each `add_stake` operation any resulted fee is used to buy active shares for this shareholder. + /// First synchronization after this epoch ends will distribute accumulated fees to the rest of the pool as refunds. + const NULL_SHAREHOLDER: address = @0x0; + + /// Minimum coins to exist on a shares pool at all times. + /// Enforced per delegator for both active and pending_inactive pools. + /// This constraint ensures the share price cannot overly increase and lead to + /// substantial loses when buying shares (can lose at most 1 share which may + /// be worth a lot if current share price is high). + /// This constraint is not enforced on inactive pools as they only allow redeems + /// (can lose at most 1 coin regardless of current share price). + const MIN_COINS_ON_SHARES_POOL: u64 = 1000000000; + + /// Scaling factor of shares pools used within the delegation pool + const SHARES_SCALING_FACTOR: u64 = 10000000000000000; + + /// Capability that represents ownership over privileged operations on the underlying stake pool. + struct DelegationPoolOwnership has key, store { + /// equal to address of the resource account owning the stake pool + pool_address: address, + } + + struct ObservedLockupCycle has copy, drop, store { + index: u64, + } + + struct DelegationPool has key { + // Shares pool of `active` + `pending_active` stake + active_shares: pool_u64::Pool, + // Index of current observed lockup cycle on the delegation pool since its creation + observed_lockup_cycle: ObservedLockupCycle, + // Shares pools of `inactive` stake on each ended OLC and `pending_inactive` stake on the current one. + // Tracks shares of delegators who requested withdrawals in each OLC + inactive_shares: Table, + // Mapping from delegator address to the OLC of its pending withdrawal if having one + pending_withdrawals: Table, + // Signer capability of the resource account owning the stake pool + stake_pool_signer_cap: account::SignerCapability, + // Total (inactive) coins on the shares pools over all ended OLCs + total_coins_inactive: u64, + // Commission fee paid to the node operator out of pool rewards + operator_commission_percentage: u64, + + // The events emitted by stake-management operations on the delegation pool + add_stake_events: EventHandle, + reactivate_stake_events: EventHandle, + unlock_stake_events: EventHandle, + withdraw_stake_events: EventHandle, + distribute_commission_events: EventHandle, + } + + struct VotingRecordKey has copy, drop, store { + voter: address, + proposal_id: u64, + } + + /// Track delgated voter of each delegator. + struct VoteDelegation has copy, drop, store { + // The account who can vote on behalf of this delegator. + voter: address, + // The account that will become the voter in the next lockup period. Changing voter address needs 1 lockup + // period to take effects. + pending_voter: address, + // Tracks the last known lockup cycle end when the voter was updated. This will be used to determine when + // the new voter becomes effective. + // If != last_locked_until_secs, it means that a lockup period has passed. + // This is slightly different from ObservedLockupCycle because ObservedLockupCycle cannot detect if a lockup + // period is passed when there is no unlocking during the lockup period. + last_locked_until_secs: u64, + } + + /// Track total voteing power of each voter. + struct DelegatedVotes has copy, drop, store { + // The total number of active shares delegated to this voter by all delegators. + active_shares: u128, + // The total number of pending inactive shares delegated to this voter by all delegators + pending_inactive_shares: u128, + // Total active shares delegated to this voter in the next lockup cycle. + // `active_shares_next_lockup` might be different `active_shares` when some delegators change their voter. + active_shares_next_lockup: u128, + // Tracks the last known lockup cycle end when the voter was updated. This will be used to determine when + // the new voter becomes effective. + // If != last_locked_until_secs, it means that a lockup period has passed. + // This is slightly different from ObservedLockupCycle because ObservedLockupCycle cannot detect if a lockup + // period is passed when there is no unlocking during the lockup period. + last_locked_until_secs: u64, + } + + /// Track governance information of a delegation(e.g. voter delegation/voting power calculation). + /// This struct should be stored in the delegation pool resource account. + struct GovernanceRecords has key { + // `votes` tracks voting power usage of each voter on each proposal. + votes: SmartTable, + // `votes_per_proposal` tracks voting power usage of this stake pool on each proposal. Key is proposal_id. + votes_per_proposal: SmartTable, + vote_delegation: SmartTable, + delegated_votes: SmartTable, + vote_events: EventHandle, + create_proposal_events: EventHandle, + // Note: a DelegateVotingPowerEvent event only means that the delegator tries to change its voter. The change + // won't take effect until the next lockup period. + delegate_voting_power_events: EventHandle, + } + + struct AddStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_added: u64, + add_stake_fee: u64, + } + + struct ReactivateStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_reactivated: u64, + } + + struct UnlockStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_unlocked: u64, + } + + struct WithdrawStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_withdrawn: u64, + } + + struct DistributeCommissionEvent has drop, store { + pool_address: address, + operator: address, + commission_active: u64, + commission_pending_inactive: u64, + } + + struct VoteEvent has drop, store { + voter: address, + proposal_id: u64, + delegation_pool: address, + num_votes: u64, + should_pass: bool, + } + + struct CreateProposalEvent has drop, store { + proposal_id: u64, + voter: address, + delegation_pool: address, + } + + struct DelegateVotingPowerEvent has drop, store { + pool_address: address, + delegator: address, + voter: address, + } + + #[view] + /// Return whether supplied address `addr` is owner of a delegation pool. + public fun owner_cap_exists(addr: address): bool { + exists(addr) + } + + #[view] + /// Return address of the delegation pool owned by `owner` or fail if there is none. + public fun get_owned_pool_address(owner: address): address acquires DelegationPoolOwnership { + assert_owner_cap_exists(owner); + borrow_global(owner).pool_address + } + + #[view] + /// Return whether a delegation pool exists at supplied address `addr`. + public fun delegation_pool_exists(addr: address): bool { + exists(addr) + } + + #[view] + /// Return whether a delegation pool has already enabled partial govnernance voting. + public fun partial_governance_voting_enabled(pool_address: address): bool { + exists(pool_address) && stake::get_delegated_voter(pool_address) == pool_address + } + + #[view] + /// Return the index of current observed lockup cycle on delegation pool `pool_address`. + public fun observed_lockup_cycle(pool_address: address): u64 acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + borrow_global(pool_address).observed_lockup_cycle.index + } + + #[view] + /// Return the operator commission percentage set on the delegation pool `pool_address`. + public fun operator_commission_percentage(pool_address: address): u64 acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + borrow_global(pool_address).operator_commission_percentage + } + + #[view] + /// Return the number of delegators owning active stake within `pool_address`. + public fun shareholders_count_active_pool(pool_address: address): u64 acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + pool_u64::shareholders_count(&borrow_global(pool_address).active_shares) + } + + #[view] + /// Return the stake amounts on `pool_address` in the different states: + /// (`active`,`inactive`,`pending_active`,`pending_inactive`) + public fun get_delegation_pool_stake(pool_address: address): (u64, u64, u64, u64) { + assert_delegation_pool_exists(pool_address); + stake::get_stake(pool_address) + } + + #[view] + /// Return whether the given delegator has any withdrawable stake. If they recently requested to unlock + /// some stake and the stake pool's lockup cycle has not ended, their coins are not withdrawable yet. + public fun get_pending_withdrawal( + pool_address: address, + delegator_address: address + ): (bool, u64) acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + let ( + lockup_cycle_ended, + _, + pending_inactive, + _, + commission_pending_inactive + ) = calculate_stake_pool_drift(pool); + + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + if (!withdrawal_exists) { + // if no pending withdrawal, there is neither inactive nor pending_inactive stake + (false, 0) + } else { + // delegator has either inactive or pending_inactive stake due to automatic withdrawals + let inactive_shares = table::borrow(&pool.inactive_shares, withdrawal_olc); + if (withdrawal_olc.index < pool.observed_lockup_cycle.index) { + // if withdrawal's lockup cycle ended on delegation pool then it is inactive + (true, pool_u64::balance(inactive_shares, delegator_address)) + } else { + pending_inactive = pool_u64::shares_to_amount_with_total_coins( + inactive_shares, + pool_u64::shares(inactive_shares, delegator_address), + // exclude operator pending_inactive rewards not converted to shares yet + pending_inactive - commission_pending_inactive + ); + // if withdrawal's lockup cycle ended ONLY on stake pool then it is also inactive + (lockup_cycle_ended, pending_inactive) + } + } + } + + #[view] + /// Return total stake owned by `delegator_address` within delegation pool `pool_address` + /// in each of its individual states: (`active`,`inactive`,`pending_inactive`) + public fun get_stake(pool_address: address, delegator_address: address): (u64, u64, u64) acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + let ( + lockup_cycle_ended, + active, + _, + commission_active, + commission_pending_inactive + ) = calculate_stake_pool_drift(pool); + + let total_active_shares = pool_u64::total_shares(&pool.active_shares); + let delegator_active_shares = pool_u64::shares(&pool.active_shares, delegator_address); + + let (_, _, pending_active, _) = stake::get_stake(pool_address); + if (pending_active == 0) { + // zero `pending_active` stake indicates that either there are no `add_stake` fees or + // previous epoch has ended and should identify shares owning these fees as released + total_active_shares = total_active_shares - pool_u64::shares(&pool.active_shares, NULL_SHAREHOLDER); + if (delegator_address == NULL_SHAREHOLDER) { + delegator_active_shares = 0 + } + }; + active = pool_u64::shares_to_amount_with_total_stats( + &pool.active_shares, + delegator_active_shares, + // exclude operator active rewards not converted to shares yet + active - commission_active, + total_active_shares + ); + + // get state and stake (0 if there is none) of the pending withdrawal + let (withdrawal_inactive, withdrawal_stake) = get_pending_withdrawal(pool_address, delegator_address); + // report non-active stakes accordingly to the state of the pending withdrawal + let (inactive, pending_inactive) = if (withdrawal_inactive) (withdrawal_stake, 0) else (0, withdrawal_stake); + + // should also include commission rewards in case of the operator account + // operator rewards are actually used to buy shares which is introducing + // some imprecision (received stake would be slightly less) + // but adding rewards onto the existing stake is still a good approximation + if (delegator_address == stake::get_operator(pool_address)) { + active = active + commission_active; + // in-flight pending_inactive commission can coexist with already inactive withdrawal + if (lockup_cycle_ended) { + inactive = inactive + commission_pending_inactive + } else { + pending_inactive = pending_inactive + commission_pending_inactive + } + }; + + (active, inactive, pending_inactive) + } + + #[view] + /// Return refundable stake to be extracted from added `amount` at `add_stake` operation on pool `pool_address`. + /// If the validator produces rewards this epoch, added stake goes directly to `pending_active` and + /// does not earn rewards. However, all shares within a pool appreciate uniformly and when this epoch ends: + /// - either added shares are still `pending_active` and steal from rewards of existing `active` stake + /// - or have moved to `pending_inactive` and get full rewards (they displaced `active` stake at `unlock`) + /// To mitigate this, some of the added stake is extracted and fed back into the pool as placeholder + /// for the rewards the remaining stake would have earned if active: + /// extracted-fee = (amount - extracted-fee) * reward-rate% * (100% - operator-commission%) + public fun get_add_stake_fee(pool_address: address, amount: u64): u64 acquires DelegationPool { + if (stake::is_current_epoch_validator(pool_address)) { + let (rewards_rate, rewards_rate_denominator) = staking_config::get_reward_rate(&staking_config::get()); + if (rewards_rate_denominator > 0) { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + + rewards_rate = rewards_rate * (MAX_FEE - pool.operator_commission_percentage); + rewards_rate_denominator = rewards_rate_denominator * MAX_FEE; + ((((amount as u128) * (rewards_rate as u128)) / ((rewards_rate as u128) + (rewards_rate_denominator as u128))) as u64) + } else { 0 } + } else { 0 } + } + + #[view] + /// Return whether `pending_inactive` stake can be directly withdrawn from + /// the delegation pool, implicitly its stake pool, in the special case + /// the validator had gone inactive before its lockup expired. + public fun can_withdraw_pending_inactive(pool_address: address): bool { + stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE && + timestamp::now_seconds() >= stake::get_lockup_secs(pool_address) + } + + #[view] + /// Return the total voting power of a delegator in a delegation pool. This function syncs DelegationPool to the + /// latest state. + public fun calculate_and_update_voter_total_voting_power(pool_address: address, voter: address): u64 acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + // Delegation pool need to be synced to explain rewards(which could change the coin amount) and + // commission(which could cause share transfer). + synchronize_delegation_pool(pool_address); + let pool = borrow_global(pool_address); + let governance_records = borrow_global_mut(pool_address); + let latest_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, voter); + calculate_total_voting_power(pool, latest_delegated_votes) + } + + #[view] + /// Return the remaining voting power of a delegator in a delegation pool on a proposal. This function syncs DelegationPool to the + /// latest state. + public fun calculate_and_update_remaining_voting_power(pool_address: address, voter_address: address, proposal_id: u64): u64 acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + // If the whole stake pool has no voting power(e.g. it has already voted before partial + // governance voting flag is enabled), the delegator also has no voting power. + if (aptos_governance::get_remaining_voting_power(pool_address, proposal_id) == 0) { + return 0 + }; + + let total_voting_power = calculate_and_update_voter_total_voting_power(pool_address, voter_address); + let governance_records = borrow_global(pool_address); + total_voting_power - get_used_voting_power(governance_records, voter_address, proposal_id) + } + + #[view] + /// Return the latest delegated voter of a delegator in a delegation pool. This function syncs DelegationPool to the + /// latest state. + public fun calculate_and_update_delegator_voter(pool_address: address, delegator_address: address): address acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + calculate_and_update_delegator_voter_internal( + borrow_global(pool_address), + borrow_global_mut(pool_address), + delegator_address + ) + } + + #[view] + /// Return the address of the stake pool to be created with the provided owner, and seed. + public fun get_expected_stake_pool_address(owner: address, delegation_pool_creation_seed: vector + ): address { + let seed = create_resource_account_seed(delegation_pool_creation_seed); + account::create_resource_address(&owner, seed) + } + + /// Initialize a delegation pool of custom fixed `operator_commission_percentage`. + /// A resource account is created from `owner` signer and its supplied `delegation_pool_creation_seed` + /// to host the delegation pool resource and own the underlying stake pool. + /// Ownership over setting the operator/voter is granted to `owner` who has both roles initially. + public entry fun initialize_delegation_pool( + owner: &signer, + operator_commission_percentage: u64, + delegation_pool_creation_seed: vector, + ) acquires DelegationPool, GovernanceRecords { + assert!(features::delegation_pools_enabled(), error::invalid_state(EDELEGATION_POOLS_DISABLED)); + let owner_address = signer::address_of(owner); + assert!(!owner_cap_exists(owner_address), error::already_exists(EOWNER_CAP_ALREADY_EXISTS)); + assert!(operator_commission_percentage <= MAX_FEE, error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE)); + + // generate a seed to be used to create the resource account hosting the delegation pool + let seed = create_resource_account_seed(delegation_pool_creation_seed); + + let (stake_pool_signer, stake_pool_signer_cap) = account::create_resource_account(owner, seed); + coin::register(&stake_pool_signer); + + // stake_pool_signer will be owner of the stake pool and have its `stake::OwnerCapability` + let pool_address = signer::address_of(&stake_pool_signer); + stake::initialize_stake_owner(&stake_pool_signer, 0, owner_address, owner_address); + + let inactive_shares = table::new(); + table::add( + &mut inactive_shares, + olc_with_index(0), + pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR) + ); + + move_to(&stake_pool_signer, DelegationPool { + active_shares: pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR), + observed_lockup_cycle: olc_with_index(0), + inactive_shares, + pending_withdrawals: table::new(), + stake_pool_signer_cap, + total_coins_inactive: 0, + operator_commission_percentage, + add_stake_events: account::new_event_handle(&stake_pool_signer), + reactivate_stake_events: account::new_event_handle(&stake_pool_signer), + unlock_stake_events: account::new_event_handle(&stake_pool_signer), + withdraw_stake_events: account::new_event_handle(&stake_pool_signer), + distribute_commission_events: account::new_event_handle(&stake_pool_signer), + }); + + // save delegation pool ownership and resource account address (inner stake pool address) on `owner` + move_to(owner, DelegationPoolOwnership { pool_address }); + + // All delegation pool enable partial governace voting by default once the feature flag is enabled. + if (features::partial_governance_voting_enabled() && features::delegation_pool_partial_governance_voting_enabled()) { + enable_partial_governance_voting(pool_address); + } + } + + /// Enable partial governance voting on a stake pool. The voter of this stake pool will be managed by this module. + /// THe existing voter will be replaced. The function is permissionless. + public entry fun enable_partial_governance_voting( + pool_address: address, + ) acquires DelegationPool, GovernanceRecords { + assert!(features::partial_governance_voting_enabled(), error::invalid_state(EDISABLED_FUNCTION)); + assert!(features::delegation_pool_partial_governance_voting_enabled(), error::invalid_state(EDISABLED_FUNCTION)); + assert_delegation_pool_exists(pool_address); + // synchronize delegation and stake pools before any user operation. + synchronize_delegation_pool(pool_address); + + let delegation_pool = borrow_global(pool_address); + let stake_pool_signer = retrieve_stake_pool_owner(delegation_pool); + // delegated_voter is managed by the stake pool itself, which signer capability is managed by DelegationPool. + // So voting power of this stake pool can only be used through this module. + stake::set_delegated_voter(&stake_pool_signer, signer::address_of(&stake_pool_signer)); + + move_to(&stake_pool_signer, GovernanceRecords { + votes: smart_table::new(), + votes_per_proposal: smart_table::new(), + vote_delegation: smart_table::new(), + delegated_votes: smart_table::new(), + vote_events: account::new_event_handle(&stake_pool_signer), + create_proposal_events: account::new_event_handle(&stake_pool_signer), + delegate_voting_power_events: account::new_event_handle(&stake_pool_signer), + }); + } + + /// Vote on a proposal with a voter's voting power. To successfully vote, the following conditions must be met: + /// 1. The voting period of the proposal hasn't ended. + /// 2. The delegation pool's lockup period ends after the voting period of the proposal. + /// 3. The voter still has spare voting power on this proposal. + /// 4. The delegation pool never votes on the proposal before enabling partial governance voting. + public entry fun vote(voter: &signer, pool_address: address, proposal_id: u64, voting_power: u64, should_pass: bool) acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + // synchronize delegation and stake pools before any user operation. + synchronize_delegation_pool(pool_address); + + let voter_address = signer::address_of(voter); + let remaining_voting_power = calculate_and_update_remaining_voting_power(pool_address, voter_address, proposal_id); + if (voting_power > remaining_voting_power) { + voting_power = remaining_voting_power; + }; + assert!(voting_power > 0, error::invalid_argument(ENO_VOTING_POWER)); + + let governance_records = borrow_global_mut(pool_address); + // Check a edge case during the transient period of enabling partial governance voting. + assert_and_update_proposal_used_voting_power(governance_records, pool_address, proposal_id, voting_power); + let used_voting_power = borrow_mut_used_voting_power(governance_records, voter_address, proposal_id); + *used_voting_power = *used_voting_power + voting_power; + + let pool_signer = retrieve_stake_pool_owner(borrow_global(pool_address)); + aptos_governance::partial_vote(&pool_signer, pool_address, proposal_id, voting_power, should_pass); + + event::emit_event( + &mut governance_records.vote_events, + VoteEvent { + voter: voter_address, + proposal_id, + delegation_pool: pool_address, + num_votes: voting_power, + should_pass, + } + ); + } + + /// A voter could create a governance proposal by this function. To successfully create a proposal, the voter's + /// voting power in THIS delegation pool must be not less than the minimum required voting power specified in + /// `aptos_governance.move`. + public entry fun create_proposal( + voter: &signer, + pool_address: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + is_multi_step_proposal: bool, + ) acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let voter_addr = signer::address_of(voter); + let pool = borrow_global(pool_address); + let governance_records = borrow_global_mut(pool_address); + let total_voting_power = calculate_and_update_delegated_votes(pool, governance_records, voter_addr); + assert!( + total_voting_power >= aptos_governance::get_required_proposer_stake(), + error::invalid_argument(EINSUFFICIENT_PROPOSER_STAKE)); + let pool_signer = retrieve_stake_pool_owner(borrow_global(pool_address)); + let proposal_id = aptos_governance::create_proposal_v2_impl( + &pool_signer, + pool_address, + execution_hash, + metadata_location, + metadata_hash, + is_multi_step_proposal, + ); + + let governance_records = borrow_global_mut(pool_address); + event::emit_event( + &mut governance_records.create_proposal_events, + CreateProposalEvent { + proposal_id, + voter: voter_addr, + delegation_pool: pool_address, + } + ); + } + + fun assert_owner_cap_exists(owner: address) { + assert!(owner_cap_exists(owner), error::not_found(EOWNER_CAP_NOT_FOUND)); + } + + fun assert_delegation_pool_exists(pool_address: address) { + assert!(delegation_pool_exists(pool_address), error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST)); + } + + fun assert_min_active_balance(pool: &DelegationPool, delegator_address: address) { + let balance = pool_u64::balance(&pool.active_shares, delegator_address); + assert!(balance >= MIN_COINS_ON_SHARES_POOL, error::invalid_argument(EDELEGATOR_ACTIVE_BALANCE_TOO_LOW)); + } + + fun assert_min_pending_inactive_balance(pool: &DelegationPool, delegator_address: address) { + let balance = pool_u64::balance(pending_inactive_shares_pool(pool), delegator_address); + assert!( + balance >= MIN_COINS_ON_SHARES_POOL, + error::invalid_argument(EDELEGATOR_PENDING_INACTIVE_BALANCE_TOO_LOW) + ); + } + + fun assert_partial_governance_voting_enabled(pool_address: address) { + assert_delegation_pool_exists(pool_address); + assert!(partial_governance_voting_enabled(pool_address), error::invalid_state(EPARTIAL_GOVERNANCE_VOTING_NOT_ENABLED)); + } + + fun coins_to_redeem_to_ensure_min_stake( + src_shares_pool: &pool_u64::Pool, + shareholder: address, + amount: u64, + ): u64 { + // find how many coins would be redeemed if supplying `amount` + let redeemed_coins = pool_u64::shares_to_amount( + src_shares_pool, + amount_to_shares_to_redeem(src_shares_pool, shareholder, amount) + ); + // if balance drops under threshold then redeem it entirely + let src_balance = pool_u64::balance(src_shares_pool, shareholder); + if (src_balance - redeemed_coins < MIN_COINS_ON_SHARES_POOL) { + amount = src_balance; + }; + amount + } + + fun coins_to_transfer_to_ensure_min_stake( + src_shares_pool: &pool_u64::Pool, + dst_shares_pool: &pool_u64::Pool, + shareholder: address, + amount: u64, + ): u64 { + // find how many coins would be redeemed from source if supplying `amount` + let redeemed_coins = pool_u64::shares_to_amount( + src_shares_pool, + amount_to_shares_to_redeem(src_shares_pool, shareholder, amount) + ); + // if balance on destination would be less than threshold then redeem difference to threshold + let dst_balance = pool_u64::balance(dst_shares_pool, shareholder); + if (dst_balance + redeemed_coins < MIN_COINS_ON_SHARES_POOL) { + // `redeemed_coins` >= `amount` - 1 as redeem can lose at most 1 coin + amount = MIN_COINS_ON_SHARES_POOL - dst_balance + 1; + }; + // check if new `amount` drops balance on source under threshold and adjust + coins_to_redeem_to_ensure_min_stake(src_shares_pool, shareholder, amount) + } + + /// Retrieves the shared resource account owning the stake pool in order + /// to forward a stake-management operation to this underlying pool. + fun retrieve_stake_pool_owner(pool: &DelegationPool): signer { + account::create_signer_with_capability(&pool.stake_pool_signer_cap) + } + + /// Get the address of delegation pool reference `pool`. + fun get_pool_address(pool: &DelegationPool): address { + account::get_signer_capability_address(&pool.stake_pool_signer_cap) + } + + /// Get the active share amount of the delegator. + fun get_delegator_active_shares(pool: &DelegationPool, delegator: address): u128 { + pool_u64::shares(&pool.active_shares, delegator) + } + + /// Get the pending inactive share amount of the delegator. + fun get_delegator_pending_inactive_shares(pool: &DelegationPool, delegator: address): u128 { + pool_u64::shares(pending_inactive_shares_pool(pool), delegator) + } + + /// Get the used voting power of a voter on a proposal. + fun get_used_voting_power(governance_records: &GovernanceRecords, voter: address, proposal_id: u64): u64 { + let votes = &governance_records.votes; + let key = VotingRecordKey { + voter, + proposal_id, + }; + *smart_table::borrow_with_default(votes, key, &0) + } + + /// Create the seed to derive the resource account address. + fun create_resource_account_seed( + delegation_pool_creation_seed: vector, + ): vector { + let seed = vector::empty(); + // include module salt (before any subseeds) to avoid conflicts with other modules creating resource accounts + vector::append(&mut seed, MODULE_SALT); + // include an additional salt in case the same resource account has already been created + vector::append(&mut seed, delegation_pool_creation_seed); + seed + } + + /// Borrow the mutable used voting power of a voter on a proposal. + inline fun borrow_mut_used_voting_power(governance_records: &mut GovernanceRecords, voter: address, proposal_id: u64): &mut u64 { + let votes = &mut governance_records.votes; + let key = VotingRecordKey { + proposal_id, + voter, + }; + smart_table::borrow_mut_with_default(votes, key, 0) + } + + /// Update VoteDelegation of a delegator to up-to-date then borrow_mut it. + fun update_and_borrow_mut_delegator_vote_delegation( + pool: &DelegationPool, + governance_records :&mut GovernanceRecords, + delegator: address + ): &mut VoteDelegation { + let pool_address = get_pool_address(pool); + let locked_until_secs = stake::get_lockup_secs(pool_address); + + let vote_delegation_table = &mut governance_records.vote_delegation; + // By default, a delegator's delegated voter is itself. + // TODO: recycle storage when VoteDelegation equals to default value. + if (!smart_table::contains(vote_delegation_table, delegator)) { + return smart_table::borrow_mut_with_default(vote_delegation_table, delegator, VoteDelegation { + voter: delegator, + last_locked_until_secs: locked_until_secs, + pending_voter: delegator, + }) + }; + + let vote_delegation = smart_table::borrow_mut(vote_delegation_table, delegator); + // A lockup period has passed since last time `vote_delegation` was updated. Pending voter takes effect. + if (vote_delegation.last_locked_until_secs < locked_until_secs && + vote_delegation.voter != vote_delegation.pending_voter) { + vote_delegation.voter = vote_delegation.pending_voter; + }; + vote_delegation + } + + /// Update DelegatedVotes of a voter to up-to-date then borrow_mut it. + fun update_and_borrow_mut_delegated_votes( + pool: &DelegationPool, + governance_records :&mut GovernanceRecords, + voter: address + ): &mut DelegatedVotes { + let pool_address = get_pool_address(pool); + let locked_until_secs = stake::get_lockup_secs(pool_address); + + let delegated_votes_per_voter = &mut governance_records.delegated_votes; + // By default, a delegator's voter is itself. + // TODO: recycle storage when DelegatedVotes equals to default value. + if (!smart_table::contains(delegated_votes_per_voter, voter)) { + let active_shares = get_delegator_active_shares(pool, voter); + let inactive_shares = get_delegator_pending_inactive_shares(pool, voter); + return smart_table::borrow_mut_with_default(delegated_votes_per_voter, voter, DelegatedVotes { + active_shares, + pending_inactive_shares: inactive_shares, + active_shares_next_lockup: active_shares, + last_locked_until_secs: locked_until_secs, + }) + }; + + let delegated_votes = smart_table::borrow_mut(delegated_votes_per_voter, voter); + // A lockup period has passed since last time `delegated_votes` was updated. Pending voter takes effect. + if (delegated_votes.last_locked_until_secs < locked_until_secs) { + delegated_votes.active_shares = delegated_votes.active_shares_next_lockup; + delegated_votes.pending_inactive_shares = 0; + delegated_votes.last_locked_until_secs = locked_until_secs; + }; + delegated_votes + } + + fun olc_with_index(index: u64): ObservedLockupCycle { + ObservedLockupCycle { index } + } + + /// Given the amounts of shares in `active_shares` pool and `inactive_shares` pool, calculate the total voting + /// power, which equals to the sum of the coin amounts. + fun calculate_total_voting_power(delegation_pool: &DelegationPool, latest_delegated_votes: &DelegatedVotes): u64 { + let active_amount = pool_u64::shares_to_amount( + &delegation_pool.active_shares, + latest_delegated_votes.active_shares); + let pending_inactive_amount = pool_u64::shares_to_amount( + pending_inactive_shares_pool(delegation_pool), + latest_delegated_votes.pending_inactive_shares); + active_amount + pending_inactive_amount + } + + /// Update VoteDelegation of a delegator to up-to-date then return the latest voter. + fun calculate_and_update_delegator_voter_internal(pool: &DelegationPool, governance_records: &mut GovernanceRecords, delegator: address): address { + let vote_delegation = update_and_borrow_mut_delegator_vote_delegation(pool, governance_records, delegator); + vote_delegation.voter + } + + /// Update DelegatedVotes of a voter to up-to-date then return the total voting power of this voter. + fun calculate_and_update_delegated_votes(pool: &DelegationPool, governance_records: &mut GovernanceRecords, voter: address): u64 { + let delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, voter); + calculate_total_voting_power(pool, delegated_votes) + } + + /// Allows an owner to change the operator of the underlying stake pool. + public entry fun set_operator( + owner: &signer, + new_operator: address + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + let pool_address = get_owned_pool_address(signer::address_of(owner)); + // synchronize delegation and stake pools before any user operation + // ensure the old operator is paid its uncommitted commission rewards + synchronize_delegation_pool(pool_address); + stake::set_operator(&retrieve_stake_pool_owner(borrow_global(pool_address)), new_operator); + } + + /// Allows an owner to change the delegated voter of the underlying stake pool. + public entry fun set_delegated_voter( + owner: &signer, + new_voter: address + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + // No one can change delegated_voter once the partial governance voting feature is enabled. + assert!(!features::delegation_pool_partial_governance_voting_enabled(), error::invalid_state(EDEPRECATED_FUNCTION)); + let pool_address = get_owned_pool_address(signer::address_of(owner)); + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + stake::set_delegated_voter(&retrieve_stake_pool_owner(borrow_global(pool_address)), new_voter); + } + + /// Allows a delegator to delegate its voting power to a voter. If this delegator already has a delegated voter, + /// this change won't take effects until the next lockup period. + public entry fun delegate_voting_power( + delegator: &signer, + pool_address: address, + new_voter: address + ) acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let delegator_address = signer::address_of(delegator); + let delegation_pool = borrow_global(pool_address); + let governance_records = borrow_global_mut(pool_address); + let delegator_vote_delegation = update_and_borrow_mut_delegator_vote_delegation( + delegation_pool, + governance_records, + delegator_address + ); + let pending_voter: address = delegator_vote_delegation.pending_voter; + + // No need to update if the voter doesn't really change. + if (pending_voter != new_voter) { + delegator_vote_delegation.pending_voter = new_voter; + let active_shares = get_delegator_active_shares(delegation_pool, delegator_address); + // of -= + // of += + let pending_delegated_votes = update_and_borrow_mut_delegated_votes( + delegation_pool, + governance_records, + pending_voter + ); + pending_delegated_votes.active_shares_next_lockup = + pending_delegated_votes.active_shares_next_lockup - active_shares; + + let new_delegated_votes = update_and_borrow_mut_delegated_votes( + delegation_pool, + governance_records, + new_voter + ); + new_delegated_votes.active_shares_next_lockup = + new_delegated_votes.active_shares_next_lockup + active_shares; + }; + + event::emit_event(&mut governance_records.delegate_voting_power_events, DelegateVotingPowerEvent { + pool_address, + delegator: delegator_address, + voter: new_voter, + }); + } + + /// Add `amount` of coins to the delegation pool `pool_address`. + public entry fun add_stake(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords { + // short-circuit if amount to add is 0 so no event is emitted + if (amount == 0) { return }; + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + // fee to be charged for adding `amount` stake on this delegation pool at this epoch + let add_stake_fee = get_add_stake_fee(pool_address, amount); + + let pool = borrow_global_mut(pool_address); + let delegator_address = signer::address_of(delegator); + + // stake the entire amount to the stake pool + coin::transfer(delegator, pool_address, amount); + stake::add_stake(&retrieve_stake_pool_owner(pool), amount); + + // but buy shares for delegator just for the remaining amount after fee + buy_in_active_shares(pool, delegator_address, amount - add_stake_fee); + assert_min_active_balance(pool, delegator_address); + + // grant temporary ownership over `add_stake` fees to a separate shareholder in order to: + // - not mistake them for rewards to pay the operator from + // - distribute them together with the `active` rewards when this epoch ends + // in order to appreciate all shares on the active pool atomically + buy_in_active_shares(pool, NULL_SHAREHOLDER, add_stake_fee); + + event::emit_event( + &mut pool.add_stake_events, + AddStakeEvent { + pool_address, + delegator_address, + amount_added: amount, + add_stake_fee, + }, + ); + } + + /// Unlock `amount` from the active + pending_active stake of `delegator` or + /// at most how much active stake there is on the stake pool. + public entry fun unlock(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords { + // short-circuit if amount to unlock is 0 so no event is emitted + if (amount == 0) { return }; + + // fail unlock of more stake than `active` on the stake pool + let (active, _, _, _) = stake::get_stake(pool_address); + assert!(amount <= active, error::invalid_argument(ENOT_ENOUGH_ACTIVE_STAKE_TO_UNLOCK)); + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let pool = borrow_global_mut(pool_address); + let delegator_address = signer::address_of(delegator); + + amount = coins_to_transfer_to_ensure_min_stake( + &pool.active_shares, + pending_inactive_shares_pool(pool), + delegator_address, + amount, + ); + amount = redeem_active_shares(pool, delegator_address, amount); + + stake::unlock(&retrieve_stake_pool_owner(pool), amount); + + buy_in_pending_inactive_shares(pool, delegator_address, amount); + assert_min_pending_inactive_balance(pool, delegator_address); + + event::emit_event( + &mut pool.unlock_stake_events, + UnlockStakeEvent { + pool_address, + delegator_address, + amount_unlocked: amount, + }, + ); + } + + /// Move `amount` of coins from pending_inactive to active. + public entry fun reactivate_stake(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords { + // short-circuit if amount to reactivate is 0 so no event is emitted + if (amount == 0) { return }; + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let pool = borrow_global_mut(pool_address); + let delegator_address = signer::address_of(delegator); + + amount = coins_to_transfer_to_ensure_min_stake( + pending_inactive_shares_pool(pool), + &pool.active_shares, + delegator_address, + amount, + ); + let observed_lockup_cycle = pool.observed_lockup_cycle; + amount = redeem_inactive_shares(pool, delegator_address, amount, observed_lockup_cycle); + + stake::reactivate_stake(&retrieve_stake_pool_owner(pool), amount); + + buy_in_active_shares(pool, delegator_address, amount); + assert_min_active_balance(pool, delegator_address); + + event::emit_event( + &mut pool.reactivate_stake_events, + ReactivateStakeEvent { + pool_address, + delegator_address, + amount_reactivated: amount, + }, + ); + } + + /// Withdraw `amount` of owned inactive stake from the delegation pool at `pool_address`. + public entry fun withdraw(delegator: &signer, pool_address: address, amount: u64) acquires DelegationPool, GovernanceRecords { + assert!(amount > 0, error::invalid_argument(EWITHDRAW_ZERO_STAKE)); + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + withdraw_internal(borrow_global_mut(pool_address), signer::address_of(delegator), amount); + } + + fun withdraw_internal(pool: &mut DelegationPool, delegator_address: address, amount: u64) acquires GovernanceRecords { + // TODO: recycle storage when a delegator fully exits the delegation pool. + // short-circuit if amount to withdraw is 0 so no event is emitted + if (amount == 0) { return }; + + let pool_address = get_pool_address(pool); + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + // exit if no withdrawal or (it is pending and cannot withdraw pending_inactive stake from stake pool) + if (!( + withdrawal_exists && + (withdrawal_olc.index < pool.observed_lockup_cycle.index || can_withdraw_pending_inactive(pool_address)) + )) { return }; + + if (withdrawal_olc.index == pool.observed_lockup_cycle.index) { + amount = coins_to_redeem_to_ensure_min_stake( + pending_inactive_shares_pool(pool), + delegator_address, + amount, + ) + }; + amount = redeem_inactive_shares(pool, delegator_address, amount, withdrawal_olc); + + let stake_pool_owner = &retrieve_stake_pool_owner(pool); + // stake pool will inactivate entire pending_inactive stake at `stake::withdraw` to make it withdrawable + // however, bypassing the inactivation of excess stake (inactivated but not withdrawn) ensures + // the OLC is not advanced indefinitely on `unlock`-`withdraw` paired calls + if (can_withdraw_pending_inactive(pool_address)) { + // get excess stake before being entirely inactivated + let (_, _, _, pending_inactive) = stake::get_stake(pool_address); + if (withdrawal_olc.index == pool.observed_lockup_cycle.index) { + // `amount` less excess if withdrawing pending_inactive stake + pending_inactive = pending_inactive - amount + }; + // escape excess stake from inactivation + stake::reactivate_stake(stake_pool_owner, pending_inactive); + stake::withdraw(stake_pool_owner, amount); + // restore excess stake to the pending_inactive state + stake::unlock(stake_pool_owner, pending_inactive); + } else { + // no excess stake if `stake::withdraw` does not inactivate at all + stake::withdraw(stake_pool_owner, amount); + }; + coin::transfer(stake_pool_owner, delegator_address, amount); + + // commit withdrawal of possibly inactive stake to the `total_coins_inactive` + // known by the delegation pool in order to not mistake it for slashing at next synchronization + let (_, inactive, _, _) = stake::get_stake(pool_address); + pool.total_coins_inactive = inactive; + + event::emit_event( + &mut pool.withdraw_stake_events, + WithdrawStakeEvent { + pool_address, + delegator_address, + amount_withdrawn: amount, + }, + ); + } + + /// Return the unique observed lockup cycle where delegator `delegator_address` may have + /// unlocking (or already unlocked) stake to be withdrawn from delegation pool `pool`. + /// A bool is returned to signal if a pending withdrawal exists at all. + fun pending_withdrawal_exists(pool: &DelegationPool, delegator_address: address): (bool, ObservedLockupCycle) { + if (table::contains(&pool.pending_withdrawals, delegator_address)) { + (true, *table::borrow(&pool.pending_withdrawals, delegator_address)) + } else { + (false, olc_with_index(0)) + } + } + + /// Return a mutable reference to the shares pool of `pending_inactive` stake on the + /// delegation pool, always the last item in `inactive_shares`. + fun pending_inactive_shares_pool_mut(pool: &mut DelegationPool): &mut pool_u64::Pool { + let observed_lockup_cycle = pool.observed_lockup_cycle; + table::borrow_mut(&mut pool.inactive_shares, observed_lockup_cycle) + } + + fun pending_inactive_shares_pool(pool: &DelegationPool): &pool_u64::Pool { + table::borrow(&pool.inactive_shares, pool.observed_lockup_cycle) + } + + /// Execute the pending withdrawal of `delegator_address` on delegation pool `pool` + /// if existing and already inactive to allow the creation of a new one. + /// `pending_inactive` stake would be left untouched even if withdrawable and should + /// be explicitly withdrawn by delegator + fun execute_pending_withdrawal(pool: &mut DelegationPool, delegator_address: address) acquires GovernanceRecords { + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + if (withdrawal_exists && withdrawal_olc.index < pool.observed_lockup_cycle.index) { + withdraw_internal(pool, delegator_address, MAX_U64); + } + } + + /// Buy shares into the active pool on behalf of delegator `shareholder` who + /// deposited `coins_amount`. This function doesn't make any coin transfer. + fun buy_in_active_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + ): u128 acquires GovernanceRecords{ + let new_shares = pool_u64::amount_to_shares(&pool.active_shares, coins_amount); + // No need to buy 0 shares. + if (new_shares == 0) { return 0 }; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + if (partial_governance_voting_enabled(pool_address)) { + update_governance_records_for_buy_in_active_shares(pool, pool_address, new_shares, shareholder); + }; + + pool_u64::buy_in(&mut pool.active_shares, shareholder, coins_amount); + new_shares + } + + /// Buy shares into the pending_inactive pool on behalf of delegator `shareholder` who + /// redeemed `coins_amount` from the active pool to schedule it for unlocking. + /// If delegator's pending withdrawal exists and has been inactivated, execute it firstly + /// to ensure there is always only one withdrawal request. + fun buy_in_pending_inactive_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + ): u128 acquires GovernanceRecords { + let new_shares = pool_u64::amount_to_shares(pending_inactive_shares_pool(pool), coins_amount); + // never create a new pending withdrawal unless delegator owns some pending_inactive shares + if (new_shares == 0) { return 0 }; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + if (partial_governance_voting_enabled(pool_address)) { + update_governance_records_for_buy_in_pending_inactive_shares(pool, pool_address, new_shares, shareholder); + }; + + // cannot buy inactive shares, only pending_inactive at current lockup cycle + pool_u64::buy_in(pending_inactive_shares_pool_mut(pool), shareholder, coins_amount); + + // execute the pending withdrawal if exists and is inactive before creating a new one + execute_pending_withdrawal(pool, shareholder); + + // save observed lockup cycle for the new pending withdrawal + let observed_lockup_cycle = pool.observed_lockup_cycle; + assert!(*table::borrow_mut_with_default( + &mut pool.pending_withdrawals, + shareholder, + observed_lockup_cycle + ) == observed_lockup_cycle, + error::invalid_state(EPENDING_WITHDRAWAL_EXISTS) + ); + + new_shares + } + + /// Convert `coins_amount` of coins to be redeemed from shares pool `shares_pool` + /// to the exact number of shares to redeem in order to achieve this. + fun amount_to_shares_to_redeem( + shares_pool: &pool_u64::Pool, + shareholder: address, + coins_amount: u64, + ): u128 { + if (coins_amount >= pool_u64::balance(shares_pool, shareholder)) { + // cap result at total shares of shareholder to pass `EINSUFFICIENT_SHARES` on subsequent redeem + pool_u64::shares(shares_pool, shareholder) + } else { + pool_u64::amount_to_shares(shares_pool, coins_amount) + } + } + + /// Redeem shares from the active pool on behalf of delegator `shareholder` who + /// wants to unlock `coins_amount` of its active stake. + /// Extracted coins will be used to buy shares into the pending_inactive pool and + /// be available for withdrawal when current OLC ends. + fun redeem_active_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + ): u64 acquires GovernanceRecords { + let shares_to_redeem = amount_to_shares_to_redeem(&pool.active_shares, shareholder, coins_amount); + // silently exit if not a shareholder otherwise redeem would fail with `ESHAREHOLDER_NOT_FOUND` + if (shares_to_redeem == 0) return 0; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + if (partial_governance_voting_enabled(pool_address)) { + update_governanace_records_for_redeem_active_shares(pool, pool_address, shares_to_redeem, shareholder); + }; + + pool_u64::redeem_shares(&mut pool.active_shares, shareholder, shares_to_redeem) + } + + /// Redeem shares from the inactive pool at `lockup_cycle` < current OLC on behalf of + /// delegator `shareholder` who wants to withdraw `coins_amount` of its unlocked stake. + /// Redeem shares from the pending_inactive pool at `lockup_cycle` == current OLC on behalf of + /// delegator `shareholder` who wants to reactivate `coins_amount` of its unlocking stake. + /// For latter case, extracted coins will be used to buy shares into the active pool and + /// escape inactivation when current lockup ends. + fun redeem_inactive_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + lockup_cycle: ObservedLockupCycle, + ): u64 acquires GovernanceRecords { + let shares_to_redeem = amount_to_shares_to_redeem( + table::borrow(&pool.inactive_shares, lockup_cycle), + shareholder, + coins_amount); + // silently exit if not a shareholder otherwise redeem would fail with `ESHAREHOLDER_NOT_FOUND` + if (shares_to_redeem == 0) return 0; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + // Only redeem shares from the pending_inactive pool at `lockup_cycle` == current OLC. + if (partial_governance_voting_enabled(pool_address) && lockup_cycle.index == pool.observed_lockup_cycle.index) { + update_governanace_records_for_redeem_pending_inactive_shares(pool, pool_address, shares_to_redeem, shareholder); + }; + + let inactive_shares = table::borrow_mut(&mut pool.inactive_shares, lockup_cycle); + // 1. reaching here means delegator owns inactive/pending_inactive shares at OLC `lockup_cycle` + let redeemed_coins = pool_u64::redeem_shares(inactive_shares, shareholder, shares_to_redeem); + + // if entirely reactivated pending_inactive stake or withdrawn inactive one, + // re-enable unlocking for delegator by deleting this pending withdrawal + if (pool_u64::shares(inactive_shares, shareholder) == 0) { + // 2. a delegator owns inactive/pending_inactive shares only at the OLC of its pending withdrawal + // 1 & 2: the pending withdrawal itself has been emptied of shares and can be safely deleted + table::remove(&mut pool.pending_withdrawals, shareholder); + }; + // destroy inactive shares pool of past OLC if all its stake has been withdrawn + if (lockup_cycle.index < pool.observed_lockup_cycle.index && total_coins(inactive_shares) == 0) { + pool_u64::destroy_empty(table::remove(&mut pool.inactive_shares, lockup_cycle)); + }; + + redeemed_coins + } + + /// Calculate stake deviations between the delegation and stake pools in order to + /// capture the rewards earned in the meantime, resulted operator commission and + /// whether the lockup expired on the stake pool. + fun calculate_stake_pool_drift(pool: &DelegationPool): (bool, u64, u64, u64, u64) { + let (active, inactive, pending_active, pending_inactive) = stake::get_stake(get_pool_address(pool)); + assert!( + inactive >= pool.total_coins_inactive, + error::invalid_state(ESLASHED_INACTIVE_STAKE_ON_PAST_OLC) + ); + // determine whether a new lockup cycle has been ended on the stake pool and + // inactivated SOME `pending_inactive` stake which should stop earning rewards now, + // thus requiring separation of the `pending_inactive` stake on current observed lockup + // and the future one on the newly started lockup + let lockup_cycle_ended = inactive > pool.total_coins_inactive; + + // actual coins on stake pool belonging to the active shares pool + active = active + pending_active; + // actual coins on stake pool belonging to the shares pool hosting `pending_inactive` stake + // at current observed lockup cycle, either pending: `pending_inactive` or already inactivated: + if (lockup_cycle_ended) { + // `inactive` on stake pool = any previous `inactive` stake + + // any previous `pending_inactive` stake and its rewards (both inactivated) + pending_inactive = inactive - pool.total_coins_inactive + }; + + // on stake-management operations, total coins on the internal shares pools and individual + // stakes on the stake pool are updated simultaneously, thus the only stakes becoming + // unsynced are rewards and slashes routed exclusively to/out the stake pool + + // operator `active` rewards not persisted yet to the active shares pool + let commission_active = total_coins(&pool.active_shares); + commission_active = if (active > commission_active) { + multiply_then_divide(active - commission_active, pool.operator_commission_percentage, MAX_FEE) + } else { + // handle any slashing applied to `active` stake + 0 + }; + // operator `pending_inactive` rewards not persisted yet to the pending_inactive shares pool + let commission_pending_inactive = total_coins(pending_inactive_shares_pool(pool)); + commission_pending_inactive = if (pending_inactive > commission_pending_inactive) { + multiply_then_divide( + pending_inactive - commission_pending_inactive, + pool.operator_commission_percentage, + MAX_FEE + ) + } else { + // handle any slashing applied to `pending_inactive` stake + 0 + }; + + (lockup_cycle_ended, active, pending_inactive, commission_active, commission_pending_inactive) + } + + /// Synchronize delegation and stake pools: distribute yet-undetected rewards to the corresponding internal + /// shares pools, assign commission to operator and eventually prepare delegation pool for a new lockup cycle. + public entry fun synchronize_delegation_pool(pool_address: address) acquires DelegationPool, GovernanceRecords { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global_mut(pool_address); + let ( + lockup_cycle_ended, + active, + pending_inactive, + commission_active, + commission_pending_inactive + ) = calculate_stake_pool_drift(pool); + + // zero `pending_active` stake indicates that either there are no `add_stake` fees or + // previous epoch has ended and should release the shares owning the existing fees + let (_, _, pending_active, _) = stake::get_stake(pool_address); + if (pending_active == 0) { + // renounce ownership over the `add_stake` fees by redeeming all shares of + // the special shareholder, implicitly their equivalent coins, out of the active shares pool + redeem_active_shares(pool, NULL_SHAREHOLDER, MAX_U64); + }; + + // distribute rewards remaining after commission, to delegators (to already existing shares) + // before buying shares for the operator for its entire commission fee + // otherwise, operator's new shares would additionally appreciate from rewards it does not own + + // update total coins accumulated by `active` + `pending_active` shares + // redeemed `add_stake` fees are restored and distributed to the rest of the pool as rewards + pool_u64::update_total_coins(&mut pool.active_shares, active - commission_active); + // update total coins accumulated by `pending_inactive` shares at current observed lockup cycle + pool_u64::update_total_coins( + pending_inactive_shares_pool_mut(pool), + pending_inactive - commission_pending_inactive + ); + + // reward operator its commission out of uncommitted active rewards (`add_stake` fees already excluded) + buy_in_active_shares(pool, stake::get_operator(pool_address), commission_active); + // reward operator its commission out of uncommitted pending_inactive rewards + buy_in_pending_inactive_shares(pool, stake::get_operator(pool_address), commission_pending_inactive); + + event::emit_event( + &mut pool.distribute_commission_events, + DistributeCommissionEvent { + pool_address, + operator: stake::get_operator(pool_address), + commission_active, + commission_pending_inactive, + }, + ); + + // advance lockup cycle on delegation pool if already ended on stake pool (AND stake explicitly inactivated) + if (lockup_cycle_ended) { + // capture inactive coins over all ended lockup cycles (including this ending one) + let (_, inactive, _, _) = stake::get_stake(pool_address); + pool.total_coins_inactive = inactive; + + // advance lockup cycle on the delegation pool + pool.observed_lockup_cycle.index = pool.observed_lockup_cycle.index + 1; + // start new lockup cycle with a fresh shares pool for `pending_inactive` stake + table::add( + &mut pool.inactive_shares, + pool.observed_lockup_cycle, + pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR) + ); + } + } + + inline fun assert_and_update_proposal_used_voting_power( + governance_records: &mut GovernanceRecords, pool_address : address, proposal_id : u64, voting_power: u64 + ) { + let stake_pool_remaining_voting_power = aptos_governance::get_remaining_voting_power(pool_address, proposal_id); + let stake_pool_used_voting_power = aptos_governance::get_voting_power(pool_address) - stake_pool_remaining_voting_power; + let proposal_used_voting_power = smart_table::borrow_mut_with_default(&mut governance_records.votes_per_proposal, proposal_id, 0); + // A edge case: Before enabling partial governance voting on a delegation pool, the delegation pool has + // a voter which can vote with all voting power of this delegation pool. If the voter votes on a proposal after + // partial governance voting flag is enabled, the delegation pool doesn't have enough voting power on this + // proposal for all the delegators. To be fair, no one can vote on this proposal through this delegation pool. + // To detect this case, check if the stake pool had used voting power not through delegation_pool module. + assert!(stake_pool_used_voting_power == *proposal_used_voting_power, error::invalid_argument(EALREADY_VOTED_BEFORE_ENABLE_PARTIAL_VOTING)); + *proposal_used_voting_power = *proposal_used_voting_power + voting_power; + } + + fun update_governance_records_for_buy_in_active_shares( + pool: &DelegationPool, pool_address: address, new_shares: u128, shareholder: address + ) acquires GovernanceRecords{ + // of += ----> + // of += + // of += + let governance_records = borrow_global_mut(pool_address); + let vote_delegation = update_and_borrow_mut_delegator_vote_delegation(pool, governance_records, shareholder); + let current_voter = vote_delegation.voter; + let pending_voter = vote_delegation.pending_voter; + let current_delegated_votes = + update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.active_shares = current_delegated_votes.active_shares + new_shares; + if (pending_voter == current_voter) { + current_delegated_votes.active_shares_next_lockup = + current_delegated_votes.active_shares_next_lockup + new_shares; + } else { + let pending_delegated_votes = + update_and_borrow_mut_delegated_votes(pool, governance_records, pending_voter); + pending_delegated_votes.active_shares_next_lockup = + pending_delegated_votes.active_shares_next_lockup + new_shares; + }; + } + + fun update_governance_records_for_buy_in_pending_inactive_shares( + pool: &DelegationPool, pool_address: address, new_shares: u128, shareholder: address + ) acquires GovernanceRecords { + // of += ----> + // of += + // no impact on of + let governance_records = borrow_global_mut(pool_address); + let current_voter = calculate_and_update_delegator_voter_internal(pool, governance_records, shareholder); + let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.pending_inactive_shares = current_delegated_votes.pending_inactive_shares + new_shares; + } + + fun update_governanace_records_for_redeem_active_shares( + pool: &DelegationPool, pool_address: address, shares_to_redeem: u128, shareholder: address + ) acquires GovernanceRecords { + // of -= ----> + // of -= + // of -= + let governance_records = borrow_global_mut(pool_address); + let vote_delegation = update_and_borrow_mut_delegator_vote_delegation( + pool, + governance_records, + shareholder + ); + let current_voter = vote_delegation.voter; + let pending_voter = vote_delegation.pending_voter; + let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.active_shares = current_delegated_votes.active_shares - shares_to_redeem; + if (current_voter == pending_voter) { + current_delegated_votes.active_shares_next_lockup = + current_delegated_votes.active_shares_next_lockup - shares_to_redeem; + } else { + let pending_delegated_votes = + update_and_borrow_mut_delegated_votes(pool, governance_records, pending_voter); + pending_delegated_votes.active_shares_next_lockup = + pending_delegated_votes.active_shares_next_lockup - shares_to_redeem; + }; + } + + fun update_governanace_records_for_redeem_pending_inactive_shares( + pool: &DelegationPool, pool_address: address, shares_to_redeem: u128, shareholder: address + ) acquires GovernanceRecords { + // of -= ----> + // of -= + // no impact on of + let governance_records = borrow_global_mut(pool_address); + let current_voter = calculate_and_update_delegator_voter_internal(pool, governance_records, shareholder); + let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.pending_inactive_shares = current_delegated_votes.pending_inactive_shares - shares_to_redeem; + } + + public fun multiply_then_divide(x: u64, y: u64, z: u64): u64 { + let result = (to_u128(x) * to_u128(y)) / to_u128(z); + (result as u64) + } + + fun to_u128(num: u64): u128 { + (num as u128) + } + + #[test_only] + use aptos_framework::reconfiguration; + #[test_only] + use aptos_std::fixed_point64; + #[test_only] + use aptos_framework::timestamp::fast_forward_seconds; + + #[test_only] + const CONSENSUS_KEY_1: vector = x"8a54b92288d4ba5073d3a52e80cc00ae9fbbc1cc5b433b46089b7804c38a76f00fc64746c7685ee628fc2d0b929c2294"; + #[test_only] + const CONSENSUS_POP_1: vector = x"a9d6c1f1270f2d1454c89a83a4099f813a56dc7db55591d46aa4e6ccae7898b234029ba7052f18755e6fa5e6b73e235f14efc4e2eb402ca2b8f56bad69f965fc11b7b25eb1c95a06f83ddfd023eac4559b6582696cfea97b227f4ce5bdfdfed0"; + + #[test_only] + const EPOCH_DURATION: u64 = 60; + #[test_only] + const LOCKUP_CYCLE_SECONDS: u64 = 3600; + + #[test_only] + const ONE_APT: u64 = 100000000; + + #[test_only] + const VALIDATOR_STATUS_PENDING_ACTIVE: u64 = 1; + #[test_only] + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + #[test_only] + const VALIDATOR_STATUS_PENDING_INACTIVE: u64 = 3; + + #[test_only] + const DELEGATION_POOLS: u64 = 11; + + #[test_only] + public fun end_aptos_epoch() { + stake::end_epoch(); // additionally forwards EPOCH_DURATION seconds + reconfiguration::reconfigure_for_test_custom(); + } + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer) { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 1, + 100, + 1000000 + ); + } + + #[test_only] + public fun initialize_for_test_no_reward(aptos_framework: &signer) { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 0, + 100, + 1000000 + ); + } + + #[test_only] + public fun initialize_for_test_custom( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_secs: u64, + allow_validator_set_change: bool, + rewards_rate_numerator: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + account::create_account_for_test(signer::address_of(aptos_framework)); + stake::initialize_for_test_custom( + aptos_framework, + minimum_stake, + maximum_stake, + recurring_lockup_secs, + allow_validator_set_change, + rewards_rate_numerator, + rewards_rate_denominator, + voting_power_increase_limit, + ); + reconfiguration::initialize_for_test(aptos_framework); + features::change_feature_flags(aptos_framework, vector[DELEGATION_POOLS], vector[]); + } + + #[test_only] + public fun initialize_test_validator( + validator: &signer, + amount: u64, + should_join_validator_set: bool, + should_end_epoch: bool, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_test_validator_custom(validator, amount, should_join_validator_set, should_end_epoch, 0); + } + + #[test_only] + public fun initialize_test_validator_custom( + validator: &signer, + amount: u64, + should_join_validator_set: bool, + should_end_epoch: bool, + commission_percentage: u64, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + let validator_address = signer::address_of(validator); + if (!account::exists_at(validator_address)) { + account::create_account_for_test(validator_address); + }; + + initialize_delegation_pool(validator, commission_percentage, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + + stake::rotate_consensus_key(validator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + + if (amount > 0) { + stake::mint(validator, amount); + add_stake(validator, pool_address, amount); + }; + + if (should_join_validator_set) { + stake::join_validator_set(validator, pool_address); + }; + + if (should_end_epoch) { + end_aptos_epoch(); + }; + } + + #[test_only] + fun unlock_with_min_stake_disabled( + delegator: &signer, + pool_address: address, + amount: u64 + ) acquires DelegationPool, GovernanceRecords { + synchronize_delegation_pool(pool_address); + + let pool = borrow_global_mut(pool_address); + let delegator_address = signer::address_of(delegator); + + amount = redeem_active_shares(pool, delegator_address, amount); + stake::unlock(&retrieve_stake_pool_owner(pool), amount); + buy_in_pending_inactive_shares(pool, delegator_address, amount); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x3000A, location = Self)] + public entry fun test_delegation_pools_disabled( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + features::change_feature_flags(aptos_framework, vector[], vector[DELEGATION_POOLS]); + + initialize_delegation_pool(validator, 0, vector::empty()); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_set_operator_and_delegated_voter( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + initialize_delegation_pool(validator, 0, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + + assert!(stake::get_operator(pool_address) == @0x123, 1); + assert!(stake::get_delegated_voter(pool_address) == @0x123, 1); + + set_operator(validator, @0x111); + assert!(stake::get_operator(pool_address) == @0x111, 2); + + set_delegated_voter(validator, @0x112); + assert!(stake::get_delegated_voter(pool_address) == @0x112, 2); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun test_cannot_set_operator( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + // account does not own any delegation pool + set_operator(validator, @0x111); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun test_cannot_set_delegated_voter( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + // account does not own any delegation pool + set_delegated_voter(validator, @0x112); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x80002, location = Self)] + public entry fun test_already_owns_delegation_pool( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_delegation_pool(validator, 0, x"00"); + initialize_delegation_pool(validator, 0, x"01"); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_cannot_withdraw_zero_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_delegation_pool(validator, 0, x"00"); + withdraw(validator, get_owned_pool_address(signer::address_of(validator)), 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_initialize_delegation_pool( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + initialize_delegation_pool(validator, 1234, vector::empty()); + + assert_owner_cap_exists(validator_address); + let pool_address = get_owned_pool_address(validator_address); + assert_delegation_pool_exists(pool_address); + + assert!(stake::stake_pool_exists(pool_address), 0); + assert!(stake::get_operator(pool_address) == validator_address, 0); + assert!(stake::get_delegated_voter(pool_address) == validator_address, 0); + + assert!(observed_lockup_cycle(pool_address) == 0, 0); + assert!(total_coins_inactive(pool_address) == 0, 0); + assert!(operator_commission_percentage(pool_address) == 1234, 0); + assert_inactive_shares_pool(pool_address, 0, true, 0); + stake::assert_stake_pool(pool_address, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_add_stake_fee( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 1, + 100, + 1000000 + ); + + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + + // create delegation pool with 37.35% operator commission + initialize_delegation_pool(validator, 3735, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + + stake::rotate_consensus_key(validator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + + // zero `add_stake` fee as validator is not producing rewards this epoch + assert!(get_add_stake_fee(pool_address, 1000000 * ONE_APT) == 0, 0); + + // add 1M APT, join the validator set and activate this stake + stake::mint(validator, 1000000 * ONE_APT); + add_stake(validator, pool_address, 1000000 * ONE_APT); + + stake::join_validator_set(validator, pool_address); + end_aptos_epoch(); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + // `add_stake` fee for 100000 coins: 100000 * 0.006265 / (1 + 0.006265) + assert!(get_add_stake_fee(pool_address, 100000 * ONE_APT) == 62259941466, 0); + + // add pending_active stake from multiple delegators + stake::mint(delegator1, 100000 * ONE_APT); + add_stake(delegator1, pool_address, 100000 * ONE_APT); + stake::mint(delegator2, 10000 * ONE_APT); + add_stake(delegator2, pool_address, 10000 * ONE_APT); + + end_aptos_epoch(); + // delegators should own the same amount as initially deposited + assert_delegation(delegator1_address, pool_address, 10000000000000, 0, 0); + assert_delegation(delegator2_address, pool_address, 1000000000000, 0, 0); + + // add more stake from delegator 1 + stake::mint(delegator1, 10000 * ONE_APT); + let (delegator1_active, _, _) = get_stake(pool_address, delegator1_address); + add_stake(delegator1, pool_address, 10000 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 10000 * ONE_APT); + assert_delegation(delegator1_address, pool_address, delegator1_active + 10000 * ONE_APT - fee, 0, 0); + + // delegator 2 should not benefit in any way from this new stake + assert_delegation(delegator2_address, pool_address, 1000000000000, 0, 0); + + // add more stake from delegator 2 + stake::mint(delegator2, 100000 * ONE_APT); + add_stake(delegator2, pool_address, 100000 * ONE_APT); + + end_aptos_epoch(); + // delegators should own the same amount as initially deposited + any rewards produced + // 10000000000000 * 1% * (100 - 37.35)% + assert_delegation(delegator1_address, pool_address, 11062650000001, 0, 0); + // 1000000000000 * 1% * (100 - 37.35)% + assert_delegation(delegator2_address, pool_address, 11006265000001, 0, 0); + + // in-flight operator commission rewards do not automatically restake/compound + synchronize_delegation_pool(pool_address); + + // stakes should remain the same - `Self::get_stake` correctly calculates them + assert_delegation(delegator1_address, pool_address, 11062650000001, 0, 0); + assert_delegation(delegator2_address, pool_address, 11006265000001, 0, 0); + + end_aptos_epoch(); + // delegators should own previous stake * 1.006265 + assert_delegation(delegator1_address, pool_address, 11131957502251, 0, 0); + assert_delegation(delegator2_address, pool_address, 11075219250226, 0, 0); + + // add more stake from delegator 1 + stake::mint(delegator1, 20000 * ONE_APT); + (delegator1_active, _, _) = get_stake(pool_address, delegator1_address); + add_stake(delegator1, pool_address, 20000 * ONE_APT); + + fee = get_add_stake_fee(pool_address, 20000 * ONE_APT); + assert_delegation(delegator1_address, pool_address, delegator1_active + 20000 * ONE_APT - fee, 0, 0); + + // delegator 1 unlocks his entire newly added stake + unlock(delegator1, pool_address, 20000 * ONE_APT - fee); + end_aptos_epoch(); + // delegator 1 should own previous 11131957502250 active * 1.006265 and 20000 coins pending_inactive + assert_delegation(delegator1_address, pool_address, 11201699216002, 0, 2000000000000); + + // stakes should remain the same - `Self::get_stake` correctly calculates them + synchronize_delegation_pool(pool_address); + assert_delegation(delegator1_address, pool_address, 11201699216002, 0, 2000000000000); + + let reward_period_start_time_in_sec = timestamp::now_seconds(); + // Enable rewards rate decrease. Initially rewards rate is still 1% every epoch. Rewards rate halves every year. + let one_year_in_secs: u64 = 31536000; + staking_config::initialize_rewards( + aptos_framework, + fixed_point64::create_from_rational(2, 100), + fixed_point64::create_from_rational(6, 1000), + one_year_in_secs, + reward_period_start_time_in_sec, + fixed_point64::create_from_rational(50, 100), + ); + features::change_feature_flags(aptos_framework, vector[features::get_periodical_reward_rate_decrease_feature()], vector[]); + + // add more stake from delegator 1 + stake::mint(delegator1, 20000 * ONE_APT); + let delegator1_pending_inactive: u64; + (delegator1_active, _, delegator1_pending_inactive) = get_stake(pool_address, delegator1_address); + fee = get_add_stake_fee(pool_address, 20000 * ONE_APT); + add_stake(delegator1, pool_address, 20000 * ONE_APT); + + assert_delegation(delegator1_address, pool_address, delegator1_active + 20000 * ONE_APT - fee, 0, delegator1_pending_inactive); + + // delegator 1 unlocks his entire newly added stake + unlock(delegator1, pool_address, 20000 * ONE_APT - fee); + end_aptos_epoch(); + // delegator 1 should own previous 11201699216002 active * ~1.01253 and 20000 * ~1.01253 + 20000 coins pending_inactive + assert_delegation(delegator1_address, pool_address, 11342056366822, 0, 4025059974939); + + // stakes should remain the same - `Self::get_stake` correctly calculates them + synchronize_delegation_pool(pool_address); + assert_delegation(delegator1_address, pool_address, 11342056366822, 0, 4025059974939); + + fast_forward_seconds(one_year_in_secs); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_never_create_pending_withdrawal_if_no_shares_bought( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + // add stake without fees as validator is not active yet + stake::mint(delegator, 10 * ONE_APT); + add_stake(delegator, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + unlock(validator, pool_address, 100 * ONE_APT); + + stake::assert_stake_pool(pool_address, 91000000000, 0, 0, 10000000000); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 91910000000, 0, 0, 10100000000); + + unlock_with_min_stake_disabled(delegator, pool_address, 1); + // request 1 coins * 910 / 919.1 = 0.99 shares to redeem * 1.01 price -> 0 coins out + // 1 coins lost at redeem due to 0.99 shares being burned + assert_delegation(delegator_address, pool_address, 1009999999, 0, 0); + assert_pending_withdrawal(delegator_address, pool_address, false, 0, false, 0); + + unlock_with_min_stake_disabled(delegator, pool_address, 2); + // request 2 coins * 909.99 / 919.1 = 1.98 shares to redeem * 1.01 price -> 1 coins out + // with 1 coins buy 1 * 100 / 101 = 0.99 shares in pending_inactive pool * 1.01 -> 0 coins in + // 1 coins lost at redeem due to 1.98 - 1.01 shares being burned + 1 coins extracted + synchronize_delegation_pool(pool_address); + assert_delegation(delegator_address, pool_address, 1009999997, 0, 0); + // the pending withdrawal has been created as > 0 pending_inactive shares have been bought + assert_pending_withdrawal(delegator_address, pool_address, true, 0, false, 0); + + // successfully delete the pending withdrawal (redeem all owned shares even worth 0 coins) + reactivate_stake(delegator, pool_address, 1); + assert_delegation(delegator_address, pool_address, 1009999997, 0, 0); + assert_pending_withdrawal(delegator_address, pool_address, false, 0, false, 0); + + // unlock min coins to own some pending_inactive balance (have to disable min-balance checks) + unlock_with_min_stake_disabled(delegator, pool_address, 3); + // request 3 coins * 909.99 / 919.09 = 2.97 shares to redeem * 1.01 price -> 2 coins out + // with 2 coins buy 2 * 100 / 101 = 1.98 shares in pending_inactive pool * 1.01 -> 1 coins in + // 1 coins lost at redeem due to 2.97 - 2 * 1.01 shares being burned + 2 coins extracted + synchronize_delegation_pool(pool_address); + assert_delegation(delegator_address, pool_address, 1009999994, 0, 1); + // the pending withdrawal has been created as > 0 pending_inactive shares have been bought + assert_pending_withdrawal(delegator_address, pool_address, true, 0, false, 1); + + reactivate_stake(delegator, pool_address, 1); + // redeem 1 coins >= delegator balance -> all shares are redeemed and pending withdrawal is deleted + assert_delegation(delegator_address, pool_address, 1009999995, 0, 0); + // the pending withdrawal has been deleted as delegator has 0 pending_inactive shares now + assert_pending_withdrawal(delegator_address, pool_address, false, 0, false, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10008, location = Self)] + public entry fun test_add_stake_min_amount( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, MIN_COINS_ON_SHARES_POOL - 1, false, false); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_add_stake_single( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, false, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + // validator is inactive => added stake is `active` by default + stake::assert_stake_pool(pool_address, 1000 * ONE_APT, 0, 0, 0); + assert_delegation(validator_address, pool_address, 1000 * ONE_APT, 0, 0); + + // zero `add_stake` fee as validator is not producing rewards this epoch + assert!(get_add_stake_fee(pool_address, 250 * ONE_APT) == 0, 0); + + // check `add_stake` increases `active` stakes of delegator and stake pool + stake::mint(validator, 300 * ONE_APT); + let balance = coin::balance(validator_address); + add_stake(validator, pool_address, 250 * ONE_APT); + + // check added stake have been transferred out of delegator account + assert!(coin::balance(validator_address) == balance - 250 * ONE_APT, 0); + // zero `add_stake` fee charged from added stake + assert_delegation(validator_address, pool_address, 1250 * ONE_APT, 0, 0); + // zero `add_stake` fee transferred to null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + // added stake is automatically `active` on inactive validator + stake::assert_stake_pool(pool_address, 1250 * ONE_APT, 0, 0, 0); + + // activate validator + stake::join_validator_set(validator, pool_address); + end_aptos_epoch(); + + // add 250 coins being pending_active until next epoch + stake::mint(validator, 250 * ONE_APT); + add_stake(validator, pool_address, 250 * ONE_APT); + + let fee1 = get_add_stake_fee(pool_address, 250 * ONE_APT); + assert_delegation(validator_address, pool_address, 1500 * ONE_APT - fee1, 0, 0); + // check `add_stake` fee has been transferred to the null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, fee1, 0, 0); + stake::assert_stake_pool(pool_address, 1250 * ONE_APT, 0, 250 * ONE_APT, 0); + + // add 100 additional coins being pending_active until next epoch + stake::mint(validator, 100 * ONE_APT); + add_stake(validator, pool_address, 100 * ONE_APT); + + let fee2 = get_add_stake_fee(pool_address, 100 * ONE_APT); + assert_delegation(validator_address, pool_address, 1600 * ONE_APT - fee1 - fee2, 0, 0); + // check `add_stake` fee has been transferred to the null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, fee1 + fee2, 0, 0); + stake::assert_stake_pool(pool_address, 1250 * ONE_APT, 0, 350 * ONE_APT, 0); + + end_aptos_epoch(); + // delegator got its `add_stake` fees back + 1250 * 1% * (100% - 0%) active rewards + assert_delegation(validator_address, pool_address, 161250000000, 0, 0); + stake::assert_stake_pool(pool_address, 161250000000, 0, 0, 0); + + // check that shares of null shareholder have been released + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + synchronize_delegation_pool(pool_address); + assert!(pool_u64::shares(&borrow_global(pool_address).active_shares, NULL_SHAREHOLDER) == 0, 0); + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + + // add 200 coins being pending_active until next epoch + stake::mint(validator, 200 * ONE_APT); + add_stake(validator, pool_address, 200 * ONE_APT); + + fee1 = get_add_stake_fee(pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 181250000000 - fee1, 0, 0); + // check `add_stake` fee has been transferred to the null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, fee1 - 1, 0, 0); + stake::assert_stake_pool(pool_address, 161250000000, 0, 20000000000, 0); + + end_aptos_epoch(); + // delegator got its `add_stake` fee back + 161250000000 * 1% active rewards + assert_delegation(validator_address, pool_address, 182862500000, 0, 0); + stake::assert_stake_pool(pool_address, 182862500000, 0, 0, 0); + + // check that shares of null shareholder have been released + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + synchronize_delegation_pool(pool_address); + assert!(pool_u64::shares(&borrow_global(pool_address).active_shares, NULL_SHAREHOLDER) == 0, 0); + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_add_stake_many( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::assert_stake_pool(pool_address, 1000 * ONE_APT, 0, 0, 0); + assert_delegation(validator_address, pool_address, 1000 * ONE_APT, 0, 0); + + // add 250 coins from second account + stake::mint(delegator, 250 * ONE_APT); + add_stake(delegator, pool_address, 250 * ONE_APT); + + let fee1 = get_add_stake_fee(pool_address, 250 * ONE_APT); + assert_delegation(delegator_address, pool_address, 250 * ONE_APT - fee1, 0, 0); + assert_delegation(validator_address, pool_address, 1000 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 1000 * ONE_APT, 0, 250 * ONE_APT, 0); + + end_aptos_epoch(); + // 1000 * 1.01 active stake + 250 pending_active stake + stake::assert_stake_pool(pool_address, 1260 * ONE_APT, 0, 0, 0); + // delegator got its `add_stake` fee back + assert_delegation(delegator_address, pool_address, 250 * ONE_APT, 0, 0); + // actual active rewards have been distributed to their earner(s) + assert_delegation(validator_address, pool_address, 100999999999, 0, 0); + + // add another 250 coins from first account + stake::mint(validator, 250 * ONE_APT); + add_stake(validator, pool_address, 250 * ONE_APT); + + fee1 = get_add_stake_fee(pool_address, 250 * ONE_APT); + assert_delegation(validator_address, pool_address, 125999999999 - fee1, 0, 0); + assert_delegation(delegator_address, pool_address, 250 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 1260 * ONE_APT, 0, 250 * ONE_APT, 0); + + // add another 100 coins from second account + stake::mint(delegator, 100 * ONE_APT); + add_stake(delegator, pool_address, 100 * ONE_APT); + + let fee2 = get_add_stake_fee(pool_address, 100 * ONE_APT); + assert_delegation(delegator_address, pool_address, 350 * ONE_APT - fee2, 0, 0); + assert_delegation(validator_address, pool_address, 125999999999 - fee1, 0, 0); + stake::assert_stake_pool(pool_address, 1260 * ONE_APT, 0, 350 * ONE_APT, 0); + + end_aptos_epoch(); + // both delegators got their `add_stake` fees back + // 250 * 1.01 active stake + 100 pending_active stake + assert_delegation(delegator_address, pool_address, 35250000001, 0, 0); + // 1010 * 1.01 active stake + 250 pending_active stake + assert_delegation(validator_address, pool_address, 127009999998, 0, 0); + stake::assert_stake_pool(pool_address, 162260000000, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_unlock_single( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + // add 200 coins pending_active until next epoch + stake::mint(validator, 200 * ONE_APT); + add_stake(validator, pool_address, 200 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 300 * ONE_APT - fee, 0, 0); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 200 * ONE_APT, 0); + + // cannot unlock pending_active stake (only 100/300 stake can be displaced) + unlock(validator, pool_address, 100 * ONE_APT); + assert_delegation(validator_address, pool_address, 200 * ONE_APT - fee, 0, 100 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 0, 0, 200 * ONE_APT, 100 * ONE_APT); + assert_inactive_shares_pool(pool_address, 0, true, 100 * ONE_APT); + + // reactivate entire pending_inactive stake progressively + reactivate_stake(validator, pool_address, 50 * ONE_APT); + + assert_delegation(validator_address, pool_address, 250 * ONE_APT - fee, 0, 50 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 50 * ONE_APT); + stake::assert_stake_pool(pool_address, 50 * ONE_APT, 0, 200 * ONE_APT, 50 * ONE_APT); + + reactivate_stake(validator, pool_address, 50 * ONE_APT); + + assert_delegation(validator_address, pool_address, 300 * ONE_APT - fee, 0, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 200 * ONE_APT, 0); + // pending_inactive shares pool has not been deleted (as can still `unlock` this OLC) + assert_inactive_shares_pool(pool_address, 0, true, 0); + + end_aptos_epoch(); + // 10000000000 * 1.01 active stake + 20000000000 pending_active stake + assert_delegation(validator_address, pool_address, 301 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 301 * ONE_APT, 0, 0, 0); + + // can unlock more than at previous epoch as the pending_active stake became active + unlock(validator, pool_address, 150 * ONE_APT); + assert_delegation(validator_address, pool_address, 15100000001, 0, 14999999999); + stake::assert_stake_pool(pool_address, 15100000001, 0, 0, 14999999999); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 14999999999); + + assert!(stake::get_remaining_lockup_secs(pool_address) == LOCKUP_CYCLE_SECONDS - EPOCH_DURATION, 0); + end_aptos_epoch(); // additionally forwards EPOCH_DURATION seconds + + // pending_inactive stake should have not been inactivated + // 15100000001 * 1.01 active stake + 14999999999 pending_inactive * 1.01 stake + assert_delegation(validator_address, pool_address, 15251000001, 0, 15149999998); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 15149999998); + stake::assert_stake_pool(pool_address, 15251000001, 0, 0, 15149999998); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS - 3 * EPOCH_DURATION); + end_aptos_epoch(); // additionally forwards EPOCH_DURATION seconds and expires lockup cycle + + // 15251000001 * 1.01 active stake + 15149999998 * 1.01 pending_inactive(now inactive) stake + assert_delegation(validator_address, pool_address, 15403510001, 15301499997, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 15301499997); + stake::assert_stake_pool(pool_address, 15403510001, 15301499997, 0, 0); + + // add 50 coins from another account + stake::mint(delegator, 50 * ONE_APT); + add_stake(delegator, pool_address, 50 * ONE_APT); + + // observed lockup cycle should have advanced at `add_stake`(on synchronization) + assert!(observed_lockup_cycle(pool_address) == 1, 0); + + fee = get_add_stake_fee(pool_address, 50 * ONE_APT); + assert_delegation(delegator_address, pool_address, 4999999999 - fee, 0, 0); + assert_delegation(validator_address, pool_address, 15403510001, 15301499997, 0); + stake::assert_stake_pool(pool_address, 15403510001, 15301499997, 50 * ONE_APT, 0); + + // cannot withdraw stake unlocked by others + withdraw(delegator, pool_address, 50 * ONE_APT); + assert!(coin::balance(delegator_address) == 0, 0); + + // withdraw own unlocked stake + withdraw(validator, pool_address, 15301499997); + assert!(coin::balance(validator_address) == 15301499997, 0); + assert_delegation(validator_address, pool_address, 15403510001, 0, 0); + // pending withdrawal has been executed and deleted + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + // inactive shares pool on OLC 0 has been deleted because its stake has been withdrawn + assert_inactive_shares_pool(pool_address, 0, false, 0); + + // new pending withdrawal can be created on lockup cycle 1 + unlock(validator, pool_address, 5403510001); + assert_delegation(validator_address, pool_address, 10000000000, 0, 5403510000); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 5403510000); + + // end lockup cycle 1 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // 10000000000 * 1.01 active stake + 5403510000 * 1.01 pending_inactive(now inactive) stake + assert_delegation(validator_address, pool_address, 10100000000, 5457545100, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 1, true, 5457545100); + + // unlock when the pending withdrawal exists and gets automatically executed + let balance = coin::balance(validator_address); + unlock(validator, pool_address, 10100000000); + assert!(coin::balance(validator_address) == balance + 5457545100, 0); + assert_delegation(validator_address, pool_address, 0, 0, 10100000000); + // this is the new pending withdrawal replacing the executed one + assert_pending_withdrawal(validator_address, pool_address, true, 2, false, 10100000000); + + // create dummy validator to ensure the existing validator can leave the set + initialize_test_validator(delegator, 100 * ONE_APT, true, true); + // inactivate validator + stake::leave_validator_set(validator, pool_address); + end_aptos_epoch(); + + // expire lockup cycle on the stake pool + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + let observed_lockup_cycle = observed_lockup_cycle(pool_address); + end_aptos_epoch(); + + // observed lockup cycle should be unchanged as no stake has been inactivated + synchronize_delegation_pool(pool_address); + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + // stake is pending_inactive as it has not been inactivated + stake::assert_stake_pool(pool_address, 5100500001, 0, 0, 10303010000); + // 10100000000 * 1.01 * 1.01 pending_inactive stake + assert_delegation(validator_address, pool_address, 0, 0, 10303010000); + // the pending withdrawal should be reported as still pending + assert_pending_withdrawal(validator_address, pool_address, true, 2, false, 10303010000); + + // validator is inactive and lockup expired => pending_inactive stake is withdrawable + balance = coin::balance(validator_address); + withdraw(validator, pool_address, 10303010000); + + assert!(coin::balance(validator_address) == balance + 10303010000, 0); + assert_delegation(validator_address, pool_address, 0, 0, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + stake::assert_stake_pool(pool_address, 5100500001, 0, 0, 0); + // pending_inactive shares pool has not been deleted (as can still `unlock` this OLC) + assert_inactive_shares_pool(pool_address, observed_lockup_cycle(pool_address), true, 0); + + stake::mint(validator, 30 * ONE_APT); + add_stake(validator, pool_address, 30 * ONE_APT); + unlock(validator, pool_address, 10 * ONE_APT); + + assert_delegation(validator_address, pool_address, 1999999999, 0, 1000000000); + // the pending withdrawal should be reported as still pending + assert_pending_withdrawal(validator_address, pool_address, true, 2, false, 1000000000); + + balance = coin::balance(validator_address); + // pending_inactive balance would be under threshold => redeem entire balance + withdraw(validator, pool_address, 1); + // pending_inactive balance has been withdrawn and the pending withdrawal executed + assert_delegation(validator_address, pool_address, 1999999999, 0, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + assert!(coin::balance(validator_address) == balance + 1000000000, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_total_coins_inactive( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + stake::mint(delegator1, 100 * ONE_APT); + stake::mint(delegator2, 200 * ONE_APT); + add_stake(delegator1, pool_address, 100 * ONE_APT); + add_stake(delegator2, pool_address, 200 * ONE_APT); + end_aptos_epoch(); + + assert_delegation(delegator1_address, pool_address, 100 * ONE_APT, 0, 0); + assert_delegation(delegator2_address, pool_address, 200 * ONE_APT, 0, 0); + + // unlock some stake from delegator 1 + unlock(delegator1, pool_address, 50 * ONE_APT); + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 4999999999); + + // move to lockup cycle 1 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // delegator 1 pending_inactive stake has been inactivated + assert_delegation(delegator1_address, pool_address, 5050000000, 5049999998, 0); + assert_delegation(delegator2_address, pool_address, 202 * ONE_APT, 0, 0); + + synchronize_delegation_pool(pool_address); + assert!(total_coins_inactive(pool_address) == 5049999998, 0); + + // unlock some stake from delegator 2 + unlock(delegator2, pool_address, 50 * ONE_APT); + assert_delegation(delegator2_address, pool_address, 15200000001, 0, 4999999999); + + // withdraw some of inactive stake of delegator 1 + withdraw(delegator1, pool_address, 2049999998); + assert_delegation(delegator1_address, pool_address, 5050000000, 3000000001, 0); + assert!(total_coins_inactive(pool_address) == 3000000001, 0); + + // move to lockup cycle 2 + let (_, inactive, _, pending_inactive) = stake::get_stake(pool_address); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // delegator 2 pending_inactive stake has been inactivated + assert_delegation(delegator1_address, pool_address, 5100500000, 3000000001, 0); + assert_delegation(delegator2_address, pool_address, 15352000001, 5049999998, 0); + + // total_coins_inactive remains unchanged in the absence of user operations + assert!(total_coins_inactive(pool_address) == inactive, 0); + synchronize_delegation_pool(pool_address); + // total_coins_inactive == previous inactive stake + previous pending_inactive stake and its rewards + assert!(total_coins_inactive(pool_address) == inactive + pending_inactive + pending_inactive / 100, 0); + + // withdraw some of inactive stake of delegator 2 + let total_coins_inactive = total_coins_inactive(pool_address); + withdraw(delegator2, pool_address, 3049999998); + assert!(total_coins_inactive(pool_address) == total_coins_inactive - 3049999997, 0); + + // unlock some stake from delegator `validator` + unlock(validator, pool_address, 50 * ONE_APT); + + // create dummy validator to ensure the existing validator can leave the set + initialize_test_validator(delegator1, 100 * ONE_APT, true, true); + // inactivate validator + stake::leave_validator_set(validator, pool_address); + end_aptos_epoch(); + + // move to lockup cycle 3 + (_, inactive, _, pending_inactive) = stake::get_stake(pool_address); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // pending_inactive stake has not been inactivated as validator is inactive + let (_, inactive_now, _, pending_inactive_now) = stake::get_stake(pool_address); + assert!(inactive_now == inactive, inactive_now); + assert!(pending_inactive_now == pending_inactive, pending_inactive_now); + + // total_coins_inactive remains unchanged in the absence of a new OLC + synchronize_delegation_pool(pool_address); + assert!(total_coins_inactive(pool_address) == inactive, 0); + + // withdraw entire pending_inactive stake + withdraw(validator, pool_address, MAX_U64); + assert!(total_coins_inactive(pool_address) == inactive, 0); + (_, _, _, pending_inactive) = stake::get_stake(pool_address); + assert!(pending_inactive == 0, pending_inactive); + + // withdraw entire inactive stake + withdraw(delegator1, pool_address, MAX_U64); + withdraw(delegator2, pool_address, MAX_U64); + assert!(total_coins_inactive(pool_address) == 0, 0); + (_, inactive, _, _) = stake::get_stake(pool_address); + assert!(inactive == 0, inactive); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_reactivate_stake_single( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + // unlock some stake from the active one + unlock(validator, pool_address, 100 * ONE_APT); + assert_delegation(validator_address, pool_address, 100 * ONE_APT, 0, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 0, 100 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 100 * ONE_APT); + + // add some stake to pending_active state + stake::mint(validator, 150 * ONE_APT); + add_stake(validator, pool_address, 150 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 150 * ONE_APT); + assert_delegation(validator_address, pool_address, 250 * ONE_APT - fee, 0, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 150 * ONE_APT, 100 * ONE_APT); + + // can reactivate only pending_inactive stake + reactivate_stake(validator, pool_address, 150 * ONE_APT); + + assert_delegation(validator_address, pool_address, 350 * ONE_APT - fee, 0, 0); + stake::assert_stake_pool(pool_address, 200 * ONE_APT, 0, 150 * ONE_APT, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + + end_aptos_epoch(); + // 20000000000 active stake * 1.01 + 15000000000 pending_active stake + assert_delegation(validator_address, pool_address, 35200000000, 0, 0); + + // unlock stake added at previous epoch (expect some imprecision when moving shares) + unlock(validator, pool_address, 150 * ONE_APT); + assert_delegation(validator_address, pool_address, 20200000001, 0, 14999999999); + stake::assert_stake_pool(pool_address, 20200000001, 0, 0, 14999999999); + + // inactivate pending_inactive stake + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // 20200000001 active stake * 1.01 + 14999999999 pending_inactive stake * 1.01 + assert_delegation(validator_address, pool_address, 20402000001, 15149999998, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 15149999998); + + // cannot reactivate inactive stake + reactivate_stake(validator, pool_address, 15149999998); + assert_delegation(validator_address, pool_address, 20402000001, 15149999998, 0); + + // unlock stake in the new lockup cycle (the pending withdrawal is executed) + unlock(validator, pool_address, 100 * ONE_APT); + assert!(coin::balance(validator_address) == 15149999998, 0); + assert_delegation(validator_address, pool_address, 10402000002, 0, 9999999999); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 9999999999); + + // reactivate the new pending withdrawal almost entirely + reactivate_stake(validator, pool_address, 8999999999); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 1000000000); + // reactivate remaining stake of the new pending withdrawal + reactivate_stake(validator, pool_address, 1000000000); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_withdraw_many( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + + unlock(validator, pool_address, 100 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 100 * ONE_APT); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_delegation(delegator_address, pool_address, 200 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 90899999999, 10100000000, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 10100000000); + assert_inactive_shares_pool(pool_address, 0, true, 100 * ONE_APT); + + // check cannot withdraw inactive stake unlocked by others + withdraw(delegator, pool_address, MAX_U64); + assert_delegation(delegator_address, pool_address, 200 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 90899999999, 10100000000, 0); + + unlock(delegator, pool_address, 100 * ONE_APT); + assert_delegation(delegator_address, pool_address, 10000000000, 0, 9999999999); + assert_delegation(validator_address, pool_address, 90900000000, 10100000000, 0); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 9999999999); + + // check cannot withdraw inactive stake unlocked by others even if owning pending_inactive + withdraw(delegator, pool_address, MAX_U64); + assert_delegation(delegator_address, pool_address, 10000000000, 0, 9999999999); + assert_delegation(validator_address, pool_address, 90900000000, 10100000000, 0); + + // withdraw entire owned inactive stake + let balance = coin::balance(validator_address); + withdraw(validator, pool_address, MAX_U64); + assert!(coin::balance(validator_address) == balance + 10100000000, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + assert_inactive_shares_pool(pool_address, 0, false, 0); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_delegation(delegator_address, pool_address, 10100000000, 10099999998, 0); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, true, 10099999998); + assert_inactive_shares_pool(pool_address, 1, true, 9999999999); + + // use too small of an unlock amount to actually transfer shares to the pending_inactive pool + // check that no leftovers have been produced on the stake or delegation pools + stake::assert_stake_pool(pool_address, 101909000001, 10099999998, 0, 0); + unlock_with_min_stake_disabled(delegator, pool_address, 1); + stake::assert_stake_pool(pool_address, 101909000001, 10099999998, 0, 0); + assert_delegation(delegator_address, pool_address, 10100000000, 10099999998, 0); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, true, 10099999998); + + // implicitly execute the pending withdrawal by unlocking min stake to buy 1 share + unlock_with_min_stake_disabled(delegator, pool_address, 2); + stake::assert_stake_pool(pool_address, 101909000000, 0, 0, 1); + assert_delegation(delegator_address, pool_address, 10099999998, 0, 1); + // old pending withdrawal has been replaced + assert_pending_withdrawal(delegator_address, pool_address, true, 2, false, 1); + assert_inactive_shares_pool(pool_address, 1, false, 0); + assert_inactive_shares_pool(pool_address, 2, true, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_inactivate_no_excess_stake( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + + // create inactive and pending_inactive stakes on the stake pool + unlock(validator, pool_address, 200 * ONE_APT); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + unlock(delegator, pool_address, 100 * ONE_APT); + + // check no excess pending_inactive is inactivated in the special case + // the validator had gone inactive before its lockup expired + + let observed_lockup_cycle = observed_lockup_cycle(pool_address); + + // create dummy validator to ensure the existing validator can leave the set + initialize_test_validator(delegator, 100 * ONE_APT, true, true); + // inactivate validator + stake::leave_validator_set(validator, pool_address); + end_aptos_epoch(); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE, 0); + + // expire lockup afterwards + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + synchronize_delegation_pool(pool_address); + // no new inactive stake detected => OLC does not advance + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + // pending_inactive stake has not been inactivated + stake::assert_stake_pool(pool_address, 113231100001, 20200000000, 0, 10200999997); + assert_delegation(delegator_address, pool_address, 10201000000, 0, 10200999997); + assert_delegation(validator_address, pool_address, 103030100000, 20200000000, 0); + + // withdraw some inactive stake (remaining pending_inactive is not inactivated) + withdraw(validator, pool_address, 200000000); + stake::assert_stake_pool(pool_address, 113231100001, 20000000001, 0, 10200999997); + assert_delegation(delegator_address, pool_address, 10201000000, 0, 10200999997); + assert_delegation(validator_address, pool_address, 103030100000, 20000000001, 0); + + // withdraw some pending_inactive stake (remaining pending_inactive is not inactivated) + withdraw(delegator, pool_address, 200999997); + stake::assert_stake_pool(pool_address, 113231100001, 20000000001, 0, 10000000001); + assert_delegation(delegator_address, pool_address, 10201000000, 0, 10000000001); + assert_delegation(validator_address, pool_address, 103030100000, 20000000001, 0); + + // no new inactive stake detected => OLC does not advance + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + unlock(delegator, pool_address, 10201000000); + withdraw(delegator, pool_address, 10201000000); + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + assert_delegation(delegator_address, pool_address, 0, 0, 10000000002); + assert_delegation(validator_address, pool_address, 103030100001, 20000000001, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 20000000001); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10000000002); + stake::assert_stake_pool(pool_address, 103030100001, 20000000001, 0, 10000000002); + + // reactivate validator + stake::join_validator_set(validator, pool_address); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 0); + end_aptos_epoch(); + + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + // no rewards have been produced yet and no stake inactivated as lockup has been refreshed + stake::assert_stake_pool(pool_address, 103030100001, 20000000001, 0, 10000000002); + + synchronize_delegation_pool(pool_address); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 20000000001); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10000000002); + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + // cannot withdraw pending_inactive stake anymore + withdraw(delegator, pool_address, 10000000002); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10000000002); + + // earning rewards is resumed from this epoch on + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 104060401001, 20000000001, 0, 10100000002); + + // new pending_inactive stake earns rewards but so does the old one + unlock(validator, pool_address, 104060401001); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 104060401000); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10100000002); + end_aptos_epoch(); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 105101005010); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10201000002); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_stake_rewards( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + end_aptos_epoch(); + // 100000000000 active stake * 1.01 + assert_delegation(validator_address, pool_address, 1010 * ONE_APT, 0, 0); + + // add stake in pending_active state + stake::mint(validator, 200 * ONE_APT); + add_stake(validator, pool_address, 200 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 1210 * ONE_APT - fee, 0, 0); + + end_aptos_epoch(); + // 101000000000 active stake * 1.01 + 20000000000 pending_active stake with no rewards + assert_delegation(validator_address, pool_address, 122010000000, 0, 0); + + end_aptos_epoch(); + // 122010000000 active stake * 1.01 + assert_delegation(validator_address, pool_address, 123230100000, 0, 0); + + // 123230100000 active stake * 1.01 + end_aptos_epoch(); + // 124462401000 active stake * 1.01 + end_aptos_epoch(); + // 125707025010 active stake * 1.01 + end_aptos_epoch(); + // 126964095260 active stake * 1.01 + end_aptos_epoch(); + // 128233736212 active stake * 1.01 + end_aptos_epoch(); + assert_delegation(validator_address, pool_address, 129516073574, 0, 0); + + // unlock 200 coins from delegator `validator` + unlock(validator, pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 109516073575, 0, 19999999999); + + // end this lockup cycle + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + // 109516073575 active stake * 1.01 + 19999999999 pending_inactive stake * 1.01 + assert_delegation(validator_address, pool_address, 110611234310, 20199999998, 0); + + end_aptos_epoch(); + // 110611234310 active stake * 1.01 + 20199999998 inactive stake + assert_delegation(validator_address, pool_address, 111717346653, 20199999998, 0); + + // add stake in pending_active state + stake::mint(validator, 1000 * ONE_APT); + add_stake(validator, pool_address, 1000 * ONE_APT); + + fee = get_add_stake_fee(pool_address, 1000 * ONE_APT); + assert_delegation(validator_address, pool_address, 211717346653 - fee, 20199999998, 0); + + end_aptos_epoch(); + // 111717346653 active stake * 1.01 + 100000000000 pending_active stake + 20199999998 inactive stake + assert_delegation(validator_address, pool_address, 212834520119, 20199999998, 0); + + end_aptos_epoch(); + // 212834520119 active stake * 1.01 + 20199999998 inactive stake + assert_delegation(validator_address, pool_address, 214962865320, 20199999998, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_active_stake_rewards_multiple( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + // add stake in pending_active state + stake::mint(delegator, 300 * ONE_APT); + add_stake(delegator, pool_address, 300 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 300 * ONE_APT); + assert_delegation(delegator_address, pool_address, 300 * ONE_APT - fee, 0, 0); + assert_delegation(validator_address, pool_address, 200 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 200 * ONE_APT, 0, 300 * ONE_APT, 0); + + end_aptos_epoch(); + // `delegator` got its `add_stake` fee back and `validator` its active stake rewards + assert_delegation(delegator_address, pool_address, 300 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 20199999999, 0, 0); + stake::assert_stake_pool(pool_address, 502 * ONE_APT, 0, 0, 0); + + // delegators earn their own rewards from now on + end_aptos_epoch(); + assert_delegation(delegator_address, pool_address, 303 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 20401999999, 0, 0); + stake::assert_stake_pool(pool_address, 50702000000, 0, 0, 0); + + end_aptos_epoch(); + assert_delegation(delegator_address, pool_address, 30603000000, 0, 0); + assert_delegation(validator_address, pool_address, 20606019999, 0, 0); + stake::assert_stake_pool(pool_address, 51209020000, 0, 0, 0); + + end_aptos_epoch(); + assert_delegation(delegator_address, pool_address, 30909030000, 0, 0); + assert_delegation(validator_address, pool_address, 20812080199, 0, 0); + stake::assert_stake_pool(pool_address, 51721110200, 0, 0, 0); + + // add more stake in pending_active state than currently active + stake::mint(delegator, 1000 * ONE_APT); + add_stake(delegator, pool_address, 1000 * ONE_APT); + + fee = get_add_stake_fee(pool_address, 1000 * ONE_APT); + assert_delegation(delegator_address, pool_address, 130909030000 - fee, 0, 0); + assert_delegation(validator_address, pool_address, 20812080199, 0, 0); + + end_aptos_epoch(); + // `delegator` got its `add_stake` fee back and `validator` its active stake rewards + assert_delegation(delegator_address, pool_address, 131218120300, 0, 0); + assert_delegation(validator_address, pool_address, 21020201001, 0, 0); + stake::assert_stake_pool(pool_address, 152238321302, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_pending_inactive_stake_rewards( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + end_aptos_epoch(); + assert_delegation(validator_address, pool_address, 1010 * ONE_APT, 0, 0); + + // unlock 200 coins from delegator `validator` + unlock(validator, pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 81000000001, 0, 19999999999); + + end_aptos_epoch(); // 81000000001 active stake * 1.01 + 19999999999 pending_inactive stake * 1.01 + end_aptos_epoch(); // 81810000001 active stake * 1.01 + 20199999998 pending_inactive stake * 1.01 + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); // 82628100001 active stake * 1.01 + 20401999997 pending_inactive stake * 1.01 + end_aptos_epoch(); // 83454381001 active stake * 1.01 + 20606019996 pending_inactive stake(now inactive) + assert_delegation(validator_address, pool_address, 84288924811, 20606019996, 0); + + // unlock 200 coins from delegator `validator` which implicitly executes its pending withdrawal + unlock(validator, pool_address, 200 * ONE_APT); + assert!(coin::balance(validator_address) == 20606019996, 0); + assert_delegation(validator_address, pool_address, 64288924812, 0, 19999999999); + + // lockup cycle is not ended, pending_inactive stake is still earning + end_aptos_epoch(); // 64288924812 active stake * 1.01 + 19999999999 pending_inactive stake * 1.01 + end_aptos_epoch(); // 64931814060 active stake * 1.01 + 20199999998 pending_inactive stake * 1.01 + end_aptos_epoch(); // 65581132200 active stake * 1.01 + 20401999997 pending_inactive stake * 1.01 + end_aptos_epoch(); // 66236943522 active stake * 1.01 + 20606019996 pending_inactive stake * 1.01 + assert_delegation(validator_address, pool_address, 66899312957, 0, 20812080195); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); // 66899312957 active stake * 1.01 + 20812080195 pending_inactive stake * 1.01 + end_aptos_epoch(); // 67568306086 active stake * 1.01 + 21020200996 pending_inactive stake(now inactive) + end_aptos_epoch(); // 68243989147 active stake * 1.01 + 21020200996 inactive stake + assert_delegation(validator_address, pool_address, 68926429037, 21020200996, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_out_of_order_redeem( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + stake::mint(delegator1, 300 * ONE_APT); + add_stake(delegator1, pool_address, 300 * ONE_APT); + + stake::mint(delegator2, 300 * ONE_APT); + add_stake(delegator2, pool_address, 300 * ONE_APT); + + end_aptos_epoch(); + + // create the pending withdrawal of delegator 1 in lockup cycle 0 + unlock(delegator1, pool_address, 150 * ONE_APT); + assert_pending_withdrawal(delegator1_address, pool_address, true, 0, false, 14999999999); + + // move to lockup cycle 1 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // create the pending withdrawal of delegator 2 in lockup cycle 1 + unlock(delegator2, pool_address, 150 * ONE_APT); + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, false, 14999999999); + // 14999999999 pending_inactive stake * 1.01 + assert_pending_withdrawal(delegator1_address, pool_address, true, 0, true, 15149999998); + + // move to lockup cycle 2 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, true, 15149999998); + assert_pending_withdrawal(delegator1_address, pool_address, true, 0, true, 15149999998); + + // both delegators who unlocked at different lockup cycles should be able to withdraw their stakes + withdraw(delegator1, pool_address, 15149999998); + withdraw(delegator2, pool_address, 5149999998); + + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, true, 10000000001); + assert_pending_withdrawal(delegator1_address, pool_address, false, 0, false, 0); + assert!(coin::balance(delegator1_address) == 15149999998, 0); + assert!(coin::balance(delegator2_address) == 5149999997, 0); + + // recreate the pending withdrawal of delegator 1 in lockup cycle 2 + unlock(delegator1, pool_address, 100 * ONE_APT); + + // move to lockup cycle 3 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, true, 10000000001); + // 9999999999 pending_inactive stake * 1.01 + assert_pending_withdrawal(delegator1_address, pool_address, true, 2, true, 10099999998); + + // withdraw inactive stake of delegator 2 left from lockup cycle 1 in cycle 3 + withdraw(delegator2, pool_address, 10000000001); + assert!(coin::balance(delegator2_address) == 15149999998, 0); + assert_pending_withdrawal(delegator2_address, pool_address, false, 0, false, 0); + + // withdraw inactive stake of delegator 1 left from previous lockup cycle + withdraw(delegator1, pool_address, 10099999998); + assert!(coin::balance(delegator1_address) == 15149999998 + 10099999998, 0); + assert_pending_withdrawal(delegator1_address, pool_address, false, 0, false, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_operator_fee( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + + // create delegation pool of commission fee 12.65% + initialize_delegation_pool(validator, 1265, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + assert!(stake::get_operator(pool_address) == validator_address, 0); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + stake::mint(delegator1, 100 * ONE_APT); + add_stake(delegator1, pool_address, 100 * ONE_APT); + + stake::mint(delegator2, 200 * ONE_APT); + add_stake(delegator2, pool_address, 200 * ONE_APT); + + // validator is inactive and added stake is instantly `active` + stake::assert_stake_pool(pool_address, 300 * ONE_APT, 0, 0, 0); + + // validator does not produce rewards yet + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 300 * ONE_APT, 0, 0, 0); + + // therefore, there are no operator commission rewards yet + assert_delegation(validator_address, pool_address, 0, 0, 0); + + // activate validator + stake::rotate_consensus_key(validator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + stake::join_validator_set(validator, pool_address); + end_aptos_epoch(); + + // produce active rewards + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 30300000000, 0, 0, 0); + + // 300000000 active rewards * 0.1265 + assert_delegation(validator_address, pool_address, 37950000, 0, 0); + // 10000000000 active stake * (1 + 1% reward-rate * 0.8735) + assert_delegation(delegator1_address, pool_address, 10087350000, 0, 0); + // 20000000000 active stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 20174700000, 0, 0); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 30603000000, 0, 0, 0); + + // 603000000 active rewards * 0.1265 instead of + // 303000000 active rewards * 0.1265 + 37950000 active stake * 1.008735 + // because operator commission rewards are not automatically restaked compared to already owned stake + assert_delegation(validator_address, pool_address, 76279500, 0, 0); + // 10087350000 active stake * 1.008735 + some of the rewards of previous commission if restaked + assert_delegation(delegator1_address, pool_address, 10175573500, 0, 0); + // 20174700000 active stake * 1.008735 + some of the rewards of previous commission if restaked + assert_delegation(delegator2_address, pool_address, 20351147000, 0, 0); + + // restake operator commission rewards + synchronize_delegation_pool(pool_address); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 30909030000, 0, 0, 0); + + // 306030000 active rewards * 0.1265 + 76279500 active stake * 1.008735 + assert_delegation(validator_address, pool_address, 115658596, 0, 0); + // 10175573500 active stake * 1.008735 + assert_delegation(delegator1_address, pool_address, 10264457134, 0, 0); + // 20351147000 active stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 20528914269, 0, 0); + + // check operator is rewarded by pending_inactive stake too + unlock(delegator2, pool_address, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 20909030001, 0, 0, 9999999999); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 21118120301, 0, 0, 10099999998); + + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + // distribute operator pending_inactive commission rewards + synchronize_delegation_pool(pool_address); + // 99999999 pending_inactive rewards * 0.1265 + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 12649998); + + // 209090300 active rewards * 0.1265 + 115658596 active stake * 1.008735 + // 99999999 pending_inactive rewards * 0.1265 + assert_delegation(validator_address, pool_address, 143118796, 0, 12649998); + // 10264457134 active stake * 1.008735 + assert_delegation(delegator1_address, pool_address, 10354117168, 0, 0); + // 10528914270 active stake * 1.008735 + // 9999999999 pending_inactive stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 10620884336, 0, 10087349999); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 21329301504, 10200999997, 0, 0); + + // operator pending_inactive rewards on previous epoch have been inactivated + // 211181203 active rewards * 0.1265 + 143118796 active stake * 1.008735 + // 100999999 pending_inactive rewards * 0.1265 + 12649998 pending_inactive stake * 1.008735 + assert_delegation(validator_address, pool_address, 171083360, 25536995, 0); + // distribute operator pending_inactive commission rewards + synchronize_delegation_pool(pool_address); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 25536995); + + // check operator is not rewarded by `add_stake` fees + stake::mint(delegator1, 100 * ONE_APT); + assert!(get_add_stake_fee(pool_address, 100 * ONE_APT) > 0, 0); + add_stake(delegator1, pool_address, 100 * ONE_APT); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 31542594519, 10200999997, 0, 0); + + // 213293015 active rewards * 0.1265 + 171083360 active stake * 1.008735 + assert_delegation(validator_address, pool_address, 199559340, 25536995, 0); + + // unlock some more stake to produce pending_inactive commission + // 10620884336 active stake * (1.008735 ^ 2 epochs) + // 10087349999 pending_inactive stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 10807241561, 10175463001, 0); + unlock(delegator2, pool_address, 100 * ONE_APT); + // 10807241561 - 100 APT < `MIN_COINS_ON_SHARES_POOL` thus active stake is entirely unlocked + assert_delegation(delegator2_address, pool_address, 0, 0, 10807241561); + end_aptos_epoch(); + + // in-flight pending_inactive commission can coexist with previous inactive commission + assert_delegation(validator_address, pool_address, 227532711, 25536996, 13671160); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 25536996); + + // distribute in-flight pending_inactive commission, implicitly executing the inactive withdrawal of operator + coin::register(validator); + synchronize_delegation_pool(pool_address); + assert!(coin::balance(validator_address) == 25536996, 0); + + // in-flight commission has been synced, implicitly used to buy shares for operator + // expect operator stake to be slightly less than previously reported by `Self::get_stake` + assert_delegation(validator_address, pool_address, 227532711, 0, 13671159); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 13671159); + } + + #[test(aptos_framework = @aptos_framework, old_operator = @0x123, delegator = @0x010, new_operator = @0x020)] + public entry fun test_change_operator( + aptos_framework: &signer, + old_operator: &signer, + delegator: &signer, + new_operator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + + let old_operator_address = signer::address_of(old_operator); + account::create_account_for_test(old_operator_address); + + let new_operator_address = signer::address_of(new_operator); + account::create_account_for_test(new_operator_address); + + // create delegation pool of commission fee 12.65% + initialize_delegation_pool(old_operator, 1265, vector::empty()); + let pool_address = get_owned_pool_address(old_operator_address); + assert!(stake::get_operator(pool_address) == old_operator_address, 0); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + unlock(delegator, pool_address, 100 * ONE_APT); + + // activate validator + stake::rotate_consensus_key(old_operator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + stake::join_validator_set(old_operator, pool_address); + end_aptos_epoch(); + + // produce active and pending_inactive rewards + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10100000000, 0, 0, 10100000000); + assert_delegation(old_operator_address, pool_address, 12650000, 0, 12650000); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10201000000, 0, 0, 10201000000); + assert_delegation(old_operator_address, pool_address, 25426500, 0, 25426500); + + // change operator + set_operator(old_operator, new_operator_address); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10303010000, 0, 0, 10303010000); + // 25426500 active stake * 1.008735 and 25426500 pending_inactive stake * 1.008735 + assert_delegation(old_operator_address, pool_address, 25648600, 0, 25648600); + // 102010000 active rewards * 0.1265 and 102010000 pending_inactive rewards * 0.1265 + assert_delegation(new_operator_address, pool_address, 12904265, 0, 12904265); + + // restake `new_operator` commission rewards + synchronize_delegation_pool(pool_address); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10406040100, 0, 0, 10406040100); + // 25648600 active stake * 1.008735 and 25648600 pending_inactive stake * 1.008735 + assert_delegation(old_operator_address, pool_address, 25872641, 0, 25872641); + // 103030100 active rewards * 0.1265 and 12904265 active stake * 1.008735 + // 103030100 pending_inactive rewards * 0.1265 and 12904265 pending_inactive stake * 1.008735 + assert_delegation(new_operator_address, pool_address, 26050290, 0, 26050290); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_min_stake_is_preserved( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + // add stake without fees as validator is not active yet + stake::mint(delegator1, 50 * ONE_APT); + add_stake(delegator1, pool_address, 50 * ONE_APT); + stake::mint(delegator2, 16 * ONE_APT); + add_stake(delegator2, pool_address, 16 * ONE_APT); + + // validator becomes active and share price is 1 + end_aptos_epoch(); + + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 0); + // pending_inactive balance would be under threshold => move MIN_COINS_ON_SHARES_POOL coins + unlock(delegator1, pool_address, MIN_COINS_ON_SHARES_POOL - 1); + assert_delegation(delegator1_address, pool_address, 3999999999, 0, 1000000001); + + // pending_inactive balance is over threshold + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 4000000000, 0, 1000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 0); + + // active balance would be under threshold => move entire balance + unlock(delegator1, pool_address, 5000000000 - (MIN_COINS_ON_SHARES_POOL - 1)); + assert_delegation(delegator1_address, pool_address, 0, 0, 5000000000); + + // active balance would be under threshold => move MIN_COINS_ON_SHARES_POOL coins + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 1000000001, 0, 3999999999); + + // active balance is over threshold + unlock(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 1000000000, 0, 4000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 4000000000 - (MIN_COINS_ON_SHARES_POOL - 1)); + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 0); + + // active + pending_inactive balance < 2 * MIN_COINS_ON_SHARES_POOL + // stake can live on only one of the shares pools + assert_delegation(delegator2_address, pool_address, 16 * ONE_APT, 0, 0); + unlock(delegator2, pool_address, 1); + assert_delegation(delegator2_address, pool_address, 0, 0, 16 * ONE_APT); + reactivate_stake(delegator2, pool_address, 1); + assert_delegation(delegator2_address, pool_address, 16 * ONE_APT, 0, 0); + + unlock(delegator2, pool_address, ONE_APT); + assert_delegation(delegator2_address, pool_address, 0, 0, 16 * ONE_APT); + reactivate_stake(delegator2, pool_address, 2 * ONE_APT); + assert_delegation(delegator2_address, pool_address, 16 * ONE_APT, 0, 0); + + // share price becomes 1.01 on both pools + unlock(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 3999999999, 0, 1000000001); + end_aptos_epoch(); + assert_delegation(delegator1_address, pool_address, 4039999998, 0, 1010000001); + + // pending_inactive balance is over threshold + reactivate_stake(delegator1, pool_address, 10000001); + assert_delegation(delegator1_address, pool_address, 4049999998, 0, 1000000001); + + // 1 coin < 1.01 so no shares are redeemed + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 4049999998, 0, 1000000001); + + // pending_inactive balance is over threshold + // requesting 2 coins actually redeems 1 coin from pending_inactive pool + reactivate_stake(delegator1, pool_address, 2); + assert_delegation(delegator1_address, pool_address, 4049999999, 0, 1000000000); + + // 1 coin < 1.01 so no shares are redeemed + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 4049999999, 0, 1000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 2); + assert_delegation(delegator1_address, pool_address, 5049999999, 0, 0); + + // pending_inactive balance would be under threshold => move MIN_COINS_ON_SHARES_POOL coins + unlock(delegator1, pool_address, MIN_COINS_ON_SHARES_POOL - 1); + assert_delegation(delegator1_address, pool_address, 4049999998, 0, 1000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 5049999998, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010)] + #[expected_failure(abort_code = 0x1000f, location = Self)] + public entry fun test_create_proposal_abort_if_inefficient_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + // delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[]); + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 2); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + stake::mint(delegator1, 100 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + create_proposal( + delegator1, + pool_address, + execution_hash, + b"", + b"", + true, + ); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010)] + public entry fun test_create_proposal_with_sufficient_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[]); + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 2); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + stake::mint(delegator1, 100 * ONE_APT); + add_stake(delegator1, pool_address, 100 * ONE_APT); + end_aptos_epoch(); + + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + create_proposal( + delegator1, + pool_address, + execution_hash, + b"", + b"", + true, + ); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020, voter1 = @0x030, voter2 = @0x040)] + public entry fun test_voting_power_change( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test_no_reward(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[] + ); + + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + let voter2_address = signer::address_of(voter2); + account::create_account_for_test(voter2_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + stake::mint(delegator2, 110 * ONE_APT); + add_stake(delegator2, pool_address, 90 * ONE_APT); + // By default, the voter of a delegator is itself. + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + end_aptos_epoch(); + // Reward rate is 0. No reward so no voting power change. + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // Delegator1 delegates its voting power to voter1 but it takes 1 lockup cycle to take effects. So no voting power + // change now. + delegate_voting_power(delegator1, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // 1 epoch passed but the lockup cycle hasn't ended. No voting power change. + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // Delegator2 delegates its voting power to voter1 but it takes 1 lockup cycle to take effects. So no voting power + // change now. + delegate_voting_power(delegator2, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_delegator_voter(pool_address, delegator2_address) == voter1_address, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // delegator1 changes to voter2 then change back. delegator2 changes to voter1. + // No voting power change in this lockup cycle. + delegate_voting_power(delegator1, pool_address, voter2_address); + delegate_voting_power(delegator2, pool_address, voter2_address); + delegate_voting_power(delegator1, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_delegator_voter(pool_address, delegator1_address) == voter1_address, 1); + assert!(calculate_and_update_delegator_voter(pool_address, delegator2_address) == voter2_address, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 90 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // delegator1 adds stake to the pool. Voting power changes immediately. + add_stake(delegator1, pool_address, 90 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 90 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // delegator1 unlocks stake and changes its voter. No voting power change until next lockup cycle. + unlock(delegator1, pool_address, 90 * ONE_APT); + delegate_voting_power(delegator1, pool_address, voter2_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 90 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + // Withdrawl inactive shares will not change voting power. + withdraw(delegator1, pool_address, 45 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // voter2 adds stake for itself. Voting power changes immediately. + stake::mint(voter2, 110 * ONE_APT); + add_stake(voter2, pool_address, 10 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 110 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + public entry fun test_voting_power_change_for_existing_delegation_pool( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test_no_reward(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created before partial governance voting feature flag is enabled. So this delegation + // pool's voter is its owner. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + assert!(!partial_governance_voting_enabled(pool_address), 1); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + + // Enable partial governance voting feature flag. + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[] + ); + // Voter doens't change until enabling partial governance voting on this delegation pool. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + // By default, the voter of a delegator is itself. + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + + // Delegator1 delegates its voting power to voter1. + // It takes 1 cycle to take effect. No immediate change. + delegate_voting_power(delegator1, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020, voter1 = @0x030, voter2 = @0x040)] + public entry fun test_voting_power_change_for_rewards( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 100, + 100, + 1000000 + ); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[] + ); + + // 50% commission rate + initialize_test_validator_custom(validator, 100 * ONE_APT, true, false, 5000); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + let voter2_address = signer::address_of(voter2); + account::create_account_for_test(voter2_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + stake::mint(delegator2, 110 * ONE_APT); + add_stake(delegator2, pool_address, 90 * ONE_APT); + // By default, the voter of a delegator is itself. + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // One epoch is passed. Delegators earn no reward because their stake was inactive. + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // 2 epoches are passed. Delegators earn reward and voting power increases. Operator earns reward and + // commission. Because there is no operation during these 2 epoches. Operator's commission is not compounded. + end_aptos_epoch(); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 550 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 25 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 225 * ONE_APT, 1); + + // Another epoch is passed. Voting power chage due to reward is correct even if delegator1 and delegator2 change its voter. + delegate_voting_power(delegator1, pool_address, voter1_address); + delegate_voting_power(delegator2, pool_address, voter1_address); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 122499999999, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 375 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020, voter1 = @0x030, voter2 = @0x040)] + public entry fun test_voting_power_change_already_voted_before_partial( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + let voter2_address = signer::address_of(voter2); + account::create_account_for_test(voter2_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + stake::mint(delegator2, 110 * ONE_APT); + add_stake(delegator2, pool_address, 90 * ONE_APT); + + // Create 2 proposals and vote for proposal1. + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposal2_id = aptos_governance::create_proposal_v2_impl( + validator, + pool_address, + execution_hash, + b"", + b"", + true, + ); + aptos_governance::vote(validator, pool_address, proposal1_id, true); + + // Enable partial governance voting feature flag. + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[] + ); + // Voter doens't change until enabling partial governance voting on this delegation pool. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + // No one can vote for proposal1 because it's already voted before enabling partial governance voting. + assert!(calculate_and_update_remaining_voting_power(pool_address, validator_address, proposal1_id) == 0, 1); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal1_id) == 0, 1); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator2_address, proposal1_id) == 0, 1); + assert!(calculate_and_update_remaining_voting_power(pool_address, validator_address, proposal2_id) == 100 * ONE_APT, 1); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 10 * ONE_APT, 1); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator2_address, proposal2_id) == 90 * ONE_APT, 1); + + // Delegator1 tries to use 50 APT to vote on proposal2, but it only has 10 APT. So only 10 APT voting power is used. + vote(delegator1, pool_address, proposal2_id, 50 * ONE_APT, true); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 0, 1); + + add_stake(delegator1, pool_address, 60 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 70 * ONE_APT, 1); + vote(delegator1, pool_address, proposal2_id, 25 * ONE_APT, true); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 35 * ONE_APT, 1); + vote(delegator1, pool_address, proposal2_id, 30 * ONE_APT, false); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 5 * ONE_APT, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + #[expected_failure(abort_code=0x10010, location = Self)] + public entry fun test_vote_should_failed_if_already_voted_before_enable_partial_voting_flag( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + aptos_governance::vote(validator, pool_address, proposal1_id, true); + + // Enable partial governance voting feature flag. + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[] + ); + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + + vote(delegator1, pool_address, proposal1_id, 10 * ONE_APT, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + #[expected_failure(abort_code=0x10011, location = Self)] + public entry fun test_vote_should_failed_if_already_voted_before_enable_partial_voting_on_pool( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + // Enable partial governance voting feature flag. + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[] + ); + + // The operator voter votes on the proposal after partial governace voting flag is enabled but before partial voting is enabled on the pool. + aptos_governance::vote(validator, pool_address, proposal1_id, true); + + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + + add_stake(delegator1, pool_address, 10 * ONE_APT); + vote(delegator1, pool_address, proposal1_id, 10 * ONE_APT, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010)] + #[expected_failure(abort_code=0x10010, location = Self)] + public entry fun test_vote_should_failed_if_no_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + // Delegator1 has no stake. Abort. + vote(delegator1, pool_address, proposal1_id, 10 * ONE_APT, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + public entry fun test_delegate_voting_power_should_pass_even_if_no_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + setup_vote(aptos_framework, validator, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + // Delegator1 has no stake. Abort. + delegate_voting_power(delegator1, pool_address, signer::address_of(voter1)); + } + + #[test(staker = @0xe256f4f4e2986cada739e339895cf5585082ff247464cab8ec56eea726bd2263)] + public entry fun test_get_expected_stake_pool_address(staker: address) { + let pool_address = get_expected_stake_pool_address(staker, vector[0x42, 0x42]); + assert!(pool_address == @0xe9fc2fbb82b7e1cb7af3daef8c7a24e66780f9122d15e4f1d486ee7c7c36c48d, 0); + } + + #[test_only] + public fun assert_delegation( + delegator_address: address, + pool_address: address, + active_stake: u64, + inactive_stake: u64, + pending_inactive_stake: u64, + ) acquires DelegationPool { + let (actual_active, actual_inactive, actual_pending_inactive) = get_stake(pool_address, delegator_address); + assert!(actual_active == active_stake, actual_active); + assert!(actual_inactive == inactive_stake, actual_inactive); + assert!(actual_pending_inactive == pending_inactive_stake, actual_pending_inactive); + } + + #[test_only] + public fun assert_pending_withdrawal( + delegator_address: address, + pool_address: address, + exists: bool, + olc: u64, + inactive: bool, + stake: u64, + ) acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + assert!(withdrawal_exists == exists, 0); + assert!(withdrawal_olc.index == olc, withdrawal_olc.index); + let (withdrawal_inactive, withdrawal_stake) = get_pending_withdrawal(pool_address, delegator_address); + assert!(withdrawal_inactive == inactive, 0); + assert!(withdrawal_stake == stake, withdrawal_stake); + } + + #[test_only] + public fun assert_inactive_shares_pool( + pool_address: address, + olc: u64, + exists: bool, + stake: u64, + ) acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + assert!(table::contains(&pool.inactive_shares, olc_with_index(olc)) == exists, 0); + if (exists) { + let actual_stake = total_coins(table::borrow(&pool.inactive_shares, olc_with_index(olc))); + assert!(actual_stake == stake, actual_stake); + } else { + assert!(0 == stake, 0); + } + } + + #[test_only] + public fun setup_vote( + aptos_framework: &signer, + validator: &signer, + enable_partial_voting: bool, + ): u64 acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords { + initialize_for_test_no_reward(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created before partial governance voting feature flag is enabled. So this delegation + // pool's voter is its owner. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + assert!(!partial_governance_voting_enabled(pool_address), 1); + end_aptos_epoch(); + + // Create 1 proposals and vote for proposal1. + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposal_id = aptos_governance::create_proposal_v2_impl( + validator, + pool_address, + execution_hash, + b"", + b"", + true, + ); + if (enable_partial_voting) { + features::change_feature_flags( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting()], + vector[]); + enable_partial_governance_voting(pool_address); + }; + proposal_id + } + + #[test_only] + public fun total_coins_inactive(pool_address: address): u64 acquires DelegationPool { + borrow_global(pool_address).total_coins_inactive + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/event.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/event.move new file mode 100644 index 0000000..279c2e5 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/event.move @@ -0,0 +1,97 @@ +/// 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 aptos_framework::event { + use std::bcs; + + use aptos_framework::guid::GUID; + use std::features; + + friend aptos_framework::account; + friend aptos_framework::object; + + /// Module event feature is not supported. + const EMODULE_EVENT_NOT_SUPPORTED: u64 = 1; + + /// Emit an event with payload `msg` by using `handle_ref`'s key and counter. + public fun emit(msg: T) { + assert!(features::module_event_enabled(), std::error::invalid_state(EMODULE_EVENT_NOT_SUPPORTED)); + write_module_event_to_store(msg); + } + + /// Log `msg` with the event stream identified by `T` + native fun write_module_event_to_store(msg: T); + + #[test_only] + public native fun emitted_events(): vector; + + #[test_only] + public fun was_event_emitted(msg: &T): bool { + use std::vector; + vector::contains(&emitted_events(), msg) + } + + #[deprecated] + /// 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: GUID, + } + + #[deprecated] + /// Use EventHandleGenerator to generate a unique event handle for `sig` + public(friend) fun new_event_handle(guid: GUID): EventHandle { + EventHandle { + counter: 0, + guid, + } + } + + #[deprecated] + /// Emit an event with payload `msg` by using `handle_ref`'s key and counter. + public fun emit_event(handle_ref: &mut EventHandle, msg: T) { + write_to_event_store(bcs::to_bytes(&handle_ref.guid), handle_ref.counter, msg); + spec { + assume handle_ref.counter + 1 <= MAX_U64; + }; + handle_ref.counter = handle_ref.counter + 1; + } + + #[deprecated] + /// Return the GUID associated with this EventHandle + public fun guid(handle_ref: &EventHandle): &GUID { + &handle_ref.guid + } + + #[deprecated] + /// Return the current counter associated with this EventHandle + public fun counter(handle_ref: &EventHandle): u64 { + handle_ref.counter + } + + #[deprecated] + /// Log `msg` as the `count`th event associated with the event stream identified by `guid` + native fun write_to_event_store(guid: vector, count: u64, msg: T); + + #[deprecated] + /// Destroy a unique handle. + public fun destroy_handle(handle: EventHandle) { + EventHandle { counter: _, guid: _ } = handle; + } + + #[deprecated] + #[test_only] + public native fun emitted_events_by_handle(handle: &EventHandle): vector; + + #[deprecated] + #[test_only] + public fun was_event_emitted_by_handle(handle: &EventHandle, msg: &T): bool { + use std::vector; + vector::contains(&emitted_events_by_handle(handle), msg) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/execution_config.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/execution_config.move new file mode 100644 index 0000000..54103c7 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/execution_config.move @@ -0,0 +1,33 @@ +/// Maintains the execution config for the blockchain. The config is stored in a +/// Reconfiguration, and may be updated by root. +module aptos_framework::execution_config { + use std::error; + use std::vector; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + + struct ExecutionConfig has key { + config: vector, + } + + /// The provided on chain config bytes are empty or invalid + const EINVALID_CONFIG: u64 = 1; + + /// This can be called by on-chain governance to update on-chain execution configs. + public fun set(account: &signer, config: vector) acquires ExecutionConfig { + system_addresses::assert_aptos_framework(account); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + + if (exists(@aptos_framework)) { + let config_ref = &mut borrow_global_mut(@aptos_framework).config; + *config_ref = config; + } else { + move_to(account, ExecutionConfig { config }); + }; + // Need to trigger reconfiguration so validator nodes can sync on the updated configs. + reconfiguration::reconfigure(); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/fungible_asset.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/fungible_asset.move new file mode 100644 index 0000000..b75eeb0 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/fungible_asset.move @@ -0,0 +1,778 @@ +/// This defines the fungible asset module that can issue fungible asset of any `Metadata` object. The +/// metadata object can be any object that equipped with `Metadata` resource. +module aptos_framework::fungible_asset { + use aptos_framework::event; + use aptos_framework::object::{Self, Object, ConstructorRef, DeleteRef}; + use std::string; + + use std::error; + use std::option::{Self, Option}; + use std::signer; + use std::string::String; + + /// Amount cannot be zero. + const EAMOUNT_CANNOT_BE_ZERO: u64 = 1; + /// The transfer ref and the fungible asset do not match. + const ETRANSFER_REF_AND_FUNGIBLE_ASSET_MISMATCH: u64 = 2; + /// Store is disabled from sending and receiving this fungible asset. + const ESTORE_IS_FROZEN: u64 = 3; + /// Insufficient balance to withdraw or transfer. + const EINSUFFICIENT_BALANCE: u64 = 4; + /// The fungible asset's supply has exceeded maximum. + const EMAX_SUPPLY_EXCEEDED: u64 = 5; + /// Fungible asset do not match when merging. + const EFUNGIBLE_ASSET_MISMATCH: u64 = 6; + /// The mint ref and the the store do not match. + const EMINT_REF_AND_STORE_MISMATCH: u64 = 7; + /// Account is not the store's owner. + const ENOT_STORE_OWNER: u64 = 8; + /// Transfer ref and store do not match. + const ETRANSFER_REF_AND_STORE_MISMATCH: u64 = 9; + /// Burn ref and store do not match. + const EBURN_REF_AND_STORE_MISMATCH: u64 = 10; + /// Fungible asset and store do not match. + const EFUNGIBLE_ASSET_AND_STORE_MISMATCH: u64 = 11; + /// Cannot destroy non-empty fungible assets. + const EAMOUNT_IS_NOT_ZERO: u64 = 12; + /// Burn ref and fungible asset do not match. + const EBURN_REF_AND_FUNGIBLE_ASSET_MISMATCH: u64 = 13; + /// Cannot destroy fungible stores with a non-zero balance. + const EBALANCE_IS_NOT_ZERO: u64 = 14; + /// Name of the fungible asset metadata is too long + const ENAME_TOO_LONG: u64 = 15; + /// Symbol of the fungible asset metadata is too long + const ESYMBOL_TOO_LONG: u64 = 16; + /// Decimals is over the maximum of 32 + const EDECIMALS_TOO_LARGE: u64 = 17; + /// Fungibility is only available for non-deletable objects. + const EOBJECT_IS_DELETABLE: u64 = 18; + /// URI for the icon of the fungible asset metadata is too long + const EURI_TOO_LONG: u64 = 19; + /// The fungible asset's supply will be negative which should be impossible. + const ESUPPLY_UNDERFLOW: u64 = 20; + /// Supply resource is not found for a metadata object. + const ESUPPLY_NOT_FOUND: u64 = 21; + + // + // Constants + // + + const MAX_NAME_LENGTH: u64 = 32; + const MAX_SYMBOL_LENGTH: u64 = 10; + const MAX_DECIMALS: u8 = 32; + const MAX_URI_LENGTH: u64 = 512; + + /// Maximum possible coin supply. + const MAX_U128: u128 = 340282366920938463463374607431768211455; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct Supply has key { + current: u128, + // option::none() means unlimited supply. + maximum: Option, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// Metadata of a Fungible asset + struct Metadata has key { + /// Name of the fungible metadata, i.e., "USDT". + name: String, + /// Symbol of the fungible metadata, usually a shorter version of the name. + /// For example, Singapore Dollar is SGD. + symbol: String, + /// Number of decimals used for display purposes. + /// For example, if `decimals` equals `2`, a balance of `505` coins should + /// be displayed to a user as `5.05` (`505 / 10 ** 2`). + decimals: u8, + /// The Uniform Resource Identifier (uri) pointing to an image that can be used as the icon for this fungible + /// asset. + icon_uri: String, + /// The Uniform Resource Identifier (uri) pointing to the website for the fungible asset. + project_uri: String, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The store object that holds fungible assets of a specific type associated with an account. + struct FungibleStore has key { + /// The address of the base metadata object. + metadata: Object, + /// The balance of the fungible metadata. + balance: u64, + /// If true, owner transfer is disabled that only `TransferRef` can move in/out from this store. + frozen: bool, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct FungibleAssetEvents has key { + deposit_events: event::EventHandle, + withdraw_events: event::EventHandle, + frozen_events: event::EventHandle, + } + + /// FungibleAsset can be passed into function for type safety and to guarantee a specific amount. + /// FungibleAsset is ephemeral and cannot be stored directly. It must be deposited back into a store. + struct FungibleAsset { + metadata: Object, + amount: u64, + } + + /// MintRef can be used to mint the fungible asset into an account's store. + struct MintRef has drop, store { + metadata: Object + } + + /// TransferRef can be used to allow or disallow the owner of fungible assets from transferring the asset + /// and allow the holder of TransferRef to transfer fungible assets from any account. + struct TransferRef has drop, store { + metadata: Object + } + + /// BurnRef can be used to burn fungible assets from a given holder account. + struct BurnRef has drop, store { + metadata: Object + } + + /// Emitted when fungible assets are deposited into a store. + struct DepositEvent has drop, store { + amount: u64, + } + + /// Emitted when fungible assets are withdrawn from a store. + struct WithdrawEvent has drop, store { + amount: u64, + } + + /// Emitted when a store's frozen status is updated. + struct FrozenEvent has drop, store { + frozen: bool, + } + + /// Make an existing object fungible by adding the Metadata resource. + /// This returns the capabilities to mint, burn, and transfer. + /// maximum_supply defines the behavior of maximum supply when monitoring: + /// - option::none(): Monitoring unlimited supply + /// - option::some(max): Monitoring fixed supply with `max` as the maximum supply. + public fun add_fungibility( + constructor_ref: &ConstructorRef, + maximum_supply: Option, + name: String, + symbol: String, + decimals: u8, + icon_uri: String, + project_uri: String, + ): Object { + assert!(!object::can_generate_delete_ref(constructor_ref), error::invalid_argument(EOBJECT_IS_DELETABLE)); + let metadata_object_signer = &object::generate_signer(constructor_ref); + assert!(string::length(&name) <= MAX_NAME_LENGTH, error::out_of_range(ENAME_TOO_LONG)); + assert!(string::length(&symbol) <= MAX_SYMBOL_LENGTH, error::out_of_range(ESYMBOL_TOO_LONG)); + assert!(decimals <= MAX_DECIMALS, error::out_of_range(EDECIMALS_TOO_LARGE)); + assert!(string::length(&icon_uri) <= MAX_URI_LENGTH, error::out_of_range(EURI_TOO_LONG)); + assert!(string::length(&project_uri) <= MAX_URI_LENGTH, error::out_of_range(EURI_TOO_LONG)); + move_to(metadata_object_signer, + Metadata { + name, + symbol, + decimals, + icon_uri, + project_uri, + } + ); + move_to(metadata_object_signer, Supply { + current: 0, + maximum: maximum_supply + }); + object::object_from_constructor_ref(constructor_ref) + } + + /// Creates a mint ref that can be used to mint fungible assets from the given fungible object's constructor ref. + /// This can only be called at object creation time as constructor_ref is only available then. + public fun generate_mint_ref(constructor_ref: &ConstructorRef): MintRef { + let metadata = object::object_from_constructor_ref(constructor_ref); + MintRef { metadata } + } + + /// Creates a burn ref that can be used to burn fungible assets from the given fungible object's constructor ref. + /// This can only be called at object creation time as constructor_ref is only available then. + public fun generate_burn_ref(constructor_ref: &ConstructorRef): BurnRef { + let metadata = object::object_from_constructor_ref(constructor_ref); + BurnRef { metadata } + } + + /// Creates a transfer ref that can be used to freeze/unfreeze/transfer fungible assets from the given fungible + /// object's constructor ref. + /// This can only be called at object creation time as constructor_ref is only available then. + public fun generate_transfer_ref(constructor_ref: &ConstructorRef): TransferRef { + let metadata = object::object_from_constructor_ref(constructor_ref); + TransferRef { metadata } + } + + #[view] + /// Get the current supply from the `metadata` object. + public fun supply(metadata: Object): Option acquires Supply { + let metadata_address = object::object_address(&metadata); + if (exists(metadata_address)) { + let supply = borrow_global(metadata_address); + option::some(supply.current) + } else { + option::none() + } + } + + #[view] + /// Get the maximum supply from the `metadata` object. + public fun maximum(metadata: Object): Option acquires Supply { + let metadata_address = object::object_address(&metadata); + if (exists(metadata_address)) { + let supply = borrow_global(metadata_address); + supply.maximum + } else { + option::none() + } + } + + #[view] + /// Get the name of the fungible asset from the `metadata` object. + public fun name(metadata: Object): String acquires Metadata { + borrow_fungible_metadata(&metadata).name + } + + #[view] + /// Get the symbol of the fungible asset from the `metadata` object. + public fun symbol(metadata: Object): String acquires Metadata { + borrow_fungible_metadata(&metadata).symbol + } + + #[view] + /// Get the decimals from the `metadata` object. + public fun decimals(metadata: Object): u8 acquires Metadata { + borrow_fungible_metadata(&metadata).decimals + } + + #[view] + /// Return whether the provided address has a store initialized. + public fun store_exists(store: address): bool { + exists(store) + } + + /// Return the underlying metadata object + public fun metadata_from_asset(fa: &FungibleAsset): Object { + fa.metadata + } + + #[view] + /// Return the underlying metadata object. + public fun store_metadata(store: Object): Object acquires FungibleStore { + borrow_store_resource(&store).metadata + } + + /// Return the `amount` of a given fungible asset. + public fun amount(fa: &FungibleAsset): u64 { + fa.amount + } + + #[view] + /// Get the balance of a given store. + public fun balance(store: Object): u64 acquires FungibleStore { + if (store_exists(object::object_address(&store))) { + borrow_store_resource(&store).balance + } else { + 0 + } + } + + #[view] + /// Return whether a store is frozen. + /// + /// If the store has not been created, we default to returning false so deposits can be sent to it. + public fun is_frozen(store: Object): bool acquires FungibleStore { + store_exists(object::object_address(&store)) && borrow_store_resource(&store).frozen + } + + public fun asset_metadata(fa: &FungibleAsset): Object { + fa.metadata + } + + /// Get the underlying metadata object from the `MintRef`. + public fun mint_ref_metadata(ref: &MintRef): Object { + ref.metadata + } + + /// Get the underlying metadata object from the `TransferRef`. + public fun transfer_ref_metadata(ref: &TransferRef): Object { + ref.metadata + } + + /// Get the underlying metadata object from the `BurnRef`. + public fun burn_ref_metadata(ref: &BurnRef): Object { + ref.metadata + } + + /// Transfer an `amount` of fungible asset from `from_store`, which should be owned by `sender`, to `receiver`. + /// Note: it does not move the underlying object. + public entry fun transfer( + sender: &signer, + from: Object, + to: Object, + amount: u64, + ) acquires FungibleStore, FungibleAssetEvents { + let fa = withdraw(sender, from, amount); + deposit(to, fa); + } + + /// Allow an object to hold a store for fungible assets. + /// Applications can use this to create multiple stores for isolating fungible assets for different purposes. + public fun create_store( + constructor_ref: &ConstructorRef, + metadata: Object, + ): Object { + let store_obj = &object::generate_signer(constructor_ref); + move_to(store_obj, FungibleStore { + metadata: object::convert(metadata), + balance: 0, + frozen: false, + }); + move_to(store_obj, + FungibleAssetEvents { + deposit_events: object::new_event_handle(store_obj), + withdraw_events: object::new_event_handle(store_obj), + frozen_events: object::new_event_handle(store_obj), + } + ); + + object::object_from_constructor_ref(constructor_ref) + } + + /// Used to delete a store. Requires the store to be completely empty prior to removing it + public fun remove_store(delete_ref: &DeleteRef) acquires FungibleStore, FungibleAssetEvents { + let store = &object::object_from_delete_ref(delete_ref); + let addr = object::object_address(store); + let FungibleStore { metadata: _, balance, frozen: _ } + = move_from(addr); + assert!(balance == 0, error::permission_denied(EBALANCE_IS_NOT_ZERO)); + let FungibleAssetEvents { + deposit_events, + withdraw_events, + frozen_events, + } = move_from(addr); + event::destroy_handle(deposit_events); + event::destroy_handle(withdraw_events); + event::destroy_handle(frozen_events); + } + + /// Withdraw `amount` of the fungible asset from `store` by the owner. + public fun withdraw( + owner: &signer, + store: Object, + amount: u64, + ): FungibleAsset acquires FungibleStore, FungibleAssetEvents { + assert!(object::owns(store, signer::address_of(owner)), error::permission_denied(ENOT_STORE_OWNER)); + assert!(!is_frozen(store), error::invalid_argument(ESTORE_IS_FROZEN)); + withdraw_internal(object::object_address(&store), amount) + } + + /// Deposit `amount` of the fungible asset to `store`. + public fun deposit(store: Object, fa: FungibleAsset) acquires FungibleStore, FungibleAssetEvents { + assert!(!is_frozen(store), error::invalid_argument(ESTORE_IS_FROZEN)); + deposit_internal(store, fa); + } + + /// Mint the specified `amount` of the fungible asset. + public fun mint(ref: &MintRef, amount: u64): FungibleAsset acquires Supply { + assert!(amount > 0, error::invalid_argument(EAMOUNT_CANNOT_BE_ZERO)); + let metadata = ref.metadata; + increase_supply(&metadata, amount); + + FungibleAsset { + metadata, + amount + } + } + + /// Mint the specified `amount` of the fungible asset to a destination store. + public fun mint_to(ref: &MintRef, store: Object, amount: u64) + acquires FungibleStore, FungibleAssetEvents, Supply { + deposit(store, mint(ref, amount)); + } + + /// Enable/disable a store's ability to do direct transfers of the fungible asset. + public fun set_frozen_flag( + ref: &TransferRef, + store: Object, + frozen: bool, + ) acquires FungibleStore, FungibleAssetEvents { + assert!( + ref.metadata == store_metadata(store), + error::invalid_argument(ETRANSFER_REF_AND_STORE_MISMATCH), + ); + let store_addr = object::object_address(&store); + borrow_global_mut(store_addr).frozen = frozen; + + let events = borrow_global_mut(store_addr); + event::emit_event(&mut events.frozen_events, FrozenEvent { frozen }); + } + + /// Burns a fungible asset + public fun burn(ref: &BurnRef, fa: FungibleAsset) acquires Supply { + let FungibleAsset { + metadata, + amount, + } = fa; + assert!(ref.metadata == metadata, error::invalid_argument(EBURN_REF_AND_FUNGIBLE_ASSET_MISMATCH)); + decrease_supply(&metadata, amount); + } + + /// Burn the `amount` of the fungible asset from the given store. + public fun burn_from( + ref: &BurnRef, + store: Object, + amount: u64 + ) acquires FungibleStore, FungibleAssetEvents, Supply { + let metadata = ref.metadata; + assert!(metadata == store_metadata(store), error::invalid_argument(EBURN_REF_AND_STORE_MISMATCH)); + let store_addr = object::object_address(&store); + burn(ref, withdraw_internal(store_addr, amount)); + } + + /// Withdraw `amount` of the fungible asset from the `store` ignoring `frozen`. + public fun withdraw_with_ref( + ref: &TransferRef, + store: Object, + amount: u64 + ): FungibleAsset acquires FungibleStore, FungibleAssetEvents { + assert!( + ref.metadata == store_metadata(store), + error::invalid_argument(ETRANSFER_REF_AND_STORE_MISMATCH), + ); + withdraw_internal(object::object_address(&store), amount) + } + + /// Deposit the fungible asset into the `store` ignoring `frozen`. + public fun deposit_with_ref( + ref: &TransferRef, + store: Object, + fa: FungibleAsset + ) acquires FungibleStore, FungibleAssetEvents { + assert!( + ref.metadata == fa.metadata, + error::invalid_argument(ETRANSFER_REF_AND_FUNGIBLE_ASSET_MISMATCH) + ); + deposit_internal(store, fa); + } + + /// Transfer `amount` of the fungible asset with `TransferRef` even it is frozen. + public fun transfer_with_ref( + transfer_ref: &TransferRef, + from: Object, + to: Object, + amount: u64, + ) acquires FungibleStore, FungibleAssetEvents { + let fa = withdraw_with_ref(transfer_ref, from, amount); + deposit_with_ref(transfer_ref, to, fa); + } + + /// Create a fungible asset with zero amount. + /// This can be useful when starting a series of computations where the initial value is 0. + public fun zero(metadata: Object): FungibleAsset { + FungibleAsset { + metadata: object::convert(metadata), + amount: 0, + } + } + + /// Extract a given amount from the given fungible asset and return a new one. + public fun extract(fungible_asset: &mut FungibleAsset, amount: u64): FungibleAsset { + assert!(fungible_asset.amount >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE)); + fungible_asset.amount = fungible_asset.amount - amount; + FungibleAsset { + metadata: fungible_asset.metadata, + amount, + } + } + + /// "Merges" the two given fungible assets. The fungible asset passed in as `dst_fungible_asset` will have a value + /// equal to the sum of the two (`dst_fungible_asset` and `src_fungible_asset`). + public fun merge(dst_fungible_asset: &mut FungibleAsset, src_fungible_asset: FungibleAsset) { + let FungibleAsset { metadata, amount } = src_fungible_asset; + assert!(metadata == dst_fungible_asset.metadata, error::invalid_argument(EFUNGIBLE_ASSET_MISMATCH)); + dst_fungible_asset.amount = dst_fungible_asset.amount + amount; + } + + /// Destroy an empty fungible asset. + public fun destroy_zero(fungible_asset: FungibleAsset) { + let FungibleAsset { amount, metadata: _ } = fungible_asset; + assert!(amount == 0, error::invalid_argument(EAMOUNT_IS_NOT_ZERO)); + } + + fun deposit_internal(store: Object, fa: FungibleAsset) acquires FungibleStore, FungibleAssetEvents { + let FungibleAsset { metadata, amount } = fa; + if (amount == 0) return; + + let store_metadata = store_metadata(store); + assert!(metadata == store_metadata, error::invalid_argument(EFUNGIBLE_ASSET_AND_STORE_MISMATCH)); + let store_addr = object::object_address(&store); + let store = borrow_global_mut(store_addr); + store.balance = store.balance + amount; + + let events = borrow_global_mut(store_addr); + event::emit_event(&mut events.deposit_events, DepositEvent { amount }); + } + + /// Extract `amount` of the fungible asset from `store`. + fun withdraw_internal( + store_addr: address, + amount: u64, + ): FungibleAsset acquires FungibleStore, FungibleAssetEvents { + assert!(amount != 0, error::invalid_argument(EAMOUNT_CANNOT_BE_ZERO)); + let store = borrow_global_mut(store_addr); + assert!(store.balance >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE)); + store.balance = store.balance - amount; + + let events = borrow_global_mut(store_addr); + let metadata = store.metadata; + event::emit_event(&mut events.withdraw_events, WithdrawEvent { amount }); + + FungibleAsset { metadata, amount } + } + + /// Increase the supply of a fungible asset by minting. + fun increase_supply(metadata: &Object, amount: u64) acquires Supply { + assert!(amount != 0, error::invalid_argument(EAMOUNT_CANNOT_BE_ZERO)); + let metadata_address = object::object_address(metadata); + assert!(exists(metadata_address), error::not_found(ESUPPLY_NOT_FOUND)); + let supply = borrow_global_mut(metadata_address); + if (option::is_some(&supply.maximum)) { + let max = *option::borrow_mut(&mut supply.maximum); + assert!( + max - supply.current >= (amount as u128), + error::out_of_range(EMAX_SUPPLY_EXCEEDED) + ) + }; + supply.current = supply.current + (amount as u128); + } + + /// Decrease the supply of a fungible asset by burning. + fun decrease_supply(metadata: &Object, amount: u64) acquires Supply { + assert!(amount != 0, error::invalid_argument(EAMOUNT_CANNOT_BE_ZERO)); + let metadata_address = object::object_address(metadata); + assert!(exists(metadata_address), error::not_found(ESUPPLY_NOT_FOUND)); + let supply = borrow_global_mut(metadata_address); + assert!( + supply.current >= (amount as u128), + error::invalid_state(ESUPPLY_UNDERFLOW) + ); + supply.current = supply.current - (amount as u128); + } + + inline fun borrow_fungible_metadata( + metadata: &Object + ): &Metadata acquires Metadata { + let addr = object::object_address(metadata); + borrow_global(addr) + } + + inline fun borrow_fungible_metadata_mut( + metadata: &Object + ): &mut Metadata acquires Metadata { + let addr = object::object_address(metadata); + borrow_global_mut(addr) + } + + inline fun borrow_store_resource(store: &Object): &FungibleStore acquires FungibleStore { + borrow_global(object::object_address(store)) + } + + #[test_only] + use aptos_framework::account; + + #[test_only] + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + + struct TestToken has key {} + + #[test_only] + public fun create_test_token(creator: &signer): (ConstructorRef, Object) { + account::create_account_for_test(signer::address_of(creator)); + let creator_ref = object::create_named_object(creator, b"TEST"); + let object_signer = object::generate_signer(&creator_ref); + move_to(&object_signer, TestToken {}); + + let token = object::object_from_constructor_ref(&creator_ref); + (creator_ref, token) + } + + #[test_only] + public fun init_test_metadata(constructor_ref: &ConstructorRef): (MintRef, TransferRef, BurnRef) { + add_fungibility( + constructor_ref, + option::some(100) /* max supply */, + string::utf8(b"TEST"), + string::utf8(b"@@"), + 0, + string::utf8(b"http://www.example.com/favicon.ico"), + string::utf8(b"http://www.example.com"), + ); + let mint_ref = generate_mint_ref(constructor_ref); + let burn_ref = generate_burn_ref(constructor_ref); + let transfer_ref = generate_transfer_ref(constructor_ref); + (mint_ref, transfer_ref, burn_ref) + } + + #[test_only] + public fun create_fungible_asset( + creator: &signer + ): (MintRef, TransferRef, BurnRef, Object) { + let (creator_ref, token_object) = create_test_token(creator); + let (mint, transfer, burn) = init_test_metadata(&creator_ref); + (mint, transfer, burn, object::convert(token_object)) + } + + #[test_only] + public fun create_test_store(owner: &signer, metadata: Object): Object { + let owner_addr = signer::address_of(owner); + if (!account::exists_at(owner_addr)) { + account::create_account_for_test(owner_addr); + }; + create_store(&object::create_object_from_account(owner), metadata) + } + + #[test(creator = @0xcafe)] + fun test_metadata_basic_flow(creator: &signer) acquires Metadata, Supply { + let (creator_ref, metadata) = create_test_token(creator); + init_test_metadata(&creator_ref); + assert!(supply(metadata) == option::some(0), 1); + assert!(maximum(metadata) == option::some(100), 2); + assert!(name(metadata) == string::utf8(b"TEST"), 3); + assert!(symbol(metadata) == string::utf8(b"@@"), 4); + assert!(decimals(metadata) == 0, 5); + + increase_supply(&metadata, 50); + assert!(supply(metadata) == option::some(50), 6); + decrease_supply(&metadata, 30); + assert!(supply(metadata) == option::some(20), 7); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x20005, location = Self)] + fun test_supply_overflow(creator: &signer) acquires Supply { + let (creator_ref, metadata) = create_test_token(creator); + init_test_metadata(&creator_ref); + increase_supply(&metadata, 101); + } + + #[test(creator = @0xcafe)] + fun test_create_and_remove_store(creator: &signer) acquires FungibleStore, FungibleAssetEvents { + let (_, _, _, metadata) = create_fungible_asset(creator); + let creator_ref = object::create_object_from_account(creator); + create_store(&creator_ref, metadata); + let delete_ref = object::generate_delete_ref(&creator_ref); + remove_store(&delete_ref); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_e2e_basic_flow( + creator: &signer, + aaron: &signer, + ) acquires FungibleStore, FungibleAssetEvents, Supply { + let (mint_ref, transfer_ref, burn_ref, test_token) = create_fungible_asset(creator); + let metadata = mint_ref.metadata; + let creator_store = create_test_store(creator, metadata); + let aaron_store = create_test_store(aaron, metadata); + + assert!(supply(test_token) == option::some(0), 1); + // Mint + let fa = mint(&mint_ref, 100); + assert!(supply(test_token) == option::some(100), 2); + // Deposit + deposit(creator_store, fa); + // Withdraw + let fa = withdraw(creator, creator_store, 80); + assert!(supply(test_token) == option::some(100), 3); + deposit(aaron_store, fa); + // Burn + burn_from(&burn_ref, aaron_store, 30); + assert!(supply(test_token) == option::some(70), 4); + // Transfer + transfer(creator, creator_store, aaron_store, 10); + assert!(balance(creator_store) == 10, 5); + assert!(balance(aaron_store) == 60, 6); + + set_frozen_flag(&transfer_ref, aaron_store, true); + assert!(is_frozen(aaron_store), 7); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x10003, location = Self)] + fun test_frozen( + creator: &signer + ) acquires FungibleStore, FungibleAssetEvents, Supply { + let (mint_ref, transfer_ref, _burn_ref, _) = create_fungible_asset(creator); + + let creator_store = create_test_store(creator, mint_ref.metadata); + let fa = mint(&mint_ref, 100); + set_frozen_flag(&transfer_ref, creator_store, true); + deposit(creator_store, fa); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_transfer_with_ref( + creator: &signer, + aaron: &signer, + ) acquires FungibleStore, FungibleAssetEvents, Supply { + let (mint_ref, transfer_ref, _burn_ref, _) = create_fungible_asset(creator); + let metadata = mint_ref.metadata; + let creator_store = create_test_store(creator, metadata); + let aaron_store = create_test_store(aaron, metadata); + + let fa = mint(&mint_ref, 100); + set_frozen_flag(&transfer_ref, creator_store, true); + set_frozen_flag(&transfer_ref, aaron_store, true); + deposit_with_ref(&transfer_ref, creator_store, fa); + transfer_with_ref(&transfer_ref, creator_store, aaron_store, 80); + assert!(balance(creator_store) == 20, 1); + assert!(balance(aaron_store) == 80, 2); + assert!(!!is_frozen(creator_store), 3); + assert!(!!is_frozen(aaron_store), 4); + } + + #[test(creator = @0xcafe)] + fun test_merge_and_exact(creator: &signer) acquires Supply { + let (mint_ref, _transfer_ref, burn_ref, _) = create_fungible_asset(creator); + let fa = mint(&mint_ref, 100); + let cash = extract(&mut fa, 80); + assert!(fa.amount == 20, 1); + assert!(cash.amount == 80, 2); + let more_cash = extract(&mut fa, 20); + destroy_zero(fa); + merge(&mut cash, more_cash); + assert!(cash.amount == 100, 3); + burn(&burn_ref, cash); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x10012, location = Self)] + fun test_add_fungibility_to_deletable_object(creator: &signer) { + account::create_account_for_test(signer::address_of(creator)); + let creator_ref = &object::create_object_from_account(creator); + init_test_metadata(creator_ref); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + #[expected_failure(abort_code = 0x10006, location = Self)] + fun test_fungible_asset_mismatch_when_merge(creator: &signer, aaron: &signer) { + let (_, _, _, metadata1) = create_fungible_asset(creator); + let (_, _, _, metadata2) = create_fungible_asset(aaron); + let base = FungibleAsset { + metadata: metadata1, + amount: 1, + }; + let addon = FungibleAsset { + metadata: metadata2, + amount: 1 + }; + merge(&mut base, addon); + let FungibleAsset { + metadata: _, + amount: _ + } = base; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/gas_schedule.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/gas_schedule.move new file mode 100644 index 0000000..36be0ca --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/gas_schedule.move @@ -0,0 +1,76 @@ +/// This module defines structs and methods to initialize the gas schedule, which dictates how much +/// it costs to execute Move on the network. +module aptos_framework::gas_schedule { + use std::error; + use std::string::String; + use std::vector; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + use aptos_framework::util::from_bytes; + use aptos_framework::storage_gas::StorageGasConfig; + use aptos_framework::storage_gas; + + friend aptos_framework::genesis; + + /// The provided gas schedule bytes are empty or invalid + const EINVALID_GAS_SCHEDULE: u64 = 1; + const EINVALID_GAS_FEATURE_VERSION: u64 = 2; + + struct GasEntry has store, copy, drop { + key: String, + val: u64, + } + + struct GasSchedule has key, copy, drop { + entries: vector + } + + struct GasScheduleV2 has key, copy, drop { + feature_version: u64, + entries: vector, + } + + /// Only called during genesis. + public(friend) fun initialize(aptos_framework: &signer, gas_schedule_blob: vector) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(!vector::is_empty(&gas_schedule_blob), error::invalid_argument(EINVALID_GAS_SCHEDULE)); + + // TODO(Gas): check if gas schedule is consistent + let gas_schedule: GasScheduleV2 = from_bytes(gas_schedule_blob); + move_to(aptos_framework, gas_schedule); + } + + /// This can be called by on-chain governance to update the gas schedule. + public fun set_gas_schedule(aptos_framework: &signer, gas_schedule_blob: vector) acquires GasSchedule, GasScheduleV2 { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(!vector::is_empty(&gas_schedule_blob), error::invalid_argument(EINVALID_GAS_SCHEDULE)); + + if (exists(@aptos_framework)) { + let gas_schedule = borrow_global_mut(@aptos_framework); + let new_gas_schedule: GasScheduleV2 = from_bytes(gas_schedule_blob); + assert!(new_gas_schedule.feature_version >= gas_schedule.feature_version, + error::invalid_argument(EINVALID_GAS_FEATURE_VERSION)); + // TODO(Gas): check if gas schedule is consistent + *gas_schedule = new_gas_schedule; + } + else { + if (exists(@aptos_framework)) { + _ = move_from(@aptos_framework); + }; + let new_gas_schedule: GasScheduleV2 = from_bytes(gas_schedule_blob); + // TODO(Gas): check if gas schedule is consistent + move_to(aptos_framework, new_gas_schedule); + }; + + // Need to trigger reconfiguration so validator nodes can sync on the updated gas schedule. + reconfiguration::reconfigure(); + } + + public fun set_storage_gas_config(aptos_framework: &signer, config: StorageGasConfig) { + storage_gas::set_config(aptos_framework, config); + // Need to trigger reconfiguration so the VM is guaranteed to load the new gas fee starting from the next + // transaction. + reconfiguration::reconfigure(); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/genesis.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/genesis.move new file mode 100644 index 0000000..e30268d --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/genesis.move @@ -0,0 +1,512 @@ +module aptos_framework::genesis { + use std::error; + use std::fixed_point32; + use std::vector; + + use aptos_std::simple_map; + + use aptos_framework::account; + use aptos_framework::aggregator_factory; + use aptos_framework::aptos_coin::{Self, AptosCoin}; + use aptos_framework::aptos_governance; + use aptos_framework::block; + use aptos_framework::chain_id; + use aptos_framework::chain_status; + use aptos_framework::coin; + use aptos_framework::consensus_config; + use aptos_framework::execution_config; + use aptos_framework::create_signer::create_signer; + use aptos_framework::gas_schedule; + use aptos_framework::reconfiguration; + use aptos_framework::stake; + use aptos_framework::staking_contract; + use aptos_framework::staking_config; + use aptos_framework::state_storage; + use aptos_framework::storage_gas; + use aptos_framework::timestamp; + use aptos_framework::transaction_fee; + use aptos_framework::transaction_validation; + use aptos_framework::version; + use aptos_framework::vesting; + + const EDUPLICATE_ACCOUNT: u64 = 1; + const EACCOUNT_DOES_NOT_EXIST: u64 = 2; + + struct AccountMap has drop { + account_address: address, + balance: u64, + } + + struct EmployeeAccountMap has copy, drop { + accounts: vector
, + validator: ValidatorConfigurationWithCommission, + vesting_schedule_numerator: vector, + vesting_schedule_denominator: u64, + beneficiary_resetter: address, + } + + struct ValidatorConfiguration has copy, drop { + owner_address: address, + operator_address: address, + voter_address: address, + stake_amount: u64, + consensus_pubkey: vector, + proof_of_possession: vector, + network_addresses: vector, + full_node_network_addresses: vector, + } + + struct ValidatorConfigurationWithCommission has copy, drop { + validator_config: ValidatorConfiguration, + commission_percentage: u64, + join_during_genesis: bool, + } + + /// Genesis step 1: Initialize aptos framework account and core modules on chain. + fun initialize( + gas_schedule: vector, + chain_id: u8, + initial_version: u64, + consensus_config: vector, + execution_config: vector, + epoch_interval_microsecs: u64, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + // Initialize the aptos framework account. This is the account where system resources and modules will be + // deployed to. This will be entirely managed by on-chain governance and no entities have the key or privileges + // to use this account. + let (aptos_framework_account, aptos_framework_signer_cap) = account::create_framework_reserved_account(@aptos_framework); + // Initialize account configs on aptos framework account. + account::initialize(&aptos_framework_account); + + transaction_validation::initialize( + &aptos_framework_account, + b"script_prologue", + b"module_prologue", + b"multi_agent_script_prologue", + b"epilogue", + ); + + // Give the decentralized on-chain governance control over the core framework account. + aptos_governance::store_signer_cap(&aptos_framework_account, @aptos_framework, aptos_framework_signer_cap); + + // put reserved framework reserved accounts under aptos governance + let framework_reserved_addresses = vector
[@0x2, @0x3, @0x4, @0x5, @0x6, @0x7, @0x8, @0x9, @0xa]; + while (!vector::is_empty(&framework_reserved_addresses)) { + let address = vector::pop_back
(&mut framework_reserved_addresses); + let (_, framework_signer_cap) = account::create_framework_reserved_account(address); + aptos_governance::store_signer_cap(&aptos_framework_account, address, framework_signer_cap); + }; + + consensus_config::initialize(&aptos_framework_account, consensus_config); + execution_config::set(&aptos_framework_account, execution_config); + version::initialize(&aptos_framework_account, initial_version); + stake::initialize(&aptos_framework_account); + staking_config::initialize( + &aptos_framework_account, + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit, + ); + storage_gas::initialize(&aptos_framework_account); + gas_schedule::initialize(&aptos_framework_account, gas_schedule); + + // Ensure we can create aggregators for supply, but not enable it for common use just yet. + aggregator_factory::initialize_aggregator_factory(&aptos_framework_account); + coin::initialize_supply_config(&aptos_framework_account); + + chain_id::initialize(&aptos_framework_account, chain_id); + reconfiguration::initialize(&aptos_framework_account); + block::initialize(&aptos_framework_account, epoch_interval_microsecs); + state_storage::initialize(&aptos_framework_account); + timestamp::set_time_has_started(&aptos_framework_account); + } + + /// Genesis step 2: Initialize Aptos coin. + fun initialize_aptos_coin(aptos_framework: &signer) { + let (burn_cap, mint_cap) = aptos_coin::initialize(aptos_framework); + // Give stake module MintCapability so it can mint rewards. + stake::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + // Give transaction_fee module BurnCapability so it can burn gas. + transaction_fee::store_aptos_coin_burn_cap(aptos_framework, burn_cap); + // Give transaction_fee module MintCapability so it can mint refunds. + transaction_fee::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + } + + /// Only called for testnets and e2e tests. + fun initialize_core_resources_and_aptos_coin( + aptos_framework: &signer, + core_resources_auth_key: vector, + ) { + let (burn_cap, mint_cap) = aptos_coin::initialize(aptos_framework); + // Give stake module MintCapability so it can mint rewards. + stake::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + // Give transaction_fee module BurnCapability so it can burn gas. + transaction_fee::store_aptos_coin_burn_cap(aptos_framework, burn_cap); + // Give transaction_fee module MintCapability so it can mint refunds. + transaction_fee::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + + let core_resources = account::create_account(@core_resources); + account::rotate_authentication_key_internal(&core_resources, core_resources_auth_key); + aptos_coin::configure_accounts_for_test(aptos_framework, &core_resources, mint_cap); + } + + fun create_accounts(aptos_framework: &signer, accounts: vector) { + let unique_accounts = vector::empty(); + vector::for_each_ref(&accounts, |account_map| { + let account_map: &AccountMap = account_map; + assert!( + !vector::contains(&unique_accounts, &account_map.account_address), + error::already_exists(EDUPLICATE_ACCOUNT), + ); + vector::push_back(&mut unique_accounts, account_map.account_address); + + create_account( + aptos_framework, + account_map.account_address, + account_map.balance, + ); + }); + } + + /// This creates an funds an account if it doesn't exist. + /// If it exists, it just returns the signer. + fun create_account(aptos_framework: &signer, account_address: address, balance: u64): signer { + if (account::exists_at(account_address)) { + create_signer(account_address) + } else { + let account = account::create_account(account_address); + coin::register(&account); + aptos_coin::mint(aptos_framework, account_address, balance); + account + } + } + + fun create_employee_validators( + employee_vesting_start: u64, + employee_vesting_period_duration: u64, + employees: vector, + ) { + let unique_accounts = vector::empty(); + + vector::for_each_ref(&employees, |employee_group| { + let j = 0; + let employee_group: &EmployeeAccountMap = employee_group; + let num_employees_in_group = vector::length(&employee_group.accounts); + + let buy_ins = simple_map::create(); + + while (j < num_employees_in_group) { + let account = vector::borrow(&employee_group.accounts, j); + assert!( + !vector::contains(&unique_accounts, account), + error::already_exists(EDUPLICATE_ACCOUNT), + ); + vector::push_back(&mut unique_accounts, *account); + + let employee = create_signer(*account); + let total = coin::balance(*account); + let coins = coin::withdraw(&employee, total); + simple_map::add(&mut buy_ins, *account, coins); + + j = j + 1; + }; + + let j = 0; + let num_vesting_events = vector::length(&employee_group.vesting_schedule_numerator); + let schedule = vector::empty(); + + while (j < num_vesting_events) { + let numerator = vector::borrow(&employee_group.vesting_schedule_numerator, j); + let event = fixed_point32::create_from_rational(*numerator, employee_group.vesting_schedule_denominator); + vector::push_back(&mut schedule, event); + + j = j + 1; + }; + + let vesting_schedule = vesting::create_vesting_schedule( + schedule, + employee_vesting_start, + employee_vesting_period_duration, + ); + + let admin = employee_group.validator.validator_config.owner_address; + let admin_signer = &create_signer(admin); + let contract_address = vesting::create_vesting_contract( + admin_signer, + &employee_group.accounts, + buy_ins, + vesting_schedule, + admin, + employee_group.validator.validator_config.operator_address, + employee_group.validator.validator_config.voter_address, + employee_group.validator.commission_percentage, + x"", + ); + let pool_address = vesting::stake_pool_address(contract_address); + + if (employee_group.beneficiary_resetter != @0x0) { + vesting::set_beneficiary_resetter(admin_signer, contract_address, employee_group.beneficiary_resetter); + }; + + let validator = &employee_group.validator.validator_config; + assert!( + account::exists_at(validator.owner_address), + error::not_found(EACCOUNT_DOES_NOT_EXIST), + ); + assert!( + account::exists_at(validator.operator_address), + error::not_found(EACCOUNT_DOES_NOT_EXIST), + ); + assert!( + account::exists_at(validator.voter_address), + error::not_found(EACCOUNT_DOES_NOT_EXIST), + ); + if (employee_group.validator.join_during_genesis) { + initialize_validator(pool_address, validator); + }; + }); + } + + fun create_initialize_validators_with_commission( + aptos_framework: &signer, + use_staking_contract: bool, + validators: vector, + ) { + vector::for_each_ref(&validators, |validator| { + let validator: &ValidatorConfigurationWithCommission = validator; + create_initialize_validator(aptos_framework, validator, use_staking_contract); + }); + + // Destroy the aptos framework account's ability to mint coins now that we're done with setting up the initial + // validators. + aptos_coin::destroy_mint_cap(aptos_framework); + + stake::on_new_epoch(); + } + + /// Sets up the initial validator set for the network. + /// The validator "owner" accounts, and their authentication + /// Addresses (and keys) are encoded in the `owners` + /// Each validator signs consensus messages with the private key corresponding to the Ed25519 + /// public key in `consensus_pubkeys`. + /// Finally, each validator must specify the network address + /// (see types/src/network_address/mod.rs) for itself and its full nodes. + /// + /// Network address fields are a vector per account, where each entry is a vector of addresses + /// encoded in a single BCS byte array. + fun create_initialize_validators(aptos_framework: &signer, validators: vector) { + let validators_with_commission = vector::empty(); + vector::for_each_reverse(validators, |validator| { + let validator_with_commission = ValidatorConfigurationWithCommission { + validator_config: validator, + commission_percentage: 0, + join_during_genesis: true, + }; + vector::push_back(&mut validators_with_commission, validator_with_commission); + }); + + create_initialize_validators_with_commission(aptos_framework, false, validators_with_commission); + } + + fun create_initialize_validator( + aptos_framework: &signer, + commission_config: &ValidatorConfigurationWithCommission, + use_staking_contract: bool, + ) { + let validator = &commission_config.validator_config; + + let owner = &create_account(aptos_framework, validator.owner_address, validator.stake_amount); + create_account(aptos_framework, validator.operator_address, 0); + create_account(aptos_framework, validator.voter_address, 0); + + // Initialize the stake pool and join the validator set. + let pool_address = if (use_staking_contract) { + staking_contract::create_staking_contract( + owner, + validator.operator_address, + validator.voter_address, + validator.stake_amount, + commission_config.commission_percentage, + x"", + ); + staking_contract::stake_pool_address(validator.owner_address, validator.operator_address) + } else { + stake::initialize_stake_owner( + owner, + validator.stake_amount, + validator.operator_address, + validator.voter_address, + ); + validator.owner_address + }; + + if (commission_config.join_during_genesis) { + initialize_validator(pool_address, validator); + }; + } + + fun initialize_validator(pool_address: address, validator: &ValidatorConfiguration) { + let operator = &create_signer(validator.operator_address); + + stake::rotate_consensus_key( + operator, + pool_address, + validator.consensus_pubkey, + validator.proof_of_possession, + ); + stake::update_network_and_fullnode_addresses( + operator, + pool_address, + validator.network_addresses, + validator.full_node_network_addresses, + ); + stake::join_validator_set_internal(operator, pool_address); + } + + /// The last step of genesis. + fun set_genesis_end(aptos_framework: &signer) { + chain_status::set_genesis_end(aptos_framework); + } + + #[verify_only] + use std::features; + + #[verify_only] + fun initialize_for_verification( + gas_schedule: vector, + chain_id: u8, + initial_version: u64, + consensus_config: vector, + execution_config: vector, + epoch_interval_microsecs: u64, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + accounts: vector, + employee_vesting_start: u64, + employee_vesting_period_duration: u64, + employees: vector, + validators: vector + ) { + initialize( + gas_schedule, + chain_id, + initial_version, + consensus_config, + execution_config, + epoch_interval_microsecs, + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit + ); + features::change_feature_flags(aptos_framework, vector[1, 2], vector[]); + initialize_aptos_coin(aptos_framework); + aptos_governance::initialize_for_verification( + aptos_framework, + min_voting_threshold, + required_proposer_stake, + voting_duration_secs + ); + create_accounts(aptos_framework, accounts); + create_employee_validators(employee_vesting_start, employee_vesting_period_duration, employees); + create_initialize_validators_with_commission(aptos_framework, true, validators); + set_genesis_end(aptos_framework); + } + + #[test_only] + public fun setup() { + initialize( + x"000000000000000000", // empty gas schedule + 4u8, // TESTING chain ID + 0, + x"12", + x"13", + 1, + 0, + 1, + 1, + true, + 1, + 1, + 30, + ) + } + + #[test] + fun test_setup() { + setup(); + assert!(account::exists_at(@aptos_framework), 1); + assert!(account::exists_at(@0x2), 1); + assert!(account::exists_at(@0x3), 1); + assert!(account::exists_at(@0x4), 1); + assert!(account::exists_at(@0x5), 1); + assert!(account::exists_at(@0x6), 1); + assert!(account::exists_at(@0x7), 1); + assert!(account::exists_at(@0x8), 1); + assert!(account::exists_at(@0x9), 1); + assert!(account::exists_at(@0xa), 1); + } + + #[test(aptos_framework = @0x1)] + fun test_create_account(aptos_framework: &signer) { + setup(); + initialize_aptos_coin(aptos_framework); + + let addr = @0x121341; // 01 -> 0a are taken + let test_signer_before = create_account(aptos_framework, addr, 15); + let test_signer_after = create_account(aptos_framework, addr, 500); + assert!(test_signer_before == test_signer_after, 0); + assert!(coin::balance(addr) == 15, 1); + } + + #[test(aptos_framework = @0x1)] + fun test_create_accounts(aptos_framework: &signer) { + setup(); + initialize_aptos_coin(aptos_framework); + + // 01 -> 0a are taken + let addr0 = @0x121341; + let addr1 = @0x121345; + + let accounts = vector[ + AccountMap { + account_address: addr0, + balance: 12345, + }, + AccountMap { + account_address: addr1, + balance: 67890, + }, + ]; + + create_accounts(aptos_framework, accounts); + assert!(coin::balance(addr0) == 12345, 0); + assert!(coin::balance(addr1) == 67890, 1); + + create_account(aptos_framework, addr0, 23456); + assert!(coin::balance(addr0) == 12345, 2); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/governance_proposal.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/governance_proposal.move new file mode 100644 index 0000000..bae6c7d --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/governance_proposal.move @@ -0,0 +1,23 @@ +/// Define the GovernanceProposal that will be used as part of on-chain governance by AptosGovernance. +/// +/// This is separate from the AptosGovernance module to avoid circular dependency between AptosGovernance and Stake. +module aptos_framework::governance_proposal { + friend aptos_framework::aptos_governance; + + struct GovernanceProposal has store, drop {} + + /// Create and return a GovernanceProposal resource. Can only be called by AptosGovernance + public(friend) fun create_proposal(): GovernanceProposal { + GovernanceProposal {} + } + + /// Useful for AptosGovernance to create an empty proposal as proof. + public(friend) fun create_empty_proposal(): GovernanceProposal { + create_proposal() + } + + #[test_only] + public fun create_test_proposal(): GovernanceProposal { + create_empty_proposal() + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/guid.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/guid.move new file mode 100644 index 0000000..e6334bb --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/guid.move @@ -0,0 +1,68 @@ +/// A module for generating globally unique identifiers +module aptos_framework::guid { + friend aptos_framework::account; + friend aptos_framework::object; + + /// A globally unique identifier derived from the sender's address and a counter + struct GUID has drop, store { + id: ID + } + + /// A non-privileged identifier that can be freely created by anyone. Useful for looking up GUID's. + struct ID has copy, drop, store { + /// If creation_num is `i`, this is the `i+1`th GUID created by `addr` + creation_num: u64, + /// Address that created the GUID + addr: address + } + + /// GUID generator must be published ahead of first usage of `create_with_capability` function. + const EGUID_GENERATOR_NOT_PUBLISHED: u64 = 0; + + /// Create and return a new GUID from a trusted module. + public(friend) fun create(addr: address, creation_num_ref: &mut u64): GUID { + let creation_num = *creation_num_ref; + *creation_num_ref = creation_num + 1; + GUID { + id: ID { + creation_num, + addr, + } + } + } + + /// Create a non-privileged id from `addr` and `creation_num` + public fun create_id(addr: address, creation_num: u64): ID { + ID { creation_num, addr } + } + + /// Get the non-privileged ID associated with a GUID + public fun id(guid: &GUID): ID { + guid.id + } + + /// Return the account address that created the GUID + public fun creator_address(guid: &GUID): address { + guid.id.addr + } + + /// Return the account address that created the guid::ID + public fun id_creator_address(id: &ID): address { + id.addr + } + + /// Return the creation number associated with the GUID + public fun creation_num(guid: &GUID): u64 { + guid.id.creation_num + } + + /// Return the creation number associated with the guid::ID + public fun id_creation_num(id: &ID): u64 { + id.creation_num + } + + /// Return true if the GUID's ID is `id` + public fun eq_id(guid: &GUID, id: &ID): bool { + &guid.id == id + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/managed_coin.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/managed_coin.move new file mode 100644 index 0000000..d2932dd --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/managed_coin.move @@ -0,0 +1,205 @@ +/// ManagedCoin is built to make a simple walkthrough of the Coins module. +/// It contains scripts you will need to initialize, mint, burn, transfer coins. +/// By utilizing this current module, a developer can create his own coin and care less about mint and burn capabilities, +module aptos_framework::managed_coin { + use std::string; + use std::error; + use std::signer; + + use aptos_framework::coin::{Self, BurnCapability, FreezeCapability, MintCapability}; + + // + // Errors + // + + /// Account has no capabilities (burn/mint). + const ENO_CAPABILITIES: u64 = 1; + + // + // Data structures + // + + /// Capabilities resource storing mint and burn capabilities. + /// The resource is stored on the account that initialized coin `CoinType`. + struct Capabilities has key { + burn_cap: BurnCapability, + freeze_cap: FreezeCapability, + mint_cap: MintCapability, + } + + // + // Public functions + // + + /// Withdraw an `amount` of coin `CoinType` from `account` and burn it. + public entry fun burn( + account: &signer, + amount: u64, + ) acquires Capabilities { + let account_addr = signer::address_of(account); + + assert!( + exists>(account_addr), + error::not_found(ENO_CAPABILITIES), + ); + + let capabilities = borrow_global>(account_addr); + + let to_burn = coin::withdraw(account, amount); + coin::burn(to_burn, &capabilities.burn_cap); + } + + /// Initialize new coin `CoinType` in Aptos Blockchain. + /// Mint and Burn Capabilities will be stored under `account` in `Capabilities` resource. + public entry fun initialize( + account: &signer, + name: vector, + symbol: vector, + decimals: u8, + monitor_supply: bool, + ) { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + account, + string::utf8(name), + string::utf8(symbol), + decimals, + monitor_supply, + ); + + move_to(account, Capabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + /// Create new coins `CoinType` and deposit them into dst_addr's account. + public entry fun mint( + account: &signer, + dst_addr: address, + amount: u64, + ) acquires Capabilities { + let account_addr = signer::address_of(account); + + assert!( + exists>(account_addr), + error::not_found(ENO_CAPABILITIES), + ); + + let capabilities = borrow_global>(account_addr); + let coins_minted = coin::mint(amount, &capabilities.mint_cap); + coin::deposit(dst_addr, coins_minted); + } + + /// Creating a resource that stores balance of `CoinType` on user's account, withdraw and deposit event handlers. + /// Required if user wants to start accepting deposits of `CoinType` in his account. + public entry fun register(account: &signer) { + coin::register(account); + } + + // + // Tests + // + + #[test_only] + use std::option; + + #[test_only] + use aptos_framework::aggregator_factory; + + #[test_only] + struct FakeMoney {} + + #[test(source = @0xa11ce, destination = @0xb0b, mod_account = @0x1)] + public entry fun test_end_to_end( + source: signer, + destination: signer, + mod_account: signer + ) acquires Capabilities { + let source_addr = signer::address_of(&source); + let destination_addr = signer::address_of(&destination); + aptos_framework::account::create_account_for_test(source_addr); + aptos_framework::account::create_account_for_test(destination_addr); + aptos_framework::account::create_account_for_test(signer::address_of(&mod_account)); + aggregator_factory::initialize_aggregator_factory_for_test(&mod_account); + + initialize( + &mod_account, + b"Fake Money", + b"FMD", + 10, + true + ); + assert!(coin::is_coin_initialized(), 0); + + coin::register(&mod_account); + register(&source); + register(&destination); + + mint(&mod_account, source_addr, 50); + mint(&mod_account, destination_addr, 10); + assert!(coin::balance(source_addr) == 50, 1); + assert!(coin::balance(destination_addr) == 10, 2); + + let supply = coin::supply(); + assert!(option::is_some(&supply), 1); + assert!(option::extract(&mut supply) == 60, 2); + + coin::transfer(&source, destination_addr, 10); + assert!(coin::balance(source_addr) == 40, 3); + assert!(coin::balance(destination_addr) == 20, 4); + + coin::transfer(&source, signer::address_of(&mod_account), 40); + burn(&mod_account, 40); + + assert!(coin::balance(source_addr) == 0, 1); + + let new_supply = coin::supply(); + assert!(option::extract(&mut new_supply) == 20, 2); + } + + #[test(source = @0xa11ce, destination = @0xb0b, mod_account = @0x1)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun fail_mint( + source: signer, + destination: signer, + mod_account: signer, + ) acquires Capabilities { + let source_addr = signer::address_of(&source); + + aptos_framework::account::create_account_for_test(source_addr); + aptos_framework::account::create_account_for_test(signer::address_of(&destination)); + aptos_framework::account::create_account_for_test(signer::address_of(&mod_account)); + aggregator_factory::initialize_aggregator_factory_for_test(&mod_account); + + initialize(&mod_account, b"Fake money", b"FMD", 1, true); + coin::register(&mod_account); + register(&source); + register(&destination); + + mint(&destination, source_addr, 100); + } + + #[test(source = @0xa11ce, destination = @0xb0b, mod_account = @0x1)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun fail_burn( + source: signer, + destination: signer, + mod_account: signer, + ) acquires Capabilities { + let source_addr = signer::address_of(&source); + + aptos_framework::account::create_account_for_test(source_addr); + aptos_framework::account::create_account_for_test(signer::address_of(&destination)); + aptos_framework::account::create_account_for_test(signer::address_of(&mod_account)); + aggregator_factory::initialize_aggregator_factory_for_test(&mod_account); + + initialize(&mod_account, b"Fake money", b"FMD", 1, true); + coin::register(&mod_account); + register(&source); + register(&destination); + + mint(&mod_account, source_addr, 100); + burn(&destination, 10); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/multisig_account.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/multisig_account.move new file mode 100644 index 0000000..6c3778c --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/multisig_account.move @@ -0,0 +1,1881 @@ +/// Enhanced multisig account standard on Aptos. This is different from the native multisig scheme support enforced via +/// the account's auth key. +/// +/// This module allows creating a flexible and powerful multisig account with seamless support for updating owners +/// without changing the auth key. Users can choose to store transaction payloads waiting for owner signatures on chain +/// or off chain (primary consideration is decentralization/transparency vs gas cost). +/// +/// The multisig account is a resource account underneath. By default, it has no auth key and can only be controlled via +/// the special multisig transaction flow. However, owners can create a transaction to change the auth key to match a +/// private key off chain if so desired. +/// +/// Transactions need to be executed in order of creation, similar to transactions for a normal Aptos account (enforced +/// with account nonce). +/// +/// The flow is like below: +/// 1. Owners can create a new multisig account by calling create (signer is default single owner) or with +/// create_with_owners where multiple initial owner addresses can be specified. This is different (and easier) from +/// the native multisig scheme where the owners' public keys have to be specified. Here, only addresses are needed. +/// 2. Owners can be added/removed any time by calling add_owners or remove_owners. The transactions to do still need +/// to follow the k-of-n scheme specified for the multisig account. +/// 3. To create a new transaction, an owner can call create_transaction with the transaction payload. This will store +/// the full transaction payload on chain, which adds decentralization (censorship is not possible as the data is +/// available on chain) and makes it easier to fetch all transactions waiting for execution. If saving gas is desired, +/// an owner can alternatively call create_transaction_with_hash where only the payload hash is stored. Later execution +/// will be verified using the hash. Only owners can create transactions and a transaction id (incremeting id) will be +/// assigned. +/// 4. To approve or reject a transaction, other owners can call approve() or reject() with the transaction id. +/// 5. If there are enough approvals, any owner can execute the transaction using the special MultisigTransaction type +/// with the transaction id if the full payload is already stored on chain or with the transaction payload if only a +/// hash is stored. Transaction execution will first check with this module that the transaction payload has gotten +/// enough signatures. If so, it will be executed as the multisig account. The owner who executes will pay for gas. +/// 6. If there are enough rejections, any owner can finalize the rejection by calling execute_rejected_transaction(). +/// +/// Note that this multisig account model is not designed to use with a large number of owners. The more owners there +/// are, the more expensive voting on transactions will become. If a large number of owners is designed, such as in a +/// flat governance structure, clients are encouraged to write their own modules on top of this multisig account module +/// and implement the governance voting logic on top. +module aptos_framework::multisig_account { + use aptos_framework::account::{Self, SignerCapability, new_event_handle, create_resource_address}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::chain_id; + use aptos_framework::create_signer::create_signer; + use aptos_framework::coin; + use aptos_framework::event::{EventHandle, emit_event}; + use aptos_framework::timestamp::now_seconds; + use aptos_std::simple_map::{Self, SimpleMap}; + use aptos_std::table::{Self, Table}; + use std::bcs::to_bytes; + use std::error; + use std::hash::sha3_256; + use std::option::{Self, Option}; + use std::signer::address_of; + use std::string::String; + use std::vector; + + /// The salt used to create a resource account during multisig account creation. + /// This is used to avoid conflicts with other modules that also create resource accounts with the same owner + /// account. + const DOMAIN_SEPARATOR: vector = b"aptos_framework::multisig_account"; + + // Any error codes > 2000 can be thrown as part of transaction prologue. + /// Owner list cannot contain the same address more than once. + const EDUPLICATE_OWNER: u64 = 1; + /// Specified account is not a multisig account. + const EACCOUNT_NOT_MULTISIG: u64 = 2002; + /// Account executing this operation is not an owner of the multisig account. + const ENOT_OWNER: u64 = 2003; + /// Transaction payload cannot be empty. + const EPAYLOAD_CANNOT_BE_EMPTY: u64 = 4; + /// Multisig account must have at least one owner. + const ENOT_ENOUGH_OWNERS: u64 = 5; + /// Transaction with specified id cannot be found. + const ETRANSACTION_NOT_FOUND: u64 = 2006; + /// Provided target function does not match the hash stored in the on-chain transaction. + const EPAYLOAD_DOES_NOT_MATCH_HASH: u64 = 2008; + /// Transaction has not received enough approvals to be executed. + const ENOT_ENOUGH_APPROVALS: u64 = 2009; + /// Transaction has not received enough rejections to be officially rejected. + const ENOT_ENOUGH_REJECTIONS: u64 = 10; + /// Number of signatures required must be more than zero and at most the total number of owners. + const EINVALID_SIGNATURES_REQUIRED: u64 = 11; + /// Payload hash must be exactly 32 bytes (sha3-256). + const EINVALID_PAYLOAD_HASH: u64 = 12; + /// The multisig account itself cannot be an owner. + const EOWNER_CANNOT_BE_MULTISIG_ACCOUNT_ITSELF: u64 = 13; + /// Multisig accounts has not been enabled on this current network yet. + const EMULTISIG_ACCOUNTS_NOT_ENABLED_YET: u64 = 14; + /// The number of metadata keys and values don't match. + const ENUMBER_OF_METADATA_KEYS_AND_VALUES_DONT_MATCH: u64 = 15; + /// The specified metadata contains duplicate attributes (keys). + const EDUPLICATE_METADATA_KEY: u64 = 16; + /// The sequence number provided is invalid. It must be between [1, next pending transaction - 1]. + const EINVALID_SEQUENCE_NUMBER: u64 = 17; + /// Provided owners to remove and new owners overlap. + const EOWNERS_TO_REMOVE_NEW_OWNERS_OVERLAP: u64 = 18; + + const ZERO_AUTH_KEY: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + + /// Represents a multisig account's configurations and transactions. + /// This will be stored in the multisig account (created as a resource account separate from any owner accounts). + struct MultisigAccount has key { + // The list of all owner addresses. + owners: vector
, + // The number of signatures required to pass a transaction (k in k-of-n). + num_signatures_required: u64, + // Map from transaction id (incrementing id) to transactions to execute for this multisig account. + // Already executed transactions are deleted to save on storage but can always be accessed via events. + transactions: Table, + // The sequence number assigned to the last executed or rejected transaction. Used to enforce in-order + // executions of proposals, similar to sequence number for a normal (single-user) account. + last_executed_sequence_number: u64, + // The sequence number to assign to the next transaction. This is not always last_executed_sequence_number + 1 + // as there can be multiple pending transactions. The number of pending transactions should be equal to + // next_sequence_number - (last_executed_sequence_number + 1). + next_sequence_number: u64, + // The signer capability controlling the multisig (resource) account. This can be exchanged for the signer. + // Currently not used as the MultisigTransaction can validate and create a signer directly in the VM but + // this can be useful to have for on-chain composability in the future. + signer_cap: Option, + // The multisig account's metadata such as name, description, etc. This can be updated through the multisig + // transaction flow (i.e. self-update). + // Note: Attributes can be arbitrarily set by the multisig account and thus will only be used for off-chain + // display purposes only. They don't change any on-chain semantics of the multisig account. + metadata: SimpleMap>, + + // Events. + add_owners_events: EventHandle, + remove_owners_events: EventHandle, + update_signature_required_events: EventHandle, + create_transaction_events: EventHandle, + vote_events: EventHandle, + execute_rejected_transaction_events: EventHandle, + execute_transaction_events: EventHandle, + transaction_execution_failed_events: EventHandle, + metadata_updated_events: EventHandle, + } + + /// A transaction to be executed in a multisig account. + /// This must contain either the full transaction payload or its hash (stored as bytes). + struct MultisigTransaction has copy, drop, store { + payload: Option>, + payload_hash: Option>, + // Mapping from owner adress to vote (yes for approve, no for reject). Uses a simple map to deduplicate. + votes: SimpleMap, + // The owner who created this transaction. + creator: address, + // The timestamp in seconds when the transaction was created. + creation_time_secs: u64, + } + + /// Contains information about execution failure. + struct ExecutionError has copy, drop, store { + // The module where the error occurs. + abort_location: String, + // There are 3 error types, stored as strings: + // 1. VMError. Indicates an error from the VM, e.g. out of gas, invalid auth key, etc. + // 2. MoveAbort. Indicates an abort, e.g. assertion failure, from inside the executed Move code. + // 3. MoveExecutionFailure. Indicates an error from Move code where the VM could not continue. For example, + // arithmetic failures. + error_type: String, + // The detailed error code explaining which error occurred. + error_code: u64, + } + + /// Used only for verifying multisig account creation on top of existing accounts. + struct MultisigAccountCreationMessage has copy, drop { + // Chain id is included to prevent cross-chain replay. + chain_id: u8, + // Account address is included to prevent cross-account replay (when multiple accounts share the same auth key). + account_address: address, + // Sequence number is not needed for replay protection as the multisig account can only be created once. + // But it's included to ensure timely execution of account creation. + sequence_number: u64, + // The list of owners for the multisig account. + owners: vector
, + // The number of signatures required (signature threshold). + num_signatures_required: u64, + } + + /// Used only for verifying multisig account creation on top of existing accounts and rotating the auth key to 0x0. + struct MultisigAccountCreationWithAuthKeyRevocationMessage has copy, drop { + // Chain id is included to prevent cross-chain replay. + chain_id: u8, + // Account address is included to prevent cross-account replay (when multiple accounts share the same auth key). + account_address: address, + // Sequence number is not needed for replay protection as the multisig account can only be created once. + // But it's included to ensure timely execution of account creation. + sequence_number: u64, + // The list of owners for the multisig account. + owners: vector
, + // The number of signatures required (signature threshold). + num_signatures_required: u64, + } + + /// Event emitted when new owners are added to the multisig account. + struct AddOwnersEvent has drop, store { + owners_added: vector
, + } + + /// Event emitted when new owners are removed from the multisig account. + struct RemoveOwnersEvent has drop, store { + owners_removed: vector
, + } + + /// Event emitted when the number of signatures required is updated. + struct UpdateSignaturesRequiredEvent has drop, store { + old_num_signatures_required: u64, + new_num_signatures_required: u64, + } + + /// Event emitted when a transaction is created. + struct CreateTransactionEvent has drop, store { + creator: address, + sequence_number: u64, + transaction: MultisigTransaction, + } + + /// Event emitted when an owner approves or rejects a transaction. + struct VoteEvent has drop, store { + owner: address, + sequence_number: u64, + approved: bool, + } + + /// Event emitted when a transaction is officially rejected because the number of rejections has reached the + /// number of signatures required. + struct ExecuteRejectedTransactionEvent has drop, store { + sequence_number: u64, + num_rejections: u64, + executor: address, + } + + /// Event emitted when a transaction is executed. + struct TransactionExecutionSucceededEvent has drop, store { + executor: address, + sequence_number: u64, + transaction_payload: vector, + num_approvals: u64, + } + + /// Event emitted when a transaction's execution failed. + struct TransactionExecutionFailedEvent has drop, store { + executor: address, + sequence_number: u64, + transaction_payload: vector, + num_approvals: u64, + execution_error: ExecutionError, + } + + /// Event emitted when a transaction's metadata is updated. + struct MetadataUpdatedEvent has drop, store { + old_metadata: SimpleMap>, + new_metadata: SimpleMap>, + } + + ////////////////////////// View functions /////////////////////////////// + + #[view] + /// Return the multisig account's metadata. + public fun metadata(multisig_account: address): SimpleMap> acquires MultisigAccount { + borrow_global(multisig_account).metadata + } + + #[view] + /// Return the number of signatures required to execute or execute-reject a transaction in the provided + /// multisig account. + public fun num_signatures_required(multisig_account: address): u64 acquires MultisigAccount { + borrow_global(multisig_account).num_signatures_required + } + + #[view] + /// Return a vector of all of the provided multisig account's owners. + public fun owners(multisig_account: address): vector
acquires MultisigAccount { + borrow_global(multisig_account).owners + } + + #[view] + /// Return the transaction with the given transaction id. + public fun get_transaction( + multisig_account: address, + sequence_number: u64, + ): MultisigTransaction acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + assert!( + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, + error::invalid_argument(EINVALID_SEQUENCE_NUMBER), + ); + *table::borrow(&multisig_account_resource.transactions, sequence_number) + } + + #[view] + /// Return all pending transactions. + public fun get_pending_transactions(multisig_account: address): vector acquires MultisigAccount { + let pending_transactions: vector = vector[]; + let multisig_account = borrow_global(multisig_account); + let i = multisig_account.last_executed_sequence_number + 1; + let next_sequence_number = multisig_account.next_sequence_number; + while (i < next_sequence_number) { + vector::push_back(&mut pending_transactions, *table::borrow(&multisig_account.transactions, i)); + i = i + 1; + }; + pending_transactions + } + + #[view] + /// Return the payload for the next transaction in the queue. + public fun get_next_transaction_payload( + multisig_account: address, provided_payload: vector): vector acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + let sequence_number = multisig_account_resource.last_executed_sequence_number + 1; + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + + if (option::is_some(&transaction.payload)) { + *option::borrow(&transaction.payload) + } else { + provided_payload + } + } + + #[view] + /// Return true if the transaction with given transaction id can be executed now. + public fun can_be_executed( + multisig_account: address, sequence_number: u64): bool acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + assert!( + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, + error::invalid_argument(EINVALID_SEQUENCE_NUMBER), + ); + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + let (num_approvals, _) = num_approvals_and_rejections(&multisig_account_resource.owners, transaction); + sequence_number == multisig_account_resource.last_executed_sequence_number + 1 && + num_approvals >= multisig_account_resource.num_signatures_required + } + + #[view] + /// Return true if the transaction with given transaction id can be officially rejected. + public fun can_be_rejected( + multisig_account: address, sequence_number: u64): bool acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + assert!( + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, + error::invalid_argument(EINVALID_SEQUENCE_NUMBER), + ); + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + let (_, num_rejections) = num_approvals_and_rejections(&multisig_account_resource.owners, transaction); + sequence_number == multisig_account_resource.last_executed_sequence_number + 1 && + num_rejections >= multisig_account_resource.num_signatures_required + } + + #[view] + /// Return the predicted address for the next multisig account if created from the given creator address. + public fun get_next_multisig_account_address(creator: address): address { + let owner_nonce = account::get_sequence_number(creator); + create_resource_address(&creator, create_multisig_account_seed(to_bytes(&owner_nonce))) + } + + #[view] + /// Return the id of the last transaction that was executed (successful or failed) or removed. + public fun last_resolved_sequence_number(multisig_account: address): u64 acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + multisig_account_resource.last_executed_sequence_number + } + + #[view] + /// Return the id of the next transaction created. + public fun next_sequence_number(multisig_account: address): u64 acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + multisig_account_resource.next_sequence_number + } + + #[view] + /// Return a bool tuple indicating whether an owner has voted and if so, whether they voted yes or no. + public fun vote( + multisig_account: address, sequence_number: u64, owner: address): (bool, bool) acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + assert!( + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, + error::invalid_argument(EINVALID_SEQUENCE_NUMBER), + ); + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + let votes = &transaction.votes; + let voted = simple_map::contains_key(votes, &owner); + let vote = voted && *simple_map::borrow(votes, &owner); + (voted, vote) + } + + ////////////////////////// Multisig account creation functions /////////////////////////////// + + /// Creates a new multisig account on top of an existing account. + /// + /// This offers a migration path for an existing account with a multi-ed25519 auth key (native multisig account). + /// In order to ensure a malicious module cannot obtain backdoor control over an existing account, a signed message + /// with a valid signature from the account's auth key is required. + /// + /// Note that this does not revoke auth key-based control over the account. Owners should separately rotate the auth + /// key after they are fully migrated to the new multisig account. Alternatively, they can call + /// create_with_existing_account_and_revoke_auth_key instead. + public entry fun create_with_existing_account( + multisig_address: address, + owners: vector
, + num_signatures_required: u64, + account_scheme: u8, + account_public_key: vector, + create_multisig_account_signed_message: vector, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + // Verify that the `MultisigAccountCreationMessage` has the right information and is signed by the account + // owner's key. + let proof_challenge = MultisigAccountCreationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners, + num_signatures_required, + }; + account::verify_signed_message( + multisig_address, + account_scheme, + account_public_key, + create_multisig_account_signed_message, + proof_challenge, + ); + + // We create the signer for the multisig account here since this is required to add the MultisigAccount resource + // This should be safe and authorized because we have verified the signed message from the existing account + // that authorizes creating a multisig account with the specified owners and signature threshold. + let multisig_account = &create_signer(multisig_address); + create_with_owners_internal( + multisig_account, + owners, + num_signatures_required, + option::none(), + metadata_keys, + metadata_values, + ); + } + + /// Creates a new multisig account on top of an existing account and immediately rotate the origin auth key to 0x0. + /// + /// Note: If the original account is a resource account, this does not revoke all control over it as if any + /// SignerCapability of the resource account still exists, it can still be used to generate the signer for the + /// account. + public entry fun create_with_existing_account_and_revoke_auth_key( + multisig_address: address, + owners: vector
, + num_signatures_required: u64, + account_scheme: u8, + account_public_key: vector, + create_multisig_account_signed_message: vector, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + // Verify that the `MultisigAccountCreationMessage` has the right information and is signed by the account + // owner's key. + let proof_challenge = MultisigAccountCreationWithAuthKeyRevocationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners, + num_signatures_required, + }; + account::verify_signed_message( + multisig_address, + account_scheme, + account_public_key, + create_multisig_account_signed_message, + proof_challenge, + ); + + // We create the signer for the multisig account here since this is required to add the MultisigAccount resource + // This should be safe and authorized because we have verified the signed message from the existing account + // that authorizes creating a multisig account with the specified owners and signature threshold. + let multisig_account = &create_signer(multisig_address); + create_with_owners_internal( + multisig_account, + owners, + num_signatures_required, + option::none(), + metadata_keys, + metadata_values, + ); + + // Rotate the account's auth key to 0x0, which effectively revokes control via auth key. + let multisig_address = address_of(multisig_account); + account::rotate_authentication_key_internal(multisig_account, ZERO_AUTH_KEY); + // This also needs to revoke any signer capability or rotation capability that exists for the account to + // completely remove all access to the account. + if (account::is_signer_capability_offered(multisig_address)) { + account::revoke_any_signer_capability(multisig_account); + }; + if (account::is_rotation_capability_offered(multisig_address)) { + account::revoke_any_rotation_capability(multisig_account); + }; + } + + /// Creates a new multisig account and add the signer as a single owner. + public entry fun create( + owner: &signer, + num_signatures_required: u64, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + create_with_owners(owner, vector[], num_signatures_required, metadata_keys, metadata_values); + } + + /// Creates a new multisig account with the specified additional owner list and signatures required. + /// + /// @param additional_owners The owner account who calls this function cannot be in the additional_owners and there + /// cannot be any duplicate owners in the list. + /// @param num_signatures_required The number of signatures required to execute a transaction. Must be at least 1 and + /// at most the total number of owners. + public entry fun create_with_owners( + owner: &signer, + additional_owners: vector
, + num_signatures_required: u64, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + let (multisig_account, multisig_signer_cap) = create_multisig_account(owner); + vector::push_back(&mut additional_owners, address_of(owner)); + create_with_owners_internal( + &multisig_account, + additional_owners, + num_signatures_required, + option::some(multisig_signer_cap), + metadata_keys, + metadata_values, + ); + } + + /// Like `create_with_owners`, but removes the calling account after creation. + /// + /// This is for creating a vanity multisig account from a bootstrapping account that should not + /// be an owner after the vanity multisig address has been secured. + public entry fun create_with_owners_then_remove_bootstrapper( + bootstrapper: &signer, + owners: vector
, + num_signatures_required: u64, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + let bootstrapper_address = address_of(bootstrapper); + create_with_owners( + bootstrapper, + owners, + num_signatures_required, + metadata_keys, + metadata_values + ); + update_owner_schema( + get_next_multisig_account_address(bootstrapper_address), + vector[], + vector[bootstrapper_address], + option::none() + ); + } + + fun create_with_owners_internal( + multisig_account: &signer, + owners: vector
, + num_signatures_required: u64, + multisig_account_signer_cap: Option, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + assert!(features::multisig_accounts_enabled(), error::unavailable(EMULTISIG_ACCOUNTS_NOT_ENABLED_YET)); + assert!( + num_signatures_required > 0 && num_signatures_required <= vector::length(&owners), + error::invalid_argument(EINVALID_SIGNATURES_REQUIRED), + ); + + let multisig_address = address_of(multisig_account); + validate_owners(&owners, multisig_address); + move_to(multisig_account, MultisigAccount { + owners, + num_signatures_required, + transactions: table::new(), + metadata: simple_map::create>(), + // First transaction will start at id 1 instead of 0. + last_executed_sequence_number: 0, + next_sequence_number: 1, + signer_cap: multisig_account_signer_cap, + add_owners_events: new_event_handle(multisig_account), + remove_owners_events: new_event_handle(multisig_account), + update_signature_required_events: new_event_handle(multisig_account), + create_transaction_events: new_event_handle(multisig_account), + vote_events: new_event_handle(multisig_account), + execute_rejected_transaction_events: new_event_handle(multisig_account), + execute_transaction_events: new_event_handle(multisig_account), + transaction_execution_failed_events: new_event_handle(multisig_account), + metadata_updated_events: new_event_handle(multisig_account), + }); + + update_metadata_internal(multisig_account, metadata_keys, metadata_values, false); + } + + ////////////////////////// Self-updates /////////////////////////////// + + /// Similar to add_owners, but only allow adding one owner. + entry fun add_owner(multisig_account: &signer, new_owner: address) acquires MultisigAccount { + add_owners(multisig_account, vector[new_owner]); + } + + /// Add new owners to the multisig account. This can only be invoked by the multisig account itself, through the + /// proposal flow. + /// + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the owners list. + entry fun add_owners( + multisig_account: &signer, new_owners: vector
) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + new_owners, + vector[], + option::none() + ); + } + + /// Add owners then update number of signatures required, in a single operation. + entry fun add_owners_and_update_signatures_required( + multisig_account: &signer, + new_owners: vector
, + new_num_signatures_required: u64 + ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + new_owners, + vector[], + option::some(new_num_signatures_required) + ); + } + + /// Similar to remove_owners, but only allow removing one owner. + entry fun remove_owner( + multisig_account: &signer, owner_to_remove: address) acquires MultisigAccount { + remove_owners(multisig_account, vector[owner_to_remove]); + } + + /// Remove owners from the multisig account. This can only be invoked by the multisig account itself, through the + /// proposal flow. + /// + /// This function skips any owners who are not in the multisig account's list of owners. + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the owners list. + entry fun remove_owners( + multisig_account: &signer, owners_to_remove: vector
) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + vector[], + owners_to_remove, + option::none() + ); + } + + /// Swap an owner in for an old one, without changing required signatures. + entry fun swap_owner( + multisig_account: &signer, + to_swap_in: address, + to_swap_out: address + ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + vector[to_swap_in], + vector[to_swap_out], + option::none() + ); + } + + /// Swap owners in and out, without changing required signatures. + entry fun swap_owners( + multisig_account: &signer, + to_swap_in: vector
, + to_swap_out: vector
+ ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + to_swap_in, + to_swap_out, + option::none() + ); + } + + /// Swap owners in and out, updating number of required signatures. + entry fun swap_owners_and_update_signatures_required( + multisig_account: &signer, + new_owners: vector
, + owners_to_remove: vector
, + new_num_signatures_required: u64 + ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + new_owners, + owners_to_remove, + option::some(new_num_signatures_required) + ); + } + + /// Update the number of signatures required to execute transaction in the specified multisig account. + /// + /// This can only be invoked by the multisig account itself, through the proposal flow. + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the number of signatures required. + entry fun update_signatures_required( + multisig_account: &signer, new_num_signatures_required: u64) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + vector[], + vector[], + option::some(new_num_signatures_required) + ); + } + + /// Allow the multisig account to update its own metadata. Note that this overrides the entire existing metadata. + /// If any attributes are not specified in the metadata, they will be removed! + /// + /// This can only be invoked by the multisig account itself, through the proposal flow. + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the number of signatures required. + entry fun update_metadata( + multisig_account: &signer, keys: vector, values: vector>) acquires MultisigAccount { + update_metadata_internal(multisig_account, keys, values, true); + } + + fun update_metadata_internal( + multisig_account: &signer, + keys: vector, + values: vector>, + emit_event: bool, + ) acquires MultisigAccount { + let num_attributes = vector::length(&keys); + assert!( + num_attributes == vector::length(&values), + error::invalid_argument(ENUMBER_OF_METADATA_KEYS_AND_VALUES_DONT_MATCH), + ); + + let multisig_address = address_of(multisig_account); + assert_multisig_account_exists(multisig_address); + let multisig_account_resource = borrow_global_mut(multisig_address); + let old_metadata = multisig_account_resource.metadata; + multisig_account_resource.metadata = simple_map::create>(); + let metadata = &mut multisig_account_resource.metadata; + let i = 0; + while (i < num_attributes) { + let key = *vector::borrow(&keys, i); + let value = *vector::borrow(&values, i); + assert!( + !simple_map::contains_key(metadata, &key), + error::invalid_argument(EDUPLICATE_METADATA_KEY), + ); + + simple_map::add(metadata, key, value); + i = i + 1; + }; + + if (emit_event) { + emit_event( + &mut multisig_account_resource.metadata_updated_events, + MetadataUpdatedEvent { + old_metadata, + new_metadata: multisig_account_resource.metadata, + } + ); + }; + } + + ////////////////////////// Multisig transaction flow /////////////////////////////// + + /// Create a multisig transaction, which will have one approval initially (from the creator). + public entry fun create_transaction( + owner: &signer, + multisig_account: address, + payload: vector, + ) acquires MultisigAccount { + assert!(vector::length(&payload) > 0, error::invalid_argument(EPAYLOAD_CANNOT_BE_EMPTY)); + + assert_multisig_account_exists(multisig_account); + let multisig_account_resource = borrow_global_mut(multisig_account); + assert_is_owner(owner, multisig_account_resource); + + let creator = address_of(owner); + let transaction = MultisigTransaction { + payload: option::some(payload), + payload_hash: option::none>(), + votes: simple_map::create(), + creator, + creation_time_secs: now_seconds(), + }; + add_transaction(creator, multisig_account_resource, transaction); + } + + /// Create a multisig transaction with a transaction hash instead of the full payload. + /// This means the payload will be stored off chain for gas saving. Later, during execution, the executor will need + /// to provide the full payload, which will be validated against the hash stored on-chain. + public entry fun create_transaction_with_hash( + owner: &signer, + multisig_account: address, + payload_hash: vector, + ) acquires MultisigAccount { + // Payload hash is a sha3-256 hash, so it must be exactly 32 bytes. + assert!(vector::length(&payload_hash) == 32, error::invalid_argument(EINVALID_PAYLOAD_HASH)); + + assert_multisig_account_exists(multisig_account); + let multisig_account_resource = borrow_global_mut(multisig_account); + assert_is_owner(owner, multisig_account_resource); + + let creator = address_of(owner); + let transaction = MultisigTransaction { + payload: option::none>(), + payload_hash: option::some(payload_hash), + votes: simple_map::create(), + creator, + creation_time_secs: now_seconds(), + }; + add_transaction(creator, multisig_account_resource, transaction); + } + + /// Approve a multisig transaction. + public entry fun approve_transaction( + owner: &signer, multisig_account: address, sequence_number: u64) acquires MultisigAccount { + vote_transanction(owner, multisig_account, sequence_number, true); + } + + /// Reject a multisig transaction. + public entry fun reject_transaction( + owner: &signer, multisig_account: address, sequence_number: u64) acquires MultisigAccount { + vote_transanction(owner, multisig_account, sequence_number, false); + } + + /// Generic function that can be used to either approve or reject a multisig transaction + public entry fun vote_transanction( + owner: &signer, multisig_account: address, sequence_number: u64, approved: bool) acquires MultisigAccount { + assert_multisig_account_exists(multisig_account); + let multisig_account_resource = borrow_global_mut(multisig_account); + assert_is_owner(owner, multisig_account_resource); + + assert!( + table::contains(&multisig_account_resource.transactions, sequence_number), + error::not_found(ETRANSACTION_NOT_FOUND), + ); + let transaction = table::borrow_mut(&mut multisig_account_resource.transactions, sequence_number); + let votes = &mut transaction.votes; + let owner_addr = address_of(owner); + + if (simple_map::contains_key(votes, &owner_addr)) { + *simple_map::borrow_mut(votes, &owner_addr) = approved; + } else { + simple_map::add(votes, owner_addr, approved); + }; + + emit_event( + &mut multisig_account_resource.vote_events, + VoteEvent { + owner: owner_addr, + sequence_number, + approved, + } + ); + } + + /// Remove the next transaction if it has sufficient owner rejections. + public entry fun execute_rejected_transaction( + owner: &signer, + multisig_account: address, + ) acquires MultisigAccount { + assert_multisig_account_exists(multisig_account); + let multisig_account_resource = borrow_global_mut(multisig_account); + assert_is_owner(owner, multisig_account_resource); + let sequence_number = multisig_account_resource.last_executed_sequence_number + 1; + assert!( + table::contains(&multisig_account_resource.transactions, sequence_number), + error::not_found(ETRANSACTION_NOT_FOUND), + ); + let (_, num_rejections) = remove_executed_transaction(multisig_account_resource); + assert!( + num_rejections >= multisig_account_resource.num_signatures_required, + error::invalid_state(ENOT_ENOUGH_REJECTIONS), + ); + + emit_event( + &mut multisig_account_resource.execute_rejected_transaction_events, + ExecuteRejectedTransactionEvent { + sequence_number, + num_rejections, + executor: address_of(owner), + } + ); + } + + ////////////////////////// To be called by VM only /////////////////////////////// + + /// Called by the VM as part of transaction prologue, which is invoked during mempool transaction validation and as + /// the first step of transaction execution. + /// + /// Transaction payload is optional if it's already stored on chain for the transaction. + fun validate_multisig_transaction( + owner: &signer, multisig_account: address, payload: vector) acquires MultisigAccount { + assert_multisig_account_exists(multisig_account); + let multisig_account_resource = borrow_global(multisig_account); + assert_is_owner(owner, multisig_account_resource); + let sequence_number = multisig_account_resource.last_executed_sequence_number + 1; + assert!( + table::contains(&multisig_account_resource.transactions, sequence_number), + error::invalid_argument(ETRANSACTION_NOT_FOUND), + ); + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + let (num_approvals, _) = num_approvals_and_rejections(&multisig_account_resource.owners, transaction); + assert!( + num_approvals >= multisig_account_resource.num_signatures_required, + error::invalid_argument(ENOT_ENOUGH_APPROVALS), + ); + + // If the transaction payload is not stored on chain, verify that the provided payload matches the hashes stored + // on chain. + if (option::is_some(&transaction.payload_hash)) { + let payload_hash = option::borrow(&transaction.payload_hash); + assert!( + sha3_256(payload) == *payload_hash, + error::invalid_argument(EPAYLOAD_DOES_NOT_MATCH_HASH), + ); + }; + } + + /// Post-execution cleanup for a successful multisig transaction execution. + /// This function is private so no other code can call this beside the VM itself as part of MultisigTransaction. + fun successful_transaction_execution_cleanup( + executor: address, + multisig_account: address, + transaction_payload: vector, + ) acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + let (num_approvals, _) = remove_executed_transaction(multisig_account_resource); + emit_event( + &mut multisig_account_resource.execute_transaction_events, + TransactionExecutionSucceededEvent { + sequence_number: multisig_account_resource.last_executed_sequence_number, + transaction_payload, + num_approvals, + executor, + } + ); + } + + /// Post-execution cleanup for a failed multisig transaction execution. + /// This function is private so no other code can call this beside the VM itself as part of MultisigTransaction. + fun failed_transaction_execution_cleanup( + executor: address, + multisig_account: address, + transaction_payload: vector, + execution_error: ExecutionError, + ) acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + let (num_approvals, _) = remove_executed_transaction(multisig_account_resource); + emit_event( + &mut multisig_account_resource.transaction_execution_failed_events, + TransactionExecutionFailedEvent { + executor, + sequence_number: multisig_account_resource.last_executed_sequence_number, + transaction_payload, + num_approvals, + execution_error, + } + ); + } + + ////////////////////////// Private functions /////////////////////////////// + + // Remove the next transaction in the queue as it's been executed and return the number of approvals it had. + fun remove_executed_transaction(multisig_account_resource: &mut MultisigAccount): (u64, u64) { + let sequence_number = multisig_account_resource.last_executed_sequence_number + 1; + let transaction = table::remove(&mut multisig_account_resource.transactions, sequence_number); + multisig_account_resource.last_executed_sequence_number = sequence_number; + num_approvals_and_rejections(&multisig_account_resource.owners, &transaction) + } + + fun add_transaction(creator: address, multisig_account: &mut MultisigAccount, transaction: MultisigTransaction) { + // The transaction creator also automatically votes for the transaction. + simple_map::add(&mut transaction.votes, creator, true); + + let sequence_number = multisig_account.next_sequence_number; + multisig_account.next_sequence_number = sequence_number + 1; + table::add(&mut multisig_account.transactions, sequence_number, transaction); + emit_event( + &mut multisig_account.create_transaction_events, + CreateTransactionEvent { creator, sequence_number, transaction }, + ); + } + + fun create_multisig_account(owner: &signer): (signer, SignerCapability) { + let owner_nonce = account::get_sequence_number(address_of(owner)); + let (multisig_signer, multisig_signer_cap) = + account::create_resource_account(owner, create_multisig_account_seed(to_bytes(&owner_nonce))); + // Register the account to receive APT as this is not done by default as part of the resource account creation + // flow. + if (!coin::is_account_registered(address_of(&multisig_signer))) { + coin::register(&multisig_signer); + }; + + (multisig_signer, multisig_signer_cap) + } + + fun create_multisig_account_seed(seed: vector): vector { + // Generate a seed that will be used to create the resource account that hosts the multisig account. + let multisig_account_seed = vector::empty(); + vector::append(&mut multisig_account_seed, DOMAIN_SEPARATOR); + vector::append(&mut multisig_account_seed, seed); + + multisig_account_seed + } + + fun validate_owners(owners: &vector
, multisig_account: address) { + let distinct_owners: vector
= vector[]; + vector::for_each_ref(owners, |owner| { + let owner = *owner; + assert!(owner != multisig_account, error::invalid_argument(EOWNER_CANNOT_BE_MULTISIG_ACCOUNT_ITSELF)); + let (found, _) = vector::index_of(&distinct_owners, &owner); + assert!(!found, error::invalid_argument(EDUPLICATE_OWNER)); + vector::push_back(&mut distinct_owners, owner); + }); + } + + fun assert_is_owner(owner: &signer, multisig_account: &MultisigAccount) { + assert!( + vector::contains(&multisig_account.owners, &address_of(owner)), + error::permission_denied(ENOT_OWNER), + ); + } + + fun num_approvals_and_rejections(owners: &vector
, transaction: &MultisigTransaction): (u64, u64) { + let num_approvals = 0; + let num_rejections = 0; + + let votes = &transaction.votes; + vector::for_each_ref(owners, |owner| { + if (simple_map::contains_key(votes, owner)) { + if (*simple_map::borrow(votes, owner)) { + num_approvals = num_approvals + 1; + } else { + num_rejections = num_rejections + 1; + }; + } + }); + + (num_approvals, num_rejections) + } + + fun assert_multisig_account_exists(multisig_account: address) { + assert!(exists(multisig_account), error::invalid_state(EACCOUNT_NOT_MULTISIG)); + } + + /// Add new owners, remove owners to remove, update signatures required. + fun update_owner_schema( + multisig_address: address, + new_owners: vector
, + owners_to_remove: vector
, + optional_new_num_signatures_required: Option, + ) acquires MultisigAccount { + assert_multisig_account_exists(multisig_address); + let multisig_account_ref_mut = + borrow_global_mut(multisig_address); + // Verify no overlap between new owners and owners to remove. + vector::for_each_ref(&new_owners, |new_owner_ref| { + assert!( + !vector::contains(&owners_to_remove, new_owner_ref), + error::invalid_argument(EOWNERS_TO_REMOVE_NEW_OWNERS_OVERLAP) + ) + }); + // If new owners provided, try to add them and emit an event. + if (vector::length(&new_owners) > 0) { + vector::append(&mut multisig_account_ref_mut.owners, new_owners); + validate_owners( + &multisig_account_ref_mut.owners, + multisig_address + ); + emit_event( + &mut multisig_account_ref_mut.add_owners_events, + AddOwnersEvent { owners_added: new_owners } + ); + }; + // If owners to remove provided, try to remove them. + if (vector::length(&owners_to_remove) > 0) { + let owners_ref_mut = &mut multisig_account_ref_mut.owners; + let owners_removed = vector[]; + vector::for_each_ref(&owners_to_remove, |owner_to_remove_ref| { + let (found, index) = + vector::index_of(owners_ref_mut, owner_to_remove_ref); + if (found) { + vector::push_back( + &mut owners_removed, + vector::swap_remove(owners_ref_mut, index) + ); + } + }); + // Only emit event if owner(s) actually removed. + if (vector::length(&owners_removed) > 0) { + emit_event( + &mut multisig_account_ref_mut.remove_owners_events, + RemoveOwnersEvent { owners_removed } + ); + } + }; + // If new signature count provided, try to update count. + if (option::is_some(&optional_new_num_signatures_required)) { + let new_num_signatures_required = + option::extract(&mut optional_new_num_signatures_required); + assert!( + new_num_signatures_required > 0, + error::invalid_argument(EINVALID_SIGNATURES_REQUIRED) + ); + let old_num_signatures_required = + multisig_account_ref_mut.num_signatures_required; + // Only apply update and emit event if a change indicated. + if (new_num_signatures_required != old_num_signatures_required) { + multisig_account_ref_mut.num_signatures_required = + new_num_signatures_required; + emit_event( + &mut multisig_account_ref_mut.update_signature_required_events, + UpdateSignaturesRequiredEvent { + old_num_signatures_required, + new_num_signatures_required, + } + ); + } + }; + // Verify number of owners. + let num_owners = vector::length(&multisig_account_ref_mut.owners); + assert!( + num_owners >= multisig_account_ref_mut.num_signatures_required, + error::invalid_state(ENOT_ENOUGH_OWNERS) + ); + } + + ////////////////////////// Tests /////////////////////////////// + + #[test_only] + use aptos_framework::aptos_account::create_account; + #[test_only] + use aptos_framework::timestamp; + #[test_only] + use aptos_std::from_bcs; + #[test_only] + use aptos_std::multi_ed25519; + #[test_only] + use std::string::utf8; + use std::features; + + #[test_only] + const PAYLOAD: vector = vector[1, 2, 3]; + #[test_only] + const ERROR_TYPE: vector = b"MoveAbort"; + #[test_only] + const ABORT_LOCATION: vector = b"abort_location"; + #[test_only] + const ERROR_CODE: u64 = 10; + + #[test_only] + fun execution_error(): ExecutionError { + ExecutionError { + abort_location: utf8(ABORT_LOCATION), + error_type: utf8(ERROR_TYPE), + error_code: ERROR_CODE, + } + } + + #[test_only] + fun setup() { + let framework_signer = &create_signer(@0x1); + features::change_feature_flags( + framework_signer, vector[features::get_multisig_accounts_feature()], vector[]); + timestamp::set_time_has_started_for_testing(framework_signer); + chain_id::initialize_for_test(framework_signer, 1); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_end_to_end( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + // Create three transactions. + create_transaction(owner_1, multisig_account, PAYLOAD); + create_transaction(owner_2, multisig_account, PAYLOAD); + create_transaction_with_hash(owner_3, multisig_account, sha3_256(PAYLOAD)); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 1), + get_transaction(multisig_account, 2), + get_transaction(multisig_account, 3), + ], 0); + + // Owner 3 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_1, multisig_account, 3); + // Third transaction has 2 approvals but cannot be executed out-of-order. + assert!(!can_be_executed(multisig_account, 3), 0); + + // Owner 1 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_2, multisig_account, 1); + // First transaction has 2 approvals so it can be executed. + assert!(can_be_executed(multisig_account, 1), 1); + // First transaction was executed successfully. + successful_transaction_execution_cleanup(owner_2_addr, multisig_account,vector[]); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 2), + get_transaction(multisig_account, 3), + ], 0); + + reject_transaction(owner_1, multisig_account, 2); + reject_transaction(owner_3, multisig_account, 2); + // Second transaction has 1 approval (owner 3) and 2 rejections (owners 1 & 2) and thus can be removed. + assert!(can_be_rejected(multisig_account, 2), 2); + execute_rejected_transaction(owner_1, multisig_account); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 3), + ], 0); + + // Third transaction can be executed now but execution fails. + failed_transaction_execution_cleanup(owner_3_addr, multisig_account, PAYLOAD, execution_error()); + assert!(get_pending_transactions(multisig_account) == vector[], 0); + } + + #[test(owner = @0x123)] + public entry fun test_create_with_single_owner(owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_addr); + assert_multisig_account_exists(multisig_account); + assert!(owners(multisig_account) == vector[owner_addr], 0); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_create_with_as_many_sigs_required_as_num_owners( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[address_of(owner_2), address_of(owner_3)], 3, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + assert_multisig_account_exists(multisig_account); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_create_with_zero_signatures_required_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 0, vector[], vector[]); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_create_with_too_many_signatures_required_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 2, vector[], vector[]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_create_with_duplicate_owners_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner_1)); + create_with_owners( + owner_1, + vector[ + // Duplicate owner 2 addresses. + address_of(owner_2), + address_of(owner_3), + address_of(owner_2), + ], + 2, + vector[], + vector[]); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0xD000E, location = Self)] + public entry fun test_create_with_without_feature_flag_enabled_should_fail( + owner: &signer) acquires MultisigAccount { + create_account(address_of(owner)); + create(owner, 2, vector[], vector[]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_create_with_creator_in_additional_owners_list_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner_1)); + create_with_owners(owner_1, vector[ + // Duplicate owner 1 addresses. + address_of(owner_1), + address_of(owner_2), + address_of(owner_3), + ], 2, + vector[], + vector[], + ); + } + + #[test] + public entry fun test_create_multisig_account_on_top_of_existing_multi_ed25519_account() + acquires MultisigAccount { + setup(); + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pk_unvalidated); + let multisig_address = from_bcs::to_address(auth_key); + create_account(multisig_address); + + let expected_owners = vector[@0x123, @0x124, @0x125]; + let proof = MultisigAccountCreationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners: expected_owners, + num_signatures_required: 2, + }; + let signed_proof = multi_ed25519::sign_struct(&curr_sk, proof); + create_with_existing_account( + multisig_address, + expected_owners, + 2, + 1, // MULTI_ED25519_SCHEME + multi_ed25519::unvalidated_public_key_to_bytes(&pk_unvalidated), + multi_ed25519::signature_to_bytes(&signed_proof), + vector[], + vector[], + ); + assert_multisig_account_exists(multisig_address); + assert!(owners(multisig_address) == expected_owners, 0); + } + + #[test] + public entry fun test_create_multisig_account_on_top_of_existing_multi_ed25519_account_and_revoke_auth_key() + acquires MultisigAccount { + setup(); + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pk_unvalidated); + let multisig_address = from_bcs::to_address(auth_key); + create_account(multisig_address); + + // Create both a signer capability and rotation capability offers + account::set_rotation_capability_offer(multisig_address, @0x123); + account::set_signer_capability_offer(multisig_address, @0x123); + + let expected_owners = vector[@0x123, @0x124, @0x125]; + let proof = MultisigAccountCreationWithAuthKeyRevocationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners: expected_owners, + num_signatures_required: 2, + }; + let signed_proof = multi_ed25519::sign_struct(&curr_sk, proof); + create_with_existing_account_and_revoke_auth_key( + multisig_address, + expected_owners, + 2, + 1, // MULTI_ED25519_SCHEME + multi_ed25519::unvalidated_public_key_to_bytes(&pk_unvalidated), + multi_ed25519::signature_to_bytes(&signed_proof), + vector[], + vector[], + ); + assert_multisig_account_exists(multisig_address); + assert!(owners(multisig_address) == expected_owners, 0); + assert!(account::get_authentication_key(multisig_address) == ZERO_AUTH_KEY, 1); + // Verify that all capability offers have been wiped. + assert!(!account::is_rotation_capability_offered(multisig_address), 2); + assert!(!account::is_signer_capability_offered(multisig_address), 3); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_update_signatures_required( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[address_of(owner_2), address_of(owner_3)], 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + assert!(num_signatures_required(multisig_account) == 1, 0); + update_signatures_required(&create_signer(multisig_account), 2); + assert!(num_signatures_required(multisig_account) == 2, 1); + // As many signatures required as number of owners (3). + update_signatures_required(&create_signer(multisig_account), 3); + assert!(num_signatures_required(multisig_account) == 3, 2); + } + + #[test(owner = @0x123)] + public entry fun test_update_metadata(owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_addr); + update_metadata( + &create_signer(multisig_account), + vector[utf8(b"key1"), utf8(b"key2")], + vector[vector[1], vector[2]], + ); + let updated_metadata = metadata(multisig_account); + assert!(simple_map::length(&updated_metadata) == 2, 0); + assert!(simple_map::borrow(&updated_metadata, &utf8(b"key1")) == &vector[1], 0); + assert!(simple_map::borrow(&updated_metadata, &utf8(b"key2")) == &vector[2], 0); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_update_with_zero_signatures_required_should_fail( + owner:& signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + update_signatures_required(&create_signer(multisig_account), 0); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_update_with_too_many_signatures_required_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + update_signatures_required(&create_signer(multisig_account), 2); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_add_owners( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner_1)); + create(owner_1, 1, vector[], vector[]); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + let multisig_signer = &create_signer(multisig_account); + assert!(owners(multisig_account) == vector[owner_1_addr], 0); + // Adding an empty vector of new owners should be no-op. + add_owners(multisig_signer, vector[]); + assert!(owners(multisig_account) == vector[owner_1_addr], 1); + add_owners(multisig_signer, vector[owner_2_addr, owner_3_addr]); + assert!(owners(multisig_account) == vector[owner_1_addr, owner_2_addr, owner_3_addr], 2); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_remove_owners( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + let multisig_signer = &create_signer(multisig_account); + assert!(owners(multisig_account) == vector[owner_2_addr, owner_3_addr, owner_1_addr], 0); + // Removing an empty vector of owners should be no-op. + remove_owners(multisig_signer, vector[]); + assert!(owners(multisig_account) == vector[owner_2_addr, owner_3_addr, owner_1_addr], 1); + remove_owners(multisig_signer, vector[owner_2_addr]); + assert!(owners(multisig_account) == vector[owner_1_addr, owner_3_addr], 2); + // Removing owners that don't exist should be no-op. + remove_owners(multisig_signer, vector[@0x130]); + assert!(owners(multisig_account) == vector[owner_1_addr, owner_3_addr], 3); + // Removing with duplicate owners should still work. + remove_owners(multisig_signer, vector[owner_3_addr, owner_3_addr, owner_3_addr]); + assert!(owners(multisig_account) == vector[owner_1_addr], 4); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_remove_all_owners_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + assert!(owners(multisig_account) == vector[owner_2_addr, owner_3_addr, owner_1_addr], 0); + let multisig_signer = &create_signer(multisig_account); + remove_owners(multisig_signer, vector[owner_1_addr, owner_2_addr, owner_3_addr]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_remove_owners_with_fewer_remaining_than_signature_threshold_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + let multisig_signer = &create_signer(multisig_account); + // Remove 2 owners so there's one left, which is less than the signature threshold of 2. + remove_owners(multisig_signer, vector[owner_2_addr, owner_3_addr]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_create_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + let transaction = get_transaction(multisig_account, 1); + assert!(transaction.creator == owner_1_addr, 0); + assert!(option::is_some(&transaction.payload), 1); + assert!(option::is_none(&transaction.payload_hash), 2); + let payload = option::extract(&mut transaction.payload); + assert!(payload == PAYLOAD, 4); + // Automatic yes vote from creator. + assert!(simple_map::length(&transaction.votes) == 1, 5); + assert!(*simple_map::borrow(&transaction.votes, &owner_1_addr), 5); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public entry fun test_create_transaction_with_empty_payload_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction(owner, multisig_account, vector[]); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_create_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction(non_owner, multisig_account, PAYLOAD); + } + + #[test(owner = @0x123)] + public entry fun test_create_transaction_with_hashes( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction_with_hash(owner, multisig_account, sha3_256(PAYLOAD)); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000C, location = Self)] + public entry fun test_create_transaction_with_empty_hash_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction_with_hash(owner, multisig_account, vector[]); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_create_transaction_with_hashes_and_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner,1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction_with_hash(non_owner, multisig_account, sha3_256(PAYLOAD)); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_approve_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + approve_transaction(owner_2, multisig_account, 1); + approve_transaction(owner_3, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(simple_map::length(&transaction.votes) == 3, 0); + assert!(*simple_map::borrow(&transaction.votes, &owner_1_addr), 1); + assert!(*simple_map::borrow(&transaction.votes, &owner_2_addr), 2); + assert!(*simple_map::borrow(&transaction.votes, &owner_3_addr), 3); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_validate_transaction_should_not_consider_removed_owners( + owner_1: &signer, owner_2: &signer, owner_3:& signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + // Owner 1 and 2 approved but then owner 1 got removed. + create_transaction(owner_1, multisig_account, PAYLOAD); + approve_transaction(owner_2, multisig_account, 1); + // Before owner 1 is removed, the transaction technically has sufficient approvals. + assert!(can_be_executed(multisig_account, 1), 0); + let multisig_signer = &create_signer(multisig_account); + remove_owners(multisig_signer, vector[owner_1_addr]); + // Now that owner 1 is removed, their approval should be invalidated and the transaction no longer + // has enough approvals to be executed. + assert!(!can_be_executed(multisig_account, 1), 1); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x607D6, location = Self)] + public entry fun test_approve_transaction_with_invalid_sequence_number_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + approve_transaction(owner, multisig_account, 2); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_approve_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + approve_transaction(non_owner, multisig_account, 1); + } + + #[test(owner = @0x123)] + public entry fun test_approval_transaction_after_rejecting( + owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + let multisig_account = get_next_multisig_account_address(owner_addr); + create(owner, 1, vector[], vector[]); + + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + approve_transaction(owner, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(*simple_map::borrow(&transaction.votes, &owner_addr), 1); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_reject_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + reject_transaction(owner_1, multisig_account, 1); + reject_transaction(owner_2, multisig_account, 1); + reject_transaction(owner_3, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(simple_map::length(&transaction.votes) == 3, 0); + assert!(!*simple_map::borrow(&transaction.votes, &owner_1_addr), 1); + assert!(!*simple_map::borrow(&transaction.votes, &owner_2_addr), 2); + assert!(!*simple_map::borrow(&transaction.votes, &owner_3_addr), 3); + } + + #[test(owner = @0x123)] + public entry fun test_reject_transaction_after_approving( + owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + let multisig_account = get_next_multisig_account_address(owner_addr); + create(owner, 1, vector[], vector[]); + + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(!*simple_map::borrow(&transaction.votes, &owner_addr), 1); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x607D6, location = Self)] + public entry fun test_reject_transaction_with_invalid_sequence_number_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 2); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_reject_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + reject_transaction(non_owner, multisig_account, 1); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_transaction_successful( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + // Owner 1 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_2, multisig_account, 1); + assert!(can_be_executed(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + successful_transaction_execution_cleanup(owner_3_addr, multisig_account,vector[]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_transaction_failed( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + // Owner 1 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_2, multisig_account, 1); + assert!(can_be_executed(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + failed_transaction_execution_cleanup(owner_3_addr, multisig_account,vector[], execution_error()); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_transaction_with_full_payload( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction_with_hash(owner_3, multisig_account, sha3_256(PAYLOAD)); + // Owner 3 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_1, multisig_account, 1); + assert!(can_be_executed(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + successful_transaction_execution_cleanup(owner_3_addr, multisig_account, PAYLOAD); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_rejected_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + reject_transaction(owner_2, multisig_account, 1); + reject_transaction(owner_3, multisig_account, 1); + assert!(can_be_rejected(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + execute_rejected_transaction(owner_3, multisig_account); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_execute_rejected_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner,1, vector[], vector[]); + + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + execute_rejected_transaction(non_owner, multisig_account); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x3000A, location = Self)] + public entry fun test_execute_rejected_transaction_without_sufficient_rejections_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + reject_transaction(owner_2, multisig_account, 1); + execute_rejected_transaction(owner_3, multisig_account); + } + + #[test( + owner_1 = @0x123, + owner_2 = @0x124, + owner_3 = @0x125 + )] + #[expected_failure(abort_code = 0x10012, location = Self)] + fun test_update_owner_schema_overlap_should_fail( + owner_1: &signer, + owner_2: &signer, + owner_3: &signer + ) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_address = get_next_multisig_account_address(owner_1_addr); + create_with_owners( + owner_1, + vector[owner_2_addr, owner_3_addr], + 2, + vector[], + vector[] + ); + update_owner_schema( + multisig_address, + vector[owner_1_addr], + vector[owner_1_addr], + option::none() + ); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/object.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/object.move new file mode 100644 index 0000000..a3d7b86 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/object.move @@ -0,0 +1,807 @@ +/// This defines the Move object model with the the following properties: +/// - Simplified storage interface that supports a heterogeneous collection of resources to be +/// stored together. This enables data types to share a common core data layer (e.g., tokens), +/// while having richer extensions (e.g., concert ticket, sword). +/// - Globally accessible data and ownership model that enables creators and developers to dictate +/// the application and lifetime of data. +/// - Extensible programming model that supports individualization of user applications that +/// leverage the core framework including tokens. +/// - Support emitting events directly, thus improving discoverability of events associated with +/// objects. +/// - Considerate of the underlying system by leveraging resource groups for gas efficiency, +/// avoiding costly deserialization and serialization costs, and supporting deletability. +/// +/// TODO: +/// * There is no means to borrow an object or a reference to an object. We are exploring how to +/// make it so that a reference to a global object can be returned from a function. +module aptos_framework::object { + use std::bcs; + use std::error; + use std::hash; + use std::signer; + use std::vector; + + use aptos_std::from_bcs; + + use aptos_framework::account; + use aptos_framework::transaction_context; + use aptos_framework::create_signer::create_signer; + use aptos_framework::event; + use aptos_framework::guid; + + friend aptos_framework::primary_fungible_store; + + /// An object already exists at this address + const EOBJECT_EXISTS: u64 = 1; + /// An object does not exist at this address + const EOBJECT_DOES_NOT_EXIST: u64 = 2; + /// The object does not have ungated transfers enabled + const ENO_UNGATED_TRANSFERS: u64 = 3; + /// The caller does not have ownership permissions + const ENOT_OBJECT_OWNER: u64 = 4; + /// The object does not allow for deletion + const ECANNOT_DELETE: u64 = 5; + /// Exceeds maximum nesting for an object transfer. + const EMAXIMUM_NESTING: u64 = 6; + /// The resource is not stored at the specified address. + const ERESOURCE_DOES_NOT_EXIST: u64 = 7; + /// Cannot reclaim objects that weren't burnt. + const EOBJECT_NOT_BURNT: u64 = 8; + + /// Explicitly separate the GUID space between Object and Account to prevent accidental overlap. + const INIT_GUID_CREATION_NUM: u64 = 0x4000000000000; + + /// Maximum nesting from one object to another. That is objects can technically have infinte + /// nesting, but any checks such as transfer will only be evaluated this deep. + const MAXIMUM_OBJECT_NESTING: u8 = 8; + + /// generate_unique_address uses this for domain separation within its native implementation + const DERIVE_AUID_ADDRESS_SCHEME: u8 = 0xFB; + + /// Scheme identifier used to generate an object's address `obj_addr` as derived from another object. + /// The object's address is generated as: + /// ``` + /// obj_addr = sha3_256(account addr | derived from object's address | 0xFC) + /// ``` + /// + /// This 0xFC constant serves as a domain separation tag to prevent existing authentication key and resource account + /// derivation to produce an object address. + const OBJECT_DERIVED_SCHEME: u8 = 0xFC; + + /// Scheme identifier used to generate an object's address `obj_addr` via a fresh GUID generated by the creator at + /// `source_addr`. The object's address is generated as: + /// ``` + /// obj_addr = sha3_256(guid | 0xFD) + /// ``` + /// where `guid = account::create_guid(create_signer(source_addr))` + /// + /// This 0xFD constant serves as a domain separation tag to prevent existing authentication key and resource account + /// derivation to produce an object address. + const OBJECT_FROM_GUID_ADDRESS_SCHEME: u8 = 0xFD; + + /// Scheme identifier used to generate an object's address `obj_addr` from the creator's `source_addr` and a `seed` as: + /// obj_addr = sha3_256(source_addr | seed | 0xFE). + /// + /// This 0xFE constant serves as a domain separation tag to prevent existing authentication key and resource account + /// derivation to produce an object address. + const OBJECT_FROM_SEED_ADDRESS_SCHEME: u8 = 0xFE; + + /// Address where unwanted objects can be forcefully transferred to. + const BURN_ADDRESS: address = @0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The core of the object model that defines ownership, transferability, and events. + struct ObjectCore has key { + /// Used by guid to guarantee globally unique objects and create event streams + guid_creation_num: u64, + /// The address (object or account) that owns this object + owner: address, + /// Object transferring is a common operation, this allows for disabling and enabling + /// transfers bypassing the use of a TransferRef. + allow_ungated_transfer: bool, + /// Emitted events upon transferring of ownership. + transfer_events: event::EventHandle, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// This is added to objects that are burnt (ownership transferred to BURN_ADDRESS). + struct TombStone has key { + /// Track the previous owner before the object is burnt so they can reclaim later if so desired. + original_owner: address, + } + + #[resource_group(scope = global)] + /// A shared resource group for storing object resources together in storage. + struct ObjectGroup {} + + /// A pointer to an object -- these can only provide guarantees based upon the underlying data + /// type, that is the validity of T existing at an address is something that cannot be verified + /// by any other module than the module that defined T. Similarly, the module that defines T + /// can remove it from storage at any point in time. + struct Object has copy, drop, store { + inner: address, + } + + /// This is a one time ability given to the creator to configure the object as necessary + struct ConstructorRef has drop { + self: address, + /// True if the object can be deleted. Named objects are not deletable. + can_delete: bool, + } + + /// Used to remove an object from storage. + struct DeleteRef has drop, store { + self: address, + } + + /// Used to create events or move additional resources into object storage. + struct ExtendRef has drop, store { + self: address, + } + + /// Used to create LinearTransferRef, hence ownership transfer. + struct TransferRef has drop, store { + self: address, + } + + /// Used to perform transfers. This locks transferring ability to a single time use bound to + /// the current owner. + struct LinearTransferRef has drop { + self: address, + owner: address, + } + + /// Used to create derived objects from a given objects. + struct DeriveRef has drop, store { + self: address, + } + + /// Emitted whenever the object's owner field is changed. + struct TransferEvent has drop, store { + object: address, + from: address, + to: address, + } + + #[view] + public fun is_burnt(object: Object): bool { + exists(object.inner) + } + + /// Produces an ObjectId from the given address. This is not verified. + public fun address_to_object(object: address): Object { + assert!(exists(object), error::not_found(EOBJECT_DOES_NOT_EXIST)); + assert!(exists_at(object), error::not_found(ERESOURCE_DOES_NOT_EXIST)); + Object { inner: object } + } + + /// Returns true if there exists an object or the remnants of an object. + public fun is_object(object: address): bool { + exists(object) + } + + /// Derives an object address from source material: sha3_256([creator address | seed | 0xFE]). + public fun create_object_address(source: &address, seed: vector): address { + let bytes = bcs::to_bytes(source); + vector::append(&mut bytes, seed); + vector::push_back(&mut bytes, OBJECT_FROM_SEED_ADDRESS_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + + /// Derives an object address from the source address and an object: sha3_256([source | object addr | 0xFC]). + public fun create_user_derived_object_address(source: address, derive_from: address): address { + let bytes = bcs::to_bytes(&source); + vector::append(&mut bytes, bcs::to_bytes(&derive_from)); + vector::push_back(&mut bytes, OBJECT_DERIVED_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + + /// Derives an object from an Account GUID. + public fun create_guid_object_address(source: address, creation_num: u64): address { + let id = guid::create_id(source, creation_num); + let bytes = bcs::to_bytes(&id); + vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + + native fun exists_at(object: address): bool; + + /// Returns the address of within an ObjectId. + public fun object_address(object: &Object): address { + object.inner + } + + /// Convert Object to Object. + public fun convert(object: Object): Object { + address_to_object(object.inner) + } + + /// Create a new named object and return the ConstructorRef. Named objects can be queried globally + /// by knowing the user generated seed used to create them. Named objects cannot be deleted. + public fun create_named_object(creator: &signer, seed: vector): ConstructorRef { + let creator_address = signer::address_of(creator); + let obj_addr = create_object_address(&creator_address, seed); + create_object_internal(creator_address, obj_addr, false) + } + + /// Create a new object whose address is derived based on the creator account address and another object. + /// Derivde objects, similar to named objects, cannot be deleted. + public(friend) fun create_user_derived_object(creator_address: address, derive_ref: &DeriveRef): ConstructorRef { + let obj_addr = create_user_derived_object_address(creator_address, derive_ref.self); + create_object_internal(creator_address, obj_addr, false) + } + + /// Create a new object by generating a random unique address based on transaction hash. + /// The unique address is computed sha3_256([transaction hash | auid counter | 0xFB]). + /// The created object is deletable as we can guarantee the same unique address can + /// never be regenerated with future txs. + public fun create_object(owner_address: address): ConstructorRef { + let unique_address = transaction_context::generate_auid_address(); + create_object_internal(owner_address, unique_address, true) + } + + /// Same as `create_object` except the object to be created will be undeletable. + public fun create_sticky_object(owner_address: address): ConstructorRef { + let unique_address = transaction_context::generate_auid_address(); + create_object_internal(owner_address, unique_address, false) + } + + #[deprecated] + /// Use `create_object` instead. + /// Create a new object from a GUID generated by an account. + /// As the GUID creation internally increments a counter, two transactions that executes + /// `create_object_from_account` function for the same creator run sequentially. + /// Therefore, using `create_object` method for creating objects is preferrable as it + /// doesn't have the same bottlenecks. + public fun create_object_from_account(creator: &signer): ConstructorRef { + let guid = account::create_guid(creator); + create_object_from_guid(signer::address_of(creator), guid) + } + + #[deprecated] + /// Use `create_object` instead. + /// Create a new object from a GUID generated by an object. + /// As the GUID creation internally increments a counter, two transactions that executes + /// `create_object_from_object` function for the same creator run sequentially. + /// Therefore, using `create_object` method for creating objects is preferrable as it + /// doesn't have the same bottlenecks. + public fun create_object_from_object(creator: &signer): ConstructorRef acquires ObjectCore { + let guid = create_guid(creator); + create_object_from_guid(signer::address_of(creator), guid) + } + + fun create_object_from_guid(creator_address: address, guid: guid::GUID): ConstructorRef { + let bytes = bcs::to_bytes(&guid); + vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME); + let obj_addr = from_bcs::to_address(hash::sha3_256(bytes)); + create_object_internal(creator_address, obj_addr, true) + } + + fun create_object_internal( + creator_address: address, + object: address, + can_delete: bool, + ): ConstructorRef { + assert!(!exists(object), error::already_exists(EOBJECT_EXISTS)); + + let object_signer = create_signer(object); + let guid_creation_num = INIT_GUID_CREATION_NUM; + let transfer_events_guid = guid::create(object, &mut guid_creation_num); + + move_to( + &object_signer, + ObjectCore { + guid_creation_num, + owner: creator_address, + allow_ungated_transfer: true, + transfer_events: event::new_event_handle(transfer_events_guid), + }, + ); + ConstructorRef { self: object, can_delete } + } + + // Creation helpers + + /// Generates the DeleteRef, which can be used to remove ObjectCore from global storage. + public fun generate_delete_ref(ref: &ConstructorRef): DeleteRef { + assert!(ref.can_delete, error::permission_denied(ECANNOT_DELETE)); + DeleteRef { self: ref.self } + } + + /// Generates the ExtendRef, which can be used to add new events and resources to the object. + public fun generate_extend_ref(ref: &ConstructorRef): ExtendRef { + ExtendRef { self: ref.self } + } + + /// Generates the TransferRef, which can be used to manage object transfers. + public fun generate_transfer_ref(ref: &ConstructorRef): TransferRef { + TransferRef { self: ref.self } + } + + /// Generates the DeriveRef, which can be used to create determnistic derived objects from the current object. + public fun generate_derive_ref(ref: &ConstructorRef): DeriveRef { + DeriveRef { self: ref.self } + } + + /// Create a signer for the ConstructorRef + public fun generate_signer(ref: &ConstructorRef): signer { + create_signer(ref.self) + } + + /// Returns the address associated with the constructor + public fun address_from_constructor_ref(ref: &ConstructorRef): address { + ref.self + } + + /// Returns an Object from within a ConstructorRef + public fun object_from_constructor_ref(ref: &ConstructorRef): Object { + address_to_object(ref.self) + } + + /// Returns whether or not the ConstructorRef can be used to create DeleteRef + public fun can_generate_delete_ref(ref: &ConstructorRef): bool { + ref.can_delete + } + + // Signer required functions + + /// Create a guid for the object, typically used for events + public fun create_guid(object: &signer): guid::GUID acquires ObjectCore { + let addr = signer::address_of(object); + let object_data = borrow_global_mut(addr); + guid::create(addr, &mut object_data.guid_creation_num) + } + + /// Generate a new event handle. + public fun new_event_handle( + object: &signer, + ): event::EventHandle acquires ObjectCore { + event::new_event_handle(create_guid(object)) + } + + // Deletion helpers + + /// Returns the address associated with the constructor + public fun address_from_delete_ref(ref: &DeleteRef): address { + ref.self + } + + /// Returns an Object from within a DeleteRef. + public fun object_from_delete_ref(ref: &DeleteRef): Object { + address_to_object(ref.self) + } + + /// Removes from the specified Object from global storage. + public fun delete(ref: DeleteRef) acquires ObjectCore { + let object_core = move_from(ref.self); + let ObjectCore { + guid_creation_num: _, + owner: _, + allow_ungated_transfer: _, + transfer_events, + } = object_core; + event::destroy_handle(transfer_events); + } + + // Extension helpers + + /// Create a signer for the ExtendRef + public fun generate_signer_for_extending(ref: &ExtendRef): signer { + create_signer(ref.self) + } + + /// Returns an address from within a ExtendRef. + public fun address_from_extend_ref(ref: &ExtendRef): address { + ref.self + } + + // Transfer functionality + + /// Disable direct transfer, transfers can only be triggered via a TransferRef + public fun disable_ungated_transfer(ref: &TransferRef) acquires ObjectCore { + let object = borrow_global_mut(ref.self); + object.allow_ungated_transfer = false; + } + + /// Enable direct transfer. + public fun enable_ungated_transfer(ref: &TransferRef) acquires ObjectCore { + let object = borrow_global_mut(ref.self); + object.allow_ungated_transfer = true; + } + + /// Create a LinearTransferRef for a one-time transfer. This requires that the owner at the + /// time of generation is the owner at the time of transferring. + public fun generate_linear_transfer_ref(ref: &TransferRef): LinearTransferRef acquires ObjectCore { + let owner = owner(Object { inner: ref.self }); + LinearTransferRef { + self: ref.self, + owner, + } + } + + /// Transfer to the destination address using a LinearTransferRef. + public fun transfer_with_ref(ref: LinearTransferRef, to: address) acquires ObjectCore { + let object = borrow_global_mut(ref.self); + assert!( + object.owner == ref.owner, + error::permission_denied(ENOT_OBJECT_OWNER), + ); + event::emit_event( + &mut object.transfer_events, + TransferEvent { + object: ref.self, + from: object.owner, + to, + }, + ); + object.owner = to; + } + + /// Entry function that can be used to transfer, if allow_ungated_transfer is set true. + public entry fun transfer_call( + owner: &signer, + object: address, + to: address, + ) acquires ObjectCore { + transfer_raw(owner, object, to) + } + + /// Transfers ownership of the object (and all associated resources) at the specified address + /// for Object to the "to" address. + public entry fun transfer( + owner: &signer, + object: Object, + to: address, + ) acquires ObjectCore { + transfer_raw(owner, object.inner, to) + } + + /// Attempts to transfer using addresses only. Transfers the given object if + /// allow_ungated_transfer is set true. Note, that this allows the owner of a nested object to + /// transfer that object, so long as allow_ungated_transfer is enabled at each stage in the + /// hierarchy. + public fun transfer_raw( + owner: &signer, + object: address, + to: address, + ) acquires ObjectCore { + let owner_address = signer::address_of(owner); + verify_ungated_and_descendant(owner_address, object); + + let object_core = borrow_global_mut(object); + if (object_core.owner == to) { + return + }; + + event::emit_event( + &mut object_core.transfer_events, + TransferEvent { + object: object, + from: object_core.owner, + to, + }, + ); + object_core.owner = to; + } + + /// Transfer the given object to another object. See `transfer` for more information. + public entry fun transfer_to_object( + owner: &signer, + object: Object, + to: Object, + ) acquires ObjectCore { + transfer(owner, object, to.inner) + } + + /// This checks that the destination address is eventually owned by the owner and that each + /// object between the two allows for ungated transfers. Note, this is limited to a depth of 8 + /// objects may have cyclic dependencies. + fun verify_ungated_and_descendant(owner: address, destination: address) acquires ObjectCore { + let current_address = destination; + assert!( + exists(current_address), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + + let object = borrow_global(current_address); + assert!( + object.allow_ungated_transfer, + error::permission_denied(ENO_UNGATED_TRANSFERS), + ); + + let current_address = object.owner; + + let count = 0; + while (owner != current_address) { + let count = count + 1; + assert!(count < MAXIMUM_OBJECT_NESTING, error::out_of_range(EMAXIMUM_NESTING)); + + // At this point, the first object exists and so the more likely case is that the + // object's owner is not an object. So we return a more sensible error. + assert!( + exists(current_address), + error::permission_denied(ENOT_OBJECT_OWNER), + ); + let object = borrow_global(current_address); + assert!( + object.allow_ungated_transfer, + error::permission_denied(ENO_UNGATED_TRANSFERS), + ); + + current_address = object.owner; + }; + } + + /// Forcefully transfer an unwanted object to BURN_ADDRESS, ignoring whether ungated_transfer is allowed. + /// This only works for objects directly owned and for simplicity does not apply to indirectly owned objects. + /// Original owners can reclaim burnt objects any time in the future by calling unburn. + public entry fun burn(owner: &signer, object: Object) acquires ObjectCore { + let original_owner = signer::address_of(owner); + assert!(owner(object) == original_owner, error::permission_denied(ENOT_OBJECT_OWNER)); + let object_addr = object.inner; + move_to(&create_signer(object_addr), TombStone { original_owner }); + let object = borrow_global_mut(object_addr); + object.owner = BURN_ADDRESS; + + // Burn should still emit event to make sure ownership is upgrade correctly in indexing. + event::emit_event( + &mut object.transfer_events, + TransferEvent { + object: object_addr, + from: original_owner, + to: BURN_ADDRESS, + }, + ); + } + + /// Allow origin owners to reclaim any objects they previous burnt. + public entry fun unburn( + original_owner: &signer, + object: Object, + ) acquires ObjectCore, TombStone { + let object_addr = object.inner; + assert!(exists(object_addr), error::invalid_argument(EOBJECT_NOT_BURNT)); + + let TombStone { original_owner: original_owner_addr } = move_from(object_addr); + assert!(original_owner_addr == signer::address_of(original_owner), error::permission_denied(ENOT_OBJECT_OWNER)); + let object = borrow_global_mut(object_addr); + object.owner = original_owner_addr; + + // Unburn reclaims should still emit event to make sure ownership is upgrade correctly in indexing. + event::emit_event( + &mut object.transfer_events, + TransferEvent { + object: object_addr, + from: BURN_ADDRESS, + to: original_owner_addr, + }, + ); + } + + /// Accessors + /// Return true if ungated transfer is allowed. + public fun ungated_transfer_allowed(object: Object): bool acquires ObjectCore { + assert!( + exists(object.inner), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + borrow_global(object.inner).allow_ungated_transfer + } + + /// Return the current owner. + public fun owner(object: Object): address acquires ObjectCore { + assert!( + exists(object.inner), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + borrow_global(object.inner).owner + } + + /// Return true if the provided address is the current owner. + public fun is_owner(object: Object, owner: address): bool acquires ObjectCore { + owner(object) == owner + } + + /// Return true if the provided address has indirect or direct ownership of the provided object. + public fun owns(object: Object, owner: address): bool acquires ObjectCore { + let current_address = object_address(&object); + if (current_address == owner) { + return true + }; + + assert!( + exists(current_address), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + + let object = borrow_global(current_address); + let current_address = object.owner; + + let count = 0; + while (owner != current_address) { + let count = count + 1; + assert!(count < MAXIMUM_OBJECT_NESTING, error::out_of_range(EMAXIMUM_NESTING)); + if (!exists(current_address)) { + return false + }; + + let object = borrow_global(current_address); + current_address = object.owner; + }; + true + } + + #[test_only] + use std::option::{Self, Option}; + + #[test_only] + const EHERO_DOES_NOT_EXIST: u64 = 0x100; + #[test_only] + const EWEAPON_DOES_NOT_EXIST: u64 = 0x101; + + #[test_only] + struct HeroEquipEvent has drop, store { + weapon_id: Option>, + } + + #[test_only] + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct Hero has key { + equip_events: event::EventHandle, + weapon: Option>, + } + + #[test_only] + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct Weapon has key {} + + #[test_only] + public fun create_hero(creator: &signer): (ConstructorRef, Object) acquires ObjectCore { + let hero_constructor_ref = create_named_object(creator, b"hero"); + let hero_signer = generate_signer(&hero_constructor_ref); + let guid_for_equip_events = create_guid(&hero_signer); + move_to( + &hero_signer, + Hero { + weapon: option::none(), + equip_events: event::new_event_handle(guid_for_equip_events), + }, + ); + + let hero = object_from_constructor_ref(&hero_constructor_ref); + (hero_constructor_ref, hero) + } + + #[test_only] + public fun create_weapon(creator: &signer): (ConstructorRef, Object) { + let weapon_constructor_ref = create_named_object(creator, b"weapon"); + let weapon_signer = generate_signer(&weapon_constructor_ref); + move_to(&weapon_signer, Weapon {}); + let weapon = object_from_constructor_ref(&weapon_constructor_ref); + (weapon_constructor_ref, weapon) + } + + #[test_only] + public fun hero_equip( + owner: &signer, + hero: Object, + weapon: Object, + ) acquires Hero, ObjectCore { + transfer_to_object(owner, weapon, hero); + let hero_obj = borrow_global_mut(object_address(&hero)); + option::fill(&mut hero_obj.weapon, weapon); + event::emit_event( + &mut hero_obj.equip_events, + HeroEquipEvent { weapon_id: option::some(weapon) }, + ); + } + + #[test_only] + public fun hero_unequip( + owner: &signer, + hero: Object, + weapon: Object, + ) acquires Hero, ObjectCore { + transfer(owner, weapon, signer::address_of(owner)); + let hero = borrow_global_mut(object_address(&hero)); + option::extract(&mut hero.weapon); + event::emit_event( + &mut hero.equip_events, + HeroEquipEvent { weapon_id: option::none() }, + ); + } + + #[test(creator = @0x123)] + fun test_object(creator: &signer) acquires Hero, ObjectCore { + let (_, hero) = create_hero(creator); + let (_, weapon) = create_weapon(creator); + + assert!(owns(weapon, @0x123), 0); + hero_equip(creator, hero, weapon); + assert!(owns(weapon, @0x123), 1); + hero_unequip(creator, hero, weapon); + } + + #[test(creator = @0x123)] + fun test_linear_transfer(creator: &signer) acquires ObjectCore { + let (hero_constructor, hero) = create_hero(creator); + let transfer_ref = generate_transfer_ref(&hero_constructor); + let linear_transfer_ref = generate_linear_transfer_ref(&transfer_ref); + transfer_with_ref(linear_transfer_ref, @0x456); + assert!(owner(hero) == @0x456, 0); + assert!(owns(hero, @0x456), 1); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 0x50004, location = Self)] + fun test_bad_linear_transfer(creator: &signer) acquires ObjectCore { + let (hero_constructor, hero) = create_hero(creator); + let transfer_ref = generate_transfer_ref(&hero_constructor); + let linear_transfer_ref_good = generate_linear_transfer_ref(&transfer_ref); + // This will contain the address of the creator + let linear_transfer_ref_bad = generate_linear_transfer_ref(&transfer_ref); + transfer_with_ref(linear_transfer_ref_good, @0x456); + assert!(owner(hero) == @0x456, 0); + transfer_with_ref(linear_transfer_ref_bad, @0x789); + } + + #[test(fx = @std)] + fun test_correct_auid(fx: signer) { + use std::features; + let feature = features::get_auids(); + features::change_feature_flags(&fx, vector[feature], vector[]); + + let auid1 = aptos_framework::transaction_context::generate_auid_address(); + let bytes = aptos_framework::transaction_context::get_transaction_hash(); + std::vector::push_back(&mut bytes, 1); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, DERIVE_AUID_ADDRESS_SCHEME); + let auid2 = aptos_framework::from_bcs::to_address(std::hash::sha3_256(bytes)); + assert!(auid1 == auid2, 0); + } + + #[test(creator = @0x123)] + fun test_burn_and_unburn(creator: &signer) acquires ObjectCore, TombStone { + let (hero_constructor, hero) = create_hero(creator); + // Freeze the object. + let transfer_ref = generate_transfer_ref(&hero_constructor); + disable_ungated_transfer(&transfer_ref); + + // Owner should be able to burn, despite ungated transfer disallowed. + burn(creator, hero); + assert!(owner(hero) == BURN_ADDRESS, 0); + assert!(!ungated_transfer_allowed(hero), 0); + + // Owner should be able to reclaim. + unburn(creator, hero); + assert!(owner(hero) == signer::address_of(creator), 0); + // Object still frozen. + assert!(!ungated_transfer_allowed(hero), 0); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 0x50004, location = Self)] + fun test_burn_indirectly_owned_should_fail(creator: &signer) acquires ObjectCore { + let (_, hero) = create_hero(creator); + let (_, weapon) = create_weapon(creator); + transfer_to_object(creator, weapon, hero); + + // Owner should be not be able to burn weapon directly. + assert!(owner(weapon) == object_address(&hero), 0); + assert!(owns(weapon, signer::address_of(creator)), 0); + burn(creator, weapon); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 0x10008, location = Self)] + fun test_unburn_object_not_burnt_should_fail(creator: &signer) acquires ObjectCore, TombStone { + let (_, hero) = create_hero(creator); + unburn(creator, hero); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/optional_aggregator.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/optional_aggregator.move new file mode 100644 index 0000000..f3a5456 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/optional_aggregator.move @@ -0,0 +1,295 @@ +/// This module provides an interface to aggregate integers either via +/// aggregator (parallelizable) or via normal integers. +module aptos_framework::optional_aggregator { + use std::error; + use std::option::{Self, Option}; + + use aptos_framework::aggregator_factory; + use aptos_framework::aggregator::{Self, Aggregator}; + + friend aptos_framework::coin; + friend aptos_framework::fungible_asset; + + /// The value of aggregator underflows (goes below zero). Raised by native code. + const EAGGREGATOR_OVERFLOW: u64 = 1; + + /// Aggregator feature is not supported. Raised by native code. + const EAGGREGATOR_UNDERFLOW: u64 = 2; + + /// Wrapper around integer with a custom overflow limit. Supports add, subtract and read just like `Aggregator`. + struct Integer has store { + value: u128, + limit: u128, + } + + /// Creates a new integer which overflows on exceeding a `limit`. + fun new_integer(limit: u128): Integer { + Integer { + value: 0, + limit, + } + } + + /// Adds `value` to integer. Aborts on overflowing the limit. + fun add_integer(integer: &mut Integer, value: u128) { + assert!( + value <= (integer.limit - integer.value), + error::out_of_range(EAGGREGATOR_OVERFLOW) + ); + integer.value = integer.value + value; + } + + /// Subtracts `value` from integer. Aborts on going below zero. + fun sub_integer(integer: &mut Integer, value: u128) { + assert!(value <= integer.value, error::out_of_range(EAGGREGATOR_UNDERFLOW)); + integer.value = integer.value - value; + } + + /// Returns an overflow limit of integer. + fun limit(integer: &Integer): u128 { + integer.limit + } + + /// Returns a value stored in this integer. + fun read_integer(integer: &Integer): u128 { + integer.value + } + + /// Destroys an integer. + fun destroy_integer(integer: Integer) { + let Integer { value: _, limit: _ } = integer; + } + + /// Contains either an aggregator or a normal integer, both overflowing on limit. + struct OptionalAggregator has store { + // Parallelizable. + aggregator: Option, + // Non-parallelizable. + integer: Option, + } + + /// Creates a new optional aggregator. + public(friend) fun new(limit: u128, parallelizable: bool): OptionalAggregator { + if (parallelizable) { + OptionalAggregator { + aggregator: option::some(aggregator_factory::create_aggregator_internal(limit)), + integer: option::none(), + } + } else { + OptionalAggregator { + aggregator: option::none(), + integer: option::some(new_integer(limit)), + } + } + } + + /// Switches between parallelizable and non-parallelizable implementations. + public fun switch(optional_aggregator: &mut OptionalAggregator) { + let value = read(optional_aggregator); + switch_and_zero_out(optional_aggregator); + add(optional_aggregator, value); + } + + /// Switches between parallelizable and non-parallelizable implementations, setting + /// the value of the new optional aggregator to zero. + fun switch_and_zero_out(optional_aggregator: &mut OptionalAggregator) { + if (is_parallelizable(optional_aggregator)) { + switch_to_integer_and_zero_out(optional_aggregator); + } else { + switch_to_aggregator_and_zero_out(optional_aggregator); + } + } + + /// Switches from parallelizable to non-parallelizable implementation, zero-initializing + /// the value. + fun switch_to_integer_and_zero_out( + optional_aggregator: &mut OptionalAggregator + ): u128 { + let aggregator = option::extract(&mut optional_aggregator.aggregator); + let limit = aggregator::limit(&aggregator); + aggregator::destroy(aggregator); + let integer = new_integer(limit); + option::fill(&mut optional_aggregator.integer, integer); + limit + } + + /// Switches from non-parallelizable to parallelizable implementation, zero-initializing + /// the value. + fun switch_to_aggregator_and_zero_out( + optional_aggregator: &mut OptionalAggregator + ): u128 { + let integer = option::extract(&mut optional_aggregator.integer); + let limit = limit(&integer); + destroy_integer(integer); + let aggregator = aggregator_factory::create_aggregator_internal(limit); + option::fill(&mut optional_aggregator.aggregator, aggregator); + limit + } + + /// Destroys optional aggregator. + public fun destroy(optional_aggregator: OptionalAggregator) { + if (is_parallelizable(&optional_aggregator)) { + destroy_optional_aggregator(optional_aggregator); + } else { + destroy_optional_integer(optional_aggregator); + } + } + + /// Destroys parallelizable optional aggregator and returns its limit. + fun destroy_optional_aggregator(optional_aggregator: OptionalAggregator): u128 { + let OptionalAggregator { aggregator, integer } = optional_aggregator; + let limit = aggregator::limit(option::borrow(&aggregator)); + aggregator::destroy(option::destroy_some(aggregator)); + option::destroy_none(integer); + limit + } + + /// Destroys non-parallelizable optional aggregator and returns its limit. + fun destroy_optional_integer(optional_aggregator: OptionalAggregator): u128 { + let OptionalAggregator { aggregator, integer } = optional_aggregator; + let limit = limit(option::borrow(&integer)); + destroy_integer(option::destroy_some(integer)); + option::destroy_none(aggregator); + limit + } + + /// Adds `value` to optional aggregator, aborting on exceeding the `limit`. + public fun add(optional_aggregator: &mut OptionalAggregator, value: u128) { + if (option::is_some(&optional_aggregator.aggregator)) { + let aggregator = option::borrow_mut(&mut optional_aggregator.aggregator); + aggregator::add(aggregator, value); + } else { + let integer = option::borrow_mut(&mut optional_aggregator.integer); + add_integer(integer, value); + } + } + + /// Subtracts `value` from optional aggregator, aborting on going below zero. + public fun sub(optional_aggregator: &mut OptionalAggregator, value: u128) { + if (option::is_some(&optional_aggregator.aggregator)) { + let aggregator = option::borrow_mut(&mut optional_aggregator.aggregator); + aggregator::sub(aggregator, value); + } else { + let integer = option::borrow_mut(&mut optional_aggregator.integer); + sub_integer(integer, value); + } + } + + /// Returns the value stored in optional aggregator. + public fun read(optional_aggregator: &OptionalAggregator): u128 { + if (option::is_some(&optional_aggregator.aggregator)) { + let aggregator = option::borrow(&optional_aggregator.aggregator); + aggregator::read(aggregator) + } else { + let integer = option::borrow(&optional_aggregator.integer); + read_integer(integer) + } + } + + /// Returns true if optional aggregator uses parallelizable implementation. + public fun is_parallelizable(optional_aggregator: &OptionalAggregator): bool { + option::is_some(&optional_aggregator.aggregator) + } + + #[test(account = @aptos_framework)] + fun optional_aggregator_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + + let aggregator = new(30, false); + assert!(!is_parallelizable(&aggregator), 0); + + add(&mut aggregator, 12); + add(&mut aggregator, 3); + assert!(read(&aggregator) == 15, 0); + + sub(&mut aggregator, 10); + assert!(read(&aggregator) == 5, 0); + + // Switch to parallelizable aggregator and check the value is preserved. + switch(&mut aggregator); + assert!(is_parallelizable(&aggregator), 0); + assert!(read(&aggregator) == 5, 0); + + add(&mut aggregator, 12); + add(&mut aggregator, 3); + assert!(read(&aggregator) == 20, 0); + + sub(&mut aggregator, 10); + assert!(read(&aggregator) == 10, 0); + + // Switch back! + switch(&mut aggregator); + assert!(!is_parallelizable(&aggregator), 0); + assert!(read(&aggregator) == 10, 0); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + fun optional_aggregator_destroy_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + + let aggregator = new(30, false); + destroy(aggregator); + + let aggregator = new(30, true); + destroy(aggregator); + + let aggregator = new(12, false); + assert!(destroy_optional_integer(aggregator) == 12, 0); + + let aggregator = new(21, true); + assert!(destroy_optional_aggregator(aggregator) == 21, 0); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020001, location = Self)] + fun non_parallelizable_aggregator_overflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(15, false); + + // Overflow! + add(&mut aggregator, 16); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020002, location = Self)] + fun non_parallelizable_aggregator_underflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(100, false); + + // Underflow! + sub(&mut aggregator, 100); + add(&mut aggregator, 100); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020001, location = aptos_framework::aggregator)] + fun parallelizable_aggregator_overflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(15, true); + + // Overflow! + add(&mut aggregator, 16); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020002, location = aptos_framework::aggregator)] + fun parallelizable_aggregator_underflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(100, true); + + // Underflow! + add(&mut aggregator, 99); + sub(&mut aggregator, 100); + add(&mut aggregator, 100); + + destroy(aggregator); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/primary_fungible_store.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/primary_fungible_store.move new file mode 100644 index 0000000..689faf5 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/primary_fungible_store.move @@ -0,0 +1,322 @@ +/// This module provides a way for creators of fungible assets to enable support for creating primary (deterministic) +/// stores for their users. This is useful for assets that are meant to be used as a currency, as it allows users to +/// easily create a store for their account and deposit/withdraw/transfer fungible assets to/from it. +/// +/// The transfer flow works as below: +/// 1. The sender calls `transfer` on the fungible asset metadata object to transfer `amount` of fungible asset to +/// `recipient`. +/// 2. The fungible asset metadata object calls `ensure_primary_store_exists` to ensure that both the sender's and the +/// recipient's primary stores exist. If either doesn't, it will be created. +/// 3. The fungible asset metadata object calls `withdraw` on the sender's primary store to withdraw `amount` of +/// fungible asset from it. This emits an withdraw event. +/// 4. The fungible asset metadata object calls `deposit` on the recipient's primary store to deposit `amount` of +/// fungible asset to it. This emits an deposit event. +module aptos_framework::primary_fungible_store { + use aptos_framework::fungible_asset::{Self, FungibleAsset, FungibleStore, Metadata, MintRef, TransferRef, BurnRef}; + use aptos_framework::object::{Self, Object, ConstructorRef, DeriveRef}; + + use std::option::Option; + use std::signer; + use std::string::String; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// A resource that holds the derive ref for the fungible asset metadata object. This is used to create primary + /// stores for users with deterministic addresses so that users can easily deposit/withdraw/transfer fungible + /// assets. + struct DeriveRefPod has key { + metadata_derive_ref: DeriveRef, + } + + /// Create a fungible asset with primary store support. When users transfer fungible assets to each other, their + /// primary stores will be created automatically if they don't exist. Primary stores have deterministic addresses + /// so that users can easily deposit/withdraw/transfer fungible assets. + public fun create_primary_store_enabled_fungible_asset( + constructor_ref: &ConstructorRef, + maximum_supply: Option, + name: String, + symbol: String, + decimals: u8, + icon_uri: String, + project_uri: String, + ) { + fungible_asset::add_fungibility( + constructor_ref, + maximum_supply, + name, + symbol, + decimals, + icon_uri, + project_uri, + ); + let metadata_obj = &object::generate_signer(constructor_ref); + move_to(metadata_obj, DeriveRefPod { + metadata_derive_ref: object::generate_derive_ref(constructor_ref), + }); + } + + /// Ensure that the primary store object for the given address exists. If it doesn't, create it. + public fun ensure_primary_store_exists( + owner: address, + metadata: Object, + ): Object acquires DeriveRefPod { + if (!primary_store_exists(owner, metadata)) { + create_primary_store(owner, metadata) + } else { + primary_store(owner, metadata) + } + } + + /// Create a primary store object to hold fungible asset for the given address. + public fun create_primary_store( + owner_addr: address, + metadata: Object, + ): Object acquires DeriveRefPod { + let metadata_addr = object::object_address(&metadata); + object::address_to_object(metadata_addr); + let derive_ref = &borrow_global(metadata_addr).metadata_derive_ref; + let constructor_ref = &object::create_user_derived_object(owner_addr, derive_ref); + + // Disable ungated transfer as deterministic stores shouldn't be transferrable. + let transfer_ref = &object::generate_transfer_ref(constructor_ref); + object::disable_ungated_transfer(transfer_ref); + + fungible_asset::create_store(constructor_ref, metadata) + } + + #[view] + /// Get the address of the primary store for the given account. + public fun primary_store_address(owner: address, metadata: Object): address { + let metadata_addr = object::object_address(&metadata); + object::create_user_derived_object_address(owner, metadata_addr) + } + + #[view] + /// Get the primary store object for the given account. + public fun primary_store(owner: address, metadata: Object): Object { + let store = primary_store_address(owner, metadata); + object::address_to_object(store) + } + + #[view] + /// Return whether the given account's primary store exists. + public fun primary_store_exists(account: address, metadata: Object): bool { + fungible_asset::store_exists(primary_store_address(account, metadata)) + } + + #[view] + /// Get the balance of `account`'s primary store. + public fun balance(account: address, metadata: Object): u64 { + if (primary_store_exists(account, metadata)) { + fungible_asset::balance(primary_store(account, metadata)) + } else { + 0 + } + } + + #[view] + /// Return whether the given account's primary store is frozen. + public fun is_frozen(account: address, metadata: Object): bool { + if (primary_store_exists(account, metadata)) { + fungible_asset::is_frozen(primary_store(account, metadata)) + } else { + false + } + } + + /// Withdraw `amount` of fungible asset from the given account's primary store. + public fun withdraw(owner: &signer, metadata: Object, amount: u64): FungibleAsset { + let store = primary_store(signer::address_of(owner), metadata); + // Check if the store object has been burnt or not. If so, unburn it first. + may_be_unburn(owner, store); + fungible_asset::withdraw(owner, store, amount) + } + + /// Deposit fungible asset `fa` to the given account's primary store. + public fun deposit(owner: address, fa: FungibleAsset) acquires DeriveRefPod { + let metadata = fungible_asset::asset_metadata(&fa); + let store = ensure_primary_store_exists(owner, metadata); + fungible_asset::deposit(store, fa); + } + + /// Transfer `amount` of fungible asset from sender's primary store to receiver's primary store. + public entry fun transfer( + sender: &signer, + metadata: Object, + recipient: address, + amount: u64, + ) acquires DeriveRefPod { + let sender_store = ensure_primary_store_exists(signer::address_of(sender), metadata); + // Check if the sender store object has been burnt or not. If so, unburn it first. + may_be_unburn(sender, sender_store); + let recipient_store = ensure_primary_store_exists(recipient, metadata); + fungible_asset::transfer(sender, sender_store, recipient_store, amount); + } + + /// Mint to the primary store of `owner`. + public fun mint(mint_ref: &MintRef, owner: address, amount: u64) acquires DeriveRefPod { + let primary_store = ensure_primary_store_exists(owner, fungible_asset::mint_ref_metadata(mint_ref)); + fungible_asset::mint_to(mint_ref, primary_store, amount); + } + + /// Burn from the primary store of `owner`. + public fun burn(burn_ref: &BurnRef, owner: address, amount: u64) { + let primary_store = primary_store(owner, fungible_asset::burn_ref_metadata(burn_ref)); + fungible_asset::burn_from(burn_ref, primary_store, amount); + } + + /// Freeze/Unfreeze the primary store of `owner`. + public fun set_frozen_flag(transfer_ref: &TransferRef, owner: address, frozen: bool) acquires DeriveRefPod { + let primary_store = ensure_primary_store_exists(owner, fungible_asset::transfer_ref_metadata(transfer_ref)); + fungible_asset::set_frozen_flag(transfer_ref, primary_store, frozen); + } + + /// Withdraw from the primary store of `owner` ignoring frozen flag. + public fun withdraw_with_ref(transfer_ref: &TransferRef, owner: address, amount: u64): FungibleAsset { + let from_primary_store = primary_store(owner, fungible_asset::transfer_ref_metadata(transfer_ref)); + fungible_asset::withdraw_with_ref(transfer_ref, from_primary_store, amount) + } + + /// Deposit from the primary store of `owner` ignoring frozen flag. + public fun deposit_with_ref(transfer_ref: &TransferRef, owner: address, fa: FungibleAsset) acquires DeriveRefPod { + let from_primary_store = ensure_primary_store_exists( + owner, + fungible_asset::transfer_ref_metadata(transfer_ref) + ); + fungible_asset::deposit_with_ref(transfer_ref, from_primary_store, fa); + } + + /// Transfer `amount` of FA from the primary store of `from` to that of `to` ignoring frozen flag. + public fun transfer_with_ref( + transfer_ref: &TransferRef, + from: address, + to: address, + amount: u64 + ) acquires DeriveRefPod { + let from_primary_store = primary_store(from, fungible_asset::transfer_ref_metadata(transfer_ref)); + let to_primary_store = ensure_primary_store_exists(to, fungible_asset::transfer_ref_metadata(transfer_ref)); + fungible_asset::transfer_with_ref(transfer_ref, from_primary_store, to_primary_store, amount); + } + + fun may_be_unburn(owner: &signer, store: Object) { + if (object::is_burnt(store)) { + object::unburn(owner, store); + }; + } + + #[test_only] + use aptos_framework::fungible_asset::{create_test_token, generate_mint_ref, generate_burn_ref, generate_transfer_ref}; + #[test_only] + use std::string; + #[test_only] + use std::option; + + #[test_only] + public fun init_test_metadata_with_primary_store_enabled( + constructor_ref: &ConstructorRef + ): (MintRef, TransferRef, BurnRef) { + create_primary_store_enabled_fungible_asset( + constructor_ref, + option::some(100), // max supply + string::utf8(b"TEST COIN"), + string::utf8(b"@T"), + 0, + string::utf8(b"http://example.com/icon"), + string::utf8(b"http://example.com"), + ); + let mint_ref = generate_mint_ref(constructor_ref); + let burn_ref = generate_burn_ref(constructor_ref); + let transfer_ref = generate_transfer_ref(constructor_ref); + (mint_ref, transfer_ref, burn_ref) + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_default_behavior(creator: &signer, aaron: &signer) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(creator); + init_test_metadata_with_primary_store_enabled(&creator_ref); + let creator_address = signer::address_of(creator); + let aaron_address = signer::address_of(aaron); + assert!(!primary_store_exists(creator_address, metadata), 1); + assert!(!primary_store_exists(aaron_address, metadata), 2); + assert!(balance(creator_address, metadata) == 0, 3); + assert!(balance(aaron_address, metadata) == 0, 4); + assert!(!is_frozen(creator_address, metadata), 5); + assert!(!is_frozen(aaron_address, metadata), 6); + ensure_primary_store_exists(creator_address, metadata); + ensure_primary_store_exists(aaron_address, metadata); + assert!(primary_store_exists(creator_address, metadata), 7); + assert!(primary_store_exists(aaron_address, metadata), 8); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_basic_flow( + creator: &signer, + aaron: &signer, + ) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(creator); + let (mint_ref, transfer_ref, burn_ref) = init_test_metadata_with_primary_store_enabled(&creator_ref); + let creator_address = signer::address_of(creator); + let aaron_address = signer::address_of(aaron); + assert!(balance(creator_address, metadata) == 0, 1); + assert!(balance(aaron_address, metadata) == 0, 2); + mint(&mint_ref, creator_address, 100); + transfer(creator, metadata, aaron_address, 80); + let fa = withdraw(aaron, metadata, 10); + deposit(creator_address, fa); + assert!(balance(creator_address, metadata) == 30, 3); + assert!(balance(aaron_address, metadata) == 70, 4); + set_frozen_flag(&transfer_ref, aaron_address, true); + assert!(is_frozen(aaron_address, metadata), 5); + let fa = withdraw_with_ref(&transfer_ref, aaron_address, 30); + deposit_with_ref(&transfer_ref, aaron_address, fa); + transfer_with_ref(&transfer_ref, aaron_address, creator_address, 20); + set_frozen_flag(&transfer_ref, aaron_address, false); + assert!(!is_frozen(aaron_address, metadata), 6); + burn(&burn_ref, aaron_address, 50); + assert!(balance(aaron_address, metadata) == 0, 7); + } + + #[test(user_1 = @0xcafe, user_2 = @0xface)] + fun test_transfer_to_burnt_store( + user_1: &signer, + user_2: &signer, + ) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(user_1); + let (mint_ref, _, _) = init_test_metadata_with_primary_store_enabled(&creator_ref); + let user_1_address = signer::address_of(user_1); + let user_2_address = signer::address_of(user_2); + mint(&mint_ref, user_1_address, 100); + transfer(user_1, metadata, user_2_address, 80); + + // User 2 burns their primary store but should still be able to transfer afterward. + let user_2_primary_store = primary_store(user_2_address, metadata); + object::burn(user_2, user_2_primary_store); + assert!(object::is_burnt(user_2_primary_store), 0); + // Balance still works + assert!(balance(user_2_address, metadata) == 80, 0); + // Deposit still works + transfer(user_1, metadata, user_2_address, 20); + transfer(user_2, metadata, user_1_address, 90); + assert!(balance(user_2_address, metadata) == 10, 0); + } + + #[test(user_1 = @0xcafe, user_2 = @0xface)] + fun test_withdraw_from_burnt_store( + user_1: &signer, + user_2: &signer, + ) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(user_1); + let (mint_ref, _, _) = init_test_metadata_with_primary_store_enabled(&creator_ref); + let user_1_address = signer::address_of(user_1); + let user_2_address = signer::address_of(user_2); + mint(&mint_ref, user_1_address, 100); + transfer(user_1, metadata, user_2_address, 80); + + // User 2 burns their primary store but should still be able to withdraw afterward. + let user_2_primary_store = primary_store(user_2_address, metadata); + object::burn(user_2, user_2_primary_store); + assert!(object::is_burnt(user_2_primary_store), 0); + let coins = withdraw(user_2, metadata, 70); + assert!(balance(user_2_address, metadata) == 10, 0); + deposit(user_2_address, coins); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/reconfiguration.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/reconfiguration.move new file mode 100644 index 0000000..deec036 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/reconfiguration.move @@ -0,0 +1,208 @@ +/// Publishes configuration information for validators, and issues reconfiguration events +/// to synchronize configuration changes for the validators. +module aptos_framework::reconfiguration { + use std::error; + use std::features; + use std::signer; + + use aptos_framework::account; + use aptos_framework::event; + use aptos_framework::stake; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use aptos_framework::chain_status; + use aptos_framework::storage_gas; + use aptos_framework::transaction_fee; + + friend aptos_framework::aptos_governance; + friend aptos_framework::block; + friend aptos_framework::consensus_config; + friend aptos_framework::execution_config; + friend aptos_framework::gas_schedule; + friend aptos_framework::genesis; + friend aptos_framework::version; + + /// Event that signals consensus to start a new epoch, + /// with new configuration information. This is also called a + /// "reconfiguration event" + struct NewEpochEvent has drop, store { + epoch: u64, + } + + /// Holds information about state of reconfiguration + struct Configuration has key { + /// Epoch number + epoch: u64, + /// Time of last reconfiguration. Only changes on reconfiguration events. + last_reconfiguration_time: u64, + /// Event handle for reconfiguration events + events: event::EventHandle, + } + + /// Reconfiguration will be disabled if this resource is published under the + /// aptos_framework system address + struct DisableReconfiguration has key {} + + /// The `Configuration` resource is in an invalid state + const ECONFIGURATION: u64 = 1; + /// A `Reconfiguration` resource is in an invalid state + const ECONFIG: u64 = 2; + /// A `ModifyConfigCapability` is in a different state than was expected + const EMODIFY_CAPABILITY: u64 = 3; + /// An invalid block time was encountered. + const EINVALID_BLOCK_TIME: u64 = 4; + /// An invalid block time was encountered. + const EINVALID_GUID_FOR_EVENT: u64 = 5; + + /// Only called during genesis. + /// Publishes `Configuration` resource. Can only be invoked by aptos framework account, and only a single time in Genesis. + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + + // assert it matches `new_epoch_event_key()`, otherwise the event can't be recognized + assert!(account::get_guid_next_creation_num(signer::address_of(aptos_framework)) == 2, error::invalid_state(EINVALID_GUID_FOR_EVENT)); + move_to( + aptos_framework, + Configuration { + epoch: 0, + last_reconfiguration_time: 0, + events: account::new_event_handle(aptos_framework), + } + ); + } + + /// Private function to temporarily halt reconfiguration. + /// This function should only be used for offline WriteSet generation purpose and should never be invoked on chain. + fun disable_reconfiguration(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(reconfiguration_enabled(), error::invalid_state(ECONFIGURATION)); + move_to(aptos_framework, DisableReconfiguration {}) + } + + /// Private function to resume reconfiguration. + /// This function should only be used for offline WriteSet generation purpose and should never be invoked on chain. + fun enable_reconfiguration(aptos_framework: &signer) acquires DisableReconfiguration { + system_addresses::assert_aptos_framework(aptos_framework); + + assert!(!reconfiguration_enabled(), error::invalid_state(ECONFIGURATION)); + DisableReconfiguration {} = move_from(signer::address_of(aptos_framework)); + } + + fun reconfiguration_enabled(): bool { + !exists(@aptos_framework) + } + + /// Signal validators to start using new configuration. Must be called from friend config modules. + public(friend) fun reconfigure() acquires Configuration { + // Do not do anything if genesis has not finished. + if (chain_status::is_genesis() || timestamp::now_microseconds() == 0 || !reconfiguration_enabled()) { + return + }; + + let config_ref = borrow_global_mut(@aptos_framework); + let current_time = timestamp::now_microseconds(); + + // Do not do anything if a reconfiguration event is already emitted within this transaction. + // + // This is OK because: + // - The time changes in every non-empty block + // - A block automatically ends after a transaction that emits a reconfiguration event, which is guaranteed by + // VM spec that all transactions comming after a reconfiguration transaction will be returned as Retry + // status. + // - Each transaction must emit at most one reconfiguration event + // + // Thus, this check ensures that a transaction that does multiple "reconfiguration required" actions emits only + // one reconfiguration event. + // + if (current_time == config_ref.last_reconfiguration_time) { + return + }; + + // Reconfiguration "forces the block" to end, as mentioned above. Therefore, we must process the collected fees + // explicitly so that staking can distribute them. + // + // This also handles the case when a validator is removed due to the governance proposal. In particular, removing + // the validator causes a reconfiguration. We explicitly process fees, i.e. we drain aggregatable coin and populate + // the fees table, prior to calling `on_new_epoch()`. That call, in turn, distributes transaction fees for all active + // and pending_inactive validators, which include any validator that is to be removed. + if (features::collect_and_distribute_gas_fees()) { + // All transactions after reconfiguration are Retry. Therefore, when the next + // block starts and tries to assign/burn collected fees it will be just 0 and + // nothing will be assigned. + transaction_fee::process_collected_fees(); + }; + + // Call stake to compute the new validator set and distribute rewards and transaction fees. + stake::on_new_epoch(); + storage_gas::on_reconfig(); + + assert!(current_time > config_ref.last_reconfiguration_time, error::invalid_state(EINVALID_BLOCK_TIME)); + config_ref.last_reconfiguration_time = current_time; + spec { + assume config_ref.epoch + 1 <= MAX_U64; + }; + config_ref.epoch = config_ref.epoch + 1; + + event::emit_event( + &mut config_ref.events, + NewEpochEvent { + epoch: config_ref.epoch, + }, + ); + } + + public fun last_reconfiguration_time(): u64 acquires Configuration { + borrow_global(@aptos_framework).last_reconfiguration_time + } + + public fun current_epoch(): u64 acquires Configuration { + borrow_global(@aptos_framework).epoch + } + + /// Emit a `NewEpochEvent` event. This function will be invoked by genesis directly to generate the very first + /// reconfiguration event. + fun emit_genesis_reconfiguration_event() acquires Configuration { + let config_ref = borrow_global_mut(@aptos_framework); + assert!(config_ref.epoch == 0 && config_ref.last_reconfiguration_time == 0, error::invalid_state(ECONFIGURATION)); + config_ref.epoch = 1; + + event::emit_event( + &mut config_ref.events, + NewEpochEvent { + epoch: config_ref.epoch, + }, + ); + } + + // For tests, skips the guid validation. + #[test_only] + public fun initialize_for_test(account: &signer) { + system_addresses::assert_aptos_framework(account); + move_to( + account, + Configuration { + epoch: 0, + last_reconfiguration_time: 0, + events: account::new_event_handle(account), + } + ); + } + + #[test_only] + public fun reconfigure_for_test() acquires Configuration { + reconfigure(); + } + + // This is used together with stake::end_epoch() for testing with last_reconfiguration_time + // It must be called each time an epoch changes + #[test_only] + public fun reconfigure_for_test_custom() acquires Configuration { + let config_ref = borrow_global_mut(@aptos_framework); + let current_time = timestamp::now_microseconds(); + if (current_time == config_ref.last_reconfiguration_time) { + return + }; + config_ref.last_reconfiguration_time = current_time; + config_ref.epoch = config_ref.epoch + 1; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/resource_account.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/resource_account.move new file mode 100644 index 0000000..7f85a8b --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/resource_account.move @@ -0,0 +1,262 @@ +/// A resource account is used to manage resources independent of an account managed by a user. +/// This contains several utilities to make using resource accounts more effective. +/// +/// ## Resource Accounts to manage liquidity pools +/// +/// A dev wishing to use resource accounts for a liquidity pool, would likely do the following: +/// +/// 1. Create a new account using `resource_account::create_resource_account`. This creates the +/// account, stores the `signer_cap` within a `resource_account::Container`, and rotates the key to +/// the current account's authentication key or a provided authentication key. +/// 2. Define the liquidity pool module's address to be the same as the resource account. +/// 3. Construct a package-publishing transaction for the resource account using the +/// authentication key used in step 1. +/// 4. In the liquidity pool module's `init_module` function, call `retrieve_resource_account_cap` +/// which will retrieve the `signer_cap` and rotate the resource account's authentication key to +/// `0x0`, effectively locking it off. +/// 5. When adding a new coin, the liquidity pool will load the capability and hence the `signer` to +/// register and store new `LiquidityCoin` resources. +/// +/// Code snippets to help: +/// +/// ``` +/// fun init_module(resource_account: &signer) { +/// let dev_address = @DEV_ADDR; +/// let signer_cap = retrieve_resource_account_cap(resource_account, dev_address); +/// let lp = LiquidityPoolInfo { signer_cap: signer_cap, ... }; +/// move_to(resource_account, lp); +/// } +/// ``` +/// +/// Later on during a coin registration: +/// ``` +/// public fun add_coin(lp: &LP, x: Coin, y: Coin) { +/// if(!exists(LP::Address(lp), LiquidityCoin)) { +/// let mint, burn = Coin::initialize>(...); +/// move_to(&create_signer_with_capability(&lp.cap), LiquidityCoin{ mint, burn }); +/// } +/// ... +/// } +/// ``` +/// ## Resource accounts to manage an account for module publishing (i.e., contract account) +/// +/// A dev wishes to have an account dedicated to managing a contract. The contract itself does not +/// require signer post initialization. The dev could do the following: +/// 1. Create a new account using `resource_account::create_resource_account_and_publish_package`. +/// This creates the account and publishes the package for that account. +/// 2. At a later point in time, the account creator can move the signer capability to the module. +/// +/// ``` +/// struct MyModuleResource has key { +/// ... +/// resource_signer_cap: Option, +/// } +/// +/// public fun provide_signer_capability(resource_signer_cap: SignerCapability) { +/// let account_addr = account::get_signer_capability_address(resource_signer_cap); +/// let resource_addr = type_info::account_address(&type_info::type_of()); +/// assert!(account_addr == resource_addr, EADDRESS_MISMATCH); +/// let module = borrow_global_mut(account_addr); +/// module.resource_signer_cap = option::some(resource_signer_cap); +/// } +/// ``` +module aptos_framework::resource_account { + use std::error; + use std::signer; + use std::vector; + use aptos_framework::account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin; + use aptos_std::simple_map::{Self, SimpleMap}; + + /// Container resource not found in account + const ECONTAINER_NOT_PUBLISHED: u64 = 1; + /// The resource account was not created by the specified source account + const EUNAUTHORIZED_NOT_OWNER: u64 = 2; + + const ZERO_AUTH_KEY: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + + struct Container has key { + store: SimpleMap, + } + + /// Creates a new resource account and rotates the authentication key to either + /// the optional auth key if it is non-empty (though auth keys are 32-bytes) + /// or the source accounts current auth key. + public entry fun create_resource_account( + origin: &signer, + seed: vector, + optional_auth_key: vector, + ) acquires Container { + let (resource, resource_signer_cap) = account::create_resource_account(origin, seed); + rotate_account_authentication_key_and_store_capability( + origin, + resource, + resource_signer_cap, + optional_auth_key, + ); + } + + /// Creates a new resource account, transfer the amount of coins from the origin to the resource + /// account, and rotates the authentication key to either the optional auth key if it is + /// non-empty (though auth keys are 32-bytes) or the source accounts current auth key. Note, + /// this function adds additional resource ownership to the resource account and should only be + /// used for resource accounts that need access to `Coin`. + public entry fun create_resource_account_and_fund( + origin: &signer, + seed: vector, + optional_auth_key: vector, + fund_amount: u64, + ) acquires Container { + let (resource, resource_signer_cap) = account::create_resource_account(origin, seed); + coin::register(&resource); + coin::transfer(origin, signer::address_of(&resource), fund_amount); + rotate_account_authentication_key_and_store_capability( + origin, + resource, + resource_signer_cap, + optional_auth_key, + ); + } + + /// Creates a new resource account, publishes the package under this account transaction under + /// this account and leaves the signer cap readily available for pickup. + public entry fun create_resource_account_and_publish_package( + origin: &signer, + seed: vector, + metadata_serialized: vector, + code: vector>, + ) acquires Container { + let (resource, resource_signer_cap) = account::create_resource_account(origin, seed); + aptos_framework::code::publish_package_txn(&resource, metadata_serialized, code); + rotate_account_authentication_key_and_store_capability( + origin, + resource, + resource_signer_cap, + ZERO_AUTH_KEY, + ); + } + + fun rotate_account_authentication_key_and_store_capability( + origin: &signer, + resource: signer, + resource_signer_cap: account::SignerCapability, + optional_auth_key: vector, + ) acquires Container { + let origin_addr = signer::address_of(origin); + if (!exists(origin_addr)) { + move_to(origin, Container { store: simple_map::create() }) + }; + + let container = borrow_global_mut(origin_addr); + let resource_addr = signer::address_of(&resource); + simple_map::add(&mut container.store, resource_addr, resource_signer_cap); + + let auth_key = if (vector::is_empty(&optional_auth_key)) { + account::get_authentication_key(origin_addr) + } else { + optional_auth_key + }; + account::rotate_authentication_key_internal(&resource, auth_key); + } + + /// When called by the resource account, it will retrieve the capability associated with that + /// account and rotate the account's auth key to 0x0 making the account inaccessible without + /// the SignerCapability. + public fun retrieve_resource_account_cap( + resource: &signer, + source_addr: address, + ): account::SignerCapability acquires Container { + assert!(exists(source_addr), error::not_found(ECONTAINER_NOT_PUBLISHED)); + + let resource_addr = signer::address_of(resource); + let (resource_signer_cap, empty_container) = { + let container = borrow_global_mut(source_addr); + assert!(simple_map::contains_key(&container.store, &resource_addr), error::invalid_argument(EUNAUTHORIZED_NOT_OWNER)); + let (_resource_addr, signer_cap) = simple_map::remove(&mut container.store, &resource_addr); + (signer_cap, simple_map::length(&container.store) == 0) + }; + + if (empty_container) { + let container = move_from(source_addr); + let Container { store } = container; + simple_map::destroy_empty(store); + }; + + account::rotate_authentication_key_internal(resource, ZERO_AUTH_KEY); + resource_signer_cap + } + + #[test(user = @0x1111)] + public entry fun test_create_account_and_retrieve_cap(user: signer) acquires Container { + let user_addr = signer::address_of(&user); + account::create_account(user_addr); + + let seed = x"01"; + + create_resource_account(&user, copy seed, vector::empty()); + let container = borrow_global(user_addr); + + let resource_addr = aptos_framework::account::create_resource_address(&user_addr, seed); + let resource_cap = simple_map::borrow(&container.store, &resource_addr); + + let resource = account::create_signer_with_capability(resource_cap); + let _resource_cap = retrieve_resource_account_cap(&resource, user_addr); + } + + #[test(user = @0x1111)] + #[expected_failure(abort_code = 0x10002, location = aptos_std::simple_map)] + public entry fun test_create_account_and_retrieve_cap_resource_address_does_not_exist(user: signer) acquires Container { + let user_addr = signer::address_of(&user); + account::create_account(user_addr); + + let seed = x"01"; + let seed2 = x"02"; + + create_resource_account(&user, seed2, vector::empty()); + let container = borrow_global(user_addr); + + let resource_addr = account::create_resource_address(&user_addr, seed); + let resource_cap = simple_map::borrow(&container.store, &resource_addr); + + let resource = account::create_signer_with_capability(resource_cap); + let _resource_cap = retrieve_resource_account_cap(&resource, user_addr); + } + + #[test(framework = @0x1, user = @0x1234)] + public entry fun with_coin(framework: signer, user: signer) acquires Container { + let user_addr = signer::address_of(&user); + aptos_framework::aptos_account::create_account(copy user_addr); + + let (burn, mint) = aptos_framework::aptos_coin::initialize_for_test(&framework); + let coin = coin::mint(100, &mint); + coin::deposit(copy user_addr, coin); + + let seed = x"01"; + create_resource_account_and_fund(&user, copy seed, vector::empty(), 10); + + let resource_addr = aptos_framework::account::create_resource_address(&user_addr, seed); + coin::transfer(&user, resource_addr, 10); + + coin::destroy_burn_cap(burn); + coin::destroy_mint_cap(mint); + } + + #[test(framework = @0x1, user = @0x2345)] + #[expected_failure(abort_code = 0x60005, location = aptos_framework::coin)] + public entry fun without_coin(framework: signer, user: signer) acquires Container { + let user_addr = signer::address_of(&user); + aptos_framework::aptos_account::create_account(user_addr); + + let seed = x"01"; + create_resource_account(&user, copy seed, vector::empty()); + + let resource_addr = aptos_framework::account::create_resource_address(&user_addr, seed); + let (burn, mint) = aptos_framework::aptos_coin::initialize_for_test(&framework); + let coin = coin::mint(100, &mint); + coin::deposit(resource_addr, coin); + + coin::destroy_burn_cap(burn); + coin::destroy_mint_cap(mint); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/stake.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/stake.move new file mode 100644 index 0000000..0b9fe26 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/stake.move @@ -0,0 +1,2759 @@ +/// +/// Validator lifecycle: +/// 1. Prepare a validator node set up and call stake::initialize_validator +/// 2. Once ready to deposit stake (or have funds assigned by a staking service in exchange for ownership capability), +/// call stake::add_stake (or *_with_cap versions if called from the staking service) +/// 3. Call stake::join_validator_set (or _with_cap version) to join the active validator set. Changes are effective in +/// the next epoch. +/// 4. Validate and gain rewards. The stake will automatically be locked up for a fixed duration (set by governance) and +/// automatically renewed at expiration. +/// 5. At any point, if the validator operator wants to update the consensus key or network/fullnode addresses, they can +/// call stake::rotate_consensus_key and stake::update_network_and_fullnode_addresses. Similar to changes to stake, the +/// changes to consensus key/network/fullnode addresses are only effective in the next epoch. +/// 6. Validator can request to unlock their stake at any time. However, their stake will only become withdrawable when +/// their current lockup expires. This can be at most as long as the fixed lockup duration. +/// 7. After exiting, the validator can either explicitly leave the validator set by calling stake::leave_validator_set +/// or if their stake drops below the min required, they would get removed at the end of the epoch. +/// 8. Validator can always rejoin the validator set by going through steps 2-3 again. +/// 9. An owner can always switch operators by calling stake::set_operator. +/// 10. An owner can always switch designated voter by calling stake::set_designated_voter. +module aptos_framework::stake { + use std::error; + use std::features; + use std::option::{Self, Option}; + use std::signer; + use std::vector; + use aptos_std::bls12381; + use aptos_std::math64::min; + use aptos_std::table::{Self, Table}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::account; + use aptos_framework::coin::{Self, Coin, MintCapability}; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::timestamp; + use aptos_framework::system_addresses; + use aptos_framework::staking_config::{Self, StakingConfig, StakingRewardsConfig}; + use aptos_framework::chain_status; + + friend aptos_framework::block; + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration; + friend aptos_framework::transaction_fee; + + /// Validator Config not published. + const EVALIDATOR_CONFIG: u64 = 1; + /// Not enough stake to join validator set. + const ESTAKE_TOO_LOW: u64 = 2; + /// Too much stake to join validator set. + const ESTAKE_TOO_HIGH: u64 = 3; + /// Account is already a validator or pending validator. + const EALREADY_ACTIVE_VALIDATOR: u64 = 4; + /// Account is not a validator. + const ENOT_VALIDATOR: u64 = 5; + /// Can't remove last validator. + const ELAST_VALIDATOR: u64 = 6; + /// Total stake exceeds maximum allowed. + const ESTAKE_EXCEEDS_MAX: u64 = 7; + /// Account is already registered as a validator candidate. + const EALREADY_REGISTERED: u64 = 8; + /// Account does not have the right operator capability. + const ENOT_OPERATOR: u64 = 9; + /// Validators cannot join or leave post genesis on this test network. + const ENO_POST_GENESIS_VALIDATOR_SET_CHANGE_ALLOWED: u64 = 10; + /// Invalid consensus public key + const EINVALID_PUBLIC_KEY: u64 = 11; + /// Validator set exceeds the limit + const EVALIDATOR_SET_TOO_LARGE: u64 = 12; + /// Voting power increase has exceeded the limit for this current epoch. + const EVOTING_POWER_INCREASE_EXCEEDS_LIMIT: u64 = 13; + /// Stake pool does not exist at the provided pool address. + const ESTAKE_POOL_DOES_NOT_EXIST: u64 = 14; + /// Owner capability does not exist at the provided account. + const EOWNER_CAP_NOT_FOUND: u64 = 15; + /// An account cannot own more than one owner capability. + const EOWNER_CAP_ALREADY_EXISTS: u64 = 16; + /// Validator is not defined in the ACL of entities allowed to be validators + const EINELIGIBLE_VALIDATOR: u64 = 17; + /// Cannot update stake pool's lockup to earlier than current lockup. + const EINVALID_LOCKUP: u64 = 18; + /// Table to store collected transaction fees for each validator already exists. + const EFEES_TABLE_ALREADY_EXISTS: u64 = 19; + + /// Validator status enum. We can switch to proper enum later once Move supports it. + const VALIDATOR_STATUS_PENDING_ACTIVE: u64 = 1; + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + const VALIDATOR_STATUS_PENDING_INACTIVE: u64 = 3; + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + /// Limit the maximum size to u16::max, it's the current limit of the bitvec + /// https://github.com/aptos-labs/aptos-core/blob/main/crates/aptos-bitvec/src/lib.rs#L20 + const MAX_VALIDATOR_SET_SIZE: u64 = 65536; + + /// Limit the maximum value of `rewards_rate` in order to avoid any arithmetic overflow. + const MAX_REWARDS_RATE: u64 = 1000000; + + const MAX_U64: u128 = 18446744073709551615; + + /// Capability that represents ownership and can be used to control the validator and the associated stake pool. + /// Having this be separate from the signer for the account that the validator resources are hosted at allows + /// modules to have control over a validator. + struct OwnerCapability has key, store { + pool_address: address, + } + + /// Each validator has a separate StakePool resource and can provide a stake. + /// Changes in stake for an active validator: + /// 1. If a validator calls add_stake, the newly added stake is moved to pending_active. + /// 2. If validator calls unlock, their stake is moved to pending_inactive. + /// 2. When the next epoch starts, any pending_inactive stake is moved to inactive and can be withdrawn. + /// Any pending_active stake is moved to active and adds to the validator's voting power. + /// + /// Changes in stake for an inactive validator: + /// 1. If a validator calls add_stake, the newly added stake is moved directly to active. + /// 2. If validator calls unlock, their stake is moved directly to inactive. + /// 3. When the next epoch starts, the validator can be activated if their active stake is more than the minimum. + struct StakePool has key { + // active stake + active: Coin, + // inactive stake, can be withdrawn + inactive: Coin, + // pending activation for next epoch + pending_active: Coin, + // pending deactivation for next epoch + pending_inactive: Coin, + locked_until_secs: u64, + // Track the current operator of the validator node. + // This allows the operator to be different from the original account and allow for separation of + // the validator operations and ownership. + // Only the account holding OwnerCapability of the staking pool can update this. + operator_address: address, + + // Track the current vote delegator of the staking pool. + // Only the account holding OwnerCapability of the staking pool can update this. + delegated_voter: address, + + // The events emitted for the entire StakePool's lifecycle. + initialize_validator_events: EventHandle, + set_operator_events: EventHandle, + add_stake_events: EventHandle, + reactivate_stake_events: EventHandle, + rotate_consensus_key_events: EventHandle, + update_network_and_fullnode_addresses_events: EventHandle, + increase_lockup_events: EventHandle, + join_validator_set_events: EventHandle, + distribute_rewards_events: EventHandle, + unlock_stake_events: EventHandle, + withdraw_stake_events: EventHandle, + leave_validator_set_events: EventHandle, + } + + /// Validator info stored in validator address. + struct ValidatorConfig has key, copy, store, drop { + consensus_pubkey: vector, + network_addresses: vector, + // to make it compatible with previous definition, remove later + fullnode_addresses: vector, + // Index in the active set if the validator corresponding to this stake pool is active. + validator_index: u64, + } + + /// Consensus information per validator, stored in ValidatorSet. + struct ValidatorInfo has copy, store, drop { + addr: address, + voting_power: u64, + config: ValidatorConfig, + } + + /// Full ValidatorSet, stored in @aptos_framework. + /// 1. join_validator_set adds to pending_active queue. + /// 2. leave_valdiator_set moves from active to pending_inactive queue. + /// 3. on_new_epoch processes two pending queues and refresh ValidatorInfo from the owner's address. + struct ValidatorSet has key { + consensus_scheme: u8, + // Active validators for the current epoch. + active_validators: vector, + // Pending validators to leave in next epoch (still active). + pending_inactive: vector, + // Pending validators to join in next epoch. + pending_active: vector, + // Current total voting power. + total_voting_power: u128, + // Total voting power waiting to join in the next epoch. + total_joining_power: u128, + } + + /// AptosCoin capabilities, set during genesis and stored in @CoreResource account. + /// This allows the Stake module to mint rewards to stakers. + struct AptosCoinCapabilities has key { + mint_cap: MintCapability, + } + + struct IndividualValidatorPerformance has store, drop { + successful_proposals: u64, + failed_proposals: u64, + } + + struct ValidatorPerformance has key { + validators: vector, + } + + struct RegisterValidatorCandidateEvent has drop, store { + pool_address: address, + } + + struct SetOperatorEvent has drop, store { + pool_address: address, + old_operator: address, + new_operator: address, + } + + struct AddStakeEvent has drop, store { + pool_address: address, + amount_added: u64, + } + + struct ReactivateStakeEvent has drop, store { + pool_address: address, + amount: u64, + } + + struct RotateConsensusKeyEvent has drop, store { + pool_address: address, + old_consensus_pubkey: vector, + new_consensus_pubkey: vector, + } + + struct UpdateNetworkAndFullnodeAddressesEvent has drop, store { + pool_address: address, + old_network_addresses: vector, + new_network_addresses: vector, + old_fullnode_addresses: vector, + new_fullnode_addresses: vector, + } + + struct IncreaseLockupEvent has drop, store { + pool_address: address, + old_locked_until_secs: u64, + new_locked_until_secs: u64, + } + + struct JoinValidatorSetEvent has drop, store { + pool_address: address, + } + + struct DistributeRewardsEvent has drop, store { + pool_address: address, + rewards_amount: u64, + } + + struct UnlockStakeEvent has drop, store { + pool_address: address, + amount_unlocked: u64, + } + + struct WithdrawStakeEvent has drop, store { + pool_address: address, + amount_withdrawn: u64, + } + + struct LeaveValidatorSetEvent has drop, store { + pool_address: address, + } + + /// Stores transaction fees assigned to validators. All fees are distributed to validators + /// at the end of the epoch. + struct ValidatorFees has key { + fees_table: Table>, + } + + /// Initializes the resource storing information about collected transaction fees per validator. + /// Used by `transaction_fee.move` to initialize fee collection and distribution. + public(friend) fun initialize_validator_fees(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(EFEES_TABLE_ALREADY_EXISTS) + ); + move_to(aptos_framework, ValidatorFees { fees_table: table::new() }); + } + + /// Stores the transaction fee collected to the specified validator address. + public(friend) fun add_transaction_fee(validator_addr: address, fee: Coin) acquires ValidatorFees { + let fees_table = &mut borrow_global_mut(@aptos_framework).fees_table; + if (table::contains(fees_table, validator_addr)) { + let collected_fee = table::borrow_mut(fees_table, validator_addr); + coin::merge(collected_fee, fee); + } else { + table::add(fees_table, validator_addr, fee); + } + } + + #[view] + /// Return the lockup expiration of the stake pool at `pool_address`. + /// This will throw an error if there's no stake pool at `pool_address`. + public fun get_lockup_secs(pool_address: address): u64 acquires StakePool { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).locked_until_secs + } + + #[view] + /// Return the remaining lockup of the stake pool at `pool_address`. + /// This will throw an error if there's no stake pool at `pool_address`. + public fun get_remaining_lockup_secs(pool_address: address): u64 acquires StakePool { + assert_stake_pool_exists(pool_address); + let lockup_time = borrow_global(pool_address).locked_until_secs; + if (lockup_time <= timestamp::now_seconds()) { + 0 + } else { + lockup_time - timestamp::now_seconds() + } + } + + #[view] + /// Return the different stake amounts for `pool_address` (whether the validator is active or not). + /// The returned amounts are for (active, inactive, pending_active, pending_inactive) stake respectively. + public fun get_stake(pool_address: address): (u64, u64, u64, u64) acquires StakePool { + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global(pool_address); + ( + coin::value(&stake_pool.active), + coin::value(&stake_pool.inactive), + coin::value(&stake_pool.pending_active), + coin::value(&stake_pool.pending_inactive), + ) + } + + #[view] + /// Returns the validator's state. + public fun get_validator_state(pool_address: address): u64 acquires ValidatorSet { + let validator_set = borrow_global(@aptos_framework); + if (option::is_some(&find_validator(&validator_set.pending_active, pool_address))) { + VALIDATOR_STATUS_PENDING_ACTIVE + } else if (option::is_some(&find_validator(&validator_set.active_validators, pool_address))) { + VALIDATOR_STATUS_ACTIVE + } else if (option::is_some(&find_validator(&validator_set.pending_inactive, pool_address))) { + VALIDATOR_STATUS_PENDING_INACTIVE + } else { + VALIDATOR_STATUS_INACTIVE + } + } + + #[view] + /// Return the voting power of the validator in the current epoch. + /// This is the same as the validator's total active and pending_inactive stake. + public fun get_current_epoch_voting_power(pool_address: address): u64 acquires StakePool, ValidatorSet { + assert_stake_pool_exists(pool_address); + let validator_state = get_validator_state(pool_address); + // Both active and pending inactive validators can still vote in the current epoch. + if (validator_state == VALIDATOR_STATUS_ACTIVE || validator_state == VALIDATOR_STATUS_PENDING_INACTIVE) { + let active_stake = coin::value(&borrow_global(pool_address).active); + let pending_inactive_stake = coin::value(&borrow_global(pool_address).pending_inactive); + active_stake + pending_inactive_stake + } else { + 0 + } + } + + #[view] + /// Return the delegated voter of the validator at `pool_address`. + public fun get_delegated_voter(pool_address: address): address acquires StakePool { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).delegated_voter + } + + #[view] + /// Return the operator of the validator at `pool_address`. + public fun get_operator(pool_address: address): address acquires StakePool { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).operator_address + } + + /// Return the pool address in `owner_cap`. + public fun get_owned_pool_address(owner_cap: &OwnerCapability): address { + owner_cap.pool_address + } + + #[view] + /// Return the validator index for `pool_address`. + public fun get_validator_index(pool_address: address): u64 acquires ValidatorConfig { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).validator_index + } + + #[view] + /// Return the number of successful and failed proposals for the proposal at the given validator index. + public fun get_current_epoch_proposal_counts(validator_index: u64): (u64, u64) acquires ValidatorPerformance { + let validator_performances = &borrow_global(@aptos_framework).validators; + let validator_performance = vector::borrow(validator_performances, validator_index); + (validator_performance.successful_proposals, validator_performance.failed_proposals) + } + + #[view] + /// Return the validator's config. + public fun get_validator_config(pool_address: address): (vector, vector, vector) acquires ValidatorConfig { + assert_stake_pool_exists(pool_address); + let validator_config = borrow_global(pool_address); + (validator_config.consensus_pubkey, validator_config.network_addresses, validator_config.fullnode_addresses) + } + + #[view] + public fun stake_pool_exists(addr: address): bool { + exists(addr) + } + + /// Initialize validator set to the core resource account. + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, ValidatorSet { + consensus_scheme: 0, + active_validators: vector::empty(), + pending_active: vector::empty(), + pending_inactive: vector::empty(), + total_voting_power: 0, + total_joining_power: 0, + }); + + move_to(aptos_framework, ValidatorPerformance { + validators: vector::empty(), + }); + } + + /// This is only called during Genesis, which is where MintCapability can be created. + /// Beyond genesis, no one can create AptosCoin mint/burn capabilities. + public(friend) fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinCapabilities { mint_cap }) + } + + /// Allow on chain governance to remove validators from the validator set. + public fun remove_validators( + aptos_framework: &signer, + validators: &vector
, + ) acquires ValidatorSet { + system_addresses::assert_aptos_framework(aptos_framework); + + let validator_set = borrow_global_mut(@aptos_framework); + let active_validators = &mut validator_set.active_validators; + let pending_inactive = &mut validator_set.pending_inactive; + let len = vector::length(validators); + let i = 0; + // Remove each validator from the validator set. + while ({ + spec { + invariant spec_validators_are_initialized(active_validators); + invariant spec_validator_indices_are_valid(active_validators); + invariant spec_validators_are_initialized(pending_inactive); + invariant spec_validator_indices_are_valid(pending_inactive); + }; + i < len + }) { + let validator = *vector::borrow(validators, i); + let validator_index = find_validator(active_validators, validator); + if (option::is_some(&validator_index)) { + let validator_info = vector::swap_remove(active_validators, *option::borrow(&validator_index)); + vector::push_back(pending_inactive, validator_info); + }; + i = i + 1; + }; + } + + /// Initialize the validator account and give ownership to the signing account + /// except it leaves the ValidatorConfig to be set by another entity. + /// Note: this triggers setting the operator and owner, set it to the account's address + /// to set later. + public entry fun initialize_stake_owner( + owner: &signer, + initial_stake_amount: u64, + operator: address, + voter: address, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + initialize_owner(owner); + move_to(owner, ValidatorConfig { + consensus_pubkey: vector::empty(), + network_addresses: vector::empty(), + fullnode_addresses: vector::empty(), + validator_index: 0, + }); + + if (initial_stake_amount > 0) { + add_stake(owner, initial_stake_amount); + }; + + let account_address = signer::address_of(owner); + if (account_address != operator) { + set_operator(owner, operator) + }; + if (account_address != voter) { + set_delegated_voter(owner, voter) + }; + } + + /// Initialize the validator account and give ownership to the signing account. + public entry fun initialize_validator( + account: &signer, + consensus_pubkey: vector, + proof_of_possession: vector, + network_addresses: vector, + fullnode_addresses: vector, + ) acquires AllowedValidators { + // Checks the public key has a valid proof-of-possession to prevent rogue-key attacks. + let pubkey_from_pop = &mut bls12381::public_key_from_bytes_with_pop( + consensus_pubkey, + &proof_of_possession_from_bytes(proof_of_possession) + ); + assert!(option::is_some(pubkey_from_pop), error::invalid_argument(EINVALID_PUBLIC_KEY)); + + initialize_owner(account); + move_to(account, ValidatorConfig { + consensus_pubkey, + network_addresses, + fullnode_addresses, + validator_index: 0, + }); + } + + fun initialize_owner(owner: &signer) acquires AllowedValidators { + let owner_address = signer::address_of(owner); + assert!(is_allowed(owner_address), error::not_found(EINELIGIBLE_VALIDATOR)); + assert!(!stake_pool_exists(owner_address), error::already_exists(EALREADY_REGISTERED)); + + move_to(owner, StakePool { + active: coin::zero(), + pending_active: coin::zero(), + pending_inactive: coin::zero(), + inactive: coin::zero(), + locked_until_secs: 0, + operator_address: owner_address, + delegated_voter: owner_address, + // Events. + initialize_validator_events: account::new_event_handle(owner), + set_operator_events: account::new_event_handle(owner), + add_stake_events: account::new_event_handle(owner), + reactivate_stake_events: account::new_event_handle(owner), + rotate_consensus_key_events: account::new_event_handle(owner), + update_network_and_fullnode_addresses_events: account::new_event_handle(owner), + increase_lockup_events: account::new_event_handle(owner), + join_validator_set_events: account::new_event_handle(owner), + distribute_rewards_events: account::new_event_handle(owner), + unlock_stake_events: account::new_event_handle(owner), + withdraw_stake_events: account::new_event_handle(owner), + leave_validator_set_events: account::new_event_handle(owner), + }); + + move_to(owner, OwnerCapability { pool_address: owner_address }); + } + + /// Extract and return owner capability from the signing account. + public fun extract_owner_cap(owner: &signer): OwnerCapability acquires OwnerCapability { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + move_from(owner_address) + } + + /// Deposit `owner_cap` into `account`. This requires `account` to not already have owernship of another + /// staking pool. + public fun deposit_owner_cap(owner: &signer, owner_cap: OwnerCapability) { + assert!(!exists(signer::address_of(owner)), error::not_found(EOWNER_CAP_ALREADY_EXISTS)); + move_to(owner, owner_cap); + } + + /// Destroy `owner_cap`. + public fun destroy_owner_cap(owner_cap: OwnerCapability) { + let OwnerCapability { pool_address: _ } = owner_cap; + } + + /// Allows an owner to change the operator of the stake pool. + public entry fun set_operator(owner: &signer, new_operator: address) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + set_operator_with_cap(ownership_cap, new_operator); + } + + /// Allows an account with ownership capability to change the operator of the stake pool. + public fun set_operator_with_cap(owner_cap: &OwnerCapability, new_operator: address) acquires StakePool { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + let old_operator = stake_pool.operator_address; + stake_pool.operator_address = new_operator; + + event::emit_event( + &mut stake_pool.set_operator_events, + SetOperatorEvent { + pool_address, + old_operator, + new_operator, + }, + ); + } + + /// Allows an owner to change the delegated voter of the stake pool. + public entry fun set_delegated_voter(owner: &signer, new_voter: address) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + set_delegated_voter_with_cap(ownership_cap, new_voter); + } + + /// Allows an owner to change the delegated voter of the stake pool. + public fun set_delegated_voter_with_cap(owner_cap: &OwnerCapability, new_voter: address) acquires StakePool { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + stake_pool.delegated_voter = new_voter; + } + + /// Add `amount` of coins from the `account` owning the StakePool. + public entry fun add_stake(owner: &signer, amount: u64) acquires OwnerCapability, StakePool, ValidatorSet { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + add_stake_with_cap(ownership_cap, coin::withdraw(owner, amount)); + } + + /// Add `coins` into `pool_address`. this requires the corresponding `owner_cap` to be passed in. + public fun add_stake_with_cap(owner_cap: &OwnerCapability, coins: Coin) acquires StakePool, ValidatorSet { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + + let amount = coin::value(&coins); + if (amount == 0) { + coin::destroy_zero(coins); + return + }; + + // Only track and validate voting power increase for active and pending_active validator. + // Pending_inactive validator will be removed from the validator set in the next epoch. + // Inactive validator's total stake will be tracked when they join the validator set. + let validator_set = borrow_global_mut(@aptos_framework); + // Search directly rather using get_validator_state to save on unnecessary loops. + if (option::is_some(&find_validator(&validator_set.active_validators, pool_address)) || + option::is_some(&find_validator(&validator_set.pending_active, pool_address))) { + update_voting_power_increase(amount); + }; + + // Add to pending_active if it's a current validator because the stake is not counted until the next epoch. + // Otherwise, the delegation can be added to active directly as the validator is also activated in the epoch. + let stake_pool = borrow_global_mut(pool_address); + if (is_current_epoch_validator(pool_address)) { + coin::merge(&mut stake_pool.pending_active, coins); + } else { + coin::merge(&mut stake_pool.active, coins); + }; + + let (_, maximum_stake) = staking_config::get_required_stake(&staking_config::get()); + let voting_power = get_next_epoch_voting_power(stake_pool); + assert!(voting_power <= maximum_stake, error::invalid_argument(ESTAKE_EXCEEDS_MAX)); + + event::emit_event( + &mut stake_pool.add_stake_events, + AddStakeEvent { + pool_address, + amount_added: amount, + }, + ); + } + + /// Move `amount` of coins from pending_inactive to active. + public entry fun reactivate_stake(owner: &signer, amount: u64) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + reactivate_stake_with_cap(ownership_cap, amount); + } + + public fun reactivate_stake_with_cap(owner_cap: &OwnerCapability, amount: u64) acquires StakePool { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + + // Cap the amount to reactivate by the amount in pending_inactive. + let stake_pool = borrow_global_mut(pool_address); + let total_pending_inactive = coin::value(&stake_pool.pending_inactive); + amount = min(amount, total_pending_inactive); + + // Since this does not count as a voting power change (pending inactive still counts as voting power in the + // current epoch), stake can be immediately moved from pending inactive to active. + // We also don't need to check voting power increase as there's none. + let reactivated_coins = coin::extract(&mut stake_pool.pending_inactive, amount); + coin::merge(&mut stake_pool.active, reactivated_coins); + + event::emit_event( + &mut stake_pool.reactivate_stake_events, + ReactivateStakeEvent { + pool_address, + amount, + }, + ); + } + + /// Rotate the consensus key of the validator, it'll take effect in next epoch. + public entry fun rotate_consensus_key( + operator: &signer, + pool_address: address, + new_consensus_pubkey: vector, + proof_of_possession: vector, + ) acquires StakePool, ValidatorConfig { + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + + assert!(exists(pool_address), error::not_found(EVALIDATOR_CONFIG)); + let validator_info = borrow_global_mut(pool_address); + let old_consensus_pubkey = validator_info.consensus_pubkey; + // Checks the public key has a valid proof-of-possession to prevent rogue-key attacks. + let pubkey_from_pop = &mut bls12381::public_key_from_bytes_with_pop( + new_consensus_pubkey, + &proof_of_possession_from_bytes(proof_of_possession) + ); + assert!(option::is_some(pubkey_from_pop), error::invalid_argument(EINVALID_PUBLIC_KEY)); + validator_info.consensus_pubkey = new_consensus_pubkey; + + event::emit_event( + &mut stake_pool.rotate_consensus_key_events, + RotateConsensusKeyEvent { + pool_address, + old_consensus_pubkey, + new_consensus_pubkey, + }, + ); + } + + /// Update the network and full node addresses of the validator. This only takes effect in the next epoch. + public entry fun update_network_and_fullnode_addresses( + operator: &signer, + pool_address: address, + new_network_addresses: vector, + new_fullnode_addresses: vector, + ) acquires StakePool, ValidatorConfig { + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + + assert!(exists(pool_address), error::not_found(EVALIDATOR_CONFIG)); + let validator_info = borrow_global_mut(pool_address); + let old_network_addresses = validator_info.network_addresses; + validator_info.network_addresses = new_network_addresses; + let old_fullnode_addresses = validator_info.fullnode_addresses; + validator_info.fullnode_addresses = new_fullnode_addresses; + + event::emit_event( + &mut stake_pool.update_network_and_fullnode_addresses_events, + UpdateNetworkAndFullnodeAddressesEvent { + pool_address, + old_network_addresses, + new_network_addresses, + old_fullnode_addresses, + new_fullnode_addresses, + }, + ); + } + + /// Similar to increase_lockup_with_cap but will use ownership capability from the signing account. + public entry fun increase_lockup(owner: &signer) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + increase_lockup_with_cap(ownership_cap); + } + + /// Unlock from active delegation, it's moved to pending_inactive if locked_until_secs < current_time or + /// directly inactive if it's not from an active validator. + public fun increase_lockup_with_cap(owner_cap: &OwnerCapability) acquires StakePool { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let config = staking_config::get(); + + let stake_pool = borrow_global_mut(pool_address); + let old_locked_until_secs = stake_pool.locked_until_secs; + let new_locked_until_secs = timestamp::now_seconds() + staking_config::get_recurring_lockup_duration(&config); + assert!(old_locked_until_secs < new_locked_until_secs, error::invalid_argument(EINVALID_LOCKUP)); + stake_pool.locked_until_secs = new_locked_until_secs; + + event::emit_event( + &mut stake_pool.increase_lockup_events, + IncreaseLockupEvent { + pool_address, + old_locked_until_secs, + new_locked_until_secs, + }, + ); + } + + /// This can only called by the operator of the validator/staking pool. + public entry fun join_validator_set( + operator: &signer, + pool_address: address + ) acquires StakePool, ValidatorConfig, ValidatorSet { + assert!( + staking_config::get_allow_validator_set_change(&staking_config::get()), + error::invalid_argument(ENO_POST_GENESIS_VALIDATOR_SET_CHANGE_ALLOWED), + ); + + join_validator_set_internal(operator, pool_address); + } + + /// Request to have `pool_address` join the validator set. Can only be called after calling `initialize_validator`. + /// If the validator has the required stake (more than minimum and less than maximum allowed), they will be + /// added to the pending_active queue. All validators in this queue will be added to the active set when the next + /// epoch starts (eligibility will be rechecked). + /// + /// This internal version can only be called by the Genesis module during Genesis. + public(friend) fun join_validator_set_internal( + operator: &signer, + pool_address: address + ) acquires StakePool, ValidatorConfig, ValidatorSet { + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + assert!( + get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE, + error::invalid_state(EALREADY_ACTIVE_VALIDATOR), + ); + + let config = staking_config::get(); + let (minimum_stake, maximum_stake) = staking_config::get_required_stake(&config); + let voting_power = get_next_epoch_voting_power(stake_pool); + assert!(voting_power >= minimum_stake, error::invalid_argument(ESTAKE_TOO_LOW)); + assert!(voting_power <= maximum_stake, error::invalid_argument(ESTAKE_TOO_HIGH)); + + // Track and validate voting power increase. + update_voting_power_increase(voting_power); + + // Add validator to pending_active, to be activated in the next epoch. + let validator_config = borrow_global_mut(pool_address); + assert!(!vector::is_empty(&validator_config.consensus_pubkey), error::invalid_argument(EINVALID_PUBLIC_KEY)); + + // Validate the current validator set size has not exceeded the limit. + let validator_set = borrow_global_mut(@aptos_framework); + vector::push_back(&mut validator_set.pending_active, generate_validator_info(pool_address, stake_pool, *validator_config)); + let validator_set_size = vector::length(&validator_set.active_validators) + vector::length(&validator_set.pending_active); + assert!(validator_set_size <= MAX_VALIDATOR_SET_SIZE, error::invalid_argument(EVALIDATOR_SET_TOO_LARGE)); + + event::emit_event( + &mut stake_pool.join_validator_set_events, + JoinValidatorSetEvent { pool_address }, + ); + } + + /// Similar to unlock_with_cap but will use ownership capability from the signing account. + public entry fun unlock(owner: &signer, amount: u64) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + unlock_with_cap(amount, ownership_cap); + } + + /// Unlock `amount` from the active stake. Only possible if the lockup has expired. + public fun unlock_with_cap(amount: u64, owner_cap: &OwnerCapability) acquires StakePool { + // Short-circuit if amount to unlock is 0 so we don't emit events. + if (amount == 0) { + return + }; + + // Unlocked coins are moved to pending_inactive. When the current lockup cycle expires, they will be moved into + // inactive in the earliest possible epoch transition. + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + // Cap amount to unlock by maximum active stake. + let amount = min(amount, coin::value(&stake_pool.active)); + let unlocked_stake = coin::extract(&mut stake_pool.active, amount); + coin::merge(&mut stake_pool.pending_inactive, unlocked_stake); + + event::emit_event( + &mut stake_pool.unlock_stake_events, + UnlockStakeEvent { + pool_address, + amount_unlocked: amount, + }, + ); + } + + /// Withdraw from `account`'s inactive stake. + public entry fun withdraw( + owner: &signer, + withdraw_amount: u64 + ) acquires OwnerCapability, StakePool, ValidatorSet { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + let coins = withdraw_with_cap(ownership_cap, withdraw_amount); + coin::deposit(owner_address, coins); + } + + /// Withdraw from `pool_address`'s inactive stake with the corresponding `owner_cap`. + public fun withdraw_with_cap( + owner_cap: &OwnerCapability, + withdraw_amount: u64 + ): Coin acquires StakePool, ValidatorSet { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + // There's an edge case where a validator unlocks their stake and leaves the validator set before + // the stake is fully unlocked (the current lockup cycle has not expired yet). + // This can leave their stake stuck in pending_inactive even after the current lockup cycle expires. + if (get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE && + timestamp::now_seconds() >= stake_pool.locked_until_secs) { + let pending_inactive_stake = coin::extract_all(&mut stake_pool.pending_inactive); + coin::merge(&mut stake_pool.inactive, pending_inactive_stake); + }; + + // Cap withdraw amount by total inactive coins. + withdraw_amount = min(withdraw_amount, coin::value(&stake_pool.inactive)); + if (withdraw_amount == 0) return coin::zero(); + + event::emit_event( + &mut stake_pool.withdraw_stake_events, + WithdrawStakeEvent { + pool_address, + amount_withdrawn: withdraw_amount, + }, + ); + + coin::extract(&mut stake_pool.inactive, withdraw_amount) + } + + /// Request to have `pool_address` leave the validator set. The validator is only actually removed from the set when + /// the next epoch starts. + /// The last validator in the set cannot leave. This is an edge case that should never happen as long as the network + /// is still operational. + /// + /// Can only be called by the operator of the validator/staking pool. + public entry fun leave_validator_set( + operator: &signer, + pool_address: address + ) acquires StakePool, ValidatorSet { + let config = staking_config::get(); + assert!( + staking_config::get_allow_validator_set_change(&config), + error::invalid_argument(ENO_POST_GENESIS_VALIDATOR_SET_CHANGE_ALLOWED), + ); + + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + // Account has to be the operator. + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + + let validator_set = borrow_global_mut(@aptos_framework); + // If the validator is still pending_active, directly kick the validator out. + let maybe_pending_active_index = find_validator(&validator_set.pending_active, pool_address); + if (option::is_some(&maybe_pending_active_index)) { + vector::swap_remove( + &mut validator_set.pending_active, option::extract(&mut maybe_pending_active_index)); + + // Decrease the voting power increase as the pending validator's voting power was added when they requested + // to join. Now that they changed their mind, their voting power should not affect the joining limit of this + // epoch. + let validator_stake = (get_next_epoch_voting_power(stake_pool) as u128); + // total_joining_power should be larger than validator_stake but just in case there has been a small + // rounding error somewhere that can lead to an underflow, we still want to allow this transaction to + // succeed. + if (validator_set.total_joining_power > validator_stake) { + validator_set.total_joining_power = validator_set.total_joining_power - validator_stake; + } else { + validator_set.total_joining_power = 0; + }; + } else { + // Validate that the validator is already part of the validator set. + let maybe_active_index = find_validator(&validator_set.active_validators, pool_address); + assert!(option::is_some(&maybe_active_index), error::invalid_state(ENOT_VALIDATOR)); + let validator_info = vector::swap_remove( + &mut validator_set.active_validators, option::extract(&mut maybe_active_index)); + assert!(vector::length(&validator_set.active_validators) > 0, error::invalid_state(ELAST_VALIDATOR)); + vector::push_back(&mut validator_set.pending_inactive, validator_info); + + event::emit_event( + &mut stake_pool.leave_validator_set_events, + LeaveValidatorSetEvent { + pool_address, + }, + ); + }; + } + + /// Returns true if the current validator can still vote in the current epoch. + /// This includes validators that requested to leave but are still in the pending_inactive queue and will be removed + /// when the epoch starts. + public fun is_current_epoch_validator(pool_address: address): bool acquires ValidatorSet { + assert_stake_pool_exists(pool_address); + let validator_state = get_validator_state(pool_address); + validator_state == VALIDATOR_STATUS_ACTIVE || validator_state == VALIDATOR_STATUS_PENDING_INACTIVE + } + + /// Update the validator performance (proposal statistics). This is only called by block::prologue(). + /// This function cannot abort. + public(friend) fun update_performance_statistics(proposer_index: Option, failed_proposer_indices: vector) acquires ValidatorPerformance { + // Validator set cannot change until the end of the epoch, so the validator index in arguments should + // match with those of the validators in ValidatorPerformance resource. + let validator_perf = borrow_global_mut(@aptos_framework); + let validator_len = vector::length(&validator_perf.validators); + + // proposer_index is an option because it can be missing (for NilBlocks) + if (option::is_some(&proposer_index)) { + let cur_proposer_index = option::extract(&mut proposer_index); + // Here, and in all other vector::borrow, skip any validator indices that are out of bounds, + // this ensures that this function doesn't abort if there are out of bounds errors. + if (cur_proposer_index < validator_len) { + let validator = vector::borrow_mut(&mut validator_perf.validators, cur_proposer_index); + spec { + assume validator.successful_proposals + 1 <= MAX_U64; + }; + validator.successful_proposals = validator.successful_proposals + 1; + }; + }; + + let f = 0; + let f_len = vector::length(&failed_proposer_indices); + while ({ + spec { + invariant len(validator_perf.validators) == validator_len; + }; + f < f_len + }) { + let validator_index = *vector::borrow(&failed_proposer_indices, f); + if (validator_index < validator_len) { + let validator = vector::borrow_mut(&mut validator_perf.validators, validator_index); + spec { + assume validator.failed_proposals + 1 <= MAX_U64; + }; + validator.failed_proposals = validator.failed_proposals + 1; + }; + f = f + 1; + }; + } + + /// Triggers at epoch boundary. This function shouldn't abort. + /// + /// 1. Distribute transaction fees and rewards to stake pools of active and pending inactive validators (requested + /// to leave but not yet removed). + /// 2. Officially move pending active stake to active and move pending inactive stake to inactive. + /// The staking pool's voting power in this new epoch will be updated to the total active stake. + /// 3. Add pending active validators to the active set if they satisfy requirements so they can vote and remove + /// pending inactive validators so they no longer can vote. + /// 4. The validator's voting power in the validator set is updated to be the corresponding staking pool's voting + /// power. + public(friend) fun on_new_epoch() acquires StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let validator_set = borrow_global_mut(@aptos_framework); + let config = staking_config::get(); + let validator_perf = borrow_global_mut(@aptos_framework); + + // Process pending stake and distribute transaction fees and rewards for each currently active validator. + vector::for_each_ref(&validator_set.active_validators, |validator| { + let validator: &ValidatorInfo = validator; + update_stake_pool(validator_perf, validator.addr, &config); + }); + + // Process pending stake and distribute transaction fees and rewards for each currently pending_inactive validator + // (requested to leave but not removed yet). + vector::for_each_ref(&validator_set.pending_inactive, |validator| { + let validator: &ValidatorInfo = validator; + update_stake_pool(validator_perf, validator.addr, &config); + }); + + // Activate currently pending_active validators. + append(&mut validator_set.active_validators, &mut validator_set.pending_active); + + // Officially deactivate all pending_inactive validators. They will now no longer receive rewards. + validator_set.pending_inactive = vector::empty(); + + // Update active validator set so that network address/public key change takes effect. + // Moreover, recalculate the total voting power, and deactivate the validator whose + // voting power is less than the minimum required stake. + let next_epoch_validators = vector::empty(); + let (minimum_stake, _) = staking_config::get_required_stake(&config); + let vlen = vector::length(&validator_set.active_validators); + let total_voting_power = 0; + let i = 0; + while ({ + spec { + invariant spec_validators_are_initialized(next_epoch_validators); + }; + i < vlen + }) { + let old_validator_info = vector::borrow_mut(&mut validator_set.active_validators, i); + let pool_address = old_validator_info.addr; + let validator_config = borrow_global_mut(pool_address); + let stake_pool = borrow_global_mut(pool_address); + let new_validator_info = generate_validator_info(pool_address, stake_pool, *validator_config); + + // A validator needs at least the min stake required to join the validator set. + if (new_validator_info.voting_power >= minimum_stake) { + spec { + assume total_voting_power + new_validator_info.voting_power <= MAX_U128; + }; + total_voting_power = total_voting_power + (new_validator_info.voting_power as u128); + vector::push_back(&mut next_epoch_validators, new_validator_info); + }; + i = i + 1; + }; + + validator_set.active_validators = next_epoch_validators; + validator_set.total_voting_power = total_voting_power; + validator_set.total_joining_power = 0; + + // Update validator indices, reset performance scores, and renew lockups. + validator_perf.validators = vector::empty(); + let recurring_lockup_duration_secs = staking_config::get_recurring_lockup_duration(&config); + let vlen = vector::length(&validator_set.active_validators); + let validator_index = 0; + while ({ + spec { + invariant spec_validators_are_initialized(validator_set.active_validators); + invariant len(validator_set.pending_active) == 0; + invariant len(validator_set.pending_inactive) == 0; + invariant 0 <= validator_index && validator_index <= vlen; + invariant vlen == len(validator_set.active_validators); + invariant forall i in 0..validator_index: + global(validator_set.active_validators[i].addr).validator_index < validator_index; + invariant len(validator_perf.validators) == validator_index; + }; + validator_index < vlen + }) { + let validator_info = vector::borrow_mut(&mut validator_set.active_validators, validator_index); + validator_info.config.validator_index = validator_index; + let validator_config = borrow_global_mut(validator_info.addr); + validator_config.validator_index = validator_index; + + vector::push_back(&mut validator_perf.validators, IndividualValidatorPerformance { + successful_proposals: 0, + failed_proposals: 0, + }); + + // Automatically renew a validator's lockup for validators that will still be in the validator set in the + // next epoch. + let stake_pool = borrow_global_mut(validator_info.addr); + if (stake_pool.locked_until_secs <= timestamp::now_seconds()) { + spec { + assume timestamp::spec_now_seconds() + recurring_lockup_duration_secs <= MAX_U64; + }; + stake_pool.locked_until_secs = + timestamp::now_seconds() + recurring_lockup_duration_secs; + }; + + validator_index = validator_index + 1; + }; + + if (features::periodical_reward_rate_decrease_enabled()) { + // Update rewards rate after reward distribution. + staking_config::calculate_and_save_latest_epoch_rewards_rate(); + }; + } + + /// Update individual validator's stake pool + /// 1. distribute transaction fees to active/pending_inactive delegations + /// 2. distribute rewards to active/pending_inactive delegations + /// 3. process pending_active, pending_inactive correspondingly + /// This function shouldn't abort. + fun update_stake_pool( + validator_perf: &ValidatorPerformance, + pool_address: address, + staking_config: &StakingConfig, + ) acquires StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorFees { + let stake_pool = borrow_global_mut(pool_address); + let validator_config = borrow_global(pool_address); + let cur_validator_perf = vector::borrow(&validator_perf.validators, validator_config.validator_index); + let num_successful_proposals = cur_validator_perf.successful_proposals; + spec { + // The following addition should not overflow because `num_total_proposals` cannot be larger than 86400, + // the maximum number of proposals in a day (1 proposal per second). + assume cur_validator_perf.successful_proposals + cur_validator_perf.failed_proposals <= MAX_U64; + }; + let num_total_proposals = cur_validator_perf.successful_proposals + cur_validator_perf.failed_proposals; + let (rewards_rate, rewards_rate_denominator) = staking_config::get_reward_rate(staking_config); + let rewards_active = distribute_rewards( + &mut stake_pool.active, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + let rewards_pending_inactive = distribute_rewards( + &mut stake_pool.pending_inactive, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + spec { + assume rewards_active + rewards_pending_inactive <= MAX_U64; + }; + let rewards_amount = rewards_active + rewards_pending_inactive; + // Pending active stake can now be active. + coin::merge(&mut stake_pool.active, coin::extract_all(&mut stake_pool.pending_active)); + + // Additionally, distribute transaction fees. + if (features::collect_and_distribute_gas_fees()) { + let fees_table = &mut borrow_global_mut(@aptos_framework).fees_table; + if (table::contains(fees_table, pool_address)) { + let coin = table::remove(fees_table, pool_address); + coin::merge(&mut stake_pool.active, coin); + }; + }; + + // Pending inactive stake is only fully unlocked and moved into inactive if the current lockup cycle has expired + let current_lockup_expiration = stake_pool.locked_until_secs; + if (timestamp::now_seconds() >= current_lockup_expiration) { + coin::merge( + &mut stake_pool.inactive, + coin::extract_all(&mut stake_pool.pending_inactive), + ); + }; + + event::emit_event( + &mut stake_pool.distribute_rewards_events, + DistributeRewardsEvent { + pool_address, + rewards_amount, + }, + ); + } + + /// Calculate the rewards amount. + fun calculate_rewards_amount( + stake_amount: u64, + num_successful_proposals: u64, + num_total_proposals: u64, + rewards_rate: u64, + rewards_rate_denominator: u64, + ): u64 { + spec { + // The following condition must hold because + // (1) num_successful_proposals <= num_total_proposals, and + // (2) `num_total_proposals` cannot be larger than 86400, the maximum number of proposals + // in a day (1 proposal per second), and `num_total_proposals` is reset to 0 every epoch. + assume num_successful_proposals * MAX_REWARDS_RATE <= MAX_U64; + }; + // The rewards amount is equal to (stake amount * rewards rate * performance multiplier). + // We do multiplication in u128 before division to avoid the overflow and minimize the rounding error. + let rewards_numerator = (stake_amount as u128) * (rewards_rate as u128) * (num_successful_proposals as u128); + let rewards_denominator = (rewards_rate_denominator as u128) * (num_total_proposals as u128); + if (rewards_denominator > 0) { + ((rewards_numerator / rewards_denominator) as u64) + } else { + 0 + } + } + + /// Mint rewards corresponding to current epoch's `stake` and `num_successful_votes`. + fun distribute_rewards( + stake: &mut Coin, + num_successful_proposals: u64, + num_total_proposals: u64, + rewards_rate: u64, + rewards_rate_denominator: u64, + ): u64 acquires AptosCoinCapabilities { + let stake_amount = coin::value(stake); + let rewards_amount = if (stake_amount > 0) { + calculate_rewards_amount(stake_amount, num_successful_proposals, num_total_proposals, rewards_rate, rewards_rate_denominator) + } else { + 0 + }; + if (rewards_amount > 0) { + let mint_cap = &borrow_global(@aptos_framework).mint_cap; + let rewards = coin::mint(rewards_amount, mint_cap); + coin::merge(stake, rewards); + }; + rewards_amount + } + + fun append(v1: &mut vector, v2: &mut vector) { + while (!vector::is_empty(v2)) { + vector::push_back(v1, vector::pop_back(v2)); + } + } + + fun find_validator(v: &vector, addr: address): Option { + let i = 0; + let len = vector::length(v); + while ({ + spec { + invariant !(exists j in 0..i: v[j].addr == addr); + }; + i < len + }) { + if (vector::borrow(v, i).addr == addr) { + return option::some(i) + }; + i = i + 1; + }; + option::none() + } + + fun generate_validator_info(addr: address, stake_pool: &StakePool, config: ValidatorConfig): ValidatorInfo { + let voting_power = get_next_epoch_voting_power(stake_pool); + ValidatorInfo { + addr, + voting_power, + config, + } + } + + /// Returns validator's next epoch voting power, including pending_active, active, and pending_inactive stake. + fun get_next_epoch_voting_power(stake_pool: &StakePool): u64 { + let value_pending_active = coin::value(&stake_pool.pending_active); + let value_active = coin::value(&stake_pool.active); + let value_pending_inactive = coin::value(&stake_pool.pending_inactive); + spec { + assume value_pending_active + value_active + value_pending_inactive <= MAX_U64; + }; + value_pending_active + value_active + value_pending_inactive + } + + fun update_voting_power_increase(increase_amount: u64) acquires ValidatorSet { + let validator_set = borrow_global_mut(@aptos_framework); + let voting_power_increase_limit = + (staking_config::get_voting_power_increase_limit(&staking_config::get()) as u128); + validator_set.total_joining_power = validator_set.total_joining_power + (increase_amount as u128); + + // Only validator voting power increase if the current validator set's voting power > 0. + if (validator_set.total_voting_power > 0) { + assert!( + validator_set.total_joining_power <= validator_set.total_voting_power * voting_power_increase_limit / 100, + error::invalid_argument(EVOTING_POWER_INCREASE_EXCEEDS_LIMIT), + ); + } + } + + fun assert_stake_pool_exists(pool_address: address) { + assert!(stake_pool_exists(pool_address), error::invalid_argument(ESTAKE_POOL_DOES_NOT_EXIST)); + } + + /// This provides an ACL for Testnet purposes. In testnet, everyone is a whale, a whale can be a validator. + /// This allows a testnet to bring additional entities into the validator set without compromising the + /// security of the testnet. This will NOT be enabled in Mainnet. + struct AllowedValidators has key { + accounts: vector
, + } + + public fun configure_allowed_validators(aptos_framework: &signer, accounts: vector
) acquires AllowedValidators { + let aptos_framework_address = signer::address_of(aptos_framework); + system_addresses::assert_aptos_framework(aptos_framework); + if (!exists(aptos_framework_address)) { + move_to(aptos_framework, AllowedValidators { accounts }); + } else { + let allowed = borrow_global_mut(aptos_framework_address); + allowed.accounts = accounts; + } + } + + fun is_allowed(account: address): bool acquires AllowedValidators { + if (!exists(@aptos_framework)) { + true + } else { + let allowed = borrow_global(@aptos_framework); + vector::contains(&allowed.accounts, &account) + } + } + + fun assert_owner_cap_exists(owner: address) { + assert!(exists(owner), error::not_found(EOWNER_CAP_NOT_FOUND)); + } + + // Will be deleted after transaction_fee has its own MintCap for storage refunds. + public(friend) fun copy_aptos_coin_mint_cap_for_storage_refund(): MintCapability acquires AptosCoinCapabilities { + borrow_global(@aptos_framework).mint_cap + } + + #[test_only] + use aptos_framework::aptos_coin; + use aptos_std::bls12381::proof_of_possession_from_bytes; + #[test_only] + use aptos_std::fixed_point64; + + #[test_only] + const EPOCH_DURATION: u64 = 60; + + #[test_only] + const LOCKUP_CYCLE_SECONDS: u64 = 3600; + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer) { + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 1000000); + } + + #[test_only] + public fun join_validator_set_for_test( + pk: &bls12381::PublicKey, + pop: &bls12381::ProofOfPossession, + operator: &signer, + pool_address: address, + should_end_epoch: bool, + ) acquires AptosCoinCapabilities, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let pk_bytes = bls12381::public_key_to_bytes(pk); + let pop_bytes = bls12381::proof_of_possession_to_bytes(pop); + rotate_consensus_key(operator, pool_address, pk_bytes, pop_bytes); + join_validator_set(operator, pool_address); + if (should_end_epoch) { + end_epoch(); + } + } + + #[test_only] + public fun fast_forward_to_unlock(pool_address: address) + acquires AptosCoinCapabilities, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let expiration_time = get_lockup_secs(pool_address); + timestamp::update_global_time_for_test_secs(expiration_time); + end_epoch(); + } + + // Convenient function for setting up all required stake initializations. + #[test_only] + public fun initialize_for_test_custom( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_secs: u64, + allow_validator_set_change: bool, + rewards_rate_numerator: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + timestamp::set_time_has_started_for_testing(aptos_framework); + if (!exists(@aptos_framework)) { + initialize(aptos_framework); + }; + staking_config::initialize_for_test( + aptos_framework, + minimum_stake, + maximum_stake, + recurring_lockup_secs, + allow_validator_set_change, + rewards_rate_numerator, + rewards_rate_denominator, + voting_power_increase_limit, + ); + + if (!exists(@aptos_framework)) { + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + coin::destroy_burn_cap(burn_cap); + }; + } + + // This function assumes the stake module already the capability to mint aptos coins. + #[test_only] + public fun mint_coins(amount: u64): Coin acquires AptosCoinCapabilities { + let mint_cap = &borrow_global(@aptos_framework).mint_cap; + coin::mint(amount, mint_cap) + } + + #[test_only] + public fun mint(account: &signer, amount: u64) acquires AptosCoinCapabilities { + coin::register(account); + coin::deposit(signer::address_of(account), mint_coins(amount)); + } + + #[test_only] + public fun mint_and_add_stake( + account: &signer, amount: u64) acquires AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorSet { + mint(account, amount); + add_stake(account, amount); + } + + #[test_only] + public fun initialize_test_validator( + public_key: &bls12381::PublicKey, + proof_of_possession: &bls12381::ProofOfPossession, + validator: &signer, + amount: u64, + should_join_validator_set: bool, + should_end_epoch: bool, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let validator_address = signer::address_of(validator); + if (!account::exists_at(signer::address_of(validator))) { + account::create_account_for_test(validator_address); + }; + + let pk_bytes = bls12381::public_key_to_bytes(public_key); + let pop_bytes = bls12381::proof_of_possession_to_bytes(proof_of_possession); + initialize_validator(validator, pk_bytes, pop_bytes, vector::empty(), vector::empty()); + + if (amount > 0) { + mint_and_add_stake(validator, amount); + }; + + if (should_join_validator_set) { + join_validator_set(validator, validator_address); + }; + if (should_end_epoch) { + end_epoch(); + }; + } + + #[test_only] + public fun create_validator_set( + aptos_framework: &signer, + active_validator_addresses: vector
, + public_keys: vector, + ) { + let active_validators = vector::empty(); + let i = 0; + while (i < vector::length(&active_validator_addresses)) { + let validator_address = vector::borrow(&active_validator_addresses, i); + let pk = vector::borrow(&public_keys, i); + vector::push_back(&mut active_validators, ValidatorInfo { + addr: *validator_address, + voting_power: 0, + config: ValidatorConfig { + consensus_pubkey: bls12381::public_key_to_bytes(pk), + network_addresses: b"", + fullnode_addresses: b"", + validator_index: 0, + } + }); + i = i + 1; + }; + + move_to(aptos_framework, ValidatorSet { + consensus_scheme: 0, + // active validators for the current epoch + active_validators, + // pending validators to leave in next epoch (still active) + pending_inactive: vector::empty(), + // pending validators to join in next epoch + pending_active: vector::empty(), + total_voting_power: 0, + total_joining_power: 0, + }); + } + + #[test_only] + public fun create_stake_pool( + account: &signer, + active: Coin, + pending_inactive: Coin, + locked_until_secs: u64, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + let account_address = signer::address_of(account); + initialize_stake_owner(account, 0, account_address, account_address); + let stake_pool = borrow_global_mut(account_address); + coin::merge(&mut stake_pool.active, active); + coin::merge(&mut stake_pool.pending_inactive, pending_inactive); + stake_pool.locked_until_secs = locked_until_secs; + } + + // Allows unit tests to set custom validator performances. + #[test_only] + public fun update_validator_performances_for_test( + proposer_index: Option, + failed_proposer_indices: vector, + ) acquires ValidatorPerformance { + update_performance_statistics(proposer_index, failed_proposer_indices); + } + + #[test_only] + public fun generate_identity(): (bls12381::SecretKey, bls12381::PublicKey, bls12381::ProofOfPossession) { + let (sk, pkpop) = bls12381::generate_keys(); + let pop = bls12381::generate_proof_of_possession(&sk); + let unvalidated_pk = bls12381::public_key_with_pop_to_normal(&pkpop); + (sk, unvalidated_pk, pop) + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_inactive_validator_can_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Add more stake to exceed max. This should fail. + mint_and_add_stake(validator, 9901); + } + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_pending_active_validator_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 100000); + // Have one validator join the set to ensure the validator set is not empty when main validator joins. + let (_sk_1, pk_1, pop_1) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, true); + + // Validator 2 joins validator set but epoch has not ended so validator is in pending_active state. + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, false); + + // Add more stake to exceed max. This should fail. + mint_and_add_stake(validator_2, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_active_validator_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Validator joins validator set and waits for epoch end so it's in the validator set. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Add more stake to exceed max. This should fail. + mint_and_add_stake(validator, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_active_validator_with_pending_inactive_stake_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Validator joins validator set and waits for epoch end so it's in the validator set. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Request to unlock 50 coins, which go to pending_inactive. Validator has 50 remaining in active. + unlock(validator, 50); + assert_validator_state(signer::address_of(validator), 50, 0, 0, 50, 0); + + // Add 9901 more. Total stake is 50 (active) + 50 (pending_inactive) + 9901 > 10000 so still exceeding max. + mint_and_add_stake(validator, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_pending_inactive_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Leave validator set so validator is in pending_inactive state. + leave_validator_set(validator_1, signer::address_of(validator_1)); + + // Add 9901 more. Total stake is 50 (active) + 50 (pending_inactive) + 9901 > 10000 so still exceeding max. + mint_and_add_stake(validator_1, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_end_to_end( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Validator has a lockup now that they've joined the validator set. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 1); + + // Validator adds more stake while already being active. + // The added stake should go to pending_active to wait for activation when next epoch starts. + mint(validator, 900); + add_stake(validator, 100); + assert!(coin::balance(validator_address) == 800, 2); + assert_validator_state(validator_address, 100, 0, 100, 0, 0); + + // Pending_active stake is activated in the new epoch. + // Rewards of 1 coin are also distributed for the existing active stake of 100 coins. + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 3); + assert_validator_state(validator_address, 201, 0, 0, 0, 0); + + // Request unlock of 100 coins. These 100 coins are moved to pending_inactive and will be unlocked when the + // current lockup expires. + unlock(validator, 100); + assert_validator_state(validator_address, 101, 0, 0, 100, 0); + + // Enough time has passed so the current lockup cycle should have ended. + // The first epoch after the lockup cycle ended should automatically move unlocked (pending_inactive) stake + // to inactive. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + // Rewards were also minted to pending_inactive, which got all moved to inactive. + assert_validator_state(validator_address, 102, 101, 0, 0, 0); + // Lockup is renewed and validator is still active. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 4); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 5); + + // Validator withdraws from inactive stake multiple times. + withdraw(validator, 50); + assert!(coin::balance(validator_address) == 850, 6); + assert_validator_state(validator_address, 102, 51, 0, 0, 0); + withdraw(validator, 51); + assert!(coin::balance(validator_address) == 901, 7); + assert_validator_state(validator_address, 102, 0, 0, 0, 0); + + // Enough time has passed again and the validator's lockup is renewed once more. Validator is still active. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 8); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 9); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_inactive_validator_with_existing_lockup_join_validator_set( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Validator sets lockup before even joining the set and lets half of lockup pass by. + increase_lockup(validator); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS / 2); + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS / 2, 1); + + // Join the validator set with an existing lockup + join_validator_set(validator, validator_address); + + // Validator is added to the set but lockup time shouldn't have changed. + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS / 2 - EPOCH_DURATION, 3); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10012, location = Self)] + public entry fun test_cannot_reduce_lockup( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Increase lockup. + increase_lockup(validator); + // Reduce recurring lockup to 0. + staking_config::update_recurring_lockup_duration_secs(aptos_framework, 1); + // INcrease lockup should now fail because the new lockup < old lockup. + increase_lockup(validator); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_inactive_validator_cannot_join_if_exceed_increase_limit( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + + // Validator 1 needs to be in the set so validator 2's added stake counts against the limit. + join_validator_set(validator_1, signer::address_of(validator_1)); + end_epoch(); + + // Validator 2 joins the validator set but their stake would lead to exceeding the voting power increase limit. + // Therefore, this should fail. + join_validator_set(validator_2, signer::address_of(validator_2)); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_pending_active_validator_can_add_more_stake( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 10000); + // Need 1 validator to be in the active validator set so joining limit works. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, true); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + + // Add more stake while still pending_active. + let validator_2_address = signer::address_of(validator_2); + join_validator_set(validator_2, validator_2_address); + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 0); + mint_and_add_stake(validator_2, 100); + assert_validator_state(validator_2_address, 200, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_pending_active_validator_cannot_add_more_stake_than_limit( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // 100% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 100); + // Need 1 validator to be in the active validator set so joining limit works. + let (_sk_1, pk_1, pop_1) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, true); + + // Validator 2 joins the validator set but epoch has not ended so they're still pending_active. + // Current voting power increase is already 100%. This is not failing yet. + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, false); + + // Add more stake, which now exceeds the 100% limit. This should fail. + mint_and_add_stake(validator_2, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_pending_active_validator_leaves_validator_set( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Validator joins but epoch hasn't ended, so the validator is still pending_active. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, false); + let validator_address = signer::address_of(validator); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 0); + + // Check that voting power increase is tracked. + assert!(borrow_global(@aptos_framework).total_joining_power == 100, 0); + + // Leave the validator set immediately. + leave_validator_set(validator, validator_address); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 1); + + // Check that voting power increase has been decreased when the pending active validator leaves. + assert!(borrow_global(@aptos_framework).total_joining_power == 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_active_validator_cannot_add_more_stake_than_limit_in_multiple_epochs( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + // Add initial stake and join the validator set. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + let validator_address = signer::address_of(validator); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + end_epoch(); + assert_validator_state(validator_address, 110, 0, 0, 0, 0); + end_epoch(); + assert_validator_state(validator_address, 121, 0, 0, 0, 0); + // Add more than 50% limit. The following line should fail. + mint_and_add_stake(validator, 99); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_active_validator_cannot_add_more_stake_than_limit( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Add more than 50% limit. This should fail. + mint_and_add_stake(validator, 51); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_unlock_partial_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Reward rate = 10%. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 100); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Unlock half of the coins. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 1); + unlock(validator, 50); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + + // Enough time has passed so the current lockup cycle should have ended. + // 50 coins should have unlocked while the remaining 51 (50 + rewards) should stay locked for another cycle. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + // Validator received rewards in both active and pending inactive. + assert_validator_state(validator_address, 55, 55, 0, 0, 0); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 3); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_can_withdraw_all_stake_and_rewards_at_once( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 0); + + // One more epoch passes to generate rewards. + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 1); + assert_validator_state(validator_address, 101, 0, 0, 0, 0); + + // Unlock all coins while still having a lockup. + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS - EPOCH_DURATION, 2); + unlock(validator, 101); + assert_validator_state(validator_address, 0, 0, 0, 101, 0); + + // One more epoch passes while the current lockup cycle (3600 secs) has not ended. + timestamp::fast_forward_seconds(1000); + end_epoch(); + // Validator should not be removed from the validator set since their 100 coins in pending_inactive state should + // still count toward voting power. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 3); + assert_validator_state(validator_address, 0, 0, 0, 102, 0); + + // Enough time has passed so the current lockup cycle should have ended. Funds are now fully unlocked. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert_validator_state(validator_address, 0, 103, 0, 0, 0); + // Validator ahs been kicked out of the validator set as their stake is 0 now. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 4); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_unlocking_more_than_available_stake_should_cap( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Validator unlocks more stake than they have active. This should limit the unlock to 100. + unlock(validator, 200); + assert_validator_state(signer::address_of(validator), 0, 0, 0, 100, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_withdraw_should_cap_by_inactive_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Initial balance = 900 (idle) + 100 (staked) = 1000. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + mint(validator, 900); + + // Validator unlocks stake. + unlock(validator, 100); + // Enough time has passed so the stake is fully unlocked. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + + // Validator can only withdraw a max of 100 unlocked coins even if they request to withdraw more than 100. + withdraw(validator, 200); + let validator_address = signer::address_of(validator); + // Receive back all coins with an extra 1 for rewards. + assert!(coin::balance(validator_address) == 1001, 2); + assert_validator_state(validator_address, 0, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_can_reactivate_pending_inactive_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Validator unlocks stake, which gets moved into pending_inactive. + unlock(validator, 50); + let validator_address = signer::address_of(validator); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + + // Validator can reactivate pending_inactive stake. + reactivate_stake(validator, 50); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_reactivate_more_than_available_pending_inactive_stake_should_cap( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Validator tries to reactivate more than available pending_inactive stake, which should limit to 50. + unlock(validator, 50); + let validator_address = signer::address_of(validator); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + reactivate_stake(validator, 51); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_having_insufficient_remaining_stake_after_withdrawal_gets_kicked( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Unlock enough coins that the remaining is not enough to meet the min required. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 1); + unlock(validator, 50); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + + // Enough time has passed so the current lockup cycle should have ended. + // 50 coins should have unlocked while the remaining 51 (50 + rewards) is not enough so the validator is kicked + // from the validator set. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 2); + assert_validator_state(validator_address, 50, 50, 0, 0, 0); + // Lockup is no longer renewed since the validator is no longer a part of the validator set. + assert!(get_remaining_lockup_secs(validator_address) == 0, 3); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, validator_2 = @0x234)] + public entry fun test_active_validator_leaves_staking_but_still_has_a_lockup( + aptos_framework: &signer, + validator: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator, 100, true, false); + // We need a second validator here just so the first validator can leave. + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Leave the validator set while still having a lockup. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 0); + leave_validator_set(validator, validator_address); + // Validator is in pending_inactive state but is technically still part of the validator set. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_PENDING_INACTIVE, 2); + assert_validator_state(validator_address, 100, 0, 0, 0, 1); + end_epoch(); + + // Epoch has ended so validator is no longer part of the validator set. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 3); + // However, their stake, including rewards, should still subject to the existing lockup. + assert_validator_state(validator_address, 101, 0, 0, 0, 1); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS - EPOCH_DURATION, 4); + + // If they try to unlock, their stake is moved to pending_inactive and would only be withdrawable after the + // lockup has expired. + unlock(validator, 50); + assert_validator_state(validator_address, 51, 0, 0, 50, 1); + // A couple of epochs passed but lockup has not expired so the validator's stake remains the same. + end_epoch(); + end_epoch(); + end_epoch(); + assert_validator_state(validator_address, 51, 0, 0, 50, 1); + // Fast forward enough so the lockup expires. Now the validator can just call withdraw directly to withdraw + // pending_inactive stakes. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + withdraw(validator, 50); + assert_validator_state(validator_address, 51, 0, 0, 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, validator_2 = @0x234)] + public entry fun test_active_validator_leaves_staking_and_rejoins_with_expired_lockup_should_be_renewed( + aptos_framework: &signer, + validator: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator, 100, true, false); + // We need a second validator here just so the first validator can leave. + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Leave the validator set while still having a lockup. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 0); + leave_validator_set(validator, validator_address); + end_epoch(); + + // Fast forward enough so the lockup expires. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + assert!(get_remaining_lockup_secs(validator_address) == 0, 1); + + // Validator rejoins the validator set. Once the current epoch ends, their lockup should be automatically + // renewed. + join_validator_set(validator, validator_address); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 2); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_pending_inactive_validator_does_not_count_in_increase_limit( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + // We need a second validator here just so the first validator can leave. + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Validator 1 leaves the validator set. Epoch has not ended so they're still pending_inactive. + leave_validator_set(validator_1, signer::address_of(validator_1)); + // Validator 1 adds more stake. This should not succeed as it should not count as a voting power increase. + mint_and_add_stake(validator_1, 51); + } + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234, validator_3 = @0x345)] + public entry fun test_multiple_validators_join_and_leave( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + validator_3: &signer + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + let validator_3_address = signer::address_of(validator_3); + + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let pk_1_bytes = bls12381::public_key_to_bytes(&pk_1); + let (_sk_2, pk_2, pop_2) = generate_identity(); + let (_sk_3, pk_3, pop_3) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + initialize_test_validator(&pk_3, &pop_3, validator_3, 100, false, false); + + // Validator 1 and 2 join the validator set. + join_validator_set(validator_2, validator_2_address); + join_validator_set(validator_1, validator_1_address); + end_epoch(); + assert!(get_validator_state(validator_1_address) == VALIDATOR_STATUS_ACTIVE, 0); + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Validator indices is the reverse order of the joining order. + assert_validator_state(validator_1_address, 100, 0, 0, 0, 0); + assert_validator_state(validator_2_address, 100, 0, 0, 0, 1); + let validator_set = borrow_global(@aptos_framework); + let validator_config_1 = vector::borrow(&validator_set.active_validators, 0); + assert!(validator_config_1.addr == validator_1_address, 2); + assert!(validator_config_1.config.validator_index == 0, 3); + let validator_config_2 = vector::borrow(&validator_set.active_validators, 1); + assert!(validator_config_2.addr == validator_2_address, 4); + assert!(validator_config_2.config.validator_index == 1, 5); + + // Validator 1 rotates consensus key. Validator 2 leaves. Validator 3 joins. + let (_sk_1b, pk_1b, pop_1b) = generate_identity(); + let pk_1b_bytes = bls12381::public_key_to_bytes(&pk_1b); + let pop_1b_bytes = bls12381::proof_of_possession_to_bytes(&pop_1b); + rotate_consensus_key(validator_1, validator_1_address, pk_1b_bytes, pop_1b_bytes); + leave_validator_set(validator_2, validator_2_address); + join_validator_set(validator_3, validator_3_address); + // Validator 2 is not effectively removed until next epoch. + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_PENDING_INACTIVE, 6); + assert!(vector::borrow(&borrow_global(@aptos_framework).pending_inactive, 0).addr == validator_2_address, 0); + // Validator 3 is not effectively added until next epoch. + assert!(get_validator_state(validator_3_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 7); + assert!(vector::borrow(&borrow_global(@aptos_framework).pending_active, 0).addr == validator_3_address, 0); + assert!(vector::borrow(&borrow_global(@aptos_framework).active_validators, 0).config.consensus_pubkey == pk_1_bytes, 0); + + // Changes applied after new epoch + end_epoch(); + assert!(get_validator_state(validator_1_address) == VALIDATOR_STATUS_ACTIVE, 8); + assert_validator_state(validator_1_address, 101, 0, 0, 0, 0); + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_INACTIVE, 9); + // The validator index of validator 2 stays the same but this doesn't matter as the next time they rejoin the + // validator set, their index will get set correctly. + assert_validator_state(validator_2_address, 101, 0, 0, 0, 1); + assert!(get_validator_state(validator_3_address) == VALIDATOR_STATUS_ACTIVE, 10); + assert_validator_state(validator_3_address, 100, 0, 0, 0, 1); + assert!(vector::borrow(&borrow_global(@aptos_framework).active_validators, 0).config.consensus_pubkey == pk_1b_bytes, 0); + + // Validators without enough stake will be removed. + unlock(validator_1, 50); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_1_address) == VALIDATOR_STATUS_INACTIVE, 11); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_delegated_staking_with_owner_cap( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 0, false, false); + let owner_cap = extract_owner_cap(validator); + + // Add stake when the validator is not yet activated. + add_stake_with_cap(&owner_cap, mint_coins(100)); + let pool_address = signer::address_of(validator); + assert_validator_state(pool_address, 100, 0, 0, 0, 0); + + // Join the validator set with enough stake. + join_validator_set(validator, pool_address); + end_epoch(); + assert!(get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + + // Unlock the entire stake. + unlock_with_cap(100, &owner_cap); + assert_validator_state(pool_address, 0, 0, 0, 100, 0); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + + // Withdraw stake + rewards. + assert_validator_state(pool_address, 0, 101, 0, 0, 0); + let coins = withdraw_with_cap(&owner_cap, 101); + assert!(coin::value(&coins) == 101, 1); + assert_validator_state(pool_address, 0, 0, 0, 0, 0); + + // Operator can separately rotate consensus key. + let (_sk_new, pk_new, pop_new) = generate_identity(); + let pk_new_bytes = bls12381::public_key_to_bytes(&pk_new); + let pop_new_bytes = bls12381::proof_of_possession_to_bytes(&pop_new); + rotate_consensus_key(validator, pool_address, pk_new_bytes, pop_new_bytes); + let validator_config = borrow_global(pool_address); + assert!(validator_config.consensus_pubkey == pk_new_bytes, 2); + + // Operator can update network and fullnode addresses. + update_network_and_fullnode_addresses(validator, pool_address, b"1", b"2"); + let validator_config = borrow_global(pool_address); + assert!(validator_config.network_addresses == b"1", 3); + assert!(validator_config.fullnode_addresses == b"2", 4); + + // Cleanups. + coin::register(validator); + coin::deposit(pool_address, coins); + deposit_owner_cap(validator, owner_cap); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000A, location = Self)] + public entry fun test_validator_cannot_join_post_genesis( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, false, 1, 100, 100); + + // Joining the validator set should fail as post genesis validator set change is not allowed. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000E, location = Self)] + public entry fun test_invalid_pool_address( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + join_validator_set(validator, @0x234); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000A, location = Self)] + public entry fun test_validator_cannot_leave_post_genesis( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, false, 1, 100, 100); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Bypass the check to join. This is the same function called during Genesis. + let validator_address = signer::address_of(validator); + join_validator_set_internal(validator, validator_address); + end_epoch(); + + // Leaving the validator set should fail as post genesis validator set change is not allowed. + leave_validator_set(validator, validator_address); + } + + #[test( + aptos_framework = @aptos_framework, + validator_1 = @aptos_framework, + validator_2 = @0x2, + validator_3 = @0x3, + validator_4 = @0x4, + validator_5 = @0x5 + )] + public entry fun test_staking_validator_index( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + validator_3: &signer, + validator_4: &signer, + validator_5: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let v1_addr = signer::address_of(validator_1); + let v2_addr = signer::address_of(validator_2); + let v3_addr = signer::address_of(validator_3); + let v4_addr = signer::address_of(validator_4); + let v5_addr = signer::address_of(validator_5); + + initialize_for_test(aptos_framework); + + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + let (_sk_3, pk_3, pop_3) = generate_identity(); + let (_sk_4, pk_4, pop_4) = generate_identity(); + let (_sk_5, pk_5, pop_5) = generate_identity(); + + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + initialize_test_validator(&pk_3, &pop_3, validator_3, 100, false, false); + initialize_test_validator(&pk_4, &pop_4, validator_4, 100, false, false); + initialize_test_validator(&pk_5, &pop_5, validator_5, 100, false, false); + + join_validator_set(validator_3, v3_addr); + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 0); + + join_validator_set(validator_4, v4_addr); + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 1); + assert!(get_validator_index(v4_addr) == 1, 2); + + join_validator_set(validator_1, v1_addr); + join_validator_set(validator_2, v2_addr); + // pending_inactive is appended in reverse order + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 6); + assert!(get_validator_index(v4_addr) == 1, 7); + assert!(get_validator_index(v2_addr) == 2, 8); + assert!(get_validator_index(v1_addr) == 3, 9); + + join_validator_set(validator_5, v5_addr); + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 10); + assert!(get_validator_index(v4_addr) == 1, 11); + assert!(get_validator_index(v2_addr) == 2, 12); + assert!(get_validator_index(v1_addr) == 3, 13); + assert!(get_validator_index(v5_addr) == 4, 14); + + // after swap remove, it's 3,4,2,5 + leave_validator_set(validator_1, v1_addr); + // after swap remove, it's 5,4,2 + leave_validator_set(validator_3, v3_addr); + end_epoch(); + + assert!(get_validator_index(v5_addr) == 0, 15); + assert!(get_validator_index(v4_addr) == 1, 16); + assert!(get_validator_index(v2_addr) == 2, 17); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_validator_rewards_are_performance_based( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + + // Both validators join the set. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Validator 2 failed proposal. + let failed_proposer_indices = vector::empty(); + let validator_1_index = borrow_global(validator_1_address).validator_index; + let validator_2_index = borrow_global(validator_2_address).validator_index; + vector::push_back(&mut failed_proposer_indices, validator_2_index); + let proposer_indices = option::some(validator_1_index); + update_performance_statistics(proposer_indices, failed_proposer_indices); + end_epoch(); + + // Validator 2 received no rewards. Validator 1 didn't fail proposals, so it still receives rewards. + assert_validator_state(validator_1_address, 101, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 100, 0, 0, 0, 0); + + // Validator 2 decides to leave. Both validators failed proposals. + unlock(validator_2, 100); + leave_validator_set(validator_2, validator_2_address); + let failed_proposer_indices = vector::empty(); + let validator_1_index = borrow_global(validator_1_address).validator_index; + let validator_2_index = borrow_global(validator_2_address).validator_index; + vector::push_back(&mut failed_proposer_indices, validator_1_index); + vector::push_back(&mut failed_proposer_indices, validator_2_index); + update_performance_statistics(option::none(), failed_proposer_indices); + // Fast forward so validator 2's stake is fully unlocked. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + + // Validator 1 and 2 received no additional rewards due to failed proposals + assert_validator_state(validator_1_address, 101, 0, 0, 0, 0); + assert_validator_state(validator_2_address, 0, 100, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_validator_rewards_rate_decrease_over_time( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + + let genesis_time_in_secs = timestamp::now_seconds(); + + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + + // Both validators join the set. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 1000, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 10000, true, true); + + // One epoch passed. Validator 1 and validator 2 should receive rewards at rewards rate = 1% every epoch. + end_epoch(); + assert_validator_state(validator_1_address, 1010, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10100, 0, 0, 0, 0); + + // Enable rewards rate decrease. Initially rewards rate is still 1% every epoch. Rewards rate halves every year. + let one_year_in_secs: u64 = 31536000; + staking_config::initialize_rewards( + aptos_framework, + fixed_point64::create_from_rational(1, 100), + fixed_point64::create_from_rational(3, 1000), + one_year_in_secs, + genesis_time_in_secs, + fixed_point64::create_from_rational(50, 100), + ); + features::change_feature_flags(aptos_framework, vector[features::get_periodical_reward_rate_decrease_feature()], vector[]); + + // For some reason, this epoch is very long. It has been 1 year since genesis when the epoch ends. + timestamp::fast_forward_seconds(one_year_in_secs - EPOCH_DURATION * 3); + end_epoch(); + // Validator 1 and validator 2 should still receive rewards at rewards rate = 1% every epoch. Rewards rate has halved after this epoch. + assert_validator_state(validator_1_address, 1020, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10200, 0, 0, 0, 0); + + // For some reason, this epoch is also very long. One year passed. + timestamp::fast_forward_seconds(one_year_in_secs - EPOCH_DURATION); + end_epoch(); + // Validator 1 and validator 2 should still receive rewards at rewards rate = 0.5% every epoch. Rewards rate has halved after this epoch. + assert_validator_state(validator_1_address, 1025, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10250, 0, 0, 0, 0); + + end_epoch(); + // Rewards rate has halved but cannot become lower than min_rewards_rate. + // Validator 1 and validator 2 should receive rewards at rewards rate = 0.3% every epoch. + assert_validator_state(validator_1_address, 1028, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10280, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_update_performance_statistics_should_not_fail_due_to_out_of_bounds( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + let valid_validator_index = borrow_global(validator_address).validator_index; + let out_of_bounds_index = valid_validator_index + 100; + + // Invalid validator index in the failed proposers vector should not lead to abort. + let failed_proposer_indices = vector::empty(); + vector::push_back(&mut failed_proposer_indices, valid_validator_index); + vector::push_back(&mut failed_proposer_indices, out_of_bounds_index); + update_performance_statistics(option::none(), failed_proposer_indices); + end_epoch(); + + // Validator received no rewards due to failing to propose. + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + + // Invalid validator index in the proposer should not lead to abort. + let proposer_index_optional = option::some(out_of_bounds_index); + update_performance_statistics(proposer_index_optional, vector::empty()); + end_epoch(); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_invalid_config( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorSet { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + + // Call initialize_stake_owner, which only initializes the stake pool but not validator config. + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + initialize_stake_owner(validator, 0, validator_address, validator_address); + mint_and_add_stake(validator, 100); + + // Join the validator set with enough stake. This should fail because the validator didn't initialize validator + // config. + join_validator_set(validator, validator_address); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_valid_config( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorSet { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + + // Call initialize_stake_owner, which only initializes the stake pool but not validator config. + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + initialize_stake_owner(validator, 0, validator_address, validator_address); + mint_and_add_stake(validator, 100); + + // Initialize validator config. + let validator_address = signer::address_of(validator); + let (_sk_new, pk_new, pop_new) = generate_identity(); + let pk_new_bytes = bls12381::public_key_to_bytes(&pk_new); + let pop_new_bytes = bls12381::proof_of_possession_to_bytes(&pop_new); + rotate_consensus_key(validator, validator_address, pk_new_bytes, pop_new_bytes); + + // Join the validator set with enough stake. This now wouldn't fail since the validator config already exists. + join_validator_set(validator, validator_address); + } + + #[test] + public entry fun test_rewards_calculation() { + let stake_amount = 2000; + let num_successful_proposals = 199; + let num_total_proposals = 200; + let rewards_rate = 700; + let rewards_rate_denominator = 777; + let rewards_amount = calculate_rewards_amount( + stake_amount, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + // Consider `amount_imprecise` and `amount_precise` defined as follows: + // amount_imprecise = (stake_amount * rewards_rate / rewards_rate_denominator) * num_successful_proposals / num_total_proposals + // amount_precise = stake_amount * rewards_rate * num_successful_proposals / (rewards_rate_denominator * num_total_proposals) + // Although they are equivalent in the real arithmetic, they are not in the integer arithmetic due to a rounding error. + // With the test parameters above, `amount_imprecise` is equal to 1791 because of an unbounded rounding error + // while `amount_precise` is equal to 1792. We expect the output of `calculate_rewards_amount` to be 1792. + assert!(rewards_amount == 1792, 0); + + let stake_amount = 100000000000000000; + let num_successful_proposals = 9999; + let num_total_proposals = 10000; + let rewards_rate = 3141592; + let rewards_rate_denominator = 10000000; + // This should not abort due to an arithmetic overflow. + let rewards_amount = calculate_rewards_amount( + stake_amount, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + assert!(rewards_amount == 31412778408000000, 0); + } + + #[test_only] + public fun set_validator_perf_at_least_one_block() acquires ValidatorPerformance { + let validator_perf = borrow_global_mut(@aptos_framework); + vector::for_each_mut(&mut validator_perf.validators, |validator|{ + let validator: &mut IndividualValidatorPerformance = validator; + if (validator.successful_proposals + validator.failed_proposals < 1) { + validator.successful_proposals = 1; + }; + }); + } + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_removing_validator_from_active_set( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + assert!(vector::length(&borrow_global(@aptos_framework).active_validators) == 2, 0); + + // Remove validator 1 from the active validator set. Only validator 2 remains. + let validator_to_remove = signer::address_of(validator_1); + remove_validators(aptos_framework, &vector[validator_to_remove]); + assert!(vector::length(&borrow_global(@aptos_framework).active_validators) == 1, 0); + assert!(get_validator_state(validator_to_remove) == VALIDATOR_STATUS_PENDING_INACTIVE, 1); + } + + #[test_only] + public fun end_epoch() acquires StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Set the number of blocks to 1, to give out rewards to non-failing validators. + set_validator_perf_at_least_one_block(); + timestamp::fast_forward_seconds(EPOCH_DURATION); + on_new_epoch(); + } + + #[test_only] + public fun assert_stake_pool( + pool_address: address, + active_stake: u64, + inactive_stake: u64, + pending_active_stake: u64, + pending_inactive_stake: u64, + ) acquires StakePool { + let stake_pool = borrow_global(pool_address); + let actual_active_stake = coin::value(&stake_pool.active); + assert!(actual_active_stake == active_stake, actual_active_stake); + let actual_inactive_stake = coin::value(&stake_pool.inactive); + assert!(actual_inactive_stake == inactive_stake, actual_inactive_stake); + let actual_pending_active_stake = coin::value(&stake_pool.pending_active); + assert!(actual_pending_active_stake == pending_active_stake, actual_pending_active_stake); + let actual_pending_inactive_stake = coin::value(&stake_pool.pending_inactive); + assert!(actual_pending_inactive_stake == pending_inactive_stake, actual_pending_inactive_stake); + } + + #[test_only] + public fun assert_validator_state( + pool_address: address, + active_stake: u64, + inactive_stake: u64, + pending_active_stake: u64, + pending_inactive_stake: u64, + validator_index: u64, + ) acquires StakePool, ValidatorConfig { + assert_stake_pool(pool_address, active_stake, inactive_stake, pending_active_stake, pending_inactive_stake); + let validator_config = borrow_global(pool_address); + assert!(validator_config.validator_index == validator_index, validator_config.validator_index); + } + + #[test(aptos_framework = @0x1, validator = @0x123)] + public entry fun test_allowed_validators( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + let addr = signer::address_of(validator); + configure_allowed_validators(aptos_framework, vector[addr]); + + account::create_account_for_test(addr); + coin::register(validator); + initialize_stake_owner(validator, 0, addr, addr); + } + + #[test(aptos_framework = @0x1, validator = @0x123)] + #[expected_failure(abort_code = 0x60011, location = Self)] + public entry fun test_not_allowed_validators( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + configure_allowed_validators(aptos_framework, vector[]); + + let addr = signer::address_of(validator); + account::create_account_for_test(addr); + coin::register(validator); + initialize_stake_owner(validator, 0, addr, addr); + } + + #[test_only] + public fun with_rewards(amount: u64): u64 { + let (numerator, denominator) = staking_config::get_reward_rate(&staking_config::get()); + amount + amount * numerator / denominator + } + + #[test_only] + public fun get_validator_fee(validator_addr: address): u64 acquires ValidatorFees { + let fees_table = &borrow_global(@aptos_framework).fees_table; + let coin = table::borrow(fees_table, validator_addr); + coin::value(coin) + } + + #[test_only] + public fun assert_no_fees_for_validator(validator_addr: address) acquires ValidatorFees { + let fees_table = &borrow_global(@aptos_framework).fees_table; + assert!(!table::contains(fees_table, validator_addr), 0); + } + + #[test_only] + const COLLECT_AND_DISTRIBUTE_GAS_FEES: u64 = 6; + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234, validator_3 = @0x345)] + fun test_distribute_validator_fees( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + validator_3: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Make sure that fees collection and distribution is enabled. + features::change_feature_flags(aptos_framework, vector[COLLECT_AND_DISTRIBUTE_GAS_FEES], vector[]); + assert!(features::collect_and_distribute_gas_fees(), 0); + + // Initialize staking and validator fees table. + initialize_for_test(aptos_framework); + initialize_validator_fees(aptos_framework); + + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + let validator_3_address = signer::address_of(validator_3); + + // Validators join the set and epoch ends. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + let (_sk_3, pk_3, pop_3) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, false); + initialize_test_validator(&pk_3, &pop_3, validator_3, 100, true, true); + + // Next, simulate fees collection during three blocks, where proposers are + // validators 1, 2, and 1 again. + add_transaction_fee(validator_1_address, mint_coins(100)); + add_transaction_fee(validator_2_address, mint_coins(500)); + add_transaction_fee(validator_1_address, mint_coins(200)); + + // Fess have to be assigned to the right validators, but not + // distributed yet. + assert!(get_validator_fee(validator_1_address) == 300, 0); + assert!(get_validator_fee(validator_2_address) == 500, 0); + assert_no_fees_for_validator(validator_3_address); + assert_validator_state(validator_1_address, 100, 0, 0, 0, 2); + assert_validator_state(validator_2_address, 100, 0, 0, 0, 1); + assert_validator_state(validator_3_address, 100, 0, 0, 0, 0); + + end_epoch(); + + // Epoch ended. Validators must have recieved their rewards and, most importantly, + // their fees. + assert_no_fees_for_validator(validator_1_address); + assert_no_fees_for_validator(validator_2_address); + assert_no_fees_for_validator(validator_3_address); + assert_validator_state(validator_1_address, 401, 0, 0, 0, 2); + assert_validator_state(validator_2_address, 601, 0, 0, 0, 1); + assert_validator_state(validator_3_address, 101, 0, 0, 0, 0); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_config.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_config.move new file mode 100644 index 0000000..12a040c --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_config.move @@ -0,0 +1,680 @@ +/// Provides the configuration for staking and rewards +module aptos_framework::staking_config { + use std::error; + use std::features; + + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + + use aptos_std::fixed_point64::{Self, FixedPoint64, less_or_equal}; + use aptos_std::math_fixed64; + + friend aptos_framework::genesis; + friend aptos_framework::stake; + + /// Stake lockup duration cannot be zero. + const EZERO_LOCKUP_DURATION: u64 = 1; + /// Reward rate denominator cannot be zero. + const EZERO_REWARDS_RATE_DENOMINATOR: u64 = 2; + /// Specified stake range is invalid. Max must be greater than min. + const EINVALID_STAKE_RANGE: u64 = 3; + /// The voting power increase limit percentage must be within (0, 50]. + const EINVALID_VOTING_POWER_INCREASE_LIMIT: u64 = 4; + /// Specified rewards rate is invalid, which must be within [0, MAX_REWARDS_RATE]. + const EINVALID_REWARDS_RATE: u64 = 5; + /// Specified min rewards rate is invalid, which must be within [0, rewards_rate]. + const EINVALID_MIN_REWARDS_RATE: u64 = 6; + /// Specified start time of last rewards rate period is invalid, which must be not late than the current timestamp. + const EINVALID_LAST_REWARDS_RATE_PERIOD_START: u64 = 7; + /// Specified rewards rate decrease rate is invalid, which must be not greater than BPS_DENOMINATOR. + const EINVALID_REWARDS_RATE_DECREASE_RATE: u64 = 8; + /// Specified rewards rate period is invalid. It must be larger than 0 and cannot be changed if configured. + const EINVALID_REWARDS_RATE_PERIOD: u64 = 9; + /// The function has been deprecated. + const EDEPRECATED_FUNCTION: u64 = 10; + /// The function is disabled or hasn't been enabled. + const EDISABLED_FUNCTION: u64 = 11; + + /// Limit the maximum value of `rewards_rate` in order to avoid any arithmetic overflow. + const MAX_REWARDS_RATE: u64 = 1000000; + /// Denominator of number in basis points. 1 bps(basis points) = 0.01%. + const BPS_DENOMINATOR: u64 = 10000; + /// 1 year => 365 * 24 * 60 * 60 + const ONE_YEAR_IN_SECS: u64 = 31536000; + + const MAX_U64: u128 = 18446744073709551615; + + + /// Validator set configurations that will be stored with the @aptos_framework account. + struct StakingConfig has copy, drop, key { + // A validator needs to stake at least this amount to be able to join the validator set. + // If after joining the validator set and at the start of any epoch, a validator's stake drops below this amount + // they will be removed from the set. + minimum_stake: u64, + // A validator can only stake at most this amount. Any larger stake will be rejected. + // If after joining the validator set and at the start of any epoch, a validator's stake exceeds this amount, + // their voting power and rewards would only be issued for the max stake amount. + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + // Whether validators are allow to join/leave post genesis. + allow_validator_set_change: bool, + // DEPRECATING: staking reward configurations will be in StakingRewardsConfig once REWARD_RATE_DECREASE flag is enabled. + // The maximum rewards given out every epoch. This will be divided by the rewards rate denominator. + // For example, 0.001% (0.00001) can be represented as 10 / 1000000. + rewards_rate: u64, + // DEPRECATING: staking reward configurations will be in StakingRewardsConfig once REWARD_RATE_DECREASE flag is enabled. + rewards_rate_denominator: u64, + // Only this % of current total voting power is allowed to join the validator set in each epoch. + // This is necessary to prevent a massive amount of new stake from joining that can potentially take down the + // network if corresponding validators are not ready to participate in consensus in time. + // This value is within (0, 50%), not inclusive. + voting_power_increase_limit: u64, + } + + /// Staking reward configurations that will be stored with the @aptos_framework account. + struct StakingRewardsConfig has copy, drop, key { + // The target rewards rate given out every epoch. This will be divided by the rewards rate denominator. + // For example, 0.001% (0.00001) can be represented as 10 / 1000000. + rewards_rate: FixedPoint64, + // The minimum threshold for rewards_rate. rewards_rate won't be lower than this. + // This will be divided by the rewards rate denominator. + min_rewards_rate: FixedPoint64, + // Reward rate decreases every rewards_rate_period_in_secs seconds. + // Currently it can only equal to 1 year. Keep this field as a plceholder so we can change the reward period + // without adding new struct. + rewards_rate_period_in_secs: u64, + // Timestamp of start of last rewards period. + last_rewards_rate_period_start_in_secs: u64, + // Rate of reward rate decrease in BPS. 1 bps(basis points) = 0.01%. + rewards_rate_decrease_rate: FixedPoint64, + } + + /// Only called during genesis. + public(friend) fun initialize( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + // This can fail genesis but is necessary so that any misconfigurations can be corrected before genesis succeeds + validate_required_stake(minimum_stake, maximum_stake); + + assert!(recurring_lockup_duration_secs > 0, error::invalid_argument(EZERO_LOCKUP_DURATION)); + assert!( + rewards_rate_denominator > 0, + error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR), + ); + assert!( + voting_power_increase_limit > 0 && voting_power_increase_limit <= 50, + error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT), + ); + + // `rewards_rate` which is the numerator is limited to be `<= MAX_REWARDS_RATE` in order to avoid the arithmetic + // overflow in the rewards calculation. `rewards_rate_denominator` can be adjusted to get the desired rewards + // rate (i.e., rewards_rate / rewards_rate_denominator). + assert!(rewards_rate <= MAX_REWARDS_RATE, error::invalid_argument(EINVALID_REWARDS_RATE)); + + // We assert that (rewards_rate / rewards_rate_denominator <= 1). + assert!(rewards_rate <= rewards_rate_denominator, error::invalid_argument(EINVALID_REWARDS_RATE)); + + move_to(aptos_framework, StakingConfig { + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit, + }); + } + + /// Initialize rewards configurations. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun initialize_rewards( + aptos_framework: &signer, + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_secs: u64, + last_rewards_rate_period_start_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + validate_rewards_config( + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_secs, + rewards_rate_decrease_rate, + ); + assert!( + timestamp::now_seconds() >= last_rewards_rate_period_start_in_secs, + error::invalid_argument(EINVALID_LAST_REWARDS_RATE_PERIOD_START) + ); + + move_to(aptos_framework, StakingRewardsConfig { + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_secs, + last_rewards_rate_period_start_in_secs, + rewards_rate_decrease_rate, + }); + } + + public fun get(): StakingConfig acquires StakingConfig { + *borrow_global(@aptos_framework) + } + + /// Return whether validator set changes are allowed + public fun get_allow_validator_set_change(config: &StakingConfig): bool { + config.allow_validator_set_change + } + + /// Return the required min/max stake. + public fun get_required_stake(config: &StakingConfig): (u64, u64) { + (config.minimum_stake, config.maximum_stake) + } + + /// Return the recurring lockup duration that every validator is automatically renewed for (unless they unlock and + /// withdraw all funds). + public fun get_recurring_lockup_duration(config: &StakingConfig): u64 { + config.recurring_lockup_duration_secs + } + + /// Return the reward rate of this epoch. + public fun get_reward_rate(config: &StakingConfig): (u64, u64) acquires StakingRewardsConfig { + if (features::periodical_reward_rate_decrease_enabled()) { + let epoch_rewards_rate = borrow_global(@aptos_framework).rewards_rate; + if (fixed_point64::is_zero(epoch_rewards_rate)) { + (0u64, 1u64) + } else { + // Maximize denominator for higher precision. + // Restriction: nominator <= MAX_REWARDS_RATE && denominator <= MAX_U64 + let denominator = fixed_point64::divide_u128((MAX_REWARDS_RATE as u128), epoch_rewards_rate); + if (denominator > MAX_U64) { + denominator = MAX_U64 + }; + let nominator = (fixed_point64::multiply_u128(denominator, epoch_rewards_rate) as u64); + (nominator, (denominator as u64)) + } + } else { + (config.rewards_rate, config.rewards_rate_denominator) + } + } + + /// Return the joining limit %. + public fun get_voting_power_increase_limit(config: &StakingConfig): u64 { + config.voting_power_increase_limit + } + + /// Calculate and save the latest rewards rate. + public(friend) fun calculate_and_save_latest_epoch_rewards_rate(): FixedPoint64 acquires StakingRewardsConfig { + assert!(features::periodical_reward_rate_decrease_enabled(), error::invalid_state(EDISABLED_FUNCTION)); + let staking_rewards_config = calculate_and_save_latest_rewards_config(); + staking_rewards_config.rewards_rate + } + + /// Calculate and return the up-to-date StakingRewardsConfig. + fun calculate_and_save_latest_rewards_config(): StakingRewardsConfig acquires StakingRewardsConfig { + let staking_rewards_config = borrow_global_mut(@aptos_framework); + let current_time_in_secs = timestamp::now_seconds(); + assert!( + current_time_in_secs >= staking_rewards_config.last_rewards_rate_period_start_in_secs, + error::invalid_argument(EINVALID_LAST_REWARDS_RATE_PERIOD_START) + ); + if (current_time_in_secs - staking_rewards_config.last_rewards_rate_period_start_in_secs < staking_rewards_config.rewards_rate_period_in_secs) { + return *staking_rewards_config + }; + // Rewards rate decrease rate cannot be greater than 100%. Otherwise rewards rate will be negative. + assert!( + fixed_point64::ceil(staking_rewards_config.rewards_rate_decrease_rate) <= 1, + error::invalid_argument(EINVALID_REWARDS_RATE_DECREASE_RATE) + ); + let new_rate = math_fixed64::mul_div( + staking_rewards_config.rewards_rate, + fixed_point64::sub( + fixed_point64::create_from_u128(1), + staking_rewards_config.rewards_rate_decrease_rate, + ), + fixed_point64::create_from_u128(1), + ); + new_rate = fixed_point64::max(new_rate, staking_rewards_config.min_rewards_rate); + + staking_rewards_config.rewards_rate = new_rate; + staking_rewards_config.last_rewards_rate_period_start_in_secs = + staking_rewards_config.last_rewards_rate_period_start_in_secs + + staking_rewards_config.rewards_rate_period_in_secs; + return *staking_rewards_config + } + + /// Update the min and max stake amounts. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_required_stake( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + ) acquires StakingConfig { + system_addresses::assert_aptos_framework(aptos_framework); + validate_required_stake(minimum_stake, maximum_stake); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.minimum_stake = minimum_stake; + staking_config.maximum_stake = maximum_stake; + } + + /// Update the recurring lockup duration. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_recurring_lockup_duration_secs( + aptos_framework: &signer, + new_recurring_lockup_duration_secs: u64, + ) acquires StakingConfig { + assert!(new_recurring_lockup_duration_secs > 0, error::invalid_argument(EZERO_LOCKUP_DURATION)); + system_addresses::assert_aptos_framework(aptos_framework); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.recurring_lockup_duration_secs = new_recurring_lockup_duration_secs; + } + + /// DEPRECATING + /// Update the rewards rate. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_rewards_rate( + aptos_framework: &signer, + new_rewards_rate: u64, + new_rewards_rate_denominator: u64, + ) acquires StakingConfig { + assert!(!features::periodical_reward_rate_decrease_enabled(), error::invalid_state(EDEPRECATED_FUNCTION)); + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + new_rewards_rate_denominator > 0, + error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR), + ); + // `rewards_rate` which is the numerator is limited to be `<= MAX_REWARDS_RATE` in order to avoid the arithmetic + // overflow in the rewards calculation. `rewards_rate_denominator` can be adjusted to get the desired rewards + // rate (i.e., rewards_rate / rewards_rate_denominator). + assert!(new_rewards_rate <= MAX_REWARDS_RATE, error::invalid_argument(EINVALID_REWARDS_RATE)); + + // We assert that (rewards_rate / rewards_rate_denominator <= 1). + assert!(new_rewards_rate <= new_rewards_rate_denominator, error::invalid_argument(EINVALID_REWARDS_RATE)); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.rewards_rate = new_rewards_rate; + staking_config.rewards_rate_denominator = new_rewards_rate_denominator; + } + + public fun update_rewards_config( + aptos_framework: &signer, + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) acquires StakingRewardsConfig { + system_addresses::assert_aptos_framework(aptos_framework); + + validate_rewards_config( + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_secs, + rewards_rate_decrease_rate, + ); + + let staking_rewards_config = borrow_global_mut(@aptos_framework); + // Currently rewards_rate_period_in_secs is not allowed to be changed because this could bring complicated + // logics. At the moment the argument is just a placeholder for future use. + assert!( + rewards_rate_period_in_secs == staking_rewards_config.rewards_rate_period_in_secs, + error::invalid_argument(EINVALID_REWARDS_RATE_PERIOD), + ); + staking_rewards_config.rewards_rate = rewards_rate; + staking_rewards_config.min_rewards_rate = min_rewards_rate; + staking_rewards_config.rewards_rate_period_in_secs = rewards_rate_period_in_secs; + staking_rewards_config.rewards_rate_decrease_rate = rewards_rate_decrease_rate; + } + + /// Update the joining limit %. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_voting_power_increase_limit( + aptos_framework: &signer, + new_voting_power_increase_limit: u64, + ) acquires StakingConfig { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + new_voting_power_increase_limit > 0 && new_voting_power_increase_limit <= 50, + error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT), + ); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.voting_power_increase_limit = new_voting_power_increase_limit; + } + + fun validate_required_stake(minimum_stake: u64, maximum_stake: u64) { + assert!(minimum_stake <= maximum_stake && maximum_stake > 0, error::invalid_argument(EINVALID_STAKE_RANGE)); + } + + fun validate_rewards_config( + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) { + // Bound rewards rate to avoid arithmetic overflow. + assert!( + less_or_equal(rewards_rate, fixed_point64::create_from_u128((1u128))), + error::invalid_argument(EINVALID_REWARDS_RATE) + ); + assert!( + less_or_equal(min_rewards_rate, rewards_rate), + error::invalid_argument(EINVALID_MIN_REWARDS_RATE) + ); + // Rewards rate decrease rate cannot be greater than 100%. Otherwise rewards rate will be negative. + assert!( + fixed_point64::ceil(rewards_rate_decrease_rate) <= 1, + error::invalid_argument(EINVALID_REWARDS_RATE_DECREASE_RATE) + ); + // This field, rewards_rate_period_in_secs must be greater than 0. + // TODO: rewards_rate_period_in_secs should be longer than the epoch duration but reading epoch duration causes a circular dependency. + assert!( + rewards_rate_period_in_secs > 0, + error::invalid_argument(EINVALID_REWARDS_RATE_PERIOD), + ); + } + + #[test_only] + use aptos_std::fixed_point64::{equal, create_from_rational}; + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_change_staking_configs(aptos_framework: signer) acquires StakingConfig { + initialize(&aptos_framework, 0, 1, 1, false, 1, 1, 1); + + update_required_stake(&aptos_framework, 100, 1000); + update_recurring_lockup_duration_secs(&aptos_framework, 10000); + update_rewards_rate(&aptos_framework, 10, 100); + update_voting_power_increase_limit(&aptos_framework, 10); + + let config = borrow_global(@aptos_framework); + assert!(config.minimum_stake == 100, 0); + assert!(config.maximum_stake == 1000, 1); + assert!(config.recurring_lockup_duration_secs == 10000, 3); + assert!(config.rewards_rate == 10, 4); + assert!(config.rewards_rate_denominator == 100, 4); + assert!(config.voting_power_increase_limit == 10, 5); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_staking_rewards_rate_decrease_over_time(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(1, 100), + create_from_rational(3, 1000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(50, 100) + ); + + let epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(1, 100)), 0); + // Rewards rate should not change until the current reward rate period ends. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS / 2); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(1, 100)), 1); + + // Rewards rate decreases to 1 / 100 * 5000 / 10000 = 5 / 1000. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS / 2); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(5, 1000)), 2); + + // Rewards rate decreases to 5 / 1000 * 5000 / 10000 = 2.5 / 1000. + // But rewards_rate cannot be lower than min_rewards_rate = 3 / 1000. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(3, 1000)), 3); + + // Test when rewards_rate_decrease_rate is very small + update_rewards_config( + &aptos_framework, + epoch_reward_rate, + create_from_rational(0, 1000), + ONE_YEAR_IN_SECS, + create_from_rational(15, 1000), + ); + // Rewards rate decreases to 3 / 1000 * 985 / 1000 = 2955 / 1000000. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!( + fixed_point64::almost_equal( + epoch_reward_rate, + create_from_rational(2955, 1000000), + create_from_rational(1, 100000000) + ), + 4); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_change_staking_rewards_configs(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(1, 100), + create_from_rational(3, 1000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(50, 100), + ); + + update_rewards_config( + &aptos_framework, + create_from_rational(2, 100), + create_from_rational(6, 1000), + ONE_YEAR_IN_SECS, + create_from_rational(25, 100), + ); + + let config = borrow_global(@aptos_framework); + assert!(equal(config.rewards_rate, create_from_rational(2, 100)), 0); + assert!(equal(config.min_rewards_rate, create_from_rational(6, 1000)), 1); + assert!(config.rewards_rate_period_in_secs == ONE_YEAR_IN_SECS, 4); + assert!(config.last_rewards_rate_period_start_in_secs == start_time_in_secs, 4); + assert!(equal(config.rewards_rate_decrease_rate, create_from_rational(25, 100)), 5); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_required_stake_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_required_stake(&account, 1, 2); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_required_lockup_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_recurring_lockup_duration_secs(&account, 1); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_rewards_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_rewards_rate(&account, 1, 10); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_voting_power_increase_limit_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_voting_power_increase_limit(&account, 10); + } + + #[test(account = @0x123, aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_rewards_config_unauthorized_should_fail(account: signer, aptos_framework: signer) acquires StakingRewardsConfig { + features::change_feature_flags(&aptos_framework, vector[features::get_periodical_reward_rate_decrease_feature()], vector[]); + update_rewards_config( + &account, + create_from_rational(1, 100), + create_from_rational(1, 100), + ONE_YEAR_IN_SECS, + create_from_rational(1, 100), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10003, location = Self)] + public entry fun test_update_required_stake_invalid_range_should_fail(aptos_framework: signer) acquires StakingConfig { + update_required_stake(&aptos_framework, 10, 5); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10003, location = Self)] + public entry fun test_update_required_stake_zero_max_stake_should_fail(aptos_framework: signer) acquires StakingConfig { + update_required_stake(&aptos_framework, 0, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_update_required_lockup_to_zero_should_fail(aptos_framework: signer) acquires StakingConfig { + update_recurring_lockup_duration_secs(&aptos_framework, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10002, location = Self)] + public entry fun test_update_rewards_invalid_denominator_should_fail(aptos_framework: signer) acquires StakingConfig { + update_rewards_rate(&aptos_framework, 1, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10005, location = Self)] + public entry fun test_update_rewards_config_rewards_rate_greater_than_1_should_fail(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(15, 1000), + ); + update_rewards_config( + &aptos_framework, + create_from_rational(101, 100), + create_from_rational(1, 100), + ONE_YEAR_IN_SECS, + create_from_rational(1, 100), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10008, location = Self)] + public entry fun test_update_rewards_config_invalid_rewards_rate_decrease_rate_should_fail(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(15, 1000), + ); + update_rewards_config( + &aptos_framework, + create_from_rational(1, 100), + create_from_rational(1, 100), + ONE_YEAR_IN_SECS, + create_from_rational(101, 100), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10009, location = Self)] + public entry fun test_update_rewards_config_cannot_change_rewards_rate_period(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(15, 1000), + ); + update_rewards_config( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS - 1, + create_from_rational(15, 1000), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x3000B, location = Self)] + public entry fun test_feature_flag_disabled_get_epoch_rewards_rate_should_fail(aptos_framework: signer) acquires StakingRewardsConfig { + features::change_feature_flags(&aptos_framework, vector[], vector[features::get_periodical_reward_rate_decrease_feature()]); + calculate_and_save_latest_epoch_rewards_rate(); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public entry fun test_update_voting_power_increase_limit_to_zero_should_fail( + aptos_framework: signer + ) acquires StakingConfig { + update_voting_power_increase_limit(&aptos_framework, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10004, location = aptos_framework::staking_config)] + public entry fun test_update_voting_power_increase_limit_to_more_than_upper_bound_should_fail( + aptos_framework: signer + ) acquires StakingConfig { + update_voting_power_increase_limit(&aptos_framework, 51); + } + + // For tests to bypass all validations. + #[test_only] + public fun initialize_for_test( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + if (!exists(@aptos_framework)) { + move_to(aptos_framework, StakingConfig { + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit, + }); + }; + } + + // For tests to bypass all validations. + #[test_only] + public fun initialize_rewards_for_test( + aptos_framework: &signer, + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_micros: u64, + last_rewards_rate_period_start_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) { + features::change_feature_flags(aptos_framework, vector[features::get_periodical_reward_rate_decrease_feature()], vector[]); + timestamp::set_time_has_started_for_testing(aptos_framework); + timestamp::update_global_time_for_test_secs(last_rewards_rate_period_start_in_secs); + initialize_rewards( + aptos_framework, + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_micros, + last_rewards_rate_period_start_in_secs, + rewards_rate_decrease_rate, + ); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_contract.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_contract.move new file mode 100644 index 0000000..1291d63 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_contract.move @@ -0,0 +1,1315 @@ +/// Allow stakers and operators to enter a staking contract with reward sharing. +/// The main accounting logic in a staking contract consists of 2 parts: +/// 1. Tracks how much commission needs to be paid out to the operator. This is tracked with an increasing principal +/// amount that's updated every time the operator requests commission, the staker withdraws funds, or the staker +/// switches operators. +/// 2. Distributions of funds to operators (commissions) and stakers (stake withdrawals) use the shares model provided +/// by the pool_u64 to track shares that increase in price as the stake pool accumulates rewards. +/// +/// Example flow: +/// 1. A staker creates a staking contract with an operator by calling create_staking_contract() with 100 coins of +/// initial stake and commission = 10%. This means the operator will receive 10% of any accumulated rewards. A new stake +/// pool will be created and hosted in a separate account that's controlled by the staking contract. +/// 2. The operator sets up a validator node and, once ready, joins the validator set by calling stake::join_validator_set +/// 3. After some time, the stake pool gains rewards and now has 150 coins. +/// 4. Operator can now call request_commission. 10% of (150 - 100) = 5 coins will be unlocked from the stake pool. The +/// staker's principal is now updated from 100 to 145 (150 coins - 5 coins of commission). The pending distribution pool +/// has 5 coins total and the operator owns all 5 shares of it. +/// 5. Some more time has passed. The pool now has 50 more coins in rewards and a total balance of 195. The operator +/// calls request_commission again. Since the previous 5 coins have now become withdrawable, it'll be deposited into the +/// operator's account first. Their new commission will be 10% of (195 coins - 145 principal) = 5 coins. Principal is +/// updated to be 190 (195 - 5). Pending distribution pool has 5 coins and operator owns all 5 shares. +/// 6. Staker calls unlock_stake to unlock 50 coins of stake, which gets added to the pending distribution pool. Based +/// on shares math, staker will be owning 50 shares and operator still owns 5 shares of the 55-coin pending distribution +/// pool. +/// 7. Some time passes and the 55 coins become fully withdrawable from the stake pool. Due to accumulated rewards, the +/// 55 coins become 70 coins. Calling distribute() distributes 6 coins to the operator and 64 coins to the validator. +module aptos_framework::staking_contract { + use std::bcs; + use std::error; + use std::signer; + use std::vector; + + use aptos_std::pool_u64::{Self, Pool}; + use aptos_std::simple_map::{Self, SimpleMap}; + + use aptos_framework::account::{Self, SignerCapability}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, Coin}; + use aptos_framework::event::{EventHandle, emit_event}; + use aptos_framework::stake::{Self, OwnerCapability}; + use aptos_framework::staking_config; + + const SALT: vector = b"aptos_framework::staking_contract"; + + /// Store amount must be at least the min stake required for a stake pool to join the validator set. + const EINSUFFICIENT_STAKE_AMOUNT: u64 = 1; + /// Commission percentage has to be between 0 and 100. + const EINVALID_COMMISSION_PERCENTAGE: u64 = 2; + /// Staker has no staking contracts. + const ENO_STAKING_CONTRACT_FOUND_FOR_STAKER: u64 = 3; + /// No staking contract between the staker and operator found. + const ENO_STAKING_CONTRACT_FOUND_FOR_OPERATOR: u64 = 4; + /// Staking contracts can't be merged. + const ECANT_MERGE_STAKING_CONTRACTS: u64 = 5; + /// The staking contract already exists and cannot be re-created. + const ESTAKING_CONTRACT_ALREADY_EXISTS: u64 = 6; + /// Not enough active stake to withdraw. Some stake might still pending and will be active in the next epoch. + const EINSUFFICIENT_ACTIVE_STAKE_TO_WITHDRAW: u64 = 7; + /// Caller must be either the staker or operator. + const ENOT_STAKER_OR_OPERATOR: u64 = 8; + + /// Maximum number of distributions a stake pool can support. + const MAXIMUM_PENDING_DISTRIBUTIONS: u64 = 20; + + #[resource_group(scope=module_)] + struct StakingGroupContainer {} + + struct StakingContract has store { + // Recorded principal after the last commission distribution. + // This is only used to calculate the commission the operator should be receiving. + principal: u64, + pool_address: address, + // The stake pool's owner capability. This can be used to control funds in the stake pool. + owner_cap: OwnerCapability, + commission_percentage: u64, + // Current distributions, including operator commission withdrawals and staker's partial withdrawals. + distribution_pool: Pool, + // Just in case we need the SignerCap for stake pool account in the future. + signer_cap: SignerCapability, + } + + struct Store has key { + staking_contracts: SimpleMap, + + // Events. + create_staking_contract_events: EventHandle, + update_voter_events: EventHandle, + reset_lockup_events: EventHandle, + add_stake_events: EventHandle, + request_commission_events: EventHandle, + unlock_stake_events: EventHandle, + switch_operator_events: EventHandle, + add_distribution_events: EventHandle, + distribute_events: EventHandle, + } + + struct UpdateCommissionEvent has drop, store { + staker: address, + operator: address, + old_commission_percentage: u64, + new_commission_percentage: u64, + } + + #[resource_group_member(group = aptos_framework::staking_contract::StakingGroupContainer)] + struct StakingGroupUpdateCommissionEvent has key { + update_commission_events: EventHandle, + } + + struct CreateStakingContractEvent has drop, store { + operator: address, + voter: address, + pool_address: address, + principal: u64, + commission_percentage: u64, + } + + struct UpdateVoterEvent has drop, store { + operator: address, + pool_address: address, + old_voter: address, + new_voter: address, + } + + struct ResetLockupEvent has drop, store { + operator: address, + pool_address: address, + } + + struct AddStakeEvent has drop, store { + operator: address, + pool_address: address, + amount: u64 + } + + struct RequestCommissionEvent has drop, store { + operator: address, + pool_address: address, + accumulated_rewards: u64, + commission_amount: u64, + } + + struct UnlockStakeEvent has drop, store { + operator: address, + pool_address: address, + amount: u64, + commission_paid: u64, + } + + struct SwitchOperatorEvent has drop, store { + old_operator: address, + new_operator: address, + pool_address: address, + } + + struct AddDistributionEvent has drop, store { + operator: address, + pool_address: address, + amount: u64, + } + + struct DistributeEvent has drop, store { + operator: address, + pool_address: address, + recipient: address, + amount: u64, + } + + #[view] + /// Return the address of the underlying stake pool for the staking contract between the provided staker and + /// operator. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun stake_pool_address(staker: address, operator: address): address acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + simple_map::borrow(staking_contracts, &operator).pool_address + } + + #[view] + /// Return the last recorded principal (the amount that 100% belongs to the staker with commission already paid for) + /// for staking contract between the provided staker and operator. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun last_recorded_principal(staker: address, operator: address): u64 acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + simple_map::borrow(staking_contracts, &operator).principal + } + + #[view] + /// Return percentage of accumulated rewards that will be paid to the operator as commission for staking contract + /// between the provided staker and operator. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun commission_percentage(staker: address, operator: address): u64 acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + simple_map::borrow(staking_contracts, &operator).commission_percentage + } + + #[view] + /// Return a tuple of three numbers: + /// 1. The total active stake in the underlying stake pool + /// 2. The total accumulated rewards that haven't had commission paid out + /// 3. The commission amount owned from those accumulated rewards. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun staking_contract_amounts(staker: address, operator: address): (u64, u64, u64) acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + let staking_contract = simple_map::borrow(staking_contracts, &operator); + get_staking_contract_amounts_internal(staking_contract) + } + + #[view] + /// Return the number of pending distributions (e.g. commission, withdrawals from stakers). + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun pending_distribution_counts(staker: address, operator: address): u64 acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + pool_u64::shareholders_count(&simple_map::borrow(staking_contracts, &operator).distribution_pool) + } + + #[view] + /// Return true if the staking contract between the provided staker and operator exists. + public fun staking_contract_exists(staker: address, operator: address): bool acquires Store { + if (!exists(staker)) { + return false + }; + + let store = borrow_global(staker); + simple_map::contains_key(&store.staking_contracts, &operator) + } + + #[view] + /// Return the address of the stake pool to be created with the provided staker, operator and seed. + public fun get_expected_stake_pool_address( + staker: address, + operator: address, + contract_creation_seed: vector, + ): address { + let seed = create_resource_account_seed(staker, operator, contract_creation_seed); + account::create_resource_address(&staker, seed) + } + + /// Staker can call this function to create a simple staking contract with a specified operator. + public entry fun create_staking_contract( + staker: &signer, + operator: address, + voter: address, + amount: u64, + commission_percentage: u64, + // Optional seed used when creating the staking contract account. + contract_creation_seed: vector, + ) acquires Store { + let staked_coins = coin::withdraw(staker, amount); + create_staking_contract_with_coins( + staker, operator, voter, staked_coins, commission_percentage, contract_creation_seed); + } + + /// Staker can call this function to create a simple staking contract with a specified operator. + public fun create_staking_contract_with_coins( + staker: &signer, + operator: address, + voter: address, + coins: Coin, + commission_percentage: u64, + // Optional seed used when creating the staking contract account. + contract_creation_seed: vector, + ): address acquires Store { + assert!( + commission_percentage >= 0 && commission_percentage <= 100, + error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE), + ); + // The amount should be at least the min_stake_required, so the stake pool will be eligible to join the + // validator set. + let (min_stake_required, _) = staking_config::get_required_stake(&staking_config::get()); + let principal = coin::value(&coins); + assert!(principal >= min_stake_required, error::invalid_argument(EINSUFFICIENT_STAKE_AMOUNT)); + + // Initialize Store resource if this is the first time the staker has delegated to anyone. + let staker_address = signer::address_of(staker); + if (!exists(staker_address)) { + move_to(staker, new_staking_contracts_holder(staker)); + }; + + // Cannot create the staking contract if it already exists. + let store = borrow_global_mut(staker_address); + let staking_contracts = &mut store.staking_contracts; + assert!( + !simple_map::contains_key(staking_contracts, &operator), + error::already_exists(ESTAKING_CONTRACT_ALREADY_EXISTS) + ); + + // Initialize the stake pool in a new resource account. This allows the same staker to contract with multiple + // different operators. + let (stake_pool_signer, stake_pool_signer_cap, owner_cap) = + create_stake_pool(staker, operator, voter, contract_creation_seed); + + // Add the stake to the stake pool. + stake::add_stake_with_cap(&owner_cap, coins); + + // Create the contract record. + let pool_address = signer::address_of(&stake_pool_signer); + simple_map::add(staking_contracts, operator, StakingContract { + principal, + pool_address, + owner_cap, + commission_percentage, + // Make sure we don't have too many pending recipients in the distribution pool. + // Otherwise, a griefing attack is possible where the staker can keep switching operators and create too + // many pending distributions. This can lead to out-of-gas failure whenever distribute() is called. + distribution_pool: pool_u64::create(MAXIMUM_PENDING_DISTRIBUTIONS), + signer_cap: stake_pool_signer_cap, + }); + + emit_event( + &mut store.create_staking_contract_events, + CreateStakingContractEvent { operator, voter, pool_address, principal, commission_percentage }, + ); + pool_address + } + + /// Add more stake to an existing staking contract. + public entry fun add_stake(staker: &signer, operator: address, amount: u64) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + + // Add the stake to the stake pool. + let staked_coins = coin::withdraw(staker, amount); + stake::add_stake_with_cap(&staking_contract.owner_cap, staked_coins); + + staking_contract.principal = staking_contract.principal + amount; + let pool_address = staking_contract.pool_address; + emit_event( + &mut store.add_stake_events, + AddStakeEvent { operator, pool_address, amount }, + ); + } + + /// Convenient function to allow the staker to update the voter address in a staking contract they made. + public entry fun update_voter(staker: &signer, operator: address, new_voter: address) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + let pool_address = staking_contract.pool_address; + let old_voter = stake::get_delegated_voter(pool_address); + stake::set_delegated_voter_with_cap(&staking_contract.owner_cap, new_voter); + + emit_event( + &mut store.update_voter_events, + UpdateVoterEvent { operator, pool_address, old_voter, new_voter }, + ); + } + + /// Convenient function to allow the staker to reset their stake pool's lockup period to start now. + public entry fun reset_lockup(staker: &signer, operator: address) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + let pool_address = staking_contract.pool_address; + stake::increase_lockup_with_cap(&staking_contract.owner_cap); + + emit_event(&mut store.reset_lockup_events, ResetLockupEvent { operator, pool_address }); + } + + /// Convenience function to allow a staker to update the commission percentage paid to the operator. + /// TODO: fix the typo in function name. commision -> commission + public entry fun update_commision(staker: &signer, operator: address, new_commission_percentage: u64) acquires Store, StakingGroupUpdateCommissionEvent { + assert!( + new_commission_percentage >= 0 && new_commission_percentage <= 100, + error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE), + ); + + let staker_address = signer::address_of(staker); + assert!(exists(staker_address), error::not_found(ENO_STAKING_CONTRACT_FOUND_FOR_STAKER)); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + distribute_internal(staker_address, operator, staking_contract, &mut store.distribute_events); + request_commission_internal( + operator, + staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + let old_commission_percentage = staking_contract.commission_percentage; + staking_contract.commission_percentage = new_commission_percentage; + if (!exists(staker_address)) { + move_to(staker, StakingGroupUpdateCommissionEvent { update_commission_events: account::new_event_handle(staker)}) + }; + emit_event( + &mut borrow_global_mut(staker_address).update_commission_events, + UpdateCommissionEvent { staker: staker_address, operator, old_commission_percentage, new_commission_percentage } + ); + } + + /// Unlock commission amount from the stake pool. Operator needs to wait for the amount to become withdrawable + /// at the end of the stake pool's lockup period before they can actually can withdraw_commission. + /// + /// Only staker or operator can call this. + public entry fun request_commission(account: &signer, staker: address, operator: address) acquires Store { + let account_addr = signer::address_of(account); + assert!(account_addr == staker || account_addr == operator, error::unauthenticated(ENOT_STAKER_OR_OPERATOR)); + assert_staking_contract_exists(staker, operator); + + let store = borrow_global_mut(staker); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + // Short-circuit if zero commission. + if (staking_contract.commission_percentage == 0) { + return + }; + + // Force distribution of any already inactive stake. + distribute_internal(staker, operator, staking_contract, &mut store.distribute_events); + + request_commission_internal( + operator, + staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + } + + fun request_commission_internal( + operator: address, + staking_contract: &mut StakingContract, + add_distribution_events: &mut EventHandle, + request_commission_events: &mut EventHandle, + ): u64 { + // Unlock just the commission portion from the stake pool. + let (total_active_stake, accumulated_rewards, commission_amount) = + get_staking_contract_amounts_internal(staking_contract); + staking_contract.principal = total_active_stake - commission_amount; + + // Short-circuit if there's no commission to pay. + if (commission_amount == 0) { + return 0 + }; + + // Add a distribution for the operator. + add_distribution(operator, staking_contract, operator, commission_amount, add_distribution_events); + + // Request to unlock the commission from the stake pool. + // This won't become fully unlocked until the stake pool's lockup expires. + stake::unlock_with_cap(commission_amount, &staking_contract.owner_cap); + + let pool_address = staking_contract.pool_address; + emit_event( + request_commission_events, + RequestCommissionEvent { operator, pool_address, accumulated_rewards, commission_amount }, + ); + + commission_amount + } + + /// Staker can call this to request withdrawal of part or all of their staking_contract. + /// This also triggers paying commission to the operator for accounting simplicity. + public entry fun unlock_stake(staker: &signer, operator: address, amount: u64) acquires Store { + // Short-circuit if amount is 0. + if (amount == 0) return; + + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + + // Force distribution of any already inactive stake. + distribute_internal(staker_address, operator, staking_contract, &mut store.distribute_events); + + // For simplicity, we request commission to be paid out first. This avoids having to ensure to staker doesn't + // withdraw into the commission portion. + let commission_paid = request_commission_internal( + operator, + staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + + // If there's less active stake remaining than the amount requested (potentially due to commission), + // only withdraw up to the active amount. + let (active, _, _, _) = stake::get_stake(staking_contract.pool_address); + if (active < amount) { + amount = active; + }; + staking_contract.principal = staking_contract.principal - amount; + + // Record a distribution for the staker. + add_distribution( + operator, staking_contract, staker_address, amount, &mut store.add_distribution_events); + + // Request to unlock the distribution amount from the stake pool. + // This won't become fully unlocked until the stake pool's lockup expires. + stake::unlock_with_cap(amount, &staking_contract.owner_cap); + + let pool_address = staking_contract.pool_address; + emit_event( + &mut store.unlock_stake_events, + UnlockStakeEvent { pool_address, operator, amount, commission_paid }, + ); + } + + /// Unlock all accumulated rewards since the last recorded principals. + public entry fun unlock_rewards(staker: &signer, operator: address) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + // Calculate how much rewards belongs to the staker after commission is paid. + let (_, accumulated_rewards, unpaid_commission) = staking_contract_amounts(staker_address, operator); + let staker_rewards = accumulated_rewards - unpaid_commission; + unlock_stake(staker, operator, staker_rewards); + } + + /// Allows staker to switch operator without going through the lenghthy process to unstake, without resetting commission. + public entry fun switch_operator_with_same_commission( + staker: &signer, + old_operator: address, + new_operator: address, + ) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, old_operator); + + let commission_percentage = commission_percentage(staker_address, old_operator); + switch_operator(staker, old_operator, new_operator, commission_percentage); + } + + /// Allows staker to switch operator without going through the lenghthy process to unstake. + public entry fun switch_operator( + staker: &signer, + old_operator: address, + new_operator: address, + new_commission_percentage: u64, + ) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, old_operator); + + // Merging two existing staking contracts is too complex as we'd need to merge two separate stake pools. + let store = borrow_global_mut(staker_address); + let staking_contracts = &mut store.staking_contracts; + assert!( + !simple_map::contains_key(staking_contracts, &new_operator), + error::invalid_state(ECANT_MERGE_STAKING_CONTRACTS), + ); + + let (_, staking_contract) = simple_map::remove(staking_contracts, &old_operator); + // Force distribution of any already inactive stake. + distribute_internal(staker_address, old_operator, &mut staking_contract, &mut store.distribute_events); + + // For simplicity, we request commission to be paid out first. This avoids having to ensure to staker doesn't + // withdraw into the commission portion. + request_commission_internal( + old_operator, + &mut staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + + // Update the staking contract's commission rate and stake pool's operator. + stake::set_operator_with_cap(&staking_contract.owner_cap, new_operator); + staking_contract.commission_percentage = new_commission_percentage; + + let pool_address = staking_contract.pool_address; + simple_map::add(staking_contracts, new_operator, staking_contract); + emit_event( + &mut store.switch_operator_events, + SwitchOperatorEvent { pool_address, old_operator, new_operator } + ); + } + + /// Allow anyone to distribute already unlocked funds. This does not affect reward compounding and therefore does + /// not need to be restricted to just the staker or operator. + public entry fun distribute(staker: address, operator: address) acquires Store { + assert_staking_contract_exists(staker, operator); + let store = borrow_global_mut(staker); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + distribute_internal(staker, operator, staking_contract, &mut store.distribute_events); + } + + /// Distribute all unlocked (inactive) funds according to distribution shares. + fun distribute_internal( + staker: address, + operator: address, + staking_contract: &mut StakingContract, + distribute_events: &mut EventHandle, + ) { + let pool_address = staking_contract.pool_address; + let (_, inactive, _, pending_inactive) = stake::get_stake(pool_address); + let total_potential_withdrawable = inactive + pending_inactive; + let coins = stake::withdraw_with_cap(&staking_contract.owner_cap, total_potential_withdrawable); + let distribution_amount = coin::value(&coins); + if (distribution_amount == 0) { + coin::destroy_zero(coins); + return + }; + + let distribution_pool = &mut staking_contract.distribution_pool; + update_distribution_pool( + distribution_pool, distribution_amount, operator, staking_contract.commission_percentage); + + // Buy all recipients out of the distribution pool. + while (pool_u64::shareholders_count(distribution_pool) > 0) { + let recipients = pool_u64::shareholders(distribution_pool); + let recipient = *vector::borrow(&mut recipients, 0); + let current_shares = pool_u64::shares(distribution_pool, recipient); + let amount_to_distribute = pool_u64::redeem_shares(distribution_pool, recipient, current_shares); + coin::deposit(recipient, coin::extract(&mut coins, amount_to_distribute)); + + emit_event( + distribute_events, + DistributeEvent { operator, pool_address, recipient, amount: amount_to_distribute } + ); + }; + + // In case there's any dust left, send them all to the staker. + if (coin::value(&coins) > 0) { + coin::deposit(staker, coins); + pool_u64::update_total_coins(distribution_pool, 0); + } else { + coin::destroy_zero(coins); + } + } + + /// Assert that a staking_contract exists for the staker/operator pair. + fun assert_staking_contract_exists(staker: address, operator: address) acquires Store { + assert!(exists(staker), error::not_found(ENO_STAKING_CONTRACT_FOUND_FOR_STAKER)); + let staking_contracts = &mut borrow_global_mut(staker).staking_contracts; + assert!( + simple_map::contains_key(staking_contracts, &operator), + error::not_found(ENO_STAKING_CONTRACT_FOUND_FOR_OPERATOR), + ); + } + + /// Add a new distribution for `recipient` and `amount` to the staking contract's distributions list. + fun add_distribution( + operator: address, + staking_contract: &mut StakingContract, + recipient: address, + coins_amount: u64, + add_distribution_events: &mut EventHandle, + ) { + let distribution_pool = &mut staking_contract.distribution_pool; + let (_, _, _, total_distribution_amount) = stake::get_stake(staking_contract.pool_address); + update_distribution_pool( + distribution_pool, total_distribution_amount, operator, staking_contract.commission_percentage); + + pool_u64::buy_in(distribution_pool, recipient, coins_amount); + let pool_address = staking_contract.pool_address; + emit_event( + add_distribution_events, + AddDistributionEvent { operator, pool_address, amount: coins_amount } + ); + } + + /// Calculate accumulated rewards and commissions since last update. + fun get_staking_contract_amounts_internal(staking_contract: &StakingContract): (u64, u64, u64) { + // Pending_inactive is not included in the calculation because pending_inactive can only come from: + // 1. Outgoing commissions. This means commission has already been extracted. + // 2. Stake withdrawals from stakers. This also means commission has already been extracted as + // request_commission_internal is called in unlock_stake + let (active, _, pending_active, _) = stake::get_stake(staking_contract.pool_address); + let total_active_stake = active + pending_active; + let accumulated_rewards = total_active_stake - staking_contract.principal; + let commission_amount = accumulated_rewards * staking_contract.commission_percentage / 100; + + (total_active_stake, accumulated_rewards, commission_amount) + } + + fun create_stake_pool( + staker: &signer, + operator: address, + voter: address, + contract_creation_seed: vector, + ): (signer, SignerCapability, OwnerCapability) { + // Generate a seed that will be used to create the resource account that hosts the staking contract. + let seed = create_resource_account_seed( + signer::address_of(staker), operator, contract_creation_seed); + + let (stake_pool_signer, stake_pool_signer_cap) = account::create_resource_account(staker, seed); + stake::initialize_stake_owner(&stake_pool_signer, 0, operator, voter); + + // Extract owner_cap from the StakePool, so we have control over it in the staking_contracts flow. + // This is stored as part of the staking_contract. Thus, the staker would not have direct control over it without + // going through well-defined functions in this module. + let owner_cap = stake::extract_owner_cap(&stake_pool_signer); + + (stake_pool_signer, stake_pool_signer_cap, owner_cap) + } + + fun update_distribution_pool( + distribution_pool: &mut Pool, + updated_total_coins: u64, + operator: address, + commission_percentage: u64, + ) { + // Short-circuit and do nothing if the pool's total value has not changed. + if (pool_u64::total_coins(distribution_pool) == updated_total_coins) { + return + }; + + // Charge all stakeholders (except for the operator themselves) commission on any rewards earnt relatively to the + // previous value of the distribution pool. + let shareholders = &pool_u64::shareholders(distribution_pool); + vector::for_each_ref(shareholders, |shareholder| { + let shareholder: address = *shareholder; + if (shareholder != operator) { + let shares = pool_u64::shares(distribution_pool, shareholder); + let previous_worth = pool_u64::balance(distribution_pool, shareholder); + let current_worth = pool_u64::shares_to_amount_with_total_coins( + distribution_pool, shares, updated_total_coins); + let unpaid_commission = (current_worth - previous_worth) * commission_percentage / 100; + // Transfer shares from current shareholder to the operator as payment. + // The value of the shares should use the updated pool's total value. + let shares_to_transfer = pool_u64::amount_to_shares_with_total_coins( + distribution_pool, unpaid_commission, updated_total_coins); + pool_u64::transfer_shares(distribution_pool, shareholder, operator, shares_to_transfer); + }; + }); + + pool_u64::update_total_coins(distribution_pool, updated_total_coins); + } + + /// Create the seed to derive the resource account address. + fun create_resource_account_seed( + staker: address, + operator: address, + contract_creation_seed: vector, + ): vector { + let seed = bcs::to_bytes(&staker); + vector::append(&mut seed, bcs::to_bytes(&operator)); + // Include a salt to avoid conflicts with any other modules out there that might also generate + // deterministic resource accounts for the same staker + operator addresses. + vector::append(&mut seed, SALT); + // Add an extra salt given by the staker in case an account with the same address has already been created. + vector::append(&mut seed, contract_creation_seed); + seed + } + + /// Create a new staking_contracts resource. + fun new_staking_contracts_holder(staker: &signer): Store { + Store { + staking_contracts: simple_map::create(), + // Events. + create_staking_contract_events: account::new_event_handle(staker), + update_voter_events: account::new_event_handle(staker), + reset_lockup_events: account::new_event_handle(staker), + add_stake_events: account::new_event_handle(staker), + request_commission_events: account::new_event_handle(staker), + unlock_stake_events: account::new_event_handle(staker), + switch_operator_events: account::new_event_handle(staker), + add_distribution_events: account::new_event_handle(staker), + distribute_events: account::new_event_handle(staker), + } + } + + #[test_only] + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + #[test_only] + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + #[test_only] + use aptos_framework::stake::with_rewards; + + #[test_only] + const INITIAL_BALANCE: u64 = 100000000000000; // 1M APT coins with 8 decimals. + + #[test_only] + const MAXIMUM_STAKE: u64 = 100000000000000000; // 1B APT coins with 8 decimals. + + #[test_only] + public fun setup(aptos_framework: &signer, staker: &signer, operator: &signer, initial_balance: u64) { + // Reward rate of 0.1% per epoch. + stake::initialize_for_test_custom(aptos_framework, INITIAL_BALANCE, MAXIMUM_STAKE, 3600, true, 10, 10000, 1000000); + + let staker_address = signer::address_of(staker); + if (!account::exists_at(staker_address)) { + account::create_account_for_test(staker_address); + }; + let operator_address = signer::address_of(operator); + if (!account::exists_at(operator_address)) { + account::create_account_for_test(operator_address); + }; + stake::mint(staker, initial_balance); + stake::mint(operator, initial_balance); + } + + #[test_only] + public fun setup_staking_contract( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + amount: u64, + commission: u64, + ) acquires Store { + setup(aptos_framework, staker, operator, amount); + let operator_address = signer::address_of(operator); + + // Voter is initially set to operator but then updated to be staker. + create_staking_contract(staker, operator_address, operator_address, amount, commission, vector::empty()); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_end_to_end(aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + assert_staking_contract_exists(staker_address, operator_address); + assert_staking_contract(staker_address, operator_address, INITIAL_BALANCE, 10); + + // Verify that the stake pool has been set up properly. + let pool_address = stake_pool_address(staker_address, operator_address); + stake::assert_stake_pool(pool_address, INITIAL_BALANCE, 0, 0, 0); + assert!(last_recorded_principal(staker_address, operator_address) == INITIAL_BALANCE, 0); + + // Operator joins the validator set. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Operator claims 10% of rewards so far as commissions. + let expected_commission_1 = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + new_balance = new_balance - expected_commission_1; + request_commission(operator, staker_address, operator_address); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, expected_commission_1); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + assert_distribution(staker_address, operator_address, operator_address, expected_commission_1); + stake::fast_forward_to_unlock(pool_address); + + // Both original stake and operator commissions have received rewards. + expected_commission_1 = with_rewards(expected_commission_1); + new_balance = with_rewards(new_balance); + stake::assert_stake_pool(pool_address, new_balance, expected_commission_1, 0, 0); + distribute(staker_address, operator_address); + let operator_balance = coin::balance(operator_address); + let expected_operator_balance = INITIAL_BALANCE + expected_commission_1; + assert!(operator_balance == expected_operator_balance, operator_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + assert_no_pending_distributions(staker_address, operator_address); + + // Staker adds more stake. + stake::mint(staker, INITIAL_BALANCE); + let previous_principal = last_recorded_principal(staker_address, operator_address); + add_stake(staker, operator_address, INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, INITIAL_BALANCE, 0); + assert!(last_recorded_principal(staker_address, operator_address) == previous_principal + INITIAL_BALANCE, 0); + + // The newly added stake didn't receive any rewards because it was only added in the new epoch. + stake::end_epoch(); + new_balance = with_rewards(new_balance) + INITIAL_BALANCE; + + // Second round of commission request/withdrawal. + let expected_commission_2 = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + new_balance = new_balance - expected_commission_2; + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission_2); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + stake::fast_forward_to_unlock(pool_address); + expected_commission_2 = with_rewards(expected_commission_2); + distribute(staker_address, operator_address); + operator_balance = coin::balance(operator_address); + expected_operator_balance = expected_operator_balance + expected_commission_2; + assert!(operator_balance == expected_operator_balance, operator_balance); + assert_no_pending_distributions(staker_address, operator_address); + new_balance = with_rewards(new_balance); + + // New rounds of rewards. + stake::fast_forward_to_unlock(pool_address); + new_balance = with_rewards(new_balance); + + // Staker withdraws all stake, which should also request commission distribution. + let unpaid_commission = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + unlock_stake(staker, operator_address, new_balance); + stake::assert_stake_pool(pool_address, 0, 0, 0, new_balance); + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission); + let withdrawn_amount = new_balance - unpaid_commission; + assert_distribution(staker_address, operator_address, staker_address, withdrawn_amount); + assert!(last_recorded_principal(staker_address, operator_address) == 0, 0); + + // End epoch. The stake pool should get kicked out of the validator set as it has 0 remaining active stake. + stake::fast_forward_to_unlock(pool_address); + // Operator should still earn 10% commission on the rewards on top of the staker's withdrawn_amount. + let commission_on_withdrawn_amount = (with_rewards(withdrawn_amount) - withdrawn_amount) / 10; + unpaid_commission = with_rewards(unpaid_commission) + commission_on_withdrawn_amount; + withdrawn_amount = with_rewards(withdrawn_amount) - commission_on_withdrawn_amount; + stake::assert_stake_pool(pool_address, 0, with_rewards(new_balance), 0, 0); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE, 0); + + // Distribute and verify balances. + distribute(staker_address, operator_address); + assert_no_pending_distributions(staker_address, operator_address); + operator_balance = coin::balance(operator_address); + assert!(operator_balance == expected_operator_balance + unpaid_commission, operator_balance); + let staker_balance = coin::balance(staker_address); + // Staker receives the extra dust due to rounding error. + assert!(staker_balance == withdrawn_amount + 1, staker_balance); + assert_no_pending_distributions(staker_address, operator_address); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_operator_cannot_request_same_commission_multiple_times( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Operator tries to request commission multiple times. But their distribution shouldn't change. + let expected_commission = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_unlock_rewards( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Staker withdraws all accumulated rewards, which should pay commission first. + unlock_rewards(staker, operator_address); + let accumulated_rewards = new_balance - INITIAL_BALANCE; + let expected_commission = accumulated_rewards / 10; + let staker_rewards = accumulated_rewards - expected_commission; + assert_distribution(staker_address, operator_address, staker_address, staker_rewards); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + #[expected_failure(abort_code = 0x80006, location = Self)] + public entry fun test_staker_cannot_create_same_staking_contract_multiple_times( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let operator_address = signer::address_of(operator); + stake::mint(staker, INITIAL_BALANCE); + create_staking_contract(staker, operator_address, operator_address, INITIAL_BALANCE, 10, vector::empty()); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + #[expected_failure(abort_code = 0x10002, location = Self)] + public entry fun test_staker_cannot_create_staking_contract_with_invalid_commission( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 101); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_staker_cannot_create_staking_contract_with_less_than_min_stake_required( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, 50, 100); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_update_voter( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + + // Voter is initially set to operator but then updated to be staker. + let pool_address = stake_pool_address(staker_address, operator_address); + assert!(stake::get_delegated_voter(pool_address) == operator_address, 0); + update_voter(staker, operator_address, staker_address); + assert!(stake::get_delegated_voter(pool_address) == staker_address, 1); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_reset_lockup( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + let origin_lockup_expiration = stake::get_lockup_secs(pool_address); + reset_lockup(staker, operator_address); + assert!(origin_lockup_expiration < stake::get_lockup_secs(pool_address), 0); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator_1 = @0x234, operator_2 = @0x345)] + public entry fun test_staker_can_switch_operator( + aptos_framework: &signer, + staker: &signer, + operator_1: &signer, + operator_2: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator_1, INITIAL_BALANCE, 10); + account::create_account_for_test(signer::address_of(operator_2)); + stake::mint(operator_2, INITIAL_BALANCE); + let staker_address = signer::address_of(staker); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + + // Join validator set and earn some rewards. + let pool_address = stake_pool_address(staker_address, operator_1_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator_1, pool_address, true); + stake::end_epoch(); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + + // Switch operators. + switch_operator(staker, operator_1_address, operator_2_address, 20); + // The staking_contract is now associated with operator 2 but there should be a pending distribution of unpaid + // commission to operator 1. + let new_balance = with_rewards(INITIAL_BALANCE); + let commission_for_operator_1 = (new_balance - INITIAL_BALANCE) / 10; + assert_distribution(staker_address, operator_2_address, operator_1_address, commission_for_operator_1); + // Unpaid commission should be unlocked from the stake pool. + new_balance = new_balance - commission_for_operator_1; + stake::assert_stake_pool(pool_address, new_balance, 0, 0, commission_for_operator_1); + assert!(last_recorded_principal(staker_address, operator_2_address) == new_balance, 0); + + // The stake pool's validator should not have left the validator set. + assert!(stake_pool_address(staker_address, operator_2_address) == pool_address, 1); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 2); + + // End epoch to get more rewards. + stake::fast_forward_to_unlock(pool_address); + new_balance = with_rewards(new_balance); + // Rewards on the commission being paid to operator_1 should still be charged commission that will go to + // operator_2; + let commission_on_operator_1_distribution = + (with_rewards(commission_for_operator_1) - commission_for_operator_1) / 5; + commission_for_operator_1 = with_rewards(commission_for_operator_1) - commission_on_operator_1_distribution; + + // Verify that when commissions are withdrawn, previous pending distribution to operator 1 also happens. + // Then new commission of 20% is paid to operator 2. + let commission_for_operator_2 = + (new_balance - last_recorded_principal(staker_address, operator_2_address)) / 5; + new_balance = new_balance - commission_for_operator_2; + request_commission(operator_2, staker_address, operator_2_address); + assert_distribution(staker_address, operator_2_address, operator_2_address, commission_for_operator_2); + let operator_1_balance = coin::balance(operator_1_address); + assert!(operator_1_balance == INITIAL_BALANCE + commission_for_operator_1, operator_1_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, commission_for_operator_2); + assert!(last_recorded_principal(staker_address, operator_2_address) == new_balance, 0); + stake::fast_forward_to_unlock(pool_address); + + // Operator 2's commission is distributed. + distribute(staker_address, operator_2_address); + let operator_2_balance = coin::balance(operator_2_address); + new_balance = with_rewards(new_balance); + commission_for_operator_2 = with_rewards(commission_for_operator_2); + assert!( + operator_2_balance == INITIAL_BALANCE + commission_for_operator_2 + commission_on_operator_1_distribution, + operator_2_balance, + ); + stake::assert_stake_pool( + pool_address, + new_balance, + 0, + 0, + 0, + ); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator_1 = @0x234, operator_2 = @0x345)] + public entry fun test_staker_can_switch_operator_with_same_commission( + aptos_framework: &signer, + staker: &signer, + operator_1: &signer, + operator_2: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator_1, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + + // Switch operators. + switch_operator_with_same_commission(staker, operator_1_address, operator_2_address); + // The staking_contract should now be associated with operator 2 but with same commission rate. + assert!(staking_contract_exists(staker_address, operator_2_address), 0); + assert!(!staking_contract_exists(staker_address, operator_1_address), 1); + assert!(commission_percentage(staker_address, operator_2_address) == 10, 2); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_staker_can_withdraw_partial_stake( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set so rewards are generated. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(initial_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Staker withdraws 1/4 of the stake, which should also request commission distribution. + let withdrawn_stake = new_balance / 4; + let unpaid_commission = (new_balance - initial_balance) / 10; + let new_balance = new_balance - withdrawn_stake - unpaid_commission; + unlock_stake(staker, operator_address, withdrawn_stake); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake + unpaid_commission); + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + + // The validator is still in the active set as its remaining stake is still above min required. + stake::fast_forward_to_unlock(pool_address); + new_balance = with_rewards(new_balance); + unpaid_commission = with_rewards(unpaid_commission); + // Commission should still be charged on the rewards on top of withdrawn_stake. + // So the operator should receive 10% of the rewards on top of withdrawn_stake. + let commission_on_withdrawn_stake = (with_rewards(withdrawn_stake) - withdrawn_stake) / 10; + unpaid_commission = unpaid_commission + commission_on_withdrawn_stake; + withdrawn_stake = with_rewards(withdrawn_stake) - commission_on_withdrawn_stake; + stake::assert_stake_pool(pool_address, new_balance, withdrawn_stake + unpaid_commission, 0, 0); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + + // Distribute and verify balances. + distribute(staker_address, operator_address); + assert_no_pending_distributions(staker_address, operator_address); + let operator_balance = coin::balance(operator_address); + assert!(operator_balance == initial_balance + unpaid_commission, operator_balance); + let staker_balance = coin::balance(staker_address); + assert!(staker_balance == withdrawn_stake, staker_balance); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_staker_can_withdraw_partial_stake_if_operator_never_joined_validator_set( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Epoch ended, but since validator never joined the set, no rewards were minted. + stake::end_epoch(); + stake::assert_stake_pool(pool_address, initial_balance, 0, 0, 0); + + // Staker withdraws 1/4 of the stake, which doesn't create any commission distribution as there's no rewards. + let withdrawn_stake = initial_balance / 4; + let new_balance = initial_balance - withdrawn_stake; + unlock_stake(staker, operator_address, withdrawn_stake); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake); + assert_distribution(staker_address, operator_address, operator_address, 0); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + + // Distribute and verify balances. + distribute(staker_address, operator_address); + assert_no_pending_distributions(staker_address, operator_address); + // Operator's balance shouldn't change as there are no rewards. + let operator_balance = coin::balance(operator_address); + assert!(operator_balance == initial_balance, operator_balance); + // Staker receives back the withdrawn amount (no rewards). + let staker_balance = coin::balance(staker_address); + assert!(staker_balance == withdrawn_stake, staker_balance); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_multiple_distributions_added_before_distribute( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set so rewards are generated. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(initial_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Staker withdraws 1/4 of the stake, which should also request commission distribution. + let withdrawn_stake = new_balance / 4; + let unpaid_commission = (new_balance - initial_balance) / 10; + let new_balance = new_balance - withdrawn_stake - unpaid_commission; + unlock_stake(staker, operator_address, withdrawn_stake); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake + unpaid_commission); + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + + // End epoch to generate some rewards. Staker withdraws another 1/4 of the stake. + // Commission should be charged on the rewards earned on the previous 1/4 stake withdrawal. + stake::end_epoch(); + let commission_on_withdrawn_stake = (with_rewards(withdrawn_stake) - withdrawn_stake) / 10; + let commission_on_new_balance = (with_rewards(new_balance) - new_balance) / 10; + unpaid_commission = with_rewards(unpaid_commission) + commission_on_withdrawn_stake + commission_on_new_balance; + new_balance = with_rewards(new_balance) - commission_on_new_balance; + let new_withdrawn_stake = new_balance / 4; + unlock_stake(staker, operator_address, new_withdrawn_stake); + new_balance = new_balance - new_withdrawn_stake; + withdrawn_stake = with_rewards(withdrawn_stake) - commission_on_withdrawn_stake + new_withdrawn_stake; + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake + unpaid_commission); + // There's some small rounding error here. + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission - 1); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + } + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_update_commission(aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store, StakingGroupUpdateCommissionEvent { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set so rewards are generated. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let balance_1epoch = with_rewards(initial_balance); + let unpaid_commission = (balance_1epoch - initial_balance) / 10; + stake::assert_stake_pool(pool_address, balance_1epoch, 0, 0, 0); + + update_commision(staker, operator_address, 5); + stake::end_epoch(); + let balance_2epoch = with_rewards(balance_1epoch - unpaid_commission); + stake::assert_stake_pool(pool_address, balance_2epoch, 0, 0, with_rewards(unpaid_commission)); + } + + #[test(staker = @0xe256f4f4e2986cada739e339895cf5585082ff247464cab8ec56eea726bd2263, operator= @0x9f0a211d218b082987408f1e393afe1ba0c202c6d280f081399788d3360c7f09)] + public entry fun test_get_expected_stake_pool_address(staker: address, operator: address) { + let pool_address = get_expected_stake_pool_address(staker, operator, vector[0x42, 0x42]); + assert!(pool_address == @0x9d9648031ada367c26f7878eb0b0406ae6a969b1a43090269e5cdfabe1b48f0f, 0); + } + + #[test_only] + public fun assert_staking_contract( + staker: address, operator: address, principal: u64, commission_percentage: u64) acquires Store { + let staking_contract = simple_map::borrow(&borrow_global(staker).staking_contracts, &operator); + assert!(staking_contract.principal == principal, staking_contract.principal); + assert!(staking_contract.commission_percentage == commission_percentage, staking_contract.commission_percentage); + } + + #[test_only] + public fun assert_no_pending_distributions(staker: address, operator: address) acquires Store { + let staking_contract = simple_map::borrow(&borrow_global(staker).staking_contracts, &operator); + let distribution_pool = &staking_contract.distribution_pool; + let shareholders_count = pool_u64::shareholders_count(distribution_pool); + assert!(shareholders_count == 0, shareholders_count); + let total_coins_remaining = pool_u64::total_coins(distribution_pool); + assert!(total_coins_remaining == 0, total_coins_remaining); + } + + #[test_only] + public fun assert_distribution( + staker: address, operator: address, recipient: address, coins_amount: u64) acquires Store { + let staking_contract = simple_map::borrow(&borrow_global(staker).staking_contracts, &operator); + let distribution_balance = pool_u64::balance(&staking_contract.distribution_pool, recipient); + assert!(distribution_balance == coins_amount, distribution_balance); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_proxy.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_proxy.move new file mode 100644 index 0000000..26d1aa3 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/staking_proxy.move @@ -0,0 +1,228 @@ +module aptos_framework::staking_proxy { + use std::signer; + use std::vector; + + use aptos_framework::stake; + use aptos_framework::staking_contract; + use aptos_framework::vesting; + + public entry fun set_operator(owner: &signer, old_operator: address, new_operator: address) { + set_vesting_contract_operator(owner, old_operator, new_operator); + set_staking_contract_operator(owner, old_operator, new_operator); + set_stake_pool_operator(owner, new_operator); + } + + public entry fun set_voter(owner: &signer, operator: address, new_voter: address) { + set_vesting_contract_voter(owner, operator, new_voter); + set_staking_contract_voter(owner, operator, new_voter); + set_stake_pool_voter(owner, new_voter); + } + + public entry fun set_vesting_contract_operator(owner: &signer, old_operator: address, new_operator: address) { + let owner_address = signer::address_of(owner); + let vesting_contracts = &vesting::vesting_contracts(owner_address); + vector::for_each_ref(vesting_contracts, |vesting_contract| { + let vesting_contract = *vesting_contract; + if (vesting::operator(vesting_contract) == old_operator) { + let current_commission_percentage = vesting::operator_commission_percentage(vesting_contract); + vesting::update_operator(owner, vesting_contract, new_operator, current_commission_percentage); + }; + }); + } + + public entry fun set_staking_contract_operator(owner: &signer, old_operator: address, new_operator: address) { + let owner_address = signer::address_of(owner); + if (staking_contract::staking_contract_exists(owner_address, old_operator)) { + let current_commission_percentage = staking_contract::commission_percentage(owner_address, old_operator); + staking_contract::switch_operator(owner, old_operator, new_operator, current_commission_percentage); + }; + } + + public entry fun set_stake_pool_operator(owner: &signer, new_operator: address) { + let owner_address = signer::address_of(owner); + if (stake::stake_pool_exists(owner_address)) { + stake::set_operator(owner, new_operator); + }; + } + + public entry fun set_vesting_contract_voter(owner: &signer, operator: address, new_voter: address) { + let owner_address = signer::address_of(owner); + let vesting_contracts = &vesting::vesting_contracts(owner_address); + vector::for_each_ref(vesting_contracts, |vesting_contract| { + let vesting_contract = *vesting_contract; + if (vesting::operator(vesting_contract) == operator) { + vesting::update_voter(owner, vesting_contract, new_voter); + }; + }); + } + + public entry fun set_staking_contract_voter(owner: &signer, operator: address, new_voter: address) { + let owner_address = signer::address_of(owner); + if (staking_contract::staking_contract_exists(owner_address, operator)) { + staking_contract::update_voter(owner, operator, new_voter); + }; + } + + public entry fun set_stake_pool_voter(owner: &signer, new_voter: address) { + if (stake::stake_pool_exists(signer::address_of(owner))) { + stake::set_delegated_voter(owner, new_voter); + }; + } + + #[test_only] + const INITIAL_BALANCE: u64 = 100000000000000; // 1M APT coins with 8 decimals. + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_operator = @0x567, + )] + public entry fun test_set_operator( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_operator: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_operator_address = signer::address_of(new_operator); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_operator_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_1, INITIAL_BALANCE, 0); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_1 = vesting::setup_vesting_contract(owner, &vector[@11], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_1, operator_1_address, 0); + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + let (_sk, pk, pop) = stake::generate_identity(); + stake::initialize_test_validator(&pk, &pop, owner, INITIAL_BALANCE, false, false); + stake::set_operator(owner, operator_1_address); + + set_operator(owner, operator_1_address, new_operator_address); + // Stake pool's operator has been switched from operator 1 to new operator. + assert!(stake::get_operator(owner_address) == new_operator_address, 0); + // Staking contract has been switched from operator 1 to new operator. + // Staking contract with operator_2 should stay unchanged. + assert!(staking_contract::staking_contract_exists(owner_address, new_operator_address), 1); + assert!(!staking_contract::staking_contract_exists(owner_address, operator_1_address), 2); + assert!(staking_contract::staking_contract_exists(owner_address, operator_2_address), 3); + // Vesting contract 1 has been switched from operator 1 to new operator while vesting contract 2 stays unchanged + assert!(vesting::operator(vesting_contract_1) == new_operator_address, 4); + assert!(vesting::operator(vesting_contract_2) == operator_2_address, 5); + } + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_operator = @0x567, + )] + public entry fun test_set_operator_nothing_to_change( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_operator: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_operator_address = signer::address_of(new_operator); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_operator_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + set_operator(owner, operator_1_address, new_operator_address); + // No staking or vesting contracts changed. + assert!(!staking_contract::staking_contract_exists(owner_address, new_operator_address), 0); + assert!(staking_contract::staking_contract_exists(owner_address, operator_2_address), 1); + assert!(vesting::operator(vesting_contract_2) == operator_2_address, 2); + } + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_voter = @0x567, + )] + public entry fun test_set_voter( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_voter: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_voter_address = signer::address_of(new_voter); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_voter_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_1, INITIAL_BALANCE, 0); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_1 = vesting::setup_vesting_contract(owner, &vector[@11], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_1, operator_1_address, 0); + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + let (_sk, pk, pop) = stake::generate_identity(); + stake::initialize_test_validator(&pk, &pop, owner, INITIAL_BALANCE, false, false); + + set_voter(owner, operator_1_address, new_voter_address); + // Stake pool's voter has been updated. + assert!(stake::get_delegated_voter(owner_address) == new_voter_address, 0); + // Staking contract with operator 1's voter has been updated. + // Staking contract with operator_2 should stay unchanged. + let stake_pool_address_1 = staking_contract::stake_pool_address(owner_address, operator_1_address); + let stake_pool_address_2 = staking_contract::stake_pool_address(owner_address, operator_2_address); + assert!(stake::get_delegated_voter(stake_pool_address_1) == new_voter_address, 1); + assert!(stake::get_delegated_voter(stake_pool_address_2) == operator_2_address, 2); + // Vesting contract 1's voter has been updated while vesting contract 2's stays unchanged. + assert!(vesting::voter(vesting_contract_1) == new_voter_address, 3); + assert!(vesting::voter(vesting_contract_2) == owner_address, 4); + } + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_voter = @0x567, + )] + public entry fun test_set_voter_nothing_to_change( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_voter: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_voter_address = signer::address_of(new_voter); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_voter_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + set_operator(owner, operator_1_address, new_voter_address); + // No staking or vesting contracts changed. + let stake_pool_address = staking_contract::stake_pool_address(owner_address, operator_2_address); + assert!(stake::get_delegated_voter(stake_pool_address) == operator_2_address, 0); + assert!(vesting::voter(vesting_contract_2) == owner_address, 1); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/state_storage.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/state_storage.move new file mode 100644 index 0000000..9db2fb8 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/state_storage.move @@ -0,0 +1,90 @@ +module aptos_framework::state_storage { + + use aptos_framework::system_addresses; + use std::error; + + friend aptos_framework::block; + friend aptos_framework::genesis; + friend aptos_framework::storage_gas; + + const ESTATE_STORAGE_USAGE: u64 = 0; + + struct Usage has copy, drop, store { + items: u64, + bytes: u64, + } + + /// This is updated at the begining of each opoch, reflecting the storage + /// usage after the last txn of the previous epoch is committed. + struct StateStorageUsage has key, store { + epoch: u64, + usage: Usage, + } + + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(ESTATE_STORAGE_USAGE) + ); + move_to(aptos_framework, StateStorageUsage { + epoch: 0, + usage: Usage { + items: 0, + bytes: 0, + } + }); + } + + public(friend) fun on_new_block(epoch: u64) acquires StateStorageUsage { + assert!( + exists(@aptos_framework), + error::not_found(ESTATE_STORAGE_USAGE) + ); + let usage = borrow_global_mut(@aptos_framework); + if (epoch != usage.epoch) { + usage.epoch = epoch; + usage.usage = get_state_storage_usage_only_at_epoch_beginning(); + } + } + + public(friend) fun current_items_and_bytes(): (u64, u64) acquires StateStorageUsage { + assert!( + exists(@aptos_framework), + error::not_found(ESTATE_STORAGE_USAGE) + ); + let usage = borrow_global(@aptos_framework); + (usage.usage.items, usage.usage.bytes) + } + + /// Warning: the result returned is based on the base state view held by the + /// VM for the entire block or chunk of transactions, it's only deterministic + /// if called from the first transaction of the block because the execution layer + /// guarantees a fresh state view then. + native fun get_state_storage_usage_only_at_epoch_beginning(): Usage; + + #[test_only] + public fun set_for_test(epoch: u64, items: u64, bytes: u64) acquires StateStorageUsage { + assert!( + exists(@aptos_framework), + error::not_found(ESTATE_STORAGE_USAGE) + ); + let usage = borrow_global_mut(@aptos_framework); + usage.epoch = epoch; + usage.usage = Usage { + items, + bytes + }; + } + + // ======================== deprecated ============================ + friend aptos_framework::reconfiguration; + + struct GasParameter has key, store { + usage: Usage, + } + + public(friend) fun on_reconfig() { + abort 0 + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/storage_gas.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/storage_gas.move new file mode 100644 index 0000000..991b619 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/storage_gas.move @@ -0,0 +1,622 @@ +/// Gas parameters for global storage. +/// +/// # General overview sections +/// +/// [Definitions](#definitions) +/// +/// * [Utilization dimensions](#utilization-dimensions) +/// * [Utilization ratios](#utilization-ratios) +/// * [Gas curve lookup](#gas-curve-lookup) +/// * [Item-wise operations](#item-wise-operations) +/// * [Byte-wise operations](#byte-wise-operations) +/// +/// [Function dependencies](#function-dependencies) +/// +/// * [Initialization](#initialization) +/// * [Reconfiguration](#reconfiguration) +/// * [Setting configurations](#setting-configurations) +/// +/// # Definitions +/// +/// ## Utilization dimensions +/// +/// Global storage gas fluctuates each epoch based on total utilization, +/// which is defined across two dimensions: +/// +/// 1. The number of "items" in global storage. +/// 2. The number of bytes in global storage. +/// +/// "Items" include: +/// +/// 1. Resources having the `key` attribute, which have been moved into +/// global storage via a `move_to()` operation. +/// 2. Table entries. +/// +/// ## Utilization ratios +/// +/// `initialize()` sets an arbitrary "target" utilization for both +/// item-wise and byte-wise storage, then each epoch, gas parameters are +/// reconfigured based on the "utilization ratio" for each of the two +/// utilization dimensions. The utilization ratio for a given dimension, +/// either item-wise or byte-wise, is taken as the quotient of actual +/// utilization and target utilization. For example, given a 500 GB +/// target and 250 GB actual utilization, the byte-wise utilization +/// ratio is 50%. +/// +/// See `base_8192_exponential_curve()` for mathematical definitions. +/// +/// ## Gas curve lookup +/// +/// The utilization ratio in a given epoch is used as a lookup value in +/// a Eulerian approximation to an exponential curve, known as a +/// `GasCurve`, which is defined in `base_8192_exponential_curve()`, +/// based on a minimum gas charge and a maximum gas charge. +/// +/// The minimum gas charge and maximum gas charge at the endpoints of +/// the curve are set in `initialize()`, and correspond to the following +/// operations defined in `StorageGas`: +/// +/// 1. Per-item read +/// 2. Per-item create +/// 3. Per-item write +/// 4. Per-byte read +/// 5. Per-byte create +/// 6. Per-byte write +/// +/// For example, if the byte-wise utilization ratio is 50%, then +/// per-byte reads will charge the minimum per-byte gas cost, plus +/// 1.09% of the difference between the maximum and the minimum cost. +/// See `base_8192_exponential_curve()` for a supporting calculation. +/// +/// ## Item-wise operations +/// +/// 1. Per-item read gas is assessed whenever an item is read from +/// global storage via `borrow_global()` or via a table entry read +/// operation. +/// 2. Per-item create gas is assessed whenever an item is created in +/// global storage via `move_to()` or via a table entry creation +/// operation. +/// 3. Per-item write gas is assessed whenever an item is overwritten in +/// global storage via `borrow_global_mut` or via a table entry +/// mutation operation. +/// +/// ## Byte-wise operations +/// +/// Byte-wise operations are assessed in a manner similar to per-item +/// operations, but account for the number of bytes affected by the +/// given operation. Notably, this number denotes the total number of +/// bytes in an *entire item*. +/// +/// For example, if an operation mutates a `u8` field in a resource that +/// has 5 other `u128` fields, the per-byte gas write cost will account +/// for $(5 * 128) / 8 + 1 = 81$ bytes. Vectors are similarly treated +/// as fields. +/// +/// # Function dependencies +/// +/// The below dependency chart uses `mermaid.js` syntax, which can be +/// automatically rendered into a diagram (depending on the browser) +/// when viewing the documentation file generated from source code. If +/// a browser renders the diagrams with coloring that makes it difficult +/// to read, try a different browser. +/// +/// ## Initialization +/// +/// ```mermaid +/// +/// flowchart LR +/// +/// initialize --> base_8192_exponential_curve +/// base_8192_exponential_curve --> new_gas_curve +/// base_8192_exponential_curve --> new_point +/// new_gas_curve --> validate_points +/// +/// ``` +/// +/// ## Reconfiguration +/// +/// ```mermaid +/// +/// flowchart LR +/// +/// calculate_gas --> Interpolate %% capitalized +/// calculate_read_gas --> calculate_gas +/// calculate_create_gas --> calculate_gas +/// calculate_write_gas --> calculate_gas +/// on_reconfig --> calculate_read_gas +/// on_reconfig --> calculate_create_gas +/// on_reconfig --> calculate_write_gas +/// reconfiguration::reconfigure --> on_reconfig +/// +/// ``` +/// +/// Here, the function `interpolate()` is spelled `Interpolate` because +/// `interpolate` is a reserved word in `mermaid.js`. +/// +/// ## Setting configurations +/// +/// ```mermaid +/// +/// flowchart LR +/// +/// gas_schedule::set_storage_gas_config --> set_config +/// +/// ``` +/// +/// # Complete docgen index +/// +/// The below index is automatically generated from source code: +module aptos_framework::storage_gas { + + use aptos_framework::system_addresses; + use std::error; + use aptos_framework::state_storage; + use std::vector; + + friend aptos_framework::gas_schedule; + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration; + + const ESTORAGE_GAS_CONFIG: u64 = 0; + const ESTORAGE_GAS: u64 = 1; + const EINVALID_GAS_RANGE: u64 = 2; + const EZERO_TARGET_USAGE: u64 = 3; + const ETARGET_USAGE_TOO_BIG: u64 = 4; + const EINVALID_MONOTONICALLY_NON_DECREASING_CURVE: u64 = 5; + const EINVALID_POINT_RANGE: u64 = 6; + + const BASIS_POINT_DENOMINATION: u64 = 10000; + + const MAX_U64: u64 = 18446744073709551615; + + /// Storage parameters, reconfigured each epoch. + /// + /// Parameters are updated during reconfiguration via + /// `on_reconfig()`, based on storage utilization at the beginning + /// of the epoch in which the reconfiguration transaction is + /// executed. The gas schedule derived from these parameters will + /// then be used to calculate gas for the entirety of the + /// following epoch, such that the data is one epoch older than + /// ideal. Notably, however, per this approach, the virtual machine + /// does not need to reload gas parameters after the + /// first transaction of an epoch. + struct StorageGas has key { + /// Cost to read an item from global storage. + per_item_read: u64, + /// Cost to create an item in global storage. + per_item_create: u64, + /// Cost to overwrite an item in global storage. + per_item_write: u64, + /// Cost to read a byte from global storage. + per_byte_read: u64, + /// Cost to create a byte in global storage. + per_byte_create: u64, + /// Cost to overwrite a byte in global storage. + per_byte_write: u64, + } + + /// A point in a Eulerian curve approximation, with each coordinate + /// given in basis points: + /// + /// | Field value | Percentage | + /// |-------------|------------| + /// | `1` | 00.01 % | + /// | `10` | 00.10 % | + /// | `100` | 01.00 % | + /// | `1000` | 10.00 % | + struct Point has copy, drop, store { + /// x-coordinate basis points, corresponding to utilization + /// ratio in `base_8192_exponential_curve()`. + x: u64, + /// y-coordinate basis points, corresponding to utilization + /// multiplier in `base_8192_exponential_curve()`. + y: u64 + } + + /// A gas configuration for either per-item or per-byte costs. + /// + /// Contains a target usage amount, as well as a Eulerian + /// approximation of an exponential curve for reads, creations, and + /// overwrites. See `StorageGasConfig`. + struct UsageGasConfig has copy, drop, store { + target_usage: u64, + read_curve: GasCurve, + create_curve: GasCurve, + write_curve: GasCurve, + } + + /// Eulerian approximation of an exponential curve. + /// + /// Assumes the following endpoints: + /// + /// * $(x_0, y_0) = (0, 0)$ + /// * $(x_f, y_f) = (10000, 10000)$ + /// + /// Intermediate points must satisfy: + /// + /// 1. $x_i > x_{i - 1}$ ( $x$ is strictly increasing). + /// 2. $0 \leq x_i \leq 10000$ ( $x$ is between 0 and 10000). + /// 3. $y_i \geq y_{i - 1}$ ( $y$ is non-decreasing). + /// 4. $0 \leq y_i \leq 10000$ ( $y$ is between 0 and 10000). + /// + /// Lookup between two successive points is calculated via linear + /// interpolation, e.g., as if there were a straight line between + /// them. + /// + /// See `base_8192_exponential_curve()`. + struct GasCurve has copy, drop, store { + min_gas: u64, + max_gas: u64, + points: vector, + } + + /// Default exponential curve having base 8192. + /// + /// # Function definition + /// + /// Gas price as a function of utilization ratio is defined as: + /// + /// $$g(u_r) = g_{min} + \frac{(b^{u_r} - 1)}{b - 1} \Delta_g$$ + /// + /// $$g(u_r) = g_{min} + u_m \Delta_g$$ + /// + /// | Variable | Description | + /// |-------------------------------------|------------------------| + /// | $g_{min}$ | `min_gas` | + /// | $g_{max}$ | `max_gas` | + /// | $\Delta_{g} = g_{max} - g_{min}$ | Gas delta | + /// | $u$ | Utilization | + /// | $u_t$ | Target utilization | + /// | $u_r = u / u_t$ | Utilization ratio | + /// | $u_m = \frac{(b^{u_r} - 1)}{b - 1}$ | Utilization multiplier | + /// | $b = 8192$ | Exponent base | + /// + /// # Example + /// + /// Hence for a utilization ratio of 50% ( $u_r = 0.5$ ): + /// + /// $$g(0.5) = g_{min} + \frac{8192^{0.5} - 1}{8192 - 1} \Delta_g$$ + /// + /// $$g(0.5) \approx g_{min} + 0.0109 \Delta_g$$ + /// + /// Which means that the price above `min_gas` is approximately + /// 1.09% of the difference between `max_gas` and `min_gas`. + /// + /// # Utilization multipliers + /// + /// | $u_r$ | $u_m$ (approximate) | + /// |-------|---------------------| + /// | 10% | 0.02% | + /// | 20% | 0.06% | + /// | 30% | 0.17% | + /// | 40% | 0.44% | + /// | 50% | 1.09% | + /// | 60% | 2.71% | + /// | 70% | 6.69% | + /// | 80% | 16.48% | + /// | 90% | 40.61% | + /// | 95% | 63.72% | + /// | 99% | 91.38% | + public fun base_8192_exponential_curve(min_gas: u64, max_gas: u64): GasCurve { + new_gas_curve(min_gas, max_gas, + vector[ + new_point(1000, 2), + new_point(2000, 6), + new_point(3000, 17), + new_point(4000, 44), + new_point(5000, 109), + new_point(6000, 271), + new_point(7000, 669), + new_point(8000, 1648), + new_point(9000, 4061), + new_point(9500, 6372), + new_point(9900, 9138), + ] + ) + } + + /// Gas configurations for per-item and per-byte prices. + struct StorageGasConfig has copy, drop, key { + /// Per-item gas configuration. + item_config: UsageGasConfig, + /// Per-byte gas configuration. + byte_config: UsageGasConfig, + } + + public fun new_point(x: u64, y: u64): Point { + assert!( + x <= BASIS_POINT_DENOMINATION && y <= BASIS_POINT_DENOMINATION, + error::invalid_argument(EINVALID_POINT_RANGE) + ); + Point { x, y } + } + + public fun new_gas_curve(min_gas: u64, max_gas: u64, points: vector): GasCurve { + assert!(max_gas >= min_gas, error::invalid_argument(EINVALID_GAS_RANGE)); + assert!(max_gas <= MAX_U64 / BASIS_POINT_DENOMINATION, error::invalid_argument(EINVALID_GAS_RANGE)); + validate_points(&points); + GasCurve { + min_gas, + max_gas, + points + } + } + + public fun new_usage_gas_config(target_usage: u64, read_curve: GasCurve, create_curve: GasCurve, write_curve: GasCurve): UsageGasConfig { + assert!(target_usage > 0, error::invalid_argument(EZERO_TARGET_USAGE)); + assert!(target_usage <= MAX_U64 / BASIS_POINT_DENOMINATION, error::invalid_argument(ETARGET_USAGE_TOO_BIG)); + UsageGasConfig { + target_usage, + read_curve, + create_curve, + write_curve, + } + } + + public fun new_storage_gas_config(item_config: UsageGasConfig, byte_config: UsageGasConfig): StorageGasConfig { + StorageGasConfig { + item_config, + byte_config + } + } + + public(friend) fun set_config(aptos_framework: &signer, config: StorageGasConfig) acquires StorageGasConfig { + system_addresses::assert_aptos_framework(aptos_framework); + *borrow_global_mut(@aptos_framework) = config; + } + + /// Initialize per-item and per-byte gas prices. + /// + /// Target utilization is set to 2 billion items and 1 TB. + /// + /// `GasCurve` endpoints are initialized as follows: + /// + /// | Data style | Operation | Minimum gas | Maximum gas | + /// |------------|-----------|-------------|-------------| + /// | Per item | Read | 300K | 300K * 100 | + /// | Per item | Create | 300k | 300k * 100 | + /// | Per item | Write | 300K | 300K * 100 | + /// | Per byte | Read | 300 | 300 * 100 | + /// | Per byte | Create | 5K | 5K * 100 | + /// | Per byte | Write | 5K | 5K * 100 | + /// + /// `StorageGas` values are additionally initialized, but per + /// `on_reconfig()`, they will be reconfigured for each subsequent + /// epoch after initialization. + /// + /// See `base_8192_exponential_curve()` fore more information on + /// target utilization. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(ESTORAGE_GAS_CONFIG) + ); + + let k: u64 = 1000; + let m: u64 = 1000 * 1000; + + let item_config = UsageGasConfig { + target_usage: 2 * k * m, // 2 billion + read_curve: base_8192_exponential_curve(300 * k, 300 * k * 100), + create_curve: base_8192_exponential_curve(300 * k, 300 * k * 100), + write_curve: base_8192_exponential_curve(300 * k, 300 * k * 100), + }; + let byte_config = UsageGasConfig { + target_usage: 1 * m * m, // 1TB + read_curve: base_8192_exponential_curve(300, 300 * 100), + create_curve: base_8192_exponential_curve(5 * k, 5 * k * 100), + write_curve: base_8192_exponential_curve(5 * k, 5 * k * 100), + }; + move_to(aptos_framework, StorageGasConfig { + item_config, + byte_config, + }); + + assert!( + !exists(@aptos_framework), + error::already_exists(ESTORAGE_GAS) + ); + move_to(aptos_framework, StorageGas { + per_item_read: 300 * k, + per_item_create: 5 * m, + per_item_write: 300 * k, + per_byte_read: 300, + per_byte_create: 5 * k, + per_byte_write: 5 * k, + }); + } + + fun validate_points(points: &vector) { + let len = vector::length(points); + spec { + assume len < MAX_U64; + }; + let i = 0; + while ({ + spec { + invariant forall j in 0..i: { + let cur = if (j == 0) { Point { x: 0, y: 0 } } else { points[j - 1] }; + let next = if (j == len) { Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION } } else { points[j] }; + cur.x < next.x && cur.y <= next.y + }; + }; + i <= len + }) { + let cur = if (i == 0) { &Point { x: 0, y: 0 } } else { vector::borrow(points, i - 1) }; + let next = if (i == len) { &Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION } } else { vector::borrow(points, i) }; + assert!(cur.x < next.x && cur.y <= next.y, error::invalid_argument(EINVALID_MONOTONICALLY_NON_DECREASING_CURVE)); + i = i + 1; + } + } + + fun calculate_gas(max_usage: u64, current_usage: u64, curve: &GasCurve): u64 { + let capped_current_usage = if (current_usage > max_usage) max_usage else current_usage; + let points = &curve.points; + let num_points = vector::length(points); + let current_usage_bps = capped_current_usage * BASIS_POINT_DENOMINATION / max_usage; + + // Check the corner case that current_usage_bps drops before the first point. + let (left, right) = if (num_points == 0) { + (&Point { x: 0, y: 0 }, &Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION }) + } else if (current_usage_bps < vector::borrow(points, 0).x) { + (&Point { x: 0, y: 0 }, vector::borrow(points, 0)) + } else if (vector::borrow(points, num_points - 1).x <= current_usage_bps) { + (vector::borrow(points, num_points - 1), &Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION }) + } else { + let (i, j) = (0, num_points - 2); + while ({ + spec { + invariant i <= j; + invariant j < num_points - 1; + invariant points[i].x <= current_usage_bps; + invariant current_usage_bps < points[j + 1].x; + }; + i < j + }) { + let mid = j - (j - i) / 2; + if (current_usage_bps < vector::borrow(points, mid).x) { + spec { + // j is strictly decreasing. + assert mid - 1 < j; + }; + j = mid - 1; + } else { + spec { + // i is strictly increasing. + assert i < mid; + }; + i = mid; + }; + }; + (vector::borrow(points, i), vector::borrow(points, i + 1)) + }; + let y_interpolated = interpolate(left.x, right.x, left.y, right.y, current_usage_bps); + interpolate(0, BASIS_POINT_DENOMINATION, curve.min_gas, curve.max_gas, y_interpolated) + } + + // Interpolates y for x on the line between (x0, y0) and (x1, y1). + fun interpolate(x0: u64, x1: u64, y0: u64, y1: u64, x: u64): u64 { + y0 + (x - x0) * (y1 - y0) / (x1 - x0) + } + + fun calculate_read_gas(config: &UsageGasConfig, usage: u64): u64 { + calculate_gas(config.target_usage, usage, &config.read_curve) + } + + fun calculate_create_gas(config: &UsageGasConfig, usage: u64): u64 { + calculate_gas(config.target_usage, usage, &config.create_curve) + } + + fun calculate_write_gas(config: &UsageGasConfig, usage: u64): u64 { + calculate_gas(config.target_usage, usage, &config.write_curve) + } + + public(friend) fun on_reconfig() acquires StorageGas, StorageGasConfig { + assert!( + exists(@aptos_framework), + error::not_found(ESTORAGE_GAS_CONFIG) + ); + assert!( + exists(@aptos_framework), + error::not_found(ESTORAGE_GAS) + ); + let (items, bytes) = state_storage::current_items_and_bytes(); + let gas_config = borrow_global(@aptos_framework); + let gas = borrow_global_mut(@aptos_framework); + gas.per_item_read = calculate_read_gas(&gas_config.item_config, items); + gas.per_item_create = calculate_create_gas(&gas_config.item_config, items); + gas.per_item_write = calculate_write_gas(&gas_config.item_config, items); + gas.per_byte_read = calculate_read_gas(&gas_config.byte_config, bytes); + gas.per_byte_create = calculate_create_gas(&gas_config.byte_config, bytes); + gas.per_byte_write = calculate_write_gas(&gas_config.byte_config, bytes); + } + + // TODO: reactivate this test after fixing assertions + //#[test(framework = @aptos_framework)] + #[test_only] + fun test_initialize_and_reconfig(framework: signer) acquires StorageGas, StorageGasConfig { + state_storage::initialize(&framework); + initialize(&framework); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_read == 10, 0); + assert!(gas_parameter.per_item_create == 10, 0); + assert!(gas_parameter.per_item_write == 10, 0); + assert!(gas_parameter.per_byte_read == 1, 0); + assert!(gas_parameter.per_byte_create == 1, 0); + assert!(gas_parameter.per_byte_write == 1, 0); + } + + #[test] + fun test_curve() { + let constant_curve = new_gas_curve(5, 5, vector[]); + let linear_curve = new_gas_curve(1, 1000, vector[]); + let standard_curve = base_8192_exponential_curve(1, 1000); + let target = BASIS_POINT_DENOMINATION / 2; + while (target < 2 * BASIS_POINT_DENOMINATION) { + let i = 0; + let old_standard_curve_gas = 1; + while (i <= target + 7) { + assert!(calculate_gas(target, i, &constant_curve) == 5, 0); + assert!(calculate_gas(target, i, &linear_curve) == (if (i < target) { 1 + 999 * (i * BASIS_POINT_DENOMINATION / target) / BASIS_POINT_DENOMINATION } else { 1000 }), 0); + let new_standard_curve_gas = calculate_gas(target, i, &standard_curve); + assert!(new_standard_curve_gas >= old_standard_curve_gas, 0); + old_standard_curve_gas = new_standard_curve_gas; + i = i + 3; + }; + assert!(old_standard_curve_gas == 1000, 0); + target = target + BASIS_POINT_DENOMINATION; + } + } + + #[test(framework = @aptos_framework)] + fun test_set_storage_gas_config(framework: signer) acquires StorageGas, StorageGasConfig { + state_storage::initialize(&framework); + initialize(&framework); + let item_curve = new_gas_curve(1000, 2000, + vector[new_point(3000, 0), new_point(5000, 5000), new_point(8000, 5000)] + ); + let byte_curve = new_gas_curve(0, 1000, vector::singleton(new_point(5000, 3000))); + let item_usage_config = new_usage_gas_config(100, copy item_curve, copy item_curve, copy item_curve); + let byte_usage_config = new_usage_gas_config(2000, copy byte_curve, copy byte_curve, copy byte_curve); + let storage_gas_config = new_storage_gas_config(item_usage_config, byte_usage_config); + set_config(&framework, storage_gas_config); + { + state_storage::set_for_test(0, 20, 100); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_read == 1000, 0); + assert!(gas_parameter.per_byte_read == 30, 0); + }; + { + state_storage::set_for_test(0, 40, 800); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_create == 1250, 0); + assert!(gas_parameter.per_byte_create == 240, 0); + }; + { + state_storage::set_for_test(0, 60, 1200); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_write == 1500, 0); + assert!(gas_parameter.per_byte_write == 440, 0); + }; + { + state_storage::set_for_test(0, 90, 1800); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_create == 1750, 0); + assert!(gas_parameter.per_byte_create == 860, 0); + }; + { + // usage overflow case + state_storage::set_for_test(0, 110, 2200); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_read == 2000, 0); + assert!(gas_parameter.per_byte_read == 1000, 0); + }; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/system_addresses.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/system_addresses.move new file mode 100644 index 0000000..49b8209 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/system_addresses.move @@ -0,0 +1,82 @@ +module aptos_framework::system_addresses { + use std::error; + use std::signer; + + /// The address/account did not correspond to the core resource address + const ENOT_CORE_RESOURCE_ADDRESS: u64 = 1; + /// The operation can only be performed by the VM + const EVM: u64 = 2; + /// The address/account did not correspond to the core framework address + const ENOT_APTOS_FRAMEWORK_ADDRESS: u64 = 3; + /// The address is not framework reserved address + const ENOT_FRAMEWORK_RESERVED_ADDRESS: u64 = 4; + + public fun assert_core_resource(account: &signer) { + assert_core_resource_address(signer::address_of(account)) + } + + public fun assert_core_resource_address(addr: address) { + assert!(is_core_resource_address(addr), error::permission_denied(ENOT_CORE_RESOURCE_ADDRESS)) + } + + public fun is_core_resource_address(addr: address): bool { + addr == @core_resources + } + + public fun assert_aptos_framework(account: &signer) { + assert!( + is_aptos_framework_address(signer::address_of(account)), + error::permission_denied(ENOT_APTOS_FRAMEWORK_ADDRESS), + ) + } + + public fun assert_framework_reserved_address(account: &signer) { + assert_framework_reserved(signer::address_of(account)); + } + + public fun assert_framework_reserved(addr: address) { + assert!( + is_framework_reserved_address(addr), + error::permission_denied(ENOT_FRAMEWORK_RESERVED_ADDRESS), + ) + } + + /// Return true if `addr` is 0x0 or under the on chain governance's control. + public fun is_framework_reserved_address(addr: address): bool { + is_aptos_framework_address(addr) || + addr == @0x2 || + addr == @0x3 || + addr == @0x4 || + addr == @0x5 || + addr == @0x6 || + addr == @0x7 || + addr == @0x8 || + addr == @0x9 || + addr == @0xa + } + + /// Return true if `addr` is 0x1. + public fun is_aptos_framework_address(addr: address): bool { + addr == @aptos_framework + } + + /// Assert that the signer has the VM reserved address. + public fun assert_vm(account: &signer) { + assert!(is_vm(account), error::permission_denied(EVM)) + } + + /// Return true if `addr` is a reserved address for the VM to call system modules. + public fun is_vm(account: &signer): bool { + is_vm_address(signer::address_of(account)) + } + + /// Return true if `addr` is a reserved address for the VM to call system modules. + public fun is_vm_address(addr: address): bool { + addr == @vm_reserved + } + + /// Return true if `addr` is either the VM address or an Aptos Framework address. + public fun is_reserved_address(addr: address): bool { + is_aptos_framework_address(addr) || is_vm_address(addr) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/timestamp.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/timestamp.move new file mode 100644 index 0000000..646ff1a --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/timestamp.move @@ -0,0 +1,88 @@ +/// This module keeps a global wall clock that stores the current Unix time in microseconds. +/// It interacts with the other modules in the following ways: +/// * genesis: to initialize the timestamp +/// * block: to reach consensus on the global wall clock time +module aptos_framework::timestamp { + use aptos_framework::system_addresses; + use std::error; + + friend aptos_framework::genesis; + + /// A singleton resource holding the current Unix time in microseconds + struct CurrentTimeMicroseconds has key { + microseconds: u64, + } + + /// Conversion factor between seconds and microseconds + const MICRO_CONVERSION_FACTOR: u64 = 1000000; + + /// The blockchain is not in an operating state yet + const ENOT_OPERATING: u64 = 1; + /// An invalid timestamp was provided + const EINVALID_TIMESTAMP: u64 = 2; + + /// Marks that time has started. This can only be called from genesis and with the aptos framework account. + public(friend) fun set_time_has_started(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let timer = CurrentTimeMicroseconds { microseconds: 0 }; + move_to(aptos_framework, timer); + } + + /// Updates the wall clock time by consensus. Requires VM privilege and will be invoked during block prologue. + public fun update_global_time( + account: &signer, + proposer: address, + timestamp: u64 + ) acquires CurrentTimeMicroseconds { + // Can only be invoked by AptosVM signer. + system_addresses::assert_vm(account); + + let global_timer = borrow_global_mut(@aptos_framework); + let now = global_timer.microseconds; + if (proposer == @vm_reserved) { + // NIL block with null address as proposer. Timestamp must be equal. + assert!(now == timestamp, error::invalid_argument(EINVALID_TIMESTAMP)); + } else { + // Normal block. Time must advance + assert!(now < timestamp, error::invalid_argument(EINVALID_TIMESTAMP)); + global_timer.microseconds = timestamp; + }; + } + + #[test_only] + public fun set_time_has_started_for_testing(account: &signer) { + if (!exists(@aptos_framework)) { + set_time_has_started(account); + }; + } + + #[view] + /// Gets the current time in microseconds. + public fun now_microseconds(): u64 acquires CurrentTimeMicroseconds { + borrow_global(@aptos_framework).microseconds + } + + #[view] + /// Gets the current time in seconds. + public fun now_seconds(): u64 acquires CurrentTimeMicroseconds { + now_microseconds() / MICRO_CONVERSION_FACTOR + } + + #[test_only] + public fun update_global_time_for_test(timestamp_microsecs: u64) acquires CurrentTimeMicroseconds { + let global_timer = borrow_global_mut(@aptos_framework); + let now = global_timer.microseconds; + assert!(now < timestamp_microsecs, error::invalid_argument(EINVALID_TIMESTAMP)); + global_timer.microseconds = timestamp_microsecs; + } + + #[test_only] + public fun update_global_time_for_test_secs(timestamp_seconds: u64) acquires CurrentTimeMicroseconds { + update_global_time_for_test(timestamp_seconds * MICRO_CONVERSION_FACTOR); + } + + #[test_only] + public fun fast_forward_seconds(timestamp_seconds: u64) acquires CurrentTimeMicroseconds { + update_global_time_for_test_secs(now_seconds() + timestamp_seconds); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_context.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_context.move new file mode 100644 index 0000000..b515ed1 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_context.move @@ -0,0 +1,83 @@ +module aptos_framework::transaction_context { + + use std::features; + + /// AUID feature is not supported. + const EAUID_NOT_SUPPORTED: u64 = 1; + + /// A wrapper denoting aptos unique identifer (AUID) + /// for storing an address + struct AUID has drop, store { + unique_address: address + } + + /// Return the transaction hash of the current transaction. + native fun get_txn_hash(): vector; + + /// Return the transaction hash of the current transaction. + /// Internally calls the private function `get_txn_hash`. + /// This function is created for to feature gate the `get_txn_hash` function. + public fun get_transaction_hash(): vector { + assert!(features::auids_enabled(), EAUID_NOT_SUPPORTED); + get_txn_hash() + } + + /// Return a universally unique identifier (of type address) generated + /// by hashing the transaction hash of this transaction and a sequence number + /// specific to this transaction. This function can be called any + /// number of times inside a single transaction. Each such call increments + /// the sequence number and generates a new unique address. + /// Uses Scheme in types/src/transaction/authenticator.rs for domain separation + /// from other ways of generating unique addresses. + native fun generate_unique_address(): address; + + /// Return a aptos unique identifier. Internally calls + /// the private function `generate_unique_address`. This function is + /// created for to feature gate the `generate_unique_address` function. + public fun generate_auid_address(): address { + assert!(features::auids_enabled(), EAUID_NOT_SUPPORTED); + generate_unique_address() + } + + /// Return the script hash of the current entry function. + public native fun get_script_hash(): vector; + + /// This method runs `generate_unique_address` native function and returns + /// the generated unique address wrapped in the AUID class. + public fun generate_auid(): AUID { + assert!(features::auids_enabled(), EAUID_NOT_SUPPORTED); + return AUID { + unique_address: generate_unique_address() + } + } + + public fun auid_address(auid: &AUID): address { + auid.unique_address + } + + #[test(fx = @std)] + fun test_auid_uniquess(fx: signer) { + use std::features; + use std::vector; + + let feature = features::get_auids(); + features::change_feature_flags(&fx, vector[feature], vector[]); + + let auids: vector
= vector
[]; + let i: u64 = 0; + let count: u64 = 50; + while (i < count) { + i = i + 1; + vector::push_back(&mut auids, generate_auid_address()); + }; + i = 0; + while (i < count - 1) { + let j: u64 = i + 1; + while (j < count) { + assert!(*vector::borrow(&auids, i) != *vector::borrow(&auids, j), 0); + j = j + 1; + }; + i = i + 1; + }; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_fee.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_fee.move new file mode 100644 index 0000000..54449b7 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_fee.move @@ -0,0 +1,397 @@ +/// This module provides an interface to burn or collect and redistribute transaction fees. +module aptos_framework::transaction_fee { + use aptos_framework::coin::{Self, AggregatableCoin, BurnCapability, Coin, MintCapability}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::stake; + use aptos_framework::system_addresses; + use std::error; + use std::option::{Self, Option}; + use aptos_framework::event; + + friend aptos_framework::block; + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration; + friend aptos_framework::transaction_validation; + + /// Gas fees are already being collected and the struct holding + /// information about collected amounts is already published. + const EALREADY_COLLECTING_FEES: u64 = 1; + + /// The burn percentage is out of range [0, 100]. + const EINVALID_BURN_PERCENTAGE: u64 = 3; + + /// Stores burn capability to burn the gas fees. + struct AptosCoinCapabilities has key { + burn_cap: BurnCapability, + } + + /// Stores mint capability to mint the refunds. + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + /// Stores information about the block proposer and the amount of fees + /// collected when executing the block. + struct CollectedFeesPerBlock has key { + amount: AggregatableCoin, + proposer: Option
, + burn_percentage: u8, + } + + #[event] + /// Summary of the fees charged and refunds issued for a transaction. + /// + /// This is meant to emitted as a module event. + struct FeeStatement has drop, store { + /// Total gas charge. + total_charge_gas_units: u64, + /// Execution gas charge. + execution_gas_units: u64, + /// IO gas charge. + io_gas_units: u64, + /// Storage fee charge. + storage_fee_octas: u64, + /// Storage fee refund. + storage_fee_refund_octas: u64, + } + + /// Initializes the resource storing information about gas fees collection and + /// distribution. Should be called by on-chain governance. + public fun initialize_fee_collection_and_distribution(aptos_framework: &signer, burn_percentage: u8) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(EALREADY_COLLECTING_FEES) + ); + assert!(burn_percentage <= 100, error::out_of_range(EINVALID_BURN_PERCENTAGE)); + + // Make sure stakng module is aware of transaction fees collection. + stake::initialize_validator_fees(aptos_framework); + + // Initially, no fees are collected and the block proposer is not set. + let collected_fees = CollectedFeesPerBlock { + amount: coin::initialize_aggregatable_coin(aptos_framework), + proposer: option::none(), + burn_percentage, + }; + move_to(aptos_framework, collected_fees); + } + + fun is_fees_collection_enabled(): bool { + exists(@aptos_framework) + } + + /// Sets the burn percentage for collected fees to a new value. Should be called by on-chain governance. + public fun upgrade_burn_percentage( + aptos_framework: &signer, + new_burn_percentage: u8 + ) acquires AptosCoinCapabilities, CollectedFeesPerBlock { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(new_burn_percentage <= 100, error::out_of_range(EINVALID_BURN_PERCENTAGE)); + + // Prior to upgrading the burn percentage, make sure to process collected + // fees. Otherwise we would use the new (incorrect) burn_percentage when + // processing fees later! + process_collected_fees(); + + if (is_fees_collection_enabled()) { + // Upgrade has no effect unless fees are being collected. + let burn_percentage = &mut borrow_global_mut(@aptos_framework).burn_percentage; + *burn_percentage = new_burn_percentage + } + } + + /// Registers the proposer of the block for gas fees collection. This function + /// can only be called at the beginning of the block. + public(friend) fun register_proposer_for_fee_collection(proposer_addr: address) acquires CollectedFeesPerBlock { + if (is_fees_collection_enabled()) { + let collected_fees = borrow_global_mut(@aptos_framework); + let _ = option::swap_or_fill(&mut collected_fees.proposer, proposer_addr); + } + } + + /// Burns a specified fraction of the coin. + fun burn_coin_fraction(coin: &mut Coin, burn_percentage: u8) acquires AptosCoinCapabilities { + assert!(burn_percentage <= 100, error::out_of_range(EINVALID_BURN_PERCENTAGE)); + + let collected_amount = coin::value(coin); + spec { + // We assume that `burn_percentage * collected_amount` does not overflow. + assume burn_percentage * collected_amount <= MAX_U64; + }; + let amount_to_burn = (burn_percentage as u64) * collected_amount / 100; + if (amount_to_burn > 0) { + let coin_to_burn = coin::extract(coin, amount_to_burn); + coin::burn( + coin_to_burn, + &borrow_global(@aptos_framework).burn_cap, + ); + } + } + + /// Calculates the fee which should be distributed to the block proposer at the + /// end of an epoch, and records it in the system. This function can only be called + /// at the beginning of the block or during reconfiguration. + public(friend) fun process_collected_fees() acquires AptosCoinCapabilities, CollectedFeesPerBlock { + if (!is_fees_collection_enabled()) { + return + }; + let collected_fees = borrow_global_mut(@aptos_framework); + + // If there are no collected fees, only unset the proposer. See the rationale for + // setting proposer to option::none() below. + if (coin::is_aggregatable_coin_zero(&collected_fees.amount)) { + if (option::is_some(&collected_fees.proposer)) { + let _ = option::extract(&mut collected_fees.proposer); + }; + return + }; + + // Otherwise get the collected fee, and check if it can distributed later. + let coin = coin::drain_aggregatable_coin(&mut collected_fees.amount); + if (option::is_some(&collected_fees.proposer)) { + // Extract the address of proposer here and reset it to option::none(). This + // is particularly useful to avoid any undesired side-effects where coins are + // collected but never distributed or distributed to the wrong account. + // With this design, processing collected fees enforces that all fees will be burnt + // unless the proposer is specified in the block prologue. When we have a governance + // proposal that triggers reconfiguration, we distribute pending fees and burn the + // fee for the proposal. Otherwise, that fee would be leaked to the next block. + let proposer = option::extract(&mut collected_fees.proposer); + + // Since the block can be produced by the VM itself, we have to make sure we catch + // this case. + if (proposer == @vm_reserved) { + burn_coin_fraction(&mut coin, 100); + coin::destroy_zero(coin); + return + }; + + burn_coin_fraction(&mut coin, collected_fees.burn_percentage); + stake::add_transaction_fee(proposer, coin); + return + }; + + // If checks did not pass, simply burn all collected coins and return none. + burn_coin_fraction(&mut coin, 100); + coin::destroy_zero(coin) + } + + /// Burn transaction fees in epilogue. + public(friend) fun burn_fee(account: address, fee: u64) acquires AptosCoinCapabilities { + coin::burn_from( + account, + fee, + &borrow_global(@aptos_framework).burn_cap, + ); + } + + /// Mint refund in epilogue. + public(friend) fun mint_and_refund(account: address, refund: u64) acquires AptosCoinMintCapability { + let mint_cap = &borrow_global(@aptos_framework).mint_cap; + let refund_coin = coin::mint(refund, mint_cap); + coin::force_deposit(account, refund_coin); + } + + /// Collect transaction fees in epilogue. + public(friend) fun collect_fee(account: address, fee: u64) acquires CollectedFeesPerBlock { + let collected_fees = borrow_global_mut(@aptos_framework); + + // Here, we are always optimistic and always collect fees. If the proposer is not set, + // or we cannot redistribute fees later for some reason (e.g. account cannot receive AptoCoin) + // we burn them all at once. This way we avoid having a check for every transaction epilogue. + let collected_amount = &mut collected_fees.amount; + coin::collect_into_aggregatable_coin(account, fee, collected_amount); + } + + /// Only called during genesis. + public(friend) fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinCapabilities { burn_cap }) + } + + /// Only called during genesis. + public(friend) fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + // Will be deleted after the mint cap is copied on both mainnet and testnet. New networks will get it from genesis. + public fun initialize_storage_refund(aptos_framework: &signer) { + let mint_cap = stake::copy_aptos_coin_mint_cap_for_storage_refund(); + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + } + + // Called by the VM after epilogue. + fun emit_fee_statement(fee_statement: FeeStatement) { + event::emit(fee_statement) + } + + #[test_only] + use aptos_framework::aggregator_factory; + + #[test(aptos_framework = @aptos_framework)] + fun test_initialize_fee_collection_and_distribution(aptos_framework: signer) acquires CollectedFeesPerBlock { + aggregator_factory::initialize_aggregator_factory_for_test(&aptos_framework); + initialize_fee_collection_and_distribution(&aptos_framework, 25); + + // Check struct has been published. + assert!(exists(@aptos_framework), 0); + + // Check that initial balance is 0 and there is no proposer set. + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(option::is_none(&collected_fees.proposer), 0); + assert!(collected_fees.burn_percentage == 25, 0); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_burn_fraction_calculation(aptos_framework: signer) acquires AptosCoinCapabilities { + use aptos_framework::aptos_coin; + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(&aptos_framework); + store_aptos_coin_burn_cap(&aptos_framework, burn_cap); + + let c1 = coin::mint(100, &mint_cap); + assert!(*option::borrow(&coin::supply()) == 100, 0); + + // Burning 25%. + burn_coin_fraction(&mut c1, 25); + assert!(coin::value(&c1) == 75, 0); + assert!(*option::borrow(&coin::supply()) == 75, 0); + + // Burning 0%. + burn_coin_fraction(&mut c1, 0); + assert!(coin::value(&c1) == 75, 0); + assert!(*option::borrow(&coin::supply()) == 75, 0); + + // Burning remaining 100%. + burn_coin_fraction(&mut c1, 100); + assert!(coin::value(&c1) == 0, 0); + assert!(*option::borrow(&coin::supply()) == 0, 0); + + coin::destroy_zero(c1); + let c2 = coin::mint(10, &mint_cap); + assert!(*option::borrow(&coin::supply()) == 10, 0); + + burn_coin_fraction(&mut c2, 5); + assert!(coin::value(&c2) == 10, 0); + assert!(*option::borrow(&coin::supply()) == 10, 0); + + burn_coin_fraction(&mut c2, 100); + coin::destroy_zero(c2); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(aptos_framework = @aptos_framework, alice = @0xa11ce, bob = @0xb0b, carol = @0xca101)] + fun test_fees_distribution( + aptos_framework: signer, + alice: signer, + bob: signer, + carol: signer, + ) acquires AptosCoinCapabilities, CollectedFeesPerBlock { + use std::signer; + use aptos_framework::aptos_account; + use aptos_framework::aptos_coin; + + // Initialization. + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(&aptos_framework); + store_aptos_coin_burn_cap(&aptos_framework, burn_cap); + initialize_fee_collection_and_distribution(&aptos_framework, 10); + + // Create dummy accounts. + let alice_addr = signer::address_of(&alice); + let bob_addr = signer::address_of(&bob); + let carol_addr = signer::address_of(&carol); + aptos_account::create_account(alice_addr); + aptos_account::create_account(bob_addr); + aptos_account::create_account(carol_addr); + coin::deposit(alice_addr, coin::mint(10000, &mint_cap)); + coin::deposit(bob_addr, coin::mint(10000, &mint_cap)); + coin::deposit(carol_addr, coin::mint(10000, &mint_cap)); + assert!(*option::borrow(&coin::supply()) == 30000, 0); + + // Block 1 starts. + process_collected_fees(); + register_proposer_for_fee_collection(alice_addr); + + // Check that there was no fees distribution in the first block. + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == alice_addr, 0); + assert!(*option::borrow(&coin::supply()) == 30000, 0); + + // Simulate transaction fee collection - here we simply collect some fees from Bob. + collect_fee(bob_addr, 100); + collect_fee(bob_addr, 500); + collect_fee(bob_addr, 400); + + // Now Bob must have 1000 less in his account. Alice and Carol have the same amounts. + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(coin::balance(bob_addr) == 9000, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Block 2 starts. + process_collected_fees(); + register_proposer_for_fee_collection(bob_addr); + + // Collected fees from Bob must have been assigned to Alice. + assert!(stake::get_validator_fee(alice_addr) == 900, 0); + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(coin::balance(bob_addr) == 9000, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Also, aggregator coin is drained and total supply is slightly changed (10% of 1000 is burnt). + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == bob_addr, 0); + assert!(*option::borrow(&coin::supply()) == 29900, 0); + + // Simulate transaction fee collection one more time. + collect_fee(bob_addr, 5000); + collect_fee(bob_addr, 4000); + + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(coin::balance(bob_addr) == 0, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Block 3 starts. + process_collected_fees(); + register_proposer_for_fee_collection(carol_addr); + + // Collected fees should have been assigned to Bob because he was the peoposer. + assert!(stake::get_validator_fee(alice_addr) == 900, 0); + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(stake::get_validator_fee(bob_addr) == 8100, 0); + assert!(coin::balance(bob_addr) == 0, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Again, aggregator coin is drained and total supply is changed by 10% of 9000. + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == carol_addr, 0); + assert!(*option::borrow(&coin::supply()) == 29000, 0); + + // Simulate transaction fee collection one last time. + collect_fee(alice_addr, 1000); + collect_fee(alice_addr, 1000); + + // Block 4 starts. + process_collected_fees(); + register_proposer_for_fee_collection(alice_addr); + + // Check that 2000 was collected from Alice. + assert!(coin::balance(alice_addr) == 8000, 0); + assert!(coin::balance(bob_addr) == 0, 0); + + // Carol must have some fees assigned now. + let collected_fees = borrow_global(@aptos_framework); + assert!(stake::get_validator_fee(carol_addr) == 1800, 0); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == alice_addr, 0); + assert!(*option::borrow(&coin::supply()) == 28800, 0); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_validation.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_validation.move new file mode 100644 index 0000000..d29473f --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/transaction_validation.move @@ -0,0 +1,300 @@ +module aptos_framework::transaction_validation { + use std::error; + use std::features; + use std::signer; + use std::vector; + + use aptos_framework::account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::chain_id; + use aptos_framework::coin; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use aptos_framework::transaction_fee; + + friend aptos_framework::genesis; + + /// This holds information that will be picked up by the VM to call the + /// correct chain-specific prologue and epilogue functions + struct TransactionValidation has key { + module_addr: address, + module_name: vector, + script_prologue_name: vector, + module_prologue_name: vector, + multi_agent_prologue_name: vector, + user_epilogue_name: vector, + } + + /// MSB is used to indicate a gas payer tx + const MAX_U64: u128 = 18446744073709551615; + + /// Transaction exceeded its allocated max gas + const EOUT_OF_GAS: u64 = 6; + + /// Prologue errors. These are separated out from the other errors in this + /// module since they are mapped separately to major VM statuses, and are + /// important to the semantics of the system. + const PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY: u64 = 1001; + const PROLOGUE_ESEQUENCE_NUMBER_TOO_OLD: u64 = 1002; + const PROLOGUE_ESEQUENCE_NUMBER_TOO_NEW: u64 = 1003; + const PROLOGUE_EACCOUNT_DOES_NOT_EXIST: u64 = 1004; + const PROLOGUE_ECANT_PAY_GAS_DEPOSIT: u64 = 1005; + const PROLOGUE_ETRANSACTION_EXPIRED: u64 = 1006; + const PROLOGUE_EBAD_CHAIN_ID: u64 = 1007; + const PROLOGUE_ESEQUENCE_NUMBER_TOO_BIG: u64 = 1008; + const PROLOGUE_ESECONDARY_KEYS_ADDRESSES_COUNT_MISMATCH: u64 = 1009; + const PROLOGUE_EFEE_PAYER_NOT_ENABLED: u64 = 1010; + + + /// Only called during genesis to initialize system resources for this module. + public(friend) fun initialize( + aptos_framework: &signer, + script_prologue_name: vector, + module_prologue_name: vector, + multi_agent_prologue_name: vector, + user_epilogue_name: vector, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, TransactionValidation { + module_addr: @aptos_framework, + module_name: b"transaction_validation", + script_prologue_name, + module_prologue_name, + multi_agent_prologue_name, + user_epilogue_name, + }); + } + + fun prologue_common( + sender: signer, + gas_payer: address, + txn_sequence_number: u64, + txn_authentication_key: vector, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + ) { + assert!( + timestamp::now_seconds() < txn_expiration_time, + error::invalid_argument(PROLOGUE_ETRANSACTION_EXPIRED), + ); + assert!(chain_id::get() == chain_id, error::invalid_argument(PROLOGUE_EBAD_CHAIN_ID)); + + let transaction_sender = signer::address_of(&sender); + assert!(account::exists_at(transaction_sender), error::invalid_argument(PROLOGUE_EACCOUNT_DOES_NOT_EXIST)); + assert!( + txn_authentication_key == account::get_authentication_key(transaction_sender), + error::invalid_argument(PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY), + ); + + assert!( + txn_sequence_number < (1u64 << 63), + error::out_of_range(PROLOGUE_ESEQUENCE_NUMBER_TOO_BIG) + ); + + let account_sequence_number = account::get_sequence_number(transaction_sender); + assert!( + txn_sequence_number >= account_sequence_number, + error::invalid_argument(PROLOGUE_ESEQUENCE_NUMBER_TOO_OLD) + ); + + // [PCA12]: Check that the transaction's sequence number matches the + // current sequence number. Otherwise sequence number is too new by [PCA11]. + assert!( + txn_sequence_number == account_sequence_number, + error::invalid_argument(PROLOGUE_ESEQUENCE_NUMBER_TOO_NEW) + ); + + let max_transaction_fee = txn_gas_price * txn_max_gas_units; + assert!( + coin::is_account_registered(gas_payer), + error::invalid_argument(PROLOGUE_ECANT_PAY_GAS_DEPOSIT), + ); + let balance = coin::balance(gas_payer); + assert!(balance >= max_transaction_fee, error::invalid_argument(PROLOGUE_ECANT_PAY_GAS_DEPOSIT)); + } + + fun module_prologue( + sender: signer, + txn_sequence_number: u64, + txn_public_key: vector, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + ) { + let gas_payer = signer::address_of(&sender); + prologue_common(sender, gas_payer, txn_sequence_number, txn_public_key, txn_gas_price, txn_max_gas_units, txn_expiration_time, chain_id) + } + + fun script_prologue( + sender: signer, + txn_sequence_number: u64, + txn_public_key: vector, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + _script_hash: vector, + ) { + let gas_payer = signer::address_of(&sender); + prologue_common(sender, gas_payer, txn_sequence_number, txn_public_key, txn_gas_price, txn_max_gas_units, txn_expiration_time, chain_id) + } + + fun multi_agent_script_prologue( + sender: signer, + txn_sequence_number: u64, + txn_sender_public_key: vector, + secondary_signer_addresses: vector
, + secondary_signer_public_key_hashes: vector>, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + ) { + let sender_addr = signer::address_of(&sender); + prologue_common( + sender, + sender_addr, + txn_sequence_number, + txn_sender_public_key, + txn_gas_price, + txn_max_gas_units, + txn_expiration_time, + chain_id, + ); + multi_agent_common_prologue(secondary_signer_addresses, secondary_signer_public_key_hashes); + } + + fun multi_agent_common_prologue( + secondary_signer_addresses: vector
, + secondary_signer_public_key_hashes: vector>, + ) { + let num_secondary_signers = vector::length(&secondary_signer_addresses); + assert!( + vector::length(&secondary_signer_public_key_hashes) == num_secondary_signers, + error::invalid_argument(PROLOGUE_ESECONDARY_KEYS_ADDRESSES_COUNT_MISMATCH), + ); + + let i = 0; + while ({ + spec { + invariant i <= num_secondary_signers; + invariant forall j in 0..i: + account::exists_at(secondary_signer_addresses[j]) + && secondary_signer_public_key_hashes[j] + == account::get_authentication_key(secondary_signer_addresses[j]); + }; + (i < num_secondary_signers) + }) { + let secondary_address = *vector::borrow(&secondary_signer_addresses, i); + assert!(account::exists_at(secondary_address), error::invalid_argument(PROLOGUE_EACCOUNT_DOES_NOT_EXIST)); + + let signer_public_key_hash = *vector::borrow(&secondary_signer_public_key_hashes, i); + assert!( + signer_public_key_hash == account::get_authentication_key(secondary_address), + error::invalid_argument(PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY), + ); + i = i + 1; + } + } + + fun fee_payer_script_prologue( + sender: signer, + txn_sequence_number: u64, + txn_sender_public_key: vector, + secondary_signer_addresses: vector
, + secondary_signer_public_key_hashes: vector>, + fee_payer_address: address, + fee_payer_public_key_hash: vector, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + ) { + assert!(features::fee_payer_enabled(), error::invalid_state(PROLOGUE_EFEE_PAYER_NOT_ENABLED)); + prologue_common( + sender, + fee_payer_address, + txn_sequence_number, + txn_sender_public_key, + txn_gas_price, + txn_max_gas_units, + txn_expiration_time, + chain_id, + ); + multi_agent_common_prologue(secondary_signer_addresses, secondary_signer_public_key_hashes); + assert!( + fee_payer_public_key_hash == account::get_authentication_key(fee_payer_address), + error::invalid_argument(PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY), + ); + } + + /// Epilogue function is run after a transaction is successfully executed. + /// Called by the Adapter + fun epilogue( + account: signer, + storage_fee_refunded: u64, + txn_gas_price: u64, + txn_max_gas_units: u64, + gas_units_remaining: u64 + ) { + let addr = signer::address_of(&account); + epilogue_gas_payer(account, addr, storage_fee_refunded, txn_gas_price, txn_max_gas_units, gas_units_remaining); + } + + /// Epilogue function with explicit gas payer specified, is run after a transaction is successfully executed. + /// Called by the Adapter + fun epilogue_gas_payer( + account: signer, + gas_payer: address, + storage_fee_refunded: u64, + txn_gas_price: u64, + txn_max_gas_units: u64, + gas_units_remaining: u64 + ) { + assert!(txn_max_gas_units >= gas_units_remaining, error::invalid_argument(EOUT_OF_GAS)); + let gas_used = txn_max_gas_units - gas_units_remaining; + + assert!( + (txn_gas_price as u128) * (gas_used as u128) <= MAX_U64, + error::out_of_range(EOUT_OF_GAS) + ); + let transaction_fee_amount = txn_gas_price * gas_used; + // it's important to maintain the error code consistent with vm + // to do failed transaction cleanup. + assert!( + coin::balance(gas_payer) >= transaction_fee_amount, + error::out_of_range(PROLOGUE_ECANT_PAY_GAS_DEPOSIT), + ); + + let amount_to_burn = if (features::collect_and_distribute_gas_fees()) { + // TODO(gas): We might want to distinguish the refundable part of the charge and burn it or track + // it separately, so that we don't increase the total supply by refunding. + + // If transaction fees are redistributed to validators, collect them here for + // later redistribution. + transaction_fee::collect_fee(gas_payer, transaction_fee_amount); + 0 + } else { + // Otherwise, just burn the fee. + // TODO: this branch should be removed completely when transaction fee collection + // is tested and is fully proven to work well. + transaction_fee_amount + }; + + if (amount_to_burn > storage_fee_refunded) { + let burn_amount = amount_to_burn - storage_fee_refunded; + transaction_fee::burn_fee(gas_payer, burn_amount); + } else if (amount_to_burn < storage_fee_refunded) { + let mint_amount = storage_fee_refunded - amount_to_burn; + transaction_fee::mint_and_refund(gas_payer, mint_amount) + }; + + // Increment sequence number + let addr = signer::address_of(&account); + account::increment_sequence_number(addr); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/util.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/util.move new file mode 100644 index 0000000..332afa2 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/util.move @@ -0,0 +1,16 @@ +/// Utility functions used by the framework modules. +module aptos_framework::util { + friend aptos_framework::code; + friend aptos_framework::gas_schedule; + + /// Native function to deserialize a type T. + /// + /// Note that this function does not put any constraint on `T`. If code uses this function to + /// deserialized a linear value, its their responsibility that the data they deserialize is + /// owned. + public(friend) native fun from_bytes(bytes: vector): T; + + public fun address_from_bytes(bytes: vector): address { + from_bytes(bytes) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/version.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/version.move new file mode 100644 index 0000000..47b1692 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/version.move @@ -0,0 +1,84 @@ +/// Maintains the version number for the blockchain. +module aptos_framework::version { + use std::error; + use std::signer; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + + struct Version has key { + major: u64, + } + + struct SetVersionCapability has key {} + + /// Specified major version number must be greater than current version number. + const EINVALID_MAJOR_VERSION_NUMBER: u64 = 1; + /// Account is not authorized to make this change. + const ENOT_AUTHORIZED: u64 = 2; + + /// Only called during genesis. + /// Publishes the Version config. + public(friend) fun initialize(aptos_framework: &signer, initial_version: u64) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, Version { major: initial_version }); + // Give aptos framework account capability to call set version. This allows on chain governance to do it through + // control of the aptos framework account. + move_to(aptos_framework, SetVersionCapability {}); + } + + /// Updates the major version to a larger version. + /// This can be called by on chain governance. + public entry fun set_version(account: &signer, major: u64) acquires Version { + assert!(exists(signer::address_of(account)), error::permission_denied(ENOT_AUTHORIZED)); + + let old_major = borrow_global(@aptos_framework).major; + assert!(old_major < major, error::invalid_argument(EINVALID_MAJOR_VERSION_NUMBER)); + + let config = borrow_global_mut(@aptos_framework); + config.major = major; + + // Need to trigger reconfiguration so validator nodes can sync on the updated version. + reconfiguration::reconfigure(); + } + + /// Only called in tests and testnets. This allows the core resources account, which only exists in tests/testnets, + /// to update the version. + fun initialize_for_test(core_resources: &signer) { + system_addresses::assert_core_resource(core_resources); + move_to(core_resources, SetVersionCapability {}); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_set_version(aptos_framework: signer) acquires Version { + initialize(&aptos_framework, 1); + assert!(borrow_global(@aptos_framework).major == 1, 0); + set_version(&aptos_framework, 2); + assert!(borrow_global(@aptos_framework).major == 2, 1); + } + + #[test(aptos_framework = @aptos_framework, core_resources = @core_resources)] + public entry fun test_set_version_core_resources( + aptos_framework: signer, + core_resources: signer, + ) acquires Version { + initialize(&aptos_framework, 1); + assert!(borrow_global(@aptos_framework).major == 1, 0); + initialize_for_test(&core_resources); + set_version(&core_resources, 2); + assert!(borrow_global(@aptos_framework).major == 2, 1); + } + + #[test(aptos_framework = @aptos_framework, random_account = @0x123)] + #[expected_failure(abort_code = 327682, location = Self)] + public entry fun test_set_version_unauthorized_should_fail( + aptos_framework: signer, + random_account: signer, + ) acquires Version { + initialize(&aptos_framework, 1); + set_version(&random_account, 2); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/vesting.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/vesting.move new file mode 100644 index 0000000..2b92118 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/vesting.move @@ -0,0 +1,1871 @@ +/// +/// Simple vesting contract that allows specifying how much APT coins should be vesting in each fixed-size period. The +/// vesting contract also comes with staking and allows shareholders to withdraw rewards anytime. +/// +/// Vesting schedule is represented as a vector of distributions. For example, a vesting schedule of +/// [3/48, 3/48, 1/48] means that after the vesting starts: +/// 1. The first and second periods will vest 3/48 of the total original grant. +/// 2. The third period will vest 1/48. +/// 3. All subsequent periods will also vest 1/48 (last distribution in the schedule) until the original grant runs out. +/// +/// Shareholder flow: +/// 1. Admin calls create_vesting_contract with a schedule of [3/48, 3/48, 1/48] with a vesting cliff of 1 year and +/// vesting period of 1 month. +/// 2. After a month, a shareholder calls unlock_rewards to request rewards. They can also call vest() which would also +/// unlocks rewards but since the 1 year cliff has not passed (vesting has not started), vest() would not release any of +/// the original grant. +/// 3. After the unlocked rewards become fully withdrawable (as it's subject to staking lockup), shareholders can call +/// distribute() to send all withdrawable funds to all shareholders based on the original grant's shares structure. +/// 4. After 1 year and 1 month, the vesting schedule now starts. Shareholders call vest() to unlock vested coins. vest() +/// checks the schedule and unlocks 3/48 of the original grant in addition to any accumulated rewards since last +/// unlock_rewards(). Once the unlocked coins become withdrawable, shareholders can call distribute(). +/// 5. Assuming the shareholders forgot to call vest() for 2 months, when they call vest() again, they will unlock vested +/// tokens for the next period since last vest. This would be for the first month they missed. They can call vest() a +/// second time to unlock for the second month they missed. +/// +/// Admin flow: +/// 1. After creating the vesting contract, admin cannot change the vesting schedule. +/// 2. Admin can call update_voter, update_operator, or reset_lockup at any time to update the underlying staking +/// contract. +/// 3. Admin can also call update_beneficiary for any shareholder. This would send all distributions (rewards, vested +/// coins) of that shareholder to the beneficiary account. By defalt, if a beneficiary is not set, the distributions are +/// send directly to the shareholder account. +/// 4. Admin can call terminate_vesting_contract to terminate the vesting. This would first finish any distribution but +/// will prevent any further rewards or vesting distributions from being created. Once the locked up stake becomes +/// withdrawable, admin can call admin_withdraw to withdraw all funds to the vesting contract's withdrawal address. +module aptos_framework::vesting { + use std::bcs; + use std::error; + use std::fixed_point32::{Self, FixedPoint32}; + use std::signer; + use std::string::{utf8, String}; + use std::vector; + + use aptos_std::pool_u64::{Self, Pool}; + use aptos_std::simple_map::{Self, SimpleMap}; + + use aptos_framework::account::{Self, SignerCapability, new_event_handle}; + use aptos_framework::aptos_account::{Self, assert_account_is_registered_for_apt}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, Coin}; + use aptos_framework::event::{EventHandle, emit_event}; + use aptos_framework::stake; + use aptos_framework::staking_contract; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + + friend aptos_framework::genesis; + + const VESTING_POOL_SALT: vector = b"aptos_framework::vesting"; + + /// Withdrawal address is invalid. + const EINVALID_WITHDRAWAL_ADDRESS: u64 = 1; + /// Vesting schedule cannot be empty. + const EEMPTY_VESTING_SCHEDULE: u64 = 2; + /// Vesting period cannot be 0. + const EZERO_VESTING_SCHEDULE_PERIOD: u64 = 3; + /// Shareholders list cannot be empty. + const ENO_SHAREHOLDERS: u64 = 4; + /// The length of shareholders and shares lists don't match. + const ESHARES_LENGTH_MISMATCH: u64 = 5; + /// Vesting cannot start before or at the current block timestamp. Has to be in the future. + const EVESTING_START_TOO_SOON: u64 = 6; + /// The signer is not the admin of the vesting contract. + const ENOT_ADMIN: u64 = 7; + /// Vesting contract needs to be in active state. + const EVESTING_CONTRACT_NOT_ACTIVE: u64 = 8; + /// Admin can only withdraw from an inactive (paused or terminated) vesting contract. + const EVESTING_CONTRACT_STILL_ACTIVE: u64 = 9; + /// No vesting contract found at provided address. + const EVESTING_CONTRACT_NOT_FOUND: u64 = 10; + /// Cannot terminate the vesting contract with pending active stake. Need to wait until next epoch. + const EPENDING_STAKE_FOUND: u64 = 11; + /// Grant amount cannot be 0. + const EZERO_GRANT: u64 = 12; + /// Vesting account has no other management roles beside admin. + const EVESTING_ACCOUNT_HAS_NO_ROLES: u64 = 13; + /// The vesting account has no such management role. + const EROLE_NOT_FOUND: u64 = 14; + /// Account is not admin or does not have the required role to take this action. + const EPERMISSION_DENIED: u64 = 15; + /// Zero items were provided to a *_many function. + const EVEC_EMPTY_FOR_MANY_FUNCTION: u64 = 16; + + /// Maximum number of shareholders a vesting pool can support. + const MAXIMUM_SHAREHOLDERS: u64 = 30; + + /// Vesting contract states. + /// Vesting contract is active and distributions can be made. + const VESTING_POOL_ACTIVE: u64 = 1; + /// Vesting contract has been terminated and all funds have been released back to the withdrawal address. + const VESTING_POOL_TERMINATED: u64 = 2; + + /// Roles that can manage certain aspects of the vesting account beyond the main admin. + const ROLE_BENEFICIARY_RESETTER: vector = b"ROLE_BENEFICIARY_RESETTER"; + + struct VestingSchedule has copy, drop, store { + // The vesting schedule as a list of fractions that vest for each period. The last number is repeated until the + // vesting amount runs out. + // For example [1/24, 1/24, 1/48] with a period of 1 month means that after vesting starts, the first two months + // will vest 1/24 of the original total amount. From the third month only, 1/48 will vest until the vesting fund + // runs out. + // u32/u32 should be sufficient to support vesting schedule fractions. + schedule: vector, + // When the vesting should start. + start_timestamp_secs: u64, + // In seconds. How long each vesting period is. For example 1 month. + period_duration: u64, + // Last vesting period, 1-indexed. For example if 2 months have passed, the last vesting period, if distribution + // was requested, would be 2. Default value is 0 which means there have been no vesting periods yet. + last_vested_period: u64, + } + + struct StakingInfo has store { + // Where the vesting's stake pool is located at. Included for convenience. + pool_address: address, + // The currently assigned operator. + operator: address, + // The currently assigned voter. + voter: address, + // Commission paid to the operator of the stake pool. + commission_percentage: u64, + } + + struct VestingContract has key { + state: u64, + admin: address, + grant_pool: Pool, + beneficiaries: SimpleMap, + vesting_schedule: VestingSchedule, + // Withdrawal address where all funds would be released back to if the admin ends the vesting for a specific + // account or terminates the entire vesting contract. + withdrawal_address: address, + staking: StakingInfo, + // Remaining amount in the grant. For calculating accumulated rewards. + remaining_grant: u64, + // Used to control staking. + signer_cap: SignerCapability, + + // Events. + update_operator_events: EventHandle, + update_voter_events: EventHandle, + reset_lockup_events: EventHandle, + set_beneficiary_events: EventHandle, + unlock_rewards_events: EventHandle, + vest_events: EventHandle, + distribute_events: EventHandle, + terminate_events: EventHandle, + admin_withdraw_events: EventHandle, + } + + struct VestingAccountManagement has key { + roles: SimpleMap, + } + + struct AdminStore has key { + vesting_contracts: vector
, + // Used to create resource accounts for new vesting contracts so there's no address collision. + nonce: u64, + + create_events: EventHandle, + } + + struct CreateVestingContractEvent has drop, store { + operator: address, + voter: address, + grant_amount: u64, + withdrawal_address: address, + vesting_contract_address: address, + staking_pool_address: address, + commission_percentage: u64, + } + + struct UpdateOperatorEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + old_operator: address, + new_operator: address, + commission_percentage: u64, + } + + struct UpdateVoterEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + old_voter: address, + new_voter: address, + } + + struct ResetLockupEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + new_lockup_expiration_secs: u64, + } + + struct SetBeneficiaryEvent has drop, store { + admin: address, + vesting_contract_address: address, + shareholder: address, + old_beneficiary: address, + new_beneficiary: address, + } + + struct UnlockRewardsEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + amount: u64, + } + + struct VestEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + period_vested: u64, + amount: u64, + } + + struct DistributeEvent has drop, store { + admin: address, + vesting_contract_address: address, + amount: u64, + } + + struct TerminateEvent has drop, store { + admin: address, + vesting_contract_address: address, + } + + struct AdminWithdrawEvent has drop, store { + admin: address, + vesting_contract_address: address, + amount: u64, + } + + #[view] + /// Return the address of the underlying stake pool (separate resource account) of the vesting contract. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun stake_pool_address(vesting_contract_address: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.pool_address + } + + #[view] + /// Return the vesting start timestamp (in seconds) of the vesting contract. + /// Vesting will start at this time, and once a full period has passed, the first vest will become unlocked. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun vesting_start_secs(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).vesting_schedule.start_timestamp_secs + } + + #[view] + /// Return the duration of one vesting period (in seconds). + /// Each vest is released after one full period has started, starting from the specified start_timestamp_secs. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun period_duration_secs(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).vesting_schedule.period_duration + } + + #[view] + /// Return the remaining grant, consisting of unvested coins that have not been distributed to shareholders. + /// Prior to start_timestamp_secs, the remaining grant will always be equal to the original grant. + /// Once vesting has started, and vested tokens are distributed, the remaining grant will decrease over time, + /// according to the vesting schedule. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun remaining_grant(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).remaining_grant + } + + #[view] + /// Return the beneficiary account of the specified shareholder in a vesting contract. + /// This is the same as the shareholder address by default and only different if it's been explicitly set. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun beneficiary(vesting_contract_address: address, shareholder: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + get_beneficiary(borrow_global(vesting_contract_address), shareholder) + } + + #[view] + /// Return the percentage of accumulated rewards that is paid to the operator as commission. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun operator_commission_percentage(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.commission_percentage + } + + #[view] + /// Return all the vesting contracts a given address is an admin of. + public fun vesting_contracts(admin: address): vector
acquires AdminStore { + if (!exists(admin)) { + vector::empty
() + } else { + borrow_global(admin).vesting_contracts + } + } + + #[view] + /// Return the operator who runs the validator for the vesting contract. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun operator(vesting_contract_address: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.operator + } + + #[view] + /// Return the voter who will be voting on on-chain governance proposals on behalf of the vesting contract's stake + /// pool. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun voter(vesting_contract_address: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.voter + } + + #[view] + /// Return the vesting contract's vesting schedule. The core schedule is represented as a list of u64-based + /// fractions, where the rightmmost 32 bits can be divided by 2^32 to get the fraction, and anything else is the + /// whole number. + /// + /// For example 3/48, or 0.0625, will be represented as 268435456. The fractional portion would be + /// 268435456 / 2^32 = 0.0625. Since there are fewer than 32 bits, the whole number portion is effectively 0. + /// So 268435456 = 0.0625. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun vesting_schedule(vesting_contract_address: address): VestingSchedule acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).vesting_schedule + } + + #[view] + /// Return the total accumulated rewards that have not been distributed to shareholders of the vesting contract. + /// This excludes any unpaid commission that the operator has not collected. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun total_accumulated_rewards(vesting_contract_address: address): u64 acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let vesting_contract = borrow_global(vesting_contract_address); + let (total_active_stake, _, commission_amount) = + staking_contract::staking_contract_amounts(vesting_contract_address, vesting_contract.staking.operator); + total_active_stake - vesting_contract.remaining_grant - commission_amount + } + + #[view] + /// Return the accumulated rewards that have not been distributed to the provided shareholder. Caller can also pass + /// the beneficiary address instead of shareholder address. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun accumulated_rewards( + vesting_contract_address: address, shareholder_or_beneficiary: address): u64 acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let total_accumulated_rewards = total_accumulated_rewards(vesting_contract_address); + let shareholder = shareholder(vesting_contract_address, shareholder_or_beneficiary); + let vesting_contract = borrow_global(vesting_contract_address); + let shares = pool_u64::shares(&vesting_contract.grant_pool, shareholder); + pool_u64::shares_to_amount_with_total_coins(&vesting_contract.grant_pool, shares, total_accumulated_rewards) + } + + #[view] + /// Return the list of all shareholders in the vesting contract. + public fun shareholders(vesting_contract_address: address): vector
acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let vesting_contract = borrow_global(vesting_contract_address); + pool_u64::shareholders(&vesting_contract.grant_pool) + } + + #[view] + /// Return the shareholder address given the beneficiary address in a given vesting contract. If there are multiple + /// shareholders with the same beneficiary address, only the first shareholder is returned. If the given beneficiary + /// address is actually a shareholder address, just return the address back. + /// + /// This returns 0x0 if no shareholder is found for the given beneficiary / the address is not a shareholder itself. + public fun shareholder(vesting_contract_address: address, shareholder_or_beneficiary: address): address acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let shareholders = &shareholders(vesting_contract_address); + if (vector::contains(shareholders, &shareholder_or_beneficiary)) { + return shareholder_or_beneficiary + }; + let vesting_contract = borrow_global(vesting_contract_address); + let result = @0x0; + vector::any(shareholders, |shareholder| { + if (shareholder_or_beneficiary == get_beneficiary(vesting_contract, *shareholder)) { + result = *shareholder; + true + } else { + false + } + }); + + result + } + + /// Create a vesting schedule with the given schedule of distributions, a vesting start time and period duration. + public fun create_vesting_schedule( + schedule: vector, + start_timestamp_secs: u64, + period_duration: u64, + ): VestingSchedule { + assert!(vector::length(&schedule) > 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE)); + assert!(period_duration > 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD)); + assert!( + start_timestamp_secs >= timestamp::now_seconds(), + error::invalid_argument(EVESTING_START_TOO_SOON), + ); + + VestingSchedule { + schedule, + start_timestamp_secs, + period_duration, + last_vested_period: 0, + } + } + + /// Create a vesting contract with a given configurations. + public fun create_vesting_contract( + admin: &signer, + shareholders: &vector
, + buy_ins: SimpleMap>, + vesting_schedule: VestingSchedule, + withdrawal_address: address, + operator: address, + voter: address, + commission_percentage: u64, + // Optional seed used when creating the staking contract account. + contract_creation_seed: vector, + ): address acquires AdminStore { + assert!( + !system_addresses::is_reserved_address(withdrawal_address), + error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS), + ); + assert_account_is_registered_for_apt(withdrawal_address); + assert!(vector::length(shareholders) > 0, error::invalid_argument(ENO_SHAREHOLDERS)); + assert!( + simple_map::length(&buy_ins) == vector::length(shareholders), + error::invalid_argument(ESHARES_LENGTH_MISMATCH), + ); + + // Create a coins pool to track shareholders and shares of the grant. + let grant = coin::zero(); + let grant_amount = 0; + let grant_pool = pool_u64::create(MAXIMUM_SHAREHOLDERS); + vector::for_each_ref(shareholders, |shareholder| { + let shareholder: address = *shareholder; + let (_, buy_in) = simple_map::remove(&mut buy_ins, &shareholder); + let buy_in_amount = coin::value(&buy_in); + coin::merge(&mut grant, buy_in); + pool_u64::buy_in( + &mut grant_pool, + shareholder, + buy_in_amount, + ); + grant_amount = grant_amount + buy_in_amount; + }); + assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT)); + + // If this is the first time this admin account has created a vesting contract, initialize the admin store. + let admin_address = signer::address_of(admin); + if (!exists(admin_address)) { + move_to(admin, AdminStore { + vesting_contracts: vector::empty
(), + nonce: 0, + create_events: new_event_handle(admin), + }); + }; + + // Initialize the vesting contract in a new resource account. This allows the same admin to create multiple + // pools. + let (contract_signer, contract_signer_cap) = create_vesting_contract_account(admin, contract_creation_seed); + let pool_address = staking_contract::create_staking_contract_with_coins( + &contract_signer, operator, voter, grant, commission_percentage, contract_creation_seed); + + // Add the newly created vesting contract's address to the admin store. + let contract_address = signer::address_of(&contract_signer); + let admin_store = borrow_global_mut(admin_address); + vector::push_back(&mut admin_store.vesting_contracts, contract_address); + emit_event( + &mut admin_store.create_events, + CreateVestingContractEvent { + operator, + voter, + withdrawal_address, + grant_amount, + vesting_contract_address: contract_address, + staking_pool_address: pool_address, + commission_percentage, + }, + ); + + move_to(&contract_signer, VestingContract { + state: VESTING_POOL_ACTIVE, + admin: admin_address, + grant_pool, + beneficiaries: simple_map::create(), + vesting_schedule, + withdrawal_address, + staking: StakingInfo { pool_address, operator, voter, commission_percentage }, + remaining_grant: grant_amount, + signer_cap: contract_signer_cap, + update_operator_events: new_event_handle(&contract_signer), + update_voter_events: new_event_handle(&contract_signer), + reset_lockup_events: new_event_handle(&contract_signer), + set_beneficiary_events: new_event_handle(&contract_signer), + unlock_rewards_events: new_event_handle(&contract_signer), + vest_events: new_event_handle(&contract_signer), + distribute_events: new_event_handle(&contract_signer), + terminate_events: new_event_handle(&contract_signer), + admin_withdraw_events: new_event_handle(&contract_signer), + }); + + simple_map::destroy_empty(buy_ins); + contract_address + } + + /// Unlock any accumulated rewards. + public entry fun unlock_rewards(contract_address: address) acquires VestingContract { + let accumulated_rewards = total_accumulated_rewards(contract_address); + let vesting_contract = borrow_global(contract_address); + unlock_stake(vesting_contract, accumulated_rewards); + } + + /// Call `unlock_rewards` for many vesting contracts. + public entry fun unlock_rewards_many(contract_addresses: vector
) acquires VestingContract { + let len = vector::length(&contract_addresses); + + assert!(len != 0, error::invalid_argument(EVEC_EMPTY_FOR_MANY_FUNCTION)); + + vector::for_each_ref(&contract_addresses, |contract_address| { + let contract_address: address = *contract_address; + unlock_rewards(contract_address); + }); + } + + /// Unlock any vested portion of the grant. + public entry fun vest(contract_address: address) acquires VestingContract { + // Unlock all rewards first, if any. + unlock_rewards(contract_address); + + // Unlock the vested amount. This amount will become withdrawable when the underlying stake pool's lockup + // expires. + let vesting_contract = borrow_global_mut(contract_address); + // Short-circuit if vesting hasn't started yet. + if (vesting_contract.vesting_schedule.start_timestamp_secs > timestamp::now_seconds()) { + return + }; + + // Check if the next vested period has already passed. If not, short-circuit since there's nothing to vest. + let vesting_schedule = &mut vesting_contract.vesting_schedule; + let last_vested_period = vesting_schedule.last_vested_period; + let next_period_to_vest = last_vested_period + 1; + let last_completed_period = + (timestamp::now_seconds() - vesting_schedule.start_timestamp_secs) / vesting_schedule.period_duration; + if (last_completed_period < next_period_to_vest) { + return + }; + + // Calculate how much has vested, excluding rewards. + // Index is 0-based while period is 1-based so we need to subtract 1. + let schedule = &vesting_schedule.schedule; + let schedule_index = next_period_to_vest - 1; + let vesting_fraction = if (schedule_index < vector::length(schedule)) { + *vector::borrow(schedule, schedule_index) + } else { + // Last vesting schedule fraction will repeat until the grant runs out. + *vector::borrow(schedule, vector::length(schedule) - 1) + }; + let total_grant = pool_u64::total_coins(&vesting_contract.grant_pool); + let vested_amount = fixed_point32::multiply_u64(total_grant, vesting_fraction); + // Cap vested amount by the remaining grant amount so we don't try to distribute more than what's remaining. + vested_amount = min(vested_amount, vesting_contract.remaining_grant); + vesting_contract.remaining_grant = vesting_contract.remaining_grant - vested_amount; + vesting_schedule.last_vested_period = next_period_to_vest; + unlock_stake(vesting_contract, vested_amount); + + emit_event( + &mut vesting_contract.vest_events, + VestEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + period_vested: next_period_to_vest, + amount: vested_amount, + }, + ); + } + + /// Call `vest` for many vesting contracts. + public entry fun vest_many(contract_addresses: vector
) acquires VestingContract { + let len = vector::length(&contract_addresses); + + assert!(len != 0, error::invalid_argument(EVEC_EMPTY_FOR_MANY_FUNCTION)); + + vector::for_each_ref(&contract_addresses, |contract_address| { + let contract_address = *contract_address; + vest(contract_address); + }); + } + + /// Distribute any withdrawable stake from the stake pool. + public entry fun distribute(contract_address: address) acquires VestingContract { + assert_active_vesting_contract(contract_address); + + let vesting_contract = borrow_global_mut(contract_address); + let coins = withdraw_stake(vesting_contract, contract_address); + let total_distribution_amount = coin::value(&coins); + if (total_distribution_amount == 0) { + coin::destroy_zero(coins); + return + }; + + // Distribute coins to all shareholders in the vesting contract. + let grant_pool = &vesting_contract.grant_pool; + let shareholders = &pool_u64::shareholders(grant_pool); + vector::for_each_ref(shareholders, |shareholder| { + let shareholder = *shareholder; + let shares = pool_u64::shares(grant_pool, shareholder); + let amount = pool_u64::shares_to_amount_with_total_coins(grant_pool, shares, total_distribution_amount); + let share_of_coins = coin::extract(&mut coins, amount); + let recipient_address = get_beneficiary(vesting_contract, shareholder); + aptos_account::deposit_coins(recipient_address, share_of_coins); + }); + + // Send any remaining "dust" (leftover due to rounding error) to the withdrawal address. + if (coin::value(&coins) > 0) { + aptos_account::deposit_coins(vesting_contract.withdrawal_address, coins); + } else { + coin::destroy_zero(coins); + }; + + emit_event( + &mut vesting_contract.distribute_events, + DistributeEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + amount: total_distribution_amount, + }, + ); + } + + /// Call `distribute` for many vesting contracts. + public entry fun distribute_many(contract_addresses: vector
) acquires VestingContract { + let len = vector::length(&contract_addresses); + + assert!(len != 0, error::invalid_argument(EVEC_EMPTY_FOR_MANY_FUNCTION)); + + vector::for_each_ref(&contract_addresses, |contract_address| { + let contract_address = *contract_address; + distribute(contract_address); + }); + } + + /// Terminate the vesting contract and send all funds back to the withdrawal address. + public entry fun terminate_vesting_contract(admin: &signer, contract_address: address) acquires VestingContract { + assert_active_vesting_contract(contract_address); + + // Distribute all withdrawable coins, which should have been from previous rewards withdrawal or vest. + distribute(contract_address); + + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let (active_stake, _, pending_active_stake, _) = stake::get_stake(vesting_contract.staking.pool_address); + assert!(pending_active_stake == 0, error::invalid_state(EPENDING_STAKE_FOUND)); + + // Unlock all remaining active stake. + vesting_contract.state = VESTING_POOL_TERMINATED; + vesting_contract.remaining_grant = 0; + unlock_stake(vesting_contract, active_stake); + + emit_event( + &mut vesting_contract.terminate_events, + TerminateEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + }, + ); + } + + /// Withdraw all funds to the preset vesting contract's withdrawal address. This can only be called if the contract + /// has already been terminated. + public entry fun admin_withdraw(admin: &signer, contract_address: address) acquires VestingContract { + let vesting_contract = borrow_global(contract_address); + assert!(vesting_contract.state == VESTING_POOL_TERMINATED, error::invalid_state(EVESTING_CONTRACT_STILL_ACTIVE)); + + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let coins = withdraw_stake(vesting_contract, contract_address); + let amount = coin::value(&coins); + if (amount == 0) { + coin::destroy_zero(coins); + return + }; + aptos_account::deposit_coins(vesting_contract.withdrawal_address, coins); + + emit_event( + &mut vesting_contract.admin_withdraw_events, + AdminWithdrawEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + amount, + }, + ); + } + + public entry fun update_operator( + admin: &signer, + contract_address: address, + new_operator: address, + commission_percentage: u64, + ) acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + let old_operator = vesting_contract.staking.operator; + staking_contract::switch_operator(contract_signer, old_operator, new_operator, commission_percentage); + vesting_contract.staking.operator = new_operator; + vesting_contract.staking.commission_percentage = commission_percentage; + + emit_event( + &mut vesting_contract.update_operator_events, + UpdateOperatorEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + old_operator, + new_operator, + commission_percentage, + }, + ); + } + + public entry fun update_operator_with_same_commission( + admin: &signer, + contract_address: address, + new_operator: address, + ) acquires VestingContract { + let commission_percentage = operator_commission_percentage(contract_address); + update_operator(admin, contract_address, new_operator, commission_percentage); + } + + public entry fun update_commission_percentage( + admin: &signer, + contract_address: address, + new_commission_percentage: u64, + ) acquires VestingContract { + let operator = operator(contract_address); + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + staking_contract::update_commision(contract_signer, operator, new_commission_percentage); + vesting_contract.staking.commission_percentage = new_commission_percentage; + // This function does not emit an event. Instead, `staking_contract::update_commission_percentage` + // emits the event for this commission percentage update. + } + + public entry fun update_voter( + admin: &signer, + contract_address: address, + new_voter: address, + ) acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + let old_voter = vesting_contract.staking.voter; + staking_contract::update_voter(contract_signer, vesting_contract.staking.operator, new_voter); + vesting_contract.staking.voter = new_voter; + + emit_event( + &mut vesting_contract.update_voter_events, + UpdateVoterEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + old_voter, + new_voter, + }, + ); + } + + public entry fun reset_lockup( + admin: &signer, + contract_address: address, + ) acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + staking_contract::reset_lockup(contract_signer, vesting_contract.staking.operator); + + emit_event( + &mut vesting_contract.reset_lockup_events, + ResetLockupEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + new_lockup_expiration_secs: stake::get_lockup_secs(vesting_contract.staking.pool_address), + }, + ); + } + + public entry fun set_beneficiary( + admin: &signer, + contract_address: address, + shareholder: address, + new_beneficiary: address, + ) acquires VestingContract { + // Verify that the beneficiary account is set up to receive APT. This is a requirement so distribute() wouldn't + // fail and block all other accounts from receiving APT if one beneficiary is not registered. + assert_account_is_registered_for_apt(new_beneficiary); + + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + + let old_beneficiary = get_beneficiary(vesting_contract, shareholder); + let beneficiaries = &mut vesting_contract.beneficiaries; + if (simple_map::contains_key(beneficiaries, &shareholder)) { + let beneficiary = simple_map::borrow_mut(beneficiaries, &shareholder); + *beneficiary = new_beneficiary; + } else { + simple_map::add(beneficiaries, shareholder, new_beneficiary); + }; + + emit_event( + &mut vesting_contract.set_beneficiary_events, + SetBeneficiaryEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + shareholder, + old_beneficiary, + new_beneficiary, + }, + ); + } + + /// Remove the beneficiary for the given shareholder. All distributions will sent directly to the shareholder + /// account. + public entry fun reset_beneficiary( + account: &signer, + contract_address: address, + shareholder: address, + ) acquires VestingAccountManagement, VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + let addr = signer::address_of(account); + assert!( + addr == vesting_contract.admin || + addr == get_role_holder(contract_address, utf8(ROLE_BENEFICIARY_RESETTER)), + error::permission_denied(EPERMISSION_DENIED), + ); + + let beneficiaries = &mut vesting_contract.beneficiaries; + if (simple_map::contains_key(beneficiaries, &shareholder)) { + simple_map::remove(beneficiaries, &shareholder); + }; + } + + public entry fun set_management_role( + admin: &signer, + contract_address: address, + role: String, + role_holder: address, + ) acquires VestingAccountManagement, VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + + if (!exists(contract_address)) { + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + move_to(contract_signer, VestingAccountManagement { + roles: simple_map::create(), + }) + }; + let roles = &mut borrow_global_mut(contract_address).roles; + if (simple_map::contains_key(roles, &role)) { + *simple_map::borrow_mut(roles, &role) = role_holder; + } else { + simple_map::add(roles, role, role_holder); + }; + } + + public entry fun set_beneficiary_resetter( + admin: &signer, + contract_address: address, + beneficiary_resetter: address, + ) acquires VestingAccountManagement, VestingContract { + set_management_role(admin, contract_address, utf8(ROLE_BENEFICIARY_RESETTER), beneficiary_resetter); + } + + public fun get_role_holder(contract_address: address, role: String): address acquires VestingAccountManagement { + assert!(exists(contract_address), error::not_found(EVESTING_ACCOUNT_HAS_NO_ROLES)); + let roles = &borrow_global(contract_address).roles; + assert!(simple_map::contains_key(roles, &role), error::not_found(EROLE_NOT_FOUND)); + *simple_map::borrow(roles, &role) + } + + /// For emergency use in case the admin needs emergency control of vesting contract account. + /// This doesn't give the admin total power as the admin would still need to follow the rules set by + /// staking_contract and stake modules. + public fun get_vesting_account_signer(admin: &signer, contract_address: address): signer acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + get_vesting_account_signer_internal(vesting_contract) + } + + fun get_vesting_account_signer_internal(vesting_contract: &VestingContract): signer { + account::create_signer_with_capability(&vesting_contract.signer_cap) + } + + /// Create a salt for generating the resource accounts that will be holding the VestingContract. + /// This address should be deterministic for the same admin and vesting contract creation nonce. + fun create_vesting_contract_account( + admin: &signer, + contract_creation_seed: vector, + ): (signer, SignerCapability) acquires AdminStore { + let admin_store = borrow_global_mut(signer::address_of(admin)); + let seed = bcs::to_bytes(&signer::address_of(admin)); + vector::append(&mut seed, bcs::to_bytes(&admin_store.nonce)); + admin_store.nonce = admin_store.nonce + 1; + + // Include a salt to avoid conflicts with any other modules out there that might also generate + // deterministic resource accounts for the same admin address + nonce. + vector::append(&mut seed, VESTING_POOL_SALT); + vector::append(&mut seed, contract_creation_seed); + + let (account_signer, signer_cap) = account::create_resource_account(admin, seed); + // Register the vesting contract account to receive APT as it'll be sent to it when claiming unlocked stake from + // the underlying staking contract. + coin::register(&account_signer); + + (account_signer, signer_cap) + } + + fun verify_admin(admin: &signer, vesting_contract: &VestingContract) { + assert!(signer::address_of(admin) == vesting_contract.admin, error::unauthenticated(ENOT_ADMIN)); + } + + fun assert_vesting_contract_exists(contract_address: address) { + assert!(exists(contract_address), error::not_found(EVESTING_CONTRACT_NOT_FOUND)); + } + + fun assert_active_vesting_contract(contract_address: address) acquires VestingContract { + assert_vesting_contract_exists(contract_address); + let vesting_contract = borrow_global(contract_address); + assert!(vesting_contract.state == VESTING_POOL_ACTIVE, error::invalid_state(EVESTING_CONTRACT_NOT_ACTIVE)); + } + + fun unlock_stake(vesting_contract: &VestingContract, amount: u64) { + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + staking_contract::unlock_stake(contract_signer, vesting_contract.staking.operator, amount); + } + + fun withdraw_stake(vesting_contract: &VestingContract, contract_address: address): Coin { + // Claim any withdrawable distribution from the staking contract. The withdrawn coins will be sent directly to + // the vesting contract's account. + staking_contract::distribute(contract_address, vesting_contract.staking.operator); + let withdrawn_coins = coin::balance(contract_address); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + coin::withdraw(contract_signer, withdrawn_coins) + } + + fun get_beneficiary(contract: &VestingContract, shareholder: address): address { + if (simple_map::contains_key(&contract.beneficiaries, &shareholder)) { + *simple_map::borrow(&contract.beneficiaries, &shareholder) + } else { + shareholder + } + } + + #[test_only] + use aptos_framework::stake::with_rewards; + + #[test_only] + use aptos_framework::account::create_account_for_test; + use aptos_std::math64::min; + + #[test_only] + const MIN_STAKE: u64 = 100000000000000; // 1M APT coins with 8 decimals. + + #[test_only] + const GRANT_AMOUNT: u64 = 20000000000000000; // 200M APT coins with 8 decimals. + + #[test_only] + const VESTING_SCHEDULE_CLIFF: u64 = 31536000; // 1 year + + #[test_only] + const VESTING_PERIOD: u64 = 2592000; // 30 days + + #[test_only] + const VALIDATOR_STATUS_PENDING_ACTIVE: u64 = 1; + #[test_only] + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + #[test_only] + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + #[test_only] + public entry fun setup(aptos_framework: &signer, accounts: &vector
) { + use aptos_framework::aptos_account::create_account; + + stake::initialize_for_test_custom(aptos_framework, MIN_STAKE, GRANT_AMOUNT * 10, 3600, true, 10, 10000, 1000000); + + vector::for_each_ref(accounts, |addr| { + let addr: address = *addr; + if (!account::exists_at(addr)) { + create_account(addr); + }; + }); + } + + #[test_only] + public fun setup_vesting_contract( + admin: &signer, + shareholders: &vector
, + shares: &vector, + withdrawal_address: address, + commission_percentage: u64, + ): address acquires AdminStore { + setup_vesting_contract_with_schedule( + admin, + shareholders, + shares, + withdrawal_address, + commission_percentage, + &vector[3, 2, 1], + 48, + ) + } + + #[test_only] + public fun setup_vesting_contract_with_schedule( + admin: &signer, + shareholders: &vector
, + shares: &vector, + withdrawal_address: address, + commission_percentage: u64, + vesting_numerators: &vector, + vesting_denominator: u64, + ): address acquires AdminStore { + let schedule = vector::empty(); + vector::for_each_ref(vesting_numerators, |num| { + vector::push_back(&mut schedule, fixed_point32::create_from_rational(*num, vesting_denominator)); + }); + let vesting_schedule = create_vesting_schedule( + schedule, + timestamp::now_seconds() + VESTING_SCHEDULE_CLIFF, + VESTING_PERIOD, + ); + + let admin_address = signer::address_of(admin); + let buy_ins = simple_map::create>(); + vector::enumerate_ref(shares, |i, share| { + let shareholder = *vector::borrow(shareholders, i); + simple_map::add(&mut buy_ins, shareholder, stake::mint_coins(*share)); + }); + + create_vesting_contract( + admin, + shareholders, + buy_ins, + vesting_schedule, + withdrawal_address, + admin_address, + admin_address, + commission_percentage, + vector[], + ) + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder_1 = @0x234, shareholder_2 = @0x345, withdrawal = @111)] + public entry fun test_end_to_end( + aptos_framework: &signer, + admin: &signer, + shareholder_1: &signer, + shareholder_2: &signer, + withdrawal: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let withdrawal_address = signer::address_of(withdrawal); + let shareholder_1_address = signer::address_of(shareholder_1); + let shareholder_2_address = signer::address_of(shareholder_2); + let shareholders = &vector[shareholder_1_address, shareholder_2_address]; + let shareholder_1_share = GRANT_AMOUNT / 4; + let shareholder_2_share = GRANT_AMOUNT * 3 / 4; + let shares = &vector[shareholder_1_share, shareholder_2_share]; + + // Create the vesting contract. + setup( + aptos_framework, &vector[admin_address, withdrawal_address, shareholder_1_address, shareholder_2_address]); + let contract_address = setup_vesting_contract(admin, shareholders, shares, withdrawal_address, 0); + assert!(vector::length(&borrow_global(admin_address).vesting_contracts) == 1, 0); + let stake_pool_address = stake_pool_address(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + + // The stake pool is still in pending active stake, so unlock_rewards and vest shouldn't do anything. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, admin, stake_pool_address, false); + assert!(stake::get_validator_state(stake_pool_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 1); + unlock_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + + // Wait for the validator to join the validator set. No rewards are earnt yet so unlock_rewards and vest should + // still do nothing. + stake::end_epoch(); + assert!(stake::get_validator_state(stake_pool_address) == VALIDATOR_STATUS_ACTIVE, 2); + unlock_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + + // Stake pool earns some rewards. unlock_rewards should unlock the right amount. + stake::end_epoch(); + let rewards = get_accumulated_rewards(contract_address); + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Stake pool earns more rewards. vest should unlock the rewards but no vested tokens as vesting hasn't started. + stake::end_epoch(); + rewards = with_rewards(rewards); // Pending inactive stake still earns rewards. + rewards = rewards + get_accumulated_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Fast forward to stake lockup expiration so rewards are fully unlocked. + // In the mean time, rewards still earn rewards. + // Calling distribute() should send rewards to the shareholders. + stake::fast_forward_to_unlock(stake_pool_address); + rewards = with_rewards(rewards); + distribute(contract_address); + let shareholder_1_bal = coin::balance(shareholder_1_address); + let shareholder_2_bal = coin::balance(shareholder_2_address); + // Distribution goes by the shares of the vesting contract. + assert!(shareholder_1_bal == rewards / 4, shareholder_1_bal); + assert!(shareholder_2_bal == rewards * 3 / 4, shareholder_2_bal); + + // Fast forward time to the vesting start. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address)); + // Calling vest only unlocks rewards but not any vested token as the first vesting period hasn't passed yet. + rewards = get_accumulated_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::fast_forward_seconds(VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + let remaining_grant = GRANT_AMOUNT - vested_amount; + let pending_distribution = rewards + vested_amount; + assert!(remaining_grant(contract_address) == remaining_grant, remaining_grant(contract_address)); + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + + // Fast forward to the end of the fourth period. We can call vest() 3 times to vest the last 3 periods. + timestamp::fast_forward_seconds(VESTING_PERIOD * 3); + vest(contract_address); + vested_amount = fraction(GRANT_AMOUNT, 2, 48); + remaining_grant = remaining_grant - vested_amount; + pending_distribution = pending_distribution + vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + vest(contract_address); + vested_amount = fraction(GRANT_AMOUNT, 1, 48); + remaining_grant = remaining_grant - vested_amount; + pending_distribution = pending_distribution + vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + // The last vesting fraction (1/48) is repeated beyond the first 3 periods. + vest(contract_address); + remaining_grant = remaining_grant - vested_amount; + pending_distribution = pending_distribution + vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + stake::end_epoch(); + let total_active = with_rewards(remaining_grant); + pending_distribution = with_rewards(pending_distribution); + distribute(contract_address); + stake::assert_stake_pool(stake_pool_address, total_active, 0, 0, 0); + assert!(coin::balance(shareholder_1_address) == shareholder_1_bal + pending_distribution / 4, 0); + assert!(coin::balance(shareholder_2_address) == shareholder_2_bal + pending_distribution * 3 / 4, 1); + // Withdrawal address receives the left-over dust of 1 coin due to rounding error. + assert!(coin::balance(withdrawal_address) == 1, 0); + + // Admin terminates the vesting contract. + terminate_vesting_contract(admin, contract_address); + stake::assert_stake_pool(stake_pool_address, 0, 0, 0, total_active); + assert!(remaining_grant(contract_address) == 0, 0); + stake::fast_forward_to_unlock(stake_pool_address); + let withdrawn_amount = with_rewards(total_active); + stake::assert_stake_pool(stake_pool_address, 0, withdrawn_amount, 0, 0); + let previous_bal = coin::balance(withdrawal_address); + admin_withdraw(admin, contract_address); + assert!(coin::balance(withdrawal_address) == previous_bal + withdrawn_amount, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x1000C, location = Self)] + public entry fun test_create_vesting_contract_with_zero_grant_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1], &vector[0], admin_address, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public entry fun test_create_vesting_contract_with_no_shareholders_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[], &vector[], admin_address, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x10005, location = Self)] + public entry fun test_create_vesting_contract_with_mistmaching_shareholders_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], admin_address, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60001, location = aptos_framework::aptos_account)] + public entry fun test_create_vesting_contract_with_invalid_withdrawal_address_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], @5, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60001, location = aptos_framework::aptos_account)] + public entry fun test_create_vesting_contract_with_missing_withdrawal_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], @11, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60002, location = aptos_framework::aptos_account)] + public entry fun test_create_vesting_contract_with_unregistered_withdrawal_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + create_account_for_test(@11); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], @11, 0); + } + + #[test(aptos_framework = @0x1)] + #[expected_failure(abort_code = 0x10002, location = Self)] + public entry fun test_create_empty_vesting_schedule_should_fail(aptos_framework: &signer) { + setup(aptos_framework, &vector[]); + create_vesting_schedule(vector[], 1, 1); + } + + #[test(aptos_framework = @0x1)] + #[expected_failure(abort_code = 0x10003, location = Self)] + public entry fun test_create_vesting_schedule_with_zero_period_duration_should_fail(aptos_framework: &signer) { + setup(aptos_framework, &vector[]); + create_vesting_schedule(vector[fixed_point32::create_from_rational(1, 1)], 1, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x10006, location = Self)] + public entry fun test_create_vesting_schedule_with_invalid_vesting_start_should_fail(aptos_framework: &signer) { + setup(aptos_framework, &vector[]); + timestamp::update_global_time_for_test_secs(1000); + create_vesting_schedule( + vector[fixed_point32::create_from_rational(1, 1)], + 900, + 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_vest_twice_should_not_double_count( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, admin, stake_pool_address, true); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + let remaining_grant = GRANT_AMOUNT - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + // Calling vest() a second time shouldn't change anything. + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_unlock_rewards_twice_should_not_double_count( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, admin, stake_pool_address, true); + + // Stake pool earns some rewards. unlock_rewards should unlock the right amount. + stake::end_epoch(); + let rewards = get_accumulated_rewards(contract_address); + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Calling unlock_rewards a second time shouldn't change anything as no new rewards has accumulated. + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234, operator = @0x345)] + public entry fun test_unlock_rewards_should_pay_commission_first( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + assert!(operator_commission_percentage(contract_address) == 0, 0); + + // 10% commission will be paid to the operator. + update_operator(admin, contract_address, operator_address, 10); + assert!(operator_commission_percentage(contract_address) == 10, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, stake_pool_address, true); + + // Stake pool earns some rewards. unlock_rewards should unlock the right amount. + stake::end_epoch(); + let accumulated_rewards = get_accumulated_rewards(contract_address); + let commission = accumulated_rewards / 10; // 10%. + let staker_rewards = accumulated_rewards - commission; + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, accumulated_rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Distribution should pay commission to operator first and remaining amount to shareholders. + stake::fast_forward_to_unlock(stake_pool_address); + stake::assert_stake_pool(stake_pool_address, with_rewards(GRANT_AMOUNT), with_rewards(accumulated_rewards), 0, 0); + // Operator also earns more commission from the rewards earnt on the withdrawn rewards. + let commission_on_staker_rewards = (with_rewards(staker_rewards) - staker_rewards) / 10; + staker_rewards = with_rewards(staker_rewards) - commission_on_staker_rewards; + commission = with_rewards(commission) + commission_on_staker_rewards; + distribute(contract_address); + // Rounding error leads to a dust amount of 1 transferred to the staker. + assert!(coin::balance(shareholder_address) == staker_rewards + 1, 0); + assert!(coin::balance(operator_address) == commission - 1, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234, operator = @0x345)] + public entry fun test_request_commission_should_not_lock_rewards_for_shareholders( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + assert!(operator_commission_percentage(contract_address) == 0, 0); + + // 10% commission will be paid to the operator. + update_operator(admin, contract_address, operator_address, 10); + assert!(operator_commission_percentage(contract_address) == 10, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, stake_pool_address, true); + + // Stake pool earns some rewards. + stake::end_epoch(); + + // Operator requests commission directly with staking_contract first. + let accumulated_rewards = get_accumulated_rewards(contract_address); + let commission = accumulated_rewards / 10; // 10%. + let staker_rewards = accumulated_rewards - commission; + staking_contract::request_commission(operator, contract_address, operator_address); + + // Unlock vesting rewards. This should still pay out the accumulated rewards to shareholders. + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, accumulated_rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Distribution should pay commission to operator first and remaining amount to shareholders. + stake::fast_forward_to_unlock(stake_pool_address); + stake::assert_stake_pool(stake_pool_address, with_rewards(GRANT_AMOUNT), with_rewards(accumulated_rewards), 0, 0); + // Operator also earns more commission from the rewards earnt on the withdrawn rewards. + let commission_on_staker_rewards = (with_rewards(staker_rewards) - staker_rewards) / 10; + staker_rewards = with_rewards(staker_rewards) - commission_on_staker_rewards; + commission = with_rewards(commission) + commission_on_staker_rewards; + distribute(contract_address); + // Rounding error leads to a dust amount of 1 transferred to the staker. + assert!(coin::balance(shareholder_address) == staker_rewards + 1, 0); + assert!(coin::balance(operator_address) == commission - 1, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, operator = @0x345)] + public entry fun test_update_operator_with_same_commission( + aptos_framework: &signer, + admin: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + setup(aptos_framework, &vector[admin_address, @11, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 10); + + update_operator_with_same_commission(admin, contract_address, operator_address); + assert!(operator_commission_percentage(contract_address) == 10, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234, operator = @0x345)] + public entry fun test_commission_percentage_change( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + assert!(operator_commission_percentage(contract_address) == 0, 0); + let stake_pool_address = stake_pool_address(contract_address); + + // 10% commission will be paid to the operator. + update_operator(admin, contract_address, operator_address, 10); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, stake_pool_address, true); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + assert!(get_accumulated_rewards(contract_address) == 0, 0); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Stake pool earns some rewards. + stake::end_epoch(); + let (_, accumulated_rewards, _) = staking_contract::staking_contract_amounts(contract_address, operator_address); + + // Update commission percentage to 20%. This also immediately requests commission. + update_commission_percentage(admin, contract_address, 20); + // Assert that the operator is still the same, and the commission percentage is updated to 20%. + assert!(operator(contract_address) == operator_address, 0); + assert!(operator_commission_percentage(contract_address) == 20, 0); + + // Commission is calculated using the previous commission percentage which is 10%. + let expected_commission = accumulated_rewards / 10; + + // Stake pool earns some more rewards. + stake::end_epoch(); + let (_, accumulated_rewards, _) = staking_contract::staking_contract_amounts(contract_address, operator_address); + + // Request commission again. + staking_contract::request_commission(operator, contract_address, operator_address); + // The commission is calculated using the current commission percentage which is 20%. + expected_commission = with_rewards(expected_commission) + (accumulated_rewards / 5); + + // Unlocks the commission. + stake::fast_forward_to_unlock(stake_pool_address); + expected_commission = with_rewards(expected_commission); + + // Distribute the commission to the operator. + distribute(contract_address); + + // Assert that the operator receives the expected commission. + assert!(coin::balance(operator_address) == expected_commission, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_cannot_unlock_rewards_after_contract_is_terminated( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Immediately terminate. Calling unlock_rewards should now fail. + terminate_vesting_contract(admin, contract_address); + unlock_rewards(contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_vesting_contract_with_zero_vestings( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract_with_schedule( + admin, + &vector[shareholder_address], + &vector[GRANT_AMOUNT], + admin_address, + 0, + &vector[0, 3, 0, 2], + 48, + ); + let stake_pool_address = stake_pool_address(contract_address); + + // First vest() should unlock 0 according to schedule. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Next period should vest 3/48. + timestamp::fast_forward_seconds(VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + let remaining_grant = GRANT_AMOUNT - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + timestamp::fast_forward_seconds(VESTING_PERIOD); + // Distribute the previous vested amount. + distribute(contract_address); + // Next period should vest 0 again. + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, 0); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + // Next period should vest 2/48. + timestamp::fast_forward_seconds(VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 2, 48); + remaining_grant = remaining_grant - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_last_vest_should_distribute_remaining_amount( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract_with_schedule( + admin, + &vector[shareholder_address], + &vector[GRANT_AMOUNT], + admin_address, + 0, + // First vest = 3/4 but last vest should only be for the remaining 1/4. + &vector[3], + 4, + ); + let stake_pool_address = stake_pool_address(contract_address); + + // First vest is 3/48 + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 4); + let remaining_grant = GRANT_AMOUNT - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + timestamp::fast_forward_seconds(VESTING_PERIOD); + // Distribute the previous vested amount. + distribute(contract_address); + // Last vest should be the remaining amount (1/4). + vest(contract_address); + let vested_amount = remaining_grant; + remaining_grant = 0; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_cannot_vest_after_contract_is_terminated( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Immediately terminate. Calling vest should now fail. + terminate_vesting_contract(admin, contract_address); + vest(contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_cannot_terminate_twice( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Call terminate_vesting_contract twice should fail. + terminate_vesting_contract(admin, contract_address); + terminate_vesting_contract(admin, contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30009, location = Self)] + public entry fun test_cannot_call_admin_withdraw_if_contract_is_not_terminated( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Calling admin_withdraw should fail as contract has not been terminated. + admin_withdraw(admin, contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60001, location = aptos_framework::aptos_account)] + public entry fun test_set_beneficiary_with_missing_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@1, @2], &vector[GRANT_AMOUNT, GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @1, @11); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60002, location = aptos_framework::aptos_account)] + public entry fun test_set_beneficiary_with_unregistered_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@1, @2], &vector[GRANT_AMOUNT, GRANT_AMOUNT], admin_address, 0); + create_account_for_test(@11); + set_beneficiary(admin, contract_address, @1, @11); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + public entry fun test_set_beneficiary_should_send_distribution( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11]); + let contract_address = setup_vesting_contract( + admin, &vector[@1], &vector[GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @1, @11); + assert!(beneficiary(contract_address, @1) == @11, 0); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + + // Distribution should go to the beneficiary account. + stake::end_epoch(); + // No rewards as validator never joined the validator set. + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + distribute(contract_address); + let balance = coin::balance(@11); + assert!(balance == vested_amount, balance); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + public entry fun test_set_management_role( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + let role = utf8(b"RANDOM"); + set_management_role(admin, contract_address, role, @12); + assert!(get_role_holder(contract_address, role) == @12, 0); + set_management_role(admin, contract_address, role, @13); + assert!(get_role_holder(contract_address, role) == @13, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + public entry fun test_reset_beneficiary( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11, @12]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @11, @12); + assert!(beneficiary(contract_address, @11) == @12, 0); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + + // Reset the beneficiary. + reset_beneficiary(admin, contract_address, @11); + + // Distribution should go to the original account. + stake::end_epoch(); + // No rewards as validator never joined the validator set. + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + distribute(contract_address); + assert!(coin::balance(@11) == vested_amount, 0); + assert!(coin::balance(@12) == 0, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, resetter = @0x234)] + public entry fun test_reset_beneficiary_with_resetter_role( + aptos_framework: &signer, + admin: &signer, + resetter: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11, @12]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @11, @12); + assert!(beneficiary(contract_address, @11) == @12, 0); + + // Reset the beneficiary with the resetter role. + let resetter_address = signer::address_of(resetter); + set_beneficiary_resetter(admin, contract_address, resetter_address); + assert!(simple_map::length(&borrow_global(contract_address).roles) == 1, 0); + reset_beneficiary(resetter, contract_address, @11); + assert!(beneficiary(contract_address, @11) == @11, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, resetter = @0x234, random = @0x345)] + #[expected_failure(abort_code = 0x5000F, location = Self)] + public entry fun test_reset_beneficiary_with_unauthorized( + aptos_framework: &signer, + admin: &signer, + resetter: &signer, + random: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + + // Reset the beneficiary with a random account. This should failed. + set_beneficiary_resetter(admin, contract_address, signer::address_of(resetter)); + reset_beneficiary(random, contract_address, @11); + } + + #[test(aptos_framework = @0x1, admin = @0x123, resetter = @0x234, random = @0x345)] + public entry fun test_shareholder( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11, @12]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + + // Confirm that the lookup returns the same address when a shareholder is + // passed for which there is no beneficiary. + assert!(shareholder(contract_address, @11) == @11, 0); + + // Set a beneficiary for @11. + set_beneficiary(admin, contract_address, @11, @12); + assert!(beneficiary(contract_address, @11) == @12, 0); + + // Confirm that lookup from beneficiary to shareholder works when a beneficiary + // is set. + assert!(shareholder(contract_address, @12) == @11, 0); + + // Confirm that it returns 0x0 when the address is not in the map. + assert!(shareholder(contract_address, @33) == @0x0, 0); + } + + #[test_only] + fun get_accumulated_rewards(contract_address: address): u64 acquires VestingContract { + let vesting_contract = borrow_global(contract_address); + let (active_stake, _, _, _) = stake::get_stake(vesting_contract.staking.pool_address); + active_stake - vesting_contract.remaining_grant + } + + #[test_only] + fun fraction(total: u64, numerator: u64, denominator: u64): u64 { + fixed_point32::multiply_u64(total, fixed_point32::create_from_rational(numerator, denominator)) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/voting.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/voting.move new file mode 100644 index 0000000..5b512c4 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosFramework/voting.move @@ -0,0 +1,1108 @@ +/// +/// This is the general Voting module that can be used as part of a DAO Governance. Voting is designed to be used by +/// standalone governance modules, who has full control over the voting flow and is responsible for voting power +/// calculation and including proper capabilities when creating the proposal so resolution can go through. +/// On-chain governance of the Aptos network also uses Voting. +/// +/// The voting flow: +/// 1. The Voting module can be deployed at a known address (e.g. 0x1 for Aptos on-chain governance) +/// 2. The governance module, e.g. AptosGovernance, can be deployed later and define a GovernanceProposal resource type +/// that can also contain other information such as Capability resource for authorization. +/// 3. The governance module's owner can then register the ProposalType with Voting. This also hosts the proposal list +/// (forum) on the calling account. +/// 4. A proposer, through the governance module, can call Voting::create_proposal to create a proposal. create_proposal +/// cannot be called directly not through the governance module. A script hash of the resolution script that can later +/// be called to execute the proposal is required. +/// 5. A voter, through the governance module, can call Voting::vote on a proposal. vote requires passing a &ProposalType +/// and thus only the governance module that registers ProposalType can call vote. +/// 6. Once the proposal's expiration time has passed and more than the defined threshold has voted yes on the proposal, +/// anyone can call resolve which returns the content of the proposal (of type ProposalType) that can be used to execute. +/// 7. Only the resolution script with the same script hash specified in the proposal can call Voting::resolve as part of +/// the resolution process. +module aptos_framework::voting { + use std::bcs::to_bytes; + use std::error; + use std::option::{Self, Option}; + use std::signer; + use std::string::{String, utf8}; + use std::vector; + + use aptos_std::from_bcs::to_u64; + use aptos_std::simple_map::{Self, SimpleMap}; + use aptos_std::table::{Self, Table}; + use aptos_std::type_info::{Self, TypeInfo}; + + use aptos_framework::account; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::timestamp; + use aptos_framework::transaction_context; + use aptos_std::from_bcs; + + /// Current script's execution hash does not match the specified proposal's + const EPROPOSAL_EXECUTION_HASH_NOT_MATCHING: u64 = 1; + /// Proposal cannot be resolved. Either voting duration has not passed, not enough votes, or fewer yes than no votes + const EPROPOSAL_CANNOT_BE_RESOLVED: u64 = 2; + /// Proposal cannot be resolved more than once + const EPROPOSAL_ALREADY_RESOLVED: u64 = 3; + /// Proposal cannot contain an empty execution script hash + const EPROPOSAL_EMPTY_EXECUTION_HASH: u64 = 4; + /// Proposal's voting period has already ended. + const EPROPOSAL_VOTING_ALREADY_ENDED: u64 = 5; + /// Voting forum has already been registered. + const EVOTING_FORUM_ALREADY_REGISTERED: u64 = 6; + /// Minimum vote threshold cannot be higher than early resolution threshold. + const EINVALID_MIN_VOTE_THRESHOLD: u64 = 7; + /// Resolution of a proposal cannot happen atomically in the same transaction as the last vote. + const ERESOLUTION_CANNOT_BE_ATOMIC: u64 = 8; + /// Cannot vote if the specified multi-step proposal is in execution. + const EMULTI_STEP_PROPOSAL_IN_EXECUTION: u64 = 9; + /// If a proposal is multi-step, we need to use `resolve_proposal_v2()` to resolve it. + /// If we use `resolve()` to resolve a multi-step proposal, it will fail with EMULTI_STEP_PROPOSAL_CANNOT_USE_SINGLE_STEP_RESOLVE_FUNCTION. + const EMULTI_STEP_PROPOSAL_CANNOT_USE_SINGLE_STEP_RESOLVE_FUNCTION: u64 = 10; + /// If we call `resolve_proposal_v2()` to resolve a single-step proposal, the `next_execution_hash` parameter should be an empty vector. + const ESINGLE_STEP_PROPOSAL_CANNOT_HAVE_NEXT_EXECUTION_HASH: u64 = 11; + /// Cannot call `is_multi_step_proposal_in_execution()` on single-step proposals. + const EPROPOSAL_IS_SINGLE_STEP: u64 = 12; + + /// ProposalStateEnum representing proposal state. + const PROPOSAL_STATE_PENDING: u64 = 0; + const PROPOSAL_STATE_SUCCEEDED: u64 = 1; + /// Proposal has failed because either the min vote threshold is not met or majority voted no. + const PROPOSAL_STATE_FAILED: u64 = 3; + + /// Key used to track the resolvable time in the proposal's metadata. + const RESOLVABLE_TIME_METADATA_KEY: vector = b"RESOLVABLE_TIME_METADATA_KEY"; + /// Key used to track if the proposal is multi-step + const IS_MULTI_STEP_PROPOSAL_KEY: vector = b"IS_MULTI_STEP_PROPOSAL_KEY"; + /// Key used to track if the multi-step proposal is in execution / resolving in progress. + const IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY: vector = b"IS_MULTI_STEP_PROPOSAL_IN_EXECUTION"; + + /// Extra metadata (e.g. description, code url) can be part of the ProposalType struct. + struct Proposal has store { + /// Required. The address of the proposer. + proposer: address, + + /// Required. Should contain enough information to execute later, for example the required capability. + /// This is stored as an option so we can return it to governance when the proposal is resolved. + execution_content: Option, + + /// Optional. Value is serialized value of an attribute. + /// Currently, we have three attributes that are used by the voting flow. + /// 1. RESOLVABLE_TIME_METADATA_KEY: this is uesed to record the resolvable time to ensure that resolution has to be done non-atomically. + /// 2. IS_MULTI_STEP_PROPOSAL_KEY: this is used to track if a proposal is single-step or multi-step. + /// 3. IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY: this attribute only applies to multi-step proposals. A single-step proposal will not have + /// this field in its metadata map. The value is used to indicate if a multi-step proposal is in execution. If yes, we will disable further + /// voting for this multi-step proposal. + metadata: SimpleMap>, + + /// Timestamp when the proposal was created. + creation_time_secs: u64, + + /// Required. The hash for the execution script module. Only the same exact script module can resolve this + /// proposal. + execution_hash: vector, + + /// A proposal is only resolved if expiration has passed and the number of votes is above threshold. + min_vote_threshold: u128, + expiration_secs: u64, + + /// Optional. Early resolution threshold. If specified, the proposal can be resolved early if the total + /// number of yes or no votes passes this threshold. + /// For example, this can be set to 50% of the total supply of the voting token, so if > 50% vote yes or no, + /// the proposal can be resolved before expiration. + early_resolution_vote_threshold: Option, + + /// Number of votes for each outcome. + /// u128 since the voting power is already u64 and can add up to more than u64 can hold. + yes_votes: u128, + no_votes: u128, + + /// Whether the proposal has been resolved. + is_resolved: bool, + /// Resolution timestamp if the proposal has been resolved. 0 otherwise. + resolution_time_secs: u64, + } + + struct VotingForum has key { + /// Use Table for execution optimization instead of Vector for gas cost since Vector is read entirely into memory + /// during execution while only relevant Table entries are. + proposals: Table>, + events: VotingEvents, + /// Unique identifier for a proposal. This allows for 2 * 10**19 proposals. + next_proposal_id: u64, + } + + struct VotingEvents has store { + create_proposal_events: EventHandle, + register_forum_events: EventHandle, + resolve_proposal_events: EventHandle, + vote_events: EventHandle, + } + + struct CreateProposalEvent has drop, store { + proposal_id: u64, + early_resolution_vote_threshold: Option, + execution_hash: vector, + expiration_secs: u64, + metadata: SimpleMap>, + min_vote_threshold: u128, + } + + struct RegisterForumEvent has drop, store { + hosting_account: address, + proposal_type_info: TypeInfo, + } + + struct VoteEvent has drop, store { + proposal_id: u64, + num_votes: u64, + } + + struct ResolveProposal has drop, store { + proposal_id: u64, + yes_votes: u128, + no_votes: u128, + resolved_early: bool + } + + public fun register(account: &signer) { + let addr = signer::address_of(account); + assert!(!exists>(addr), error::already_exists(EVOTING_FORUM_ALREADY_REGISTERED)); + + let voting_forum = VotingForum { + next_proposal_id: 0, + proposals: table::new>(), + events: VotingEvents { + create_proposal_events: account::new_event_handle(account), + register_forum_events: account::new_event_handle(account), + resolve_proposal_events: account::new_event_handle(account), + vote_events: account::new_event_handle(account), + } + }; + + event::emit_event( + &mut voting_forum.events.register_forum_events, + RegisterForumEvent { + hosting_account: addr, + proposal_type_info: type_info::type_of(), + }, + ); + + move_to(account, voting_forum); + } + + /// Create a single-step proposal with the given parameters + /// + /// @param voting_forum_address The forum's address where the proposal will be stored. + /// @param execution_content The execution content that will be given back at resolution time. This can contain + /// data such as a capability resource used to scope the execution. + /// @param execution_hash The hash for the execution script module. Only the same exact script module can resolve + /// this proposal. + /// @param min_vote_threshold The minimum number of votes needed to consider this proposal successful. + /// @param expiration_secs The time in seconds at which the proposal expires and can potentially be resolved. + /// @param early_resolution_vote_threshold The vote threshold for early resolution of this proposal. + /// @param metadata A simple_map that stores information about this proposal. + /// @return The proposal id. + public fun create_proposal( + proposer: address, + voting_forum_address: address, + execution_content: ProposalType, + execution_hash: vector, + min_vote_threshold: u128, + expiration_secs: u64, + early_resolution_vote_threshold: Option, + metadata: SimpleMap>, + ): u64 acquires VotingForum { + create_proposal_v2( + proposer, + voting_forum_address, + execution_content, + execution_hash, + min_vote_threshold, + expiration_secs, + early_resolution_vote_threshold, + metadata, + false + ) + } + + /// Create a single-step or a multi-step proposal with the given parameters + /// + /// @param voting_forum_address The forum's address where the proposal will be stored. + /// @param execution_content The execution content that will be given back at resolution time. This can contain + /// data such as a capability resource used to scope the execution. + /// @param execution_hash The sha-256 hash for the execution script module. Only the same exact script module can + /// resolve this proposal. + /// @param min_vote_threshold The minimum number of votes needed to consider this proposal successful. + /// @param expiration_secs The time in seconds at which the proposal expires and can potentially be resolved. + /// @param early_resolution_vote_threshold The vote threshold for early resolution of this proposal. + /// @param metadata A simple_map that stores information about this proposal. + /// @param is_multi_step_proposal A bool value that indicates if the proposal is single-step or multi-step. + /// @return The proposal id. + public fun create_proposal_v2( + proposer: address, + voting_forum_address: address, + execution_content: ProposalType, + execution_hash: vector, + min_vote_threshold: u128, + expiration_secs: u64, + early_resolution_vote_threshold: Option, + metadata: SimpleMap>, + is_multi_step_proposal: bool, + ): u64 acquires VotingForum { + if (option::is_some(&early_resolution_vote_threshold)) { + assert!( + min_vote_threshold <= *option::borrow(&early_resolution_vote_threshold), + error::invalid_argument(EINVALID_MIN_VOTE_THRESHOLD), + ); + }; + // Make sure the execution script's hash is not empty. + assert!(vector::length(&execution_hash) > 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal_id = voting_forum.next_proposal_id; + voting_forum.next_proposal_id = voting_forum.next_proposal_id + 1; + + // Add a flag to indicate if this proposal is single-step or multi-step. + simple_map::add(&mut metadata, utf8(IS_MULTI_STEP_PROPOSAL_KEY), to_bytes(&is_multi_step_proposal)); + + let is_multi_step_in_execution_key = utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY); + if (is_multi_step_proposal) { + // If the given proposal is a multi-step proposal, we will add a flag to indicate if this multi-step proposal is in execution. + // This value is by default false. We turn this value to true when we start executing the multi-step proposal. This value + // will be used to disable further voting after we started executing the multi-step proposal. + simple_map::add(&mut metadata, is_multi_step_in_execution_key, to_bytes(&false)); + // If the proposal is a single-step proposal, we check if the metadata passed by the client has the IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY key. + // If they have the key, we will remove it, because a single-step proposal that doesn't need this key. + } else if (simple_map::contains_key(&mut metadata, &is_multi_step_in_execution_key)) { + simple_map::remove(&mut metadata, &is_multi_step_in_execution_key); + }; + + table::add(&mut voting_forum.proposals, proposal_id, Proposal { + proposer, + creation_time_secs: timestamp::now_seconds(), + execution_content: option::some(execution_content), + execution_hash, + metadata, + min_vote_threshold, + expiration_secs, + early_resolution_vote_threshold, + yes_votes: 0, + no_votes: 0, + is_resolved: false, + resolution_time_secs: 0, + }); + + event::emit_event( + &mut voting_forum.events.create_proposal_events, + CreateProposalEvent { + proposal_id, + early_resolution_vote_threshold, + execution_hash, + expiration_secs, + metadata, + min_vote_threshold, + }, + ); + + proposal_id + } + + /// Vote on the given proposal. + /// + /// @param _proof Required so only the governance module that defines ProposalType can initiate voting. + /// This guarantees that voting eligibility and voting power are controlled by the right governance. + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + /// @param num_votes Number of votes. Voting power should be calculated by governance. + /// @param should_pass Whether the votes are for yes or no. + public fun vote( + _proof: &ProposalType, + voting_forum_address: address, + proposal_id: u64, + num_votes: u64, + should_pass: bool, + ) acquires VotingForum { + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + // Voting might still be possible after the proposal has enough yes votes to be resolved early. This would only + // lead to possible proposal resolution failure if the resolve early threshold is not definitive (e.g. < 50% + 1 + // of the total voting token's supply). In this case, more voting might actually still be desirable. + // Governance mechanisms built on this voting module can apply additional rules on when voting is closed as + // appropriate. + assert!(!is_voting_period_over(proposal), error::invalid_state(EPROPOSAL_VOTING_ALREADY_ENDED)); + assert!(!proposal.is_resolved, error::invalid_state(EPROPOSAL_ALREADY_RESOLVED)); + // Assert this proposal is single-step, or if the proposal is multi-step, it is not in execution yet. + assert!(!simple_map::contains_key(&proposal.metadata, &utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY)) + || *simple_map::borrow(&proposal.metadata, &utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY)) == to_bytes(&false), + error::invalid_state(EMULTI_STEP_PROPOSAL_IN_EXECUTION)); + + if (should_pass) { + proposal.yes_votes = proposal.yes_votes + (num_votes as u128); + } else { + proposal.no_votes = proposal.no_votes + (num_votes as u128); + }; + + // Record the resolvable time to ensure that resolution has to be done non-atomically. + let timestamp_secs_bytes = to_bytes(×tamp::now_seconds()); + let key = utf8(RESOLVABLE_TIME_METADATA_KEY); + if (simple_map::contains_key(&proposal.metadata, &key)) { + *simple_map::borrow_mut(&mut proposal.metadata, &key) = timestamp_secs_bytes; + } else { + simple_map::add(&mut proposal.metadata, key, timestamp_secs_bytes); + }; + + event::emit_event( + &mut voting_forum.events.vote_events, + VoteEvent { proposal_id, num_votes }, + ); + } + + /// Common checks on if a proposal is resolvable, regardless if the proposal is single-step or multi-step. + fun is_proposal_resolvable( + voting_forum_address: address, + proposal_id: u64, + ) acquires VotingForum { + let proposal_state = get_proposal_state(voting_forum_address, proposal_id); + assert!(proposal_state == PROPOSAL_STATE_SUCCEEDED, error::invalid_state(EPROPOSAL_CANNOT_BE_RESOLVED)); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + assert!(!proposal.is_resolved, error::invalid_state(EPROPOSAL_ALREADY_RESOLVED)); + + // We need to make sure that the resolution is happening in + // a separate transaction from the last vote to guard against any potential flashloan attacks. + let resolvable_time = to_u64(*simple_map::borrow(&proposal.metadata, &utf8(RESOLVABLE_TIME_METADATA_KEY))); + assert!(timestamp::now_seconds() > resolvable_time, error::invalid_state(ERESOLUTION_CANNOT_BE_ATOMIC)); + + assert!( + transaction_context::get_script_hash() == proposal.execution_hash, + error::invalid_argument(EPROPOSAL_EXECUTION_HASH_NOT_MATCHING), + ); + } + + /// Resolve a single-step proposal with given id. Can only be done if there are at least as many votes as min required and + /// there are more yes votes than no. If either of these conditions is not met, this will revert. + /// + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + public fun resolve( + voting_forum_address: address, + proposal_id: u64, + ): ProposalType acquires VotingForum { + is_proposal_resolvable(voting_forum_address, proposal_id); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + + // Assert that the specified proposal is not a multi-step proposal. + let multi_step_key = utf8(IS_MULTI_STEP_PROPOSAL_KEY); + let has_multi_step_key = simple_map::contains_key(&proposal.metadata, &multi_step_key); + if (has_multi_step_key) { + let is_multi_step_proposal = from_bcs::to_bool(*simple_map::borrow(&proposal.metadata, &multi_step_key)); + assert!(!is_multi_step_proposal, error::permission_denied(EMULTI_STEP_PROPOSAL_CANNOT_USE_SINGLE_STEP_RESOLVE_FUNCTION)); + }; + + let resolved_early = can_be_resolved_early(proposal); + proposal.is_resolved = true; + proposal.resolution_time_secs = timestamp::now_seconds(); + + event::emit_event( + &mut voting_forum.events.resolve_proposal_events, + ResolveProposal { + proposal_id, + yes_votes: proposal.yes_votes, + no_votes: proposal.no_votes, + resolved_early, + }, + ); + + option::extract(&mut proposal.execution_content) + } + + /// Resolve a single-step or a multi-step proposal with the given id. + /// Can only be done if there are at least as many votes as min required and + /// there are more yes votes than no. If either of these conditions is not met, this will revert. + /// + /// + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + /// @param next_execution_hash The next execution hash if the given proposal is multi-step. + public fun resolve_proposal_v2( + voting_forum_address: address, + proposal_id: u64, + next_execution_hash: vector, + ) acquires VotingForum { + is_proposal_resolvable(voting_forum_address, proposal_id); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + + // Update the IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY key to indicate that the multi-step proposal is in execution. + let multi_step_in_execution_key = utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY); + if (simple_map::contains_key(&proposal.metadata, &multi_step_in_execution_key)) { + let is_multi_step_proposal_in_execution_value = simple_map::borrow_mut(&mut proposal.metadata, &multi_step_in_execution_key); + *is_multi_step_proposal_in_execution_value = to_bytes(&true); + }; + + let multi_step_key = utf8(IS_MULTI_STEP_PROPOSAL_KEY); + let is_multi_step = simple_map::contains_key(&proposal.metadata, &multi_step_key) && from_bcs::to_bool(*simple_map::borrow(&proposal.metadata, &multi_step_key)); + let next_execution_hash_is_empty = vector::length(&next_execution_hash) == 0; + + // Assert that if this proposal is single-step, the `next_execution_hash` parameter is empty. + assert!(is_multi_step || next_execution_hash_is_empty, error::invalid_argument(ESINGLE_STEP_PROPOSAL_CANNOT_HAVE_NEXT_EXECUTION_HASH)); + + // If the `next_execution_hash` parameter is empty, it means that either + // - this proposal is a single-step proposal, or + // - this proposal is multi-step and we're currently resolving the last step in the multi-step proposal. + // We can mark that this proposal is resolved. + if (next_execution_hash_is_empty) { + proposal.is_resolved = true; + proposal.resolution_time_secs = timestamp::now_seconds(); + + // Set the `IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY` value to false upon successful resolution of the last step of a multi-step proposal. + if (is_multi_step) { + let is_multi_step_proposal_in_execution_value = simple_map::borrow_mut(&mut proposal.metadata, &multi_step_in_execution_key); + *is_multi_step_proposal_in_execution_value = to_bytes(&false); + }; + } else { + // If the current step is not the last step, + // update the proposal's execution hash on-chain to the execution hash of the next step. + proposal.execution_hash = next_execution_hash; + }; + + // For single-step proposals, we emit one `ResolveProposal` event per proposal. + // For multi-step proposals, we emit one `ResolveProposal` event per step in the multi-step proposal. This means + // that we emit multiple `ResolveProposal` events for the same multi-step proposal. + let resolved_early = can_be_resolved_early(proposal); + event::emit_event( + &mut voting_forum.events.resolve_proposal_events, + ResolveProposal { + proposal_id, + yes_votes: proposal.yes_votes, + no_votes: proposal.no_votes, + resolved_early, + }, + ); + } + + #[view] + /// Return the next unassigned proposal id + public fun next_proposal_id(voting_forum_address: address,): u64 acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + voting_forum.next_proposal_id + } + + #[view] + public fun is_voting_closed(voting_forum_address: address, proposal_id: u64): bool acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + can_be_resolved_early(proposal) || is_voting_period_over(proposal) + } + + /// Return true if the proposal has reached early resolution threshold (if specified). + public fun can_be_resolved_early(proposal: &Proposal): bool { + if (option::is_some(&proposal.early_resolution_vote_threshold)) { + let early_resolution_threshold = *option::borrow(&proposal.early_resolution_vote_threshold); + if (proposal.yes_votes >= early_resolution_threshold || proposal.no_votes >= early_resolution_threshold) { + return true + }; + }; + false + } + + #[view] + /// Return the state of the proposal with given id. + /// + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + /// @return Proposal state as an enum value. + public fun get_proposal_state( + voting_forum_address: address, + proposal_id: u64, + ): u64 acquires VotingForum { + if (is_voting_closed(voting_forum_address, proposal_id)) { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + let yes_votes = proposal.yes_votes; + let no_votes = proposal.no_votes; + + if (yes_votes > no_votes && yes_votes + no_votes >= proposal.min_vote_threshold) { + PROPOSAL_STATE_SUCCEEDED + } else { + PROPOSAL_STATE_FAILED + } + } else { + PROPOSAL_STATE_PENDING + } + } + + #[view] + /// Return the proposal's creation time. + public fun get_proposal_creation_secs( + voting_forum_address: address, + proposal_id: u64, + ): u64 acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + proposal.creation_time_secs + } + + #[view] + /// Return the proposal's expiration time. + public fun get_proposal_expiration_secs( + voting_forum_address: address, + proposal_id: u64, + ): u64 acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + proposal.expiration_secs + } + + #[view] + /// Return the proposal's execution hash. + public fun get_execution_hash( + voting_forum_address: address, + proposal_id: u64, + ): vector acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + proposal.execution_hash + } + + #[view] + /// Return the proposal's minimum vote threshold + public fun get_min_vote_threshold( + voting_forum_address: address, + proposal_id: u64, + ): u128 acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + proposal.min_vote_threshold + } + + #[view] + /// Return the proposal's early resolution minimum vote threshold (optionally set) + public fun get_early_resolution_vote_threshold( + voting_forum_address: address, + proposal_id: u64, + ): Option acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + proposal.early_resolution_vote_threshold + } + + #[view] + /// Return the proposal's current vote count (yes_votes, no_votes) + public fun get_votes( + voting_forum_address: address, + proposal_id: u64, + ): (u128, u128) acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + (proposal.yes_votes, proposal.no_votes) + } + + #[view] + /// Return true if the governance proposal has already been resolved. + public fun is_resolved( + voting_forum_address: address, + proposal_id: u64, + ): bool acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + proposal.is_resolved + } + + #[view] + /// Return true if the multi-step governance proposal is in execution. + public fun is_multi_step_proposal_in_execution( + voting_forum_address: address, + proposal_id: u64, + ): bool acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + let is_multi_step_in_execution_key = utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY); + assert!(simple_map::contains_key(&proposal.metadata, &is_multi_step_in_execution_key), error::invalid_argument(EPROPOSAL_IS_SINGLE_STEP)); + from_bcs::to_bool(*simple_map::borrow(&proposal.metadata, &is_multi_step_in_execution_key)) + } + + /// Return true if the voting period of the given proposal has already ended. + fun is_voting_period_over(proposal: &Proposal): bool { + timestamp::now_seconds() > proposal.expiration_secs + } + + #[test_only] + struct TestProposal has store {} + + #[test_only] + const VOTING_DURATION_SECS: u64 = 100000; + + #[test_only] + public fun create_test_proposal_generic( + governance: &signer, + early_resolution_threshold: Option, + use_generic_create_proposal_function: bool, + ): u64 acquires VotingForum { + // Register voting forum and create a proposal. + register(governance); + let governance_address = signer::address_of(governance); + let proposal = TestProposal {}; + + // This works because our Move unit test extensions mock out the execution hash to be [1]. + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let metadata = simple_map::create>(); + + if (use_generic_create_proposal_function) { + create_proposal_v2( + governance_address, + governance_address, + proposal, + execution_hash, + 10, + timestamp::now_seconds() + VOTING_DURATION_SECS, + early_resolution_threshold, + metadata, + use_generic_create_proposal_function + ) + } else { + create_proposal( + governance_address, + governance_address, + proposal, + execution_hash, + 10, + timestamp::now_seconds() + VOTING_DURATION_SECS, + early_resolution_threshold, + metadata, + ) + } + } + + #[test_only] + public fun resolve_proposal_for_test(voting_forum_address: address, proposal_id: u64, is_multi_step: bool, finish_multi_step_execution: bool) acquires VotingForum { + if (is_multi_step) { + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + resolve_proposal_v2(voting_forum_address, proposal_id, execution_hash); + + if (finish_multi_step_execution) { + resolve_proposal_v2(voting_forum_address, proposal_id, vector::empty()); + }; + } else { + let proposal = resolve(voting_forum_address, proposal_id); + let TestProposal {} = proposal; + }; + } + + #[test_only] + public fun create_test_proposal( + governance: &signer, + early_resolution_threshold: Option, + ): u64 acquires VotingForum { + create_test_proposal_generic(governance, early_resolution_threshold, false) + } + + #[test_only] + public fun create_proposal_with_empty_execution_hash_should_fail_generic(governance: &signer, is_multi_step: bool) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + register(governance); + let proposal = TestProposal {}; + + // This should fail because execution hash is empty. + if (is_multi_step) { + create_proposal_v2( + governance_address, + governance_address, + proposal, + b"", + 10, + 100000, + option::none(), + simple_map::create>(), + is_multi_step + ); + } else { + create_proposal( + governance_address, + governance_address, + proposal, + b"", + 10, + 100000, + option::none(), + simple_map::create>(), + ); + }; + } + + #[test(governance = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public fun create_proposal_with_empty_execution_hash_should_fail(governance: &signer) acquires VotingForum { + create_proposal_with_empty_execution_hash_should_fail_generic(governance, false); + } + + #[test(governance = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public fun create_proposal_with_empty_execution_hash_should_fail_multi_step(governance: &signer) acquires VotingForum { + create_proposal_with_empty_execution_hash_should_fail_generic(governance, true); + } + + #[test_only] + public entry fun test_voting_passed_generic(aptos_framework: &signer, governance: &signer, use_create_multi_step: bool, use_resolve_multi_step: bool) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), use_create_multi_step); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + + // This if statement is specifically for the test `test_voting_passed_single_step_can_use_generic_function()`. + // It's testing when we have a single-step proposal that was created by the single-step `create_proposal()`, + // we should be able to successfully resolve it using the generic `resolve_proposal_v2` function. + if (!use_create_multi_step && use_resolve_multi_step) { + resolve_proposal_v2(governance_address, proposal_id, vector::empty()); + } else { + resolve_proposal_for_test(governance_address, proposal_id, use_resolve_multi_step, true); + }; + let voting_forum = borrow_global>(governance_address); + assert!(table::borrow(&voting_forum.proposals, proposal_id).is_resolved, 2); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, false, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_multi_step(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, true, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code=0x5000a, location = Self)] + public entry fun test_voting_passed_multi_step_cannot_use_single_step_resolve_function(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, true, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_single_step_can_use_generic_function(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, false, true); + } + + #[test_only] + public entry fun test_cannot_resolve_twice_generic(aptos_framework: &signer, governance: &signer, is_multi_step: bool) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), is_multi_step); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30003, location = Self)] + public entry fun test_cannot_resolve_twice(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_cannot_resolve_twice_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30003, location = Self)] + public entry fun test_cannot_resolve_twice_multi_step(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_cannot_resolve_twice_generic(aptos_framework, governance, true); + } + + #[test_only] + public entry fun test_voting_passed_early_generic(aptos_framework: &signer, governance: &signer, is_multi_step: bool) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::some(100), is_multi_step); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Assert that IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY has value `false` in proposal.metadata. + if (is_multi_step) { + assert!(!is_multi_step_proposal_in_execution(governance_address, 0), 1); + }; + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 100, true); + vote(&proof, governance_address, proposal_id, 10, false); + let TestProposal {} = proof; + + // Resolve early. Need to increase timestamp as resolution cannot happen in the same tx. + timestamp::fast_forward_seconds(1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 2); + + if (is_multi_step) { + // Assert that IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY still has value `false` in proposal.metadata before execution. + assert!(!is_multi_step_proposal_in_execution(governance_address, 0), 3); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, false); + + // Assert that the multi-step proposal is in execution but not resolved yet. + assert!(is_multi_step_proposal_in_execution(governance_address, 0), 4); + let voting_forum = borrow_global_mut>(governance_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + assert!(!proposal.is_resolved, 5); + }; + + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + let voting_forum = borrow_global_mut>(governance_address); + assert!(table::borrow(&voting_forum.proposals, proposal_id).is_resolved, 6); + + // Assert that the IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY value is set back to `false` upon successful resolution of this multi-step proposal. + if (is_multi_step) { + assert!(!is_multi_step_proposal_in_execution(governance_address, 0), 7); + }; + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_early(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_early_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_early_multi_step(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_early_generic(aptos_framework, governance, true); + } + + #[test_only] + public entry fun test_voting_passed_early_in_same_tx_should_fail_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::some(100), is_multi_step); + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 40, true); + vote(&proof, governance_address, proposal_id, 60, true); + let TestProposal {} = proof; + + // Resolving early should fail since timestamp hasn't changed since the last vote. + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_voting_passed_early_in_same_tx_should_fail( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_passed_early_in_same_tx_should_fail_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_voting_passed_early_in_same_tx_should_fail_multi_step( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_passed_early_in_same_tx_should_fail_generic(aptos_framework, governance, true); + } + + #[test_only] + public entry fun test_voting_failed_generic(aptos_framework: &signer, governance: &signer, is_multi_step: bool) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), is_multi_step); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + vote(&proof, governance_address, proposal_id, 100, false); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_FAILED, 1); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_failed_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed_multi_step(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_failed_generic(aptos_framework, governance, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_cannot_vote_after_voting_period_is_over( + aptos_framework: signer, + governance: signer + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(&aptos_framework); + let governance_address = signer::address_of(&governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal(&governance, option::none()); + // Voting period is over. Voting should now fail. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code=0x30009, location = Self)] + public entry fun test_cannot_vote_after_multi_step_proposal_starts_executing( + aptos_framework: signer, + governance: signer + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(&aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(&governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(&governance, option::some(100), true); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 100, true); + + // Resolve early. + timestamp::fast_forward_seconds(1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + resolve_proposal_for_test(governance_address, proposal_id, true, false); + vote(&proof, governance_address, proposal_id, 100, false); + let TestProposal {} = proof; + } + + #[test_only] + public entry fun test_voting_failed_early_generic(aptos_framework: &signer, governance: &signer, is_multi_step: bool) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::some(100), is_multi_step); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 100, true); + vote(&proof, governance_address, proposal_id, 100, false); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_FAILED, 1); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed_early(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_failed_early_generic(aptos_framework, governance, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed_early_multi_step(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_failed_early_generic(aptos_framework, governance, false); + } + + #[test_only] + public entry fun test_cannot_set_min_threshold_higher_than_early_resolution_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool, + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(signer::address_of(governance)); + // This should fail. + create_test_proposal_generic(governance, option::some(5), is_multi_step); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_cannot_set_min_threshold_higher_than_early_resolution( + aptos_framework: &signer, + governance: &signer, + ) acquires VotingForum { + test_cannot_set_min_threshold_higher_than_early_resolution_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_cannot_set_min_threshold_higher_than_early_resolution_multi_step( + aptos_framework: &signer, + governance: &signer, + ) acquires VotingForum { + test_cannot_set_min_threshold_higher_than_early_resolution_generic(aptos_framework, governance, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_replace_execution_hash(aptos_framework: &signer, governance: &signer) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), true); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + + resolve_proposal_v2(governance_address, proposal_id, vector[10u8]); + let voting_forum = borrow_global>(governance_address); + let proposal = table::borrow(&voting_forum.proposals, 0); + assert!(proposal.execution_hash == vector[10u8], 2); + assert!(!table::borrow(&voting_forum.proposals, proposal_id).is_resolved, 3); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/any.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/any.move new file mode 100644 index 0000000..d2851b7 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/any.move @@ -0,0 +1,57 @@ +module aptos_std::any { + use aptos_std::type_info; + use aptos_std::from_bcs::from_bytes; + use std::bcs::to_bytes; + use std::error; + use std::string::String; + + friend aptos_std::copyable_any; + + /// The type provided for `unpack` is not the same as was given for `pack`. + const ETYPE_MISMATCH: u64 = 1; + + /// A type which can represent a value of any type. This allows for representation of 'unknown' future + /// values. For example, to define a resource such that it can be later be extended without breaking + /// changes one can do + /// + /// ```move + /// struct Resource { + /// field: Type, + /// ... + /// extension: Option + /// } + /// ``` + struct Any has drop, store { + type_name: String, + data: vector + } + + /// Pack a value into the `Any` representation. Because Any can be stored and dropped, this is + /// also required from `T`. + public fun pack(x: T): Any { + Any { + type_name: type_info::type_name(), + data: to_bytes(&x) + } + } + + /// Unpack a value from the `Any` representation. This aborts if the value has not the expected type `T`. + public fun unpack(x: Any): T { + assert!(type_info::type_name() == x.type_name, error::invalid_argument(ETYPE_MISMATCH)); + from_bytes(x.data) + } + + /// Returns the type name of this Any + public fun type_name(x: &Any): &String { + &x.type_name + } + + #[test_only] + struct S has store, drop { x: u64 } + + #[test] + fun test_any() { + assert!(unpack(pack(22)) == 22, 1); + assert!(unpack(pack(S { x: 22 })) == S { x: 22 }, 2); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/aptos_hash.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/aptos_hash.move new file mode 100644 index 0000000..db07a05 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/aptos_hash.move @@ -0,0 +1,253 @@ +/// Cryptographic hashes: +/// - Keccak-256: see https://keccak.team/keccak.html +/// +/// In addition, SHA2-256 and SHA3-256 are available in `std::hash`. Note that SHA3-256 is a variant of Keccak: it is +/// NOT the same as Keccak-256. +/// +/// Non-cryptograhic hashes: +/// - SipHash: an add-rotate-xor (ARX) based family of pseudorandom functions created by Jean-Philippe Aumasson and Daniel J. Bernstein in 2012 +module aptos_std::aptos_hash { + use std::bcs; + use std::features; + + // + // Constants + // + + /// A newly-added native function is not yet enabled. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 1; + + // + // Functions + // + + /// Returns the (non-cryptographic) SipHash of `bytes`. See https://en.wikipedia.org/wiki/SipHash + native public fun sip_hash(bytes: vector): u64; + + /// Returns the (non-cryptographic) SipHash of the BCS serialization of `v`. See https://en.wikipedia.org/wiki/SipHash + public fun sip_hash_from_value(v: &MoveValue): u64 { + let bytes = bcs::to_bytes(v); + + sip_hash(bytes) + } + + /// Returns the Keccak-256 hash of `bytes`. + native public fun keccak256(bytes: vector): vector; + + /// Returns the SHA2-512 hash of `bytes`. + public fun sha2_512(bytes: vector): vector { + if(!features::sha_512_and_ripemd_160_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + sha2_512_internal(bytes) + } + + /// Returns the SHA3-512 hash of `bytes`. + public fun sha3_512(bytes: vector): vector { + if(!features::sha_512_and_ripemd_160_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + sha3_512_internal(bytes) + } + + + /// Returns the RIPEMD-160 hash of `bytes`. + /// + /// WARNING: Only 80-bit security is provided by this function. This means an adversary who can compute roughly 2^80 + /// hashes will, with high probability, find a collision x_1 != x_2 such that RIPEMD-160(x_1) = RIPEMD-160(x_2). + public fun ripemd160(bytes: vector): vector { + if(!features::sha_512_and_ripemd_160_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + ripemd160_internal(bytes) + } + + /// Returns the BLAKE2B-256 hash of `bytes`. + public fun blake2b_256(bytes: vector): vector { + if(!features::blake2b_256_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + blake2b_256_internal(bytes) + } + + // + // Private native functions + // + + /// Returns the SHA2-512 hash of `bytes`. + native fun sha2_512_internal(bytes: vector): vector; + + + /// Returns the SHA3-512 hash of `bytes`. + native fun sha3_512_internal(bytes: vector): vector; + + /// Returns the RIPEMD-160 hash of `bytes`. + /// + /// WARNING: Only 80-bit security is provided by this function. This means an adversary who can compute roughly 2^80 + /// hashes will, with high probability, find a collision x_1 != x_2 such that RIPEMD-160(x_1) = RIPEMD-160(x_2). + native fun ripemd160_internal(bytes: vector): vector; + + /// Returns the BLAKE2B-256 hash of `bytes`. + native fun blake2b_256_internal(bytes: vector): vector; + + // + // Testing + // + + #[test] + fun keccak256_test() { + let inputs = vector[ + b"testing", + b"", + ]; + + let outputs = vector[ + x"5f16f4c7f149ac4f9510d9cf8cf384038ad348b3bcdc01915f95de12df9d1b02", + x"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = keccak256(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + fun sha2_512_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags(&fx, vector[features::get_sha_512_and_ripemd_160_feature()], vector[]); + + let inputs = vector[ + b"testing", + b"", + ]; + + // From https://emn178.github.io/online-tools/sha512.html + let outputs = vector[ + x"521b9ccefbcd14d179e7a1bb877752870a6d620938b28a66a107eac6e6805b9d0989f45b5730508041aa5e710847d439ea74cd312c9355f1f2dae08d40e41d50", + x"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = sha2_512(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + fun sha3_512_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags(&fx, vector[features::get_sha_512_and_ripemd_160_feature()], vector[]); + let inputs = vector[ + b"testing", + b"", + ]; + + // From https://emn178.github.io/online-tools/sha3_512.html + let outputs = vector[ + x"881c7d6ba98678bcd96e253086c4048c3ea15306d0d13ff48341c6285ee71102a47b6f16e20e4d65c0c3d677be689dfda6d326695609cbadfafa1800e9eb7fc1", + x"a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = sha3_512(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + fun ripemd160_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags(&fx, vector[features::get_sha_512_and_ripemd_160_feature()], vector[]); + let inputs = vector[ + b"testing", + b"", + ]; + + // From https://www.browserling.com/tools/ripemd160-hash + let outputs = vector[ + x"b89ba156b40bed29a5965684b7d244c49a3a769b", + x"9c1185a5c5e9fc54612808977ee8f548b2258d31", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = ripemd160(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + #[expected_failure(abort_code = 196609, location = Self)] + fun blake2b_256_aborts(fx: signer) { + // We disable the feature to make sure the `blake2b_256` call aborts + features::change_feature_flags(&fx, vector[], vector[features::get_blake2b_256_feature()]); + + blake2b_256(b"This will abort"); + } + + #[test(fx = @aptos_std)] + fun blake2b_256_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags(&fx, vector[features::get_blake2b_256_feature()], vector[]); + let inputs = vector[ + b"", + b"testing", + b"testing again", // empty message doesn't yield an output on the online generator + ]; + + // From https://www.toolkitbay.com/tkb/tool/BLAKE2b_256 + // + // For computing the hash of an empty string, we use the following Python3 script: + // ``` + // #!/usr/bin/python3 + // + // import hashlib + // + // print(hashlib.blake2b(b'', digest_size=32).hexdigest()); + // ``` + let outputs = vector[ + x"0e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf12fe3a8", + x"99397ff32ae348b8b6536d5c213f343d7e9fdeaa10e8a23a9f90ab21a1658565", + x"1deab5a4eb7481453ca9b29e1f7c4be8ba44de4faeeafdf173b310cbaecfc84c", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = blake2b_256(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/big_vector.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/big_vector.move new file mode 100644 index 0000000..a7eca39 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/big_vector.move @@ -0,0 +1,469 @@ +module aptos_std::big_vector { + use std::error; + use std::vector; + use aptos_std::table_with_length::{Self, TableWithLength}; + friend aptos_std::smart_vector; + + /// Vector index is out of bounds + const EINDEX_OUT_OF_BOUNDS: u64 = 1; + /// Cannot destroy a non-empty vector + const EVECTOR_NOT_EMPTY: u64 = 2; + /// Cannot pop back from an empty vector + const EVECTOR_EMPTY: u64 = 3; + /// bucket_size cannot be 0 + const EZERO_BUCKET_SIZE: u64 = 4; + + /// A scalable vector implementation based on tables where elements are grouped into buckets. + /// Each bucket has a capacity of `bucket_size` elements. + struct BigVector has store { + buckets: TableWithLength>, + end_index: u64, + bucket_size: u64 + } + + /// Regular Vector API + + /// Create an empty vector. + public(friend) fun empty(bucket_size: u64): BigVector { + assert!(bucket_size > 0, error::invalid_argument(EZERO_BUCKET_SIZE)); + BigVector { + buckets: table_with_length::new(), + end_index: 0, + bucket_size, + } + } + + /// Create a vector of length 1 containing the passed in element. + public(friend) fun singleton(element: T, bucket_size: u64): BigVector { + let v = empty(bucket_size); + push_back(&mut v, element); + v + } + + /// Destroy the vector `v`. + /// Aborts if `v` is not empty. + public fun destroy_empty(v: BigVector) { + assert!(is_empty(&v), error::invalid_argument(EVECTOR_NOT_EMPTY)); + let BigVector { buckets, end_index: _, bucket_size: _ } = v; + table_with_length::destroy_empty(buckets); + } + + /// Destroy the vector `v` if T has `drop` + public fun destroy(v: BigVector) { + let BigVector { buckets, end_index, bucket_size: _ } = v; + let i = 0; + while (end_index > 0) { + let num_elements = vector::length(&table_with_length::remove(&mut buckets, i)); + end_index = end_index - num_elements; + i = i + 1; + }; + table_with_length::destroy_empty(buckets); + } + + /// Acquire an immutable reference to the `i`th element of the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow(v: &BigVector, i: u64): &T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + vector::borrow(table_with_length::borrow(&v.buckets, i / v.bucket_size), i % v.bucket_size) + } + + /// Return a mutable reference to the `i`th element in the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow_mut(v: &mut BigVector, i: u64): &mut T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + vector::borrow_mut(table_with_length::borrow_mut(&mut v.buckets, i / v.bucket_size), i % v.bucket_size) + } + + /// Empty and destroy the other vector, and push each of the elements in the other vector onto the lhs vector in the + /// same order as they occurred in other. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun append(lhs: &mut BigVector, other: BigVector) { + let other_len = length(&other); + let half_other_len = other_len / 2; + let i = 0; + while (i < half_other_len) { + push_back(lhs, swap_remove(&mut other, i)); + i = i + 1; + }; + while (i < other_len) { + push_back(lhs, pop_back(&mut other)); + i = i + 1; + }; + destroy_empty(other); + } + + /// Add element `val` to the end of the vector `v`. It grows the buckets when the current buckets are full. + /// This operation will cost more gas when it adds new bucket. + public fun push_back(v: &mut BigVector, val: T) { + let num_buckets = table_with_length::length(&v.buckets); + if (v.end_index == num_buckets * v.bucket_size) { + table_with_length::add(&mut v.buckets, num_buckets, vector::empty()); + vector::push_back(table_with_length::borrow_mut(&mut v.buckets, num_buckets), val); + } else { + vector::push_back(table_with_length::borrow_mut(&mut v.buckets, num_buckets - 1), val); + }; + v.end_index = v.end_index + 1; + } + + /// Pop an element from the end of vector `v`. It doesn't shrink the buckets even if they're empty. + /// Call `shrink_to_fit` explicity to deallocate empty buckets. + /// Aborts if `v` is empty. + public fun pop_back(v: &mut BigVector): T { + assert!(!is_empty(v), error::invalid_state(EVECTOR_EMPTY)); + let num_buckets = table_with_length::length(&v.buckets); + let last_bucket = table_with_length::borrow_mut(&mut v.buckets, num_buckets - 1); + let val = vector::pop_back(last_bucket); + // Shrink the table if the last vector is empty. + if (vector::is_empty(last_bucket)) { + move last_bucket; + vector::destroy_empty(table_with_length::remove(&mut v.buckets, num_buckets - 1)); + }; + v.end_index = v.end_index - 1; + val + } + + /// Remove the element at index i in the vector v and return the owned value that was previously stored at i in v. + /// All elements occurring at indices greater than i will be shifted down by 1. Will abort if i is out of bounds. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun remove(v: &mut BigVector, i: u64): T { + let len = length(v); + assert!(i < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let num_buckets = table_with_length::length(&v.buckets); + let cur_bucket_index = i / v.bucket_size + 1; + let cur_bucket = table_with_length::borrow_mut(&mut v.buckets, cur_bucket_index - 1); + let res = vector::remove(cur_bucket, i % v.bucket_size); + v.end_index = v.end_index - 1; + move cur_bucket; + while ({ + spec { + invariant cur_bucket_index <= num_buckets; + invariant table_with_length::spec_len(v.buckets) == num_buckets; + }; + (cur_bucket_index < num_buckets) + }) { + // remove one element from the start of current vector + let cur_bucket = table_with_length::borrow_mut(&mut v.buckets, cur_bucket_index); + let t = vector::remove(cur_bucket, 0); + move cur_bucket; + // and put it at the end of the last one + let prev_bucket = table_with_length::borrow_mut(&mut v.buckets, cur_bucket_index - 1); + vector::push_back(prev_bucket, t); + cur_bucket_index = cur_bucket_index + 1; + }; + spec { + assert cur_bucket_index == num_buckets; + }; + + // Shrink the table if the last vector is empty. + let last_bucket = table_with_length::borrow_mut(&mut v.buckets, num_buckets - 1); + if (vector::is_empty(last_bucket)) { + move last_bucket; + vector::destroy_empty(table_with_length::remove(&mut v.buckets, num_buckets - 1)); + }; + + res + } + + /// 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 BigVector, i: u64): T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let last_val = pop_back(v); + // if the requested value is the last one, return it + if (v.end_index == i) { + return last_val + }; + // because the lack of mem::swap, here we swap remove the requested value from the bucket + // and append the last_val to the bucket then swap the last bucket val back + let bucket = table_with_length::borrow_mut(&mut v.buckets, i / v.bucket_size); + let bucket_len = vector::length(bucket); + let val = vector::swap_remove(bucket, i % v.bucket_size); + vector::push_back(bucket, last_val); + vector::swap(bucket, i % v.bucket_size, bucket_len - 1); + val + } + + /// Swap the elements at the i'th and j'th indices in the vector v. Will abort if either of i or j are out of bounds + /// for v. + public fun swap(v: &mut BigVector, i: u64, j: u64) { + assert!(i < length(v) && j < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let i_bucket_index = i / v.bucket_size; + let j_bucket_index = j / v.bucket_size; + let i_vector_index = i % v.bucket_size; + let j_vector_index = j % v.bucket_size; + if (i_bucket_index == j_bucket_index) { + vector::swap(table_with_length::borrow_mut(&mut v.buckets, i_bucket_index), i_vector_index, j_vector_index); + return + }; + // If i and j are in different buckets, take the buckets out first for easy mutation. + let bucket_i = table_with_length::remove(&mut v.buckets, i_bucket_index); + let bucket_j = table_with_length::remove(&mut v.buckets, j_bucket_index); + // Get the elements from buckets by calling `swap_remove`. + let element_i = vector::swap_remove(&mut bucket_i, i_vector_index); + let element_j = vector::swap_remove(&mut bucket_j, j_vector_index); + // Swap the elements and push back to the other bucket. + vector::push_back(&mut bucket_i, element_j); + vector::push_back(&mut bucket_j, element_i); + let last_index_in_bucket_i = vector::length(&bucket_i) - 1; + let last_index_in_bucket_j = vector::length(&bucket_j) - 1; + // Re-position the swapped elements to the right index. + vector::swap(&mut bucket_i, i_vector_index, last_index_in_bucket_i); + vector::swap(&mut bucket_j, j_vector_index, last_index_in_bucket_j); + // Add back the buckets. + table_with_length::add(&mut v.buckets, i_bucket_index, bucket_i); + table_with_length::add(&mut v.buckets, j_bucket_index, bucket_j); + } + + /// Reverse the order of the elements in the vector v in-place. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun reverse(v: &mut BigVector) { + let new_buckets = vector[]; + let push_bucket = vector[]; + let num_buckets = table_with_length::length(&v.buckets); + let num_buckets_left = num_buckets; + + while (num_buckets_left > 0) { + let pop_bucket = table_with_length::remove(&mut v.buckets, num_buckets_left - 1); + vector::for_each_reverse(pop_bucket, |val| { + vector::push_back(&mut push_bucket, val); + if (vector::length(&push_bucket) == v.bucket_size) { + vector::push_back(&mut new_buckets, push_bucket); + push_bucket = vector[]; + }; + }); + num_buckets_left = num_buckets_left - 1; + }; + + if (vector::length(&push_bucket) > 0) { + vector::push_back(&mut new_buckets, push_bucket); + } else { + vector::destroy_empty(push_bucket); + }; + + vector::reverse(&mut new_buckets); + let i = 0; + assert!(table_with_length::length(&v.buckets) == 0, 0); + while (i < num_buckets) { + table_with_length::add(&mut v.buckets, i, vector::pop_back(&mut new_buckets)); + i = i + 1; + }; + vector::destroy_empty(new_buckets); + } + + /// Return the index of the first occurrence of an element in v that is equal to e. Returns (true, index) if such an + /// element was found, and (false, 0) otherwise. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun index_of(v: &BigVector, val: &T): (bool, u64) { + let num_buckets = table_with_length::length(&v.buckets); + let bucket_index = 0; + while (bucket_index < num_buckets) { + let cur = table_with_length::borrow(&v.buckets, bucket_index); + let (found, i) = vector::index_of(cur, val); + if (found) { + return (true, bucket_index * v.bucket_size + i) + }; + bucket_index = bucket_index + 1; + }; + (false, 0) + } + + /// Return if an element equal to e exists in the vector v. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun contains(v: &BigVector, val: &T): bool { + if (is_empty(v)) return false; + let (exist, _) = index_of(v, val); + exist + } + + /// Convert a big vector to a native vector, which is supposed to be called mostly by view functions to get an + /// atomic view of the whole vector. + /// Disclaimer: This function may be costly as the big vector may be huge in size. Use it at your own discretion. + public fun to_vector(v: &BigVector): vector { + let res = vector[]; + let num_buckets = table_with_length::length(&v.buckets); + let i = 0; + while (i < num_buckets) { + vector::append(&mut res, *table_with_length::borrow(&v.buckets, i)); + i = i + 1; + }; + res + } + + /// Return the length of the vector. + public fun length(v: &BigVector): u64 { + v.end_index + } + + /// Return `true` if the vector `v` has no elements and `false` otherwise. + public fun is_empty(v: &BigVector): bool { + length(v) == 0 + } + + #[test] + fun big_vector_test() { + let v = empty(5); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let j = 0; + while (j < 100) { + let val = borrow(&v, j); + assert!(*val == j, 0); + j = j + 1; + }; + while (i > 0) { + i = i - 1; + let (exist, index) = index_of(&v, &i); + let j = pop_back(&mut v); + assert!(exist, 0); + assert!(index == i, 0); + assert!(j == i, 0); + }; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let last_index = length(&v) - 1; + assert!(swap_remove(&mut v, last_index) == 99, 0); + assert!(swap_remove(&mut v, 0) == 0, 0); + while (length(&v) > 0) { + // the vector is always [N, 1, 2, ... N-1] with repetitive swap_remove(&mut v, 0) + let expected = length(&v); + let val = swap_remove(&mut v, 0); + assert!(val == expected, 0); + }; + destroy_empty(v); + } + + #[test] + fun big_vector_append_edge_case_test() { + let v1 = empty(5); + let v2 = singleton(1u64, 7); + let v3 = empty(6); + let v4 = empty(8); + append(&mut v3, v4); + assert!(length(&v3) == 0, 0); + append(&mut v2, v3); + assert!(length(&v2) == 1, 0); + append(&mut v1, v2); + assert!(length(&v1) == 1, 0); + destroy(v1); + } + + #[test] + fun big_vector_append_test() { + let v1 = empty(5); + let v2 = empty(7); + let i = 0; + while (i < 7) { + push_back(&mut v1, i); + i = i + 1; + }; + while (i < 25) { + push_back(&mut v2, i); + i = i + 1; + }; + append(&mut v1, v2); + assert!(length(&v1) == 25, 0); + i = 0; + while (i < 25) { + assert!(*borrow(&v1, i) == i, 0); + i = i + 1; + }; + destroy(v1); + } + + #[test] + fun big_vector_to_vector_test() { + let v1 = empty(7); + let i = 0; + while (i < 100) { + push_back(&mut v1, i); + i = i + 1; + }; + let v2 = to_vector(&v1); + let j = 0; + while (j < 100) { + assert!(*vector::borrow(&v2, j) == j, 0); + j = j + 1; + }; + destroy(v1); + } + + #[test] + fun big_vector_remove_and_reverse_test() { + let v = empty(11); + let i = 0; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + remove(&mut v, 100); + remove(&mut v, 90); + remove(&mut v, 80); + remove(&mut v, 70); + remove(&mut v, 60); + remove(&mut v, 50); + remove(&mut v, 40); + remove(&mut v, 30); + remove(&mut v, 20); + remove(&mut v, 10); + remove(&mut v, 0); + assert!(length(&v) == 90, 0); + + let index = 0; + i = 0; + while (i < 101) { + if (i % 10 != 0) { + assert!(*borrow(&v, index) == i, 0); + index = index + 1; + }; + i = i + 1; + }; + destroy(v); + } + + #[test] + fun big_vector_swap_test() { + let v = empty(11); + let i = 0; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + i = 0; + while (i < 51) { + swap(&mut v, i, 100 - i); + i = i + 1; + }; + i = 0; + while (i < 101) { + assert!(*borrow(&v, i) == 100 - i, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun big_vector_index_of_test() { + let v = empty(11); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + let (found, idx) = index_of(&mut v, &i); + assert!(found && idx == i, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun big_vector_empty_contains() { + let v = empty(10); + assert!(!contains(&v, &(1 as u64)), 0); + destroy_empty(v); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381.move new file mode 100644 index 0000000..de7d05a --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381.move @@ -0,0 +1,985 @@ +/// Contains functions for: +/// +/// The minimum-pubkey-size variant of [Boneh-Lynn-Shacham (BLS) signatures](https://en.wikipedia.org/wiki/BLS_digital_signature), +/// where public keys are BLS12-381 elliptic-curve points in $\mathbb{G}_1$ and signatures are in $\mathbb{G}_2$, +/// as per the [IETF BLS draft standard](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature#section-2.1). + +module aptos_std::bls12381 { + use std::option::{Self, Option}; + #[test_only] + use std::error::invalid_argument; + + /// The signature size, in bytes + const SIGNATURE_SIZE: u64 = 96; + + /// The public key size, in bytes + const PUBLIC_KEY_NUM_BYTES: u64 = 48; + + /// The caller was supposed to input one or more public keys. + const EZERO_PUBKEYS: u64 = 1; + + /// One of the given inputs has the wrong size.s + const EWRONG_SIZE: u64 = 2; + + /// The number of signers does not match the number of messages to be signed. + const E_NUM_SIGNERS_MUST_EQ_NUM_MESSAGES: u64 = 3; + + // TODO: Performance would increase if structs in this module are implemented natively via handles (similar to Table and + // RistrettoPoint). This will avoid unnecessary (de)serialization. We would need to allow storage of these structs too. + + #[test_only] + struct SecretKey has copy, drop { + bytes: vector, + } + + /// A *validated* public key that: + /// (1) is a point in the prime-order subgroup of the BLS12-381 elliptic curve, and + /// (2) is not the identity point + /// + /// This struct can be used to verify a normal (non-aggregated) signature. + /// + /// This struct can be combined with a ProofOfPossession struct in order to create a PublicKeyWithPop struct, which + /// can be used to verify a multisignature. + struct PublicKey has copy, drop, store { + bytes: vector + } + + /// A proof-of-possession (PoP). + /// Given such a struct and a PublicKey struct, one can construct a PublicKeyWithPoP (see below). + struct ProofOfPossession has copy, drop, store { + bytes: vector + } + + /// A *validated* public key that had a successfully-verified proof-of-possession (PoP). + /// + /// A vector of these structs can be either: + /// (1) used to verify an aggregate signature + /// (2) aggregated with other PublicKeyWithPoP structs into an AggrPublicKeysWithPoP, which in turn can be used + /// to verify a multisignature + struct PublicKeyWithPoP has copy, drop, store { + bytes: vector + } + + /// An aggregation of public keys with verified PoPs, which can be used to verify multisignatures. + struct AggrPublicKeysWithPoP has copy, drop, store { + bytes: vector + } + + /// A BLS signature. This can be either a: + /// (1) normal (non-aggregated) signature + /// (2) signature share (for a multisignature or aggregate signature) + struct Signature has copy, drop, store { + bytes: vector + } + + /// An aggregation of BLS signatures. This can be either a: + /// (4) aggregated signature (i.e., an aggregation of signatures s_i, each on a message m_i) + /// (3) multisignature (i.e., an aggregation of signatures s_i, each on the same message m) + /// + /// We distinguish between a Signature type and a AggrOrMultiSignature type to prevent developers from interchangeably + /// calling `verify_multisignature` and `verify_signature_share` to verify both multisignatures and signature shares, + /// which could create problems down the line. + struct AggrOrMultiSignature has copy, drop, store { + bytes: vector + } + + /// Creates a new public key from a sequence of bytes. + public fun public_key_from_bytes(bytes: vector): Option { + if (validate_pubkey_internal(bytes)) { + option::some(PublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Serializes a public key into 48 bytes. + public fun public_key_to_bytes(pk: &PublicKey): vector { + pk.bytes + } + + /// Creates a new proof-of-possession (PoP) which can be later used to create a PublicKeyWithPoP struct, + public fun proof_of_possession_from_bytes(bytes: vector): ProofOfPossession { + ProofOfPossession { + bytes + } + } + + /// Serializes the signature into 96 bytes. + public fun proof_of_possession_to_bytes(pop: &ProofOfPossession): vector { + pop.bytes + } + + /// Creates a PoP'd public key from a normal public key and a corresponding proof-of-possession. + public fun public_key_from_bytes_with_pop(pk_bytes: vector, pop: &ProofOfPossession): Option { + if (verify_proof_of_possession_internal(pk_bytes, pop.bytes)) { + option::some(PublicKeyWithPoP { + bytes: pk_bytes + }) + } else { + option::none() + } + } + + /// Creates a normal public key from a PoP'd public key. + public fun public_key_with_pop_to_normal(pkpop: &PublicKeyWithPoP): PublicKey { + PublicKey { + bytes: pkpop.bytes + } + } + + /// Serializes a PoP'd public key into 48 bytes. + public fun public_key_with_pop_to_bytes(pk: &PublicKeyWithPoP): vector { + pk.bytes + } + + /// Creates a new signature from a sequence of bytes. Does not check the signature for prime-order subgroup + /// membership since that is done implicitly during verification. + public fun signature_from_bytes(bytes: vector): Signature { + Signature { + bytes + } + } + + /// Serializes the signature into 96 bytes. + public fun signature_to_bytes(sig: &Signature): vector { + sig.bytes + } + + /// Checks that the group element that defines a signature is in the prime-order subgroup. + /// This check is implicitly performed when verifying any signature via this module, but we expose this functionality + /// in case it might be useful for applications to easily dismiss invalid signatures early on. + public fun signature_subgroup_check(signature: &Signature): bool { + signature_subgroup_check_internal(signature.bytes) + } + + /// Given a vector of public keys with verified PoPs, combines them into an *aggregated* public key which can be used + /// to verify multisignatures using `verify_multisignature` and aggregate signatures using `verify_aggregate_signature`. + /// Aborts if no public keys are given as input. + public fun aggregate_pubkeys(public_keys: vector): AggrPublicKeysWithPoP { + let (bytes, success) = aggregate_pubkeys_internal(public_keys); + assert!(success, std::error::invalid_argument(EZERO_PUBKEYS)); + + AggrPublicKeysWithPoP { + bytes + } + } + + /// Serializes an aggregate public key into 48 bytes. + public fun aggregate_pubkey_to_bytes(apk: &AggrPublicKeysWithPoP): vector { + apk.bytes + } + + /// Aggregates the input signatures into an aggregate-or-multi-signature structure, which can be later verified via + /// `verify_aggregate_signature` or `verify_multisignature`. Returns `None` if zero signatures are given as input + /// or if some of the signatures are not valid group elements. + public fun aggregate_signatures(signatures: vector): Option { + let (bytes, success) = aggregate_signatures_internal(signatures); + if (success) { + option::some( + AggrOrMultiSignature { + bytes + } + ) + } else { + option::none() + } + } + + /// Serializes an aggregate-or-multi-signature into 96 bytes. + public fun aggr_or_multi_signature_to_bytes(sig: &AggrOrMultiSignature): vector { + sig.bytes + } + + /// Deserializes an aggregate-or-multi-signature from 96 bytes. + public fun aggr_or_multi_signature_from_bytes(bytes: vector): AggrOrMultiSignature { + assert!(std::vector::length(&bytes) == SIGNATURE_SIZE, std::error::invalid_argument(EWRONG_SIZE)); + + AggrOrMultiSignature { + bytes + } + } + + + /// Checks that the group element that defines an aggregate-or-multi-signature is in the prime-order subgroup. + public fun aggr_or_multi_signature_subgroup_check(signature: &AggrOrMultiSignature): bool { + signature_subgroup_check_internal(signature.bytes) + } + + /// Verifies an aggregate signature, an aggregation of many signatures `s_i`, each on a different message `m_i`. + public fun verify_aggregate_signature( + aggr_sig: &AggrOrMultiSignature, + public_keys: vector, + messages: vector>, + ): bool { + verify_aggregate_signature_internal(aggr_sig.bytes, public_keys, messages) + } + + /// Verifies a multisignature: an aggregation of many signatures, each on the same message `m`. + public fun verify_multisignature( + multisig: &AggrOrMultiSignature, + aggr_public_key: &AggrPublicKeysWithPoP, + message: vector + ): bool { + verify_multisignature_internal(multisig.bytes, aggr_public_key.bytes, message) + } + + /// Verifies a normal, non-aggregated signature. + public fun verify_normal_signature( + signature: &Signature, + public_key: &PublicKey, + message: vector + ): bool { + verify_normal_signature_internal(signature.bytes, public_key.bytes, message) + } + + /// Verifies a signature share in the multisignature share or an aggregate signature share. + public fun verify_signature_share( + signature_share: &Signature, + public_key: &PublicKeyWithPoP, + message: vector + ): bool { + verify_signature_share_internal(signature_share.bytes, public_key.bytes, message) + } + + #[test_only] + /// Generates a BLS key-pair: a secret key with its corresponding public key. + public fun generate_keys(): (SecretKey, PublicKeyWithPoP) { + let (sk_bytes, pk_bytes) = generate_keys_internal(); + let sk = SecretKey { + bytes: sk_bytes + }; + let pkpop = PublicKeyWithPoP { + bytes: pk_bytes + }; + (sk, pkpop) + } + + #[test_only] + /// Generates a BLS signature for a message with a signing key. + public fun sign_arbitrary_bytes(signing_key: &SecretKey, message: vector): Signature { + Signature { + bytes: sign_internal(signing_key.bytes, message) + } + } + + #[test_only] + /// Generates a multi-signature for a message with multiple signing keys. + public fun multi_sign_arbitrary_bytes(signing_keys: &vector, message: vector): AggrOrMultiSignature { + let n = std::vector::length(signing_keys); + let sigs = vector[]; + let i: u64 = 0; + while (i < n) { + let sig = sign_arbitrary_bytes(std::vector::borrow(signing_keys, i), message); + std::vector::push_back(&mut sigs, sig); + i = i + 1; + }; + let multisig = aggregate_signatures(sigs); + option::extract(&mut multisig) + } + + #[test_only] + /// Generates an aggregated signature over all messages in messages, where signing_keys[i] signs messages[i]. + public fun aggr_sign_arbitrary_bytes(signing_keys: &vector, messages: &vector>): AggrOrMultiSignature { + let signing_key_count = std::vector::length(signing_keys); + let message_count = std::vector::length(messages); + assert!(signing_key_count == message_count, invalid_argument(E_NUM_SIGNERS_MUST_EQ_NUM_MESSAGES)); + let sigs = vector[]; + let i: u64 = 0; + while (i < signing_key_count) { + let sig = sign_arbitrary_bytes(std::vector::borrow(signing_keys, i), *std::vector::borrow(messages, i)); + std::vector::push_back(&mut sigs, sig); + i = i + 1; + }; + let aggr_sig = aggregate_signatures(sigs); + option::extract(&mut aggr_sig) + } + + #[test_only] + /// Returns a mauled copy of a byte array. + public fun maul_bytes(bytes: &vector): vector { + let new_bytes = *bytes; + let first_byte = std::vector::borrow_mut(&mut new_bytes, 0); + *first_byte = *first_byte ^ 0xff; + new_bytes + } + + #[test_only] + /// Returns a mauled copy of a normal signature. + public fun maul_signature(sig: &Signature): Signature { + Signature { + bytes: maul_bytes(&signature_to_bytes(sig)) + } + } + + #[test_only] + /// Returns a mauled copy of an aggregated signature or a multi-signature. + public fun maul_aggr_or_multi_signature(sig: &AggrOrMultiSignature): AggrOrMultiSignature { + AggrOrMultiSignature { + bytes: maul_bytes(&aggr_or_multi_signature_to_bytes(sig)) + } + } + + #[test_only] + /// Returns a mauled copy of a normal public key. + public fun maul_public_key(pk: &PublicKey): PublicKey { + PublicKey { + bytes: maul_bytes(&public_key_to_bytes(pk)) + } + } + + #[test_only] + /// Returns a mauled copy of a PoP'd public key. + public fun maul_public_key_with_pop(pk: &PublicKeyWithPoP): PublicKeyWithPoP { + PublicKeyWithPoP { + bytes: maul_bytes(&public_key_with_pop_to_bytes(pk)) + } + } + + #[test_only] + /// Returns a mauled copy of an aggregated public key. + public fun maul_aggregated_public_key(pk: &AggrPublicKeysWithPoP): AggrPublicKeysWithPoP { + AggrPublicKeysWithPoP { + bytes: maul_bytes(&aggregate_pubkey_to_bytes(pk)) + } + } + + #[test_only] + /// Returns a mauled copy of a proof-of-possession. + public fun maul_proof_of_possession(pop: &ProofOfPossession): ProofOfPossession { + ProofOfPossession { + bytes: maul_bytes(&proof_of_possession_to_bytes(pop)) + } + } + + + #[test_only] + /// Generates a proof-of-possession (PoP) for the public key associated with the secret key `sk`. + public fun generate_proof_of_possession(sk: &SecretKey): ProofOfPossession { + ProofOfPossession { + bytes: generate_proof_of_possession_internal(sk.bytes) + } + } + + // + // Native functions + // + + /// CRYPTOGRAPHY WARNING: This function assumes that the caller verified all public keys have a valid + /// proof-of-possesion (PoP) using `verify_proof_of_possession`. + /// + /// Given a vector of serialized public keys, combines them into an aggregated public key, returning `(bytes, true)`, + /// where `bytes` store the serialized public key. + /// Aborts if no public keys are given as input. + native fun aggregate_pubkeys_internal(public_keys: vector): (vector, bool); + + + /// CRYPTOGRAPHY WARNING: This function can be safely called without verifying that the input signatures are elements + /// of the prime-order subgroup of the BLS12-381 curve. + /// + /// Given a vector of serialized signatures, combines them into an aggregate signature, returning `(bytes, true)`, + /// where `bytes` store the serialized signature. + /// Does not check the input signatures nor the final aggregated signatures for prime-order subgroup membership. + /// Returns `(_, false)` if no signatures are given as input. + /// Does not abort. + native fun aggregate_signatures_internal(signatures: vector): (vector, bool); + + /// Return `true` if the bytes in `public_key` are a valid BLS12-381 public key: + /// (1) it is NOT the identity point, and + /// (2) it is a BLS12-381 elliptic curve point, and + /// (3) it is a prime-order point + /// Return `false` otherwise. + /// Does not abort. + native fun validate_pubkey_internal(public_key: vector): bool; + + /// Return `true` if the elliptic curve point serialized in `signature`: + /// (1) is NOT the identity point, and + /// (2) is a BLS12-381 elliptic curve point, and + /// (3) is a prime-order point + /// Return `false` otherwise. + /// Does not abort. + native fun signature_subgroup_check_internal(signature: vector): bool; + + /// CRYPTOGRAPHY WARNING: First, this function assumes all public keys have a valid proof-of-possesion (PoP). + /// This prevents both small-subgroup attacks and rogue-key attacks. Second, this function can be safely called + /// without verifying that the aggregate signature is in the prime-order subgroup of the BLS12-381 curve. + /// + /// Returns `true` if the aggregate signature `aggsig` on `messages` under `public_keys` verifies (where `messages[i]` + /// should be signed by `public_keys[i]`). + /// + /// Returns `false` if either: + /// - no public keys or messages are given as input, + /// - number of messages does not equal number of public keys + /// - `aggsig` (1) is the identity point, or (2) is NOT a BLS12-381 elliptic curve point, or (3) is NOT a + /// prime-order point + /// Does not abort. + native fun verify_aggregate_signature_internal( + aggsig: vector, + public_keys: vector, + messages: vector>, + ): bool; + + /// CRYPTOGRAPHY WARNING: This function assumes verified proofs-of-possesion (PoP) for the public keys used in + /// computing the aggregate public key. This prevents small-subgroup attacks and rogue-key attacks. + /// + /// Return `true` if the BLS `multisignature` on `message` verifies against the BLS aggregate public key `agg_public_key`. + /// Returns `false` otherwise. + /// Does not abort. + native fun verify_multisignature_internal( + multisignature: vector, + agg_public_key: vector, + message: vector + ): bool; + + /// CRYPTOGRAPHY WARNING: This function WILL check that the public key is a prime-order point, in order to prevent + /// library users from misusing the library by forgetting to validate public keys before giving them as arguments to + /// this function. + /// + /// Returns `true` if the `signature` on `message` verifies under `public key`. + /// Returns `false` otherwise. + /// Does not abort. + native fun verify_normal_signature_internal( + signature: vector, + public_key: vector, + message: vector + ): bool; + + /// Return `true` if the bytes in `public_key` are a valid bls12381 public key (as per `validate_pubkey`) + /// *and* this public key has a valid proof-of-possesion (PoP). + /// Return `false` otherwise. + /// Does not abort. + native fun verify_proof_of_possession_internal( + public_key: vector, + proof_of_possesion: vector + ): bool; + + /// CRYPTOGRAPHY WARNING: Assumes the public key has a valid proof-of-possesion (PoP). This prevents rogue-key + /// attacks later on during signature aggregation. + /// + /// Returns `true` if the `signature_share` on `message` verifies under `public key`. + /// Returns `false` otherwise, similar to `verify_multisignature`. + /// Does not abort. + native fun verify_signature_share_internal( + signature_share: vector, + public_key: vector, + message: vector + ): bool; + + #[test_only] + native fun generate_keys_internal(): (vector, vector); + + #[test_only] + native fun sign_internal(sk: vector, msg: vector): vector; + + #[test_only] + native fun generate_proof_of_possession_internal(sk: vector): vector; + + // + // Constants and helpers for tests + // + + /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. + /// The message signed is "Hello Aptos!" and the associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. + const RANDOM_SIGNATURE: vector = x"a01a65854f987d3434149b7f08f70730e30b241984e8712bc2aca885d632aafced4c3f661209debb6b1c8601326623cc16ca2f6c9edc53b7b88b7435fb6b05ddece418d2c34dc6aca2f5a11a79e67774582c14084a01dcb7820e4cb4bad0ea8d"; + + /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. + /// The associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. + const RANDOM_PK: vector = x"8a53e7ae5270e3e765cd8a4032c2e77c6f7e87a44ebb85bf28a4d7865565698f975346714262f9e47c6f3e0d5d951660"; + + // + // Tests + // + + #[test_only] + fun get_random_aggsig(): AggrOrMultiSignature { + assert!(signature_subgroup_check_internal(RANDOM_SIGNATURE), 1); + + AggrOrMultiSignature { bytes: RANDOM_SIGNATURE } + } + + #[test_only] + fun get_random_pk_with_pop(): PublicKeyWithPoP { + assert!(validate_pubkey_internal(RANDOM_PK), 1); + + PublicKeyWithPoP { + bytes: RANDOM_PK + } + } + + #[test] + fun test_pubkey_validation() { + // test low order points (in group for PK) + assert!(option::is_none(&public_key_from_bytes(x"ae3cd9403b69c20a0d455fd860e977fe6ee7140a7f091f26c860f2caccd3e0a7a7365798ac10df776675b3a67db8faa0")), 1); + assert!(option::is_none(&public_key_from_bytes(x"928d4862a40439a67fd76a9c7560e2ff159e770dcf688ff7b2dd165792541c88ee76c82eb77dd6e9e72c89cbf1a56a68")), 1); + assert!(option::is_some(&public_key_from_bytes(x"b3e4921277221e01ed71284be5e3045292b26c7f465a6fcdba53ee47edd39ec5160da3b229a73c75671024dcb36de091")), 1); + } + + #[test] + #[expected_failure(abort_code = 65537, location = Self)] + fun test_empty_pubkey_aggregation() { + // First, make sure if no inputs are given, the function returns None + // assert!(aggregate_pop_verified_pubkeys(vector::empty()) == option::none(), 1); + aggregate_pubkeys(std::vector::empty()); + } + + #[test] + fun test_pubkey_aggregation() { + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- sample_aggregate_pk_and_multisig --nocapture --include-ignored + let pks = vector[ + PublicKeyWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + PublicKeyWithPoP { bytes: x"ab9df801c6f96ade1c0490c938c87d5bcc2e52ccb8768e1b5d14197c5e8bfa562783b96711b702dda411a1a9f08ebbfa" }, + PublicKeyWithPoP { bytes: x"b698c932cf7097d99c17bd6e9c9dc4eeba84278c621700a8f80ec726b1daa11e3ab55fc045b4dbadefbeef05c4182494" }, + PublicKeyWithPoP { bytes: x"934706a8b876d47a996d427e1526ce52c952d5ec0858d49cd262efb785b62b1972d06270b0a7adda1addc98433ad1843" }, + PublicKeyWithPoP { bytes: x"a4cd352daad3a0651c1998dfbaa7a748e08d248a54347544bfedd51a197e016bb6008e9b8e45a744e1a030cc3b27d2da" }, + ]; + + // agg_pks[i] = \sum_{j <= i} pk[j] + let agg_pks = vector[ + AggrPublicKeysWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + AggrPublicKeysWithPoP { bytes: x"b79ad47abb441d7eda9b220a626df2e4e4910738c5f777947f0213398ecafae044ec0c20d552d1348347e9abfcf3eca1" }, + AggrPublicKeysWithPoP { bytes: x"b5f5eb6153ab5388a1a76343d714e4a2dcf224c5d0722d1e8e90c6bcead05c573fffe986460bd4000645a655bf52bc60" }, + AggrPublicKeysWithPoP { bytes: x"b922006ec14c183572a8864c31dc6632dccffa9f9c86411796f8b1b5a93a2457762c8e2f5ef0a2303506c4bca9a4e0bf" }, + AggrPublicKeysWithPoP { bytes: x"b53df1cfee2168f59e5792e710bf22928dc0553e6531dae5c7656c0a66fc12cb82fbb04863938c953dc901a5a79cc0f3" }, + ]; + + let i = 0; + let accum_pk = std::vector::empty(); + while (i < std::vector::length(&pks)) { + std::vector::push_back(&mut accum_pk, *std::vector::borrow(&pks, i)); + + let apk = aggregate_pubkeys(accum_pk); + + // Make sure PKs were aggregated correctly + assert!(apk == *std::vector::borrow(&agg_pks, i), 1); + assert!(validate_pubkey_internal(apk.bytes), 1); + + i = i + 1; + }; + } + + #[test] + fun test_pubkey_validation_against_invalid_keys() { + let (_sk, pk) = generate_keys(); + let pk_bytes = public_key_with_pop_to_bytes(&pk); + assert!(option::is_some(&public_key_from_bytes(pk_bytes)), 1); + assert!(option::is_none(&public_key_from_bytes(maul_bytes(&pk_bytes))), 1); + } + + #[test] + fun test_signature_aggregation() { + // First, test empty aggregation + assert!(option::is_none(&mut aggregate_signatures(vector[])), 1); + + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- sample_aggregate_sigs --nocapture --include-ignored + + // Signatures of each signer i + let sigs = vector[ + signature_from_bytes(x"a55ac2d64b4c1d141b15d876d3e54ad1eea07ee488e8287cce7cdf3eec551458ab5795ab196f8c112590346f7bc7c97e0053cd5be0f9bd74b93a87cd44458e98d125d6d5c6950ea5e62666beb34422ead79121f8cb0815dae41a986688d03eaf"), + signature_from_bytes(x"90a639a44491191c46379a843266c293de3a46197714ead2ad3886233dd5c2b608b6437fa32fbf9d218b20f1cbfa7970182663beb9c148e2e9412b148e16abf283ffa51b8a536c0e55d61b2e5c849edc49f636c0ef07cb99f125cbcf602e22bb"), + signature_from_bytes(x"9527d81aa15863ef3a3bf96bea6d58157d5063a93a6d0eb9d8b4f4bbda3b31142ec4586cb519da2cd7600941283d1bad061b5439703fd584295b44037a969876962ae1897dcc7cadf909d06faae213c4fef8e015dfb33ec109af02ab0c3f6833"), + signature_from_bytes(x"a54d264f5cab9654b1744232c4650c42b29adf2b19bd00bbdaf4a4d792ee4dfd40a1fe1b067f298bcfd8ae4fdc8250660a2848bd4a80d96585afccec5c6cfa617033dd7913c9acfdf98a72467e8a5155d4cad589a72d6665be7cb410aebc0068"), + signature_from_bytes(x"8d22876bdf73e6ad36ed98546018f6258cd47e45904b87c071e774a6ef4b07cac323258cb920b2fe2b07cca1f2b24bcb0a3194ec76f32edb92391ed2c39e1ada8919f8ea755c5e39873d33ff3a8f4fba21b1261c1ddb9d1688c2b40b77e355d1"), + ]; + + // multisigs[i] is a signature on "Hello, Aptoverse!" from signers 1 through i (inclusive) + let multisigs = vector[ + AggrOrMultiSignature { bytes: x"a55ac2d64b4c1d141b15d876d3e54ad1eea07ee488e8287cce7cdf3eec551458ab5795ab196f8c112590346f7bc7c97e0053cd5be0f9bd74b93a87cd44458e98d125d6d5c6950ea5e62666beb34422ead79121f8cb0815dae41a986688d03eaf" }, + AggrOrMultiSignature { bytes: x"8f1949a06b95c3cb62898d861f889350c0d2cb740da513bfa195aa0ab8fa006ea2efe004a7bbbd9bb363637a279aed20132efd0846f520e7ee0e8ed847a1c6969bb986ad2239bcc9af561b6c2aa6d3016e1c722146471f1e28313de189fe7ebc" }, + AggrOrMultiSignature { bytes: x"ab5ad42bb8f350f8a6b4ae897946a05dbe8f2b22db4f6c37eff6ff737aebd6c5d75bd1abdfc99345ac8ec38b9a449700026f98647752e1c99f69bb132340f063b8a989728e0a3d82a753740bf63e5d8f51e413ebd9a36f6acbe1407a00c4b3e7" }, + AggrOrMultiSignature { bytes: x"ae307a0d055d3ba55ad6ec7094adef27ed821bdcf735fb509ab2c20b80952732394bc67ea1fd8c26ea963540df7448f8102509f7b8c694e4d75f30a43c455f251b6b3fd8b580b9228ffeeb9039834927aacefccd3069bef4b847180d036971cf" }, + AggrOrMultiSignature { bytes: x"8284e4e3983f29cb45020c3e2d89066df2eae533a01cb6ca2c4d466b5e02dd22467f59640aa120db2b9cc49e931415c3097e3d54ff977fd9067b5bc6cfa1c885d9d8821aef20c028999a1d97e783ae049d8fa3d0bbac36ce4ca8e10e551d3461" }, + ]; + + let i = 0; + let accum_sigs = std::vector::empty(); + while (i < std::vector::length(&sigs)) { + std::vector::push_back(&mut accum_sigs, *std::vector::borrow(&sigs, i)); + + let multisig = option::extract(&mut aggregate_signatures(accum_sigs)); + + // Make sure sigs were aggregated correctly + assert!(multisig == *std::vector::borrow(&multisigs, i), 1); + assert!(signature_subgroup_check_internal(multisig.bytes), 1); + + i = i + 1; + }; + } + + #[test] + fun test_empty_signature_aggregation() { + assert!(option::is_none(&mut aggregate_signatures(vector[])), 1); + } + + #[test] + fun test_verify_multisig() { + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- sample_aggregate_pk_and_multisig --nocapture --include-ignored + let pks = vector[ + PublicKeyWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + PublicKeyWithPoP { bytes: x"ab9df801c6f96ade1c0490c938c87d5bcc2e52ccb8768e1b5d14197c5e8bfa562783b96711b702dda411a1a9f08ebbfa" }, + PublicKeyWithPoP { bytes: x"b698c932cf7097d99c17bd6e9c9dc4eeba84278c621700a8f80ec726b1daa11e3ab55fc045b4dbadefbeef05c4182494" }, + PublicKeyWithPoP { bytes: x"934706a8b876d47a996d427e1526ce52c952d5ec0858d49cd262efb785b62b1972d06270b0a7adda1addc98433ad1843" }, + PublicKeyWithPoP { bytes: x"a4cd352daad3a0651c1998dfbaa7a748e08d248a54347544bfedd51a197e016bb6008e9b8e45a744e1a030cc3b27d2da" }, + ]; + + // agg_pks[i] = \sum_{j <= i} pk[j] + let agg_pks = vector[ + AggrPublicKeysWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + AggrPublicKeysWithPoP { bytes: x"b79ad47abb441d7eda9b220a626df2e4e4910738c5f777947f0213398ecafae044ec0c20d552d1348347e9abfcf3eca1" }, + AggrPublicKeysWithPoP { bytes: x"b5f5eb6153ab5388a1a76343d714e4a2dcf224c5d0722d1e8e90c6bcead05c573fffe986460bd4000645a655bf52bc60" }, + AggrPublicKeysWithPoP { bytes: x"b922006ec14c183572a8864c31dc6632dccffa9f9c86411796f8b1b5a93a2457762c8e2f5ef0a2303506c4bca9a4e0bf" }, + AggrPublicKeysWithPoP { bytes: x"b53df1cfee2168f59e5792e710bf22928dc0553e6531dae5c7656c0a66fc12cb82fbb04863938c953dc901a5a79cc0f3" }, + ]; + + // multisigs[i] is a signature on "Hello, Aptoverse!" under agg_pks[i] + let multisigs = vector[ + AggrOrMultiSignature { bytes: x"ade45c67bff09ae57e0575feb0be870f2d351ce078e8033d847615099366da1299c69497027b77badb226ff1708543cd062597030c3f1553e0aef6c17e7af5dd0de63c1e4f1f9da68c966ea6c1dcade2cdc646bd5e8bcd4773931021ec5be3fd" }, + AggrOrMultiSignature { bytes: x"964af3d83436f6a9a382f34590c0c14e4454dc1de536af205319ce1ed417b87a2374863d5df7b7d5ed900cf91dffa7a105d3f308831d698c0d74fb2259d4813434fb86425db0ded664ae8f85d02ec1d31734910317d4155cbf69017735900d4d" }, + AggrOrMultiSignature { bytes: x"b523a31813e771e55aa0fc99a48db716ecc1085f9899ccadb64e759ecb481a2fb1cdcc0b266f036695f941361de773081729311f6a1bca9d47393f5359c8c87dc34a91f5dae335590aacbff974076ad1f910dd81750553a72ccbcad3c8cc0f07" }, + AggrOrMultiSignature { bytes: x"a945f61699df58617d37530a85e67bd1181349678b89293951ed29d1fb7588b5c12ebb7917dfc9d674f3f4fde4d062740b85a5f4927f5a4f0091e46e1ac6e41bbd650a74dd49e91445339d741e3b10bdeb9bc8bba46833e0011ff91fa5c77bd2" }, + AggrOrMultiSignature { bytes: x"b627b2cfd8ae59dcf5e58cc6c230ae369985fd096e1bc3be38da5deafcbed7d939f07cccc75383539940c56c6b6453db193f563f5b6e4fe54915afd9e1baea40a297fa7eda74abbdcd4cc5c667d6db3b9bd265782f7693798894400f2beb4637" }, + ]; + + let i = 0; + let accum_pk = std::vector::empty(); + while (i < std::vector::length(&pks)) { + std::vector::push_back(&mut accum_pk, *std::vector::borrow(&pks, i)); + + let apk = aggregate_pubkeys(accum_pk); + + assert!(apk == *std::vector::borrow(&agg_pks, i), 1); + + assert!(verify_multisignature(std::vector::borrow(&multisigs, i), &apk, b"Hello, Aptoverse!"), 1); + + i = i + 1; + }; + } + + #[test] + fun test_verify_multisignature_randomized() { + let signer_count = 1; + let max_signer_count = 5; + let msg = b"hello world"; + while (signer_count <= max_signer_count) { + // Generate key pairs. + let signing_keys = vector[]; + let public_keys = vector[]; + let i = 0; + while (i < signer_count) { + let (sk, pk) = generate_keys(); + std::vector::push_back(&mut signing_keys, sk); + std::vector::push_back(&mut public_keys, pk); + i = i + 1; + }; + + // Generate multi-signature. + let aggr_pk = aggregate_pubkeys(public_keys); + let multisig = multi_sign_arbitrary_bytes(&signing_keys, msg); + + // Test signature verification. + assert!(verify_multisignature(&multisig, &aggr_pk, msg), 1); + assert!(!verify_multisignature(&maul_aggr_or_multi_signature(&multisig), &aggr_pk, msg), 1); + assert!(!verify_multisignature(&multisig, &maul_aggregated_public_key(&aggr_pk), msg), 1); + assert!(!verify_multisignature(&multisig, &aggr_pk, maul_bytes(&msg)), 1); + + // Also test signature aggregation. + let signatures = vector[]; + let i = 0; + while (i < signer_count) { + let sk = std::vector::borrow(&signing_keys, i); + let sig = sign_arbitrary_bytes(sk, msg); + std::vector::push_back(&mut signatures, sig); + i = i + 1; + }; + let aggregated_signature = option::extract(&mut aggregate_signatures(signatures)); + assert!(aggr_or_multi_signature_subgroup_check(&aggregated_signature), 1); + assert!(aggr_or_multi_signature_to_bytes(&aggregated_signature) == aggr_or_multi_signature_to_bytes(&multisig), 1); + + signer_count = signer_count + 1; + } + } + + #[test] + fun test_verify_aggsig() { + assert!(aggr_or_multi_signature_to_bytes(&aggr_or_multi_signature_from_bytes(RANDOM_SIGNATURE)) == RANDOM_SIGNATURE, 1); + + // First, make sure verification returns None when no inputs are given or |pks| != |msgs| + assert!(verify_aggregate_signature(&get_random_aggsig(), vector[], vector[]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[ get_random_pk_with_pop() ], + vector[]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[], + vector[ x"ab" ]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[ get_random_pk_with_pop() ], + vector[ + x"cd", x"ef" + ]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[ + get_random_pk_with_pop(), + get_random_pk_with_pop(), + get_random_pk_with_pop(), + ], + vector[ + x"cd", x"ef" + ]) == false, 1); + + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- bls12381_sample_aggregate_pk_and_aggsig --nocapture --ignored + + // The signed messages are "Hello, Aptos !", where \in {1, ..., 5} + let msgs = vector[ + x"48656c6c6f2c204170746f73203121", + x"48656c6c6f2c204170746f73203221", + x"48656c6c6f2c204170746f73203321", + x"48656c6c6f2c204170746f73203421", + x"48656c6c6f2c204170746f73203521", + ]; + + // Public key of signer i + let pks = vector[ + PublicKeyWithPoP { bytes: x"b93d6aabb2b83e52f4b8bda43c24ea920bbced87a03ffc80f8f70c814a8b3f5d69fbb4e579ca76ee008d61365747dbc6" }, + PublicKeyWithPoP { bytes: x"b45648ceae3a983bcb816a96db599b5aef3b688c5753fa20ce36ac7a4f2c9ed792ab20af6604e85e42dab746398bb82c" }, + PublicKeyWithPoP { bytes: x"b3e4921277221e01ed71284be5e3045292b26c7f465a6fcdba53ee47edd39ec5160da3b229a73c75671024dcb36de091" }, + PublicKeyWithPoP { bytes: x"8463b8671c9775a7dbd98bf76d3deba90b5a90535fc87dc8c13506bb5c7bbd99be4d257e60c548140e1e30b107ff5822" }, + PublicKeyWithPoP { bytes: x"a79e3d0e9d04587a3b27d05efe5717da05fd93485dc47978c866dc70a01695c2efd247d1dd843a011a4b6b24079d7384" }, + ]; + + // aggsigs[i] = \sum_{j <= i} sigs[j], where sigs[j] is a signature on msgs[j] under pks[j] + let aggsigs = vector[ + AggrOrMultiSignature { bytes: x"a2bc8bdebe6215ba74b5b53c5ed2aa0c68221a4adf868989ccdcfb62bb0eecc6537def9ee686a7960169c5917d25e5220177ed1c5e95ecfd68c09694062e76efcb00759beac874e4f9a715fd144210883bf9bb272f156b0a1fa15d0e9460f01f" }, + AggrOrMultiSignature { bytes: x"a523aa3c3f1f1074d968ffecf017c7b93ae5243006bf0abd2e45c036ddbec99302984b650ebe5ba306cda4071d281ba50a99ef0e66c3957fab94163296f9d673fc58a36de4276f82bfb1d9180b591df93b5c2804d40dd68cf0f72cd92f86442e" }, + AggrOrMultiSignature { bytes: x"abed10f464de74769121fc09715e59a3ac96a5054a43a9d43cc890a2d4d332614c74c7fb4cceef6d25f85c65dee337330f062f89f23fec9ecf7ce3193fbba2c886630d753be6a4513a4634428904b767af2f230c5cadbcb53a451dd9c7d977f6" }, + AggrOrMultiSignature { bytes: x"8362871631ba822742a31209fa4abce6dc94b741ac4725995459da2951324b51efbbf6bc3ab4681e547ebfbadd80e0360dc078c04188198f0acea26c12645ace9107a4a23cf8db46abc7a402637f16a0477c72569fc9966fe804ef4dc0e5e758" }, + AggrOrMultiSignature { bytes: x"a44d967935fbe63a763ce2dd2b16981f967ecd31e20d3266eef5517530cdc233c8a18273b6d9fd7f61dd39178826e3f115df4e7b304f2de17373a95ea0c9a14293dcfd6f0ef416e06fa23f6a3c850d638e4d8f97ab4562ef55d49a96a50baa13" }, + ]; + + let i = 0; + let msg_subset = std::vector::empty>(); + let pk_subset = std::vector::empty(); + while (i < std::vector::length(&pks)) { + let aggsig = *std::vector::borrow(&aggsigs, i); + + std::vector::push_back(&mut pk_subset, *std::vector::borrow(&pks, i)); + std::vector::push_back(&mut msg_subset, *std::vector::borrow(&msgs, i)); + + assert!(verify_aggregate_signature(&aggsig, pk_subset, msg_subset), 1); + + i = i + 1; + }; + } + + #[test] + fun test_verify_aggregated_signature_randomized() { + let signer_count = 1; + let max_signer_count = 5; + while (signer_count <= max_signer_count) { + // Generate key pairs and messages. + let signing_keys = vector[]; + let public_keys = vector[]; + let messages: vector> = vector[]; + let i = 0; + while (i < signer_count) { + let (sk, pk) = generate_keys(); + std::vector::push_back(&mut signing_keys, sk); + std::vector::push_back(&mut public_keys, pk); + let msg: vector = vector[104, 101, 108, 108, 111, 32, 97, 112, 116, 111, 115, 32, 117, 115, 101, 114, 32, 48+(i as u8)]; //"hello aptos user {i}" + std::vector::push_back(&mut messages, msg); + i = i + 1; + }; + + // Maul messages and public keys. + let mauled_public_keys = vector[maul_public_key_with_pop(std::vector::borrow(&public_keys, 0))]; + let mauled_messages = vector[maul_bytes(std::vector::borrow(&messages, 0))]; + let i = 1; + while (i < signer_count) { + let pk = std::vector::borrow(&public_keys, i); + let msg = std::vector::borrow(&messages, i); + std::vector::push_back(&mut mauled_public_keys, *pk); + std::vector::push_back(&mut mauled_messages, *msg); + i = i + 1; + }; + + // Generate aggregated signature. + let aggrsig = aggr_sign_arbitrary_bytes(&signing_keys, &messages); + + // Test signature verification. + assert!(verify_aggregate_signature(&aggrsig, public_keys, messages), 1); + assert!(!verify_aggregate_signature(&maul_aggr_or_multi_signature(&aggrsig), public_keys, messages), 1); + assert!(!verify_aggregate_signature(&aggrsig, mauled_public_keys, messages), 1); + assert!(!verify_aggregate_signature(&aggrsig, public_keys, mauled_messages), 1); + + // Also test signature aggregation. + let signatures = vector[]; + let i = 0; + while (i < signer_count) { + let sk = std::vector::borrow(&signing_keys, i); + let msg = std::vector::borrow(&messages, i); + let sig = sign_arbitrary_bytes(sk, *msg); + std::vector::push_back(&mut signatures, sig); + i = i + 1; + }; + let aggrsig_another = option::extract(&mut aggregate_signatures(signatures)); + assert!(aggr_or_multi_signature_to_bytes(&aggrsig_another) == aggr_or_multi_signature_to_bytes(&aggrsig), 1); + + signer_count = signer_count + 1; + } + } + + #[test] + /// Tests verification of a random BLS signature created using sk = x"" + fun test_verify_normal_and_verify_sigshare() { + // Test case generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in + // `crates/aptos-crypto` + // ============================================================================================================= + // SK: 077c8a56f26259215a4a245373ab6ddf328ac6e00e5ea38d8700efa361bdc58d + + let message = b"Hello Aptos!"; + + // First, test signatures that verify + let ok = verify_normal_signature( + &signature_from_bytes(x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7"), + &option::extract(&mut public_key_from_bytes(x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858")), + message, + ); + assert!(ok == true, 1); + + let pk = option::extract(&mut public_key_from_bytes(x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858")); + let pk_with_pop = PublicKeyWithPoP { bytes: pk.bytes }; + + let ok = verify_signature_share( + &signature_from_bytes(x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7"), + &pk_with_pop, + message, + ); + assert!(ok == true, 1); + + // Second, test signatures that do NOT verify + let sigs = vector[ + Signature { bytes: x"a01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7" }, + Signature { bytes: x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7" }, + Signature { bytes: x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7" }, + ]; + let pks = vector[ + x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858", + x"ae4851bb9e7782027437ed0e2c026dd63b77a972ddf4bd9f72bcc218e327986568317e3aa9f679c697a2cb7cebf992f3", + x"82ed7bb5528303a2e306775040a7309e0bd597b70d9949d8c6198a01a7be0b00079320ebfeaf7bbd5bfe86809940d252", + ]; + let messages = vector[ + b"Hello Aptos!", + b"Hello Aptos!", + b"Bello Aptos!", + ]; + + let i = 0; + while (i < std::vector::length(&pks)) { + let sig = std::vector::borrow(&sigs, i); + let pk = *std::vector::borrow(&pks, i); + let msg = *std::vector::borrow(&messages, i); + + let pk = option::extract(&mut public_key_from_bytes(pk)); + + let notok = verify_normal_signature( + sig, + &pk, + msg, + ); + assert!(notok == false, 1); + + let notok = verify_signature_share( + sig, + &PublicKeyWithPoP { bytes: pk.bytes }, + msg, + ); + assert!(notok == false, 1); + + i = i + 1; + } + } + + #[test] + fun test_verify_normal_signature_or_signature_share_randomized() { + let (sk, pkpop) = generate_keys(); + let pk = public_key_with_pop_to_normal(&pkpop); + + let msg = b"hello world"; + let sig = sign_arbitrary_bytes(&sk, msg); + assert!(verify_normal_signature(&sig, &pk, msg), 1); + assert!(!verify_normal_signature(&maul_signature(&sig), &pk, msg), 1); + assert!(!verify_normal_signature(&sig, &maul_public_key(&pk), msg), 1); + assert!(!verify_normal_signature(&sig, &pk, maul_bytes(&msg)), 1); + + assert!(verify_signature_share(&sig, &pkpop, msg), 1); + assert!(!verify_signature_share(&maul_signature(&sig), &pkpop, msg), 1); + assert!(!verify_signature_share(&sig, &maul_public_key_with_pop(&pkpop), msg), 1); + assert!(!verify_signature_share(&sig, &pkpop, maul_bytes(&msg)), 1); + } + + #[test] + /// Tests verification of random BLS proofs-of-possession (PoPs) + fun test_verify_pop() { + // Test case generated by running `cargo test -- sample_pop --nocapture --include-ignored` in `crates/aptos-crypto` + // ============================================================================================================= + + let pks = vector[ + x"808864c91ae7a9998b3f5ee71f447840864e56d79838e4785ff5126c51480198df3d972e1e0348c6da80d396983e42d7", + x"8843843c76d167c02842a214c21277bad0bfd83da467cb5cf2d3ee67b2dcc7221b9fafa6d430400164012580e0c34d27", + x"a23b524d4308d46e43ee8cbbf57f3e1c20c47061ad9c3f915212334ea6532451dd5c01d3d3ada6bea10fe180b2c3b450", + x"a2aaa3eae1df3fc36365491afa1da5181acbb03801afd1430f04bb3b3eb18036f8b756b3508e4caee04beff50d455d1c", + x"84985b7e983dbdaddfca1f0b7dad9660bb39fff660e329acec15f69ac48c75dfa5d2df9f0dc320e4e7b7658166e0ac1c", + ]; + + let pops = vector[ + proof_of_possession_from_bytes(x"ab42afff92510034bf1232a37a0d31bc8abfc17e7ead9170d2d100f6cf6c75ccdcfedbd31699a112b4464a06fd636f3f190595863677d660b4c5d922268ace421f9e86e3a054946ee34ce29e1f88c1a10f27587cf5ec528d65ba7c0dc4863364"), + proof_of_possession_from_bytes(x"a6da5f2bc17df70ce664cff3e3a3e09d17162e47e652032b9fedc0c772fd5a533583242cba12095602e422e579c5284b1735009332dbdd23430bbcf61cc506ae37e41ff9a1fc78f0bc0d99b6bc7bf74c8f567dfb59079a035842bdc5fa3a0464"), + proof_of_possession_from_bytes(x"b8eef236595e2eab34d3c1abdab65971f5cfa1988c731ef62bd63c9a9ad3dfc9259f4f183bfffbc8375a38ba62e1c41a11173209705996ce889859bcbb3ddd7faa3c4ea3d8778f30a9ff814fdcfea1fb163d745c54dfb4dcc5a8cee092ee0070"), + proof_of_possession_from_bytes(x"a03a12fab68ad59d85c15dd1528560eff2c89250070ad0654ba260fda4334da179811d2ecdaca57693f80e9ce977d62011e3b1ee7bb4f7e0eb9b349468dd758f10fc35d54e0d0b8536ca713a77a301944392a5c192b6adf2a79ae2b38912dc98"), + proof_of_possession_from_bytes(x"8899b294f3c066e6dfb59bc0843265a1ccd6afc8f0f38a074d45ded8799c39d25ee0376cd6d6153b0d4d2ff8655e578b140254f1287b9e9df4e2aecc5b049d8556a4ab07f574df68e46348fd78e5298b7913377cf5bb3cf4796bfc755902bfdd"), + ]; + + assert!(std::vector::length(&pks) == std::vector::length(&pops), 1); + + let i = 0; + while (i < std::vector::length(&pks)) { + let opt_pk = public_key_from_bytes_with_pop(*std::vector::borrow(&pks, i), std::vector::borrow(&pops, i)); + assert!(option::is_some(&opt_pk), 1); + + i = i + 1; + }; + + // assert first PK's PoP does not verify against modifed PK' = 0xa0 | PK[1:] + let opt_pk = public_key_from_bytes_with_pop( + x"a08864c91ae7a9998b3f5ee71f447840864e56d79838e4785ff5126c51480198df3d972e1e0348c6da80d396983e42d7", + &proof_of_possession_from_bytes(x"ab42afff92510034bf1232a37a0d31bc8abfc17e7ead9170d2d100f6cf6c75ccdcfedbd31699a112b4464a06fd636f3f190595863677d660b4c5d922268ace421f9e86e3a054946ee34ce29e1f88c1a10f27587cf5ec528d65ba7c0dc4863364")); + assert!(option::is_none(&opt_pk), 1); + + // assert first PK's PoP does not verify if modifed as pop' = 0xb0 | pop[1:] + let opt_pk = public_key_from_bytes_with_pop( + x"808864c91ae7a9998b3f5ee71f447840864e56d79838e4785ff5126c51480198df3d972e1e0348c6da80d396983e42d7", + &proof_of_possession_from_bytes(x"bb42afff92510034bf1232a37a0d31bc8abfc17e7ead9170d2d100f6cf6c75ccdcfedbd31699a112b4464a06fd636f3f190595863677d660b4c5d922268ace421f9e86e3a054946ee34ce29e1f88c1a10f27587cf5ec528d65ba7c0dc4863364")); + assert!(option::is_none(&opt_pk), 1); + } + + #[test] + fun test_verify_pop_randomized() { + let (sk, pk) = generate_keys(); + let pk_bytes = public_key_with_pop_to_bytes(&pk); + let pop = generate_proof_of_possession(&sk); + assert!(option::is_some(&public_key_from_bytes_with_pop(pk_bytes, &pop)), 1); + assert!(option::is_none(&public_key_from_bytes_with_pop(pk_bytes, &maul_proof_of_possession(&pop))), 1); + assert!(option::is_none(&public_key_from_bytes_with_pop(maul_bytes(&pk_bytes), &pop)), 1); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381_algebra.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381_algebra.move new file mode 100644 index 0000000..5fb99be --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/bls12381_algebra.move @@ -0,0 +1,802 @@ +/// This module defines marker types, constants and test cases for working with BLS12-381 curves +/// using the generic API defined in `algebra.move`. +/// See https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11#name-bls-curves-for-the-128-bit- +/// for the full specification of BLS12-381 curves. +/// +/// Currently-supported BLS12-381 structures include `Fq12`, `Fr`, `G1`, `G2` and `Gt`, +/// along with their widely-used serialization formats, +/// the pairing between `G1`, `G2` and `Gt`, +/// and the hash-to-curve operations for `G1` and `G2` defined in https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16. +/// +/// Other unimplemented BLS12-381 structures and serialization formats are also listed here, +/// as they help define some of the currently supported structures. +/// Their implementation may also be added in the future. +/// +/// `Fq`: the finite field $F_q$ used in BLS12-381 curves with a prime order $q$ equal to +/// 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab. +/// +/// `FormatFqLsb`: a serialization format for `Fq` elements, +/// where an element is represented by a byte array `b[]` of size 48 with the least significant byte (LSB) coming first. +/// +/// `FormatFqMsb`: a serialization format for `Fq` elements, +/// where an element is represented by a byte array `b[]` of size 48 with the most significant byte (MSB) coming first. +/// +/// `Fq2`: the finite field $F_{q^2}$ used in BLS12-381 curves, +/// which is an extension field of `Fq`, constructed as $F_{q^2}=F_q[u]/(u^2+1)$. +/// +/// `FormatFq2LscLsb`: a serialization format for `Fq2` elements, +/// where an element in the form $(c_0+c_1\cdot u)$ is represented by a byte array `b[]` of size 96, +/// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first: +/// - `b[0..48]` is $c_0$ serialized using `FormatFqLsb`. +/// - `b[48..96]` is $c_1$ serialized using `FormatFqLsb`. +/// +/// `FormatFq2MscMsb`: a serialization format for `Fq2` elements, +/// where an element in the form $(c_0+c_1\cdot u)$ is represented by a byte array `b[]` of size 96, +/// which is a concatenation of its coefficients serialized, with the most significant coefficient (MSC) coming first: +/// - `b[0..48]` is $c_1$ serialized using `FormatFqLsb`. +/// - `b[48..96]` is $c_0$ serialized using `FormatFqLsb`. +/// +/// `Fq6`: the finite field $F_{q^6}$ used in BLS12-381 curves, +/// which is an extension field of `Fq2`, constructed as $F_{q^6}=F_{q^2}[v]/(v^3-u-1)$. +/// +/// `FormatFq6LscLsb`: a serialization scheme for `Fq6` elements, +/// where an element in the form $(c_0+c_1\cdot v+c_2\cdot v^2)$ is represented by a byte array `b[]` of size 288, +/// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first: +/// - `b[0..96]` is $c_0$ serialized using `FormatFq2LscLsb`. +/// - `b[96..192]` is $c_1$ serialized using `FormatFq2LscLsb`. +/// - `b[192..288]` is $c_2$ serialized using `FormatFq2LscLsb`. +/// +/// `G1Full`: a group constructed by the points on the BLS12-381 curve $E(F_q): y^2=x^3+4$ and the point at infinity, +/// under the elliptic curve point addition. +/// It contains the prime-order subgroup $G_1$ used in pairing. +/// +/// `G2Full`: a group constructed by the points on a curve $E'(F_{q^2}): y^2=x^3+4(u+1)$ and the point at infinity, +/// under the elliptic curve point addition. +/// It contains the prime-order subgroup $G_2$ used in pairing. +module aptos_std::bls12381_algebra { + // + // Marker types + serialization formats begin. + // + + /// The finite field $F_{q^12}$ used in BLS12-381 curves, + /// which is an extension field of `Fq6` (defined in the module documentation), constructed as $F_{q^12}=F_{q^6}[w]/(w^2-v)$. + struct Fq12 {} + + /// A serialization scheme for `Fq12` elements, + /// where an element $(c_0+c_1\cdot w)$ is represented by a byte array `b[]` of size 576, + /// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first. + /// - `b[0..288]` is $c_0$ serialized using `FormatFq6LscLsb` (defined in the module documentation). + /// - `b[288..576]` is $c_1$ serialized using `FormatFq6LscLsb`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatFq12LscLsb {} + + /// The group $G_1$ in BLS12-381-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a subgroup of `G1Full` (defined in the module documentation) with a prime order $r$ + /// equal to 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the associated scalar field). + struct G1 {} + + /// A serialization scheme for `G1` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G1` element `p` and outputs a byte array of size 96. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` and `y` into `b_x[]` and `b_y[]` respectively using `FormatFqMsb` (defined in the module documentation). + /// 1. Concatenate `b_x[]` and `b_y[]` into `b[]`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[0]: = b[0] | 0x40`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not 96, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is true, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Deserialize `[b[0] & 0x1f, b[1], ..., b[47]]` to `x` using `FormatFqMsb`. If `x` is none, return none. + /// 1. Deserialize `[b[48], ..., b[95]]` to `y` using `FormatFqMsb`. If `y` is none, return none. + /// 1. Check if `(x,y)` is on curve `E`. If not, return none. + /// 1. Check if `(x,y)` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y)`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG1Uncompr {} + + /// A serialization scheme for `G1` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G1` element `p` and outputs a byte array of size 48. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` into `b[]` using `FormatFqMsb` (defined in the module documentation). + /// 1. Set the compression bit: `b[0] := b[0] | 0x80`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[0]: = b[0] | 0x40`. + /// 1. If `y > -y`, set the lexicographical flag: `b[0] := b[0] | 0x20`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not 48, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is false, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Compute the lexicographical flag as `b[0] & 0x20 != 0`. + /// 1. Deserialize `[b[0] & 0x1f, b[1], ..., b[47]]` to `x` using `FormatFqMsb`. If `x` is none, return none. + /// 1. Solve the curve equation with `x` for `y`. If no such `y` exists, return none. + /// 1. Let `y'` be `max(y,-y)` if the lexicographical flag is set, or `min(y,-y)` otherwise. + /// 1. Check if `(x,y')` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y')`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG1Compr {} + + /// The group $G_2$ in BLS12-381-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a subgroup of `G2Full` (defined in the module documentation) with a prime order $r$ equal to + /// 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the scalar field). + struct G2 {} + + /// A serialization scheme for `G2` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G2` element `p` and outputs a byte array of size 192. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` and `y` into `b_x[]` and `b_y[]` respectively using `FormatFq2MscMsb` (defined in the module documentation). + /// 1. Concatenate `b_x[]` and `b_y[]` into `b[]`. + /// 1. If `p` is the point at infinity, set the infinity bit in `b[]`: `b[0]: = b[0] | 0x40`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G2` element or none. + /// 1. If the size of `b[]` is not 192, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is true, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Deserialize `[b[0] & 0x1f, ..., b[95]]` to `x` using `FormatFq2MscMsb`. If `x` is none, return none. + /// 1. Deserialize `[b[96], ..., b[191]]` to `y` using `FormatFq2MscMsb`. If `y` is none, return none. + /// 1. Check if `(x,y)` is on the curve `E'`. If not, return none. + /// 1. Check if `(x,y)` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y)`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG2Uncompr {} + + /// A serialization scheme for `G2` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G2` element `p` and outputs a byte array of size 96. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` into `b[]` using `FormatFq2MscMsb` (defined in the module documentation). + /// 1. Set the compression bit: `b[0] := b[0] | 0x80`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[0]: = b[0] | 0x40`. + /// 1. If `y > -y`, set the lexicographical flag: `b[0] := b[0] | 0x20`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G2` element or none. + /// 1. If the size of `b[]` is not 96, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is false, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Compute the lexicographical flag as `b[0] & 0x20 != 0`. + /// 1. Deserialize `[b[0] & 0x1f, b[1], ..., b[95]]` to `x` using `FormatFq2MscMsb`. If `x` is none, return none. + /// 1. Solve the curve equation with `x` for `y`. If no such `y` exists, return none. + /// 1. Let `y'` be `max(y,-y)` if the lexicographical flag is set, or `min(y,-y)` otherwise. + /// 1. Check if `(x,y')` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y')`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG2Compr {} + + /// The group $G_t$ in BLS12-381-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a multiplicative subgroup of `Fq12`, + /// with a prime order $r$ equal to 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the scalar field). + /// The identity of `Gt` is 1. + struct Gt {} + + /// A serialization scheme for `Gt` elements. + /// + /// To serialize, it treats a `Gt` element `p` as an `Fq12` element and serialize it using `FormatFq12LscLsb`. + /// + /// To deserialize, it uses `FormatFq12LscLsb` to try deserializing to an `Fq12` element then test the membership in `Gt`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatGt {} + + /// The finite field $F_r$ that can be used as the scalar fields + /// associated with the groups $G_1$, $G_2$, $G_t$ in BLS12-381-based pairing. + struct Fr {} + + /// A serialization format for `Fr` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the least significant byte (LSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0, blst-0.3.7. + struct FormatFrLsb {} + + /// A serialization scheme for `Fr` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the most significant byte (MSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0, blst-0.3.7. + struct FormatFrMsb {} + + // + // (Marker types + serialization formats end here.) + // Hash-to-structure suites begin. + // + + /// The hash-to-curve suite `BLS12381G1_XMD:SHA-256_SSWU_RO_` that hashes a byte array into `G1` elements. + /// + /// Full specification is defined in https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#name-bls12-381-g1. + struct HashG1XmdSha256SswuRo {} + + /// The hash-to-curve suite `BLS12381G2_XMD:SHA-256_SSWU_RO_` that hashes a byte array into `G2` elements. + /// + /// Full specification is defined in https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#name-bls12-381-g2. + struct HashG2XmdSha256SswuRo {} + + // + // (Hash-to-structure suites end here.) + // Tests begin. + // + + #[test_only] + const FQ12_VAL_0_SERIALIZED: vector = x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_1_SERIALIZED: vector = x"010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_7_SERIALIZED: vector = x"070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_7_NEG_SERIALIZED: vector = x"a4aafffffffffeb9ffff53b1feffab1e24f6b0f6a0d23067bf1285f3844b7764d7ac4b43b6a71b4b9ae67f39ea11011a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const Q12_SERIALIZED: vector = x"1175f55da544c7625f8ccb1360e2b1d3ca40747811c8f5ed04440afe232b476c0215676aec05f2a44ac2da6b6d1b7cff075e7b2a587e0aab601a8d3db4f0d29906e5e4d0d78119f396d5a59f0f8d1ca8bca62540be6ab9c12d0ca00de1f311f106278d000e55a393c9766a74e0d08a298450f60d7e666575e3354bf14b8731f4e721c0c180a5ed55c2f8f51f815baecbf96b5fc717eb58ac161a27d1d5f2bdc1a079609b9d6449165b2466b32a01eac7992a1ea0cac2f223cde1d56f9bbccc67afe44621daf858df3fc0eb837818f3e42ab3e131ce4e492efa63c108e6ef91c29ed63b3045baebcb0ab8d203c7f558beaffccba31b12aca7f54b58d0c28340e4fdb3c7c94fe9c4fef9d640ff2fcff02f1748416cbed0981fbff49f0e39eaf8a30273e67ed851944d33d6a593ef5ddcd62da84568822a6045b633bf6a513b3cfe8f9de13e76f8dcbd915980dec205eab6a5c0c72dcebd9afff1d25509ddbf33f8e24131fbd74cda93336514340cf8036b66b09ed9e6a6ac37e22fb3ac407e321beae8cd9fe74c8aaeb4edaa9a7272848fc623f6fe835a2e647379f547fc5ec6371318a85bfa60009cb20ccbb8a467492988a87633c14c0324ba0d0c3e1798ed29c8494cea35023746da05e35d184b4a301d5b2238d665495c6318b5af8653758008952d06cb9e62487b196d64383c73c06d6e1cccdf9b3ce8f95679e7050d949004a55f4ccf95b2552880ae36d1f7e09504d2338316d87d14a064511a295d768113e301bdf9d4383a8be32192d3f2f3b2de14181c73839a7cb4af5301"; + + #[test_only] + fun rand_vector(num: u64): vector> { + let elements = vector[]; + while (num > 0) { + std::vector::push_back(&mut elements, rand_insecure()); + num = num - 1; + }; + elements + } + + #[test(fx = @std)] + fun test_fq12(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(Q12_SERIALIZED == order(), 1); + + // Serialization/deserialization. + let val_0 = zero(); + let val_1 = one(); + assert!(FQ12_VAL_0_SERIALIZED == serialize(&val_0), 1); + assert!(FQ12_VAL_1_SERIALIZED == serialize(&val_1), 1); + let val_7 = from_u64(7); + let val_7_another = std::option::extract(&mut deserialize(&FQ12_VAL_7_SERIALIZED)); + assert!(eq(&val_7, &val_7_another), 1); + assert!(FQ12_VAL_7_SERIALIZED == serialize(&val_7), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Negation. + let val_minus_7 = neg(&val_7); + assert!(FQ12_VAL_7_NEG_SERIALIZED == serialize(&val_minus_7), 1); + + // Addition. + let val_9 = from_u64(9); + let val_2 = from_u64(2); + assert!(eq(&val_2, &add(&val_minus_7, &val_9)), 1); + + // Subtraction. + assert!(eq(&val_9, &sub(&val_2, &val_minus_7)), 1); + + // Multiplication. + let val_63 = from_u64(63); + assert!(eq(&val_63, &mul(&val_7, &val_9)), 1); + + // division. + let val_0 = from_u64(0); + assert!(eq(&val_7, &std::option::extract(&mut div(&val_63, &val_9))), 1); + assert!(std::option::is_none(&div(&val_63, &val_0)), 1); + + // Inversion. + assert!(eq(&val_minus_7, &neg(&val_7)), 1); + assert!(std::option::is_none(&inv(&val_0)), 1); + + // Squaring. + let val_x = rand_insecure(); + assert!(eq(&mul(&val_x, &val_x), &sqr(&val_x)), 1); + + // Downcasting. + assert!(eq(&zero(), &std::option::extract(&mut downcast(&val_1))), 1); + } + + #[test_only] + const R_SERIALIZED: vector = x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed73"; + #[test_only] + const G1_INF_SERIALIZED_COMP: vector = x"c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G1_INF_SERIALIZED_UNCOMP: vector = x"400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G1_GENERATOR_SERIALIZED_COMP: vector = x"97f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"; + #[test_only] + const G1_GENERATOR_SERIALIZED_UNCOMP: vector = x"17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP: vector = x"b928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb7"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP: vector = x"1928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb7108dadbaa4b636445639d5ae3089b3c43a8a1d47818edd1839d7383959a41c10fdc66849cfa1b08c5a11ec7e28981a1c"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP: vector = x"9928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb7"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP: vector = x"1928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb70973642f94c9b055f4e1d20812c1f91329ed2e3d71f635a72d599a679d0cda1320e597b4e1b24f735fed1381d767908f"; + + #[test(fx = @std)] + fun test_g1affine(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(R_SERIALIZED == order(), 1); + let point_at_infinity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(G1_GENERATOR_SERIALIZED_UNCOMP == serialize(&generator), 1); + assert!(G1_GENERATOR_SERIALIZED_COMP == serialize(&generator), 1); + let generator_from_comp = std::option::extract(&mut deserialize(&G1_GENERATOR_SERIALIZED_COMP + )); + let generator_from_uncomp = std::option::extract(&mut deserialize(&G1_GENERATOR_SERIALIZED_UNCOMP + )); + assert!(eq(&generator, &generator_from_comp), 1); + assert!(eq(&generator, &generator_from_uncomp), 1); + + // Deserialization should fail if given a byte array of correct size but the value is not a member. + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + assert!( + G1_INF_SERIALIZED_UNCOMP == serialize(&point_at_infinity), 1); + assert!(G1_INF_SERIALIZED_COMP == serialize(&point_at_infinity), 1); + let inf_from_uncomp = std::option::extract(&mut deserialize(&G1_INF_SERIALIZED_UNCOMP + )); + let inf_from_comp = std::option::extract(&mut deserialize(&G1_INF_SERIALIZED_COMP + )); + assert!(eq(&point_at_infinity, &inf_from_comp), 1); + assert!(eq(&point_at_infinity, &inf_from_uncomp), 1); + + let point_7g_from_uncomp = std::option::extract(&mut deserialize(&G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP + )); + let point_7g_from_comp = std::option::extract(&mut deserialize(&G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP + )); + assert!(eq(&point_7g_from_comp, &point_7g_from_uncomp), 1); + + // Deserialization should fail if given a point on the curve but off its prime-order subgroup, e.g., `(0,2)`. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002")), 1); + assert!(std::option::is_none(&deserialize(&x"800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given a valid point in (Fq,Fq) but not on the curve. + assert!(std::option::is_none(&deserialize(&x"8959e137e0719bf872abb08411010f437a8955bd42f5ba20fca64361af58ce188b1adb96ef229698bb7860b79e24ba12000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given an invalid point (x not in Fq). + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa76e9853b35f5c9b2002d9e5833fd8f9ab4cd3934a4722a06f6055bfca720c91629811e2ecae7f0cf301b6d07898a90f")), 1); + assert!(std::option::is_none(&deserialize(&x"9fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Scalar multiplication. + let scalar_7 = from_u64(7); + let point_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&point_7g_calc, &point_7g_from_comp), 1); + assert!(G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP == serialize(&point_7g_calc), 1); + assert!(G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP == serialize( &point_7g_calc), 1); + + // Multi-scalar multiplication. + let num_entries = 1; + while (num_entries < 10) { + let scalars = rand_vector(num_entries); + let elements = rand_vector(num_entries); + + let expected = zero(); + let i = 0; + while (i < num_entries) { + let element = std::vector::borrow(&elements, i); + let scalar = std::vector::borrow(&scalars, i); + expected = add(&expected, &scalar_mul(element, scalar)); + i = i + 1; + }; + + let actual = multi_scalar_mul(&elements, &scalars); + assert!(eq(&expected, &actual), 1); + + num_entries = num_entries + 1; + }; + + // Doubling. + let scalar_2 = from_u64(2); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_double_g = double(&generator); + assert!(eq(&point_2g, &point_double_g), 1); + + // Negation. + let point_minus_7g_calc = neg(&point_7g_calc); + assert!(G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP == serialize(&point_minus_7g_calc), 1); + assert!(G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP == serialize(&point_minus_7g_calc), 1); + + // Addition. + let scalar_9 = from_u64(9); + let point_9g = scalar_mul(&generator, &scalar_9); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_2g_calc = add(&point_minus_7g_calc, &point_9g); + assert!(eq(&point_2g, &point_2g_calc), 1); + + // Subtraction. + assert!(eq(&point_9g, &sub(&point_2g, &point_minus_7g_calc)), 1); + + // Hash-to-group using suite `BLS12381G1_XMD:SHA-256_SSWU_RO_`. + // Test vectors source: https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-bls12381g1_xmdsha-256_sswu_ + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G1_XMD:SHA-256_SSWU_RO_", &b""); + let expected = std::option::extract(&mut deserialize(&x"052926add2207b76ca4fa57a8734416c8dc95e24501772c814278700eed6d1e4e8cf62d9c09db0fac349612b759e79a108ba738453bfed09cb546dbb0783dbb3a5f1f566ed67bb6be0e8c67e2e81a4cc68ee29813bb7994998f3eae0c9c6a265")); + assert!(eq(&expected, &actual), 1); + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G1_XMD:SHA-256_SSWU_RO_", &b"abcdef0123456789"); + let expected = std::option::extract(&mut deserialize(&x"11e0b079dea29a68f0383ee94fed1b940995272407e3bb916bbf268c263ddd57a6a27200a784cbc248e84f357ce82d9803a87ae2caf14e8ee52e51fa2ed8eefe80f02457004ba4d486d6aa1f517c0889501dc7413753f9599b099ebcbbd2d709")); + assert!(eq(&expected, &actual), 1); + } + + #[test_only] + const G2_INF_SERIALIZED_UNCOMP: vector = x"400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G2_INF_SERIALIZED_COMP: vector = x"c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G2_GENERATOR_SERIALIZED_UNCOMP: vector = x"13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"; + #[test_only] + const G2_GENERATOR_SERIALIZED_COMP: vector = x"93e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP: vector = x"0d0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c05ecf93654b7a1885695aaeeb7caf41b0239dc45e1022be55d37111af2aecef87799638bec572de86a7437898efa702008b7ae4dbf802c17a6648842922c9467e460a71c88d393ee7af356da123a2f3619e80c3bdcc8e2b1da52f8cd9913ccdd"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP: vector = x"8d0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP: vector = x"0d0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c141418b3e4c84511f485fcc78b80b8bc623d6f3f1282e6da09f9c1860402272ba7129c72c4fcd2174f8ac87671053a8b1149639c79ffba82a4b71f73b11f186f8016a4686ab17ed0ec3d7bc6e476c6ee04c3f3c2d48b1d4ddfac073266ebddce"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP: vector = x"ad0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c"; + + #[test(fx = @std)] + fun test_g2affine(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Special constants. + assert!(R_SERIALIZED == order(), 1); + let point_at_infinity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(G2_GENERATOR_SERIALIZED_COMP == serialize(&generator), 1); + assert!(G2_GENERATOR_SERIALIZED_UNCOMP == serialize(&generator), 1); + let generator_from_uncomp = std::option::extract(&mut deserialize(&G2_GENERATOR_SERIALIZED_UNCOMP + )); + let generator_from_comp = std::option::extract(&mut deserialize(&G2_GENERATOR_SERIALIZED_COMP + )); + assert!(eq(&generator, &generator_from_comp), 1); + assert!(eq(&generator, &generator_from_uncomp), 1); + assert!(G2_INF_SERIALIZED_UNCOMP == serialize(&point_at_infinity), 1); + assert!(G2_INF_SERIALIZED_COMP == serialize(&point_at_infinity), 1); + let inf_from_uncomp = std::option::extract(&mut deserialize(&G2_INF_SERIALIZED_UNCOMP)); + let inf_from_comp = std::option::extract(&mut deserialize(&G2_INF_SERIALIZED_COMP)); + assert!(eq(&point_at_infinity, &inf_from_comp), 1); + assert!(eq(&point_at_infinity, &inf_from_uncomp), 1); + let point_7g_from_uncomp = std::option::extract(&mut deserialize(&G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP + )); + let point_7g_from_comp = std::option::extract(&mut deserialize(&G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP + )); + assert!(eq(&point_7g_from_comp, &point_7g_from_uncomp), 1); + + // Deserialization should fail if given a point on the curve but not in the prime-order subgroup. + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890ddd862a6308796bf47e2265073c1f7d81afd69f9497fc1403e2e97a866129b43b672295229c21116d4a99f3e5c2ae720a31f181dbed8a93e15f909c20cf69d11a8879adbbe6890740def19814e6d4ed23fb0dcbd79291655caf48b466ac9cae04")), 1); + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890d")), 1); + + // Deserialization should fail if given a valid point in (Fq2,Fq2) but not on the curve. + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given an invalid point (x not in Fq2). + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdd862a6308796bf47e2265073c1f7d81afd69f9497fc1403e2e97a866129b43b672295229c21116d4a99f3e5c2ae720a31f181dbed8a93e15f909c20cf69d11a8879adbbe6890740def19814e6d4ed23fb0dcbd79291655caf48b466ac9cae04")), 1); + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Scalar multiplication. + let scalar_7 = from_u64(7); + let point_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&point_7g_calc, &point_7g_from_comp), 1); + assert!(G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP == serialize(&point_7g_calc), 1); + assert!(G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP == serialize(&point_7g_calc), 1); + + // Multi-scalar multiplication. + let num_entries = 1; + while (num_entries < 10) { + let scalars = rand_vector(num_entries); + let elements = rand_vector(num_entries); + + let expected = zero(); + let i = 0; + while (i < num_entries) { + let element = std::vector::borrow(&elements, i); + let scalar = std::vector::borrow(&scalars, i); + expected = add(&expected, &scalar_mul(element, scalar)); + i = i + 1; + }; + + let actual = multi_scalar_mul(&elements, &scalars); + assert!(eq(&expected, &actual), 1); + + num_entries = num_entries + 1; + }; + + // Doubling. + let scalar_2 = from_u64(2); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_double_g = double(&generator); + assert!(eq(&point_2g, &point_double_g), 1); + + // Negation. + let point_minus_7g_calc = neg(&point_7g_calc); + assert!(G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP == serialize(&point_minus_7g_calc), 1); + assert!(G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP == serialize(&point_minus_7g_calc), 1); + + // Addition. + let scalar_9 = from_u64(9); + let point_9g = scalar_mul(&generator, &scalar_9); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_2g_calc = add(&point_minus_7g_calc, &point_9g); + assert!(eq(&point_2g, &point_2g_calc), 1); + + // Subtraction. + assert!(eq(&point_9g, &sub(&point_2g, &point_minus_7g_calc)), 1); + + // Hash-to-group using suite `BLS12381G2_XMD:SHA-256_SSWU_RO_`. + // Test vectors source: https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-bls12381g2_xmdsha-256_sswu_ + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G2_XMD:SHA-256_SSWU_RO_", &b""); + let expected = std::option::extract(&mut deserialize(&x"05cb8437535e20ecffaef7752baddf98034139c38452458baeefab379ba13dff5bf5dd71b72418717047f5b0f37da03d0141ebfbdca40eb85b87142e130ab689c673cf60f1a3e98d69335266f30d9b8d4ac44c1038e9dcdd5393faf5c41fb78a12424ac32561493f3fe3c260708a12b7c620e7be00099a974e259ddc7d1f6395c3c811cdd19f1e8dbf3e9ecfdcbab8d60503921d7f6a12805e72940b963c0cf3471c7b2a524950ca195d11062ee75ec076daf2d4bc358c4b190c0c98064fdd92")); + assert!(eq(&expected, &actual), 1); + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G2_XMD:SHA-256_SSWU_RO_", &b"abcdef0123456789"); + let expected = std::option::extract(&mut deserialize(&x"190d119345b94fbd15497bcba94ecf7db2cbfd1e1fe7da034d26cbba169fb3968288b3fafb265f9ebd380512a71c3f2c121982811d2491fde9ba7ed31ef9ca474f0e1501297f68c298e9f4c0028add35aea8bb83d53c08cfc007c1e005723cd00bb5e7572275c567462d91807de765611490205a941a5a6af3b1691bfe596c31225d3aabdf15faff860cb4ef17c7c3be05571a0f8d3c08d094576981f4a3b8eda0a8e771fcdcc8ecceaf1356a6acf17574518acb506e435b639353c2e14827c8")); + assert!(eq(&expected, &actual), 1); + } + + #[test_only] + const FQ12_ONE_SERIALIZED: vector = x"010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const GT_GENERATOR_SERIALIZED: vector = x"b68917caaa0543a808c53908f694d1b6e7b38de90ce9d83d505ca1ef1b442d2727d7d06831d8b2a7920afc71d8eb50120f17a0ea982a88591d9f43503e94a8f1abaf2e4589f65aafb7923c484540a868883432a5c60e75860b11e5465b1c9a08873ec29e844c1c888cb396933057ffdd541b03a5220eda16b2b3a6728ea678034ce39c6839f20397202d7c5c44bb68134f93193cec215031b17399577a1de5ff1f5b0666bdd8907c61a7651e4e79e0372951505a07fa73c25788db6eb8023519a5aa97b51f1cad1d43d8aabbff4dc319c79a58cafc035218747c2f75daf8f2fb7c00c44da85b129113173d4722f5b201b6b4454062e9ea8ba78c5ca3cadaf7238b47bace5ce561804ae16b8f4b63da4645b8457a93793cbd64a7254f150781019de87ee42682940f3e70a88683d512bb2c3fb7b2434da5dedbb2d0b3fb8487c84da0d5c315bdd69c46fb05d23763f2191aabd5d5c2e12a10b8f002ff681bfd1b2ee0bf619d80d2a795eb22f2aa7b85d5ffb671a70c94809f0dafc5b73ea2fb0657bae23373b4931bc9fa321e8848ef78894e987bff150d7d671aee30b3931ac8c50e0b3b0868effc38bf48cd24b4b811a2995ac2a09122bed9fd9fa0c510a87b10290836ad06c8203397b56a78e9a0c61c77e56ccb4f1bc3d3fcaea7550f3503efe30f2d24f00891cb45620605fcfaa4292687b3a7db7c1c0554a93579e889a121fd8f72649b2402996a084d2381c5043166673b3849e4fd1e7ee4af24aa8ed443f56dfd6b68ffde4435a92cd7a4ac3bc77e1ad0cb728606cf08bf6386e5410f"; + #[test_only] + const GT_GENERATOR_MUL_BY_7_SERIALIZED: vector = x"2041ea7b66c19680e2c0bb23245a71918753220b31f88a925aa9b1e192e7c188a0b365cb994b3ec5e809206117c6411242b940b10caa37ce734496b3b7c63578a0e3c076f9b31a7ca13a716262e0e4cda4ac994efb9e19893cbfe4d464b9210d099d808a08b3c4c3846e7529984899478639c4e6c46152ef49a04af9c8e6ff442d286c4613a3dac6a4bee4b40e1f6b030f2871dabe4223b250c3181ecd3bc6819004745aeb6bac567407f2b9c7d1978c45ee6712ae46930bc00638383f6696158bad488cbe7663d681c96c035481dbcf78e7a7fbaec3799163aa6914cef3365156bdc3e533a7c883d5974e3462ac6f19e3f9ce26800ae248a45c5f0dd3a48a185969224e6cd6af9a048241bdcac9800d94aeee970e08488fb961e36a769b6c185d185b4605dc9808517196bba9d00a3e37bca466c19187486db104ee03962d39fe473e276355618e44c965f05082bb027a7baa4bcc6d8c0775c1e8a481e77df36ddad91e75a982302937f543a11fe71922dcd4f46fe8f951f91cde412b359507f2b3b6df0374bfe55c9a126ad31ce254e67d64194d32d7955ec791c9555ea5a917fc47aba319e909de82da946eb36e12aff936708402228295db2712f2fc807c95092a86afd71220699df13e2d2fdf2857976cb1e605f72f1b2edabadba3ff05501221fe81333c13917c85d725ce92791e115eb0289a5d0b3330901bb8b0ed146abeb81381b7331f1c508fb14e057b05d8b0190a9e74a3d046dcd24e7ab747049945b3d8a120c4f6d88e67661b55573aa9b361367488a1ef7dffd967d64a1518"; + #[test_only] + const GT_GENERATOR_MUL_BY_7_NEG_SERIALIZED: vector = x"2041ea7b66c19680e2c0bb23245a71918753220b31f88a925aa9b1e192e7c188a0b365cb994b3ec5e809206117c6411242b940b10caa37ce734496b3b7c63578a0e3c076f9b31a7ca13a716262e0e4cda4ac994efb9e19893cbfe4d464b9210d099d808a08b3c4c3846e7529984899478639c4e6c46152ef49a04af9c8e6ff442d286c4613a3dac6a4bee4b40e1f6b030f2871dabe4223b250c3181ecd3bc6819004745aeb6bac567407f2b9c7d1978c45ee6712ae46930bc00638383f6696158bad488cbe7663d681c96c035481dbcf78e7a7fbaec3799163aa6914cef3365156bdc3e533a7c883d5974e3462ac6f19e3f9ce26800ae248a45c5f0dd3a48a185969224e6cd6af9a048241bdcac9800d94aeee970e08488fb961e36a769b6c184e92a4b9fa2366b1ae8ebdf5542fa1e0ec390c90df40a91e5261800581b5492bd9640d1c5352babc551d1a49998f4517312f55b4339272b28a3e6b0c7d182e2bb61bd7d72b29ae3696db8fafe32b904ab5d0764e46bf21f9a0c9a1f7bedc6b12b9f64820fc8b3fd4a26541472be3c9c93d784cdd53a059d1604bf3292fedd1babfb00398128e3241bc63a5a47b5e9207fcb0c88f7bfddc376a242c9f0c032ba28eec8670f1fa1d47567593b4571c983b8015df91cfa1241b7fb8a57e0e6e01145b98de017eccc2a66e83ced9d83119a505e552467838d35b8ce2f4d7cc9a894f6dee922f35f0e72b7e96f0879b0c8614d3f9e5f5618b5be9b82381628448641a8bb0fd1dffb16c70e6831d8d69f61f2a2ef9e90c421f7a5b1ce7a5d113c7eb01"; + + #[test(fx = @std)] + fun test_gt(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Special constants. + assert!(R_SERIALIZED == order(), 1); + let identity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(GT_GENERATOR_SERIALIZED == serialize(&generator), 1); + let generator_from_deser = std::option::extract(&mut deserialize(>_GENERATOR_SERIALIZED)); + assert!(eq(&generator, &generator_from_deser), 1); + assert!(FQ12_ONE_SERIALIZED == serialize(&identity), 1); + let identity_from_deser = std::option::extract(&mut deserialize(&FQ12_ONE_SERIALIZED)); + assert!(eq(&identity, &identity_from_deser), 1); + let element_7g_from_deser = std::option::extract(&mut deserialize(>_GENERATOR_MUL_BY_7_SERIALIZED + )); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Deserialization should fail if given an element in Fq12 but not in the prime-order subgroup. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Element scalar multiplication. + let scalar_7 = from_u64(7); + let element_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&element_7g_calc, &element_7g_from_deser), 1); + assert!(GT_GENERATOR_MUL_BY_7_SERIALIZED == serialize(&element_7g_calc), 1); + + // Element negation. + let element_minus_7g_calc = neg(&element_7g_calc); + assert!(GT_GENERATOR_MUL_BY_7_NEG_SERIALIZED == serialize(&element_minus_7g_calc), 1); + + // Element addition. + let scalar_9 = from_u64(9); + let element_9g = scalar_mul(&generator, &scalar_9); + let scalar_2 = from_u64(2); + let element_2g = scalar_mul(&generator, &scalar_2); + let element_2g_calc = add(&element_minus_7g_calc, &element_9g); + assert!(eq(&element_2g, &element_2g_calc), 1); + + // Subtraction. + assert!(eq(&element_9g, &sub(&element_2g, &element_minus_7g_calc)), 1); + + // Upcasting to Fq12. + assert!(eq(&one(), &upcast(&identity)), 1); + } + + #[test_only] + use aptos_std::crypto_algebra::{zero, one, from_u64, eq, deserialize, serialize, neg, add, sub, mul, div, inv, rand_insecure, sqr, order, scalar_mul, multi_scalar_mul, double, hash_to, upcast, enable_cryptography_algebra_natives, pairing, multi_pairing, downcast, Element}; + + #[test_only] + const FR_VAL_0_SERIALIZED_LSB: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_1_SERIALIZED_LSB: vector = x"0100000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_7_SERIALIZED_LSB: vector = x"0700000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_7_SERIALIZED_MSB: vector = x"0000000000000000000000000000000000000000000000000000000000000007"; + #[test_only] + const FR_VAL_7_NEG_SERIALIZED_LSB: vector = x"fafffffffefffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed73"; + + #[test(fx = @std)] + fun test_fr(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(R_SERIALIZED == order(), 1); + + // Serialization/deserialization. + let val_0 = zero(); + let val_1 = one(); + assert!(FR_VAL_0_SERIALIZED_LSB == serialize(&val_0), 1); + assert!(FR_VAL_1_SERIALIZED_LSB == serialize(&val_1), 1); + let val_7 = from_u64(7); + let val_7_2nd = std::option::extract(&mut deserialize(&FR_VAL_7_SERIALIZED_LSB)); + let val_7_3rd = std::option::extract(&mut deserialize(&FR_VAL_7_SERIALIZED_MSB)); + assert!(eq(&val_7, &val_7_2nd), 1); + assert!(eq(&val_7, &val_7_3rd), 1); + assert!(FR_VAL_7_SERIALIZED_LSB == serialize(&val_7), 1); + assert!(FR_VAL_7_SERIALIZED_MSB == serialize(&val_7), 1); + + // Deserialization should fail if given a byte array of right size but the value is not a member. + assert!(std::option::is_none(&deserialize(&x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed73")), 1); + assert!(std::option::is_none(&deserialize(&x"73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed7300")), 1); + assert!(std::option::is_none(&deserialize(&x"0073eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Negation. + let val_minus_7 = neg(&val_7); + assert!(FR_VAL_7_NEG_SERIALIZED_LSB == serialize(&val_minus_7), 1); + + // Addition. + let val_9 = from_u64(9); + let val_2 = from_u64(2); + assert!(eq(&val_2, &add(&val_minus_7, &val_9)), 1); + + // Subtraction. + assert!(eq(&val_9, &sub(&val_2, &val_minus_7)), 1); + + // Multiplication. + let val_63 = from_u64(63); + assert!(eq(&val_63, &mul(&val_7, &val_9)), 1); + + // division. + let val_0 = from_u64(0); + assert!(eq(&val_7, &std::option::extract(&mut div(&val_63, &val_9))), 1); + assert!(std::option::is_none(&div(&val_63, &val_0)), 1); + + // Inversion. + assert!(eq(&val_minus_7, &neg(&val_7)), 1); + assert!(std::option::is_none(&inv(&val_0)), 1); + + // Squaring. + let val_x = rand_insecure(); + assert!(eq(&mul(&val_x, &val_x), &sqr(&val_x)), 1); + } + + #[test(fx = @std)] + fun test_pairing(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // pairing(a*P,b*Q) == (a*b)*pairing(P,Q) + let element_p = rand_insecure(); + let element_q = rand_insecure(); + let a = rand_insecure(); + let b = rand_insecure(); + let gt_element = pairing(&scalar_mul(&element_p, &a), &scalar_mul(&element_q, &b)); + let gt_element_another = scalar_mul(&pairing(&element_p, &element_q), &mul(&a, &b)); + assert!(eq(>_element, >_element_another), 1); + } + + #[test(fx = @std)] + fun test_multi_pairing(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Will compute e(a0*P0,b0*Q0)+e(a1*P1,b1*Q1)+e(a2*P2,b2*Q2). + let a0 = rand_insecure(); + let a1 = rand_insecure(); + let a2 = rand_insecure(); + let element_p0 = rand_insecure(); + let element_p1 = rand_insecure(); + let element_p2 = rand_insecure(); + let p0_a0 = scalar_mul(&element_p0, &a0); + let p1_a1 = scalar_mul(&element_p1, &a1); + let p2_a2 = scalar_mul(&element_p2, &a2); + let b0 = rand_insecure(); + let b1 = rand_insecure(); + let b2 = rand_insecure(); + let element_q0 = rand_insecure(); + let element_q1 = rand_insecure(); + let element_q2 = rand_insecure(); + let q0_b0 = scalar_mul(&element_q0, &b0); + let q1_b1 = scalar_mul(&element_q1, &b1); + let q2_b2 = scalar_mul(&element_q2, &b2); + + // Naive method. + let n0 = pairing(&p0_a0, &q0_b0); + let n1 = pairing(&p1_a1, &q1_b1); + let n2 = pairing(&p2_a2, &q2_b2); + let n = zero(); + n = add(&n, &n0); + n = add(&n, &n1); + n = add(&n, &n2); + + // Efficient API. + let m = multi_pairing(&vector[p0_a0, p1_a1, p2_a2], &vector[q0_b0, q1_b1, q2_b2]); + assert!(eq(&n, &m), 1); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010002, location = aptos_std::crypto_algebra)] + fun test_multi_pairing_should_abort_when_sizes_mismatch(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let g1_elements = vector[rand_insecure()]; + let g2_elements = vector[rand_insecure(), rand_insecure()]; + multi_pairing(&g1_elements, &g2_elements); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010002, location = aptos_std::crypto_algebra)] + fun test_multi_scalar_mul_should_abort_when_sizes_mismatch(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let elements = vector[rand_insecure()]; + let scalars = vector[rand_insecure(), rand_insecure()]; + multi_scalar_mul(&elements, &scalars); + } + + #[test_only] + /// The maximum number of `G1` elements that can be created in a transaction, + /// calculated by the current memory limit (1MB) and the in-mem G1 representation size (144 bytes per element). + const G1_NUM_MAX: u64 = 1048576 / 144; + + #[test(fx = @std)] + fun test_memory_limit(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let remaining = G1_NUM_MAX; + while (remaining > 0) { + zero(); + remaining = remaining - 1; + } + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x090003, location = std::crypto_algebra)] + fun test_memory_limit_exceeded_with_g1(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let remaining = G1_NUM_MAX + 1; + while (remaining > 0) { + zero(); + remaining = remaining - 1; + } + } + + // + // (Tests end here.) + // +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/capability.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/capability.move new file mode 100644 index 0000000..b61c18c --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/capability.move @@ -0,0 +1,193 @@ +/// A module which defines the basic concept of +/// [*capabilities*](https://en.wikipedia.org/wiki/Capability-based_security) for managing access control. +/// +/// EXPERIMENTAL +/// +/// # Overview +/// +/// A capability is a unforgeable token which testifies that a signer has authorized a certain operation. +/// The token is valid during the transaction where it is obtained. Since the type `capability::Cap` has +/// no ability to be stored in global memory, capabilities cannot leak out of a transaction. For every function +/// called within a transaction which has a capability as a parameter, it is guaranteed that the capability +/// has been obtained via a proper signer-based authorization step previously in the transaction's execution. +/// +/// ## Usage +/// +/// Initializing and acquiring capabilities is usually encapsulated in a module with a type +/// tag which can only be constructed by this module. +/// +/// ``` +/// module Pkg::Feature { +/// use std::capability::Cap; +/// +/// /// A type tag used in Cap. Only this module can create an instance, +/// /// and there is no public function other than Self::acquire which returns a value of this type. +/// /// This way, this module has full control how Cap is given out. +/// struct Feature has drop {} +/// +/// /// Initializes this module. +/// public fun initialize(s: &signer) { +/// // Create capability. This happens once at module initialization time. +/// // One needs to provide a witness for being the owner of Feature +/// // in the 2nd parameter. +/// <> +/// capability::create(s, &Feature{}); +/// } +/// +/// /// Acquires the capability to work with this feature. +/// public fun acquire(s: &signer): Cap { +/// <> +/// capability::acquire(s, &Feature{}); +/// } +/// +/// /// Does something related to the feature. The caller must pass a Cap. +/// public fun do_something(_cap: Cap) { ... } +/// } +/// ``` +/// +/// ## Delegation +/// +/// Capabilities come with the optional feature of *delegation*. Via `Self::delegate`, an owner of a capability +/// can designate another signer to be also capable of acquiring the capability. Like the original creator, +/// the delegate needs to present his signer to obtain the capability in his transactions. Delegation can +/// be revoked via `Self::revoke`, removing this access right from the delegate. +/// +/// While the basic authorization mechanism for delegates is the same as with core capabilities, the +/// target of delegation might be subject of restrictions which need to be specified and verified. This can +/// be done via global invariants in the specification language. For example, in order to prevent delegation +/// all together for a capability, one can use the following invariant: +/// +/// ``` +/// invariant forall a: address where capability::spec_has_cap(a): +/// len(capability::spec_delegates(a)) == 0; +/// ``` +/// +/// Similarly, the following invariant would enforce that delegates, if existent, must satisfy a certain +/// predicate: +/// +/// ``` +/// invariant forall a: address where capability::spec_has_cap(a): +/// forall d in capability::spec_delegates(a): +/// is_valid_delegate_for_feature(d); +/// ``` +/// +module aptos_std::capability { + use std::error; + use std::signer; + use std::vector; + + /// Capability resource already exists on the specified account + const ECAPABILITY_ALREADY_EXISTS: u64 = 1; + /// Capability resource not found + const ECAPABILITY_NOT_FOUND: u64 = 2; + /// Account does not have delegated permissions + const EDELEGATE: u64 = 3; + + /// The token representing an acquired capability. Cannot be stored in memory, but copied and dropped freely. + struct Cap has copy, drop { + root: address + } + + /// A linear version of a capability token. This can be used if an acquired capability should be enforced + /// to be used only once for an authorization. + struct LinearCap has drop { + root: address + } + + /// An internal data structure for representing a configured capability. + struct CapState has key { + delegates: vector
+ } + + /// An internal data structure for representing a configured delegated capability. + struct CapDelegateState has key { + root: address + } + + /// Creates a new capability class, owned by the passed signer. A caller must pass a witness that + /// they own the `Feature` type parameter. + public fun create(owner: &signer, _feature_witness: &Feature) { + let addr = signer::address_of(owner); + assert!(!exists>(addr), error::already_exists(ECAPABILITY_ALREADY_EXISTS)); + move_to>(owner, CapState { delegates: vector::empty() }); + } + + /// Acquires a capability token. Only the owner of the capability class, or an authorized delegate, + /// can succeed with this operation. A caller must pass a witness that they own the `Feature` type + /// parameter. + public fun acquire(requester: &signer, _feature_witness: &Feature): Cap + acquires CapState, CapDelegateState { + Cap { root: validate_acquire(requester) } + } + + /// Acquires a linear capability token. It is up to the module which owns `Feature` to decide + /// whether to expose a linear or non-linear capability. + public fun acquire_linear(requester: &signer, _feature_witness: &Feature): LinearCap + acquires CapState, CapDelegateState { + LinearCap { root: validate_acquire(requester) } + } + + /// Helper to validate an acquire. Returns the root address of the capability. + fun validate_acquire(requester: &signer): address + acquires CapState, CapDelegateState { + let addr = signer::address_of(requester); + if (exists>(addr)) { + let root_addr = borrow_global>(addr).root; + // double check that requester is actually registered as a delegate + assert!(exists>(root_addr), error::invalid_state(EDELEGATE)); + assert!(vector::contains(&borrow_global>(root_addr).delegates, &addr), + error::invalid_state(EDELEGATE)); + root_addr + } else { + assert!(exists>(addr), error::not_found(ECAPABILITY_NOT_FOUND)); + addr + } + } + + /// Returns the root address associated with the given capability token. Only the owner + /// of the feature can do this. + public fun root_addr(cap: Cap, _feature_witness: &Feature): address { + cap.root + } + + /// Returns the root address associated with the given linear capability token. + public fun linear_root_addr(cap: LinearCap, _feature_witness: &Feature): address { + cap.root + } + + /// Registers a delegation relation. If the relation already exists, this function does + /// nothing. + // TODO: explore whether this should be idempotent like now or abort + public fun delegate(cap: Cap, _feature_witness: &Feature, to: &signer) + acquires CapState { + let addr = signer::address_of(to); + if (exists>(addr)) return; + move_to(to, CapDelegateState { root: cap.root }); + add_element(&mut borrow_global_mut>(cap.root).delegates, addr); + } + + /// Revokes a delegation relation. If no relation exists, this function does nothing. + // TODO: explore whether this should be idempotent like now or abort + public fun revoke(cap: Cap, _feature_witness: &Feature, from: address) + acquires CapState, CapDelegateState + { + if (!exists>(from)) return; + let CapDelegateState { root: _root } = move_from>(from); + remove_element(&mut borrow_global_mut>(cap.root).delegates, &from); + } + + /// 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) + } + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/comparator.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/comparator.move new file mode 100644 index 0000000..869b486 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/comparator.move @@ -0,0 +1,173 @@ +/// Provides a framework for comparing two elements +module aptos_std::comparator { + use std::bcs; + use std::vector; + + const EQUAL: u8 = 0; + const SMALLER: u8 = 1; + const GREATER: u8 = 2; + + struct Result has drop { + inner: u8, + } + + public fun is_equal(result: &Result): bool { + result.inner == EQUAL + } + + public fun is_smaller_than(result: &Result): bool { + result.inner == SMALLER + } + + public fun is_greater_than(result: &Result): bool { + result.inner == GREATER + } + + // Performs a comparison of two types after BCS serialization. + // BCS uses little endian encoding for all integer types, + // so comparison between primitive integer types will not behave as expected. + // For example, 1(0x1) will be larger than 256(0x100) after BCS serialization. + public fun compare(left: &T, right: &T): Result { + let left_bytes = bcs::to_bytes(left); + let right_bytes = bcs::to_bytes(right); + + compare_u8_vector(left_bytes, right_bytes) + } + + // Performs a comparison of two vectors or byte vectors + public fun compare_u8_vector(left: vector, right: vector): Result { + let left_length = vector::length(&left); + let right_length = vector::length(&right); + + let idx = 0; + + while (idx < left_length && idx < right_length) { + let left_byte = *vector::borrow(&left, idx); + let right_byte = *vector::borrow(&right, idx); + + if (left_byte < right_byte) { + return Result { inner: SMALLER } + } else if (left_byte > right_byte) { + return Result { inner: GREATER } + }; + idx = idx + 1; + }; + + if (left_length < right_length) { + Result { inner: SMALLER } + } else if (left_length > right_length) { + Result { inner: GREATER } + } else { + Result { inner: EQUAL } + } + } + + #[test] + public fun test_strings() { + use std::string; + + let value0 = string::utf8(b"alpha"); + let value1 = string::utf8(b"beta"); + let value2 = string::utf8(b"betaa"); + + assert!(is_equal(&compare(&value0, &value0)), 0); + assert!(is_equal(&compare(&value1, &value1)), 1); + assert!(is_equal(&compare(&value2, &value2)), 2); + + assert!(is_greater_than(&compare(&value0, &value1)), 3); + assert!(is_smaller_than(&compare(&value1, &value0)), 4); + + assert!(is_smaller_than(&compare(&value0, &value2)), 5); + assert!(is_greater_than(&compare(&value2, &value0)), 6); + + assert!(is_smaller_than(&compare(&value1, &value2)), 7); + assert!(is_greater_than(&compare(&value2, &value1)), 8); + } + + #[test] + #[expected_failure] + public fun test_integer() { + // 1(0x1) will be larger than 256(0x100) after BCS serialization. + let value0: u128 = 1; + let value1: u128 = 256; + + assert!(is_equal(&compare(&value0, &value0)), 0); + assert!(is_equal(&compare(&value1, &value1)), 1); + + assert!(is_smaller_than(&compare(&value0, &value1)), 2); + assert!(is_greater_than(&compare(&value1, &value0)), 3); + } + + #[test] + public fun test_u128() { + let value0: u128 = 5; + let value1: u128 = 152; + let value2: u128 = 511; // 0x1ff + + assert!(is_equal(&compare(&value0, &value0)), 0); + assert!(is_equal(&compare(&value1, &value1)), 1); + assert!(is_equal(&compare(&value2, &value2)), 2); + + assert!(is_smaller_than(&compare(&value0, &value1)), 2); + assert!(is_greater_than(&compare(&value1, &value0)), 3); + + assert!(is_smaller_than(&compare(&value0, &value2)), 3); + assert!(is_greater_than(&compare(&value2, &value0)), 4); + + assert!(is_smaller_than(&compare(&value1, &value2)), 5); + assert!(is_greater_than(&compare(&value2, &value1)), 6); + } + + #[test_only] + struct Complex has drop { + value0: vector, + value1: u8, + value2: u64, + } + + #[test] + public fun test_complex() { + let value0_0 = vector::empty(); + vector::push_back(&mut value0_0, 10); + vector::push_back(&mut value0_0, 9); + vector::push_back(&mut value0_0, 5); + + let value0_1 = vector::empty(); + vector::push_back(&mut value0_1, 10); + vector::push_back(&mut value0_1, 9); + vector::push_back(&mut value0_1, 5); + vector::push_back(&mut value0_1, 1); + + let base = Complex { + value0: value0_0, + value1: 13, + value2: 41, + }; + + let other_0 = Complex { + value0: value0_1, + value1: 13, + value2: 41, + }; + + let other_1 = Complex { + value0: copy value0_0, + value1: 14, + value2: 41, + }; + + let other_2 = Complex { + value0: value0_0, + value1: 13, + value2: 42, + }; + + assert!(is_equal(&compare(&base, &base)), 0); + assert!(is_smaller_than(&compare(&base, &other_0)), 1); + assert!(is_greater_than(&compare(&other_0, &base)), 2); + assert!(is_smaller_than(&compare(&base, &other_1)), 3); + assert!(is_greater_than(&compare(&other_1, &base)), 4); + assert!(is_smaller_than(&compare(&base, &other_2)), 5); + assert!(is_greater_than(&compare(&other_2, &base)), 6); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/copyable_any.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/copyable_any.move new file mode 100644 index 0000000..b12303a --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/copyable_any.move @@ -0,0 +1,45 @@ +module aptos_std::copyable_any { + use aptos_std::type_info; + use aptos_std::from_bcs::from_bytes; + use std::bcs; + use std::error; + use std::string::String; + + /// The type provided for `unpack` is not the same as was given for `pack`. + const ETYPE_MISMATCH: u64 = 0; + + /// The same as `any::Any` but with the copy ability. + struct Any has drop, store, copy { + type_name: String, + data: vector + } + + /// Pack a value into the `Any` representation. Because Any can be stored, dropped, and copied this is + /// also required from `T`. + public fun pack(x: T): Any { + Any { + type_name: type_info::type_name(), + data: bcs::to_bytes(&x) + } + } + + /// Unpack a value from the `Any` representation. This aborts if the value has not the expected type `T`. + public fun unpack(x: Any): T { + assert!(type_info::type_name() == x.type_name, error::invalid_argument(ETYPE_MISMATCH)); + from_bytes(x.data) + } + + /// Returns the type name of this Any + public fun type_name(x: &Any): &String { + &x.type_name + } + + #[test_only] + struct S has store, drop, copy { x: u64 } + + #[test] + fun test_any() { + assert!(unpack(pack(22)) == 22, 1); + assert!(unpack(pack(S { x: 22 })) == S { x: 22 }, 2); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/crypto_algebra.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/crypto_algebra.move new file mode 100644 index 0000000..6058d48 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/crypto_algebra.move @@ -0,0 +1,345 @@ +/// This module provides generic structs/functions for operations of algebraic structures (e.g. fields and groups), +/// which can be used to build generic cryptographic schemes atop. +/// E.g., a Groth16 ZK proof verifier can be built to work over any pairing supported in this module. +/// +/// In general, every structure implements basic operations like (de)serialization, equality check, random sampling. +/// +/// A group may also implement the following operations. (Additive group notation is assumed.) +/// - `order()` for getting the group order. +/// - `zero()` for getting the group identity. +/// - `one()` for getting the group generator (if exists). +/// - `neg()` for group element inversion. +/// - `add()` for group operation (i.e., a group addition). +/// - `sub()` for group element subtraction. +/// - `double()` for efficient doubling. +/// - `scalar_mul()` for group scalar multiplication. +/// - `multi_scalar_mul()` for efficient group multi-scalar multiplication. +/// - `hash_to()` for hash-to-group. +/// +/// A field may also implement the following operations. +/// - `zero()` for getting the field additive identity. +/// - `one()` for getting the field multiplicative identity. +/// - `add()` for field addition. +/// - `sub()` for field subtraction. +/// - `mul()` for field multiplication. +/// - `div()` for field division. +/// - `neg()` for field negation. +/// - `inv()` for field inversion. +/// - `sqr()` for efficient field element squaring. +/// - `from_u64()` for quick conversion from u64 to field element. +/// +/// For 3 groups that admit a bilinear map, `pairing()` and `multi_pairing()` may be implemented. +/// +/// For a subset/superset relationship between 2 structures, `upcast()` and `downcast()` may be implemented. +/// E.g., in BLS12-381 pairing, since `Gt` is a subset of `Fq12`, +/// `upcast()` and `downcast()` will be supported. +/// +/// See `*_algebra.move` for currently implemented algebraic structures. +module aptos_std::crypto_algebra { + use std::option::{Option, some, none}; + use std::features; + + const E_NOT_IMPLEMENTED: u64 = 1; + const E_NON_EQUAL_LENGTHS: u64 = 2; + const E_TOO_MUCH_MEMORY_USED: u64 = 3; + + /// This struct represents an element of a structure `S`. + struct Element has copy, drop { + handle: u64 + } + + // + // Public functions begin. + // + + /// Check if `x == y` for elements `x` and `y` of a structure `S`. + public fun eq(x: &Element, y: &Element): bool { + abort_unless_cryptography_algebra_natives_enabled(); + eq_internal(x.handle, y.handle) + } + + /// Convert a u64 to an element of a structure `S`. + public fun from_u64(value: u64): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: from_u64_internal(value) + } + } + + /// Return the additive identity of field `S`, or the identity of group `S`. + public fun zero(): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: zero_internal() + } + } + + /// Return the multiplicative identity of field `S`, or a fixed generator of group `S`. + public fun one(): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: one_internal() + } + } + + /// Compute `-x` for an element `x` of a structure `S`. + public fun neg(x: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: neg_internal(x.handle) + } + } + + /// Compute `x + y` for elements `x` and `y` of structure `S`. + public fun add(x: &Element, y: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: add_internal(x.handle, y.handle) + } + } + + /// Compute `x - y` for elements `x` and `y` of a structure `S`. + public fun sub(x: &Element, y: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: sub_internal(x.handle, y.handle) + } + } + + /// Compute `x * y` for elements `x` and `y` of a structure `S`. + public fun mul(x: &Element, y: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: mul_internal(x.handle, y.handle) + } + } + + /// Try computing `x / y` for elements `x` and `y` of a structure `S`. + /// Return none if `y` does not have a multiplicative inverse in the structure `S` + /// (e.g., when `S` is a field, and `y` is zero). + public fun div(x: &Element, y: &Element): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succ, handle) = div_internal(x.handle, y.handle); + if (succ) { + some(Element { handle }) + } else { + none() + } + } + + /// Compute `x^2` for an element `x` of a structure `S`. Faster and cheaper than `mul(x, x)`. + public fun sqr(x: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: sqr_internal(x.handle) + } + } + + /// Try computing `x^(-1)` for an element `x` of a structure `S`. + /// Return none if `x` does not have a multiplicative inverse in the structure `S` + /// (e.g., when `S` is a field, and `x` is zero). + public fun inv(x: &Element): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succeeded, handle) = inv_internal(x.handle); + if (succeeded) { + let scalar = Element { handle }; + some(scalar) + } else { + none() + } + } + + /// Compute `2*P` for an element `P` of a structure `S`. Faster and cheaper than `add(P, P)`. + public fun double(element_p: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: double_internal(element_p.handle) + } + } + + /// Compute `k[0]*P[0]+...+k[n-1]*P[n-1]`, where + /// `P[]` are `n` elements of group `G` represented by parameter `elements`, and + /// `k[]` are `n` elements of the scalarfield `S` of group `G` represented by parameter `scalars`. + /// + /// Abort with code `std::error::invalid_argument(E_NON_EQUAL_LENGTHS)` if the sizes of `elements` and `scalars` do not match. + public fun multi_scalar_mul(elements: &vector>, scalars: &vector>): Element { + let element_handles = handles_from_elements(elements); + let scalar_handles = handles_from_elements(scalars); + Element { + handle: multi_scalar_mul_internal(element_handles, scalar_handles) + } + } + + /// Compute `k*P`, where `P` is an element of a group `G` and `k` is an element of the scalar field `S` associated to the group `G`. + public fun scalar_mul(element_p: &Element, scalar_k: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: scalar_mul_internal(element_p.handle, scalar_k.handle) + } + } + + /// Efficiently compute `e(P[0],Q[0])+...+e(P[n-1],Q[n-1])`, + /// where `e: (G1,G2) -> (Gt)` is the pairing function from groups `(G1,G2)` to group `Gt`, + /// `P[]` are `n` elements of group `G1` represented by parameter `g1_elements`, and + /// `Q[]` are `n` elements of group `G2` represented by parameter `g2_elements`. + /// + /// Abort with code `std::error::invalid_argument(E_NON_EQUAL_LENGTHS)` if the sizes of `g1_elements` and `g2_elements` do not match. + /// + /// NOTE: we are viewing the target group `Gt` of the pairing as an additive group, + /// rather than a multiplicative one (which is typically the case). + public fun multi_pairing(g1_elements: &vector>, g2_elements: &vector>): Element { + abort_unless_cryptography_algebra_natives_enabled(); + let g1_handles = handles_from_elements(g1_elements); + let g2_handles = handles_from_elements(g2_elements); + Element { + handle: multi_pairing_internal(g1_handles, g2_handles) + } + } + + /// Compute the pairing function (a.k.a., bilinear map) on a `G1` element and a `G2` element. + /// Return an element in the target group `Gt`. + public fun pairing(element_1: &Element, element_2: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: pairing_internal(element_1.handle, element_2.handle) + } + } + + /// Try deserializing a byte array to an element of an algebraic structure `S` using a given serialization format `F`. + /// Return none if the deserialization failed. + public fun deserialize(bytes: &vector): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succeeded, handle) = deserialize_internal(bytes); + if (succeeded) { + some(Element { handle }) + } else { + none() + } + } + + /// Serialize an element of an algebraic structure `S` to a byte array using a given serialization format `F`. + public fun serialize(element: &Element): vector { + abort_unless_cryptography_algebra_natives_enabled(); + serialize_internal(element.handle) + } + + /// Get the order of structure `S`, a big integer little-endian encoded as a byte array. + public fun order(): vector { + abort_unless_cryptography_algebra_natives_enabled(); + order_internal() + } + + /// Cast an element of a structure `S` to a parent structure `L`. + public fun upcast(element: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: upcast_internal(element.handle) + } + } + + /// Try casting an element `x` of a structure `L` to a sub-structure `S`. + /// Return none if `x` is not a member of `S`. + /// + /// NOTE: Membership check in `S` is performed inside, which can be expensive, depending on the structures `L` and `S`. + public fun downcast(element_x: &Element): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succ, new_handle) = downcast_internal(element_x.handle); + if (succ) { + some(Element { handle: new_handle }) + } else { + none() + } + } + + /// Hash an arbitrary-length byte array `msg` into structure `S` with a domain separation tag `dst` + /// using the given hash-to-structure suite `H`. + /// + /// NOTE: some hashing methods do not accept a `dst` and will abort if a non-empty one is provided. + public fun hash_to(dst: &vector, msg: &vector): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: hash_to_internal(dst, msg) + } + } + + #[test_only] + /// Generate a random element of an algebraic structure `S`. + public fun rand_insecure(): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: rand_insecure_internal() + } + } + + // + // (Public functions end here.) + // Private functions begin. + // + + fun abort_unless_cryptography_algebra_natives_enabled() { + if (features::cryptography_algebra_enabled()) return; + abort(std::error::not_implemented(0)) + } + + #[test_only] + public fun enable_cryptography_algebra_natives(fx: &signer) { + std::features::change_feature_flags(fx, vector[std::features::get_cryptography_algebra_natives_feature()], vector[]); + } + + fun handles_from_elements(elements: &vector>): vector { + let num_elements = std::vector::length(elements); + let element_handles = std::vector::empty(); + let i = 0; + while (i < num_elements) { + std::vector::push_back(&mut element_handles, std::vector::borrow(elements, i).handle); + i = i + 1; + }; + element_handles + } + + // + // (Private functions end here.) + // Native functions begin. + // + + native fun add_internal(handle_1: u64, handle_2: u64): u64; + native fun deserialize_internal(bytes: &vector): (bool, u64); + native fun div_internal(handle_1: u64, handle_2: u64): (bool, u64); + native fun double_internal(element_handle: u64): u64; + native fun downcast_internal(handle: u64): (bool, u64); + native fun from_u64_internal(value: u64): u64; + native fun eq_internal(handle_1: u64, handle_2: u64): bool; + native fun hash_to_internal(dst: &vector, bytes: &vector): u64; + native fun inv_internal(handle: u64): (bool, u64); + #[test_only] + native fun rand_insecure_internal(): u64; + native fun mul_internal(handle_1: u64, handle_2: u64): u64; + native fun multi_pairing_internal(g1_handles: vector, g2_handles: vector): u64; + native fun multi_scalar_mul_internal(element_handles: vector, scalar_handles: vector): u64; + native fun neg_internal(handle: u64): u64; + native fun one_internal(): u64; + native fun order_internal(): vector; + native fun pairing_internal(g1_handle: u64, g2_handle: u64): u64; + native fun scalar_mul_internal(element_handle: u64, scalar_handle: u64): u64; + native fun serialize_internal(handle: u64): vector; + native fun sqr_internal(handle: u64): u64; + native fun sub_internal(handle_1: u64, handle_2: u64): u64; + native fun upcast_internal(handle: u64): u64; + native fun zero_internal(): u64; + + // + // (Native functions end here.) + // Tests begin. + // + + #[test_only] + struct MysteriousGroup {} + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x0c0001, location = Self)] + fun test_generic_operation_should_abort_with_unsupported_structures(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let _ = order(); + } + // Tests end. +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/debug.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/debug.move new file mode 100644 index 0000000..21b707c --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/debug.move @@ -0,0 +1,278 @@ +/// Module providing debug functionality. +module aptos_std::debug { + use std::string::String; + + public fun print(x: &T) { + native_print(format(x)); + } + + public fun print_stack_trace() { + native_print(native_stack_trace()); + } + + inline fun format(x: &T): String { + aptos_std::string_utils::debug_string(x) + } + + native fun native_print(x: String); + native fun native_stack_trace(): String; + + #[test_only] + use std::vector; + + #[test_only] + struct Foo has drop {} + #[test_only] + struct Bar has drop { x: u128, y: Foo, z: bool } + #[test_only] + struct Box has drop { x: T } + + #[test_only] + struct GenericStruct has drop { + val: u64, + } + + #[test_only] + struct TestInner has drop { + val: u128, + vec: vector, + msgs: vector> + } + + #[test_only] + struct TestStruct has drop { + addr: address, + number: u8, + bytes: vector, + name: String, + vec: vector, + } + + #[test_only] + fun assert_equal(x: &T, expected: vector) { + if (std::string::bytes(&format(x)) != &expected) { + print(&format(x)); + print(&std::string::utf8(expected)); + assert!(false, 1); + }; + } + + #[test_only] + fun assert_string_equal(x: vector, expected: vector) { + assert!(std::string::bytes(&format(&std::string::utf8(x))) == &expected, 1); + } + + #[test] + public fun test() { + let x = 42; + assert_equal(&x, b"42"); + + let v = vector::empty(); + vector::push_back(&mut v, 100); + vector::push_back(&mut v, 200); + vector::push_back(&mut v, 300); + assert_equal(&v, b"[ 100, 200, 300 ]"); + + let foo = Foo {}; + assert_equal(&foo, b"0x1::debug::Foo {\n dummy_field: false\n}"); + + let bar = Bar { x: 404, y: Foo {}, z: true }; + assert_equal(&bar, b"0x1::debug::Bar {\n x: 404,\n y: 0x1::debug::Foo {\n dummy_field: false\n },\n z: true\n}"); + + let box = Box { x: Foo {} }; + assert_equal(&box, b"0x1::debug::Box<0x1::debug::Foo> {\n x: 0x1::debug::Foo {\n dummy_field: false\n }\n}"); + } + + #[test] + fun test_print_string() { + let str_bytes = b"Hello, sane Move debugging!"; + + assert_equal(&str_bytes, b"0x48656c6c6f2c2073616e65204d6f766520646562756767696e6721"); + + let str = std::string::utf8(str_bytes); + assert_equal(&str, b"\"Hello, sane Move debugging!\""); + } + + #[test] + fun test_print_quoted_string() { + let str_bytes = b"Can you say \"Hel\\lo\"?"; + + let str = std::string::utf8(str_bytes); + assert_equal(&str, b"\"Can you say \\\"Hel\\\\lo\\\"?\""); + } + + + #[test_only] + use std::features; + #[test(s = @0x123)] + fun test_print_primitive_types(s: signer) { + let u8 = 255u8; + assert_equal(&u8, b"255"); + + let u16 = 65535u16; + assert_equal(&u16, b"65535"); + + let u32 = 4294967295u32; + assert_equal(&u32, b"4294967295"); + + let u64 = 18446744073709551615u64; + assert_equal(&u64, b"18446744073709551615"); + + let u128 = 340282366920938463463374607431768211455u128; + assert_equal(&u128, b"340282366920938463463374607431768211455"); + + let u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935u256; + assert_equal(&u256, b"115792089237316195423570985008687907853269984665640564039457584007913129639935"); + + let bool = false; + assert_equal(&bool, b"false"); + + let bool = true; + assert_equal(&bool, b"true"); + + let a = @0x1234c0ffee; + assert_equal(&a, b"@0x1234c0ffee"); + + if (features::signer_native_format_fix_enabled()) { + let signer = s; + assert_equal(&signer, b"signer(@0x123)"); + } + } + + const MSG_1 : vector = b"abcdef"; + const MSG_2 : vector = b"123456"; + + #[test] + fun test_print_struct() { + let obj = TestInner { + val: 100, + vec: vector[200u128, 400u128], + msgs: vector[MSG_1, MSG_2], + }; + + assert_equal(&obj, b"0x1::debug::TestInner {\n val: 100,\n vec: [ 200, 400 ],\n msgs: [\n 0x616263646566,\n 0x313233343536\n ]\n}"); + + let obj = TestInner { + val: 10, + vec: vector[], + msgs: vector[], + }; + + assert_equal(&obj, b"0x1::debug::TestInner {\n val: 10,\n vec: [],\n msgs: []\n}"); + } + + #[test(s1 = @0x123, s2 = @0x456)] + fun test_print_vectors(s1: signer, s2: signer) { + let v_u8 = x"ffabcdef"; + assert_equal(&v_u8, b"0xffabcdef"); + + let v_u16 = vector[16u16, 17u16, 18u16, 19u16]; + assert_equal(&v_u16, b"[ 16, 17, 18, 19 ]"); + + let v_u32 = vector[32u32, 33u32, 34u32, 35u32]; + assert_equal(&v_u32, b"[ 32, 33, 34, 35 ]"); + + let v_u64 = vector[64u64, 65u64, 66u64, 67u64]; + assert_equal(&v_u64, b"[ 64, 65, 66, 67 ]"); + + let v_u128 = vector[128u128, 129u128, 130u128, 131u128]; + assert_equal(&v_u128, b"[ 128, 129, 130, 131 ]"); + + let v_u256 = vector[256u256, 257u256, 258u256, 259u256]; + assert_equal(&v_u256, b"[ 256, 257, 258, 259 ]"); + + let v_bool = vector[true, false]; + assert_equal(&v_bool, b"[ true, false ]"); + + let v_addr = vector[@0x1234, @0x5678, @0xabcdef]; + assert_equal(&v_addr, b"[ @0x1234, @0x5678, @0xabcdef ]"); + + if (features::signer_native_format_fix_enabled()) { + let v_signer = vector[s1, s2]; + assert_equal(&v_signer, b"[ signer(@0x123), signer(@0x456) ]"); + }; + + let v = vector[ + TestInner { + val: 4u128, + vec: vector[127u128, 128u128], + msgs: vector[x"00ff", x"abcd"], + }, + TestInner { + val: 8u128 , + vec: vector[128u128, 129u128], + msgs: vector[x"0000"], + } + ]; + assert_equal(&v, b"[\n 0x1::debug::TestInner {\n val: 4,\n vec: [ 127, 128 ],\n msgs: [\n 0x00ff,\n 0xabcd\n ]\n },\n 0x1::debug::TestInner {\n val: 8,\n vec: [ 128, 129 ],\n msgs: [\n 0x0000\n ]\n }\n]"); + } + + #[test(s1 = @0x123, s2 = @0x456)] + fun test_print_vector_of_vectors(s1: signer, s2: signer) { + let v_u8 = vector[x"ffab", x"cdef"]; + assert_equal(&v_u8, b"[\n 0xffab,\n 0xcdef\n]"); + + let v_u16 = vector[vector[16u16, 17u16], vector[18u16, 19u16]]; + assert_equal(&v_u16, b"[\n [ 16, 17 ],\n [ 18, 19 ]\n]"); + + let v_u32 = vector[vector[32u32, 33u32], vector[34u32, 35u32]]; + assert_equal(&v_u32, b"[\n [ 32, 33 ],\n [ 34, 35 ]\n]"); + + let v_u64 = vector[vector[64u64, 65u64], vector[66u64, 67u64]]; + assert_equal(&v_u64, b"[\n [ 64, 65 ],\n [ 66, 67 ]\n]"); + + let v_u128 = vector[vector[128u128, 129u128], vector[130u128, 131u128]]; + assert_equal(&v_u128, b"[\n [ 128, 129 ],\n [ 130, 131 ]\n]"); + + let v_u256 = vector[vector[256u256, 257u256], vector[258u256, 259u256]]; + assert_equal(&v_u256, b"[\n [ 256, 257 ],\n [ 258, 259 ]\n]"); + + let v_bool = vector[vector[true, false], vector[false, true]]; + assert_equal(&v_bool, b"[\n [ true, false ],\n [ false, true ]\n]"); + + let v_addr = vector[vector[@0x1234, @0x5678], vector[@0xabcdef, @0x9999]]; + assert_equal(&v_addr, b"[\n [ @0x1234, @0x5678 ],\n [ @0xabcdef, @0x9999 ]\n]"); + + if (features::signer_native_format_fix_enabled()) { + let v_signer = vector[vector[s1], vector[s2]]; + assert_equal(&v_signer, b"[\n [ signer(@0x123) ],\n [ signer(@0x456) ]\n]"); + }; + + let v = vector[ + vector[ + TestInner { val: 4u128, vec: vector[127u128, 128u128], msgs: vector[] }, + TestInner { val: 8u128 , vec: vector[128u128, 129u128], msgs: vector[] } + ], + vector[ + TestInner { val: 4u128, vec: vector[127u128, 128u128], msgs: vector[] }, + TestInner { val: 8u128 , vec: vector[128u128, 129u128], msgs: vector[] } + ] + ]; + assert_equal(&v, b"[\n [\n 0x1::debug::TestInner {\n val: 4,\n vec: [ 127, 128 ],\n msgs: []\n },\n 0x1::debug::TestInner {\n val: 8,\n vec: [ 128, 129 ],\n msgs: []\n }\n ],\n [\n 0x1::debug::TestInner {\n val: 4,\n vec: [ 127, 128 ],\n msgs: []\n },\n 0x1::debug::TestInner {\n val: 8,\n vec: [ 128, 129 ],\n msgs: []\n }\n ]\n]"); + } + + #[test] + fun test_print_nested_struct() { + let obj = TestStruct { + addr: @0x1, + number: 255u8, + bytes: x"c0ffee", + name: std::string::utf8(b"He\"llo"), + vec: vector[ + TestInner { val: 1, vec: vector[130u128, 131u128], msgs: vector[] }, + TestInner { val: 2, vec: vector[132u128, 133u128], msgs: vector[] } + ], + }; + + assert_equal(&obj, b"0x1::debug::TestStruct {\n addr: @0x1,\n number: 255,\n bytes: 0xc0ffee,\n name: \"He\\\"llo\",\n vec: [\n 0x1::debug::TestInner {\n val: 1,\n vec: [ 130, 131 ],\n msgs: []\n },\n 0x1::debug::TestInner {\n val: 2,\n vec: [ 132, 133 ],\n msgs: []\n }\n ]\n}"); + } + + #[test] + fun test_print_generic_struct() { + let obj = GenericStruct { + val: 60u64, + }; + + assert_equal(&obj, b"0x1::debug::GenericStruct<0x1::debug::Foo> {\n val: 60\n}"); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ed25519.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ed25519.move new file mode 100644 index 0000000..0f8d9c8 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ed25519.move @@ -0,0 +1,262 @@ +/// Contains functions for: +/// +/// 1. [Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519) digital signatures: i.e., EdDSA signatures over Edwards25519 curves with co-factor 8 +/// +module aptos_std::ed25519 { + use std::bcs; + use aptos_std::type_info::{Self, TypeInfo}; + use std::option::{Self, Option}; + + // + // Error codes + // + + /// Wrong number of bytes were given as input when deserializing an Ed25519 public key. + const E_WRONG_PUBKEY_SIZE: u64 = 1; + + /// Wrong number of bytes were given as input when deserializing an Ed25519 signature. + const E_WRONG_SIGNATURE_SIZE: u64 = 2; + + // + // Constants + // + + /// The identifier of the Ed25519 signature scheme, which is used when deriving Aptos authentication keys by hashing + /// it together with an Ed25519 public key. + const SIGNATURE_SCHEME_ID: u8 = 0; + + /// The size of a serialized public key, in bytes. + const PUBLIC_KEY_NUM_BYTES: u64 = 32; + + /// The size of a serialized signature, in bytes. + const SIGNATURE_NUM_BYTES: u64 = 64; + + // + // Structs + // + + #[test_only] + /// This struct holds an Ed25519 secret key that can be used to generate Ed25519 signatures during testing. + struct SecretKey has drop { + bytes: vector + } + + /// A BCS-serializable message, which one can verify signatures on via `signature_verify_strict_t` + struct SignedMessage has drop { + type_info: TypeInfo, + inner: MessageType, + } + + /// An *unvalidated* Ed25519 public key: not necessarily an elliptic curve point, just a sequence of 32 bytes + struct UnvalidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A *validated* Ed25519 public key: not necessarily a prime-order point, could be mixed-order, but will never be + /// a small-order point. + /// + /// For now, this struct is not used in any verification functions, but it might be in the future. + struct ValidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A purported Ed25519 signature that can be verified via `signature_verify_strict` or `signature_verify_strict_t`. + struct Signature has copy, drop, store { + bytes: vector + } + + // + // Functions + // + + /// Parses the input 32 bytes as an *unvalidated* Ed25519 public key. + public fun new_unvalidated_public_key_from_bytes(bytes: vector): UnvalidatedPublicKey { + assert!(std::vector::length(&bytes) == PUBLIC_KEY_NUM_BYTES, std::error::invalid_argument(E_WRONG_PUBKEY_SIZE)); + UnvalidatedPublicKey { bytes } + } + + /// Parses the input 32 bytes as a *validated* Ed25519 public key. + public fun new_validated_public_key_from_bytes(bytes: vector): Option { + if (public_key_validate_internal(bytes)) { + option::some(ValidatedPublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Parses the input 64 bytes as a purported Ed25519 signature. + public fun new_signature_from_bytes(bytes: vector): Signature { + assert!(std::vector::length(&bytes) == SIGNATURE_NUM_BYTES, std::error::invalid_argument(E_WRONG_SIGNATURE_SIZE)); + Signature { bytes } + } + + /// Converts a ValidatedPublicKey to an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_to_unvalidated(pk: &ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Moves a ValidatedPublicKey into an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_into_unvalidated(pk: ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Serializes an UnvalidatedPublicKey struct to 32-bytes. + public fun unvalidated_public_key_to_bytes(pk: &UnvalidatedPublicKey): vector { + pk.bytes + } + + /// Serializes an ValidatedPublicKey struct to 32-bytes. + public fun validated_public_key_to_bytes(pk: &ValidatedPublicKey): vector { + pk.bytes + } + + /// Serializes a Signature struct to 64-bytes. + public fun signature_to_bytes(sig: &Signature): vector { + sig.bytes + } + + /// Takes in an *unvalidated* public key and attempts to validate it. + /// Returns `Some(ValidatedPublicKey)` if successful and `None` otherwise. + public fun public_key_validate(pk: &UnvalidatedPublicKey): Option { + new_validated_public_key_from_bytes(pk.bytes) + } + + /// Verifies a purported Ed25519 `signature` under an *unvalidated* `public_key` on the specified `message`. + /// This call will validate the public key by checking it is NOT in the small subgroup. + public fun signature_verify_strict( + signature: &Signature, + public_key: &UnvalidatedPublicKey, + message: vector + ): bool { + signature_verify_strict_internal(signature.bytes, public_key.bytes, message) + } + + /// This function is used to verify a signature on any BCS-serializable type T. For now, it is used to verify the + /// proof of private key ownership when rotating authentication keys. + public fun signature_verify_strict_t(signature: &Signature, public_key: &UnvalidatedPublicKey, data: T): bool { + let encoded = SignedMessage { + type_info: type_info::type_of(), + inner: data, + }; + + signature_verify_strict_internal(signature.bytes, public_key.bytes, bcs::to_bytes(&encoded)) + } + + /// Helper method to construct a SignedMessage struct. + public fun new_signed_message(data: T): SignedMessage { + SignedMessage { + type_info: type_info::type_of(), + inner: data, + } + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun unvalidated_public_key_to_authentication_key(pk: &UnvalidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun validated_public_key_to_authentication_key(pk: &ValidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + fun public_key_bytes_to_authentication_key(pk_bytes: vector): vector { + std::vector::push_back(&mut pk_bytes, SIGNATURE_SCHEME_ID); + std::hash::sha3_256(pk_bytes) + } + + #[test_only] + /// Generates an Ed25519 key pair. + public fun generate_keys(): (SecretKey, ValidatedPublicKey) { + let (sk_bytes, pk_bytes) = generate_keys_internal(); + let sk = SecretKey { + bytes: sk_bytes + }; + let pk = ValidatedPublicKey { + bytes: pk_bytes + }; + (sk,pk) + } + + #[test_only] + /// Generates an Ed25519 signature for a given byte array using a given signing key. + public fun sign_arbitrary_bytes(sk: &SecretKey, msg: vector): Signature { + Signature { + bytes: sign_internal(sk.bytes, msg) + } + } + + #[test_only] + /// Generates an Ed25519 signature for given structured data using a given signing key. + public fun sign_struct(sk: &SecretKey, data: T): Signature { + let encoded = new_signed_message(data); + Signature { + bytes: sign_internal(sk.bytes, bcs::to_bytes(&encoded)) + } + } + + // + // Native functions + // + + /// Return `true` if the bytes in `public_key` can be parsed as a valid Ed25519 public key: i.e., it passes + /// points-on-curve and not-in-small-subgroup checks. + /// Returns `false` otherwise. + native fun public_key_validate_internal(bytes: vector): bool; + + /// Return true if the Ed25519 `signature` on `message` verifies against the Ed25519 `public_key`. + /// Returns `false` if either: + /// - `signature` or `public key` are of wrong sizes + /// - `public_key` does not pass points-on-curve or not-in-small-subgroup checks, + /// - `signature` does not pass points-on-curve or not-in-small-subgroup checks, + /// - the signature on `message` does not verify. + native fun signature_verify_strict_internal( + signature: vector, + public_key: vector, + message: vector + ): bool; + + #[test_only] + /// Generates an Ed25519 key pair. + native fun generate_keys_internal(): (vector, vector); + + #[test_only] + /// Generates an Ed25519 signature for a given byte array using a given signing key. + native fun sign_internal(sk: vector, msg: vector): vector; + + // + // Tests + // + + #[test_only] + struct TestMessage has copy, drop { + title: vector, + content: vector, + } + + #[test] + fun test_gen_sign_verify_combo() { + let (sk, vpk) = generate_keys(); + let pk = public_key_into_unvalidated(vpk); + + let msg1: vector = x"0123456789abcdef"; + let sig1 = sign_arbitrary_bytes(&sk, msg1); + assert!(signature_verify_strict(&sig1, &pk, msg1), std::error::invalid_state(1)); + + let msg2 = TestMessage { + title: b"Some Title", + content: b"That is it.", + }; + let sig2 = sign_struct(&sk, copy msg2); + assert!(signature_verify_strict_t(&sig2, &pk, copy msg2), std::error::invalid_state(2)); + } + + +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/fixed_point64.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/fixed_point64.move new file mode 100644 index 0000000..6669d6a --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/fixed_point64.move @@ -0,0 +1,447 @@ +/// Defines a fixed-point numeric type with a 64-bit integer part and +/// a 64-bit fractional part. + +module aptos_std::fixed_point64 { + + /// Define a fixed-point numeric type with 64 fractional bits. + /// This is just a u128 integer but it is wrapped in a struct to + /// make a unique type. This is a binary representation, so decimal + /// values may not be exactly representable, but it provides more + /// than 9 decimal digits of precision both before and after the + /// decimal point (18 digits total). For comparison, double precision + /// floating-point has less than 16 decimal digits of precision, so + /// be careful about using floating-point to convert these values to + /// decimal. + struct FixedPoint64 has copy, drop, store { value: u128 } + + const MAX_U128: u256 = 340282366920938463463374607431768211455; + + /// The denominator provided was zero + const EDENOMINATOR: u64 = 0x10001; + /// The quotient value would be too large to be held in a `u128` + const EDIVISION: u64 = 0x20002; + /// The multiplied value would be too large to be held in a `u128` + const EMULTIPLICATION: u64 = 0x20003; + /// A division by zero was encountered + const EDIVISION_BY_ZERO: u64 = 0x10004; + /// The computed ratio when converting to a `FixedPoint64` would be unrepresentable + const ERATIO_OUT_OF_RANGE: u64 = 0x20005; + /// Abort code on calculation result is negative. + const ENEGATIVE_RESULT: u64 = 0x10006; + + /// Returns x - y. x must be not less than y. + public fun sub(x: FixedPoint64, y: FixedPoint64): FixedPoint64 { + let x_raw = get_raw_value(x); + let y_raw = get_raw_value(y); + assert!(x_raw >= y_raw, ENEGATIVE_RESULT); + create_from_raw_value(x_raw - y_raw) + } + spec sub { + pragma opaque; + aborts_if x.value < y.value with ENEGATIVE_RESULT; + ensures result.value == x.value - y.value; + } + + /// Returns x + y. The result cannot be greater than MAX_U128. + public fun add(x: FixedPoint64, y: FixedPoint64): FixedPoint64 { + let x_raw = get_raw_value(x); + let y_raw = get_raw_value(y); + let result = (x_raw as u256) + (y_raw as u256); + assert!(result <= MAX_U128, ERATIO_OUT_OF_RANGE); + create_from_raw_value((result as u128)) + } + spec add { + pragma opaque; + aborts_if (x.value as u256) + (y.value as u256) > MAX_U128 with ERATIO_OUT_OF_RANGE; + ensures result.value == x.value + y.value; + } + + /// Multiply a u128 integer by a fixed-point number, truncating any + /// fractional part of the product. This will abort if the product + /// overflows. + public fun multiply_u128(val: u128, multiplier: FixedPoint64): u128 { + // The product of two 128 bit values has 256 bits, so perform the + // multiplication with u256 types and keep the full 256 bit product + // to avoid losing accuracy. + let unscaled_product = (val as u256) * (multiplier.value as u256); + // The unscaled product has 64 fractional bits (from the multiplier) + // so rescale it by shifting away the low bits. + let product = unscaled_product >> 64; + // Check whether the value is too large. + assert!(product <= MAX_U128, EMULTIPLICATION); + (product as u128) + } + spec multiply_u128 { + pragma opaque; + include MultiplyAbortsIf; + ensures result == spec_multiply_u128(val, multiplier); + } + spec schema MultiplyAbortsIf { + val: num; + multiplier: FixedPoint64; + aborts_if spec_multiply_u128(val, multiplier) > MAX_U128 with EMULTIPLICATION; + } + spec fun spec_multiply_u128(val: num, multiplier: FixedPoint64): num { + (val * multiplier.value) >> 64 + } + + /// Divide a u128 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_u128(val: u128, divisor: FixedPoint64): u128 { + // Check for division by zero. + assert!(divisor.value != 0, EDIVISION_BY_ZERO); + // First convert to 256 bits and then shift left to + // add 64 fractional zero bits to the dividend. + let scaled_value = (val as u256) << 64; + let quotient = scaled_value / (divisor.value as u256); + // Check whether the value is too large. + assert!(quotient <= MAX_U128, EDIVISION); + // the value may be too large, which will cause the cast to fail + // with an arithmetic error. + (quotient as u128) + } + spec divide_u128 { + pragma opaque; + include DivideAbortsIf; + ensures result == spec_divide_u128(val, divisor); + } + spec schema DivideAbortsIf { + val: num; + divisor: FixedPoint64; + aborts_if divisor.value == 0 with EDIVISION_BY_ZERO; + aborts_if spec_divide_u128(val, divisor) > MAX_U128 with EDIVISION; + } + spec fun spec_divide_u128(val: num, divisor: FixedPoint64): num { + (val << 64) / divisor.value + } + + /// Create a fixed-point value from a rational number specified by its + /// numerator and denominator. Calling this function should be preferred + /// for using `Self::create_from_raw_value` which is also available. + /// This will abort if the denominator is zero. It will also + /// abort if the numerator is nonzero and the ratio is not in the range + /// 2^-64 .. 2^64-1. When specifying decimal fractions, be careful about + /// rounding errors: if you round to display N digits after the decimal + /// point, you can use a denominator of 10^N to avoid numbers where the + /// very small imprecision in the binary representation could change the + /// rounding, e.g., 0.0125 will round down to 0.012 instead of up to 0.013. + public fun create_from_rational(numerator: u128, denominator: u128): FixedPoint64 { + // If the denominator is zero, this will abort. + // Scale the numerator to have 64 fractional bits, so that the quotient will have 64 + // fractional bits. + let scaled_numerator = (numerator as u256) << 64; + assert!(denominator != 0, EDENOMINATOR); + let quotient = scaled_numerator / (denominator as u256); + assert!(quotient != 0 || numerator == 0, 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_U128, ERATIO_OUT_OF_RANGE); + FixedPoint64 { value: (quotient as u128) } + } + spec create_from_rational { + pragma opaque; + pragma verify_duration_estimate = 120; // TODO: set because of timeout (property proved). + include CreateFromRationalAbortsIf; + ensures result == spec_create_from_rational(numerator, denominator); + } + spec schema CreateFromRationalAbortsIf { + numerator: u128; + denominator: u128; + let scaled_numerator = (numerator as u256)<< 64; + let scaled_denominator = (denominator as u256); + let quotient = scaled_numerator / scaled_denominator; + aborts_if scaled_denominator == 0 with EDENOMINATOR; + aborts_if quotient == 0 && scaled_numerator != 0 with ERATIO_OUT_OF_RANGE; + aborts_if quotient > MAX_U128 with ERATIO_OUT_OF_RANGE; + } + spec fun spec_create_from_rational(numerator: num, denominator: num): FixedPoint64 { + FixedPoint64{value: (numerator << 128) / (denominator << 64)} + } + + /// Create a fixedpoint value from a raw value. + public fun create_from_raw_value(value: u128): FixedPoint64 { + FixedPoint64 { value } + } + spec create_from_raw_value { + pragma opaque; + aborts_if false; + ensures result.value == value; + } + + /// Accessor for the raw u128 value. Other less common operations, such as + /// adding or subtracting FixedPoint64 values, can be done using the raw + /// values directly. + public fun get_raw_value(num: FixedPoint64): u128 { + num.value + } + + /// Returns true if the ratio is zero. + public fun is_zero(num: FixedPoint64): bool { + num.value == 0 + } + + /// Returns the smaller of the two FixedPoint64 numbers. + public fun min(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + spec min { + pragma opaque; + aborts_if false; + ensures result == spec_min(num1, num2); + } + spec fun spec_min(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + + /// Returns the larger of the two FixedPoint64 numbers. + public fun max(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + spec max { + pragma opaque; + aborts_if false; + ensures result == spec_max(num1, num2); + } + spec fun spec_max(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + + /// Returns true if num1 <= num2 + public fun less_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value <= num2.value + } + spec less_or_equal { + pragma opaque; + aborts_if false; + ensures result == spec_less_or_equal(num1, num2); + } + spec fun spec_less_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value <= num2.value + } + + /// Returns true if num1 < num2 + public fun less(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value < num2.value + } + spec less { + pragma opaque; + aborts_if false; + ensures result == spec_less(num1, num2); + } + spec fun spec_less(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value < num2.value + } + + /// Returns true if num1 >= num2 + public fun greater_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value >= num2.value + } + spec greater_or_equal { + pragma opaque; + aborts_if false; + ensures result == spec_greater_or_equal(num1, num2); + } + spec fun spec_greater_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value >= num2.value + } + + /// Returns true if num1 > num2 + public fun greater(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value > num2.value + } + spec greater { + pragma opaque; + aborts_if false; + ensures result == spec_greater(num1, num2); + } + spec fun spec_greater(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value > num2.value + } + + /// Returns true if num1 = num2 + public fun equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value == num2.value + } + spec equal { + pragma opaque; + aborts_if false; + ensures result == spec_equal(num1, num2); + } + spec fun spec_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value == num2.value + } + + /// Returns true if num1 almost equals to num2, which means abs(num1-num2) <= precision + public fun almost_equal(num1: FixedPoint64, num2: FixedPoint64, precision: FixedPoint64): bool { + if (num1.value > num2.value) { + (num1.value - num2.value <= precision.value) + } else { + (num2.value - num1.value <= precision.value) + } + } + spec almost_equal { + pragma opaque; + aborts_if false; + ensures result == spec_almost_equal(num1, num2, precision); + } + spec fun spec_almost_equal(num1: FixedPoint64, num2: FixedPoint64, precision: FixedPoint64): bool { + if (num1.value > num2.value) { + (num1.value - num2.value <= precision.value) + } else { + (num2.value - num1.value <= precision.value) + } + } + /// Create a fixedpoint value from a u128 value. + public fun create_from_u128(val: u128): FixedPoint64 { + let value = (val as u256) << 64; + assert!(value <= MAX_U128, ERATIO_OUT_OF_RANGE); + FixedPoint64 {value: (value as u128)} + } + spec create_from_u128 { + pragma opaque; + include CreateFromU64AbortsIf; + ensures result == spec_create_from_u128(val); + } + spec schema CreateFromU64AbortsIf { + val: num; + let scaled_value = (val as u256) << 64; + aborts_if scaled_value > MAX_U128; + } + spec fun spec_create_from_u128(val: num): FixedPoint64 { + FixedPoint64 {value: val << 64} + } + + /// Returns the largest integer less than or equal to a given number. + public fun floor(num: FixedPoint64): u128 { + num.value >> 64 + } + spec floor { + pragma opaque; + aborts_if false; + ensures result == spec_floor(num); + } + spec fun spec_floor(val: FixedPoint64): u128 { + let fractional = val.value % (1 << 64); + if (fractional == 0) { + val.value >> 64 + } else { + (val.value - fractional) >> 64 + } + } + + /// Rounds up the given FixedPoint64 to the next largest integer. + public fun ceil(num: FixedPoint64): u128 { + let floored_num = floor(num) << 64; + if (num.value == floored_num) { + return floored_num >> 64 + }; + let val = ((floored_num as u256) + (1 << 64)); + (val >> 64 as u128) + } + spec ceil { + /// TODO: worked in the past but started to time out since last z3 update + pragma verify = false; + pragma opaque; + aborts_if false; + ensures result == spec_ceil(num); + } + spec fun spec_ceil(val: FixedPoint64): u128 { + let fractional = val.value % (1 << 64); + let one = 1 << 64; + if (fractional == 0) { + val.value >> 64 + } else { + (val.value - fractional + one) >> 64 + } + } + + /// Returns the value of a FixedPoint64 to the nearest integer. + public fun round(num: FixedPoint64): u128 { + let floored_num = floor(num) << 64; + let boundary = floored_num + ((1 << 64) / 2); + if (num.value < boundary) { + floored_num >> 64 + } else { + ceil(num) + } + } + spec round { + pragma opaque; + aborts_if false; + ensures result == spec_round(num); + } + spec fun spec_round(val: FixedPoint64): u128 { + let fractional = val.value % (1 << 64); + let boundary = (1 << 64) / 2; + let one = 1 << 64; + if (fractional < boundary) { + (val.value - fractional) >> 64 + } else { + (val.value - fractional + one) >> 64 + } + } + + // **************** SPECIFICATIONS **************** + + spec module {} // switch documentation context to module level + + spec module { + pragma aborts_if_is_strict; + } + + #[test] + public entry fun test_sub() { + let x = create_from_rational(9, 7); + let y = create_from_rational(1, 3); + let result = sub(x, y); + // 9/7 - 1/3 = 20/21 + let expected_result = create_from_rational(20, 21); + assert_approx_the_same((get_raw_value(result) as u256), (get_raw_value(expected_result) as u256), 16); + } + + #[test] + #[expected_failure(abort_code = 0x10006, location = Self)] + public entry fun test_sub_should_abort() { + let x = create_from_rational(1, 3); + let y = create_from_rational(9, 7); + let _ = sub(x, y); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u256, y: u256, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = 1u256; + let n = 10u256; + while (precission > 0) { + if (precission % 2 == 1) { + mult = mult * n; + }; + precission = precission / 2; + n = n * n; + }; + assert!((x - y) * mult < x, 0); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/from_bcs.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/from_bcs.move new file mode 100644 index 0000000..1d7c3c5 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/from_bcs.move @@ -0,0 +1,91 @@ +/// This module provides a number of functions to convert _primitive_ types from their representation in `std::bcs` +/// to values. This is the opposite of `bcs::to_bytes`. Note that it is not safe to define a generic public `from_bytes` +/// function because this can violate implicit struct invariants, therefore only primitive types are offerred. If +/// a general conversion back-and-force is needed, consider the `aptos_std::Any` type which preserves invariants. +/// +/// Example: +/// ``` +/// use std::bcs; +/// use aptos_std::from_bcs; +/// +/// assert!(from_bcs::to_address(bcs::to_bytes(&@0xabcdef)) == @0xabcdef, 0); +/// ``` +module aptos_std::from_bcs { + use std::string::{Self, String}; + + /// UTF8 check failed in conversion from bytes to string + const EINVALID_UTF8: u64 = 0x1; + + public fun to_bool(v: vector): bool { + from_bytes(v) + } + + public fun to_u8(v: vector): u8 { + from_bytes(v) + } + + public fun to_u16(v: vector): u16 { + from_bytes(v) + } + + public fun to_u32(v: vector): u32 { + from_bytes(v) + } + + public fun to_u64(v: vector): u64 { + from_bytes(v) + } + + public fun to_u128(v: vector): u128 { + from_bytes(v) + } + + public fun to_u256(v: vector): u256 { + from_bytes(v) + } + + public fun to_address(v: vector): address { + from_bytes
(v) + } + + public fun to_bytes(v: vector): vector { + from_bytes>(v) + } + + public fun to_string(v: vector): String { + // To make this safe, we need to evaluate the utf8 invariant. + let s = from_bytes(v); + assert!(string::internal_check_utf8(string::bytes(&s)), EINVALID_UTF8); + s + } + + /// Package private native function to deserialize a type T. + /// + /// Note that this function does not put any constraint on `T`. If code uses this function to + /// deserialize a linear value, its their responsibility that the data they deserialize is + /// owned. + public(friend) native fun from_bytes(bytes: vector): T; + friend aptos_std::any; + friend aptos_std::copyable_any; + + + #[test_only] + use std::bcs; + + #[test] + fun test_address() { + let addr = @0x01; + let addr_vec = x"0000000000000000000000000000000000000000000000000000000000000001"; + let addr_out = to_address(addr_vec); + let addr_vec_out = bcs::to_bytes(&addr_out); + assert!(addr == addr_out, 0); + assert!(addr_vec == addr_vec_out, 1); + } + + #[test] + #[expected_failure(abort_code = 0x10001, location = Self)] + fun test_address_fail() { + let bad_vec = b"01"; + to_address(bad_vec); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math128.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math128.move new file mode 100644 index 0000000..8f4dee3 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math128.move @@ -0,0 +1,310 @@ +/// Standard math utilities missing in the Move Language. +module aptos_std::math128 { + + use std::fixed_point32::FixedPoint32; + use std::fixed_point32; + use aptos_std::fixed_point64::FixedPoint64; + use aptos_std::fixed_point64; + + /// Abort value when an invalid argument is provided. + const EINVALID_ARG_FLOOR_LOG2: u64 = 1; + const EDIVISION_BY_ZERO: u64 = 2; + + /// Return the largest of two numbers. + public fun max(a: u128, b: u128): u128 { + if (a >= b) a else b + } + + /// Return the smallest of two numbers. + public fun min(a: u128, b: u128): u128 { + if (a < b) a else b + } + + /// Return the average of two. + public fun average(a: u128, b: u128): u128 { + if (a < b) { + a + (b - a) / 2 + } else { + b + (a - b) / 2 + } + } + + /// Returns a * b / c going through u128 to prevent intermediate overflow + public inline fun mul_div(a: u128, b: u128, c: u128): u128 { + (((a as u256) * (b as u256) / (c as u256)) as u128) + } + + /// Return x clamped to the interval [lower, upper]. + public fun clamp(x: u128, lower: u128, upper: u128): u128 { + min(upper, max(lower, x)) + } + + /// Return the value of n raised to power e + public fun pow(n: u128, e: u128): u128 { + if (e == 0) { + 1 + } else { + let p = 1; + while (e > 1) { + if (e % 2 == 1) { + p = p * n; + }; + e = e / 2; + n = n * n; + }; + p * n + } + } + + /// Returns floor(log2(x)) + public fun floor_log2(x: u128): u8 { + let res = 0; + assert!(x != 0, std::error::invalid_argument(EINVALID_ARG_FLOOR_LOG2)); + // Effectively the position of the most significant set bit + let n = 64; + while (n > 0) { + if (x >= (1 << n)) { + x = x >> n; + res = res + n; + }; + n = n >> 1; + }; + res + } + + // Returns log2(x) + public fun log2(x: u128): FixedPoint32 { + let integer_part = floor_log2(x); + // Normalize x to [1, 2) in fixed point 32. + if (x >= 1 << 32) { + x = x >> (integer_part - 32); + } else { + x = x << (32 - integer_part); + }; + let frac = 0; + let delta = 1 << 31; + while (delta != 0) { + // log x = 1/2 log x^2 + // x in [1, 2) + x = (x * x) >> 32; + // x is now in [1, 4) + // if x in [2, 4) then log x = 1 + log (x / 2) + if (x >= (2 << 32)) { frac = frac + delta; x = x >> 1; }; + delta = delta >> 1; + }; + fixed_point32::create_from_raw_value (((integer_part as u64) << 32) + frac) + } + + // Return log2(x) as FixedPoint64 + public fun log2_64(x: u128): FixedPoint64 { + let integer_part = floor_log2(x); + // Normalize x to [1, 2) in fixed point 63. To ensure x is smaller then 1<<64 + if (x >= 1 << 63) { + x = x >> (integer_part - 63); + } else { + x = x << (63 - integer_part); + }; + let frac = 0; + let delta = 1 << 63; + while (delta != 0) { + // log x = 1/2 log x^2 + // x in [1, 2) + x = (x * x) >> 63; + // x is now in [1, 4) + // if x in [2, 4) then log x = 1 + log (x / 2) + if (x >= (2 << 63)) { frac = frac + delta; x = x >> 1; }; + delta = delta >> 1; + }; + fixed_point64::create_from_raw_value (((integer_part as u128) << 64) + frac) + } + + /// Returns square root of x, precisely floor(sqrt(x)) + public fun sqrt(x: u128): u128 { + if (x == 0) return 0; + // Note the plus 1 in the expression. Let n = floor_lg2(x) we have x in [2^n, 2^{n+1}) and thus the answer in + // the half-open interval [2^(n/2), 2^{(n+1)/2}). For even n we can write this as [2^(n/2), sqrt(2) 2^{n/2}) + // for odd n [2^((n+1)/2)/sqrt(2), 2^((n+1)/2). For even n the left end point is integer for odd the right + // end point is integer. If we choose as our first approximation the integer end point we have as maximum + // relative error either (sqrt(2) - 1) or (1 - 1/sqrt(2)) both are smaller then 1/2. + let res = 1 << ((floor_log2(x) + 1) >> 1); + // We use standard newton-rhapson iteration to improve the initial approximation. + // The error term evolves as delta_i+1 = delta_i^2 / 2 (quadratic convergence). + // It turns out that after 5 iterations the delta is smaller than 2^-64 and thus below the treshold. + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + min(res, x / res) + } + + public inline fun ceil_div(x: u128, y: u128): u128 { + // ceil_div(x, y) = floor((x + y - 1) / y) = floor((x - 1) / y) + 1 + // (x + y - 1) could spuriously overflow. so we use the later version + if (x == 0) { + assert!(y != 0, EDIVISION_BY_ZERO); + 0 + } + else (x - 1) / y + 1 + } + + #[test] + public entry fun test_ceil_div() { + assert!(ceil_div(9, 3) == 3, 0); + assert!(ceil_div(10, 3) == 4, 0); + assert!(ceil_div(11, 3) == 4, 0); + assert!(ceil_div(12, 3) == 4, 0); + assert!(ceil_div(13, 3) == 5, 0); + + // No overflow + assert!(ceil_div((((1u256<<128) - 9) as u128), 11) == 30934760629176223951215873402888019223, 0); + } + #[test] + public entry fun test_max() { + let result = max(3u128, 6u128); + assert!(result == 6, 0); + + let result = max(15u128, 12u128); + assert!(result == 15, 1); + } + + #[test] + public entry fun test_min() { + let result = min(3u128, 6u128); + assert!(result == 3, 0); + + let result = min(15u128, 12u128); + assert!(result == 12, 1); + } + + #[test] + public entry fun test_average() { + let result = average(3u128, 6u128); + assert!(result == 4, 0); + + let result = average(15u128, 12u128); + assert!(result == 13, 0); + } + + #[test] + public entry fun test_pow() { + let result = pow(10u128, 18u128); + assert!(result == 1000000000000000000, 0); + + let result = pow(10u128, 1u128); + assert!(result == 10, 0); + + let result = pow(10u128, 0u128); + assert!(result == 1, 0); + } + + #[test] + public entry fun test_mul_div() { + let tmp: u128 = 1<<127; + assert!(mul_div(tmp,tmp,tmp) == tmp, 0); + + assert!(mul_div(tmp,5,5) == tmp, 0); + // Note that ordering other way is imprecise. + assert!((tmp / 5) * 5 != tmp, 0); + } + + #[test] + public entry fun test_floor_log2() { + let idx: u8 = 0; + while (idx < 128) { + assert!(floor_log2(1<> 32; + let taylor3 = (taylor2 * taylor1) >> 32; + let expected = expected - ((taylor1 + taylor2 / 2 + taylor3 / 3) << 32) / 2977044472; + // verify it matches to 8 significant digits + assert_approx_the_same((fixed_point32::get_raw_value(res) as u128), expected, 8); + idx = idx + 1; + }; + } + + #[test] + public entry fun test_log2_64() { + let idx: u8 = 0; + while (idx < 128) { + let res = log2_64(1<> 64; + let taylor3 = (taylor2 * taylor1) >> 64; + let taylor4 = (taylor3 * taylor1) >> 64; + let expected = expected - ((taylor1 + taylor2 / 2 + taylor3 / 3 + taylor4 / 4) << 64) / 12786308645202655660; + // verify it matches to 8 significant digits + assert_approx_the_same(fixed_point64::get_raw_value(res), (expected as u128), 14); + idx = idx + 1; + }; + } + + #[test] + public entry fun test_sqrt() { + let result = sqrt(0); + assert!(result == 0, 0); + + let result = sqrt(1); + assert!(result == 1, 0); + + let result = sqrt(256); + assert!(result == 16, 0); + + let result = sqrt(1<<126); + assert!(result == 1<<63, 0); + + let result = sqrt((((1u256 << 128) - 1) as u128)); + assert!(result == (1u128 << 64) - 1, 0); + + let result = sqrt((1u128 << 127)); + assert!(result == 13043817825332782212, 0); + + let result = sqrt((1u128 << 127) - 1); + assert!(result == 13043817825332782212, 0); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u128, y: u128, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = pow(10, precission); + assert!((x - y) * mult < x, 0); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math64.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math64.move new file mode 100644 index 0000000..9cf086c --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math64.move @@ -0,0 +1,266 @@ +/// Standard math utilities missing in the Move Language. +module aptos_std::math64 { + + use std::fixed_point32::FixedPoint32; + use std::fixed_point32; + + /// Abort value when an invalid argument is provided. + const EINVALID_ARG_FLOOR_LOG2: u64 = 1; + const EDIVISION_BY_ZERO: u64 = 1; + + /// Return the largest of two numbers. + public fun max(a: u64, b: u64): u64 { + if (a >= b) a else b + } + + /// Return the smallest of two numbers. + public fun min(a: u64, b: u64): u64 { + if (a < b) a else b + } + + /// Return the average of two. + public fun average(a: u64, b: u64): u64 { + if (a < b) { + a + (b - a) / 2 + } else { + b + (a - b) / 2 + } + } + + /// Returns a * b / c going through u128 to prevent intermediate overflow + public inline fun mul_div(a: u64, b: u64, c: u64): u64 { + (((a as u128) * (b as u128) / (c as u128)) as u64) + } + + /// Return x clamped to the interval [lower, upper]. + public fun clamp(x: u64, lower: u64, upper: u64): u64 { + min(upper, max(lower, x)) + } + + /// Return the value of n raised to power e + public fun pow(n: u64, e: u64): u64 { + if (e == 0) { + 1 + } else { + let p = 1; + while (e > 1) { + if (e % 2 == 1) { + p = p * n; + }; + e = e / 2; + n = n * n; + }; + p * n + } + } + + /// Returns floor(lg2(x)) + public fun floor_log2(x: u64): u8 { + let res = 0; + assert!(x != 0, std::error::invalid_argument(EINVALID_ARG_FLOOR_LOG2)); + // Effectively the position of the most significant set bit + let n = 32; + while (n > 0) { + if (x >= (1 << n)) { + x = x >> n; + res = res + n; + }; + n = n >> 1; + }; + res + } + + // Returns log2(x) + public fun log2(x: u64): FixedPoint32 { + let integer_part = floor_log2(x); + // Normalize x to [1, 2) in fixed point 32. + let y = (if (x >= 1 << 32) { + x >> (integer_part - 32) + } else { + x << (32 - integer_part) + } as u128); + let frac = 0; + let delta = 1 << 31; + while (delta != 0) { + // log x = 1/2 log x^2 + // x in [1, 2) + y = (y * y) >> 32; + // x is now in [1, 4) + // if x in [2, 4) then log x = 1 + log (x / 2) + if (y >= (2 << 32)) { frac = frac + delta; y = y >> 1; }; + delta = delta >> 1; + }; + fixed_point32::create_from_raw_value (((integer_part as u64) << 32) + frac) + } + + /// Returns square root of x, precisely floor(sqrt(x)) + public fun sqrt(x: u64): u64 { + if (x == 0) return 0; + // Note the plus 1 in the expression. Let n = floor_lg2(x) we have x in [2^n, 2^(n+1)> and thus the answer in + // the half-open interval [2^(n/2), 2^((n+1)/2)>. For even n we can write this as [2^(n/2), sqrt(2) 2^(n/2)> + // for odd n [2^((n+1)/2)/sqrt(2), 2^((n+1)/2>. For even n the left end point is integer for odd the right + // end point is integer. If we choose as our first approximation the integer end point we have as maximum + // relative error either (sqrt(2) - 1) or (1 - 1/sqrt(2)) both are smaller then 1/2. + let res = 1 << ((floor_log2(x) + 1) >> 1); + // We use standard newton-rhapson iteration to improve the initial approximation. + // The error term evolves as delta_i+1 = delta_i^2 / 2 (quadratic convergence). + // It turns out that after 4 iterations the delta is smaller than 2^-32 and thus below the treshold. + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + min(res, x / res) + } + + public inline fun ceil_div(x: u64, y: u64): u64 { + // ceil_div(x, y) = floor((x + y - 1) / y) = floor((x - 1) / y) + 1 + // (x + y - 1) could spuriously overflow. so we use the later version + if (x == 0) { + assert!(y != 0, EDIVISION_BY_ZERO); + 0 + } + else (x - 1) / y + 1 + } + + #[test] + public entry fun test_ceil_div() { + assert!(ceil_div(9, 3) == 3, 0); + assert!(ceil_div(10, 3) == 4, 0); + assert!(ceil_div(11, 3) == 4, 0); + assert!(ceil_div(12, 3) == 4, 0); + assert!(ceil_div(13, 3) == 5, 0); + + // No overflow + assert!(ceil_div((((1u128<<64) - 9) as u64), 11) == 1676976733973595601, 0); + } + + #[test] + public entry fun test_max_64() { + let result = max(3u64, 6u64); + assert!(result == 6, 0); + + let result = max(15u64, 12u64); + assert!(result == 15, 1); + } + + #[test] + public entry fun test_min() { + let result = min(3u64, 6u64); + assert!(result == 3, 0); + + let result = min(15u64, 12u64); + assert!(result == 12, 1); + } + + #[test] + public entry fun test_average() { + let result = average(3u64, 6u64); + assert!(result == 4, 0); + + let result = average(15u64, 12u64); + assert!(result == 13, 0); + } + + #[test] + public entry fun test_average_does_not_overflow() { + let result = average(18446744073709551615, 18446744073709551615); + assert!(result == 18446744073709551615, 0); + } + + #[test] + public entry fun test_pow() { + let result = pow(10u64, 18u64); + assert!(result == 1000000000000000000, 0); + + let result = pow(10u64, 1u64); + assert!(result == 10, 0); + + let result = pow(10u64, 0u64); + assert!(result == 1, 0); + } + + #[test] + public entry fun test_mul_div() { + let tmp: u64 = 1<<63; + assert!(mul_div(tmp,tmp,tmp) == tmp, 0); + + assert!(mul_div(tmp,5,5) == tmp, 0); + // Note that ordering other way is imprecise. + assert!((tmp / 5) * 5 != tmp, 0); + } + + #[test] + public entry fun test_floor_lg2() { + let idx: u8 = 0; + while (idx < 64) { + assert!(floor_log2(1<> 32; + let taylor3 = (taylor2 * taylor1) >> 32; + let expected = expected - ((taylor1 + taylor2 / 2 + taylor3 / 3) << 32) / 2977044472; + // verify it matches to 8 significant digits + assert_approx_the_same((fixed_point32::get_raw_value(res) as u128), expected, 8); + idx = idx + 1; + }; + } + + #[test] + public entry fun test_sqrt() { + let result = sqrt(0); + assert!(result == 0, 0); + + let result = sqrt(1); + assert!(result == 1, 0); + + let result = sqrt(256); + assert!(result == 16, 0); + + let result = sqrt(1<<62); + assert!(result == 1<<31, 0); + + let result = sqrt((((1u128 << 64) - 1) as u64)); + assert!(result == (1u64 << 32) - 1, 0); + + let result = sqrt((1u64 << 63)); + assert!(result == 3037000499, 0); + + let result = sqrt((1u64 << 63) - 1); + assert!(result == 3037000499, 0); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u128, y: u128, precission: u64) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = (pow(10, precission) as u128); + assert!((x - y) * mult < x, 0); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed.move new file mode 100644 index 0000000..b7993a5 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed.move @@ -0,0 +1,139 @@ +/// Standard math utilities missing in the Move Language. +module aptos_std::math_fixed { + use std::fixed_point32; + use std::fixed_point32::FixedPoint32; + use aptos_std::math128; + use aptos_std::math64; + + /// Abort code on overflow + const EOVERFLOW_EXP: u64 = 1; + + /// Natural log 2 in 32 bit fixed point + const LN2: u128 = 2977044472; // ln(2) in fixed 32 representation + const LN2_X_32: u64 = 32 * 2977044472; // ln(2) in fixed 32 representation + + /// Square root of fixed point number + public fun sqrt(x: FixedPoint32): FixedPoint32 { + let y = (fixed_point32::get_raw_value(x) as u128); + fixed_point32::create_from_raw_value((math128::sqrt(y << 32) as u64)) + } + + /// Exponent function with a precission of 9 digits. + public fun exp(x: FixedPoint32): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + fixed_point32::create_from_raw_value((exp_raw(raw_value) as u64)) + } + + /// Because log2 is negative for values < 1 we instead return log2(x) + 32 which + /// is positive for all values of x. + public fun log2_plus_32(x: FixedPoint32): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + math128::log2(raw_value) + } + + public fun ln_plus_32ln2(x: FixedPoint32): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + let x = (fixed_point32::get_raw_value(math128::log2(raw_value)) as u128); + fixed_point32::create_from_raw_value((x * LN2 >> 32 as u64)) + } + + /// Integer power of a fixed point number + public fun pow(x: FixedPoint32, n: u64): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + fixed_point32::create_from_raw_value((pow_raw(raw_value, (n as u128)) as u64)) + } + + /// Specialized function for x * y / z that omits intermediate shifting + public fun mul_div(x: FixedPoint32, y: FixedPoint32, z: FixedPoint32): FixedPoint32 { + let a = fixed_point32::get_raw_value(x); + let b = fixed_point32::get_raw_value(y); + let c = fixed_point32::get_raw_value(z); + fixed_point32::create_from_raw_value (math64::mul_div(a, b, c)) + } + + // Calculate e^x where x and the result are fixed point numbers + fun exp_raw(x: u128): u128 { + // exp(x / 2^32) = 2^(x / (2^32 * ln(2))) = 2^(floor(x / (2^32 * ln(2))) + frac(x / (2^32 * ln(2)))) + let shift_long = x / LN2; + assert!(shift_long <= 31, std::error::invalid_state(EOVERFLOW_EXP)); + let shift = (shift_long as u8); + let remainder = x % LN2; + // At this point we want to calculate 2^(remainder / ln2) << shift + // ln2 = 595528 * 4999 which means + let bigfactor = 595528; + let exponent = remainder / bigfactor; + let x = remainder % bigfactor; + // 2^(remainder / ln2) = (2^(1/4999))^exponent * exp(x / 2^32) + let roottwo = 4295562865; // fixed point representation of 2^(1/4999) + // This has an error of 5000 / 4 10^9 roughly 6 digits of precission + let power = pow_raw(roottwo, exponent); + let eps_correction = 1241009291; + power = power + ((power * eps_correction * exponent) >> 64); + // x is fixed point number smaller than 595528/2^32 < 0.00014 so we need only 2 tayler steps + // to get the 6 digits of precission + let taylor1 = (power * x) >> (32 - shift); + let taylor2 = (taylor1 * x) >> 32; + let taylor3 = (taylor2 * x) >> 32; + (power << shift) + taylor1 + taylor2 / 2 + taylor3 / 6 + } + + // Calculate x to the power of n, where x and the result are fixed point numbers. + fun pow_raw(x: u128, n: u128): u128 { + let res: u256 = 1 << 64; + x = x << 32; + while (n != 0) { + if (n & 1 != 0) { + res = (res * (x as u256)) >> 64; + }; + n = n >> 1; + x = ((((x as u256) * (x as u256)) >> 64) as u128); + }; + ((res >> 32) as u128) + } + + #[test] + public entry fun test_sqrt() { + // Sqrt is based on math128::sqrt and thus most of the testing is done there. + let fixed_base = 1 << 32; + let result = sqrt(fixed_point32::create_from_u64(1)); + assert!(fixed_point32::get_raw_value(result) == fixed_base, 0); + + let result = sqrt(fixed_point32::create_from_u64(2)); + assert_approx_the_same((fixed_point32::get_raw_value(result) as u128), 6074001000, 9); + } + + #[test] + public entry fun test_exp() { + let fixed_base = 1 << 32; + let result = exp_raw(0); + assert!(result == fixed_base, 0); + + let result = exp_raw(fixed_base); + let e = 11674931554; // e in 32 bit fixed point + assert_approx_the_same(result, e, 9); + + let result = exp_raw(10 * fixed_base); + let exp10 = 94602950235157; // e^10 in 32 bit fixed point + assert_approx_the_same(result, exp10, 9); + } + + #[test] + public entry fun test_pow() { + // We use the case of exp + let result = pow_raw(4295562865, 4999); + assert_approx_the_same(result, 1 << 33, 6); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u128, y: u128, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = math128::pow(10, precission); + assert!((x - y) * mult < x, 0); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed64.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed64.move new file mode 100644 index 0000000..2369b6a --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/math_fixed64.move @@ -0,0 +1,142 @@ +/// Standard math utilities missing in the Move Language. + +module aptos_std::math_fixed64 { + use aptos_std::fixed_point64; + use aptos_std::fixed_point64::FixedPoint64; + use aptos_std::math128; + + /// Abort code on overflow + const EOVERFLOW_EXP: u64 = 1; + + /// Natural log 2 in 32 bit fixed point + const LN2: u256 = 12786308645202655660; // ln(2) in fixed 64 representation + + /// Square root of fixed point number + public fun sqrt(x: FixedPoint64): FixedPoint64 { + let y = fixed_point64::get_raw_value(x); + let z = (math128::sqrt(y) << 32 as u256); + z = (z + ((y as u256) << 64) / z) >> 1; + fixed_point64::create_from_raw_value((z as u128)) + } + + /// Exponent function with a precission of 9 digits. + public fun exp(x: FixedPoint64): FixedPoint64 { + let raw_value = (fixed_point64::get_raw_value(x) as u256); + fixed_point64::create_from_raw_value((exp_raw(raw_value) as u128)) + } + + /// Because log2 is negative for values < 1 we instead return log2(x) + 64 which + /// is positive for all values of x. + public fun log2_plus_64(x: FixedPoint64): FixedPoint64 { + let raw_value = (fixed_point64::get_raw_value(x) as u128); + math128::log2_64(raw_value) + } + + public fun ln_plus_32ln2(x: FixedPoint64): FixedPoint64 { + let raw_value = fixed_point64::get_raw_value(x); + let x = (fixed_point64::get_raw_value(math128::log2_64(raw_value)) as u256); + fixed_point64::create_from_raw_value(((x * LN2) >> 64 as u128)) + } + + /// Integer power of a fixed point number + public fun pow(x: FixedPoint64, n: u64): FixedPoint64 { + let raw_value = (fixed_point64::get_raw_value(x) as u256); + fixed_point64::create_from_raw_value((pow_raw(raw_value, (n as u128)) as u128)) + } + + /// Specialized function for x * y / z that omits intermediate shifting + public fun mul_div(x: FixedPoint64, y: FixedPoint64, z: FixedPoint64): FixedPoint64 { + let a = fixed_point64::get_raw_value(x); + let b = fixed_point64::get_raw_value(y); + let c = fixed_point64::get_raw_value(z); + fixed_point64::create_from_raw_value (math128::mul_div(a, b, c)) + } + + // Calculate e^x where x and the result are fixed point numbers + fun exp_raw(x: u256): u256 { + // exp(x / 2^64) = 2^(x / (2^64 * ln(2))) = 2^(floor(x / (2^64 * ln(2))) + frac(x / (2^64 * ln(2)))) + let shift_long = x / LN2; + assert!(shift_long <= 63, std::error::invalid_state(EOVERFLOW_EXP)); + let shift = (shift_long as u8); + let remainder = x % LN2; + // At this point we want to calculate 2^(remainder / ln2) << shift + // ln2 = 580 * 22045359733108027 + let bigfactor = 22045359733108027; + let exponent = remainder / bigfactor; + let x = remainder % bigfactor; + // 2^(remainder / ln2) = (2^(1/580))^exponent * exp(x / 2^64) + let roottwo = 18468802611690918839; // fixed point representation of 2^(1/580) + // 2^(1/580) = roottwo(1 - eps), so the number we seek is roottwo^exponent (1 - eps * exponent) + let power = pow_raw(roottwo, (exponent as u128)); + let eps_correction = 219071715585908898; + power = power - ((power * eps_correction * exponent) >> 128); + // x is fixed point number smaller than bigfactor/2^64 < 0.0011 so we need only 5 tayler steps + // to get the 15 digits of precission + let taylor1 = (power * x) >> (64 - shift); + let taylor2 = (taylor1 * x) >> 64; + let taylor3 = (taylor2 * x) >> 64; + let taylor4 = (taylor3 * x) >> 64; + let taylor5 = (taylor4 * x) >> 64; + let taylor6 = (taylor5 * x) >> 64; + (power << shift) + taylor1 + taylor2 / 2 + taylor3 / 6 + taylor4 / 24 + taylor5 / 120 + taylor6 / 720 + } + + // Calculate x to the power of n, where x and the result are fixed point numbers. + fun pow_raw(x: u256, n: u128): u256 { + let res: u256 = 1 << 64; + while (n != 0) { + if (n & 1 != 0) { + res = (res * x) >> 64; + }; + n = n >> 1; + x = (x * x) >> 64; + }; + res + } + + #[test] + public entry fun test_sqrt() { + // Sqrt is based on math128::sqrt and thus most of the testing is done there. + let fixed_base = 1 << 64; + let result = sqrt(fixed_point64::create_from_u128(1)); + assert!(fixed_point64::get_raw_value(result) == fixed_base, 0); + + let result = sqrt(fixed_point64::create_from_u128(2)); + assert_approx_the_same((fixed_point64::get_raw_value(result) as u256), 26087635650665564424, 16); + } + + #[test] + public entry fun test_exp() { + let fixed_base = 1 << 64; + let result = exp_raw(0); + assert!(result == fixed_base, 0); + + let result = exp_raw(fixed_base); + let e = 50143449209799256682; // e in 32 bit fixed point + assert_approx_the_same(result, e, 16); + + let result = exp_raw(10 * fixed_base); + let exp10 = 406316577365116946489258; // e^10 in 32 bit fixed point + assert_approx_the_same(result, exp10, 16); + } + + #[test] + public entry fun test_pow() { + // We use the case of exp + let result = pow_raw(18468802611690918839, 580); + assert_approx_the_same(result, 1 << 65, 16); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u256, y: u256, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = (math128::pow(10, precission) as u256); + assert!((x - y) * mult < x, 0); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/multi_ed25519.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/multi_ed25519.move new file mode 100644 index 0000000..903b1d0 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/multi_ed25519.move @@ -0,0 +1,482 @@ +/// Exports MultiEd25519 multi-signatures in Move. +/// This module has the exact same interface as the Ed25519 module. + +module aptos_std::multi_ed25519 { + use std::bcs; + use std::error; + use std::features; + use std::option::{Self, Option}; + use std::vector; + use aptos_std::ed25519; + + // + // Error codes + // + + /// Wrong number of bytes were given as input when deserializing an Ed25519 public key. + const E_WRONG_PUBKEY_SIZE: u64 = 1; + + /// Wrong number of bytes were given as input when deserializing an Ed25519 signature. + const E_WRONG_SIGNATURE_SIZE: u64 = 2; + + /// The threshold must be in the range `[1, n]`, where n is the total number of signers. + const E_INVALID_THRESHOLD_OR_NUMBER_OF_SIGNERS: u64 = 3; + + /// The native functions have not been rolled out yet. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 4; + + // + // Constants + // + + /// The identifier of the MultiEd25519 signature scheme, which is used when deriving Aptos authentication keys by hashing + /// it together with an MultiEd25519 public key. + const SIGNATURE_SCHEME_ID: u8 = 1; + + /// The size of an individual Ed25519 public key, in bytes. + /// (A MultiEd25519 public key consists of several of these, plus the threshold.) + const INDIVIDUAL_PUBLIC_KEY_NUM_BYTES: u64 = 32; + + /// The size of an individual Ed25519 signature, in bytes. + /// (A MultiEd25519 signature consists of several of these, plus the signer bitmap.) + const INDIVIDUAL_SIGNATURE_NUM_BYTES: u64 = 64; + + /// When serializing a MultiEd25519 public key, the threshold k will be encoded using this many bytes. + const THRESHOLD_SIZE_BYTES: u64 = 1; + + /// When serializing a MultiEd25519 signature, the bitmap that indicates the signers will be encoded using this many + /// bytes. + const BITMAP_NUM_OF_BYTES: u64 = 4; + + /// Max number of ed25519 public keys allowed in multi-ed25519 keys + const MAX_NUMBER_OF_PUBLIC_KEYS: u64 = 32; + + // + // Structs + // + #[test_only] + struct SecretKey has drop { + bytes: vector, + } + + /// An *unvalidated*, k out of n MultiEd25519 public key. The `bytes` field contains (1) several chunks of + /// `ed25519::PUBLIC_KEY_NUM_BYTES` bytes, each encoding a Ed25519 PK, and (2) a single byte encoding the threshold k. + /// *Unvalidated* means there is no guarantee that the underlying PKs are valid elliptic curve points of non-small + /// order. + struct UnvalidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A *validated* k out of n MultiEd25519 public key. *Validated* means that all the underlying PKs will be + /// elliptic curve points that are NOT of small-order. It does not necessarily mean they will be prime-order points. + /// This struct encodes the public key exactly as `UnvalidatedPublicKey`. + /// + /// For now, this struct is not used in any verification functions, but it might be in the future. + struct ValidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A purported MultiEd25519 multi-signature that can be verified via `signature_verify_strict` or + /// `signature_verify_strict_t`. The `bytes` field contains (1) several chunks of `ed25519::SIGNATURE_NUM_BYTES` + /// bytes, each encoding a Ed25519 signature, and (2) a `BITMAP_NUM_OF_BYTES`-byte bitmap encoding the signer + /// identities. + struct Signature has copy, drop, store { + bytes: vector + } + + // + // Functions + // + + #[test_only] + public fun generate_keys(threshold: u8, n: u8): (SecretKey, ValidatedPublicKey) { + assert!(1 <= threshold && threshold <= n, error::invalid_argument(E_INVALID_THRESHOLD_OR_NUMBER_OF_SIGNERS)); + let (sk_bytes, pk_bytes) = generate_keys_internal(threshold, n); + let sk = SecretKey { + bytes: sk_bytes + }; + let pk = ValidatedPublicKey { + bytes: pk_bytes + }; + (sk, pk) + } + + #[test_only] + public fun sign_arbitrary_bytes(sk: &SecretKey, msg: vector) : Signature { + Signature { + bytes: sign_internal(sk.bytes, msg) + } + } + + #[test_only] + public fun sign_struct(sk: &SecretKey, data: T) : Signature { + let encoded = ed25519::new_signed_message(data); + Signature { + bytes: sign_internal(sk.bytes, bcs::to_bytes(&encoded)), + } + } + + /// Parses the input 32 bytes as an *unvalidated* MultiEd25519 public key. + /// + /// NOTE: This function could have also checked that the # of sub-PKs is > 0, but it did not. However, since such + /// invalid PKs are rejected during signature verification (see `bugfix_unvalidated_pk_from_zero_subpks`) they + /// will not cause problems. + /// + /// We could fix this API by adding a new one that checks the # of sub-PKs is > 0, but it is likely not a good idea + /// to reproduce the PK validation logic in Move. We should not have done so in the first place. Instead, we will + /// leave it as is and continue assuming `UnvalidatedPublicKey` objects could be invalid PKs that will safely be + /// rejected during signature verification. + public fun new_unvalidated_public_key_from_bytes(bytes: vector): UnvalidatedPublicKey { + let len = vector::length(&bytes); + let num_sub_pks = len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES; + + assert!(num_sub_pks <= MAX_NUMBER_OF_PUBLIC_KEYS, error::invalid_argument(E_WRONG_PUBKEY_SIZE)); + assert!(len % INDIVIDUAL_PUBLIC_KEY_NUM_BYTES == THRESHOLD_SIZE_BYTES, error::invalid_argument(E_WRONG_PUBKEY_SIZE)); + UnvalidatedPublicKey { bytes } + } + + /// DEPRECATED: Use `new_validated_public_key_from_bytes_v2` instead. See `public_key_validate_internal` comments. + /// + /// (Incorrectly) parses the input bytes as a *validated* MultiEd25519 public key. + public fun new_validated_public_key_from_bytes(bytes: vector): Option { + // Note that `public_key_validate_internal` will check that `vector::length(&bytes) / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES <= MAX_NUMBER_OF_PUBLIC_KEYS`. + if (vector::length(&bytes) % INDIVIDUAL_PUBLIC_KEY_NUM_BYTES == THRESHOLD_SIZE_BYTES && + public_key_validate_internal(bytes)) { + option::some(ValidatedPublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Parses the input bytes as a *validated* MultiEd25519 public key (see `public_key_validate_internal_v2`). + public fun new_validated_public_key_from_bytes_v2(bytes: vector): Option { + if (!features::multi_ed25519_pk_validate_v2_enabled()) { + abort(error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + if (public_key_validate_v2_internal(bytes)) { + option::some(ValidatedPublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Parses the input bytes as a purported MultiEd25519 multi-signature. + public fun new_signature_from_bytes(bytes: vector): Signature { + assert!(vector::length(&bytes) % INDIVIDUAL_SIGNATURE_NUM_BYTES == BITMAP_NUM_OF_BYTES, error::invalid_argument(E_WRONG_SIGNATURE_SIZE)); + Signature { bytes } + } + + /// Converts a ValidatedPublicKey to an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_to_unvalidated(pk: &ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Moves a ValidatedPublicKey into an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_into_unvalidated(pk: ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Serializes an UnvalidatedPublicKey struct to 32-bytes. + public fun unvalidated_public_key_to_bytes(pk: &UnvalidatedPublicKey): vector { + pk.bytes + } + + /// Serializes a ValidatedPublicKey struct to 32-bytes. + public fun validated_public_key_to_bytes(pk: &ValidatedPublicKey): vector { + pk.bytes + } + + /// Serializes a Signature struct to 64-bytes. + public fun signature_to_bytes(sig: &Signature): vector { + sig.bytes + } + + /// DEPRECATED: Use `public_key_validate_v2` instead. See `public_key_validate_internal` comments. + /// + /// Takes in an *unvalidated* public key and attempts to validate it. + /// Returns `Some(ValidatedPublicKey)` if successful and `None` otherwise. + public fun public_key_validate(pk: &UnvalidatedPublicKey): Option { + new_validated_public_key_from_bytes(pk.bytes) + } + + /// Takes in an *unvalidated* public key and attempts to validate it. + /// Returns `Some(ValidatedPublicKey)` if successful and `None` otherwise. + public fun public_key_validate_v2(pk: &UnvalidatedPublicKey): Option { + new_validated_public_key_from_bytes_v2(pk.bytes) + } + + /// Verifies a purported MultiEd25519 `multisignature` under an *unvalidated* `public_key` on the specified `message`. + /// This call will validate the public key by checking it is NOT in the small subgroup. + public fun signature_verify_strict( + multisignature: &Signature, + public_key: &UnvalidatedPublicKey, + message: vector + ): bool { + signature_verify_strict_internal(multisignature.bytes, public_key.bytes, message) + } + + /// This function is used to verify a multi-signature on any BCS-serializable type T. For now, it is used to verify the + /// proof of private key ownership when rotating authentication keys. + public fun signature_verify_strict_t(multisignature: &Signature, public_key: &UnvalidatedPublicKey, data: T): bool { + let encoded = ed25519::new_signed_message(data); + + signature_verify_strict_internal(multisignature.bytes, public_key.bytes, bcs::to_bytes(&encoded)) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun unvalidated_public_key_to_authentication_key(pk: &UnvalidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Returns the number n of sub-PKs in an unvalidated t-out-of-n MultiEd25519 PK. + /// If this `UnvalidatedPublicKey` would pass validation in `public_key_validate`, then the returned # of sub-PKs + /// can be relied upon as correct. + /// + /// We provide this API as a cheaper alternative to calling `public_key_validate` and then `validated_public_key_num_sub_pks` + /// when the input `pk` is known to be valid. + public fun unvalidated_public_key_num_sub_pks(pk: &UnvalidatedPublicKey): u8 { + let len = vector::length(&pk.bytes); + + ((len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES) as u8) + } + + /// Returns the number t of sub-PKs in an unvalidated t-out-of-n MultiEd25519 PK (i.e., the threshold) or `None` + /// if `bytes` does not correctly encode such a PK. + public fun unvalidated_public_key_threshold(pk: &UnvalidatedPublicKey): Option { + check_and_get_threshold(pk.bytes) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun validated_public_key_to_authentication_key(pk: &ValidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Returns the number n of sub-PKs in a validated t-out-of-n MultiEd25519 PK. + /// Since the format of this PK has been validated, the returned # of sub-PKs is guaranteed to be correct. + public fun validated_public_key_num_sub_pks(pk: &ValidatedPublicKey): u8 { + let len = vector::length(&pk.bytes); + + ((len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES) as u8) + } + + /// Returns the number t of sub-PKs in a validated t-out-of-n MultiEd25519 PK (i.e., the threshold). + public fun validated_public_key_threshold(pk: &ValidatedPublicKey): u8 { + let len = vector::length(&pk.bytes); + let threshold_byte = *vector::borrow(&pk.bytes, len - 1); + + threshold_byte + } + + /// Checks that the serialized format of a t-out-of-n MultiEd25519 PK correctly encodes 1 <= n <= 32 sub-PKs. + /// (All `ValidatedPublicKey` objects are guaranteed to pass this check.) + /// Returns the threshold t <= n of the PK. + public fun check_and_get_threshold(bytes: vector): Option { + let len = vector::length(&bytes); + if (len == 0) { + return option::none() + }; + + let threshold_num_of_bytes = len % INDIVIDUAL_PUBLIC_KEY_NUM_BYTES; + let num_of_keys = len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES; + let threshold_byte = *vector::borrow(&bytes, len - 1); + + if (num_of_keys == 0 || num_of_keys > MAX_NUMBER_OF_PUBLIC_KEYS || threshold_num_of_bytes != 1) { + return option::none() + } else if (threshold_byte == 0 || threshold_byte > (num_of_keys as u8)) { + return option::none() + } else { + return option::some(threshold_byte) + } + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + fun public_key_bytes_to_authentication_key(pk_bytes: vector): vector { + vector::push_back(&mut pk_bytes, SIGNATURE_SCHEME_ID); + std::hash::sha3_256(pk_bytes) + } + + // + // Native functions + // + + /// DEPRECATED: Use `public_key_validate_internal_v2` instead. This function was NOT correctly implemented: + /// + /// 1. It does not check that the # of sub public keys is > 0, which leads to invalid `ValidatedPublicKey` objects + /// against which no signature will verify, since `signature_verify_strict_internal` will reject such invalid PKs. + /// This is not a security issue, but a correctness issue. See `bugfix_validated_pk_from_zero_subpks`. + /// 2. It charges too much gas: if the first sub-PK is invalid, it will charge for verifying all remaining sub-PKs. + /// + /// DEPRECATES: + /// - new_validated_public_key_from_bytes + /// - public_key_validate + /// + /// Return `true` if the bytes in `public_key` can be parsed as a valid MultiEd25519 public key: i.e., all underlying + /// PKs pass point-on-curve and not-in-small-subgroup checks. + /// Returns `false` otherwise. + native fun public_key_validate_internal(bytes: vector): bool; + + /// Return `true` if the bytes in `public_key` can be parsed as a valid MultiEd25519 public key: i.e., all underlying + /// sub-PKs pass point-on-curve and not-in-small-subgroup checks. + /// Returns `false` otherwise. + native fun public_key_validate_v2_internal(bytes: vector): bool; + + /// Return true if the MultiEd25519 `multisignature` on `message` verifies against the MultiEd25519 `public_key`. + /// Returns `false` if either: + /// - The PKs in `public_key` do not all pass points-on-curve or not-in-small-subgroup checks, + /// - The signatures in `multisignature` do not all pass points-on-curve or not-in-small-subgroup checks, + /// - the `multisignature` on `message` does not verify. + native fun signature_verify_strict_internal( + multisignature: vector, + public_key: vector, + message: vector + ): bool; + + #[test_only] + native fun generate_keys_internal(threshold: u8, n: u8): (vector,vector); + + #[test_only] + native fun sign_internal(sk: vector, message: vector): vector; + + // + // Tests + // + + #[test_only] + struct TestMessage has copy, drop { + foo: vector, + bar: u64, + } + + #[test_only] + public fun maul_first_signature(sig: &mut Signature) { + let first_sig_byte = vector::borrow_mut(&mut sig.bytes, 0); + *first_sig_byte = *first_sig_byte ^ 0xff; + } + + + #[test(fx = @std)] + fun bugfix_validated_pk_from_zero_subpks(fx: signer) { + features::change_feature_flags(&fx, vector[ features::multi_ed25519_pk_validate_v2_feature()], vector[]); + let bytes = vector[1u8]; + assert!(vector::length(&bytes) == 1, 1); + + // Try deserializing a MultiEd25519 `ValidatedPublicKey` with 0 Ed25519 sub-PKs and 1 threshold byte. + // This would ideally NOT succeed, but it currently does. Regardless, such invalid PKs will be safely dismissed + // during signature verification. + let some = new_validated_public_key_from_bytes(bytes); + assert!(option::is_none(&check_and_get_threshold(bytes)), 1); // ground truth + assert!(option::is_some(&some), 2); // incorrect + + // In contrast, the v2 API will fail deserializing, as it should. + let none = new_validated_public_key_from_bytes_v2(bytes); + assert!(option::is_none(&none), 3); + } + + #[test(fx = @std)] + fun test_validated_pk_without_threshold_byte(fx: signer) { + features::change_feature_flags(&fx, vector[ features::multi_ed25519_pk_validate_v2_feature()], vector[]); + + let (_, subpk) = ed25519::generate_keys(); + let bytes = ed25519::validated_public_key_to_bytes(&subpk); + assert!(vector::length(&bytes) == INDIVIDUAL_PUBLIC_KEY_NUM_BYTES, 1); + + // Try deserializing a MultiEd25519 `ValidatedPublicKey` with 1 Ed25519 sub-PKs but no threshold byte, which + // will not succeed, + let none = new_validated_public_key_from_bytes(bytes); + assert!(option::is_none(&check_and_get_threshold(bytes)), 1); // ground truth + assert!(option::is_none(&none), 2); // correct + + // Similarly, the v2 API will also fail deserializing. + let none = new_validated_public_key_from_bytes_v2(bytes); + assert!(option::is_none(&none), 3); // also correct + } + + #[test(fx = @std)] + fun test_validated_pk_from_small_order_subpk(fx: signer) { + features::change_feature_flags(&fx, vector[ features::multi_ed25519_pk_validate_v2_feature()], vector[]); + let torsion_point_with_threshold_1 = vector[ + 1, 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, + ]; + + assert!(option::extract(&mut check_and_get_threshold(torsion_point_with_threshold_1)) == 1, 1); + + // Try deserializing a MultiEd25519 `ValidatedPublicKey` with 1 Ed25519 sub-PKs and 1 threshold byte, as it should, + // except the sub-PK is of small order. This should not succeed, + let none = new_validated_public_key_from_bytes(torsion_point_with_threshold_1); + assert!(option::is_none(&none), 2); + + // Similarly, the v2 API will also fail deserializing. + let none = new_validated_public_key_from_bytes_v2(torsion_point_with_threshold_1); + assert!(option::is_none(&none), 3); + } + + #[test] + fun test_gen_sign_verify() { + let thresholds = vector[1, 1, 2, 2, 3, 15,]; // the thresholds, implicitly encoded in the public keys + let party_counts = vector[1, 2, 2, 3, 10, 32,]; + let test_case_count = vector::length(&party_counts); + let test_case_idx = 0; + + while (test_case_idx < test_case_count) { + let threshold = *vector::borrow(&thresholds, test_case_idx); + let group_size = *vector::borrow(&party_counts, test_case_idx); + + let (sk, pk) = generate_keys(threshold, group_size); + assert!(validated_public_key_threshold(&pk) == threshold, 1); + assert!(validated_public_key_num_sub_pks(&pk) == group_size, 2); + assert!(public_key_validate_v2_internal(pk.bytes), 3); + + let upk = public_key_into_unvalidated(pk); + assert!(option::extract(&mut unvalidated_public_key_threshold(&upk)) == threshold, 4); + assert!(unvalidated_public_key_num_sub_pks(&upk) == group_size, 5); + + let msg1 = b"Hello Aptos!"; + let sig1 = sign_arbitrary_bytes(&sk, msg1); + assert!(signature_verify_strict(&sig1, &upk, msg1), 6); + + let obj2 = TestMessage { + foo: b"Hello Move!", + bar: 64, + }; + let sig2 = sign_struct(&sk, copy obj2); + assert!(signature_verify_strict_t(&sig2, &upk, copy obj2), 7); + + test_case_idx = test_case_idx + 1; + } + } + + #[test] + fun test_threshold_not_met_rejection() { + let (sk,pk) = generate_keys(4, 5); + assert!(validated_public_key_threshold(&pk) == 4, 1); + assert!(validated_public_key_num_sub_pks(&pk) == 5, 2); + assert!(public_key_validate_v2_internal(pk.bytes), 3); + + let upk = public_key_into_unvalidated(pk); + assert!(option::extract(&mut unvalidated_public_key_threshold(&upk)) == 4, 4); + assert!(unvalidated_public_key_num_sub_pks(&upk) == 5, 5); + + let msg1 = b"Hello Aptos!"; + let sig1 = sign_arbitrary_bytes(&sk, msg1); + maul_first_signature(&mut sig1); + assert!(!signature_verify_strict(&sig1, &upk, msg1), 6); + + let obj2 = TestMessage { + foo: b"Hello Move!", + bar: 64, + }; + let sig2 = sign_struct(&sk, copy obj2); + maul_first_signature(&mut sig2); + assert!(!signature_verify_strict_t(&sig2, &upk, copy obj2), 7); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64.move new file mode 100644 index 0000000..f1aaea9 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64.move @@ -0,0 +1,571 @@ +/// +/// Simple module for tracking and calculating shares of a pool of coins. The shares are worth more as the total coins in +/// the pool increases. New shareholder can buy more shares or redeem their existing shares. +/// +/// Example flow: +/// 1. Pool start outs empty. +/// 2. Shareholder A buys in with 1000 coins. A will receive 1000 shares in the pool. Pool now has 1000 total coins and +/// 1000 total shares. +/// 3. Pool appreciates in value from rewards and now has 2000 coins. A's 1000 shares are now worth 2000 coins. +/// 4. Shareholder B now buys in with 1000 coins. Since before the buy in, each existing share is worth 2 coins, B will +/// receive 500 shares in exchange for 1000 coins. Pool now has 1500 shares and 3000 coins. +/// 5. Pool appreciates in value from rewards and now has 6000 coins. +/// 6. A redeems 500 shares. Each share is worth 6000 / 1500 = 4. A receives 2000 coins. Pool has 4000 coins and 1000 +/// shares left. +/// +module aptos_std::pool_u64 { + use aptos_std::simple_map::{Self, SimpleMap}; + use std::error; + use std::vector; + + /// Shareholder not present in pool. + const ESHAREHOLDER_NOT_FOUND: u64 = 1; + /// There are too many shareholders in the pool. + const ETOO_MANY_SHAREHOLDERS: u64 = 2; + /// Cannot destroy non-empty pool. + const EPOOL_IS_NOT_EMPTY: u64 = 3; + /// Cannot redeem more shares than the shareholder has in the pool. + const EINSUFFICIENT_SHARES: u64 = 4; + /// Shareholder cannot have more than u64.max shares. + const ESHAREHOLDER_SHARES_OVERFLOW: u64 = 5; + /// Pool's total coins cannot exceed u64.max. + const EPOOL_TOTAL_COINS_OVERFLOW: u64 = 6; + /// Pool's total shares cannot exceed u64.max. + const EPOOL_TOTAL_SHARES_OVERFLOW: u64 = 7; + + const MAX_U64: u64 = 18446744073709551615; + + struct Pool has store { + shareholders_limit: u64, + total_coins: u64, + total_shares: u64, + shares: SimpleMap, + shareholders: vector
, + // Default to 1. This can be used to minimize rounding errors when computing shares and coins amount. + // However, users need to make sure the coins amount don't overflow when multiplied by the scaling factor. + scaling_factor: u64, + } + + /// Create a new pool. + public fun new(shareholders_limit: u64): Pool { + // Default to a scaling factor of 1 (effectively no scaling). + create_with_scaling_factor(shareholders_limit, 1) + } + + #[deprecated] + /// Deprecated. Use `new` instead. + /// Create a new pool. + public fun create(shareholders_limit: u64): Pool { + new(shareholders_limit) + } + + /// Create a new pool with custom `scaling_factor`. + public fun create_with_scaling_factor(shareholders_limit: u64, scaling_factor: u64): Pool { + Pool { + shareholders_limit, + total_coins: 0, + total_shares: 0, + shares: simple_map::create(), + shareholders: vector::empty
(), + scaling_factor, + } + } + + /// Destroy an empty pool. This will fail if the pool has any balance of coins. + public fun destroy_empty(pool: Pool) { + assert!(pool.total_coins == 0, error::invalid_state(EPOOL_IS_NOT_EMPTY)); + let Pool { + shareholders_limit: _, + total_coins: _, + total_shares: _, + shares: _, + shareholders: _, + scaling_factor: _, + } = pool; + } + + /// Return `pool`'s total balance of coins. + public fun total_coins(pool: &Pool): u64 { + pool.total_coins + } + + /// Return the total number of shares across all shareholders in `pool`. + public fun total_shares(pool: &Pool): u64 { + pool.total_shares + } + + /// Return true if `shareholder` is in `pool`. + public fun contains(pool: &Pool, shareholder: address): bool { + simple_map::contains_key(&pool.shares, &shareholder) + } + + /// Return the number of shares of `stakeholder` in `pool`. + public fun shares(pool: &Pool, shareholder: address): u64 { + if (contains(pool, shareholder)) { + *simple_map::borrow(&pool.shares, &shareholder) + } else { + 0 + } + } + + /// Return the balance in coins of `shareholder` in `pool.` + public fun balance(pool: &Pool, shareholder: address): u64 { + let num_shares = shares(pool, shareholder); + shares_to_amount(pool, num_shares) + } + + /// Return the list of shareholders in `pool`. + public fun shareholders(pool: &Pool): vector
{ + pool.shareholders + } + + /// Return the number of shareholders in `pool`. + public fun shareholders_count(pool: &Pool): u64 { + vector::length(&pool.shareholders) + } + + /// Update `pool`'s total balance of coins. + public fun update_total_coins(pool: &mut Pool, new_total_coins: u64) { + pool.total_coins = new_total_coins; + } + + /// Allow an existing or new shareholder to add their coins to the pool in exchange for new shares. + public fun buy_in(pool: &mut Pool, shareholder: address, coins_amount: u64): u64 { + if (coins_amount == 0) return 0; + + let new_shares = amount_to_shares(pool, coins_amount); + assert!(MAX_U64 - pool.total_coins >= coins_amount, error::invalid_argument(EPOOL_TOTAL_COINS_OVERFLOW)); + assert!(MAX_U64 - pool.total_shares >= new_shares, error::invalid_argument(EPOOL_TOTAL_COINS_OVERFLOW)); + + pool.total_coins = pool.total_coins + coins_amount; + pool.total_shares = pool.total_shares + new_shares; + add_shares(pool, shareholder, new_shares); + new_shares + } + + /// Add the number of shares directly for `shareholder` in `pool`. + /// This would dilute other shareholders if the pool's balance of coins didn't change. + fun add_shares(pool: &mut Pool, shareholder: address, new_shares: u64): u64 { + if (contains(pool, shareholder)) { + let existing_shares = simple_map::borrow_mut(&mut pool.shares, &shareholder); + let current_shares = *existing_shares; + assert!(MAX_U64 - current_shares >= new_shares, error::invalid_argument(ESHAREHOLDER_SHARES_OVERFLOW)); + + *existing_shares = current_shares + new_shares; + *existing_shares + } else if (new_shares > 0) { + assert!( + vector::length(&pool.shareholders) < pool.shareholders_limit, + error::invalid_state(ETOO_MANY_SHAREHOLDERS), + ); + + vector::push_back(&mut pool.shareholders, shareholder); + simple_map::add(&mut pool.shares, shareholder, new_shares); + new_shares + } else { + new_shares + } + } + + /// Allow `shareholder` to redeem their shares in `pool` for coins. + public fun redeem_shares(pool: &mut Pool, shareholder: address, shares_to_redeem: u64): u64 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= shares_to_redeem, error::invalid_argument(EINSUFFICIENT_SHARES)); + + if (shares_to_redeem == 0) return 0; + + let redeemed_coins = shares_to_amount(pool, shares_to_redeem); + pool.total_coins = pool.total_coins - redeemed_coins; + pool.total_shares = pool.total_shares - shares_to_redeem; + deduct_shares(pool, shareholder, shares_to_redeem); + + redeemed_coins + } + + /// Transfer shares from `shareholder_1` to `shareholder_2`. + public fun transfer_shares( + pool: &mut Pool, + shareholder_1: address, + shareholder_2: address, + shares_to_transfer: u64, + ) { + assert!(contains(pool, shareholder_1), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder_1) >= shares_to_transfer, error::invalid_argument(EINSUFFICIENT_SHARES)); + if (shares_to_transfer == 0) return; + + deduct_shares(pool, shareholder_1, shares_to_transfer); + add_shares(pool, shareholder_2, shares_to_transfer); + } + + /// Directly deduct `shareholder`'s number of shares in `pool` and return the number of remaining shares. + fun deduct_shares(pool: &mut Pool, shareholder: address, num_shares: u64): u64 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= num_shares, error::invalid_argument(EINSUFFICIENT_SHARES)); + + let existing_shares = simple_map::borrow_mut(&mut pool.shares, &shareholder); + *existing_shares = *existing_shares - num_shares; + + // Remove the shareholder completely if they have no shares left. + let remaining_shares = *existing_shares; + if (remaining_shares == 0) { + let (_, shareholder_index) = vector::index_of(&pool.shareholders, &shareholder); + vector::remove(&mut pool.shareholders, shareholder_index); + simple_map::remove(&mut pool.shares, &shareholder); + }; + + remaining_shares + } + + /// Return the number of new shares `coins_amount` can buy in `pool`. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares(pool: &Pool, coins_amount: u64): u64 { + amount_to_shares_with_total_coins(pool, coins_amount, pool.total_coins) + } + + /// Return the number of new shares `coins_amount` can buy in `pool` with a custom total coins number. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares_with_total_coins(pool: &Pool, coins_amount: u64, total_coins: u64): u64 { + // No shares yet so amount is worth the same number of shares. + if (pool.total_coins == 0 || pool.total_shares == 0) { + // Multiply by scaling factor to minimize rounding errors during internal calculations for buy ins/redeems. + // This can overflow but scaling factor is expected to be chosen carefully so this would not overflow. + coins_amount * pool.scaling_factor + } else { + // Shares price = total_coins / total existing shares. + // New number of shares = new_amount / shares_price = new_amount * existing_shares / total_amount. + // We rearrange the calc and do multiplication first to avoid rounding errors. + multiply_then_divide(pool, coins_amount, pool.total_shares, total_coins) + } + } + + /// Return the number of coins `shares` are worth in `pool`. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount(pool: &Pool, shares: u64): u64 { + shares_to_amount_with_total_coins(pool, shares, pool.total_coins) + } + + /// Return the number of coins `shares` are worth in `pool` with a custom total coins number. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount_with_total_coins(pool: &Pool, shares: u64, total_coins: u64): u64 { + // No shares or coins yet so shares are worthless. + if (pool.total_coins == 0 || pool.total_shares == 0) { + 0 + } else { + // Shares price = total_coins / total existing shares. + // Shares worth = shares * shares price = shares * total_coins / total existing shares. + // We rearrange the calc and do multiplication first to avoid rounding errors. + multiply_then_divide(pool, shares, total_coins, pool.total_shares) + } + } + + public fun multiply_then_divide(_pool: &Pool, x: u64, y: u64, z: u64): u64 { + let result = (to_u128(x) * to_u128(y)) / to_u128(z); + (result as u64) + } + + fun to_u128(num: u64): u128 { + (num as u128) + } + + #[test_only] + public fun destroy_pool(pool: Pool) { + let Pool { + shareholders_limit: _, + total_coins: _, + total_shares: _, + shares: _, + shareholders: _, + scaling_factor: _, + } = pool; + } + + #[test] + public entry fun test_buy_in_and_redeem() { + let pool = new(5); + + // Shareholders 1 and 2 buy in first. + buy_in(&mut pool, @1, 1000); + buy_in(&mut pool, @2, 2000); + assert!(shareholders_count(&pool) == 2, 0); + assert!(total_coins(&pool) == 3000, 1); + assert!(total_shares(&pool) == 3000, 2); + assert!(shares(&pool, @1) == 1000, 3); + assert!(shares(&pool, @2) == 2000, 4); + assert!(balance(&pool, @1) == 1000, 5); + assert!(balance(&pool, @2) == 2000, 6); + + // Pool increases in value. + update_total_coins(&mut pool, 5000); + assert!(shares(&pool, @1) == 1000, 7); + assert!(shares(&pool, @2) == 2000, 8); + let expected_balance_1 = 1000 * 5000 / 3000; + assert!(balance(&pool, @1) == expected_balance_1, 9); + let expected_balance_2 = 2000 * 5000 / 3000; + assert!(balance(&pool, @2) == expected_balance_2, 10); + + // Shareholder 3 buys in into the 5000-coin pool with 1000 coins. There are 3000 existing shares. + let expected_shares = 1000 * 3000 / 5000; + buy_in(&mut pool, @3, 1000); + assert!(shares(&pool, @3) == expected_shares, 11); + assert!(balance(&pool, @3) == 1000, 12); + + // Pool increases more in value. + update_total_coins(&mut pool, 8000); + + // Shareholders 1 and 2 redeem. + let all_shares = 3000 + expected_shares; + assert!(total_shares(&pool) == all_shares, 13); + let expected_value_per_500_shares = 500 * 8000 / all_shares; + assert!(redeem_shares(&mut pool, @1, 500) == expected_value_per_500_shares, 14); + assert!(redeem_shares(&mut pool, @1, 500) == expected_value_per_500_shares, 15); + assert!(redeem_shares(&mut pool, @2, 2000) == expected_value_per_500_shares * 4, 16); + + // Due to a very small rounding error of 1, shareholder 3 actually has 1 more coin. + let shareholder_3_balance = expected_value_per_500_shares * 6 / 5 + 1; + assert!(balance(&pool, @3) == shareholder_3_balance, 17); + assert!(total_coins(&pool) == shareholder_3_balance, 18); + assert!(shareholders_count(&pool) == 1, 19); + let num_shares_3 = shares(&pool, @3); + assert!(redeem_shares(&mut pool, @3, num_shares_3) == shareholder_3_balance, 20); + + // Nothing left. + assert!(shareholders_count(&pool) == 0, 21); + destroy_empty(pool); + } + + #[test] + #[expected_failure(abort_code = 196611, location = Self)] + public entry fun test_destroy_empty_should_fail_if_not_empty() { + let pool = new(1); + update_total_coins(&mut pool, 100); + destroy_empty(pool); + } + + #[test] + public entry fun test_buy_in_and_redeem_large_numbers() { + let pool = new(2); + let half_max_u64 = MAX_U64 / 2; + let shares_1 = buy_in(&mut pool, @1, half_max_u64); + assert!(shares_1 == half_max_u64, 0); + let shares_2 = buy_in(&mut pool, @2, half_max_u64 + 1); + assert!(shares_2 == half_max_u64 + 1, 1); + assert!(total_shares(&pool) == MAX_U64, 2); + assert!(total_coins(&pool) == MAX_U64, 3); + assert!(redeem_shares(&mut pool, @1, shares_1) == half_max_u64, 4); + assert!(redeem_shares(&mut pool, @2, shares_2) == half_max_u64 + 1, 5); + destroy_empty(pool); + } + + #[test] + public entry fun test_buy_in_and_redeem_large_numbers_with_scaling_factor() { + let scaling_factor = 100; + let pool = create_with_scaling_factor(2, scaling_factor); + let coins_amount = MAX_U64 / 100; + let shares = buy_in(&mut pool, @1, coins_amount); + assert!(total_shares(&pool) == coins_amount * scaling_factor, 0); + assert!(total_coins(&pool) == coins_amount, 1); + assert!(redeem_shares(&mut pool, @1, shares) == coins_amount, 2); + destroy_empty(pool); + } + + #[test] + public entry fun test_buy_in_zero_amount() { + let pool = new(2); + buy_in(&mut pool, @1, 100); + assert!(buy_in(&mut pool, @2, 0) == 0, 0); + assert!(total_shares(&pool) == shares(&pool, @1), 1); + assert!(shareholders_count(&pool) == 1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_buy_in_with_small_coins_amount() { + let pool = new(2); + // Shareholder 1 buys in with 1e17 coins. + buy_in(&mut pool, @1, 100000000000000000); + // Shareholder 2 buys in with a very small amount. + assert!(buy_in(&mut pool, @2, 1) == 1, 0); + // Pool's total coins increases by 20%. Shareholder 2 shouldn't see any actual balance increase as it gets + // rounded down. + let total_coins = total_coins(&pool); + update_total_coins(&mut pool, total_coins * 6 / 5); + // Minus 1 due to rounding error. + assert!(balance(&pool, @1) == 100000000000000000 * 6 / 5 - 1, 1); + assert!(balance(&pool, @2) == 1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_zero_shares_should_not_add_shareholder() { + let pool = new(1); + update_total_coins(&mut pool, 1000); + assert!(add_shares(&mut pool, @1, 0) == 0, 0); + assert!(shareholders_count(&pool) == 0, 1); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_zero_shares_returns_existing_number_of_shares() { + let pool = new(1); + update_total_coins(&mut pool, 1000); + add_shares(&mut pool, @1, 1); + assert!(shares(&pool, @1) == add_shares(&mut pool, @1, 0), 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_shares_existing_shareholder() { + let pool = new(1); + update_total_coins(&mut pool, 1000); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @1, 2); + assert!(shares(&mut pool, @1) == 3, 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_shares_new_shareholder() { + let pool = new(2); + update_total_coins(&mut pool, 1000); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + assert!(shares(&mut pool, @1) == 1, 0); + assert!(shares(&mut pool, @2) == 2, 1); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 196610, location = Self)] + public entry fun test_add_shares_should_enforce_shareholder_limit() { + let pool = new(2); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + add_shares(&mut pool, @3, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_shares_should_work_after_reducing_shareholders_below_limit() { + let pool = new(3); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + deduct_shares(&mut pool, @2, 2); + add_shares(&mut pool, @3, 3); + assert!(shares(&pool, @3) == 3, 0); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65537, location = Self)] + public entry fun test_redeem_shares_non_existent_shareholder() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + redeem_shares(&mut pool, @2, 1); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65540, location = Self)] + public entry fun test_redeem_shares_insufficient_shares() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + redeem_shares(&mut pool, @1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_redeem_small_number_of_shares() { + let pool = new(2); + // 1e17 shares and coins. + buy_in(&mut pool, @1, 100000000000000000); + buy_in(&mut pool, @2, 100000000000000000); + assert!(redeem_shares(&mut pool, @1, 1) == 1, 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_redeem_zero_shares() { + let pool = new(2); + buy_in(&mut pool, @1, 1); + assert!(redeem_shares(&mut pool, @1, 0) == 0, 0); + assert!(shares(&pool, @1) == 1, 1); + assert!(total_coins(&pool) == 1, 2); + assert!(total_shares(&pool) == 1, 3); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65537, location = Self)] + public entry fun test_deduct_shares_non_existent_shareholder() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + deduct_shares(&mut pool, @2, 1); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65540, location = Self)] + public entry fun test_deduct_shares_insufficient_shares() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + deduct_shares(&mut pool, @1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_deduct_shares_remove_shareholder_with_no_shares() { + let pool = new(2); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + assert!(shareholders_count(&pool) == 2, 0); + deduct_shares(&mut pool, @1, 1); + assert!(shareholders_count(&pool) == 1, 1); + destroy_pool(pool); + } + + #[test] + public entry fun test_transfer_shares() { + let pool = new(2); + add_shares(&mut pool, @1, 2); + add_shares(&mut pool, @2, 2); + assert!(shareholders_count(&pool) == 2, 0); + transfer_shares(&mut pool, @1, @2, 1); + assert!(shares(&pool, @1) == 1, 0); + assert!(shares(&pool, @2) == 3, 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_amount_to_shares_empty_pool() { + let pool = new(1); + // No total shares and total coins. + assert!(amount_to_shares(&pool, 1000) == 1000, 0); + + // No total shares but some total coins. + update_total_coins(&mut pool, 1000); + assert!(amount_to_shares(&pool, 1000) == 1000, 1); + + // No total coins but some total shares. + update_total_coins(&mut pool, 0); + add_shares(&mut pool, @1, 100); + assert!(amount_to_shares(&pool, 1000) == 1000, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_shares_to_amount_empty_pool() { + let pool = new(1); + // No total shares and total coins. + assert!(shares_to_amount(&pool, 1000) == 0, 0); + + // No total shares but some total coins. + update_total_coins(&mut pool, 1000); + assert!(shares_to_amount(&pool, 1000) == 0, 1); + + // No total coins but some total shares. + update_total_coins(&mut pool, 0); + add_shares(&mut pool, @1, 100); + assert!(shares_to_amount(&pool, 1000) == 0, 2); + destroy_pool(pool); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64_unbound.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64_unbound.move new file mode 100644 index 0000000..c9ab78e --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/pool_u64_unbound.move @@ -0,0 +1,270 @@ +/// +/// Simple module for tracking and calculating shares of a pool of coins. The shares are worth more as the total coins in +/// the pool increases. New shareholder can buy more shares or redeem their existing shares. +/// +/// Example flow: +/// 1. Pool start outs empty. +/// 2. Shareholder A buys in with 1000 coins. A will receive 1000 shares in the pool. Pool now has 1000 total coins and +/// 1000 total shares. +/// 3. Pool appreciates in value from rewards and now has 2000 coins. A's 1000 shares are now worth 2000 coins. +/// 4. Shareholder B now buys in with 1000 coins. Since before the buy in, each existing share is worth 2 coins, B will +/// receive 500 shares in exchange for 1000 coins. Pool now has 1500 shares and 3000 coins. +/// 5. Pool appreciates in value from rewards and now has 6000 coins. +/// 6. A redeems 500 shares. Each share is worth 6000 / 1500 = 4. A receives 2000 coins. Pool has 4000 coins and 1000 +/// shares left. +/// +module aptos_std::pool_u64_unbound { + use aptos_std::table_with_length::{Self as table, TableWithLength as Table}; + use std::error; + + /// Shareholder not present in pool. + const ESHAREHOLDER_NOT_FOUND: u64 = 1; + /// There are too many shareholders in the pool. + const ETOO_MANY_SHAREHOLDERS: u64 = 2; + /// Cannot destroy non-empty pool. + const EPOOL_IS_NOT_EMPTY: u64 = 3; + /// Cannot redeem more shares than the shareholder has in the pool. + const EINSUFFICIENT_SHARES: u64 = 4; + /// Shareholder cannot have more than u64.max shares. + const ESHAREHOLDER_SHARES_OVERFLOW: u64 = 5; + /// Pool's total coins cannot exceed u64.max. + const EPOOL_TOTAL_COINS_OVERFLOW: u64 = 6; + /// Pool's total shares cannot exceed u64.max. + const EPOOL_TOTAL_SHARES_OVERFLOW: u64 = 7; + + const MAX_U64: u64 = 18446744073709551615; + + const MAX_U128: u128 = 340282366920938463463374607431768211455; + + struct Pool has store { + total_coins: u64, + total_shares: u128, + shares: Table, + // Default to 1. This can be used to minimize rounding errors when computing shares and coins amount. + // However, users need to make sure the coins amount don't overflow when multiplied by the scaling factor. + scaling_factor: u64, + } + + /// Create a new pool. + public fun new(): Pool { + // Default to a scaling factor of 1 (effectively no scaling). + create_with_scaling_factor(1) + } + + #[deprecated] + /// Deprecated. Use `new` instead. + /// Create a new pool. + public fun create(): Pool { + new() + } + + /// Create a new pool with custom `scaling_factor`. + public fun create_with_scaling_factor(scaling_factor: u64): Pool { + Pool { + total_coins: 0, + total_shares: 0, + shares: table::new(), + scaling_factor, + } + } + + /// Destroy an empty pool. This will fail if the pool has any balance of coins. + public fun destroy_empty(pool: Pool) { + assert!(pool.total_coins == 0, error::invalid_state(EPOOL_IS_NOT_EMPTY)); + let Pool { + total_coins: _, + total_shares: _, + shares, + scaling_factor: _, + } = pool; + table::destroy_empty(shares); + } + + /// Return `pool`'s total balance of coins. + public fun total_coins(pool: &Pool): u64 { + pool.total_coins + } + + /// Return the total number of shares across all shareholders in `pool`. + public fun total_shares(pool: &Pool): u128 { + pool.total_shares + } + + /// Return true if `shareholder` is in `pool`. + public fun contains(pool: &Pool, shareholder: address): bool { + table::contains(&pool.shares, shareholder) + } + + /// Return the number of shares of `stakeholder` in `pool`. + public fun shares(pool: &Pool, shareholder: address): u128 { + if (contains(pool, shareholder)) { + *table::borrow(&pool.shares, shareholder) + } else { + 0 + } + } + + /// Return the balance in coins of `shareholder` in `pool.` + public fun balance(pool: &Pool, shareholder: address): u64 { + let num_shares = shares(pool, shareholder); + shares_to_amount(pool, num_shares) + } + + /// Return the number of shareholders in `pool`. + public fun shareholders_count(pool: &Pool): u64 { + table::length(&pool.shares) + } + + /// Update `pool`'s total balance of coins. + public fun update_total_coins(pool: &mut Pool, new_total_coins: u64) { + pool.total_coins = new_total_coins; + } + + /// Allow an existing or new shareholder to add their coins to the pool in exchange for new shares. + public fun buy_in(pool: &mut Pool, shareholder: address, coins_amount: u64): u128 { + if (coins_amount == 0) return 0; + + let new_shares = amount_to_shares(pool, coins_amount); + assert!(MAX_U64 - pool.total_coins >= coins_amount, error::invalid_argument(EPOOL_TOTAL_COINS_OVERFLOW)); + assert!(MAX_U128 - pool.total_shares >= new_shares, error::invalid_argument(EPOOL_TOTAL_SHARES_OVERFLOW)); + + pool.total_coins = pool.total_coins + coins_amount; + pool.total_shares = pool.total_shares + new_shares; + add_shares(pool, shareholder, new_shares); + new_shares + } + + /// Add the number of shares directly for `shareholder` in `pool`. + /// This would dilute other shareholders if the pool's balance of coins didn't change. + fun add_shares(pool: &mut Pool, shareholder: address, new_shares: u128): u128 { + if (contains(pool, shareholder)) { + let existing_shares = table::borrow_mut(&mut pool.shares, shareholder); + let current_shares = *existing_shares; + assert!(MAX_U128 - current_shares >= new_shares, error::invalid_argument(ESHAREHOLDER_SHARES_OVERFLOW)); + + *existing_shares = current_shares + new_shares; + *existing_shares + } else if (new_shares > 0) { + table::add(&mut pool.shares, shareholder, new_shares); + new_shares + } else { + new_shares + } + } + + /// Allow `shareholder` to redeem their shares in `pool` for coins. + public fun redeem_shares(pool: &mut Pool, shareholder: address, shares_to_redeem: u128): u64 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= shares_to_redeem, error::invalid_argument(EINSUFFICIENT_SHARES)); + + if (shares_to_redeem == 0) return 0; + + let redeemed_coins = shares_to_amount(pool, shares_to_redeem); + pool.total_coins = pool.total_coins - redeemed_coins; + pool.total_shares = pool.total_shares - shares_to_redeem; + deduct_shares(pool, shareholder, shares_to_redeem); + + redeemed_coins + } + + /// Transfer shares from `shareholder_1` to `shareholder_2`. + public fun transfer_shares( + pool: &mut Pool, + shareholder_1: address, + shareholder_2: address, + shares_to_transfer: u128, + ) { + assert!(contains(pool, shareholder_1), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder_1) >= shares_to_transfer, error::invalid_argument(EINSUFFICIENT_SHARES)); + if (shares_to_transfer == 0) return; + + deduct_shares(pool, shareholder_1, shares_to_transfer); + add_shares(pool, shareholder_2, shares_to_transfer); + } + + /// Directly deduct `shareholder`'s number of shares in `pool` and return the number of remaining shares. + fun deduct_shares(pool: &mut Pool, shareholder: address, num_shares: u128): u128 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= num_shares, error::invalid_argument(EINSUFFICIENT_SHARES)); + + let existing_shares = table::borrow_mut(&mut pool.shares, shareholder); + *existing_shares = *existing_shares - num_shares; + + // Remove the shareholder completely if they have no shares left. + let remaining_shares = *existing_shares; + if (remaining_shares == 0) { + table::remove(&mut pool.shares, shareholder); + }; + + remaining_shares + } + + /// Return the number of new shares `coins_amount` can buy in `pool`. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares(pool: &Pool, coins_amount: u64): u128 { + amount_to_shares_with_total_coins(pool, coins_amount, pool.total_coins) + } + + /// Return the number of new shares `coins_amount` can buy in `pool` with a custom total coins number. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares_with_total_coins(pool: &Pool, coins_amount: u64, total_coins: u64): u128 { + // No shares yet so amount is worth the same number of shares. + if (pool.total_coins == 0 || pool.total_shares == 0) { + // Multiply by scaling factor to minimize rounding errors during internal calculations for buy ins/redeems. + // This can overflow but scaling factor is expected to be chosen carefully so this would not overflow. + to_u128(coins_amount) * to_u128(pool.scaling_factor) + } else { + // Shares price = total_coins / total existing shares. + // New number of shares = new_amount / shares_price = new_amount * existing_shares / total_amount. + // We rearrange the calc and do multiplication first to avoid rounding errors. + multiply_then_divide(pool, to_u128(coins_amount), pool.total_shares, to_u128(total_coins)) + } + } + + /// Return the number of coins `shares` are worth in `pool`. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount(pool: &Pool, shares: u128): u64 { + shares_to_amount_with_total_coins(pool, shares, pool.total_coins) + } + + /// Return the number of coins `shares` are worth in `pool` with a custom total coins number. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount_with_total_coins(pool: &Pool, shares: u128, total_coins: u64): u64 { + // No shares or coins yet so shares are worthless. + if (pool.total_coins == 0 || pool.total_shares == 0) { + 0 + } else { + // Shares price = total_coins / total existing shares. + // Shares worth = shares * shares price = shares * total_coins / total existing shares. + // We rearrange the calc and do multiplication first to avoid rounding errors. + (multiply_then_divide(pool, shares, to_u128(total_coins), pool.total_shares) as u64) + } + } + + /// Return the number of coins `shares` are worth in `pool` with custom total coins and shares numbers. + public fun shares_to_amount_with_total_stats( + pool: &Pool, + shares: u128, + total_coins: u64, + total_shares: u128, + ): u64 { + if (pool.total_coins == 0 || total_shares == 0) { + 0 + } else { + (multiply_then_divide(pool, shares, to_u128(total_coins), total_shares) as u64) + } + } + + public fun multiply_then_divide(_pool: &Pool, x: u128, y: u128, z: u128): u128 { + let result = (to_u256(x) * to_u256(y)) / to_u256(z); + (result as u128) + } + + fun to_u128(num: u64): u128 { + (num as u128) + } + + fun to_u256(num: u128): u256 { + (num as u256) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255.move new file mode 100644 index 0000000..c69a338 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255.move @@ -0,0 +1,1310 @@ +/// This module contains functions for Ristretto255 curve arithmetic, assuming addition as the group operation. +/// +/// The order of the Ristretto255 elliptic curve group is $\ell = 2^252 + 27742317777372353535851937790883648493$, same +/// as the order of the prime-order subgroup of Curve25519. +/// +/// This module provides two structs for encoding Ristretto elliptic curves to the developer: +/// +/// - First, a 32-byte-sized CompressedRistretto struct, which is used to persist points in storage. +/// +/// - Second, a larger, in-memory, RistrettoPoint struct, which is decompressable from a CompressedRistretto struct. This +/// larger struct can be used for fast arithmetic operations (additions, multiplications, etc.). The results can be saved +/// back into storage by compressing RistrettoPoint structs back to CompressedRistretto structs. +/// +/// This module also provides a Scalar struct for persisting scalars in storage and doing fast arithmetic on them. +/// +/// One invariant maintained by this module is that all CompressedRistretto structs store a canonically-encoded point, +/// which can always be decompressed into a valid point on the curve as a RistrettoPoint struct. Unfortunately, due to +/// limitations in our underlying curve25519-dalek elliptic curve library, this decompression will unnecessarily verify +/// the validity of the point and thus slightly decrease performance. +/// +/// Similarly, all Scalar structs store a canonically-encoded scalar, which can always be safely operated on using +/// arithmetic operations. +/// +/// In the future, we might support additional features: +/// +/// * For scalars: +/// - batch_invert() +/// +/// * For points: +/// - double() +/// + The challenge is that curve25519-dalek does NOT export double for Ristretto points (nor for Edwards) +/// +/// - double_and_compress_batch() +/// +/// - fixed-base, variable-time via optional_mixed_multiscalar_mul() in VartimePrecomputedMultiscalarMul +/// + This would require a storage-friendly RistrettoBasepointTable and an in-memory variant of it too +/// + Similar to the CompressedRistretto and RistrettoPoint structs in this module +/// + The challenge is that curve25519-dalek's RistrettoBasepointTable is not serializable + +module aptos_std::ristretto255 { + use std::features; + use std::option::Option; + + #[test_only] + use std::option; + + // + // Constants + // + + /// The order of the Ristretto255 group and its scalar field, in little-endian. + const ORDER_ELL: vector = x"edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + /// `ORDER_ELL` - 1: i.e., the "largest", reduced scalar in the field + const L_MINUS_ONE: vector = x"ecd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + /// The maximum size in bytes of a canonically-encoded Scalar is 32 bytes. + const MAX_SCALAR_NUM_BYTES: u64 = 32u64; + + /// The maximum size in bits of a canonically-encoded Scalar is 256 bits. + const MAX_SCALAR_NUM_BITS: u64 = 256u64; + + /// The maximum size in bytes of a canonically-encoded Ristretto255 point is 32 bytes. + const MAX_POINT_NUM_BYTES: u64 = 32u64; + + /// The basepoint (generator) of the Ristretto255 group + const BASE_POINT: vector = x"e2f2ae0a6abc4e71a884a961c500515f58e30b6aa582dd8db6a65945e08d2d76"; + + /// The hash of the basepoint of the Ristretto255 group using SHA3_512 + const HASH_BASE_POINT: vector = x"8c9240b456a9e6dc65c377a1048d745f94a08cdb7f44cbcd7b46f34048871134"; + + // + // Reasons for error codes + // + + /// The number of scalars does not match the number of points. + const E_DIFFERENT_NUM_POINTS_AND_SCALARS: u64 = 1; + /// Expected more than zero points as input. + const E_ZERO_POINTS: u64 = 2; + /// Expected more than zero scalars as input. + const E_ZERO_SCALARS: u64 = 3; + /// Too many points have been created in the current transaction execution. + const E_TOO_MANY_POINTS_CREATED: u64 = 4; + /// The native function has not been deployed yet. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 5; + + // + // Scalar and point structs + // + + /// This struct represents a scalar as a little-endian byte encoding of an integer in $\mathbb{Z}_\ell$, which is + /// stored in `data`. Here, \ell denotes the order of the scalar field (and the underlying elliptic curve group). + struct Scalar has copy, store, drop { + data: vector + } + + /// This struct represents a serialized point on the Ristretto255 curve, in 32 bytes. + /// This struct can be decompressed from storage into an in-memory RistrettoPoint, on which fast curve arithmetic + /// can be performed. + struct CompressedRistretto has copy, store, drop { + data: vector + } + + /// This struct represents an in-memory Ristretto255 point and supports fast curve arithmetic. + /// + /// An important invariant: There will never be two RistrettoPoint's constructed with the same handle. One can have + /// immutable references to the same RistrettoPoint, of course. + struct RistrettoPoint has drop { + handle: u64 + } + + // + // Functions for arithmetic on points + // + + /// Returns the identity point as a CompressedRistretto. + public fun point_identity_compressed(): CompressedRistretto { + CompressedRistretto { + data: x"0000000000000000000000000000000000000000000000000000000000000000" + } + } + + /// Returns the identity point as a CompressedRistretto. + public fun point_identity(): RistrettoPoint { + RistrettoPoint { + handle: point_identity_internal() + } + } + + /// Returns the basepoint (generator) of the Ristretto255 group as a compressed point + public fun basepoint_compressed(): CompressedRistretto { + CompressedRistretto { + data: BASE_POINT + } + } + + /// Returns the hash-to-point result of serializing the basepoint of the Ristretto255 group. + /// For use as the random value basepoint in Pedersen commitments + public fun hash_to_point_base(): RistrettoPoint { + let comp_res = CompressedRistretto { data: HASH_BASE_POINT }; + point_decompress(&comp_res) + } + + /// Returns the basepoint (generator) of the Ristretto255 group + public fun basepoint(): RistrettoPoint { + let (handle, _) = point_decompress_internal(BASE_POINT); + + RistrettoPoint { + handle + } + } + + /// Multiplies the basepoint (generator) of the Ristretto255 group by a scalar and returns the result. + /// This call is much faster than `point_mul(&basepoint(), &some_scalar)` because of precomputation tables. + public fun basepoint_mul(a: &Scalar): RistrettoPoint { + RistrettoPoint { + handle: basepoint_mul_internal(a.data) + } + } + + /// Creates a new CompressedRistretto point from a sequence of 32 bytes. If those bytes do not represent a valid + /// point, returns None. + public fun new_compressed_point_from_bytes(bytes: vector): Option { + if (point_is_canonical_internal(bytes)) { + std::option::some(CompressedRistretto { + data: bytes + }) + } else { + std::option::none() + } + } + + /// Creates a new RistrettoPoint from a sequence of 32 bytes. If those bytes do not represent a valid point, + /// returns None. + public fun new_point_from_bytes(bytes: vector): Option { + let (handle, is_canonical) = point_decompress_internal(bytes); + if (is_canonical) { + std::option::some(RistrettoPoint { handle }) + } else { + std::option::none() + } + } + + /// Given a compressed ristretto point `point`, returns the byte representation of that point + public fun compressed_point_to_bytes(point: CompressedRistretto): vector { + point.data + } + + /// DEPRECATED: Use the more clearly-named `new_point_from_sha2_512` + /// + /// Hashes the input to a uniformly-at-random RistrettoPoint via SHA512. + public fun new_point_from_sha512(sha2_512_input: vector): RistrettoPoint { + new_point_from_sha2_512(sha2_512_input) + } + + /// Hashes the input to a uniformly-at-random RistrettoPoint via SHA2-512. + public fun new_point_from_sha2_512(sha2_512_input: vector): RistrettoPoint { + RistrettoPoint { + handle: new_point_from_sha512_internal(sha2_512_input) + } + } + + /// Samples a uniformly-at-random RistrettoPoint given a sequence of 64 uniformly-at-random bytes. This function + /// can be used to build a collision-resistant hash function that maps 64-byte messages to RistrettoPoint's. + public fun new_point_from_64_uniform_bytes(bytes: vector): Option { + if (std::vector::length(&bytes) == 64) { + std::option::some(RistrettoPoint { + handle: new_point_from_64_uniform_bytes_internal(bytes) + }) + } else { + std::option::none() + } + } + + /// Decompresses a CompressedRistretto from storage into a RistrettoPoint which can be used for fast arithmetic. + public fun point_decompress(point: &CompressedRistretto): RistrettoPoint { + // NOTE: Our CompressedRistretto invariant assures us that every CompressedRistretto in storage is a valid + // RistrettoPoint + let (handle, _) = point_decompress_internal(point.data); + RistrettoPoint { handle } + } + + /// Clones a RistrettoPoint. + public fun point_clone(point: &RistrettoPoint): RistrettoPoint { + if(!features::bulletproofs_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + RistrettoPoint { + handle: point_clone_internal(point.handle) + } + } + + /// Compresses a RistrettoPoint to a CompressedRistretto which can be put in storage. + public fun point_compress(point: &RistrettoPoint): CompressedRistretto { + CompressedRistretto { + data: point_compress_internal(point) + } + } + + /// Returns the sequence of bytes representin this Ristretto point. + /// To convert a RistrettoPoint 'p' to bytes, first compress it via `c = point_compress(&p)`, and then call this + /// function on `c`. + public fun point_to_bytes(point: &CompressedRistretto): vector { + point.data + } + + /// Returns a * point. + public fun point_mul(point: &RistrettoPoint, a: &Scalar): RistrettoPoint { + RistrettoPoint { + handle: point_mul_internal(point, a.data, false) + } + } + + /// Sets a *= point and returns 'a'. + public fun point_mul_assign(point: &mut RistrettoPoint, a: &Scalar): &mut RistrettoPoint { + point_mul_internal(point, a.data, true); + point + } + + /// Returns (a * a_base + b * base_point), where base_point is the Ristretto basepoint encoded in `BASE_POINT`. + public fun basepoint_double_mul(a: &Scalar, a_base: &RistrettoPoint, b: &Scalar): RistrettoPoint { + RistrettoPoint { + handle: basepoint_double_mul_internal(a.data, a_base, b.data) + } + } + + /// Returns a + b + public fun point_add(a: &RistrettoPoint, b: &RistrettoPoint): RistrettoPoint { + RistrettoPoint { + handle: point_add_internal(a, b, false) + } + } + + /// Sets a += b and returns 'a'. + public fun point_add_assign(a: &mut RistrettoPoint, b: &RistrettoPoint): &mut RistrettoPoint { + point_add_internal(a, b, true); + a + } + + /// Returns a - b + public fun point_sub(a: &RistrettoPoint, b: &RistrettoPoint): RistrettoPoint { + RistrettoPoint { + handle: point_sub_internal(a, b, false) + } + } + + /// Sets a -= b and returns 'a'. + public fun point_sub_assign(a: &mut RistrettoPoint, b: &RistrettoPoint): &mut RistrettoPoint { + point_sub_internal(a, b, true); + a + } + + /// Returns -a + public fun point_neg(a: &RistrettoPoint): RistrettoPoint { + RistrettoPoint { + handle: point_neg_internal(a, false) + } + } + + /// Sets a = -a, and returns 'a'. + public fun point_neg_assign(a: &mut RistrettoPoint): &mut RistrettoPoint { + point_neg_internal(a, true); + a + } + + /// Returns true if the two RistrettoPoints are the same points on the elliptic curve. + native public fun point_equals(g: &RistrettoPoint, h: &RistrettoPoint): bool; + + /// Computes a double-scalar multiplication, returning a_1 p_1 + a_2 p_2 + /// This function is much faster than computing each a_i p_i using `point_mul` and adding up the results using `point_add`. + public fun double_scalar_mul(scalar1: &Scalar, point1: &RistrettoPoint, scalar2: &Scalar, point2: &RistrettoPoint): RistrettoPoint { + if(!features::bulletproofs_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + RistrettoPoint { + handle: double_scalar_mul_internal(point1.handle, point2.handle, scalar1.data, scalar2.data) + } + } + + /// Computes a multi-scalar multiplication, returning a_1 p_1 + a_2 p_2 + ... + a_n p_n. + /// This function is much faster than computing each a_i p_i using `point_mul` and adding up the results using `point_add`. + public fun multi_scalar_mul(points: &vector, scalars: &vector): RistrettoPoint { + assert!(!std::vector::is_empty(points), std::error::invalid_argument(E_ZERO_POINTS)); + assert!(!std::vector::is_empty(scalars), std::error::invalid_argument(E_ZERO_SCALARS)); + assert!(std::vector::length(points) == std::vector::length(scalars), std::error::invalid_argument(E_DIFFERENT_NUM_POINTS_AND_SCALARS)); + + RistrettoPoint { + handle: multi_scalar_mul_internal(points, scalars) + } + } + + // + // Functions for arithmetic on Scalars + // + + /// Given a sequence of 32 bytes, checks if they canonically-encode a Scalar and return it. + /// Otherwise, returns None. + public fun new_scalar_from_bytes(bytes: vector): Option { + if (scalar_is_canonical_internal(bytes)) { + std::option::some(Scalar { + data: bytes + }) + } else { + std::option::none() + } + } + + /// DEPRECATED: Use the more clearly-named `new_scalar_from_sha2_512` + /// + /// Hashes the input to a uniformly-at-random Scalar via SHA2-512 + public fun new_scalar_from_sha512(sha2_512_input: vector): Scalar { + new_scalar_from_sha2_512(sha2_512_input) + } + + /// Hashes the input to a uniformly-at-random Scalar via SHA2-512 + public fun new_scalar_from_sha2_512(sha2_512_input: vector): Scalar { + Scalar { + data: scalar_from_sha512_internal(sha2_512_input) + } + } + + /// Creates a Scalar from an u8. + public fun new_scalar_from_u8(byte: u8): Scalar { + let s = scalar_zero(); + let byte_zero = std::vector::borrow_mut(&mut s.data, 0); + *byte_zero = byte; + + s + } + + /// Creates a Scalar from an u32. + public fun new_scalar_from_u32(four_bytes: u32): Scalar { + Scalar { + data: scalar_from_u64_internal((four_bytes as u64)) + } + } + + /// Creates a Scalar from an u64. + public fun new_scalar_from_u64(eight_bytes: u64): Scalar { + Scalar { + data: scalar_from_u64_internal(eight_bytes) + } + } + + /// Creates a Scalar from an u128. + public fun new_scalar_from_u128(sixteen_bytes: u128): Scalar { + Scalar { + data: scalar_from_u128_internal(sixteen_bytes) + } + } + + /// Creates a Scalar from 32 bytes by reducing the little-endian-encoded number in those bytes modulo $\ell$. + public fun new_scalar_reduced_from_32_bytes(bytes: vector): Option { + if (std::vector::length(&bytes) == 32) { + std::option::some(Scalar { + data: scalar_reduced_from_32_bytes_internal(bytes) + }) + } else { + std::option::none() + } + } + + /// Samples a scalar uniformly-at-random given 64 uniform-at-random bytes as input by reducing the little-endian-encoded number + /// in those bytes modulo $\ell$. + public fun new_scalar_uniform_from_64_bytes(bytes: vector): Option { + if (std::vector::length(&bytes) == 64) { + std::option::some(Scalar { + data: scalar_uniform_from_64_bytes_internal(bytes) + }) + } else { + std::option::none() + } + } + + /// Returns 0 as a Scalar. + public fun scalar_zero(): Scalar { + Scalar { + data: x"0000000000000000000000000000000000000000000000000000000000000000" + } + } + + /// Returns true if the given Scalar equals 0. + public fun scalar_is_zero(s: &Scalar): bool { + s.data == x"0000000000000000000000000000000000000000000000000000000000000000" + } + + /// Returns 1 as a Scalar. + public fun scalar_one(): Scalar { + Scalar { + data: x"0100000000000000000000000000000000000000000000000000000000000000" + } + } + + /// Returns true if the given Scalar equals 1. + public fun scalar_is_one(s: &Scalar): bool { + s.data == x"0100000000000000000000000000000000000000000000000000000000000000" + } + + /// Returns true if the two scalars are equal. + public fun scalar_equals(lhs: &Scalar, rhs: &Scalar): bool { + lhs.data == rhs.data + } + + /// Returns the inverse s^{-1} mod \ell of a scalar s. + /// Returns None if s is zero. + public fun scalar_invert(s: &Scalar): Option { + if (scalar_is_zero(s)) { + std::option::none() + } else { + std::option::some(Scalar { + data: scalar_invert_internal(s.data) + }) + } + } + + /// Returns the product of the two scalars. + public fun scalar_mul(a: &Scalar, b: &Scalar): Scalar { + Scalar { + data: scalar_mul_internal(a.data, b.data) + } + } + + /// Computes the product of 'a' and 'b' and assigns the result to 'a'. + /// Returns 'a'. + public fun scalar_mul_assign(a: &mut Scalar, b: &Scalar): &mut Scalar { + a.data = scalar_mul(a, b).data; + a + } + + /// Returns the sum of the two scalars. + public fun scalar_add(a: &Scalar, b: &Scalar): Scalar { + Scalar { + data: scalar_add_internal(a.data, b.data) + } + } + + /// Computes the sum of 'a' and 'b' and assigns the result to 'a' + /// Returns 'a'. + public fun scalar_add_assign(a: &mut Scalar, b: &Scalar): &mut Scalar { + a.data = scalar_add(a, b).data; + a + } + + /// Returns the difference of the two scalars. + public fun scalar_sub(a: &Scalar, b: &Scalar): Scalar { + Scalar { + data: scalar_sub_internal(a.data, b.data) + } + } + + /// Subtracts 'b' from 'a' and assigns the result to 'a'. + /// Returns 'a'. + public fun scalar_sub_assign(a: &mut Scalar, b: &Scalar): &mut Scalar { + a.data = scalar_sub(a, b).data; + a + } + + /// Returns the negation of 'a': i.e., $(0 - a) \mod \ell$. + public fun scalar_neg(a: &Scalar): Scalar { + Scalar { + data: scalar_neg_internal(a.data) + } + } + + /// Replaces 'a' by its negation. + /// Returns 'a'. + public fun scalar_neg_assign(a: &mut Scalar): &mut Scalar { + a.data = scalar_neg(a).data; + a + } + + /// Returns the byte-representation of the scalar. + public fun scalar_to_bytes(s: &Scalar): vector { + s.data + } + + // + // Only used internally for implementing CompressedRistretto and RistrettoPoint + // + + // NOTE: This was supposed to be more clearly named with *_sha2_512_*. + native fun new_point_from_sha512_internal(sha2_512_input: vector): u64; + + native fun new_point_from_64_uniform_bytes_internal(bytes: vector): u64; + + native fun point_is_canonical_internal(bytes: vector): bool; + + native fun point_identity_internal(): u64; + + native fun point_decompress_internal(maybe_non_canonical_bytes: vector): (u64, bool); + + native fun point_clone_internal(point_handle: u64): u64; + native fun point_compress_internal(point: &RistrettoPoint): vector; + + native fun point_mul_internal(point: &RistrettoPoint, a: vector, in_place: bool): u64; + + native fun basepoint_mul_internal(a: vector): u64; + + native fun basepoint_double_mul_internal(a: vector, some_point: &RistrettoPoint, b: vector): u64; + + native fun point_add_internal(a: &RistrettoPoint, b: &RistrettoPoint, in_place: bool): u64; + + native fun point_sub_internal(a: &RistrettoPoint, b: &RistrettoPoint, in_place: bool): u64; + + native fun point_neg_internal(a: &RistrettoPoint, in_place: bool): u64; + + native fun double_scalar_mul_internal(point1: u64, point2: u64, scalar1: vector, scalar2: vector): u64; + + /// The generic arguments are needed to deal with some Move VM peculiarities which prevent us from borrowing the + /// points (or scalars) inside a &vector in Rust. + /// + /// WARNING: This function can only be called with P = RistrettoPoint and S = Scalar. + native fun multi_scalar_mul_internal(points: &vector

, scalars: &vector): u64; + + // + // Only used internally for implementing Scalar. + // + + native fun scalar_is_canonical_internal(s: vector): bool; + + native fun scalar_from_u64_internal(num: u64): vector; + + native fun scalar_from_u128_internal(num: u128): vector; + + native fun scalar_reduced_from_32_bytes_internal(bytes: vector): vector; + + native fun scalar_uniform_from_64_bytes_internal(bytes: vector): vector; + + native fun scalar_invert_internal(bytes: vector): vector; + + // NOTE: This was supposed to be more clearly named with *_sha2_512_*. + native fun scalar_from_sha512_internal(sha2_512_input: vector): vector; + + native fun scalar_mul_internal(a_bytes: vector, b_bytes: vector): vector; + + native fun scalar_add_internal(a_bytes: vector, b_bytes: vector): vector; + + native fun scalar_sub_internal(a_bytes: vector, b_bytes: vector): vector; + + native fun scalar_neg_internal(a_bytes: vector): vector; + + #[test_only] + native fun random_scalar_internal(): vector; + + // + // Test-only functions + // + + #[test_only] + public fun random_scalar(): Scalar { + Scalar { + data: random_scalar_internal() + } + } + + #[test_only] + public fun random_point(): RistrettoPoint { + let s = random_scalar(); + + basepoint_mul(&s) + } + + // + // Testing constants + // + + // The scalar 2 + #[test_only] + const TWO_SCALAR: vector = x"0200000000000000000000000000000000000000000000000000000000000000"; + + // Non-canonical scalar: the order \ell of the group + 1 + #[test_only] + const L_PLUS_ONE: vector = x"eed3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + // Non-canonical scalar: the order \ell of the group + 2 + #[test_only] + const L_PLUS_TWO: vector = x"efd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + // Some random scalar denoted by X + #[test_only] + const X_SCALAR: vector = x"4e5ab4345d4708845913b4641bc27d5252a585101bcc4244d449f4a879d9f204"; + + // X^{-1} = 1/X = 6859937278830797291664592131120606308688036382723378951768035303146619657244 + // 0x1CDC17FCE0E9A5BBD9247E56BB016347BBBA31EDD5A9BB96D50BCD7A3F962A0F + #[test_only] + const X_INV_SCALAR: vector = x"1cdc17fce0e9a5bbd9247e56bb016347bbba31edd5a9bb96d50bcd7a3f962a0f"; + + // Some random scalar Y = 2592331292931086675770238855846338635550719849568364935475441891787804997264 + #[test_only] + const Y_SCALAR: vector = x"907633fe1c4b66a4a28d2dd7678386c353d0de5455d4fc9de8ef7ac31f35bb05"; + + // X * Y = 5690045403673944803228348699031245560686958845067437804563560795922180092780 + #[test_only] + const X_TIMES_Y_SCALAR: vector = x"6c3374a1894f62210aaa2fe186a6f92ce0aa75c2779581c295fc08179a73940c"; + + // X + 2^256 * X \mod \ell + #[test_only] + const REDUCED_X_PLUS_2_TO_256_TIMES_X_SCALAR: vector = x"d89ab38bd279024745639ed817ad3f64cc005b32db9939f91c521fc564a5c008"; + + // sage: l = 2^252 + 27742317777372353535851937790883648493 + // sage: big = 2^256 - 1 + // sage: repr((big % l).digits(256)) + #[test_only] + const REDUCED_2_256_MINUS_1_SCALAR: vector = x"1c95988d7431ecd670cf7d73f45befc6feffffffffffffffffffffffffffff0f"; + + #[test_only] + const NON_CANONICAL_ALL_ONES: vector = x"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; + + #[test_only] + const A_SCALAR: vector = x"1a0e978a90f6622d3747023f8ad8264da758aa1b88e040d1589e7b7f2376ef09"; + + // Generated in curve25519-dalek via: + // ``` + // let mut hasher = sha2::Sha512::default(); + // hasher.update(b"bello!"); + // let s = Scalar::from_hash(hasher); + // println!("scalar: {:x?}", s.to_bytes()); + // ``` + #[test_only] + const B_SCALAR: vector = x"dbfd97afd38a06f0138d0527efb28ead5b7109b486465913bf3aa472a8ed4e0d"; + + #[test_only] + const A_TIMES_B_SCALAR: vector = x"2ab50e383d7c210f74d5387330735f18315112d10dfb98fcce1e2620c0c01402"; + + #[test_only] + const A_PLUS_B_SCALAR: vector = x"083839dd491e57c5743710c39a91d6e502cab3cf0e279ae417d91ff2cb633e07"; + + #[test_only] + /// A_SCALAR * BASE_POINT, computed by modifying a test in curve25519-dalek in src/edwards.rs to do: + /// ``` + /// let comp = RistrettoPoint(A_TIMES_BASEPOINT.decompress().unwrap()).compress(); + /// println!("hex: {:x?}", comp.to_bytes()); + /// ``` + const A_TIMES_BASE_POINT: vector = x"96d52d9262ee1e1aae79fbaee8c1d9068b0d01bf9a4579e618090c3d1088ae10"; + + #[test_only] + const A_POINT: vector = x"e87feda199d72b83de4f5b2d45d34805c57019c6c59c42cb70ee3d19aa996f75"; + #[test_only] + const B_POINT: vector = x"fa0b3624b081c62f364d0b2839dcc76d7c3ab0e27e31beb2b9ed766575f28e76"; + #[test_only] + const A_PLUS_B_POINT: vector = x"70cf3753475b9ff33e2f84413ed6b5052073bccc0a0a81789d3e5675dc258056"; + + // const NON_CANONICAL_LARGEST_ED25519_S: vector = x"f8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"; + // const CANONICAL_LARGEST_ED25519_S_PLUS_ONE: vector = x"7e344775474a7f9723b63a8be92ae76dffffffffffffffffffffffffffffff0f"; + // const CANONICAL_LARGEST_ED25519_S_MINUS_ONE: vector = x"7c344775474a7f9723b63a8be92ae76dffffffffffffffffffffffffffffff0f"; + + // + // Tests + // + + #[test] + fun test_point_decompression() { + let compressed = new_compressed_point_from_bytes(A_POINT); + assert!(std::option::is_some(&compressed), 1); + + let point = new_point_from_bytes(A_POINT); + assert!(std::option::is_some(&point), 1); + + let point = std::option::extract(&mut point); + let compressed = std::option::extract(&mut compressed); + let same_point = point_decompress(&compressed); + + assert!(point_equals(&point, &same_point), 1); + } + + #[test] + fun test_point_equals() { + let g = basepoint(); + let same_g = std::option::extract(&mut new_point_from_bytes(BASE_POINT)); + let ag = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + + assert!(point_equals(&g, &same_g), 1); + assert!(!point_equals(&g, &ag), 1); + } + + #[test] + fun test_point_mul() { + // fetch g + let g = basepoint(); + // fetch a + let a = std::option::extract(&mut new_scalar_from_bytes(A_SCALAR)); + // fetch expected a*g + let ag = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + + // compute a*g + let p = point_mul(&g, &a); + + // sanity-check the handles + assert!(g.handle == 0, 1); + assert!(ag.handle == 1, 1); + assert!(p.handle == 2, 1); + + assert!(!point_equals(&g, &ag), 1); // make sure input g remains unmodifed + assert!(point_equals(&p, &ag), 1); // make sure output a*g is correct + } + + #[test] + fun test_point_mul_assign() { + let g = basepoint(); + assert!(g.handle == 0, 1); + + let a = std::option::extract(&mut new_scalar_from_bytes(A_SCALAR)); + + let ag = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + assert!(ag.handle == 1, 1); + assert!(!point_equals(&g, &ag), 1); + + { + // NOTE: new_g is just a mutable reference to g + let upd_g = point_mul_assign(&mut g, &a); + + // in a mul_assign the returned &mut RistrettoPoint reference should have the same handle as 'g' + assert!(upd_g.handle == 0, 1); + + assert!(point_equals(upd_g, &ag), 1); + }; + + assert!(point_equals(&g, &ag), 1); + } + + #[test] + fun test_point_add() { + // fetch a + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + // fetch b + let b = std::option::extract(&mut new_point_from_bytes(B_POINT)); + + // fetch expected a + b + let a_plus_b = std::option::extract(&mut new_point_from_bytes(A_PLUS_B_POINT)); + + // compute a*g + let result = point_add(&a, &b); + + assert!(!point_equals(&a, &b), 1); + + // sanity-check the handles + assert!(a.handle == 0, 1); + assert!(b.handle == 1, 1); + assert!(a_plus_b.handle == 2, 1); + assert!(result.handle == 3, 1); + + assert!(!point_equals(&a, &result), 1); // make sure input a remains unmodifed + assert!(!point_equals(&b, &result), 1); // make sure input b remains unmodifed + assert!(point_equals(&a_plus_b, &result), 1); // make sure output a+b is correct + } + + #[test] + fun test_point_add_assign_0_0() { + test_point_add_assign_internal(0, 0); + } + + #[test] + fun test_point_add_assign_1_0() { + test_point_add_assign_internal(1, 0); + } + + #[test] + fun test_point_add_assign_0_1() { + test_point_add_assign_internal(0, 1); + } + + #[test] + fun test_point_add_assign_3_7() { + test_point_add_assign_internal(3, 7); + } + + #[test_only] + fun test_point_add_assign_internal(before_a_gap: u64, before_b_gap: u64) { + // create extra RistrettoPoints here, so as to generate different PointStore layouts inside the native Rust implementation + let c = before_a_gap; + while (c > 0) { + let _ignore = std::option::extract(&mut new_point_from_bytes(BASE_POINT)); + + c = c - 1; + }; + + // fetch a + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + // create extra RistrettoPoints here, so as to generate different PointStore layouts inside the native Rust implementation + let c = before_b_gap; + while (c > 0) { + let _ignore = std::option::extract(&mut new_point_from_bytes(BASE_POINT)); + + c = c - 1; + }; + // fetch b + let b = std::option::extract(&mut new_point_from_bytes(B_POINT)); + + let a_plus_b = std::option::extract(&mut new_point_from_bytes(A_PLUS_B_POINT)); + + // sanity-check the handles + assert!(a.handle == before_a_gap, 1); + assert!(b.handle == 1 + before_a_gap + before_b_gap, 1); + assert!(a_plus_b.handle == 2 + before_a_gap + before_b_gap, 1); + + assert!(!point_equals(&a, &b), 1); + assert!(!point_equals(&a, &a_plus_b), 1); + + { + // NOTE: new_h is just a mutable reference to g + let upd_a = point_add_assign(&mut a, &b); + + // in a add_assign the returned &mut RistrettoPoint reference should have the same handle as 'a' + assert!(upd_a.handle == before_a_gap, 1); + + assert!(point_equals(upd_a, &a_plus_b), 1); + }; + + assert!(point_equals(&a, &a_plus_b), 1); + } + + #[test] + fun test_point_sub() { + // fetch a + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + // fetch b + let b = std::option::extract(&mut new_point_from_bytes(B_POINT)); + + // fetch expected a + b + let a_plus_b = std::option::extract(&mut new_point_from_bytes(A_PLUS_B_POINT)); + + // compute a*g + let result = point_sub(&a_plus_b, &b); + + assert!(!point_equals(&a, &b), 1); + + // sanity-check the handles + assert!(a.handle == 0, 1); + assert!(b.handle == 1, 1); + assert!(a_plus_b.handle == 2, 1); + assert!(result.handle == 3, 1); + + assert!(!point_equals(&a_plus_b, &result), 1); // make sure input a_plus_b remains unmodifed + assert!(!point_equals(&b, &result), 1); // make sure input b remains unmodifed + assert!(point_equals(&a, &result), 1); // make sure output 'a+b-b' is correct + } + + #[test] + fun test_point_neg() { + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + let neg_a = point_neg(&a); + + assert!(a.handle != neg_a.handle, 1); + assert!(!point_equals(&a, &neg_a), 1); + assert!(!point_equals(&point_add(&point_identity(), &a), &neg_a), 1); + assert!(point_equals(&point_add(&a, &neg_a), &point_identity()), 1); + + let handle = a.handle; + let neg_a_ref = point_neg_assign(&mut a); + assert!(handle == neg_a_ref.handle, 1); + assert!(point_equals(neg_a_ref, &neg_a), 1); + } + + #[test] + fun test_basepoint_mul() { + let a = Scalar { data: A_SCALAR }; + let basepoint = basepoint(); + let expected = point_mul(&basepoint, &a); + assert!(point_equals(&expected, &basepoint_mul(&a)), 1); + } + + #[test(fx = @std)] + fun test_basepoint_double_mul(fx: signer) { + features::change_feature_flags(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let expected = option::extract(&mut new_point_from_bytes(x"be5d615d8b8f996723cdc6e1895b8b6d312cc75d1ffb0259873b99396a38c05a")); + + let a = Scalar { data: A_SCALAR }; + let a_point = option::extract(&mut new_point_from_bytes(A_POINT)); + let b = Scalar { data: B_SCALAR }; + let actual = basepoint_double_mul(&a, &a_point, &b); + + assert!(point_equals(&expected, &actual), 1); + + let expected = double_scalar_mul(&a, &a_point, &b, &basepoint()); + assert!(point_equals(&expected, &actual), 1); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_empty_scalars() { + multi_scalar_mul(&vector[ basepoint() ], &vector[]); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_empty_points() { + multi_scalar_mul(&vector[ ], &vector[ Scalar { data: A_SCALAR } ]); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_empty_all() { + multi_scalar_mul(&vector[ ], &vector[ ]); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_different_sizes() { + multi_scalar_mul(&vector[ basepoint() ], &vector[ Scalar { data: A_SCALAR }, Scalar { data: B_SCALAR } ]); + } + + #[test] + fun test_multi_scalar_mul_single() { + // Test single exp + let points = vector[ + basepoint(), + ]; + + let scalars = vector[ + Scalar { data: A_SCALAR }, + ]; + + let result = multi_scalar_mul(&points, &scalars); + let expected = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + + assert!(point_equals(&result, &expected), 1); + } + + #[test] + fun test_multi_scalar_mul_double() { + // Test double exp + let points = vector[ + basepoint(), + basepoint(), + ]; + + let scalars = vector[ + Scalar { data: A_SCALAR }, + Scalar { data: B_SCALAR }, + ]; + + let result = multi_scalar_mul(&points, &scalars); + let expected = basepoint_double_mul( + std::vector::borrow(&scalars, 0), + &basepoint(), + std::vector::borrow(&scalars, 1)); + + assert!(point_equals(&result, &expected), 1); + } + + #[test] + fun test_multi_scalar_mul_many() { + let scalars = vector[ + new_scalar_from_sha2_512(b"1"), + new_scalar_from_sha2_512(b"2"), + new_scalar_from_sha2_512(b"3"), + new_scalar_from_sha2_512(b"4"), + new_scalar_from_sha2_512(b"5"), + ]; + + let points = vector[ + new_point_from_sha2_512(b"1"), + new_point_from_sha2_512(b"2"), + new_point_from_sha2_512(b"3"), + new_point_from_sha2_512(b"4"), + new_point_from_sha2_512(b"5"), + ]; + + let expected = std::option::extract(&mut new_point_from_bytes(x"c4a98fbe6bd0f315a0c150858aec8508be397443093e955ef982e299c1318928")); + let result = multi_scalar_mul(&points, &scalars); + + assert!(point_equals(&expected, &result), 1); + } + + #[test] + fun test_new_point_from_sha2_512() { + let msg = b"To really appreciate architecture, you may even need to commit a murder"; + let expected = option::extract(&mut new_point_from_bytes(x"baaa91eb43e5e2f12ffc96347e14bc458fdb1772b2232b08977ee61ea9f84e31")); + + assert!(point_equals(&expected, &new_point_from_sha2_512(msg)), 1); + } + + #[test] + fun test_new_point_from_64_uniform_bytes() { + let bytes_64 = x"baaa91eb43e5e2f12ffc96347e14bc458fdb1772b2232b08977ee61ea9f84e31e87feda199d72b83de4f5b2d45d34805c57019c6c59c42cb70ee3d19aa996f75"; + let expected = option::extract(&mut new_point_from_bytes(x"4a8e429f906478654232d7ae180ad60854754944ac67f38e20d8fa79e4b7d71e")); + + let point = option::extract(&mut new_point_from_64_uniform_bytes(bytes_64)); + assert!(point_equals(&expected, &point), 1); + } + + #[test] + fun test_scalar_basic_viability() { + // Test conversion from u8 + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_equals(&new_scalar_from_u8(2u8), &two), 1); + + // Test conversion from u64 + assert!(scalar_equals(&new_scalar_from_u64(2u64), &two), 1); + + // Test conversion from u128 + assert!(scalar_equals(&new_scalar_from_u128(2u128), &two), 1); + + // Test (0 - 1) % order = order - 1 + assert!(scalar_equals(&scalar_sub(&scalar_zero(), &scalar_one()), &Scalar { data: L_MINUS_ONE }), 1); + } + + #[test] + /// Tests deserializing a Scalar from a sequence of canonical bytes + fun test_scalar_from_canonical_bytes() { + // Too few bytes + assert!(std::option::is_none(&new_scalar_from_bytes(x"00")), 1); + + // 32 zero bytes are canonical + assert!(std::option::is_some(&new_scalar_from_bytes(x"0000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Non-canonical because unreduced + assert!(std::option::is_none(&new_scalar_from_bytes(x"1010101010101010101010101010101010101010101010101010101010101010")), 1); + + // Canonical because \ell - 1 + assert!(std::option::is_some(&new_scalar_from_bytes(L_MINUS_ONE)), 1); + + // Non-canonical because \ell + assert!(std::option::is_none(&new_scalar_from_bytes(ORDER_ELL)), 1); + + // Non-canonical because \ell+1 + assert!(std::option::is_none(&new_scalar_from_bytes(L_PLUS_ONE)), 1); + + // Non-canonical because \ell+2 + assert!(std::option::is_none(&new_scalar_from_bytes(L_PLUS_TWO)), 1); + + // Non-canonical because high bit is set + let non_canonical_highbit = vector[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, 128]; + let non_canonical_highbit_hex = x"0000000000000000000000000000000000000000000000000000000000000080"; + assert!(non_canonical_highbit == non_canonical_highbit_hex, 1); + assert!(std::option::is_none(&new_scalar_from_bytes(non_canonical_highbit)), 1); + } + + #[test] + fun test_scalar_zero() { + // 0 == 0 + assert!(scalar_is_zero(&scalar_zero()), 1); + assert!(scalar_is_zero(&new_scalar_from_u8(0u8)), 1); + + // 0 != 1 + assert!(scalar_is_zero(&scalar_one()) == false, 1); + + // Pick a random scalar by hashing from some "random" bytes + let s = new_scalar_from_sha2_512(x"deadbeef"); + + // Technically, there is a negligible probability (i.e., 1/2^\ell) that the hashed s is zero or one + assert!(scalar_is_zero(&s) == false, 1); + assert!(scalar_is_one(&s) == false, 1); + + // Multiply 0 with a random scalar and make sure you get zero + assert!(scalar_is_zero(&scalar_mul(&scalar_zero(), &s)), 1); + assert!(scalar_is_zero(&scalar_mul(&s, &scalar_zero())), 1); + } + + #[test] + fun test_scalar_one() { + // 1 == 1 + assert!(scalar_is_one(&scalar_one()), 1); + assert!(scalar_is_one(&new_scalar_from_u8(1u8)), 1); + + // 1 != 0 + assert!(scalar_is_one(&scalar_zero()) == false, 1); + + // Pick a random scalar by hashing from some "random" bytes + let s = new_scalar_from_sha2_512(x"deadbeef"); + let inv = scalar_invert(&s); + + // Technically, there is a negligible probability (i.e., 1/2^\ell) that s was zero and the call above returned None + assert!(std::option::is_some(&inv), 1); + + let inv = std::option::extract(&mut inv); + + // Multiply s with s^{-1} and make sure you get one + assert!(scalar_is_one(&scalar_mul(&s, &inv)), 1); + assert!(scalar_is_one(&scalar_mul(&inv, &s)), 1); + } + + #[test] + fun test_scalar_from_sha2_512() { + // Test a specific message hashes correctly to the field + let str: vector = vector[]; + std::vector::append(&mut str, b"To really appreciate architecture, you may even need to commit a murder."); + std::vector::append(&mut str, b"While the programs used for The Manhattan Transcripts are of the most extreme"); + std::vector::append(&mut str, b"nature, they also parallel the most common formula plot: the archetype of"); + std::vector::append(&mut str, b"murder. Other phantasms were occasionally used to underline the fact that"); + std::vector::append(&mut str, b"perhaps all architecture, rather than being about functional standards, is"); + std::vector::append(&mut str, b"about love and death."); + + let s = new_scalar_from_sha2_512(str); + + let expected: vector = vector[ + 21, 88, 208, 252, 63, 122, 210, 152, + 154, 38, 15, 23, 16, 167, 80, 150, + 192, 221, 77, 226, 62, 25, 224, 148, + 239, 48, 176, 10, 185, 69, 168, 11 + ]; + + assert!(s.data == expected, 1) + } + + #[test] + fun test_scalar_invert() { + // Cannot invert zero + assert!(std::option::is_none(&scalar_invert(&scalar_zero())), 1); + + // One's inverse is one + let one = scalar_invert(&scalar_one()); + assert!(std::option::is_some(&one), 1); + + let one = std::option::extract(&mut one); + assert!(scalar_is_one(&one), 1); + + // Test a random point X's inverse is correct + let x = Scalar { data: X_SCALAR }; + let xinv = scalar_invert(&x); + assert!(std::option::is_some(&xinv), 1); + + let xinv = std::option::extract(&mut xinv); + let xinv_expected = Scalar { data: X_INV_SCALAR }; + + assert!(scalar_equals(&xinv, &xinv_expected), 1) + } + + #[test] + fun test_scalar_neg() { + // -(-X) == X + let x = Scalar { data: X_SCALAR }; + + let x_neg = scalar_neg(&x); + let x_neg_neg = scalar_neg(&x_neg); + + assert!(scalar_equals(&x, &x_neg_neg), 1); + } + + #[test] + fun test_scalar_neg_assign() { + let x = Scalar { data: X_SCALAR }; + let x_copy = x; + + scalar_neg_assign(&mut x); + assert!(!scalar_equals(&x, &x_copy), 1); + scalar_neg_assign(&mut x); + assert!(scalar_equals(&x, &x_copy), 1); + + assert!(scalar_equals(scalar_neg_assign(scalar_neg_assign(&mut x)), &x_copy), 1); + } + + #[test] + fun test_scalar_mul() { + // X * 1 == X + let x = Scalar { data: X_SCALAR }; + assert!(scalar_equals(&x, &scalar_mul(&x, &scalar_one())), 1); + + // Test multiplication of two random scalars + let y = Scalar { data: Y_SCALAR }; + let x_times_y = Scalar { data: X_TIMES_Y_SCALAR }; + assert!(scalar_equals(&scalar_mul(&x, &y), &x_times_y), 1); + + // A * B + assert!(scalar_equals(&scalar_mul(&Scalar { data: A_SCALAR }, &Scalar { data: B_SCALAR }), &Scalar { data: A_TIMES_B_SCALAR }), 1); + } + + #[test] + fun test_scalar_mul_assign() { + let x = Scalar { data: X_SCALAR }; + let y = Scalar { data: Y_SCALAR }; + let x_times_y = Scalar { data: X_TIMES_Y_SCALAR }; + + scalar_mul_assign(&mut x, &y); + + assert!(scalar_equals(&x, &x_times_y), 1); + } + + #[test] + fun test_scalar_add() { + // Addition reduces: \ell-1 + 1 = \ell = 0 + let ell_minus_one = Scalar { data: L_MINUS_ONE }; + assert!(scalar_is_zero(&scalar_add(&ell_minus_one, &scalar_one())), 1); + + // 1 + 1 = 2 + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_equals(&scalar_add(&scalar_one(), &scalar_one()), &two), 1); + + // A + B + assert!(scalar_equals(&scalar_add(&Scalar { data: A_SCALAR }, &Scalar { data: B_SCALAR }), &Scalar { data: A_PLUS_B_SCALAR }), 1); + } + + #[test] + fun test_scalar_sub() { + // Subtraction reduces: 0 - 1 = \ell - 1 + let ell_minus_one = Scalar { data: L_MINUS_ONE }; + assert!(scalar_equals(&scalar_sub(&scalar_zero(), &scalar_one()), &ell_minus_one), 1); + + // 2 - 1 = 1 + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_is_one(&scalar_sub(&two, &scalar_one())), 1); + + // 1 - 2 = -1 = \ell - 1 + let ell_minus_one = Scalar { data: L_MINUS_ONE }; + assert!(scalar_equals(&scalar_sub(&scalar_one(), &two), &ell_minus_one), 1); + } + + #[test] + fun test_scalar_reduced_from_32_bytes() { + // \ell + 2 = 0 + 2 = 2 (modulo \ell) + let s = std::option::extract(&mut new_scalar_reduced_from_32_bytes(L_PLUS_TWO)); + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_equals(&s, &two), 1); + + // Reducing the all 1's bit vector yields $(2^256 - 1) \mod \ell$ + let biggest = std::option::extract(&mut new_scalar_reduced_from_32_bytes(NON_CANONICAL_ALL_ONES)); + assert!(scalar_equals(&biggest, &Scalar { data: REDUCED_2_256_MINUS_1_SCALAR }), 1); + } + + #[test] + fun test_scalar_from_64_uniform_bytes() { + // Test X + 2^256 * X reduces correctly + let x_plus_2_to_256_times_x: vector = vector[]; + + std::vector::append(&mut x_plus_2_to_256_times_x, X_SCALAR); + std::vector::append(&mut x_plus_2_to_256_times_x, X_SCALAR); + + let reduced = std::option::extract(&mut new_scalar_uniform_from_64_bytes(x_plus_2_to_256_times_x)); + let expected = Scalar { data: REDUCED_X_PLUS_2_TO_256_TIMES_X_SCALAR }; + assert!(scalar_equals(&reduced, &expected), 1) + } + + #[test] + fun test_scalar_to_bytes() { + // zero is canonical + assert!(scalar_is_canonical_internal(scalar_zero().data), 1); + + // ...but if we maul it and set the high bit to 1, it is non-canonical + let non_can = scalar_zero(); + let last_byte = std::vector::borrow_mut(&mut non_can.data, 31); + *last_byte = 128; + assert!(!scalar_is_canonical_internal(non_can.data), 1); + + // This test makes sure scalar_to_bytes does not return a mutable reference to a scalar's bits + let non_can = scalar_zero(); + let bytes = scalar_to_bytes(&scalar_zero()); + let last_byte = std::vector::borrow_mut(&mut bytes, 31); + *last_byte = 128; + assert!(scalar_is_canonical_internal(non_can.data), 1); + assert!(scalar_equals(&non_can, &scalar_zero()), 1); + } + + #[test] + fun test_num_points_within_limit() { + let limit = 10000; + let i = 0; + while (i < limit) { + point_identity(); + i = i + 1; + } + } + + #[test] + #[expected_failure(abort_code=0x090004, location=Self)] + fun test_num_points_limit_exceeded() { + let limit = 10001; + let i = 0; + while (i < limit) { + point_identity(); + i = i + 1; + } + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move new file mode 100644 index 0000000..4e19b65 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move @@ -0,0 +1,253 @@ +/// This module implements a Bulletproof range proof verifier on the Ristretto255 curve. +/// +/// A Bulletproof-based zero-knowledge range proof is a proof that a Pedersen commitment +/// $c = v G + r H$ commits to an $n$-bit value $v$ (i.e., $v \in [0, 2^n)$). Currently, this module only supports +/// $n \in \{8, 16, 32, 64\}$ for the number of bits. +module aptos_std::ristretto255_bulletproofs { + use std::error; + use std::features; + use aptos_std::ristretto255_pedersen as pedersen; + use aptos_std::ristretto255::{Self, RistrettoPoint}; + + // + // Constants + // + + /// The maximum range supported by the Bulletproofs library is $[0, 2^{64})$. + const MAX_RANGE_BITS : u64 = 64; + + // + // Error codes + // + + /// There was an error deserializing the range proof. + const E_DESERIALIZE_RANGE_PROOF: u64 = 1; + + /// The committed value given to the prover is too large. + const E_VALUE_OUTSIDE_RANGE: u64 = 2; + + /// The range proof system only supports proving ranges of type $[0, 2^b)$ where $b \in \{8, 16, 32, 64\}$. + const E_RANGE_NOT_SUPPORTED: u64 = 3; + + /// The native functions have not been rolled out yet. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 4; + + // + // Structs + // + + /// Represents a zero-knowledge range proof that a value committed inside a Pedersen commitment lies in + /// `[0, 2^{MAX_RANGE_BITS})`. + struct RangeProof has copy, drop, store { + bytes: vector + } + + // + // Public functions + // + + /// Returns the maximum # of bits that the range proof system can verify proofs for. + public fun get_max_range_bits(): u64 { + MAX_RANGE_BITS + } + + /// Deserializes a range proof from a sequence of bytes. The serialization format is the same as the format in + /// the zkcrypto's `bulletproofs` library (https://docs.rs/bulletproofs/4.0.0/bulletproofs/struct.RangeProof.html#method.from_bytes). + public fun range_proof_from_bytes(bytes: vector): RangeProof { + RangeProof { + bytes + } + } + + /// Returns the byte-representation of a range proof. + public fun range_proof_to_bytes(proof: &RangeProof): vector { + proof.bytes + } + + /// Verifies a zero-knowledge range proof that the value `v` committed in `com` (under the default Bulletproofs + /// commitment key; see `pedersen::new_commitment_for_bulletproof`) satisfies $v \in [0, 2^b)$. Only works + /// for $b \in \{8, 16, 32, 64\}$. Additionally, checks that the prover used `dst` as the domain-separation + /// tag (DST). + /// + /// WARNING: The DST check is VERY important for security as it prevents proofs computed for one application + /// (a.k.a., a _domain_) with `dst_1` from verifying in a different application with `dst_2 != dst_1`. + public fun verify_range_proof_pedersen(com: &pedersen::Commitment, proof: &RangeProof, num_bits: u64, dst: vector): bool { + assert!(features::bulletproofs_enabled(), error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)); + + verify_range_proof_internal( + ristretto255::point_to_bytes(&pedersen::commitment_as_compressed_point(com)), + &ristretto255::basepoint(), &ristretto255::hash_to_point_base(), + proof.bytes, + num_bits, + dst + ) + } + + /// Verifies a zero-knowledge range proof that the value `v` committed in `com` (as v * val_base + r * rand_base, + /// for some randomness `r`) satisfies `v` in `[0, 2^num_bits)`. Only works for `num_bits` in `{8, 16, 32, 64}`. + public fun verify_range_proof( + com: &RistrettoPoint, + val_base: &RistrettoPoint, rand_base: &RistrettoPoint, + proof: &RangeProof, num_bits: u64, dst: vector): bool + { + assert!(features::bulletproofs_enabled(), error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)); + + verify_range_proof_internal( + ristretto255::point_to_bytes(&ristretto255::point_compress(com)), + val_base, rand_base, + proof.bytes, num_bits, dst + ) + } + + #[test_only] + /// Computes a range proof for the Pedersen commitment to 'val' with randomness 'r', under the default Bulletproofs + /// commitment key; see `pedersen::new_commitment_for_bulletproof`. Returns the said commitment too. + /// Only works for `num_bits` in `{8, 16, 32, 64}`. + public fun prove_range_pedersen(val: &Scalar, r: &Scalar, num_bits: u64, dst: vector): (RangeProof, pedersen::Commitment) { + let (bytes, compressed_comm) = prove_range_internal(scalar_to_bytes(val), scalar_to_bytes(r), num_bits, dst, &ristretto255::basepoint(), &ristretto255::hash_to_point_base()); + let point = ristretto255::new_compressed_point_from_bytes(compressed_comm); + let point = &std::option::extract(&mut point); + + ( + RangeProof { bytes }, + pedersen::commitment_from_compressed(point) + ) + } + + // + // Native functions + // + + /// Aborts with `error::invalid_argument(E_DESERIALIZE_RANGE_PROOF)` if `proof` is not a valid serialization of a + /// range proof. + /// Aborts with `error::invalid_argument(E_RANGE_NOT_SUPPORTED)` if an unsupported `num_bits` is provided. + native fun verify_range_proof_internal( + com: vector, + val_base: &RistrettoPoint, + rand_base: &RistrettoPoint, + proof: vector, + num_bits: u64, + dst: vector): bool; + + #[test_only] + /// Returns a tuple consisting of (1) a range proof for 'val' committed with randomness 'r' under the default Bulletproofs + /// commitment key and (2) the commitment itself. + /// + /// Aborts with `error::invalid_argument(E_RANGE_NOT_SUPPORTED)` if an unsupported `num_bits` is provided. + /// Aborts with `error::invalid_argument(E_VALUE_OUTSIDE_RANGE)` if an `val_base` is not `num_bits` wide. + native fun prove_range_internal( + val: vector, + r: vector, + num_bits: u64, + dst: vector, + val_base: &RistrettoPoint, + rand_base: &RistrettoPoint): (vector, vector); + + // + // Testing + // + + #[test_only] + use aptos_std::ristretto255::{Scalar, scalar_to_bytes, point_equals}; + + #[test_only] + const A_DST: vector = b"AptosBulletproofs"; + #[test_only] + const A_VALUE: vector = x"870c2fa1b2e9ac45000000000000000000000000000000000000000000000000"; // i.e., 5020644638028926087u64 + #[test_only] + const A_BLINDER: vector = x"e7c7b42b75503bfc7b1932783786d227ebf88f79da752b68f6b865a9c179640c"; + // Pedersen commitment to A_VALUE with randomness A_BLINDER + #[test_only] + const A_COMM: vector = x"0a665260a4e42e575882c2cdcb3d0febd6cf168834f6de1e9e61e7b2e53dbf14"; + // Range proof for A_COMM using domain-separation tag in A_DST, and MAX_RANGE_BITS + #[test_only] + const A_RANGE_PROOF_PEDERSEN: vector = x"d8d422d3fb9511d1942b78e3ec1a8c82fe1c01a0a690c55a4761e7e825633a753cca816667d2cbb716fe04a9c199cad748c2d4e59de4ed04fedf5f04f4341a74ae75b63c1997fd65d5fb3a8c03ad8771abe2c0a4f65d19496c11d948d6809503eac4d996f2c6be4e64ebe2df31102c96f106695bdf489dc9290c93b4d4b5411fb6298d0c33afa57e2e1948c38ef567268a661e7b1c099272e29591e717930a06a2c6e0e2d56aedea3078fd59334634f1a4543069865409eba074278f191039083102a9a0621791a9be09212a847e22061e083d7a712b05bca7274b25e4cb1201c679c4957f0842d7661fa1d3f5456a651e89112628b456026f8ad3a7abeaba3fec8031ec8b0392c0aa6c96205f7b21b0c2d6b5d064bd5bd1a1d91c41625d910688fa0dca35ec0f0e31a45792f8d6a330be970a22e1e0773111a083de893c89419ee7de97295978de90bcdf873a2826746809e64f9143417dbed09fa1c124e673febfed65c137cc45fabda963c96b64645802d1440cba5e58717e539f55f3321ab0c0f60410fba70070c5db500fee874265a343a2a59773fd150bcae09321a5166062e176e2e76bef0e3dd1a9250bcb7f4c971c10f0b24eb2a94e009b72c1fc21ee4267881e27b4edba8bed627ddf37e0c53cd425bc279d0c50d154d136503e54882e9541820d6394bd52ca2b438fd8c517f186fec0649c4846c4e43ce845d80e503dee157ce55392188039a7efc78719107ab989db8d9363b9dfc1946f01a84dbca5e742ed5f30b07ac61cf17ce2cf2c6a49d799ed3968a63a3ccb90d9a0e50960d959f17f202dd5cf0f2c375a8a702e063d339e48c0227e7cf710157f63f13136d8c3076c672ea2c1028fc1825366a145a4311de6c2cc46d3144ae3d2bc5808819b9817be3fce1664ecb60f74733e75e97ca8e567d1b81bdd4c56c7a340ba00"; + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010003, location = Self)] + fun test_unsupported_ranges(fx: signer) { + features::change_feature_flags(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let comm = ristretto255::new_point_from_bytes(A_COMM); + let comm = std::option::extract(&mut comm); + let comm = pedersen::commitment_from_point(comm); + + assert!(verify_range_proof_pedersen( + &comm, + &range_proof_from_bytes(A_RANGE_PROOF_PEDERSEN), 10, A_DST), 1); + } + + #[test(fx = @std)] + fun test_prover(fx: signer) { + features::change_feature_flags(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let v = ristretto255::new_scalar_from_u64(59); + let r = ristretto255::new_scalar_from_bytes(A_BLINDER); + let r = std::option::extract(&mut r); + let num_bits = 8; + + let (proof, comm) = prove_range_pedersen(&v, &r, num_bits, A_DST); + + assert!(verify_range_proof_pedersen(&comm, &proof, 64, A_DST) == false, 1); + assert!(verify_range_proof_pedersen(&comm, &proof, 32, A_DST) == false, 1); + assert!(verify_range_proof_pedersen(&comm, &proof, 16, A_DST) == false, 1); + assert!(verify_range_proof_pedersen(&comm, &proof, num_bits, A_DST), 1); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010001, location = Self)] + fun test_empty_range_proof(fx: signer) { + features::change_feature_flags(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let proof = &range_proof_from_bytes(vector[ ]); + let num_bits = 64; + let com = pedersen::new_commitment_for_bulletproof( + &ristretto255::scalar_one(), + &ristretto255::new_scalar_from_sha2_512(b"hello random world") + ); + + // This will fail with error::invalid_argument(E_DESERIALIZE_RANGE_PROOF) + verify_range_proof_pedersen(&com, proof, num_bits, A_DST); + } + + #[test(fx = @std)] + fun test_valid_range_proof_verifies_against_comm(fx: signer) { + features::change_feature_flags(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let value = ristretto255::new_scalar_from_bytes(A_VALUE); + let value = std::option::extract(&mut value); + + let blinder = ristretto255::new_scalar_from_bytes(A_BLINDER); + let blinder = std::option::extract(&mut blinder); + + let comm = pedersen::new_commitment_for_bulletproof(&value, &blinder); + + let expected_comm = std::option::extract(&mut ristretto255::new_point_from_bytes(A_COMM)); + assert!(point_equals(pedersen::commitment_as_point(&comm), &expected_comm), 1); + + assert!(verify_range_proof_pedersen( + &comm, + &range_proof_from_bytes(A_RANGE_PROOF_PEDERSEN), MAX_RANGE_BITS, A_DST), 1); + } + + #[test(fx = @std)] + fun test_invalid_range_proof_fails_verification(fx: signer) { + features::change_feature_flags(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let comm = ristretto255::new_point_from_bytes(A_COMM); + let comm = std::option::extract(&mut comm); + let comm = pedersen::commitment_from_point(comm); + + // Take a valid proof... + let range_proof_invalid = A_RANGE_PROOF_PEDERSEN; + + // ...and modify a byte in the middle of the proof + let pos = std::vector::length(&range_proof_invalid) / 2; + let byte = std::vector::borrow_mut(&mut range_proof_invalid, pos); + *byte = *byte + 1; + + assert!(verify_range_proof_pedersen( + &comm, + &range_proof_from_bytes(range_proof_invalid), MAX_RANGE_BITS, A_DST) == false, 1); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_elgamal.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_elgamal.move new file mode 100644 index 0000000..a6912e7 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_elgamal.move @@ -0,0 +1,234 @@ +/// This module implements an ElGamal encryption API, over the Ristretto255 curve, that can be used with the +/// Bulletproofs module. +/// +/// An ElGamal *ciphertext* is an encryption of a value `v` under a basepoint `G` and public key `Y = sk * G`, where `sk` +/// is the corresponding secret key, is `(v * G + r * Y, r * G)`, for a random scalar `r`. +/// +/// Note that we place the value `v` "in the exponent" of `G` so that ciphertexts are additively homomorphic: i.e., so +/// that `Enc_Y(v, r) + Enc_Y(v', r') = Enc_Y(v + v', r + r')` where `v, v'` are plaintext messages, `Y` is a public key and `r, r'` +/// are the randomness of the ciphertexts. + +module aptos_std::ristretto255_elgamal { + use aptos_std::ristretto255::{Self, RistrettoPoint, Scalar, CompressedRistretto, point_compress}; + use std::option::Option; + use std::vector; + + // + // Structs + // + + /// An ElGamal ciphertext. + struct Ciphertext has drop { + left: RistrettoPoint, // v * G + r * Y + right: RistrettoPoint, // r * G + } + + /// A compressed ElGamal ciphertext. + struct CompressedCiphertext has store, copy, drop { + left: CompressedRistretto, + right: CompressedRistretto, + } + + /// An ElGamal public key. + struct CompressedPubkey has store, copy, drop { + point: CompressedRistretto, + } + + // + // Public functions + // + + /// Creates a new public key from a serialized Ristretto255 point. + public fun new_pubkey_from_bytes(bytes: vector): Option { + let point = ristretto255::new_compressed_point_from_bytes(bytes); + if (std::option::is_some(&mut point)) { + let pk = CompressedPubkey { + point: std::option::extract(&mut point) + }; + std::option::some(pk) + } else { + std::option::none() + } + } + + /// Given an ElGamal public key `pubkey`, returns the byte representation of that public key. + public fun pubkey_to_bytes(pubkey: &CompressedPubkey): vector { + ristretto255::compressed_point_to_bytes(pubkey.point) + } + + /// Given a public key `pubkey`, returns the underlying `RistrettoPoint` representing that key. + public fun pubkey_to_point(pubkey: &CompressedPubkey): RistrettoPoint { + ristretto255::point_decompress(&pubkey.point) + } + + /// Given a public key, returns the underlying `CompressedRistretto` point representing that key. + public fun pubkey_to_compressed_point(pubkey: &CompressedPubkey): CompressedRistretto { + pubkey.point + } + + /// Creates a new ciphertext from two serialized Ristretto255 points: the first 32 bytes store `r * G` while the + /// next 32 bytes store `v * G + r * Y`, where `Y` is the public key. + public fun new_ciphertext_from_bytes(bytes: vector): Option { + if(vector::length(&bytes) != 64) { + return std::option::none() + }; + + let bytes_right = vector::trim(&mut bytes, 32); + + let left_point = ristretto255::new_point_from_bytes(bytes); + let right_point = ristretto255::new_point_from_bytes(bytes_right); + + if (std::option::is_some(&mut left_point) && std::option::is_some(&mut right_point)) { + std::option::some(Ciphertext { + left: std::option::extract(&mut left_point), + right: std::option::extract(&mut right_point) + }) + } else { + std::option::none() + } + } + + /// Creates a new ciphertext `(val * G + 0 * Y, 0 * G) = (val * G, 0 * G)` where `G` is the Ristretto255 basepoint + /// and the randomness is set to zero. + public fun new_ciphertext_no_randomness(val: &Scalar): Ciphertext { + Ciphertext { + left: ristretto255::basepoint_mul(val), + right: ristretto255::point_identity(), + } + } + + /// Moves a pair of Ristretto points into an ElGamal ciphertext. + public fun ciphertext_from_points(left: RistrettoPoint, right: RistrettoPoint): Ciphertext { + Ciphertext { + left, + right, + } + } + + /// Moves a pair of `CompressedRistretto` points into an ElGamal ciphertext. + public fun ciphertext_from_compressed_points(left: CompressedRistretto, right: CompressedRistretto): CompressedCiphertext { + CompressedCiphertext { + left, + right, + } + } + + /// Given a ciphertext `ct`, serializes that ciphertext into bytes. + public fun ciphertext_to_bytes(ct: &Ciphertext): vector { + let bytes_left = ristretto255::point_to_bytes(&ristretto255::point_compress(&ct.left)); + let bytes_right = ristretto255::point_to_bytes(&ristretto255::point_compress(&ct.right)); + let bytes = vector::empty(); + vector::append(&mut bytes, bytes_left); + vector::append(&mut bytes, bytes_right); + bytes + } + + /// Moves the ciphertext into a pair of `RistrettoPoint`'s. + public fun ciphertext_into_points(c: Ciphertext): (RistrettoPoint, RistrettoPoint) { + let Ciphertext { left, right } = c; + (left, right) + } + + /// Returns the pair of `RistrettoPoint`'s representing the ciphertext. + public fun ciphertext_as_points(c: &Ciphertext): (&RistrettoPoint, &RistrettoPoint) { + (&c.left, &c.right) + } + + /// Creates a new compressed ciphertext from a decompressed ciphertext. + public fun compress_ciphertext(ct: &Ciphertext): CompressedCiphertext { + CompressedCiphertext { + left: point_compress(&ct.left), + right: point_compress(&ct.right), + } + } + + /// Creates a new decompressed ciphertext from a compressed ciphertext. + public fun decompress_ciphertext(ct: &CompressedCiphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_decompress(&ct.left), + right: ristretto255::point_decompress(&ct.right), + } + } + + /// Homomorphically combines two ciphertexts `lhs` and `rhs` as `lhs + rhs`. + /// Useful for re-randomizing the ciphertext or updating the committed value. + public fun ciphertext_add(lhs: &Ciphertext, rhs: &Ciphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_add(&lhs.left, &rhs.left), + right: ristretto255::point_add(&lhs.right, &rhs.right), + } + } + + /// Like `ciphertext_add` but assigns `lhs = lhs + rhs`. + public fun ciphertext_add_assign(lhs: &mut Ciphertext, rhs: &Ciphertext) { + ristretto255::point_add_assign(&mut lhs.left, &rhs.left); + ristretto255::point_add_assign(&mut lhs.right, &rhs.right); + } + + /// Homomorphically combines two ciphertexts `lhs` and `rhs` as `lhs - rhs`. + /// Useful for re-randomizing the ciphertext or updating the committed value. + public fun ciphertext_sub(lhs: &Ciphertext, rhs: &Ciphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_sub(&lhs.left, &rhs.left), + right: ristretto255::point_sub(&lhs.right, &rhs.right), + } + } + + /// Like `ciphertext_add` but assigns `lhs = lhs - rhs`. + public fun ciphertext_sub_assign(lhs: &mut Ciphertext, rhs: &Ciphertext) { + ristretto255::point_sub_assign(&mut lhs.left, &rhs.left); + ristretto255::point_sub_assign(&mut lhs.right, &rhs.right); + } + + /// Creates a copy of this ciphertext. + public fun ciphertext_clone(c: &Ciphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_clone(&c.left), + right: ristretto255::point_clone(&c.right), + } + } + + /// Returns true if the two ciphertexts are identical: i.e., same value and same randomness. + public fun ciphertext_equals(lhs: &Ciphertext, rhs: &Ciphertext): bool { + ristretto255::point_equals(&lhs.left, &rhs.left) && + ristretto255::point_equals(&lhs.right, &rhs.right) + } + + /// Returns the `RistrettoPoint` in the ciphertext which contains the encrypted value in the exponent. + public fun get_value_component(ct: &Ciphertext): &RistrettoPoint { + &ct.left + } + + // + // Test-only functions + // + + #[test_only] + /// Given an ElGamal secret key `sk`, returns the corresponding ElGamal public key as `sk * G`. + public fun pubkey_from_secret_key(sk: &Scalar): CompressedPubkey { + let point = ristretto255::basepoint_mul(sk); + CompressedPubkey { + point: point_compress(&point) + } + } + + #[test_only] + /// Returns a ciphertext (v * point + r * pubkey, r * point) where `point` is *any* Ristretto255 point, + /// `pubkey` is the public key and `r` is the randomness. + public fun new_ciphertext(v: &Scalar, point: &RistrettoPoint, r: &Scalar, pubkey: &CompressedPubkey): Ciphertext { + Ciphertext { + left: ristretto255::double_scalar_mul(v, point, r, &pubkey_to_point(pubkey)), + right: ristretto255::point_mul(point, r), + } + } + + #[test_only] + /// Returns a ciphertext (v * basepoint + r * pubkey, r * basepoint) where `basepoint` is the Ristretto255 basepoint + /// `pubkey` is the public key and `r` is the randomness. + public fun new_ciphertext_with_basepoint(v: &Scalar, r: &Scalar, pubkey: &CompressedPubkey): Ciphertext { + Ciphertext { + left: ristretto255::basepoint_double_mul(r, &pubkey_to_point(pubkey), v), + right: ristretto255::basepoint_mul(r), + } + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_pedersen.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_pedersen.move new file mode 100644 index 0000000..7a49a04 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/ristretto255_pedersen.move @@ -0,0 +1,158 @@ +/// This module implements a Pedersen commitment API, over the Ristretto255 curve, that can be used with the +/// Bulletproofs module. +/// +/// A Pedersen commitment to a value `v` under _commitment key_ `(g, h)` is `v * g + r * h`, for a random scalar `r`. + +module aptos_std::ristretto255_pedersen { + use aptos_std::ristretto255::{Self, RistrettoPoint, Scalar, CompressedRistretto, point_compress}; + use std::option::Option; + + // + // Constants + // + + /// The default Pedersen randomness base `h` used in our underlying Bulletproofs library. + /// This is obtained by hashing the compressed Ristretto255 basepoint using SHA3-512 (not SHA2-512). + const BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE : vector = x"8c9240b456a9e6dc65c377a1048d745f94a08cdb7f44cbcd7b46f34048871134"; + + // + // Structs + // + + /// A Pedersen commitment to some value with some randomness. + struct Commitment has drop { + point: RistrettoPoint, + } + + // + // Public functions + // + + /// Creates a new public key from a serialized Ristretto255 point. + public fun new_commitment_from_bytes(bytes: vector): Option { + let point = ristretto255::new_point_from_bytes(bytes); + if (std::option::is_some(&mut point)) { + let comm = Commitment { + point: std::option::extract(&mut point) + }; + std::option::some(comm) + } else { + std::option::none() + } + } + + /// Returns a commitment as a serialized byte array + public fun commitment_to_bytes(comm: &Commitment): vector { + ristretto255::point_to_bytes(&ristretto255::point_compress(&comm.point)) + } + + /// Moves a Ristretto point into a Pedersen commitment. + public fun commitment_from_point(point: RistrettoPoint): Commitment { + Commitment { + point + } + } + + /// Deserializes a commitment from a compressed Ristretto point. + public fun commitment_from_compressed(point: &CompressedRistretto): Commitment { + Commitment { + point: ristretto255::point_decompress(point) + } + } + + /// Returns a commitment `v * val_base + r * rand_base` where `(val_base, rand_base)` is the commitment key. + public fun new_commitment(v: &Scalar, val_base: &RistrettoPoint, r: &Scalar, rand_base: &RistrettoPoint): Commitment { + Commitment { + point: ristretto255::double_scalar_mul(v, val_base, r, rand_base) + } + } + + /// Returns a commitment `v * G + r * rand_base` where `G` is the Ristretto255 basepoint. + public fun new_commitment_with_basepoint(v: &Scalar, r: &Scalar, rand_base: &RistrettoPoint): Commitment { + Commitment { + point: ristretto255::basepoint_double_mul(r, rand_base, v) + } + } + + /// Returns a commitment `v * G + r * H` where `G` is the Ristretto255 basepoint and `H` is the default randomness + /// base used in the Bulletproofs library (i.e., `BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE`). + public fun new_commitment_for_bulletproof(v: &Scalar, r: &Scalar): Commitment { + let rand_base = ristretto255::new_point_from_bytes(BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE); + let rand_base = std::option::extract(&mut rand_base); + + Commitment { + point: ristretto255::basepoint_double_mul(r, &rand_base, v) + } + } + + /// Homomorphically combines two commitments `lhs` and `rhs` as `lhs + rhs`. + /// Useful for re-randomizing the commitment or updating the committed value. + public fun commitment_add(lhs: &Commitment, rhs: &Commitment): Commitment { + Commitment { + point: ristretto255::point_add(&lhs.point, &rhs.point) + } + } + + /// Like `commitment_add` but assigns `lhs = lhs + rhs`. + public fun commitment_add_assign(lhs: &mut Commitment, rhs: &Commitment) { + ristretto255::point_add_assign(&mut lhs.point, &rhs.point); + } + + /// Homomorphically combines two commitments `lhs` and `rhs` as `lhs - rhs`. + /// Useful for re-randomizing the commitment or updating the committed value. + public fun commitment_sub(lhs: &Commitment, rhs: &Commitment): Commitment { + Commitment { + point: ristretto255::point_sub(&lhs.point, &rhs.point) + } + } + + /// Like `commitment_add` but assigns `lhs = lhs - rhs`. + public fun commitment_sub_assign(lhs: &mut Commitment, rhs: &Commitment) { + ristretto255::point_sub_assign(&mut lhs.point, &rhs.point); + } + + /// Creates a copy of this commitment. + public fun commitment_clone(c: &Commitment): Commitment { + Commitment { + point: ristretto255::point_clone(&c.point) + } + } + + /// Returns true if the two commitments are identical: i.e., same value and same randomness. + public fun commitment_equals(lhs: &Commitment, rhs: &Commitment): bool { + ristretto255::point_equals(&lhs.point, &rhs.point) + } + + /// Returns the underlying elliptic curve point representing the commitment as an in-memory `RistrettoPoint`. + public fun commitment_as_point(c: &Commitment): &RistrettoPoint { + &c.point + } + + /// Returns the Pedersen commitment as a `CompressedRistretto` point. + public fun commitment_as_compressed_point(c: &Commitment): CompressedRistretto { + point_compress(&c.point) + } + + /// Moves the Commitment into a CompressedRistretto point. + public fun commitment_into_point(c: Commitment): RistrettoPoint { + let Commitment { point } = c; + point + } + + /// Moves the Commitment into a `CompressedRistretto` point. + public fun commitment_into_compressed_point(c: Commitment): CompressedRistretto { + point_compress(&c.point) + } + + /// Returns the randomness base compatible with the Bulletproofs module. + /// + /// Recal that a Bulletproof range proof attests, in zero-knowledge, that a value `v` inside a Pedersen commitment + /// `v * g + r * h` is sufficiently "small" (e.g., is 32-bits wide). Here, `h` is referred to as the + /// "randomness base" of the commitment scheme. + /// + /// Bulletproof has a default choice for `g` and `h` and this function returns the default `h` as used in the + /// Bulletproofs Move module. + public fun randomness_base_for_bulletproof(): RistrettoPoint { + std::option::extract(&mut ristretto255::new_point_from_bytes(BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE)) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/secp256k1.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/secp256k1.move new file mode 100644 index 0000000..8acf936 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/secp256k1.move @@ -0,0 +1,114 @@ +/// This module implements ECDSA signatures based on the prime-order secp256k1 ellptic curve (i.e., cofactor is 1). + +module aptos_std::secp256k1 { + use std::option::Option; + + /// An error occurred while deserializing, for example due to wrong input size. + const E_DESERIALIZE: u64 = 1; // This code must be the same, if ever returned from the native Rust implementation. + + /// The size of a secp256k1-based ECDSA public key, in bytes. + const RAW_PUBLIC_KEY_NUM_BYTES: u64 = 64; + //const COMPRESSED_PUBLIC_KEY_SIZE: u64 = 33; + + /// The size of a secp256k1-based ECDSA signature, in bytes. + const SIGNATURE_NUM_BYTES: u64 = 64; + + /// A 64-byte ECDSA public key. + struct ECDSARawPublicKey has copy, drop, store { + bytes: vector + } + + /// A 64-byte ECDSA signature. + struct ECDSASignature has copy, drop, store { + bytes: vector + } + + /// Constructs an ECDSASignature struct from the given 64 bytes. + public fun ecdsa_signature_from_bytes(bytes: vector): ECDSASignature { + assert!(std::vector::length(&bytes) == SIGNATURE_NUM_BYTES, std::error::invalid_argument(E_DESERIALIZE)); + ECDSASignature { bytes } + } + + /// Constructs an ECDSARawPublicKey struct, given a 64-byte raw representation. + public fun ecdsa_raw_public_key_from_64_bytes(bytes: vector): ECDSARawPublicKey { + assert!(std::vector::length(&bytes) == RAW_PUBLIC_KEY_NUM_BYTES, std::error::invalid_argument(E_DESERIALIZE)); + ECDSARawPublicKey { bytes } + } + + /// Serializes an ECDSARawPublicKey struct to 64-bytes. + public fun ecdsa_raw_public_key_to_bytes(pk: &ECDSARawPublicKey): vector { + pk.bytes + } + + /// Serializes an ECDSASignature struct to 64-bytes. + public fun ecdsa_signature_to_bytes(sig: &ECDSASignature): vector { + sig.bytes + } + + /// Recovers the signer's raw (64-byte) public key from a secp256k1 ECDSA `signature` given the `recovery_id` and the signed + /// `message` (32 byte digest). + /// + /// Note that an invalid signature, or a signature from a different message, will result in the recovery of an + /// incorrect public key. This recovery algorithm can only be used to check validity of a signature if the signer's + /// public key (or its hash) is known beforehand. + public fun ecdsa_recover( + message: vector, + recovery_id: u8, + signature: &ECDSASignature, + ): Option { + let (pk, success) = ecdsa_recover_internal(message, recovery_id, signature.bytes); + if (success) { + std::option::some(ecdsa_raw_public_key_from_64_bytes(pk)) + } else { + std::option::none() + } + } + + // + // Native functions + // + + /// Returns `(public_key, true)` if `signature` verifies on `message` under the recovered `public_key` + /// and returns `([], false)` otherwise. + native fun ecdsa_recover_internal( + message: vector, + recovery_id: u8, + signature: vector + ): (vector, bool); + + // + // Tests + // + + #[test] + /// Test on a valid secp256k1 ECDSA signature created using sk = x"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + fun test_ecdsa_recover() { + use std::hash; + + let pk = ecdsa_recover( + hash::sha2_256(b"test aptos secp256k1"), + 0, + &ECDSASignature { bytes: x"f7ad936da03f948c14c542020e3c5f4e02aaacd1f20427c11aa6e2fbf8776477646bba0e1a37f9e7c777c423a1d2849baafd7ff6a9930814a43c3f80d59db56f" }, + ); + assert!(std::option::is_some(&pk), 1); + assert!(std::option::extract(&mut pk).bytes == x"4646ae5047316b4230d0086c8acec687f00b1cd9d1dc634f6cb358ac0a9a8ffffe77b4dd0a4bfb95851f3b7355c781dd60f8418fc8a65d14907aff47c903a559", 1); + + // Flipped bits; Signature stays valid + let pk = ecdsa_recover( + hash::sha2_256(b"test aptos secp256k1"), + 0, + // NOTE: A '7' was flipped to an 'f' here + &ECDSASignature { bytes: x"f7ad936da03f948c14c542020e3c5f4e02aaacd1f20427c11aa6e2fbf8776477646bba0e1a37f9e7c7f7c423a1d2849baafd7ff6a9930814a43c3f80d59db56f" }, + ); + assert!(std::option::is_some(&pk), 1); + assert!(std::option::extract(&mut pk).bytes != x"4646ae5047316b4230d0086c8acec687f00b1cd9d1dc634f6cb358ac0a9a8ffffe77b4dd0a4bfb95851f3b7355c781dd60f8418fc8a65d14907aff47c903a559", 1); + + // Flipped bits; Signature becomes invalid + let pk = ecdsa_recover( + hash::sha2_256(b"test aptos secp256k1"), + 0, + &ECDSASignature { bytes: x"ffad936da03f948c14c542020e3c5f4e02aaacd1f20427c11aa6e2fbf8776477646bba0e1a37f9e7c7f7c423a1d2849baafd7ff6a9930814a43c3f80d59db56f" }, + ); + assert!(std::option::is_none(&pk), 1); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/simple_map.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/simple_map.move new file mode 100644 index 0000000..98ae46c --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/simple_map.move @@ -0,0 +1,319 @@ +/// This module provides a solution for unsorted 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(N) time +/// 4) The keys are unsorted. +/// 5) Adds and removals take O(N) time +module aptos_std::simple_map { + use std::error; + use std::option; + use std::vector; + + /// 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) + } + + /// Create an empty SimpleMap. + public fun new(): SimpleMap { + SimpleMap { + data: vector::empty(), + } + } + + /// Create a SimpleMap from a vector of keys and values. The keys must be unique. + public fun new_from( + keys: vector, + values: vector, + ): SimpleMap { + let map = new(); + add_all(&mut map, keys, values); + map + } + + #[deprecated] + /// Create an empty SimpleMap. + /// This function is deprecated, use `new` instead. + public fun create(): SimpleMap { + new() + } + + public fun borrow( + map: &SimpleMap, + key: &Key, + ): &Value { + let maybe_idx = find(map, key); + assert!(option::is_some(&maybe_idx), error::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), error::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); + } + + /// Add a key/value pair to the map. The key must not already exist. + public fun add( + map: &mut SimpleMap, + key: Key, + value: Value, + ) { + let maybe_idx = find(map, &key); + assert!(option::is_none(&maybe_idx), error::invalid_argument(EKEY_ALREADY_EXISTS)); + + vector::push_back(&mut map.data, Element { key, value }); + } + + /// Add multiple key/value pairs to the map. The keys must not already exist. + public fun add_all( + map: &mut SimpleMap, + keys: vector, + values: vector, + ) { + vector::zip(keys, values, |key, value| { + add(map, key, value); + }); + } + + /// Insert key/value pair or update an existing key to a new value + public fun upsert( + map: &mut SimpleMap, + key: Key, + value: Value + ): (std::option::Option, std::option::Option) { + let data = &mut map.data; + let len = vector::length(data); + let i = 0; + while (i < len) { + let element = vector::borrow(data, i); + if (&element.key == &key) { + vector::push_back(data, Element { key, value }); + vector::swap(data, i, len); + let Element { key, value } = vector::pop_back(data); + return (std::option::some(key), std::option::some(value)) + }; + i = i + 1; + }; + vector::push_back(&mut map.data, Element { key, value }); + (std::option::none(), std::option::none()) + } + + /// Return all keys in the map. This requires keys to be copyable. + public fun keys(map: &SimpleMap): vector { + vector::map_ref(&map.data, |e| { + let e: &Element = e; + e.key + }) + } + + /// Return all values in the map. This requires values to be copyable. + public fun values(map: &SimpleMap): vector { + vector::map_ref(&map.data, |e| { + let e: &Element = e; + e.value + }) + } + + /// Transform the map into two vectors with the keys and values respectively + /// Primarily used to destroy a map + public fun to_vec_pair( + map: SimpleMap): (vector, vector) { + let keys: vector = vector::empty(); + let values: vector = vector::empty(); + let SimpleMap { data } = map; + vector::for_each(data, |e| { + let Element { key, value } = e; + vector::push_back(&mut keys, key); + vector::push_back(&mut values, value); + }); + (keys, values) + } + + /// For maps that cannot be dropped this is a utility to destroy them + /// using lambdas to destroy the individual keys and values. + public inline fun destroy( + map: SimpleMap, + dk: |Key|, + dv: |Value| + ) { + let (keys, values) = to_vec_pair(map); + vector::destroy(keys, |_k| dk(_k)); + vector::destroy(values, |_v| dv(_v)); + } + + /// Remove a key/value pair from the map. The key must exist. + public fun remove( + map: &mut SimpleMap, + key: &Key, + ): (Key, Value) { + let maybe_idx = find(map, key); + assert!(option::is_some(&maybe_idx), error::invalid_argument(EKEY_NOT_FOUND)); + let placement = option::extract(&mut maybe_idx); + let Element { key, value } = vector::swap_remove(&mut map.data, placement); + (key, value) + } + + fun find( + map: &SimpleMap, + key: &Key, + ): option::Option { + let leng = vector::length(&map.data); + let i = 0; + while (i < leng) { + let element = vector::borrow(&map.data, i); + if (&element.key == key) { + return option::some(i) + }; + i = i + 1; + }; + option::none() + } + + #[test] + public fun test_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_add_all() { + let map = create(); + + assert!(length(&map) == 0, 0); + add_all(&mut map, vector[1, 2, 3], vector[10, 20, 30]); + assert!(length(&map) == 3, 1); + assert!(borrow(&map, &1) == &10, 2); + assert!(borrow(&map, &2) == &20, 3); + assert!(borrow(&map, &3) == &30, 4); + + remove(&mut map, &1); + remove(&mut map, &2); + remove(&mut map, &3); + destroy_empty(map); + } + + #[test] + public fun test_keys() { + let map = create(); + assert!(keys(&map) == vector[], 0); + add(&mut map, 2, 1); + add(&mut map, 3, 1); + + assert!(keys(&map) == vector[2, 3], 0); + } + + #[test] + public fun test_values() { + let map = create(); + assert!(values(&map) == vector[], 0); + add(&mut map, 2, 1); + add(&mut map, 3, 2); + + assert!(values(&map) == vector[1, 2], 0); + } + + #[test] + #[expected_failure] + public fun test_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 test_remove_twice() { + let map = create(); + add(&mut map, 3, 1); + remove(&mut map, &3); + remove(&mut map, &3); + + destroy_empty(map); + } + + #[test] + public fun test_upsert_test() { + let map = create(); + // test adding 3 elements using upsert + upsert(&mut map, 1, 1); + upsert(&mut map, 2, 2); + upsert(&mut map, 3, 3); + + assert!(length(&map) == 3, 0); + assert!(contains_key(&map, &1), 1); + assert!(contains_key(&map, &2), 2); + assert!(contains_key(&map, &3), 3); + assert!(borrow(&map, &1) == &1, 4); + assert!(borrow(&map, &2) == &2, 5); + assert!(borrow(&map, &3) == &3, 6); + + // change mapping 1->1 to 1->4 + upsert(&mut map, 1, 4); + + assert!(length(&map) == 3, 7); + assert!(contains_key(&map, &1), 8); + assert!(borrow(&map, &1) == &4, 9); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_table.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_table.move new file mode 100644 index 0000000..cde4e19 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_table.move @@ -0,0 +1,544 @@ +/// A smart table implementation based on linear hashing. (https://en.wikipedia.org/wiki/Linear_hashing) +/// Compare to Table, it uses less storage slots but has higher chance of collision, a trade-off between space and time. +/// Compare to other dynamic hashing implementation, linear hashing splits one bucket a time instead of doubling buckets +/// when expanding to avoid unexpected gas cost. +/// SmartTable uses faster hash function SipHash instead of cryptographically secure hash functions like sha3-256 since +/// it tolerates collisions. +module aptos_std::smart_table { + use std::error; + use std::vector; + use aptos_std::aptos_hash::sip_hash_from_value; + use aptos_std::table_with_length::{Self, TableWithLength}; + use aptos_std::type_info::size_of_val; + use aptos_std::math64::max; + use aptos_std::simple_map::SimpleMap; + use aptos_std::simple_map; + + /// Key not found in the smart table + const ENOT_FOUND: u64 = 1; + /// Smart table capacity must be larger than 0 + const EZERO_CAPACITY: u64 = 2; + /// Cannot destroy non-empty hashmap + const ENOT_EMPTY: u64 = 3; + /// Key already exists + const EALREADY_EXIST: u64 = 4; + /// Invalid load threshold percent to trigger split. + const EINVALID_LOAD_THRESHOLD_PERCENT: u64 = 5; + /// Invalid target bucket size. + const EINVALID_TARGET_BUCKET_SIZE: u64 = 6; + /// Invalid target bucket size. + const EEXCEED_MAX_BUCKET_SIZE: u64 = 7; + + /// SmartTable entry contains both the key and value. + struct Entry has copy, drop, store { + hash: u64, + key: K, + value: V, + } + + struct SmartTable has store { + buckets: TableWithLength>>, + num_buckets: u64, + // number of bits to represent num_buckets + level: u8, + // total number of items + size: u64, + // Split will be triggered when target load threshold in percentage is reached when adding a new entry. + split_load_threshold: u8, + // The target size of each bucket, which is NOT enforced so oversized buckets can exist. + target_bucket_size: u64, + } + + /// Create an empty SmartTable with default configurations. + public fun new(): SmartTable { + new_with_config(0, 0, 0) + } + + /// Create an empty SmartTable with customized configurations. + /// `num_initial_buckets`: The number of buckets on initialization. 0 means using default value. + /// `split_load_threshold`: The percent number which once reached, split will be triggered. 0 means using default + /// value. + /// `target_bucket_size`: The target number of entries per bucket, though not guaranteed. 0 means not set and will + /// dynamically assgined by the contract code. + public fun new_with_config( + num_initial_buckets: u64, + split_load_threshold: u8, + target_bucket_size: u64 + ): SmartTable { + assert!(split_load_threshold <= 100, error::invalid_argument(EINVALID_LOAD_THRESHOLD_PERCENT)); + let buckets = table_with_length::new(); + table_with_length::add(&mut buckets, 0, vector::empty()); + let table = SmartTable { + buckets, + num_buckets: 1, + level: 0, + size: 0, + // The default split load threshold is 75%. + split_load_threshold: if (split_load_threshold == 0) { 75 } else { split_load_threshold }, + target_bucket_size, + }; + // The default number of initial buckets is 2. + if (num_initial_buckets == 0) { + num_initial_buckets = 2; + }; + while (num_initial_buckets > 1) { + num_initial_buckets = num_initial_buckets - 1; + split_one_bucket(&mut table); + }; + table + } + + /// Destroy empty table. + /// Aborts if it's not empty. + public fun destroy_empty(table: SmartTable) { + assert!(table.size == 0, error::invalid_argument(ENOT_EMPTY)); + let i = 0; + while (i < table.num_buckets) { + vector::destroy_empty(table_with_length::remove(&mut table.buckets, i)); + i = i + 1; + }; + let SmartTable { buckets, num_buckets: _, level: _, size: _, split_load_threshold: _, target_bucket_size: _ } = table; + table_with_length::destroy_empty(buckets); + } + + /// Destroy a table completely when V has `drop`. + public fun destroy(table: SmartTable) { + clear(&mut table); + destroy_empty(table); + } + + /// Clear a table completely when T has `drop`. + public fun clear(table: &mut SmartTable) { + *table_with_length::borrow_mut(&mut table.buckets, 0) = vector::empty(); + let i = 1; + while (i < table.num_buckets) { + table_with_length::remove(&mut table.buckets, i); + i = i + 1; + }; + table.num_buckets = 1; + table.level = 0; + table.size = 0; + } + + /// Add (key, value) pair in the hash map, it may grow one bucket if current load factor exceeds the threshold. + /// Note it may not split the actual overflowed bucket. Instead, it was determined by `num_buckets` and `level`. + /// For standard linear hash algorithm, it is stored as a variable but `num_buckets` here could be leveraged. + /// Abort if `key` already exists. + /// Note: This method may occasionally cost much more gas when triggering bucket split. + public fun add(table: &mut SmartTable, key: K, value: V) { + let hash = sip_hash_from_value(&key); + let index = bucket_index(table.level, table.num_buckets, hash); + let bucket = table_with_length::borrow_mut(&mut table.buckets, index); + // We set a per-bucket limit here with a upper bound (10000) that nobody should normally reach. + assert!(vector::length(bucket) <= 10000, error::permission_denied(EEXCEED_MAX_BUCKET_SIZE)); + assert!(vector::all(bucket, | entry | { + let e: &Entry = entry; + &e.key != &key + }), error::invalid_argument(EALREADY_EXIST)); + let e = Entry { hash, key, value }; + if (table.target_bucket_size == 0) { + let estimated_entry_size = max(size_of_val(&e), 1); + table.target_bucket_size = max(1024 /* free_write_quota */ / estimated_entry_size, 1); + }; + vector::push_back(bucket, e); + table.size = table.size + 1; + + if (load_factor(table) >= (table.split_load_threshold as u64)) { + split_one_bucket(table); + } + } + + /// Add multiple key/value pairs to the smart table. The keys must not already exist. + public fun add_all(table: &mut SmartTable, keys: vector, values: vector) { + vector::zip(keys, values, |key, value| { add(table, key, value); }); + } + + inline fun unzip_entries(entries: &vector>): (vector, vector) { + let keys = vector[]; + let values = vector[]; + vector::for_each_ref(entries, |e|{ + let entry: &Entry = e; + vector::push_back(&mut keys, entry.key); + vector::push_back(&mut values, entry.value); + }); + (keys, values) + } + + /// Convert a smart table to a simple_map, which is supposed to be called mostly by view functions to get an atomic + /// view of the whole table. + /// Disclaimer: This function may be costly as the smart table may be huge in size. Use it at your own discretion. + public fun to_simple_map( + table: &SmartTable, + ): SimpleMap { + let i = 0; + let res = simple_map::new(); + while (i < table.num_buckets) { + let (keys, values) = unzip_entries(table_with_length::borrow(&table.buckets, i)); + simple_map::add_all(&mut res, keys, values); + i = i + 1; + }; + res + } + + /// Decide which is the next bucket to split and split it into two with the elements inside the bucket. + fun split_one_bucket(table: &mut SmartTable) { + let new_bucket_index = table.num_buckets; + // the next bucket to split is num_bucket without the most significant bit. + let to_split = new_bucket_index ^ (1 << table.level); + table.num_buckets = new_bucket_index + 1; + // if the whole level is splitted once, bump the level. + if (to_split + 1 == 1 << table.level) { + table.level = table.level + 1; + }; + let old_bucket = table_with_length::borrow_mut(&mut table.buckets, to_split); + // partition the bucket, [0..p) stays in old bucket, [p..len) goes to new bucket + let p = vector::partition(old_bucket, |e| { + let entry: &Entry = e; // Explicit type to satisfy compiler + bucket_index(table.level, table.num_buckets, entry.hash) != new_bucket_index + }); + let new_bucket = vector::trim_reverse(old_bucket, p); + table_with_length::add(&mut table.buckets, new_bucket_index, new_bucket); + } + + /// Return the expected bucket index to find the hash. + /// Basically, it use different base `1 << level` vs `1 << (level + 1)` in modulo operation based on the target + /// bucket index compared to the index of the next bucket to split. + fun bucket_index(level: u8, num_buckets: u64, hash: u64): u64 { + let index = hash % (1 << (level + 1)); + if (index < num_buckets) { + // in existing bucket + index + } else { + // in unsplitted bucket + index % (1 << level) + } + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow(table: &SmartTable, key: K): &V { + let index = bucket_index(table.level, table.num_buckets, sip_hash_from_value(&key)); + let bucket = table_with_length::borrow(&table.buckets, index); + let i = 0; + let len = vector::length(bucket); + while (i < len) { + let entry = vector::borrow(bucket, i); + if (&entry.key == &key) { + return &entry.value + }; + i = i + 1; + }; + abort error::invalid_argument(ENOT_FOUND) + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Returns specified default value if there is no entry for `key`. + public fun borrow_with_default(table: &SmartTable, key: K, default: &V): &V { + if (!contains(table, copy key)) { + default + } else { + borrow(table, copy key) + } + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow_mut(table: &mut SmartTable, key: K): &mut V { + let index = bucket_index(table.level, table.num_buckets, sip_hash_from_value(&key)); + let bucket = table_with_length::borrow_mut(&mut table.buckets, index); + let i = 0; + let len = vector::length(bucket); + while (i < len) { + let entry = vector::borrow_mut(bucket, i); + if (&entry.key == &key) { + return &mut entry.value + }; + i = i + 1; + }; + abort error::invalid_argument(ENOT_FOUND) + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Insert the pair (`key`, `default`) first if there is no entry for `key`. + public fun borrow_mut_with_default( + table: &mut SmartTable, + key: K, + default: V + ): &mut V { + if (!contains(table, copy key)) { + add(table, copy key, default) + }; + borrow_mut(table, key) + } + + /// Returns true iff `table` contains an entry for `key`. + public fun contains(table: &SmartTable, key: K): bool { + let hash = sip_hash_from_value(&key); + let index = bucket_index(table.level, table.num_buckets, hash); + let bucket = table_with_length::borrow(&table.buckets, index); + vector::any(bucket, | entry | { + let e: &Entry = entry; + e.hash == hash && &e.key == &key + }) + } + + /// Remove from `table` and return the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun remove(table: &mut SmartTable, key: K): V { + let index = bucket_index(table.level, table.num_buckets, sip_hash_from_value(&key)); + let bucket = table_with_length::borrow_mut(&mut table.buckets, index); + let i = 0; + let len = vector::length(bucket); + while (i < len) { + let entry = vector::borrow(bucket, i); + if (&entry.key == &key) { + let Entry { hash: _, key: _, value } = vector::swap_remove(bucket, i); + table.size = table.size - 1; + return value + }; + i = i + 1; + }; + abort error::invalid_argument(ENOT_FOUND) + } + + /// Insert the pair (`key`, `value`) if there is no entry for `key`. + /// update the value of the entry for `key` to `value` otherwise + public fun upsert(table: &mut SmartTable, key: K, value: V) { + if (!contains(table, copy key)) { + add(table, copy key, value) + } else { + let ref = borrow_mut(table, key); + *ref = value; + }; + } + + /// Returns the length of the table, i.e. the number of entries. + public fun length(table: &SmartTable): u64 { + table.size + } + + /// Return the load factor of the hashtable. + public fun load_factor(table: &SmartTable): u64 { + table.size * 100 / table.num_buckets / table.target_bucket_size + } + + /// Update `split_load_threshold`. + public fun update_split_load_threshold(table: &mut SmartTable, split_load_threshold: u8) { + assert!( + split_load_threshold <= 100 && split_load_threshold > 0, + error::invalid_argument(EINVALID_LOAD_THRESHOLD_PERCENT) + ); + table.split_load_threshold = split_load_threshold; + } + + /// Update `target_bucket_size`. + public fun update_target_bucket_size(table: &mut SmartTable, target_bucket_size: u64) { + assert!(target_bucket_size > 0, error::invalid_argument(EINVALID_TARGET_BUCKET_SIZE)); + table.target_bucket_size = target_bucket_size; + } + + /// Apply the function to a reference of each key-value pair in the table. + public inline fun for_each_ref(table: &SmartTable, f: |&K, &V|) { + let i = 0; + while (i < aptos_std::smart_table::num_buckets(table)) { + vector::for_each_ref( + aptos_std::table_with_length::borrow(aptos_std::smart_table::borrow_buckets(table), i), + |elem| { + let (key, value) = aptos_std::smart_table::borrow_kv(elem); + f(key, value) + } + ); + i = i + 1; + } + } + + /// Apply the function to a mutable reference of each key-value pair in the table. + public inline fun for_each_mut(table: &mut SmartTable, f: |&K, &mut V|) { + let i = 0; + while (i < aptos_std::smart_table::num_buckets(table)) { + vector::for_each_mut( + table_with_length::borrow_mut(aptos_std::smart_table::borrow_buckets_mut(table), i), + |elem| { + let (key, value) = aptos_std::smart_table::borrow_kv_mut(elem); + f(key, value) + } + ); + i = i + 1; + }; + } + + /// Map the function over the references of key-value pairs in the table without modifying it. + public inline fun map_ref( + table: &SmartTable, + f: |&V1|V2 + ): SmartTable { + let new_table = new(); + for_each_ref(table, |key, value| add(&mut new_table, *key, f(value))); + new_table + } + + /// Return true if any key-value pair in the table satisfies the predicate. + public inline fun any( + table: &SmartTable, + p: |&K, &V|bool + ): bool { + let found = false; + let i = 0; + while (i < aptos_std::smart_table::num_buckets(table)) { + found = vector::any(table_with_length::borrow(aptos_std::smart_table::borrow_buckets(table), i), |elem| { + let (key, value) = aptos_std::smart_table::borrow_kv(elem); + p(key, value) + }); + if (found) break; + i = i + 1; + }; + found + } + + // Helper functions to circumvent the scope issue of inline functions. + public fun borrow_kv(e: &Entry): (&K, &V) { + (&e.key, &e.value) + } + + public fun borrow_kv_mut(e: &mut Entry): (&mut K, &mut V) { + (&mut e.key, &mut e.value) + } + + public fun num_buckets(table: &SmartTable): u64 { + table.num_buckets + } + + public fun borrow_buckets(table: &SmartTable): &TableWithLength>> { + &table.buckets + } + + public fun borrow_buckets_mut(table: &mut SmartTable): &mut TableWithLength>> { + &mut table.buckets + } + + + #[test] + fun smart_table_test() { + let table = new(); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(length(&table) == 200, 0); + i = 0; + while (i < 200) { + *borrow_mut(&mut table, i) = i * 2; + assert!(*borrow(&table, i) == i * 2, 0); + i = i + 1; + }; + i = 0; + assert!(table.num_buckets > 5, table.num_buckets); + while (i < 200) { + assert!(contains(&table, i), 0); + assert!(remove(&mut table, i) == i * 2, 0); + i = i + 1; + }; + destroy_empty(table); + } + + #[test] + fun smart_table_split_test() { + let table: SmartTable = new_with_config(1, 100, 1); + let i = 1; + let level = 0; + while (i <= 256) { + assert!(table.num_buckets == i, 0); + assert!(table.level == level, i); + add(&mut table, i, i); + i = i + 1; + if (i == 1 << (level + 1)) { + level = level + 1; + }; + }; + let i = 1; + while (i <= 256) { + assert!(*borrow(&table, i) == i, 0); + i = i + 1; + }; + assert!(table.num_buckets == 257, table.num_buckets); + assert!(load_factor(&table) == 99, 0); + assert!(length(&table) == 256, 0); + destroy(table); + } + + #[test] + fun smart_table_update_configs() { + let table = new(); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(length(&table) == 200, 0); + update_target_bucket_size(&mut table, 10); + update_split_load_threshold(&mut table, 50); + while (i < 400) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(length(&table) == 400, 0); + i = 0; + while (i < 400) { + assert!(contains(&table, i), 0); + assert!(remove(&mut table, i) == i, 0); + i = i + 1; + }; + destroy_empty(table); + } + + #[test] + public fun smart_table_add_all_test() { + let table: SmartTable = new_with_config(1, 100, 2); + assert!(length(&table) == 0, 0); + add_all(&mut table, vector[1, 2, 3, 4, 5, 6, 7], vector[1, 2, 3, 4, 5, 6, 7]); + assert!(length(&table) == 7, 1); + let i = 1; + while (i < 8) { + assert!(*borrow(&table, i) == i, 0); + i = i + 1; + }; + i = i - 1; + while (i > 0) { + remove(&mut table, i); + i = i - 1; + }; + destroy_empty(table); + } + + #[test] + public fun smart_table_to_simple_map_test() { + let table = new(); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + let map = to_simple_map(&table); + assert!(simple_map::length(&map) == 200, 0); + destroy(table); + } + + #[test] + public fun smart_table_clear_test() { + let table = new(); + let i = 0u64; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + clear(&mut table); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(table.size == 200, 0); + destroy(table); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_vector.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_vector.move new file mode 100644 index 0000000..10f3c81 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/smart_vector.move @@ -0,0 +1,766 @@ +module aptos_std::smart_vector { + use std::error; + use std::vector; + use aptos_std::big_vector::{Self, BigVector}; + use aptos_std::math64::max; + use aptos_std::type_info::size_of_val; + use std::option::{Self, Option}; + + /// Vector index is out of bounds + const EINDEX_OUT_OF_BOUNDS: u64 = 1; + /// Cannot destroy a non-empty vector + const EVECTOR_NOT_EMPTY: u64 = 2; + /// Cannot pop back from an empty vector + const EVECTOR_EMPTY: u64 = 3; + /// bucket_size cannot be 0 + const EZERO_BUCKET_SIZE: u64 = 4; + /// The length of the smart vectors are not equal. + const ESMART_VECTORS_LENGTH_MISMATCH: u64 = 0x20005; + + /// A Scalable vector implementation based on tables, Ts are grouped into buckets with `bucket_size`. + /// The option wrapping BigVector saves space in the metadata associated with BigVector when smart_vector is + /// so small that inline_vec vector can hold all the data. + struct SmartVector has store { + inline_vec: vector, + big_vec: Option>, + inline_capacity: Option, + bucket_size: Option, + } + + /// Regular Vector API + + /// Create an empty vector using default logic to estimate `inline_capacity` and `bucket_size`, which may be + /// inaccurate. + /// This is exactly the same as empty() but is more standardized as all other data structures have new(). + public fun new(): SmartVector { + empty() + } + + #[deprecated] + /// Create an empty vector using default logic to estimate `inline_capacity` and `bucket_size`, which may be + /// inaccurate. + public fun empty(): SmartVector { + SmartVector { + inline_vec: vector[], + big_vec: option::none(), + inline_capacity: option::none(), + bucket_size: option::none(), + } + } + + /// Create an empty vector with customized config. + /// When inline_capacity = 0, SmartVector degrades to a wrapper of BigVector. + public fun empty_with_config(inline_capacity: u64, bucket_size: u64): SmartVector { + assert!(bucket_size > 0, error::invalid_argument(EZERO_BUCKET_SIZE)); + SmartVector { + inline_vec: vector[], + big_vec: option::none(), + inline_capacity: option::some(inline_capacity), + bucket_size: option::some(bucket_size), + } + } + + /// Create a vector of length 1 containing the passed in T. + public fun singleton(element: T): SmartVector { + let v = empty(); + push_back(&mut v, element); + v + } + + /// Destroy the vector `v`. + /// Aborts if `v` is not empty. + public fun destroy_empty(v: SmartVector) { + assert!(is_empty(&v), error::invalid_argument(EVECTOR_NOT_EMPTY)); + let SmartVector { inline_vec, big_vec, inline_capacity: _, bucket_size: _ } = v; + vector::destroy_empty(inline_vec); + option::destroy_none(big_vec); + } + + /// Destroy a vector completely when T has `drop`. + public fun destroy(v: SmartVector) { + clear(&mut v); + destroy_empty(v); + } + + /// Clear a vector completely when T has `drop`. + public fun clear(v: &mut SmartVector) { + v.inline_vec = vector[]; + if (option::is_some(&v.big_vec)) { + big_vector::destroy(option::extract(&mut v.big_vec)); + } + } + + /// Acquire an immutable reference to the `i`th T of the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow(v: &SmartVector, i: u64): &T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i < inline_len) { + vector::borrow(&v.inline_vec, i) + } else { + big_vector::borrow(option::borrow(&v.big_vec), i - inline_len) + } + } + + /// Return a mutable reference to the `i`th T in the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow_mut(v: &mut SmartVector, i: u64): &mut T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i < inline_len) { + vector::borrow_mut(&mut v.inline_vec, i) + } else { + big_vector::borrow_mut(option::borrow_mut(&mut v.big_vec), i - inline_len) + } + } + + /// Empty and destroy the other vector, and push each of the Ts in the other vector onto the lhs vector in the + /// same order as they occurred in other. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun append(lhs: &mut SmartVector, other: SmartVector) { + let other_len = length(&other); + let half_other_len = other_len / 2; + let i = 0; + while (i < half_other_len) { + push_back(lhs, swap_remove(&mut other, i)); + i = i + 1; + }; + while (i < other_len) { + push_back(lhs, pop_back(&mut other)); + i = i + 1; + }; + destroy_empty(other); + } + + /// Add multiple values to the vector at once. + public fun add_all(v: &mut SmartVector, vals: vector) { + vector::for_each(vals, |val| { push_back(v, val); }) + } + + /// Convert a smart vector to a native vector, which is supposed to be called mostly by view functions to get an + /// atomic view of the whole vector. + /// Disclaimer: This function may be costly as the smart vector may be huge in size. Use it at your own discretion. + public fun to_vector(v: &SmartVector): vector { + let res = v.inline_vec; + if (option::is_some(&v.big_vec)) { + let big_vec = option::borrow(&v.big_vec); + vector::append(&mut res, big_vector::to_vector(big_vec)); + }; + res + } + + /// Add T `val` to the end of the vector `v`. It grows the buckets when the current buckets are full. + /// This operation will cost more gas when it adds new bucket. + public fun push_back(v: &mut SmartVector, val: T) { + let len = length(v); + let inline_len = vector::length(&v.inline_vec); + if (len == inline_len) { + let bucket_size = if (option::is_some(&v.inline_capacity)) { + if (len < *option::borrow(&v.inline_capacity)) { + vector::push_back(&mut v.inline_vec, val); + return + }; + *option::borrow(&v.bucket_size) + } else { + let val_size = size_of_val(&val); + if (val_size * (inline_len + 1) < 150 /* magic number */) { + vector::push_back(&mut v.inline_vec, val); + return + }; + let estimated_avg_size = max((size_of_val(&v.inline_vec) + val_size) / (inline_len + 1), 1); + max(1024 /* free_write_quota */ / estimated_avg_size, 1) + }; + option::fill(&mut v.big_vec, big_vector::empty(bucket_size)); + }; + big_vector::push_back(option::borrow_mut(&mut v.big_vec), val); + } + + /// Pop an T from the end of vector `v`. It does shrink the buckets if they're empty. + /// Aborts if `v` is empty. + public fun pop_back(v: &mut SmartVector): T { + assert!(!is_empty(v), error::invalid_state(EVECTOR_EMPTY)); + let big_vec_wrapper = &mut v.big_vec; + if (option::is_some(big_vec_wrapper)) { + let big_vec = option::extract(big_vec_wrapper); + let val = big_vector::pop_back(&mut big_vec); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + val + } else { + vector::pop_back(&mut v.inline_vec) + } + } + + /// Remove the T at index i in the vector v and return the owned value that was previously stored at i in v. + /// All Ts occurring at indices greater than i will be shifted down by 1. Will abort if i is out of bounds. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun remove(v: &mut SmartVector, i: u64): T { + let len = length(v); + assert!(i < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i < inline_len) { + vector::remove(&mut v.inline_vec, i) + } else { + let big_vec_wrapper = &mut v.big_vec; + let big_vec = option::extract(big_vec_wrapper); + let val = big_vector::remove(&mut big_vec, i - inline_len); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + val + } + } + + /// Swap the `i`th T of the vector `v` with the last T and then pop the vector. + /// This is O(1), but does not preserve ordering of Ts in the vector. + /// Aborts if `i` is out of bounds. + public fun swap_remove(v: &mut SmartVector, i: u64): T { + let len = length(v); + assert!(i < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + let big_vec_wrapper = &mut v.big_vec; + let inline_vec = &mut v.inline_vec; + if (i >= inline_len) { + let big_vec = option::extract(big_vec_wrapper); + let val = big_vector::swap_remove(&mut big_vec, i - inline_len); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + val + } else { + if (inline_len < len) { + let big_vec = option::extract(big_vec_wrapper); + let last_from_big_vec = big_vector::pop_back(&mut big_vec); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + vector::push_back(inline_vec, last_from_big_vec); + }; + vector::swap_remove(inline_vec, i) + } + } + + /// Swap the Ts at the i'th and j'th indices in the vector v. Will abort if either of i or j are out of bounds + /// for v. + public fun swap(v: &mut SmartVector, i: u64, j: u64) { + if (i > j) { + return swap(v, j, i) + }; + let len = length(v); + assert!(j < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i >= inline_len) { + big_vector::swap(option::borrow_mut(&mut v.big_vec), i - inline_len, j - inline_len); + } else if (j < inline_len) { + vector::swap(&mut v.inline_vec, i, j); + } else { + let big_vec = option::borrow_mut(&mut v.big_vec); + let inline_vec = &mut v.inline_vec; + let element_i = vector::swap_remove(inline_vec, i); + let element_j = big_vector::swap_remove(big_vec, j - inline_len); + vector::push_back(inline_vec, element_j); + vector::swap(inline_vec, i, inline_len - 1); + big_vector::push_back(big_vec, element_i); + big_vector::swap(big_vec, j - inline_len, len - inline_len - 1); + } + } + + /// Reverse the order of the Ts in the vector v in-place. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun reverse(v: &mut SmartVector) { + let inline_len = vector::length(&v.inline_vec); + let i = 0; + let new_inline_vec = vector[]; + // Push the last `inline_len` Ts into a temp vector. + while (i < inline_len) { + vector::push_back(&mut new_inline_vec, pop_back(v)); + i = i + 1; + }; + vector::reverse(&mut new_inline_vec); + // Reverse the big_vector left if exists. + if (option::is_some(&v.big_vec)) { + big_vector::reverse(option::borrow_mut(&mut v.big_vec)); + }; + // Mem::swap the two vectors. + let temp_vec = vector[]; + while (!vector::is_empty(&mut v.inline_vec)) { + vector::push_back(&mut temp_vec, vector::pop_back(&mut v.inline_vec)); + }; + vector::reverse(&mut temp_vec); + while (!vector::is_empty(&mut new_inline_vec)) { + vector::push_back(&mut v.inline_vec, vector::pop_back(&mut new_inline_vec)); + }; + vector::destroy_empty(new_inline_vec); + // Push the rest Ts originally left in inline_vector back to the end of the smart vector. + while (!vector::is_empty(&mut temp_vec)) { + push_back(v, vector::pop_back(&mut temp_vec)); + }; + vector::destroy_empty(temp_vec); + } + + /// Return `(true, i)` if `val` is in the vector `v` at index `i`. + /// Otherwise, returns `(false, 0)`. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun index_of(v: &SmartVector, val: &T): (bool, u64) { + let (found, i) = vector::index_of(&v.inline_vec, val); + if (found) { + (true, i) + } else if (option::is_some(&v.big_vec)) { + let (found, i) = big_vector::index_of(option::borrow(&v.big_vec), val); + (found, i + vector::length(&v.inline_vec)) + } else { + (false, 0) + } + } + + /// Return true if `val` is in the vector `v`. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun contains(v: &SmartVector, val: &T): bool { + if (is_empty(v)) return false; + let (exist, _) = index_of(v, val); + exist + } + + /// Return the length of the vector. + public fun length(v: &SmartVector): u64 { + vector::length(&v.inline_vec) + if (option::is_none(&v.big_vec)) { + 0 + } else { + big_vector::length(option::borrow(&v.big_vec)) + } + } + + /// Return `true` if the vector `v` has no Ts and `false` otherwise. + public fun is_empty(v: &SmartVector): bool { + length(v) == 0 + } + + /// Apply the function to each T in the vector, consuming it. + public inline fun for_each(v: SmartVector, f: |T|) { + aptos_std::smart_vector::reverse(&mut v); // We need to reverse the vector to consume it efficiently + aptos_std::smart_vector::for_each_reverse(v, |e| f(e)); + } + + /// Apply the function to each T in the vector, consuming it. + public inline fun for_each_reverse(v: SmartVector, f: |T|) { + let len = aptos_std::smart_vector::length(&v); + while (len > 0) { + f(aptos_std::smart_vector::pop_back(&mut v)); + len = len - 1; + }; + aptos_std::smart_vector::destroy_empty(v) + } + + /// Apply the function to a reference of each T in the vector. + public inline fun for_each_ref(v: &SmartVector, f: |&T|) { + let i = 0; + let len = aptos_std::smart_vector::length(v); + while (i < len) { + f(aptos_std::smart_vector::borrow(v, i)); + i = i + 1 + } + } + + /// Apply the function to a mutable reference to each T in the vector. + public inline fun for_each_mut(v: &mut SmartVector, f: |&mut T|) { + let i = 0; + let len = aptos_std::smart_vector::length(v); + while (i < len) { + f(aptos_std::smart_vector::borrow_mut(v, i)); + i = i + 1 + } + } + + /// Apply the function to a reference of each T in the vector with its index. + public inline fun enumerate_ref(v: &SmartVector, f: |u64, &T|) { + let i = 0; + let len = aptos_std::smart_vector::length(v); + while (i < len) { + f(i, aptos_std::smart_vector::borrow(v, i)); + i = i + 1; + }; + } + + /// Apply the function to a mutable reference of each T in the vector with its index. + public inline fun enumerate_mut(v: &mut SmartVector, f: |u64, &mut T|) { + let i = 0; + let len = length(v); + while (i < len) { + f(i, borrow_mut(v, i)); + i = i + 1; + }; + } + + /// Fold the function over the Ts. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(f(f(0, 1), 2), 3)` + public inline fun fold( + v: SmartVector, + init: Accumulator, + f: |Accumulator, T|Accumulator + ): Accumulator { + let accu = init; + aptos_std::smart_vector::for_each(v, |elem| accu = f(accu, elem)); + accu + } + + /// Fold right like fold above but working right to left. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(1, f(2, f(3, 0)))` + public inline fun foldr( + v: SmartVector, + init: Accumulator, + f: |T, Accumulator|Accumulator + ): Accumulator { + let accu = init; + aptos_std::smart_vector::for_each_reverse(v, |elem| accu = f(elem, accu)); + accu + } + + /// Map the function over the references of the Ts of the vector, producing a new vector without modifying the + /// original vector. + public inline fun map_ref( + v: &SmartVector, + f: |&T1|T2 + ): SmartVector { + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::for_each_ref(v, |elem| aptos_std::smart_vector::push_back(&mut result, f(elem))); + result + } + + /// Map the function over the Ts of the vector, producing a new vector. + public inline fun map( + v: SmartVector, + f: |T1|T2 + ): SmartVector { + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::for_each(v, |elem| push_back(&mut result, f(elem))); + result + } + + /// Filter the vector using the boolean function, removing all Ts for which `p(e)` is not true. + public inline fun filter( + v: SmartVector, + p: |&T|bool + ): SmartVector { + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::for_each(v, |elem| { + if (p(&elem)) aptos_std::smart_vector::push_back(&mut result, elem); + }); + result + } + + public inline fun zip(v1: SmartVector, v2: SmartVector, f: |T1, T2|) { + // We need to reverse the vectors to consume it efficiently + aptos_std::smart_vector::reverse(&mut v1); + aptos_std::smart_vector::reverse(&mut v2); + aptos_std::smart_vector::zip_reverse(v1, v2, |e1, e2| f(e1, e2)); + } + + /// Apply the function to each pair of elements in the two given vectors in the reverse order, consuming them. + /// This errors out if the vectors are not of the same length. + public inline fun zip_reverse( + v1: SmartVector, + v2: SmartVector, + f: |T1, T2|, + ) { + let len = aptos_std::smart_vector::length(&v1); + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == aptos_std::smart_vector::length(&v2), 0x20005); + while (len > 0) { + f(aptos_std::smart_vector::pop_back(&mut v1), aptos_std::smart_vector::pop_back(&mut v2)); + len = len - 1; + }; + aptos_std::smart_vector::destroy_empty(v1); + aptos_std::smart_vector::destroy_empty(v2); + } + + /// Apply the function to the references of each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_ref( + v1: &SmartVector, + v2: &SmartVector, + f: |&T1, &T2|, + ) { + let len = aptos_std::smart_vector::length(v1); + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == aptos_std::smart_vector::length(v2), 0x20005); + let i = 0; + while (i < len) { + f(aptos_std::smart_vector::borrow(v1, i), aptos_std::smart_vector::borrow(v2, i)); + i = i + 1 + } + } + + /// Apply the function to mutable references to each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_mut( + v1: &mut SmartVector, + v2: &mut SmartVector, + f: |&mut T1, &mut T2|, + ) { + let i = 0; + let len = aptos_std::smart_vector::length(v1); + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == aptos_std::smart_vector::length(v2), 0x20005); + while (i < len) { + f(aptos_std::smart_vector::borrow_mut(v1, i), aptos_std::smart_vector::borrow_mut(v2, i)); + i = i + 1 + } + } + + /// Map the function over the element pairs of the two vectors, producing a new vector. + public inline fun zip_map( + v1: SmartVector, + v2: SmartVector, + f: |T1, T2|NewT + ): SmartVector { + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(aptos_std::smart_vector::length(&v1) == aptos_std::smart_vector::length(&v2), 0x20005); + + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::zip(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + /// Map the function over the references of the element pairs of two vectors, producing a new vector from the return + /// values without modifying the original vectors. + public inline fun zip_map_ref( + v1: &SmartVector, + v2: &SmartVector, + f: |&T1, &T2|NewT + ): SmartVector { + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(aptos_std::smart_vector::length(v1) == aptos_std::smart_vector::length(v2), 0x20005); + + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::zip_ref(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + #[test] + fun smart_vector_test() { + let v = empty(); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let j = 0; + while (j < 100) { + let val = borrow(&v, j); + assert!(*val == j, 0); + j = j + 1; + }; + while (i > 0) { + i = i - 1; + let (exist, index) = index_of(&v, &i); + let j = pop_back(&mut v); + assert!(exist, 0); + assert!(index == i, 0); + assert!(j == i, 0); + }; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let last_index = length(&v) - 1; + assert!(swap_remove(&mut v, last_index) == 99, 0); + assert!(swap_remove(&mut v, 0) == 0, 0); + while (length(&v) > 0) { + // the vector is always [N, 1, 2, ... N-1] with repetitive swap_remove(&mut v, 0) + let expected = length(&v); + let val = swap_remove(&mut v, 0); + assert!(val == expected, 0); + }; + destroy_empty(v); + } + + #[test] + fun smart_vector_append_edge_case_test() { + let v1 = empty(); + let v2 = singleton(1u64); + let v3 = empty(); + let v4 = empty(); + append(&mut v3, v4); + assert!(length(&v3) == 0, 0); + append(&mut v2, v3); + assert!(length(&v2) == 1, 0); + append(&mut v1, v2); + assert!(length(&v1) == 1, 0); + destroy(v1); + } + + #[test] + fun smart_vector_append_test() { + let v1 = empty(); + let v2 = empty(); + let i = 0; + while (i < 7) { + push_back(&mut v1, i); + i = i + 1; + }; + while (i < 25) { + push_back(&mut v2, i); + i = i + 1; + }; + append(&mut v1, v2); + assert!(length(&v1) == 25, 0); + i = 0; + while (i < 25) { + assert!(*borrow(&v1, i) == i, 0); + i = i + 1; + }; + destroy(v1); + } + + #[test] + fun smart_vector_remove_test() { + let v = empty(); + let i = 0u64; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + let inline_len = vector::length(&v.inline_vec); + remove(&mut v, 100); + remove(&mut v, 90); + remove(&mut v, 80); + remove(&mut v, 70); + remove(&mut v, 60); + remove(&mut v, 50); + remove(&mut v, 40); + remove(&mut v, 30); + remove(&mut v, 20); + assert!(vector::length(&v.inline_vec) == inline_len, 0); + remove(&mut v, 10); + assert!(vector::length(&v.inline_vec) + 1 == inline_len, 0); + remove(&mut v, 0); + assert!(vector::length(&v.inline_vec) + 2 == inline_len, 0); + assert!(length(&v) == 90, 0); + + let index = 0; + i = 0; + while (i < 101) { + if (i % 10 != 0) { + assert!(*borrow(&v, index) == i, 0); + index = index + 1; + }; + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_reverse_test() { + let v = empty(); + let i = 0u64; + while (i < 10) { + push_back(&mut v, i); + i = i + 1; + }; + reverse(&mut v); + let k = 0; + while (k < 10) { + assert!(*vector::borrow(&v.inline_vec, k) == 9 - k, 0); + k = k + 1; + }; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + while (!vector::is_empty(&v.inline_vec)) { + remove(&mut v, 0); + }; + reverse(&mut v); + i = 0; + let len = length(&v); + while (i + 1 < len) { + assert!( + *big_vector::borrow(option::borrow(&v.big_vec), i) == *big_vector::borrow( + option::borrow(&v.big_vec), + i + 1 + ) + 1, + 0 + ); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_add_all_test() { + let v = empty_with_config(1, 2); + add_all(&mut v, vector[1, 2, 3, 4, 5, 6]); + assert!(length(&v) == 6, 0); + let i = 0; + while (i < 6) { + assert!(*borrow(&v, i) == i + 1, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_to_vector_test() { + let v1 = empty_with_config(7, 11); + let i = 0; + while (i < 100) { + push_back(&mut v1, i); + i = i + 1; + }; + let v2 = to_vector(&v1); + let j = 0; + while (j < 100) { + assert!(*vector::borrow(&v2, j) == j, 0); + j = j + 1; + }; + destroy(v1); + } + + #[test] + fun smart_vector_swap_test() { + let v = empty(); + let i = 0; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + i = 0; + while (i < 51) { + swap(&mut v, i, 100 - i); + i = i + 1; + }; + i = 0; + while (i < 101) { + assert!(*borrow(&v, i) == 100 - i, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_index_of_test() { + let v = empty(); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + let (found, idx) = index_of(&mut v, &i); + assert!(found && idx == i, 0); + i = i + 1; + }; + destroy(v); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/string_utils.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/string_utils.move new file mode 100644 index 0000000..c7f239b --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/string_utils.move @@ -0,0 +1,146 @@ +/// A module for formatting move values as strings. +module aptos_std::string_utils { + use std::string::String; + + /// The number of values in the list does not match the number of "{}" in the format string. + const EARGS_MISMATCH: u64 = 1; + /// The format string is not valid. + const EINVALID_FORMAT: u64 = 2; + + /// Format a move value as a human readable string, + /// eg. `to_string(&1u64) == "1"`, `to_string(&false) == "false"`, `to_string(&@0x1) == "@0x1"`. + /// For vectors and structs the format is similar to rust, eg. + /// `to_string(&cons(1,2)) == "Cons { car: 1, cdr: 2 }"` and `to_string(&vector[1, 2, 3]) == "[ 1, 2, 3 ]"` + /// For vectors of u8 the output is hex encoded, eg. `to_string(&vector[1u8, 2u8, 3u8]) == "0x010203"` + /// For std::string::String the output is the string itself including quotes, eg. + /// `to_string(&std::string::utf8(b"My string")) == "\"My string\""` + public fun to_string(s: &T): String { + native_format(s, false, false, true, false) + } + + /// Format addresses as 64 zero-padded hexadecimals. + public fun to_string_with_canonical_addresses(s: &T): String { + native_format(s, false, true, true, false) + } + + /// Format emitting integers with types ie. 6u8 or 128u32. + public fun to_string_with_integer_types(s: &T): String { + native_format(s, false, true, true, false) + } + + /// Format vectors and structs with newlines and indentation. + public fun debug_string(s: &T): String { + native_format(s, true, false, false, false) + } + + /// Formatting with a rust-like format string, eg. `format2(&b"a = {}, b = {}", 1, 2) == "a = 1, b = 2"`. + public fun format1(fmt: &vector, a: T0): String { + native_format_list(fmt, &list1(a)) + } + public fun format2(fmt: &vector, a: T0, b: T1): String { + native_format_list(fmt, &list2(a, b)) + } + public fun format3(fmt: &vector, a: T0, b: T1, c: T2): String { + native_format_list(fmt, &list3(a, b, c)) + } + public fun format4(fmt: &vector, a: T0, b: T1, c: T2, d: T3): String { + native_format_list(fmt, &list4(a, b, c, d)) + } + + // Helper struct to allow passing a generic heterogeneous list of values to native_format_list. + struct Cons has copy, drop, store { + car: T, + cdr: N, + } + + struct NIL has copy, drop, store {} + + // Create a pair of values. + fun cons(car: T, cdr: N): Cons { Cons { car, cdr } } + + // Create a nil value. + fun nil(): NIL { NIL {} } + + // Create a list of values. + inline fun list1(a: T0): Cons { cons(a, nil()) } + inline fun list2(a: T0, b: T1): Cons> { cons(a, list1(b)) } + inline fun list3(a: T0, b: T1, c: T2): Cons>> { cons(a, list2(b, c)) } + inline fun list4(a: T0, b: T1, c: T2, d: T3): Cons>>> { cons(a, list3(b, c, d)) } + + // Native functions + native fun native_format(s: &T, type_tag: bool, canonicalize: bool, single_line: bool, include_int_types: bool): String; + native fun native_format_list(fmt: &vector, val: &T): String; + + #[test] + fun test_format() { + assert!(to_string(&1u64) == std::string::utf8(b"1"), 1); + assert!(to_string(&false) == std::string::utf8(b"false"), 2); + assert!(to_string(&1u256) == std::string::utf8(b"1"), 3); + assert!(to_string(&vector[1, 2, 3]) == std::string::utf8(b"[ 1, 2, 3 ]"), 4); + assert!(to_string(&cons(std::string::utf8(b"My string"),2)) == std::string::utf8(b"Cons { car: \"My string\", cdr: 2 }"), 5); + assert!(to_string(&std::option::none()) == std::string::utf8(b"None"), 6); + assert!(to_string(&std::option::some(1)) == std::string::utf8(b"Some(1)"), 7); + } + + #[test] + fun test_format_list() { + let s = format3(&b"a = {} b = {} c = {}", 1, 2, std::string::utf8(b"My string")); + assert!(s == std::string::utf8(b"a = 1 b = 2 c = \"My string\""), 1); + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_to_many_vals() { + format4(&b"a = {} b = {} c = {}", 1, 2, 3, 4); + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_not_enough_vals() { + format2(&b"a = {} b = {} c = {}", 1, 2); + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_not_valid_nil() { + let l = cons(1, cons(2, cons(3, 4))); + native_format_list(&b"a = {} b = {} c = {}", &l); + } + + /// #[test_only] + struct FakeCons has copy, drop, store { + car: T, + cdr: N, + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_not_valid_list() { + let l = cons(1, FakeCons { car: 2, cdr: cons(3, nil())}); + native_format_list(&b"a = {} b = {} c = {}", &l); + } + + #[test] + #[expected_failure(abort_code = EINVALID_FORMAT)] + fun test_format_unclosed_braces() { + format3(&b"a = {} b = {} c = {", 1, 2 ,3); + } + + #[test] + #[expected_failure(abort_code = EINVALID_FORMAT)] + fun test_format_unclosed_braces_2() { + format3(&b"a = {} b = { c = {}", 1, 2, 3); + } + + #[test] + #[expected_failure(abort_code = EINVALID_FORMAT)] + fun test_format_unopened_braces() { + format3(&b"a = } b = {} c = {}", 1, 2, 3); + } + + #[test] + fun test_format_escape_braces_works() { + let s = format3(&b"{{a = {} b = {} c = {}}}", 1, 2, 3); + assert!(s == std::string::utf8(b"{a = 1 b = 2 c = 3}"), 1); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table.move new file mode 100644 index 0000000..dbc8520 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table.move @@ -0,0 +1,152 @@ +/// Type of large-scale storage tables. +/// source: https://github.com/move-language/move/blob/1b6b7513dcc1a5c866f178ca5c1e74beb2ce181e/language/extensions/move-table-extension/sources/Table.move#L1 +/// +/// It implements the Table type which supports individual table items to be represented by +/// separate global state items. The number of items and a unique handle are tracked on the table +/// struct itself, while the operations are implemented as native functions. No traversal is provided. + +module aptos_std::table { + friend aptos_std::table_with_length; + + /// Type of tables + struct Table has store { + handle: address, + } + + /// Create a new Table. + public fun new(): Table { + Table { + handle: new_table_handle(), + } + } + + /// Add a new entry to the table. Aborts if an entry for this + /// key already exists. The entry itself is not stored in the + /// table, and cannot be discovered from it. + public fun add(table: &mut Table, key: K, val: V) { + add_box>(table, key, Box { val }) + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow(table: &Table, key: K): &V { + &borrow_box>(table, key).val + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Returns specified default value if there is no entry for `key`. + public fun borrow_with_default(table: &Table, key: K, default: &V): &V { + if (!contains(table, copy key)) { + default + } else { + borrow(table, copy key) + } + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow_mut(table: &mut Table, key: K): &mut V { + &mut borrow_box_mut>(table, key).val + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Insert the pair (`key`, `default`) first if there is no entry for `key`. + public fun borrow_mut_with_default(table: &mut Table, key: K, default: V): &mut V { + if (!contains(table, copy key)) { + add(table, copy key, default) + }; + borrow_mut(table, key) + } + + /// Insert the pair (`key`, `value`) if there is no entry for `key`. + /// update the value of the entry for `key` to `value` otherwise + public fun upsert(table: &mut Table, key: K, value: V) { + if (!contains(table, copy key)) { + add(table, copy key, value) + } else { + let ref = borrow_mut(table, key); + *ref = value; + }; + } + + /// Remove from `table` and return the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun remove(table: &mut Table, key: K): V { + let Box { val } = remove_box>(table, key); + val + } + + /// Returns true iff `table` contains an entry for `key`. + public fun contains(table: &Table, key: K): bool { + contains_box>(table, key) + } + + #[test_only] + /// Testing only: allows to drop a table even if it is not empty. + public fun drop_unchecked(table: Table) { + drop_unchecked_box>(table) + } + + public(friend) fun destroy(table: Table) { + destroy_empty_box>(&table); + drop_unchecked_box>(table) + } + + #[test_only] + struct TableHolder has key { + t: Table + } + + #[test(account = @0x1)] + fun test_upsert(account: signer) { + let t = new(); + let key: u64 = 111; + let error_code: u64 = 1; + assert!(!contains(&t, key), error_code); + upsert(&mut t, key, 12); + assert!(*borrow(&t, key) == 12, error_code); + upsert(&mut t, key, 23); + assert!(*borrow(&t, key) == 23, error_code); + + move_to(&account, TableHolder { t }); + } + + #[test(account = @0x1)] + fun test_borrow_with_default(account: signer) { + let t = new(); + let key: u64 = 100; + let error_code: u64 = 1; + assert!(!contains(&t, key), error_code); + assert!(*borrow_with_default(&t, key, &12) == 12, error_code); + add(&mut t, key, 1); + assert!(*borrow_with_default(&t, key, &12) == 1, error_code); + + move_to(&account, TableHolder{ t }); + } + + // ====================================================================================================== + // Internal API + + /// Wrapper for values. Required for making values appear as resources in the implementation. + struct Box has key, drop, store { + val: V + } + + // Primitives which take as an additional type parameter `Box`, so the implementation + // can use this to determine serialization layout. + native fun new_table_handle(): address; + + native fun add_box(table: &mut Table, key: K, val: Box); + + native fun borrow_box(table: &Table, key: K): &Box; + + native fun borrow_box_mut(table: &mut Table, key: K): &mut Box; + + native fun contains_box(table: &Table, key: K): bool; + + native fun remove_box(table: &mut Table, key: K): Box; + + native fun destroy_empty_box(table: &Table); + + native fun drop_unchecked_box(table: Table); +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table_with_length.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table_with_length.move new file mode 100644 index 0000000..c56ff2b --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/table_with_length.move @@ -0,0 +1,141 @@ +/// Extends Table and provides functions such as length and the ability to be destroyed + +module aptos_std::table_with_length { + use std::error; + use aptos_std::table::{Self, Table}; + + // native code raises this with error::invalid_arguments() + const EALREADY_EXISTS: u64 = 100; + // native code raises this with error::invalid_arguments() + const ENOT_FOUND: u64 = 101; + const ENOT_EMPTY: u64 = 102; + + /// Type of tables + struct TableWithLength has store { + inner: Table, + length: u64, + } + + /// Create a new Table. + public fun new(): TableWithLength { + TableWithLength { + inner: table::new(), + length: 0, + } + } + + /// Destroy a table. The table must be empty to succeed. + public fun destroy_empty(table: TableWithLength) { + assert!(table.length == 0, error::invalid_state(ENOT_EMPTY)); + let TableWithLength { inner, length: _ } = table; + table::destroy(inner) + } + + /// Add a new entry to the table. Aborts if an entry for this + /// key already exists. The entry itself is not stored in the + /// table, and cannot be discovered from it. + public fun add(table: &mut TableWithLength, key: K, val: V) { + table::add(&mut table.inner, key, val); + table.length = table.length + 1; + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow(table: &TableWithLength, key: K): &V { + table::borrow(&table.inner, key) + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow_mut(table: &mut TableWithLength, key: K): &mut V { + table::borrow_mut(&mut table.inner, key) + } + + /// Returns the length of the table, i.e. the number of entries. + public fun length(table: &TableWithLength): u64 { + table.length + } + + /// Returns true if this table is empty. + public fun empty(table: &TableWithLength): bool { + table.length == 0 + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Insert the pair (`key`, `default`) first if there is no entry for `key`. + public fun borrow_mut_with_default(table: &mut TableWithLength, key: K, default: V): &mut V { + if (table::contains(&table.inner, key)) { + table::borrow_mut(&mut table.inner, key) + } else { + table::add(&mut table.inner, key, default); + table.length = table.length + 1; + table::borrow_mut(&mut table.inner, key) + } + } + + /// Insert the pair (`key`, `value`) if there is no entry for `key`. + /// update the value of the entry for `key` to `value` otherwise + public fun upsert(table: &mut TableWithLength, key: K, value: V) { + if (!table::contains(&table.inner, key)) { + add(table, copy key, value) + } else { + let ref = table::borrow_mut(&mut table.inner, key); + *ref = value; + }; + } + + /// Remove from `table` and return the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun remove(table: &mut TableWithLength, key: K): V { + let val = table::remove(&mut table.inner, key); + table.length = table.length - 1; + val + } + + /// Returns true iff `table` contains an entry for `key`. + public fun contains(table: &TableWithLength, key: K): bool { + table::contains(&table.inner, key) + } + + #[test_only] + /// Drop table even if not empty, only when testing. + public fun drop_unchecked(table: TableWithLength) { + // Unpack table with length, dropping length count but not + // inner table. + let TableWithLength{inner, length: _} = table; + table::drop_unchecked(inner); // Drop inner table. + } + + #[test] + /// Verify test-only drop functionality. + fun test_drop_unchecked() { + let table = new(); // Declare new table. + add(&mut table, true, false); // Add table entry. + drop_unchecked(table); // Drop table. + } + + #[test] + fun test_upsert() { + let t = new(); + // Table should not have key 0 yet + assert!(!contains(&t, 0), 1); + // This should insert key 0, with value 10, and length should be 1 + upsert(&mut t, 0, 10); + // Ensure the value is correctly set to 10 + assert!(*borrow(&t, 0) == 10, 1); + // Ensure the length is correctly set + assert!(length(&t) == 1, 1); + // Lets upsert the value to something else, and verify it's correct + upsert(&mut t, 0, 23); + assert!(*borrow(&t, 0) == 23, 1); + // Since key 0 already existed, the length should not have changed + assert!(length(&t) == 1, 1); + // If we upsert a non-existing key, the length should increase + upsert(&mut t, 1, 7); + assert!(length(&t) == 2, 1); + + remove(&mut t, 0); + remove(&mut t, 1); + destroy_empty(t); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/type_info.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/type_info.move new file mode 100644 index 0000000..22f97b3 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosStdlib/type_info.move @@ -0,0 +1,350 @@ +module aptos_std::type_info { + use std::bcs; + use std::features; + use std::string::{Self, String}; + use std::vector; + + // + // Error codes + // + + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 1; + + // + // Structs + // + + struct TypeInfo has copy, drop, store { + account_address: address, + module_name: vector, + struct_name: vector, + } + + // + // Public functions + // + + 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 + } + + /// Returns the current chain ID, mirroring what `aptos_framework::chain_id::get()` would return, except in `#[test]` + /// functions, where this will always return `4u8` as the chain ID, whereas `aptos_framework::chain_id::get()` will + /// return whichever ID was passed to `aptos_framework::chain_id::initialize_for_test()`. + public fun chain_id(): u8 { + if (!features::aptos_stdlib_chain_id_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + chain_id_internal() + } + + /// Return the `TypeInfo` struct containing for the type `T`. + public native fun type_of(): TypeInfo; + + /// Return the human readable string for the type, including the address, module name, and any type arguments. + /// Example: 0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin> + /// Or: 0x1::table::Table<0x1::string::String, 0x1::string::String> + public native fun type_name(): String; + + native fun chain_id_internal(): u8; + + /// Return the BCS size, in bytes, of value at `val_ref`. + /// + /// See the [BCS spec](https://github.com/diem/bcs) + /// + /// See `test_size_of_val()` for an analysis of common types and + /// nesting patterns, as well as `test_size_of_val_vectors()` for an + /// analysis of vector size dynamism. + public fun size_of_val(val_ref: &T): u64 { + // Return vector length of vectorized BCS representation. + vector::length(&bcs::to_bytes(val_ref)) + } + + #[test_only] + use aptos_std::table::Table; + + #[test] + fun test_type_of() { + let type_info = type_of(); + assert!(account_address(&type_info) == @aptos_std, 0); + assert!(module_name(&type_info) == b"type_info", 1); + assert!(struct_name(&type_info) == b"TypeInfo", 2); + } + + #[test] + fun test_type_of_with_type_arg() { + let type_info = type_of>(); + assert!(account_address(&type_info) == @aptos_std, 0); + assert!(module_name(&type_info) == b"table", 1); + assert!(struct_name(&type_info) == b"Table<0x1::string::String, 0x1::string::String>", 2); + } + + #[test(fx = @std)] + fun test_chain_id(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags(&fx, vector[features::get_aptos_stdlib_chain_id_feature()], vector[]); + + // The testing environment chain ID is 4u8. + assert!(chain_id() == 4u8, 1); + } + + #[test] + fun test_type_name() { + + + assert!(type_name() == string::utf8(b"bool"), 0); + assert!(type_name() == string::utf8(b"u8"), 1); + assert!(type_name() == string::utf8(b"u64"), 2); + assert!(type_name() == string::utf8(b"u128"), 3); + assert!(type_name

() == string::utf8(b"address"), 4); + assert!(type_name() == string::utf8(b"signer"), 5); + + // vector + assert!(type_name>() == string::utf8(b"vector"), 6); + assert!(type_name>>() == string::utf8(b"vector>"), 7); + assert!(type_name>>() == string::utf8(b"vector>"), 8); + + + // struct + assert!(type_name() == string::utf8(b"0x1::type_info::TypeInfo"), 9); + assert!(type_name< + Table< + TypeInfo, + Table> + > + >() == string::utf8(b"0x1::table::Table<0x1::type_info::TypeInfo, 0x1::table::Table>>"), 10); + } + + #[verify_only] + fun verify_type_of() { + let type_info = type_of(); + let account_address = account_address(&type_info); + let module_name = module_name(&type_info); + let struct_name = struct_name(&type_info); + spec { + assert account_address == @aptos_std; + assert module_name == b"type_info"; + assert struct_name == b"TypeInfo"; + }; + } + + #[verify_only] + fun verify_type_of_generic() { + let type_info = type_of(); + let account_address = account_address(&type_info); + let module_name = module_name(&type_info); + let struct_name = struct_name(&type_info); + spec { + assert account_address == type_of().account_address; + assert module_name == type_of().module_name; + assert struct_name == type_of().struct_name; + }; + } + spec verify_type_of_generic { + aborts_if !spec_is_struct(); + } + + #[test_only] + struct CustomType has drop {} + + #[test_only] + struct SimpleStruct has copy, drop { + field: u8 + } + + #[test_only] + struct ComplexStruct has copy, drop { + field_1: bool, + field_2: u8, + field_3: u64, + field_4: u128, + field_5: SimpleStruct, + field_6: T + } + + #[test_only] + struct TwoBools has drop { + bool_1: bool, + bool_2: bool + } + + #[test_only] + use std::option; + + #[test(account = @0x0)] + /// Ensure valid returns across native types and nesting schemas. + fun test_size_of_val( + account: &signer + ) { + assert!(size_of_val(&false) == 1, 0); // Bool takes 1 byte. + assert!(size_of_val(&0) == 1, 0); // u8 takes 1 byte. + assert!(size_of_val(&0) == 8, 0); // u64 takes 8 bytes. + assert!(size_of_val(&0) == 16, 0); // u128 takes 16 bytes. + // Address is a u256. + assert!(size_of_val(&@0x0) == 32, 0); + assert!(size_of_val(account) == 32, 0); // Signer is an address. + // Assert custom type without fields has size 1. + assert!(size_of_val(&CustomType{}) == 1, 0); + // Declare a simple struct with a 1-byte field. + let simple_struct = SimpleStruct{field: 0}; + // Assert size is indicated as 1 byte. + assert!(size_of_val(&simple_struct) == 1, 0); + let complex_struct = ComplexStruct{ + field_1: false, + field_2: 0, + field_3: 0, + field_4: 0, + field_5: simple_struct, + field_6: 0 + }; // Declare a complex struct with another nested inside. + // Assert size is bytewise sum of components. + assert!(size_of_val(&complex_struct) == (1 + 1 + 8 + 16 + 1 + 16), 0); + // Declare a struct with two boolean values. + let two_bools = TwoBools{bool_1: false, bool_2: false}; + // Assert size is two bytes. + assert!(size_of_val(&two_bools) == 2, 0); + // Declare an empty vector of element type u64. + let empty_vector_u64 = vector::empty(); + // Declare an empty vector of element type u128. + let empty_vector_u128 = vector::empty(); + // Assert size is 1 byte regardless of underlying element type. + assert!(size_of_val(&empty_vector_u64) == 1, 0); + // Assert size is 1 byte regardless of underlying element type. + assert!(size_of_val(&empty_vector_u128) == 1, 0); + // Declare a bool in a vector. + let bool_vector = vector::singleton(false); + // Push back another bool. + vector::push_back(&mut bool_vector, false); + // Assert size is 3 bytes (1 per element, 1 for base vector). + assert!(size_of_val(&bool_vector) == 3, 0); + // Get a some option, which is implemented as a vector. + let u64_option = option::some(0); + // Assert size is 9 bytes (8 per element, 1 for base vector). + assert!(size_of_val(&u64_option) == 9, 0); + option::extract(&mut u64_option); // Remove the value inside. + // Assert size reduces to 1 byte. + assert!(size_of_val(&u64_option) == 1, 0); + } + + #[test] + /// Verify returns for base vector size at different lengths, with + /// different underlying fixed-size elements. + /// + /// For a vector of length n containing fixed-size elements, the + /// size of the vector is b + n * s bytes, where s is the size of an + /// element in bytes, and b is a "base size" in bytes that varies + /// with n. + /// + /// The base size is an artifact of vector BCS encoding, namely, + /// with b leading bytes that declare how many elements are in the + /// vector. Each such leading byte has a reserved control bit (e.g. + /// is this the last leading byte?), such that 7 bits per leading + /// byte remain for the actual element count. Hence for a single + /// leading byte, the maximum element count that can be described is + /// (2 ^ 7) - 1, and for b leading bytes, the maximum element count + /// that can be described is (2 ^ 7) ^ b - 1: + /// + /// * b = 1, n < 128 + /// * b = 2, 128 <= n < 16384 + /// * b = 3, 16384 <= n < 2097152 + /// * ... + /// * (2 ^ 7) ^ (b - 1) <= n < (2 ^ 7) ^ b + /// * ... + /// * b = 9, 72057594037927936 <= n < 9223372036854775808 + /// * b = 10, 9223372036854775808 <= n < 18446744073709551616 + /// + /// Note that the upper bound on n for b = 10 is 2 ^ 64, rather than + /// (2 ^ 7) ^ 10 - 1, because the former, lower figure is the + /// maximum number of elements that can be stored in a vector in the + /// first place, e.g. U64_MAX. + /// + /// In practice b > 2 is unlikely to be encountered. + fun test_size_of_val_vectors() { + // Declare vector base sizes. + let (base_size_1, base_size_2, base_size_3) = (1, 2, 3); + // A base size of 1 applies for 127 or less elements. + let n_elems_cutoff_1 = 127; // (2 ^ 7) ^ 1 - 1. + // A base size of 2 applies for 128 < n <= 16384 elements. + let n_elems_cutoff_2 = 16383; // (2 ^ 7) ^ 2 - 1. + let vector_u64 = vector::empty(); // Declare empty vector. + let null_element = 0; // Declare a null element. + // Get element size. + let element_size = size_of_val(&null_element); + // Vector size is 1 byte when length is 0. + assert!(size_of_val(&vector_u64) == base_size_1, 0); + let i = 0; // Declare loop counter. + while (i < n_elems_cutoff_1) { // Iterate until first cutoff: + // Add an element. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + }; + // Vector base size is still 1 byte. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_1, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + // Vector base size is now 2 bytes. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_2, 0); + while (i < n_elems_cutoff_2) { // Iterate until second cutoff: + // Add an element. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + }; + // Vector base size is still 2 bytes. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_2, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + // Vector base size is now 3 bytes. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_3, 0); + // Repeat for custom struct. + let vector_complex = vector::empty>(); + // Declare a null element. + let null_element = ComplexStruct{ + field_1: false, + field_2: 0, + field_3: 0, + field_4: 0, + field_5: SimpleStruct{field: 0}, + field_6: @0x0 + }; + element_size = size_of_val(&null_element); // Get element size. + // Vector size is 1 byte when length is 0. + assert!(size_of_val(&vector_complex) == base_size_1, 0); + i = 0; // Re-initialize loop counter. + while (i < n_elems_cutoff_1) { // Iterate until first cutoff: + // Add an element. + vector::push_back(&mut vector_complex, copy null_element); + i = i + 1; // Increment counter. + }; + assert!( // Vector base size is still 1 byte. + size_of_val(&vector_complex) - element_size * i == base_size_1, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_complex, null_element); + i = i + 1; // Increment counter. + assert!( // Vector base size is now 2 bytes. + size_of_val(&vector_complex) - element_size * i == base_size_2, 0); + while (i < n_elems_cutoff_2) { // Iterate until second cutoff: + // Add an element. + vector::push_back(&mut vector_complex, copy null_element); + i = i + 1; // Increment counter. + }; + assert!( // Vector base size is still 2 bytes. + size_of_val(&vector_complex) - element_size * i == base_size_2, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_complex, null_element); + i = i + 1; // Increment counter. + assert!( // Vector base size is now 3 bytes. + size_of_val(&vector_complex) - element_size * i == base_size_3, 0); + } + +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/property_map.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/property_map.move new file mode 100644 index 0000000..45546cc --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/property_map.move @@ -0,0 +1,383 @@ +/// PropertyMap is a specialization of SimpleMap for Tokens. +/// It maps a String key to a PropertyValue that consists of type (string) and value (vector) +/// It provides basic on-chain serialization of primitive and string to property value with type information +/// It also supports deserializing property value to it original type. +module aptos_token::property_map { + use std::bcs; + use std::vector; + use std::error; + use std::string::{Self, String}; + use aptos_std::from_bcs; + use aptos_std::simple_map::{Self, SimpleMap}; + use aptos_std::type_info::type_name; + + // + // Constants + // + /// The maximal number of property that can be stored in property map + const MAX_PROPERTY_MAP_SIZE: u64 = 1000; + const MAX_PROPERTY_NAME_LENGTH: u64 = 128; + + + // + // Errors. + // + /// The property key already exists + const EKEY_AREADY_EXIST_IN_PROPERTY_MAP: u64 = 1; + + /// The number of property exceeds the limit + const EPROPERTY_NUMBER_EXCEED_LIMIT: u64 = 2; + + /// The property doesn't exist + const EPROPERTY_NOT_EXIST: u64 = 3; + + /// Property key and value count don't match + const EKEY_COUNT_NOT_MATCH_VALUE_COUNT: u64 = 4; + + /// Property key and type count don't match + const EKEY_COUNT_NOT_MATCH_TYPE_COUNT: u64 = 5; + + /// Property type doesn't match + const ETYPE_NOT_MATCH: u64 = 6; + + /// The name (key) of the property is too long + const EPROPERTY_MAP_NAME_TOO_LONG: u64 = 7; + + + // + // Structs + // + + struct PropertyMap has copy, drop, store { + map: SimpleMap, + } + + struct PropertyValue has store, copy, drop { + value: vector, + type: String, + } + + public fun new( + keys: vector, + values: vector>, + types: vector + ): PropertyMap { + let length = vector::length(&keys); + assert!(length <= MAX_PROPERTY_MAP_SIZE, error::invalid_argument(EPROPERTY_NUMBER_EXCEED_LIMIT)); + assert!(length == vector::length(&values), error::invalid_argument(EKEY_COUNT_NOT_MATCH_VALUE_COUNT)); + assert!(length == vector::length(&types), error::invalid_argument(EKEY_COUNT_NOT_MATCH_TYPE_COUNT)); + + let properties = empty(); + + let i = 0; + while (i < length) { + let key = *vector::borrow(&keys, i); + assert!(string::length(&key) <= MAX_PROPERTY_NAME_LENGTH, error::invalid_argument(EPROPERTY_MAP_NAME_TOO_LONG)); + simple_map::add( + &mut properties.map, + key, + PropertyValue { value: *vector::borrow(&values, i), type: *vector::borrow(&types, i) } + ); + i = i + 1; + }; + properties + } + + /// Create property map directly from key and property value + public fun new_with_key_and_property_value( + keys: vector, + values: vector + ): PropertyMap { + let length = vector::length(&keys); + assert!(length <= MAX_PROPERTY_MAP_SIZE, error::invalid_argument(EPROPERTY_NUMBER_EXCEED_LIMIT)); + assert!(length == vector::length(&values), error::invalid_argument(EKEY_COUNT_NOT_MATCH_VALUE_COUNT)); + + let properties = empty(); + + let i = 0; + while (i < length) { + let key = *vector::borrow(&keys, i); + let val = *vector::borrow(&values, i); + assert!(string::length(&key) <= MAX_PROPERTY_NAME_LENGTH, error::invalid_argument(EPROPERTY_MAP_NAME_TOO_LONG)); + add(&mut properties, key, val); + i = i + 1; + }; + properties + } + + public fun empty(): PropertyMap { + PropertyMap { + map: simple_map::create(), + } + } + + public fun contains_key(map: &PropertyMap, key: &String): bool { + simple_map::contains_key(&map.map, key) + } + + public fun add(map: &mut PropertyMap, key: String, value: PropertyValue) { + assert!(string::length(&key) <= MAX_PROPERTY_NAME_LENGTH, error::invalid_argument(EPROPERTY_MAP_NAME_TOO_LONG)); + assert!(simple_map::length(&map.map) < MAX_PROPERTY_MAP_SIZE, error::invalid_state(EPROPERTY_NUMBER_EXCEED_LIMIT)); + simple_map::add(&mut map.map, key, value); + } + + public fun length(map: &PropertyMap): u64 { + simple_map::length(&map.map) + } + + public fun borrow(map: &PropertyMap, key: &String): &PropertyValue { + let found = contains_key(map, key); + assert!(found, EPROPERTY_NOT_EXIST); + simple_map::borrow(&map.map, key) + } + + /// Return all the keys in the property map in the order they are added. + public fun keys(map: &PropertyMap): vector { + simple_map::keys(&map.map) + } + + /// Return the types of all properties in the property map in the order they are added. + public fun types(map: &PropertyMap): vector { + vector::map_ref(&simple_map::values(&map.map), |v| { + let v: &PropertyValue = v; + v.type + }) + } + + /// Return the values of all properties in the property map in the order they are added. + public fun values(map: &PropertyMap): vector> { + vector::map_ref(&simple_map::values(&map.map), |v| { + let v: &PropertyValue = v; + v.value + }) + } + + public fun read_string(map: &PropertyMap, key: &String): String { + let prop = borrow(map, key); + assert!(prop.type == string::utf8(b"0x1::string::String"), error::invalid_state(ETYPE_NOT_MATCH)); + from_bcs::to_string(prop.value) + } + + public fun read_u8(map: &PropertyMap, key: &String): u8 { + let prop = borrow(map, key); + assert!(prop.type == string::utf8(b"u8"), error::invalid_state(ETYPE_NOT_MATCH)); + from_bcs::to_u8(prop.value) + } + + public fun read_u64(map: &PropertyMap, key: &String): u64 { + let prop = borrow(map, key); + assert!(prop.type == string::utf8(b"u64"), error::invalid_state(ETYPE_NOT_MATCH)); + from_bcs::to_u64(prop.value) + } + + public fun read_address(map: &PropertyMap, key: &String): address { + let prop = borrow(map, key); + assert!(prop.type == string::utf8(b"address"), error::invalid_state(ETYPE_NOT_MATCH)); + from_bcs::to_address(prop.value) + } + + public fun read_u128(map: &PropertyMap, key: &String): u128 { + let prop = borrow(map, key); + assert!(prop.type == string::utf8(b"u128"), error::invalid_state(ETYPE_NOT_MATCH)); + from_bcs::to_u128(prop.value) + } + + public fun read_bool(map: &PropertyMap, key: &String): bool { + let prop = borrow(map, key); + assert!(prop.type == string::utf8(b"bool"), error::invalid_state(ETYPE_NOT_MATCH)); + from_bcs::to_bool(prop.value) + } + + public fun borrow_value(property: &PropertyValue): vector { + property.value + } + + public fun borrow_type(property: &PropertyValue): String { + property.type + } + + public fun remove( + map: &mut PropertyMap, + key: &String + ): (String, PropertyValue) { + let found = contains_key(map, key); + assert!(found, error::not_found(EPROPERTY_NOT_EXIST)); + simple_map::remove(&mut map.map, key) + } + + /// Update the property in the existing property map + /// Allow updating existing keys' value and add new key-value pairs + public fun update_property_map( + map: &mut PropertyMap, + keys: vector, + values: vector>, + types: vector, + ) { + let key_len = vector::length(&keys); + let val_len = vector::length(&values); + let typ_len = vector::length(&types); + assert!(key_len == val_len, error::invalid_state(EKEY_COUNT_NOT_MATCH_VALUE_COUNT)); + assert!(key_len == typ_len, error::invalid_state(EKEY_COUNT_NOT_MATCH_TYPE_COUNT)); + + let i = 0; + while (i < key_len) { + let key = vector::borrow(&keys, i); + let prop_val = PropertyValue { + value: *vector::borrow(&values, i), + type: *vector::borrow(&types, i), + }; + if (contains_key(map, key)) { + update_property_value(map, key, prop_val); + } else { + add(map, *key, prop_val); + }; + i = i + 1; + } + } + + public fun update_property_value( + map: &mut PropertyMap, + key: &String, + value: PropertyValue + ) { + let property_val = simple_map::borrow_mut(&mut map.map, key); + *property_val = value; + } + + public fun create_property_value_raw( + value: vector, + type: String + ): PropertyValue { + PropertyValue { + value, + type, + } + } + + /// create a property value from generic type data + public fun create_property_value(data: &T): PropertyValue { + let name = type_name(); + if ( + name == string::utf8(b"bool") || + name == string::utf8(b"u8") || + name == string::utf8(b"u64") || + name == string::utf8(b"u128") || + name == string::utf8(b"address") || + name == string::utf8(b"0x1::string::String") + ) { + create_property_value_raw(bcs::to_bytes(data), name) + } else { + create_property_value_raw(bcs::to_bytes(data), string::utf8(b"vector")) + } + } + + #[test_only] + use std::string::utf8; + + #[test_only] + fun test_keys(): vector { + vector[ utf8(b"attack"), utf8(b"durability"), utf8(b"type") ] + } + + #[test_only] + fun test_values(): vector> { + vector[ b"10", b"5", b"weapon" ] + } + + #[test_only] + fun test_types(): vector { + vector[ utf8(b"integer"), utf8(b"integer"), utf8(b"String") ] + } + + #[test_only] + fun create_property_list(): PropertyMap { + new(test_keys(), test_values(), test_types()) + } + + #[test] + fun test_add_property(): PropertyMap { + let properties = create_property_list(); + add( + &mut properties, utf8(b"level"), + PropertyValue { + value: b"1", + type: utf8(b"integer") + }); + assert!( + borrow(&properties, &utf8(b"level")).value == b"1", + EPROPERTY_NOT_EXIST); + properties + } + + #[test] + fun test_get_property_keys() { + assert!(keys(&create_property_list()) == test_keys(), 0); + } + + #[test] + fun test_get_property_types() { + assert!(types(&create_property_list()) == test_types(), 0); + } + + #[test] + fun test_get_property_values() { + assert!(values(&create_property_list()) == test_values(), 0); + } + + #[test] + fun test_update_property(): PropertyMap { + let properties = create_property_list(); + update_property_value(&mut properties, &utf8(b"attack"), PropertyValue { value: b"7", type: utf8(b"integer") }); + assert!( + borrow(&properties, &utf8(b"attack")).value == b"7", + 1 + ); + properties + } + + #[test] + fun test_remove_property(): PropertyMap { + let properties = create_property_list(); + assert!(length(&mut properties) == 3, 1); + let (_, _) = remove(&mut properties, &utf8(b"attack")); + assert!(length(&properties) == 2, 1); + properties + } + + #[test_only] + public fun test_create_property_value(type: String, value: vector): PropertyValue { + PropertyValue { + type, + value + } + } + + #[test] + fun test_read_value_with_type() { + let keys = vector[ utf8(b"attack"), utf8(b"mutable")]; + let values = vector>[ bcs::to_bytes(&10), bcs::to_bytes(&false) ]; + let types = vector[ utf8(b"u8"), utf8(b"bool")]; + let plist = new(keys, values, types); + assert!(!read_bool(&plist, &utf8(b"mutable")), 1); + assert!(read_u8(&plist, &utf8(b"attack")) == 10, 1); + } + + #[test] + fun test_generate_property_value_convert_back() { + let data: address = @0xcafe; + let pv = create_property_value(&data); + let pm = create_property_list(); + add(&mut pm, string::utf8(b"addr"), pv); + assert!(read_address(&pm, &string::utf8(b"addr")) == data, 1) + } + + #[test] + fun test_create_property_map_from_key_value_pairs() { + let data1: address = @0xcafe; + let data2: bool = false; + let pvs = vector[create_property_value(&data1), create_property_value(&data2)]; + let keys = vector[string::utf8(b"addr"), string::utf8(b"flag")]; + let pm = new_with_key_and_property_value(keys, pvs); + assert!(length(&pm) == 2, 1); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token.move new file mode 100644 index 0000000..168a6fa --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token.move @@ -0,0 +1,2700 @@ +/// This module provides the foundation for Tokens. +/// Checkout our developer doc on our token standard https://aptos.dev/standards +module aptos_token::token { + use std::error; + use std::option::{Self, Option}; + use std::signer; + use std::string::{Self, String}; + use std::vector; + + use aptos_framework::account; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::timestamp; + use aptos_std::table::{Self, Table}; + use aptos_token::property_map::{Self, PropertyMap, PropertyValue}; + use aptos_token::token_event_store; + + // + // Constants + // + + const TOKEN_MAX_MUTABLE_IND: u64 = 0; + const TOKEN_URI_MUTABLE_IND: u64 = 1; + const TOKEN_ROYALTY_MUTABLE_IND: u64 = 2; + const TOKEN_DESCRIPTION_MUTABLE_IND: u64 = 3; + const TOKEN_PROPERTY_MUTABLE_IND: u64 = 4; + const TOKEN_PROPERTY_VALUE_MUTABLE_IND: u64 = 5; + + const COLLECTION_DESCRIPTION_MUTABLE_IND: u64 = 0; + const COLLECTION_URI_MUTABLE_IND: u64 = 1; + const COLLECTION_MAX_MUTABLE_IND: u64 = 2; + + const MAX_COLLECTION_NAME_LENGTH: u64 = 128; + const MAX_NFT_NAME_LENGTH: u64 = 128; + const MAX_URI_LENGTH: u64 = 512; + + // Property key stored in default_properties controlling who can burn the token. + // the corresponding property value is BCS serialized bool. + const BURNABLE_BY_CREATOR: vector = b"TOKEN_BURNABLE_BY_CREATOR"; + const BURNABLE_BY_OWNER: vector = b"TOKEN_BURNABLE_BY_OWNER"; + const TOKEN_PROPERTY_MUTABLE: vector = b"TOKEN_PROPERTY_MUTATBLE"; + + // + // Errors + // + /// The token has balance and cannot be initialized + const EALREADY_HAS_BALANCE: u64 = 0; + + /// There isn't any collection under this account + const ECOLLECTIONS_NOT_PUBLISHED: u64 = 1; + + /// Cannot find collection in creator's account + const ECOLLECTION_NOT_PUBLISHED: u64 = 2; + + /// The collection already exists + const ECOLLECTION_ALREADY_EXISTS: u64 = 3; + + /// Exceeds the collection's maximal number of token_data + const ECREATE_WOULD_EXCEED_COLLECTION_MAXIMUM: u64 = 4; + + /// Insufficient token balance + const EINSUFFICIENT_BALANCE: u64 = 5; + + /// Cannot merge the two tokens with different token id + const EINVALID_TOKEN_MERGE: u64 = 6; + + /// Exceed the token data maximal allowed + const EMINT_WOULD_EXCEED_TOKEN_MAXIMUM: u64 = 7; + + /// No burn capability + const ENO_BURN_CAPABILITY: u64 = 8; + + /// TokenData already exists + const ETOKEN_DATA_ALREADY_EXISTS: u64 = 9; + + /// TokenData not published + const ETOKEN_DATA_NOT_PUBLISHED: u64 = 10; + + /// TokenStore doesn't exist + const ETOKEN_STORE_NOT_PUBLISHED: u64 = 11; + + /// Cannot split token to an amount larger than its amount + const ETOKEN_SPLIT_AMOUNT_LARGER_OR_EQUAL_TO_TOKEN_AMOUNT: u64 = 12; + + /// The field is not mutable + const EFIELD_NOT_MUTABLE: u64 = 13; + + /// Not authorized to mutate + const ENO_MUTATE_CAPABILITY: u64 = 14; + + /// Token not in the token store + const ENO_TOKEN_IN_TOKEN_STORE: u64 = 15; + + /// User didn't opt-in direct transfer + const EUSER_NOT_OPT_IN_DIRECT_TRANSFER: u64 = 16; + + /// Cannot withdraw 0 token + const EWITHDRAW_ZERO: u64 = 17; + + /// Cannot split a token that only has 1 amount + const ENFT_NOT_SPLITABLE: u64 = 18; + + /// No mint capability + const ENO_MINT_CAPABILITY: u64 = 19; + + /// The collection name is too long + const ECOLLECTION_NAME_TOO_LONG: u64 = 25; + + /// The NFT name is too long + const ENFT_NAME_TOO_LONG: u64 = 26; + + /// The URI is too long + const EURI_TOO_LONG: u64 = 27; + + /// Cannot deposit a Token with 0 amount + const ENO_DEPOSIT_TOKEN_WITH_ZERO_AMOUNT: u64 = 28; + + /// Cannot burn 0 Token + const ENO_BURN_TOKEN_WITH_ZERO_AMOUNT: u64 = 29; + + /// Token is not burnable by owner + const EOWNER_CANNOT_BURN_TOKEN: u64 = 30; + + /// Token is not burnable by creator + const ECREATOR_CANNOT_BURN_TOKEN: u64 = 31; + + /// Reserved fields for token contract + /// Cannot be updated by user + const ECANNOT_UPDATE_RESERVED_PROPERTY: u64 = 32; + + /// TOKEN with 0 amount is not allowed + const ETOKEN_CANNOT_HAVE_ZERO_AMOUNT: u64 = 33; + + /// Royalty invalid if the numerator is larger than the denominator + const EINVALID_ROYALTY_NUMERATOR_DENOMINATOR: u64 = 34; + + /// Royalty payee account does not exist + const EROYALTY_PAYEE_ACCOUNT_DOES_NOT_EXIST: u64 = 35; + + /// Collection or tokendata maximum must be larger than supply + const EINVALID_MAXIMUM: u64 = 36; + + /// Token Properties count doesn't match + const ETOKEN_PROPERTIES_COUNT_NOT_MATCH: u64 = 37; + + + /// Withdraw capability doesn't have sufficient amount + const EINSUFFICIENT_WITHDRAW_CAPABILITY_AMOUNT: u64 = 38; + + /// Withdraw proof expires + const EWITHDRAW_PROOF_EXPIRES: u64 = 39; + + /// The property is reserved by token standard + const EPROPERTY_RESERVED_BY_STANDARD: u64 = 40; + + // + // Core data structures for holding tokens + // + struct Token has store { + id: TokenId, + /// the amount of tokens. Only property_version = 0 can have a value bigger than 1. + amount: u64, + /// The properties with this token. + /// when property_version = 0, the token_properties are the same as default_properties in TokenData, we don't store it. + /// when the property_map mutates, a new property_version is assigned to the token. + token_properties: PropertyMap, + } + + /// global unique identifier of a token + struct TokenId has store, copy, drop { + /// the id to the common token data shared by token with different property_version + token_data_id: TokenDataId, + /// The version of the property map; when a fungible token is mutated, a new property version is created and assigned to the token to make it an NFT + property_version: u64, + } + + /// globally unique identifier of tokendata + struct TokenDataId has copy, drop, store { + /// The address of the creator, eg: 0xcafe + creator: address, + /// The name of collection; this is unique under the same account, eg: "Aptos Animal Collection" + collection: String, + /// The name of the token; this is the same as the name field of TokenData + name: String, + } + + /// The shared TokenData by tokens with different property_version + struct TokenData has store { + /// The maximal number of tokens that can be minted under this TokenData; if the maximum is 0, there is no limit + maximum: u64, + /// The current largest property version of all tokens with this TokenData + largest_property_version: u64, + /// The number of tokens with this TokenData. Supply is only tracked for the limited token whose maximum is not 0 + supply: u64, + /// The Uniform Resource Identifier (uri) pointing to the JSON file stored in off-chain storage; the URL length should be less than 512 characters, eg: https://arweave.net/Fmmn4ul-7Mv6vzm7JwE69O-I-vd6Bz2QriJO1niwCh4 + uri: String, + /// The denominator and numerator for calculating the royalty fee; it also contains payee account address for depositing the Royalty + royalty: Royalty, + /// The name of the token, which should be unique within the collection; the length of name should be smaller than 128, characters, eg: "Aptos Animal #1234" + name: String, + /// Describes this Token + description: String, + /// The properties are stored in the TokenData that are shared by all tokens + default_properties: PropertyMap, + /// Control the TokenData field mutability + mutability_config: TokenMutabilityConfig, + } + + /// The royalty of a token + struct Royalty has copy, drop, store { + royalty_points_numerator: u64, + royalty_points_denominator: u64, + /// if the token is jointly owned by multiple creators, the group of creators should create a shared account. + /// the payee_address will be the shared account address. + payee_address: address, + } + + /// This config specifies which fields in the TokenData are mutable + struct TokenMutabilityConfig has copy, store, drop { + /// control if the token maximum is mutable + maximum: bool, + /// control if the token uri is mutable + uri: bool, + /// control if the token royalty is mutable + royalty: bool, + /// control if the token description is mutable + description: bool, + /// control if the property map is mutable + properties: bool, + } + + /// Represents token resources owned by token owner + struct TokenStore has key { + /// the tokens owned by a token owner + tokens: Table, + direct_transfer: bool, + deposit_events: EventHandle, + withdraw_events: EventHandle, + burn_events: EventHandle, + mutate_token_property_events: EventHandle, + } + + /// This config specifies which fields in the Collection are mutable + struct CollectionMutabilityConfig has copy, store, drop { + /// control if description is mutable + description: bool, + /// control if uri is mutable + uri: bool, + /// control if collection maxium is mutable + maximum: bool, + } + + /// Represent collection and token metadata for a creator + struct Collections has key { + collection_data: Table, + token_data: Table, + create_collection_events: EventHandle, + create_token_data_events: EventHandle, + mint_token_events: EventHandle, + } + + /// Represent the collection metadata + struct CollectionData has store { + /// A description for the token collection Eg: "Aptos Toad Overload" + description: String, + /// The collection name, which should be unique among all collections by the creator; the name should also be smaller than 128 characters, eg: "Animal Collection" + name: String, + /// The URI for the collection; its length should be smaller than 512 characters + uri: String, + /// The number of different TokenData entries in this collection + supply: u64, + /// If maximal is a non-zero value, the number of created TokenData entries should be smaller or equal to this maximum + /// If maximal is 0, Aptos doesn't track the supply of this collection, and there is no limit + maximum: u64, + /// control which collectionData field is mutable + mutability_config: CollectionMutabilityConfig, + } + + /// capability to withdraw without signer, this struct should be non-copyable + struct WithdrawCapability has drop, store { + token_owner: address, + token_id: TokenId, + amount: u64, + expiration_sec: u64, + } + + /// Set of data sent to the event stream during a receive + struct DepositEvent has drop, store { + id: TokenId, + amount: u64, + } + + /// Set of data sent to the event stream during a withdrawal + struct WithdrawEvent has drop, store { + id: TokenId, + amount: u64, + } + + /// token creation event id of token created + struct CreateTokenDataEvent has drop, store { + id: TokenDataId, + description: String, + maximum: u64, + uri: String, + royalty_payee_address: address, + royalty_points_denominator: u64, + royalty_points_numerator: u64, + name: String, + mutability_config: TokenMutabilityConfig, + property_keys: vector, + property_values: vector>, + property_types: vector, + } + + /// mint token event. This event triggered when creator adds more supply to existing token + struct MintTokenEvent has drop, store { + id: TokenDataId, + amount: u64, + } + + /// + struct BurnTokenEvent has drop, store { + id: TokenId, + amount: u64, + } + + /// + struct MutateTokenPropertyMapEvent has drop, store { + old_id: TokenId, + new_id: TokenId, + keys: vector, + values: vector>, + types: vector, + } + + /// create collection event with creator address and collection name + struct CreateCollectionEvent has drop, store { + creator: address, + collection_name: String, + uri: String, + description: String, + maximum: u64, + } + + // + // Creator Entry functions + // + + /// create a empty token collection with parameters + public entry fun create_collection_script( + creator: &signer, + name: String, + description: String, + uri: String, + maximum: u64, + mutate_setting: vector, + ) acquires Collections { + create_collection( + creator, + name, + description, + uri, + maximum, + mutate_setting + ); + } + + /// create token with raw inputs + public entry fun create_token_script( + account: &signer, + collection: String, + name: String, + description: String, + balance: u64, + maximum: u64, + uri: String, + royalty_payee_address: address, + royalty_points_denominator: u64, + royalty_points_numerator: u64, + mutate_setting: vector, + property_keys: vector, + property_values: vector>, + property_types: vector + ) acquires Collections, TokenStore { + let token_mut_config = create_token_mutability_config(&mutate_setting); + let tokendata_id = create_tokendata( + account, + collection, + name, + description, + maximum, + uri, + royalty_payee_address, + royalty_points_denominator, + royalty_points_numerator, + token_mut_config, + property_keys, + property_values, + property_types + ); + + mint_token( + account, + tokendata_id, + balance, + ); + } + + /// Mint more token from an existing token_data. Mint only adds more token to property_version 0 + public entry fun mint_script( + account: &signer, + token_data_address: address, + collection: String, + name: String, + amount: u64, + ) acquires Collections, TokenStore { + let token_data_id = create_token_data_id( + token_data_address, + collection, + name, + ); + // only creator of the tokendata can mint more tokens for now + assert!(token_data_id.creator == signer::address_of(account), error::permission_denied(ENO_MINT_CAPABILITY)); + mint_token( + account, + token_data_id, + amount, + ); + } + + /// mutate the token property and save the new property in TokenStore + /// if the token property_version is 0, we will create a new property_version per token to generate a new token_id per token + /// if the token property_version is not 0, we will just update the propertyMap and use the existing token_id (property_version) + public entry fun mutate_token_properties( + account: &signer, + token_owner: address, + creator: address, + collection_name: String, + token_name: String, + token_property_version: u64, + amount: u64, + keys: vector, + values: vector>, + types: vector, + ) acquires Collections, TokenStore { + assert!(signer::address_of(account) == creator, error::not_found(ENO_MUTATE_CAPABILITY)); + let i = 0; + let token_id = create_token_id_raw( + creator, + collection_name, + token_name, + token_property_version, + ); + // give a new property_version for each token + while (i < amount) { + mutate_one_token(account, token_owner, token_id, keys, values, types); + i = i + 1; + }; + } + + // + // Transaction Entry functions + // + + public entry fun direct_transfer_script( + sender: &signer, + receiver: &signer, + creators_address: address, + collection: String, + name: String, + property_version: u64, + amount: u64, + ) acquires TokenStore { + let token_id = create_token_id_raw(creators_address, collection, name, property_version); + direct_transfer(sender, receiver, token_id, amount); + } + + public entry fun opt_in_direct_transfer(account: &signer, opt_in: bool) acquires TokenStore { + let addr = signer::address_of(account); + initialize_token_store(account); + let opt_in_flag = &mut borrow_global_mut(addr).direct_transfer; + *opt_in_flag = opt_in; + token_event_store::emit_token_opt_in_event(account, opt_in); + } + + /// Transfers `amount` of tokens from `from` to `to`. + /// The receiver `to` has to opt-in direct transfer first + public entry fun transfer_with_opt_in( + from: &signer, + creator: address, + collection_name: String, + token_name: String, + token_property_version: u64, + to: address, + amount: u64, + ) acquires TokenStore { + let token_id = create_token_id_raw(creator, collection_name, token_name, token_property_version); + transfer(from, token_id, to, amount); + } + + /// Burn a token by creator when the token's BURNABLE_BY_CREATOR is true + /// The token is owned at address owner + public entry fun burn_by_creator( + creator: &signer, + owner: address, + collection: String, + name: String, + property_version: u64, + amount: u64, + ) acquires Collections, TokenStore { + let creator_address = signer::address_of(creator); + assert!(amount > 0, error::invalid_argument(ENO_BURN_TOKEN_WITH_ZERO_AMOUNT)); + let token_id = create_token_id_raw(creator_address, collection, name, property_version); + let creator_addr = token_id.token_data_id.creator; + assert!( + exists(creator_addr), + error::not_found(ECOLLECTIONS_NOT_PUBLISHED), + ); + + let collections = borrow_global_mut(creator_address); + assert!( + table::contains(&collections.token_data, token_id.token_data_id), + error::not_found(ETOKEN_DATA_NOT_PUBLISHED), + ); + + let token_data = table::borrow_mut( + &mut collections.token_data, + token_id.token_data_id, + ); + + // The property should be explicitly set in the property_map for creator to burn the token + assert!( + property_map::contains_key(&token_data.default_properties, &string::utf8(BURNABLE_BY_CREATOR)), + error::permission_denied(ECREATOR_CANNOT_BURN_TOKEN) + ); + + let burn_by_creator_flag = property_map::read_bool(&token_data.default_properties, &string::utf8(BURNABLE_BY_CREATOR)); + assert!(burn_by_creator_flag, error::permission_denied(ECREATOR_CANNOT_BURN_TOKEN)); + + // Burn the tokens. + let Token { id: _, amount: burned_amount, token_properties: _ } = withdraw_with_event_internal(owner, token_id, amount); + let token_store = borrow_global_mut(owner); + event::emit_event( + &mut token_store.burn_events, + BurnTokenEvent { id: token_id, amount: burned_amount }, + ); + + if (token_data.maximum > 0) { + token_data.supply = token_data.supply - burned_amount; + + // Delete the token_data if supply drops to 0. + if (token_data.supply == 0) { + destroy_token_data(table::remove(&mut collections.token_data, token_id.token_data_id)); + + // update the collection supply + let collection_data = table::borrow_mut( + &mut collections.collection_data, + token_id.token_data_id.collection + ); + if (collection_data.maximum > 0) { + collection_data.supply = collection_data.supply - 1; + // delete the collection data if the collection supply equals 0 + if (collection_data.supply == 0) { + destroy_collection_data(table::remove(&mut collections.collection_data, collection_data.name)); + }; + }; + }; + }; + } + + /// Burn a token by the token owner + public entry fun burn( + owner: &signer, + creators_address: address, + collection: String, + name: String, + property_version: u64, + amount: u64 + ) acquires Collections, TokenStore { + assert!(amount > 0, error::invalid_argument(ENO_BURN_TOKEN_WITH_ZERO_AMOUNT)); + let token_id = create_token_id_raw(creators_address, collection, name, property_version); + let creator_addr = token_id.token_data_id.creator; + assert!( + exists(creator_addr), + error::not_found(ECOLLECTIONS_NOT_PUBLISHED), + ); + + let collections = borrow_global_mut(creator_addr); + assert!( + table::contains(&collections.token_data, token_id.token_data_id), + error::not_found(ETOKEN_DATA_NOT_PUBLISHED), + ); + + let token_data = table::borrow_mut( + &mut collections.token_data, + token_id.token_data_id, + ); + + assert!( + property_map::contains_key(&token_data.default_properties, &string::utf8(BURNABLE_BY_OWNER)), + error::permission_denied(EOWNER_CANNOT_BURN_TOKEN) + ); + let burn_by_owner_flag = property_map::read_bool(&token_data.default_properties, &string::utf8(BURNABLE_BY_OWNER)); + assert!(burn_by_owner_flag, error::permission_denied(EOWNER_CANNOT_BURN_TOKEN)); + + // Burn the tokens. + let Token { id: _, amount: burned_amount, token_properties: _ } = withdraw_token(owner, token_id, amount); + let token_store = borrow_global_mut(signer::address_of(owner)); + event::emit_event( + &mut token_store.burn_events, + BurnTokenEvent { id: token_id, amount: burned_amount }, + ); + + // Decrease the supply correspondingly by the amount of tokens burned. + let token_data = table::borrow_mut( + &mut collections.token_data, + token_id.token_data_id, + ); + + // only update the supply if we tracking the supply and maximal + // maximal == 0 is reserved for unlimited token and collection with no tracking info. + if (token_data.maximum > 0) { + token_data.supply = token_data.supply - burned_amount; + + // Delete the token_data if supply drops to 0. + if (token_data.supply == 0) { + destroy_token_data(table::remove(&mut collections.token_data, token_id.token_data_id)); + + // update the collection supply + let collection_data = table::borrow_mut( + &mut collections.collection_data, + token_id.token_data_id.collection + ); + + // only update and check the supply for unlimited collection + if (collection_data.maximum > 0){ + collection_data.supply = collection_data.supply - 1; + // delete the collection data if the collection supply equals 0 + if (collection_data.supply == 0) { + destroy_collection_data(table::remove(&mut collections.collection_data, collection_data.name)); + }; + }; + }; + }; + } + + // + // Public functions for creating and maintaining tokens + // + + // Functions for mutating CollectionData fields + public fun mutate_collection_description(creator: &signer, collection_name: String, description: String) acquires Collections { + let creator_address = signer::address_of(creator); + assert_collection_exists(creator_address, collection_name); + let collection_data = table::borrow_mut(&mut borrow_global_mut(creator_address).collection_data, collection_name); + assert!(collection_data.mutability_config.description, error::permission_denied(EFIELD_NOT_MUTABLE)); + token_event_store::emit_collection_description_mutate_event(creator, collection_name, collection_data.description, description); + collection_data.description = description; + } + + public fun mutate_collection_uri(creator: &signer, collection_name: String, uri: String) acquires Collections { + assert!(string::length(&uri) <= MAX_URI_LENGTH, error::invalid_argument(EURI_TOO_LONG)); + let creator_address = signer::address_of(creator); + assert_collection_exists(creator_address, collection_name); + let collection_data = table::borrow_mut(&mut borrow_global_mut(creator_address).collection_data, collection_name); + assert!(collection_data.mutability_config.uri, error::permission_denied(EFIELD_NOT_MUTABLE)); + token_event_store::emit_collection_uri_mutate_event(creator, collection_name, collection_data.uri , uri); + collection_data.uri = uri; + } + + public fun mutate_collection_maximum(creator: &signer, collection_name: String, maximum: u64) acquires Collections { + let creator_address = signer::address_of(creator); + assert_collection_exists(creator_address, collection_name); + let collection_data = table::borrow_mut(&mut borrow_global_mut(creator_address).collection_data, collection_name); + // cannot change maximum from 0 and cannot change maximum to 0 + assert!(collection_data.maximum != 0 && maximum != 0, error::invalid_argument(EINVALID_MAXIMUM)); + assert!(maximum >= collection_data.supply, error::invalid_argument(EINVALID_MAXIMUM)); + assert!(collection_data.mutability_config.maximum, error::permission_denied(EFIELD_NOT_MUTABLE)); + token_event_store::emit_collection_maximum_mutate_event(creator, collection_name, collection_data.maximum, maximum); + collection_data.maximum = maximum; + } + + // Functions for mutating TokenData fields + public fun mutate_tokendata_maximum(creator: &signer, token_data_id: TokenDataId, maximum: u64) acquires Collections { + assert_tokendata_exists(creator, token_data_id); + let all_token_data = &mut borrow_global_mut(token_data_id.creator).token_data; + let token_data = table::borrow_mut(all_token_data, token_data_id); + // cannot change maximum from 0 and cannot change maximum to 0 + assert!(token_data.maximum != 0 && maximum != 0, error::invalid_argument(EINVALID_MAXIMUM)); + assert!(maximum >= token_data.supply, error::invalid_argument(EINVALID_MAXIMUM)); + assert!(token_data.mutability_config.maximum, error::permission_denied(EFIELD_NOT_MUTABLE)); + token_event_store::emit_token_maximum_mutate_event(creator, token_data_id.collection, token_data_id.name, token_data.maximum, maximum); + token_data.maximum = maximum; + } + + public fun mutate_tokendata_uri( + creator: &signer, + token_data_id: TokenDataId, + uri: String + ) acquires Collections { + assert!(string::length(&uri) <= MAX_URI_LENGTH, error::invalid_argument(EURI_TOO_LONG)); + assert_tokendata_exists(creator, token_data_id); + + let all_token_data = &mut borrow_global_mut(token_data_id.creator).token_data; + let token_data = table::borrow_mut(all_token_data, token_data_id); + assert!(token_data.mutability_config.uri, error::permission_denied(EFIELD_NOT_MUTABLE)); + token_event_store::emit_token_uri_mutate_event(creator, token_data_id.collection, token_data_id.name, token_data.uri ,uri); + token_data.uri = uri; + } + + public fun mutate_tokendata_royalty(creator: &signer, token_data_id: TokenDataId, royalty: Royalty) acquires Collections { + assert_tokendata_exists(creator, token_data_id); + + let all_token_data = &mut borrow_global_mut(token_data_id.creator).token_data; + let token_data = table::borrow_mut(all_token_data, token_data_id); + assert!(token_data.mutability_config.royalty, error::permission_denied(EFIELD_NOT_MUTABLE)); + + token_event_store::emit_token_royalty_mutate_event( + creator, + token_data_id.collection, + token_data_id.name, + token_data.royalty.royalty_points_numerator, + token_data.royalty.royalty_points_denominator, + token_data.royalty.payee_address, + royalty.royalty_points_numerator, + royalty.royalty_points_denominator, + royalty.payee_address + ); + token_data.royalty = royalty; + } + + public fun mutate_tokendata_description(creator: &signer, token_data_id: TokenDataId, description: String) acquires Collections { + assert_tokendata_exists(creator, token_data_id); + + let all_token_data = &mut borrow_global_mut(token_data_id.creator).token_data; + let token_data = table::borrow_mut(all_token_data, token_data_id); + assert!(token_data.mutability_config.description, error::permission_denied(EFIELD_NOT_MUTABLE)); + token_event_store::emit_token_descrition_mutate_event(creator, token_data_id.collection, token_data_id.name, token_data.description, description); + token_data.description = description; + } + + /// Allow creator to mutate the default properties in TokenData + public fun mutate_tokendata_property( + creator: &signer, + token_data_id: TokenDataId, + keys: vector, + values: vector>, + types: vector, + ) acquires Collections { + assert_tokendata_exists(creator, token_data_id); + let key_len = vector::length(&keys); + let val_len = vector::length(&values); + let typ_len = vector::length(&types); + assert!(key_len == val_len, error::invalid_state(ETOKEN_PROPERTIES_COUNT_NOT_MATCH)); + assert!(key_len == typ_len, error::invalid_state(ETOKEN_PROPERTIES_COUNT_NOT_MATCH)); + + let all_token_data = &mut borrow_global_mut(token_data_id.creator).token_data; + let token_data = table::borrow_mut(all_token_data, token_data_id); + assert!(token_data.mutability_config.properties, error::permission_denied(EFIELD_NOT_MUTABLE)); + let i: u64 = 0; + let old_values: vector> = vector::empty(); + let new_values: vector = vector::empty(); + assert_non_standard_reserved_property(&keys); + while (i < vector::length(&keys)){ + let key = vector::borrow(&keys, i); + let old_pv = if (property_map::contains_key(&token_data.default_properties, key)) { + option::some(*property_map::borrow(&token_data.default_properties, key)) + } else { + option::none() + }; + vector::push_back(&mut old_values, old_pv); + let new_pv = property_map::create_property_value_raw(*vector::borrow(&values, i), *vector::borrow(&types, i)); + vector::push_back(&mut new_values, new_pv); + if (option::is_some(&old_pv)) { + property_map::update_property_value(&mut token_data.default_properties, key, new_pv); + } else { + property_map::add(&mut token_data.default_properties, *key, new_pv); + }; + i = i + 1; + }; + token_event_store::emit_default_property_mutate_event(creator, token_data_id.collection, token_data_id.name, keys, old_values, new_values); + } + + /// Mutate the token_properties of one token. + public fun mutate_one_token( + account: &signer, + token_owner: address, + token_id: TokenId, + keys: vector, + values: vector>, + types: vector, + ): TokenId acquires Collections, TokenStore { + let creator = token_id.token_data_id.creator; + assert!(signer::address_of(account) == creator, error::permission_denied(ENO_MUTATE_CAPABILITY)); + // validate if the properties is mutable + assert!(exists(creator), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &mut borrow_global_mut( + creator + ).token_data; + + assert!(table::contains(all_token_data, token_id.token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + let token_data = table::borrow_mut(all_token_data, token_id.token_data_id); + + // if default property is mutatable, token property is alwasy mutable + // we only need to check TOKEN_PROPERTY_MUTABLE when default property is immutable + if (!token_data.mutability_config.properties) { + assert!( + property_map::contains_key(&token_data.default_properties, &string::utf8(TOKEN_PROPERTY_MUTABLE)), + error::permission_denied(EFIELD_NOT_MUTABLE) + ); + + let token_prop_mutable = property_map::read_bool(&token_data.default_properties, &string::utf8(TOKEN_PROPERTY_MUTABLE)); + assert!(token_prop_mutable, error::permission_denied(EFIELD_NOT_MUTABLE)); + }; + + // check if the property_version is 0 to determine if we need to update the property_version + if (token_id.property_version == 0) { + let token = withdraw_with_event_internal(token_owner, token_id, 1); + // give a new property_version for each token + let cur_property_version = token_data.largest_property_version + 1; + let new_token_id = create_token_id(token_id.token_data_id, cur_property_version); + let new_token = Token { + id: new_token_id, + amount: 1, + token_properties: token_data.default_properties, + }; + direct_deposit(token_owner, new_token); + update_token_property_internal(token_owner, new_token_id, keys, values, types); + event::emit_event( + &mut borrow_global_mut(token_owner).mutate_token_property_events, + MutateTokenPropertyMapEvent { + old_id: token_id, + new_id: new_token_id, + keys, + values, + types + }, + ); + + token_data.largest_property_version = cur_property_version; + // burn the orignial property_version 0 token after mutation + let Token { id: _, amount: _, token_properties: _ } = token; + new_token_id + } else { + // only 1 copy for the token with property verion bigger than 0 + update_token_property_internal(token_owner, token_id, keys, values, types); + event::emit_event( + &mut borrow_global_mut(token_owner).mutate_token_property_events, + MutateTokenPropertyMapEvent { + old_id: token_id, + new_id: token_id, + keys, + values, + types + }, + ); + token_id + } + } + + public fun create_royalty(royalty_points_numerator: u64, royalty_points_denominator: u64, payee_address: address): Royalty { + assert!(royalty_points_numerator <= royalty_points_denominator, error::invalid_argument(EINVALID_ROYALTY_NUMERATOR_DENOMINATOR)); + assert!(account::exists_at(payee_address), error::invalid_argument(EROYALTY_PAYEE_ACCOUNT_DOES_NOT_EXIST)); + Royalty { + royalty_points_numerator, + royalty_points_denominator, + payee_address + } + } + + /// Deposit the token balance into the owner's account and emit an event. + public fun deposit_token(account: &signer, token: Token) acquires TokenStore { + let account_addr = signer::address_of(account); + initialize_token_store(account); + direct_deposit(account_addr, token) + } + + /// direct deposit if user opt in direct transfer + public fun direct_deposit_with_opt_in(account_addr: address, token: Token) acquires TokenStore { + let opt_in_transfer = borrow_global(account_addr).direct_transfer; + assert!(opt_in_transfer, error::permission_denied(EUSER_NOT_OPT_IN_DIRECT_TRANSFER)); + direct_deposit(account_addr, token); + } + + public fun direct_transfer( + sender: &signer, + receiver: &signer, + token_id: TokenId, + amount: u64, + ) acquires TokenStore { + let token = withdraw_token(sender, token_id, amount); + deposit_token(receiver, token); + } + + public fun initialize_token_store(account: &signer) { + if (!exists(signer::address_of(account))) { + move_to( + account, + TokenStore { + tokens: table::new(), + direct_transfer: false, + deposit_events: account::new_event_handle(account), + withdraw_events: account::new_event_handle(account), + burn_events: account::new_event_handle(account), + mutate_token_property_events: account::new_event_handle(account), + }, + ); + } + } + + public fun merge(dst_token: &mut Token, source_token: Token) { + assert!(&dst_token.id == &source_token.id, error::invalid_argument(EINVALID_TOKEN_MERGE)); + dst_token.amount = dst_token.amount + source_token.amount; + let Token { id: _, amount: _, token_properties: _ } = source_token; + } + + public fun split(dst_token: &mut Token, amount: u64): Token { + assert!(dst_token.id.property_version == 0, error::invalid_state(ENFT_NOT_SPLITABLE)); + assert!(dst_token.amount > amount, error::invalid_argument(ETOKEN_SPLIT_AMOUNT_LARGER_OR_EQUAL_TO_TOKEN_AMOUNT)); + assert!(amount > 0, error::invalid_argument(ETOKEN_CANNOT_HAVE_ZERO_AMOUNT)); + dst_token.amount = dst_token.amount - amount; + Token { + id: dst_token.id, + amount, + token_properties: property_map::empty(), + } + } + + public fun token_id(token: &Token): &TokenId { + &token.id + } + + /// Transfers `amount` of tokens from `from` to `to`. + public fun transfer( + from: &signer, + id: TokenId, + to: address, + amount: u64, + ) acquires TokenStore { + let opt_in_transfer = borrow_global(to).direct_transfer; + assert!(opt_in_transfer, error::permission_denied(EUSER_NOT_OPT_IN_DIRECT_TRANSFER)); + let token = withdraw_token(from, id, amount); + direct_deposit(to, token); + } + + + /// Token owner can create this one-time withdraw capability with an expiration time + public fun create_withdraw_capability( + owner: &signer, + token_id: TokenId, + amount: u64, + expiration_sec: u64, + ): WithdrawCapability { + WithdrawCapability { + token_owner: signer::address_of(owner), + token_id, + amount, + expiration_sec, + } + } + + /// Withdraw the token with a capability + public fun withdraw_with_capability( + withdraw_proof: WithdrawCapability, + ): Token acquires TokenStore { + // verify the delegation hasn't expired yet + assert!(timestamp::now_seconds() <= withdraw_proof.expiration_sec, error::invalid_argument(EWITHDRAW_PROOF_EXPIRES)); + + withdraw_with_event_internal( + withdraw_proof.token_owner, + withdraw_proof.token_id, + withdraw_proof.amount, + ) + } + + /// Withdraw the token with a capability. + public fun partial_withdraw_with_capability( + withdraw_proof: WithdrawCapability, + withdraw_amount: u64, + ): (Token, Option) acquires TokenStore { + // verify the delegation hasn't expired yet + assert!(timestamp::now_seconds() <= withdraw_proof.expiration_sec, error::invalid_argument(EWITHDRAW_PROOF_EXPIRES)); + + assert!(withdraw_amount <= withdraw_proof.amount, error::invalid_argument(EINSUFFICIENT_WITHDRAW_CAPABILITY_AMOUNT)); + + let res: Option = if (withdraw_amount == withdraw_proof.amount) { + option::none() + } else { + option::some( + WithdrawCapability { + token_owner: withdraw_proof.token_owner, + token_id: withdraw_proof.token_id, + amount: withdraw_proof.amount - withdraw_amount, + expiration_sec: withdraw_proof.expiration_sec, + } + ) + }; + + ( + withdraw_with_event_internal( + withdraw_proof.token_owner, + withdraw_proof.token_id, + withdraw_amount, + ), + res + ) + + } + + public fun withdraw_token( + account: &signer, + id: TokenId, + amount: u64, + ): Token acquires TokenStore { + let account_addr = signer::address_of(account); + withdraw_with_event_internal(account_addr, id, amount) + } + + /// Create a new collection to hold tokens + public fun create_collection( + creator: &signer, + name: String, + description: String, + uri: String, + maximum: u64, + mutate_setting: vector + ) acquires Collections { + assert!(string::length(&name) <= MAX_COLLECTION_NAME_LENGTH, error::invalid_argument(ECOLLECTION_NAME_TOO_LONG)); + assert!(string::length(&uri) <= MAX_URI_LENGTH, error::invalid_argument(EURI_TOO_LONG)); + let account_addr = signer::address_of(creator); + if (!exists(account_addr)) { + move_to( + creator, + Collections { + collection_data: table::new(), + token_data: table::new(), + create_collection_events: account::new_event_handle(creator), + create_token_data_events: account::new_event_handle(creator), + mint_token_events: account::new_event_handle(creator), + }, + ) + }; + + let collection_data = &mut borrow_global_mut(account_addr).collection_data; + + assert!( + !table::contains(collection_data, name), + error::already_exists(ECOLLECTION_ALREADY_EXISTS), + ); + + let mutability_config = create_collection_mutability_config(&mutate_setting); + let collection = CollectionData { + description, + name: name, + uri, + supply: 0, + maximum, + mutability_config + }; + + table::add(collection_data, name, collection); + let collection_handle = borrow_global_mut(account_addr); + event::emit_event( + &mut collection_handle.create_collection_events, + CreateCollectionEvent { + creator: account_addr, + collection_name: name, + uri, + description, + maximum, + } + ); + } + + public fun check_collection_exists(creator: address, name: String): bool acquires Collections { + assert!( + exists(creator), + error::not_found(ECOLLECTIONS_NOT_PUBLISHED), + ); + + let collection_data = &borrow_global(creator).collection_data; + table::contains(collection_data, name) + } + + public fun check_tokendata_exists(creator: address, collection_name: String, token_name: String): bool acquires Collections { + assert!( + exists(creator), + error::not_found(ECOLLECTIONS_NOT_PUBLISHED), + ); + + let token_data = &borrow_global(creator).token_data; + let token_data_id = create_token_data_id(creator, collection_name, token_name); + table::contains(token_data, token_data_id) + } + + public fun create_tokendata( + account: &signer, + collection: String, + name: String, + description: String, + maximum: u64, + uri: String, + royalty_payee_address: address, + royalty_points_denominator: u64, + royalty_points_numerator: u64, + token_mutate_config: TokenMutabilityConfig, + property_keys: vector, + property_values: vector>, + property_types: vector + ): TokenDataId acquires Collections { + assert!(string::length(&name) <= MAX_NFT_NAME_LENGTH, error::invalid_argument(ENFT_NAME_TOO_LONG)); + assert!(string::length(&collection) <= MAX_COLLECTION_NAME_LENGTH, error::invalid_argument(ECOLLECTION_NAME_TOO_LONG)); + assert!(string::length(&uri) <= MAX_URI_LENGTH, error::invalid_argument(EURI_TOO_LONG)); + assert!(royalty_points_numerator <= royalty_points_denominator, error::invalid_argument(EINVALID_ROYALTY_NUMERATOR_DENOMINATOR)); + + let account_addr = signer::address_of(account); + assert!( + exists(account_addr), + error::not_found(ECOLLECTIONS_NOT_PUBLISHED), + ); + let collections = borrow_global_mut(account_addr); + + let token_data_id = create_token_data_id(account_addr, collection, name); + + assert!( + table::contains(&collections.collection_data, token_data_id.collection), + error::not_found(ECOLLECTION_NOT_PUBLISHED), + ); + assert!( + !table::contains(&collections.token_data, token_data_id), + error::already_exists(ETOKEN_DATA_ALREADY_EXISTS), + ); + + let collection = table::borrow_mut(&mut collections.collection_data, token_data_id.collection); + + // if collection maximum == 0, user don't want to enforce supply constraint. + // we don't track supply to make token creation parallelizable + if (collection.maximum > 0) { + collection.supply = collection.supply + 1; + assert!( + collection.maximum >= collection.supply, + error::invalid_argument(ECREATE_WOULD_EXCEED_COLLECTION_MAXIMUM), + ); + }; + + let token_data = TokenData { + maximum, + largest_property_version: 0, + supply: 0, + uri, + royalty: create_royalty(royalty_points_numerator, royalty_points_denominator, royalty_payee_address), + name, + description, + default_properties: property_map::new(property_keys, property_values, property_types), + mutability_config: token_mutate_config, + }; + + table::add(&mut collections.token_data, token_data_id, token_data); + + event::emit_event( + &mut collections.create_token_data_events, + CreateTokenDataEvent { + id: token_data_id, + description, + maximum, + uri, + royalty_payee_address, + royalty_points_denominator, + royalty_points_numerator, + name, + mutability_config: token_mutate_config, + property_keys, + property_values, + property_types, + }, + ); + token_data_id + } + + /// return the number of distinct token_data_id created under this collection + public fun get_collection_supply(creator_address: address, collection_name: String): Option acquires Collections { + assert_collection_exists(creator_address, collection_name); + let collection_data = table::borrow_mut(&mut borrow_global_mut(creator_address).collection_data, collection_name); + + if (collection_data.maximum > 0) { + option::some(collection_data.supply) + } else { + option::none() + } + } + + public fun get_collection_description(creator_address: address, collection_name: String): String acquires Collections { + assert_collection_exists(creator_address, collection_name); + let collection_data = table::borrow_mut(&mut borrow_global_mut(creator_address).collection_data, collection_name); + collection_data.description + } + + public fun get_collection_uri(creator_address: address, collection_name: String): String acquires Collections { + assert_collection_exists(creator_address, collection_name); + let collection_data = table::borrow_mut(&mut borrow_global_mut(creator_address).collection_data, collection_name); + collection_data.uri + } + + public fun get_collection_maximum(creator_address: address, collection_name: String): u64 acquires Collections { + assert_collection_exists(creator_address, collection_name); + let collection_data = table::borrow_mut(&mut borrow_global_mut(creator_address).collection_data, collection_name); + collection_data.maximum + } + + /// return the number of distinct token_id created under this TokenData + public fun get_token_supply(creator_address: address, token_data_id: TokenDataId): Option acquires Collections { + assert!(exists(creator_address), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &borrow_global(creator_address).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + let token_data = table::borrow(all_token_data, token_data_id); + + if (token_data.maximum > 0) { + option::some(token_data.supply) + } else { + option::none() + } + } + + /// return the largest_property_version of this TokenData + public fun get_tokendata_largest_property_version(creator_address: address, token_data_id: TokenDataId): u64 acquires Collections { + assert!(exists(creator_address), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &borrow_global(creator_address).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + table::borrow(all_token_data, token_data_id).largest_property_version + } + + /// return the TokenId for a given Token + public fun get_token_id(token: &Token): TokenId { + token.id + } + + public fun get_direct_transfer(receiver: address): bool acquires TokenStore { + if (!exists(receiver)) { + return false + }; + + borrow_global(receiver).direct_transfer + } + + public fun create_token_mutability_config(mutate_setting: &vector): TokenMutabilityConfig { + TokenMutabilityConfig { + maximum: *vector::borrow(mutate_setting, TOKEN_MAX_MUTABLE_IND), + uri: *vector::borrow(mutate_setting, TOKEN_URI_MUTABLE_IND), + royalty: *vector::borrow(mutate_setting, TOKEN_ROYALTY_MUTABLE_IND), + description: *vector::borrow(mutate_setting, TOKEN_DESCRIPTION_MUTABLE_IND), + properties: *vector::borrow(mutate_setting, TOKEN_PROPERTY_MUTABLE_IND), + } + } + + public fun create_collection_mutability_config(mutate_setting: &vector): CollectionMutabilityConfig { + CollectionMutabilityConfig { + description: *vector::borrow(mutate_setting, COLLECTION_DESCRIPTION_MUTABLE_IND), + uri: *vector::borrow(mutate_setting, COLLECTION_URI_MUTABLE_IND), + maximum: *vector::borrow(mutate_setting, COLLECTION_MAX_MUTABLE_IND), + } + } + + public fun mint_token( + account: &signer, + token_data_id: TokenDataId, + amount: u64, + ): TokenId acquires Collections, TokenStore { + assert!(token_data_id.creator == signer::address_of(account), error::permission_denied(ENO_MINT_CAPABILITY)); + let creator_addr = token_data_id.creator; + let all_token_data = &mut borrow_global_mut(creator_addr).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + let token_data = table::borrow_mut(all_token_data, token_data_id); + + if (token_data.maximum > 0) { + assert!(token_data.supply + amount <= token_data.maximum, error::invalid_argument(EMINT_WOULD_EXCEED_TOKEN_MAXIMUM)); + token_data.supply = token_data.supply + amount; + }; + + // we add more tokens with property_version 0 + let token_id = create_token_id(token_data_id, 0); + event::emit_event( + &mut borrow_global_mut(creator_addr).mint_token_events, + MintTokenEvent { + id: token_data_id, + amount, + } + ); + + deposit_token(account, + Token { + id: token_id, + amount, + token_properties: property_map::empty(), // same as default properties no need to store + } + ); + + token_id + } + + /// create tokens and directly deposite to receiver's address. The receiver should opt-in direct transfer + public fun mint_token_to( + account: &signer, + receiver: address, + token_data_id: TokenDataId, + amount: u64, + ) acquires Collections, TokenStore { + assert!(exists(receiver), error::not_found(ETOKEN_STORE_NOT_PUBLISHED)); + let opt_in_transfer = borrow_global(receiver).direct_transfer; + assert!(opt_in_transfer, error::permission_denied(EUSER_NOT_OPT_IN_DIRECT_TRANSFER)); + + assert!(token_data_id.creator == signer::address_of(account), error::permission_denied(ENO_MINT_CAPABILITY)); + let creator_addr = token_data_id.creator; + let all_token_data = &mut borrow_global_mut(creator_addr).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + let token_data = table::borrow_mut(all_token_data, token_data_id); + + if (token_data.maximum > 0) { + assert!(token_data.supply + amount <= token_data.maximum, error::invalid_argument(EMINT_WOULD_EXCEED_TOKEN_MAXIMUM)); + token_data.supply = token_data.supply + amount; + }; + + // we add more tokens with property_version 0 + let token_id = create_token_id(token_data_id, 0); + + event::emit_event( + &mut borrow_global_mut(creator_addr).mint_token_events, + MintTokenEvent { + id: token_data_id, + amount, + } + ); + + direct_deposit(receiver, + Token { + id: token_id, + amount, + token_properties: property_map::empty(), // same as default properties no need to store + } + ); + } + + public fun create_token_id(token_data_id: TokenDataId, property_version: u64): TokenId { + TokenId { + token_data_id, + property_version, + } + } + + public fun create_token_data_id( + creator: address, + collection: String, + name: String, + ): TokenDataId { + assert!(string::length(&collection) <= MAX_COLLECTION_NAME_LENGTH, error::invalid_argument(ECOLLECTION_NAME_TOO_LONG)); + assert!(string::length(&name) <= MAX_NFT_NAME_LENGTH, error::invalid_argument(ENFT_NAME_TOO_LONG)); + TokenDataId { creator, collection, name } + } + + public fun create_token_id_raw( + creator: address, + collection: String, + name: String, + property_version: u64, + ): TokenId { + TokenId { + token_data_id: create_token_data_id(creator, collection, name), + property_version, + } + } + + public fun balance_of(owner: address, id: TokenId): u64 acquires TokenStore { + if (!exists(owner)) { + return 0 + }; + let token_store = borrow_global(owner); + if (table::contains(&token_store.tokens, id)) { + table::borrow(&token_store.tokens, id).amount + } else { + 0 + } + } + + public fun has_token_store(owner: address): bool { + exists(owner) + } + + public fun get_royalty(token_id: TokenId): Royalty acquires Collections { + let token_data_id = token_id.token_data_id; + get_tokendata_royalty(token_data_id) + } + + public fun get_royalty_numerator(royalty: &Royalty): u64 { + royalty.royalty_points_numerator + } + + public fun get_royalty_denominator(royalty: &Royalty): u64 { + royalty.royalty_points_denominator + } + + public fun get_royalty_payee(royalty: &Royalty): address { + royalty.payee_address + } + + public fun get_token_amount(token: &Token): u64 { + token.amount + } + + /// return the creator address, collection name, token name and property_version + public fun get_token_id_fields(token_id: &TokenId): (address, String, String, u64) { + ( + token_id.token_data_id.creator, + token_id.token_data_id.collection, + token_id.token_data_id.name, + token_id.property_version, + ) + } + + public fun get_token_data_id_fields(token_data_id: &TokenDataId): (address, String, String) { + ( + token_data_id.creator, + token_data_id.collection, + token_data_id.name, + ) + } + + /// return a copy of the token property map. + /// if property_version = 0, return the default property map + /// if property_version > 0, return the property value stored at owner's token store + public fun get_property_map(owner: address, token_id: TokenId): PropertyMap acquires Collections, TokenStore { + assert!(balance_of(owner, token_id) > 0, error::not_found(EINSUFFICIENT_BALANCE)); + // if property_version = 0, return default property map + if (token_id.property_version == 0) { + let creator_addr = token_id.token_data_id.creator; + let all_token_data = &borrow_global(creator_addr).token_data; + assert!(table::contains(all_token_data, token_id.token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + let token_data = table::borrow(all_token_data, token_id.token_data_id); + token_data.default_properties + } else { + let tokens = &borrow_global(owner).tokens; + table::borrow(tokens, token_id).token_properties + } + } + + public fun get_tokendata_maximum(token_data_id: TokenDataId): u64 acquires Collections { + let creator_address = token_data_id.creator; + assert!(exists(creator_address), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &borrow_global(creator_address).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + + let token_data = table::borrow(all_token_data, token_data_id); + token_data.maximum + } + + public fun get_tokendata_uri(creator: address, token_data_id: TokenDataId): String acquires Collections { + assert!(exists(creator), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &borrow_global(creator).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + + let token_data = table::borrow(all_token_data, token_data_id); + token_data.uri + } + + public fun get_tokendata_description(token_data_id: TokenDataId): String acquires Collections { + let creator_address = token_data_id.creator; + assert!(exists(creator_address), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &borrow_global(creator_address).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + + let token_data = table::borrow(all_token_data, token_data_id); + token_data.description + } + + public fun get_tokendata_royalty(token_data_id: TokenDataId): Royalty acquires Collections { + let creator_address = token_data_id.creator; + assert!(exists(creator_address), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &borrow_global(creator_address).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + + let token_data = table::borrow(all_token_data, token_data_id); + token_data.royalty + } + + /// return the token_data_id from the token_id + public fun get_tokendata_id(token_id: TokenId): TokenDataId { + token_id.token_data_id + } + + /// return the mutation setting of the token + public fun get_tokendata_mutability_config(token_data_id: TokenDataId): TokenMutabilityConfig acquires Collections { + let creator_addr = token_data_id.creator; + assert!(exists(creator_addr), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &borrow_global(creator_addr).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + table::borrow(all_token_data, token_data_id).mutability_config + } + + /// return if the token's maximum is mutable + public fun get_token_mutability_maximum(config: &TokenMutabilityConfig): bool { + config.maximum + } + + /// return if the token royalty is mutable with a token mutability config + public fun get_token_mutability_royalty(config: &TokenMutabilityConfig): bool { + config.royalty + } + + /// return if the token uri is mutable with a token mutability config + public fun get_token_mutability_uri(config: &TokenMutabilityConfig): bool { + config.uri + } + + /// return if the token description is mutable with a token mutability config + public fun get_token_mutability_description(config: &TokenMutabilityConfig): bool { + config.description + } + + /// return if the tokendata's default properties is mutable with a token mutability config + public fun get_token_mutability_default_properties(config: &TokenMutabilityConfig): bool { + config.properties + } + + #[view] + /// return the collection mutation setting + public fun get_collection_mutability_config( + creator: address, + collection_name: String + ): CollectionMutabilityConfig acquires Collections { + assert!(exists(creator), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_collection_data = &borrow_global(creator).collection_data; + assert!(table::contains(all_collection_data, collection_name), error::not_found(ECOLLECTION_NOT_PUBLISHED)); + table::borrow(all_collection_data, collection_name).mutability_config + } + + /// return if the collection description is mutable with a collection mutability config + public fun get_collection_mutability_description(config: &CollectionMutabilityConfig): bool { + config.description + } + + /// return if the collection uri is mutable with a collection mutability config + public fun get_collection_mutability_uri(config: &CollectionMutabilityConfig): bool { + config.uri + } + /// return if the collection maximum is mutable with collection mutability config + public fun get_collection_mutability_maximum(config: &CollectionMutabilityConfig): bool { + config.maximum + } + + // + // Private functions + // + fun destroy_token_data(token_data: TokenData) { + let TokenData { + maximum: _, + largest_property_version: _, + supply: _, + uri: _, + royalty: _, + name: _, + description: _, + default_properties: _, + mutability_config: _, + } = token_data; + } + + fun destroy_collection_data(collection_data: CollectionData) { + let CollectionData { + description: _, + name: _, + uri: _, + supply: _, + maximum: _, + mutability_config: _, + } = collection_data; + } + + fun withdraw_with_event_internal( + account_addr: address, + id: TokenId, + amount: u64, + ): Token acquires TokenStore { + // It does not make sense to withdraw 0 tokens. + assert!(amount > 0, error::invalid_argument(EWITHDRAW_ZERO)); + // Make sure the account has sufficient tokens to withdraw. + assert!(balance_of(account_addr, id) >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE)); + + assert!( + exists(account_addr), + error::not_found(ETOKEN_STORE_NOT_PUBLISHED), + ); + + let token_store = borrow_global_mut(account_addr); + event::emit_event( + &mut token_store.withdraw_events, + WithdrawEvent { id, amount }, + ); + let tokens = &mut borrow_global_mut(account_addr).tokens; + assert!( + table::contains(tokens, id), + error::not_found(ENO_TOKEN_IN_TOKEN_STORE), + ); + // balance > amount and amount > 0 indirectly asserted that balance > 0. + let balance = &mut table::borrow_mut(tokens, id).amount; + if (*balance > amount) { + *balance = *balance - amount; + Token { id, amount, token_properties: property_map::empty() } + } else { + table::remove(tokens, id) + } + } + + fun update_token_property_internal( + token_owner: address, + token_id: TokenId, + keys: vector, + values: vector>, + types: vector, + ) acquires TokenStore { + let tokens = &mut borrow_global_mut(token_owner).tokens; + assert!(table::contains(tokens, token_id), error::not_found(ENO_TOKEN_IN_TOKEN_STORE)); + + let value = &mut table::borrow_mut(tokens, token_id).token_properties; + assert_non_standard_reserved_property(&keys); + property_map::update_property_map(value, keys, values, types); + } + + /// Deposit the token balance into the recipients account and emit an event. + fun direct_deposit(account_addr: address, token: Token) acquires TokenStore { + assert!(token.amount > 0, error::invalid_argument(ETOKEN_CANNOT_HAVE_ZERO_AMOUNT)); + let token_store = borrow_global_mut(account_addr); + + event::emit_event( + &mut token_store.deposit_events, + DepositEvent { id: token.id, amount: token.amount }, + ); + + assert!( + exists(account_addr), + error::not_found(ETOKEN_STORE_NOT_PUBLISHED), + ); + + if (!table::contains(&token_store.tokens, token.id)) { + table::add(&mut token_store.tokens, token.id, token); + } else { + let recipient_token = table::borrow_mut(&mut token_store.tokens, token.id); + merge(recipient_token, token); + }; + } + + fun assert_collection_exists(creator_address: address, collection_name: String) acquires Collections { + assert!(exists(creator_address), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_collection_data = &borrow_global(creator_address).collection_data; + assert!(table::contains(all_collection_data, collection_name), error::not_found(ECOLLECTION_NOT_PUBLISHED)); + } + + fun assert_tokendata_exists(creator: &signer, token_data_id: TokenDataId) acquires Collections { + let creator_addr = token_data_id.creator; + assert!(signer::address_of(creator) == creator_addr, error::permission_denied(ENO_MUTATE_CAPABILITY)); + assert!(exists(creator_addr), error::not_found(ECOLLECTIONS_NOT_PUBLISHED)); + let all_token_data = &mut borrow_global_mut(creator_addr).token_data; + assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED)); + } + + fun assert_non_standard_reserved_property(keys: &vector) { + vector::for_each_ref(keys, |key| { + let key: &String = key; + let length = string::length(key); + if (length >= 6) { + let prefix = string::sub_string(&*key, 0, 6); + assert!(prefix != string::utf8(b"TOKEN_"), error::permission_denied(EPROPERTY_RESERVED_BY_STANDARD)); + }; + }); + } + + // ****************** TEST-ONLY FUNCTIONS ************** + + #[test(creator = @0x1, owner = @0x2)] + public fun create_withdraw_deposit_token( + creator: signer, + owner: signer + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(&creator)); + account::create_account_for_test(signer::address_of(&owner)); + let token_id = create_collection_and_token( + &creator, + 1, + 1, + 1, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + + let token = withdraw_token(&creator, token_id, 1); + deposit_token(&owner, token); + } + + #[test(creator = @0xCC, owner = @0xCB)] + public fun create_withdraw_deposit( + creator: signer, + owner: signer + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(&creator)); + account::create_account_for_test(signer::address_of(&owner)); + let token_id = create_collection_and_token( + &creator, + 2, + 5, + 5, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + + let token_0 = withdraw_token(&creator, token_id, 1); + let token_1 = withdraw_token(&creator, token_id, 1); + deposit_token(&owner, token_0); + deposit_token(&creator, token_1); + let token_2 = withdraw_token(&creator, token_id, 1); + deposit_token(&owner, token_2); + } + + #[test(creator = @0x1)] + #[expected_failure] + public entry fun test_collection_maximum(creator: signer) acquires Collections, TokenStore { + use std::bcs; + account::create_account_for_test(signer::address_of(&creator)); + let token_id = create_collection_and_token( + &creator, + 2, + 2, + 1, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + let default_keys = vector[ string::utf8(b"attack"), string::utf8(b"num_of_use") ]; + let default_vals = vector>[ bcs::to_bytes(&10), bcs::to_bytes(&5) ]; + let default_types = vector[ string::utf8(b"u64"), string::utf8(b"u64") ]; + let mutate_setting = vector[ false, false, false, false, false, false ]; + create_token_script( + &creator, + token_id.token_data_id.collection, + string::utf8(b"Token"), + string::utf8(b"Hello, Token"), + 100, + 2, + string::utf8(b"https://aptos.dev"), + signer::address_of(&creator), + 100, + 0, + mutate_setting, + default_keys, + default_vals, + default_types, + ); + } + + #[test(creator = @0xFA, owner = @0xAF)] + public entry fun direct_transfer_test( + creator: signer, + owner: signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(&creator)); + account::create_account_for_test(signer::address_of(&owner)); + let token_id = create_collection_and_token( + &creator, + 2, + 2, + 2, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + assert!(balance_of(signer::address_of(&owner), token_id) == 0, 1); + + direct_transfer(&creator, &owner, token_id, 1); + let token = withdraw_token(&owner, token_id, 1); + deposit_token(&creator, token); + } + + #[test_only] + public fun get_collection_name(): String { + use std::string; + string::utf8(b"Hello, World") + } + + #[test_only] + public fun get_token_name(): String { + use std::string; + string::utf8(b"Token") + } + + #[test_only] + public entry fun create_collection_and_token( + creator: &signer, + amount: u64, + collection_max: u64, + token_max: u64, + property_keys: vector, + property_values: vector>, + property_types: vector, + collection_mutate_setting: vector, + token_mutate_setting: vector, + ): TokenId acquires Collections, TokenStore { + use std::string; + use std::bcs; + let mutate_setting = collection_mutate_setting; + + create_collection( + creator, + get_collection_name(), + string::utf8(b"Collection: Hello, World"), + string::utf8(b"https://aptos.dev"), + collection_max, + mutate_setting + ); + + let default_keys = if (vector::length(&property_keys) == 0) { vector[string::utf8(b"attack"), string::utf8(b"num_of_use")] } else { property_keys }; + let default_vals = if (vector::length>(&property_values) == 0) { vector>[bcs::to_bytes(&10), bcs::to_bytes(&5)] } else { property_values }; + let default_types = if (vector::length(&property_types) == 0) { vector[string::utf8(b"u64"), string::utf8(b"u64")] } else { property_types }; + let mutate_setting = token_mutate_setting; + create_token_script( + creator, + get_collection_name(), + get_token_name(), + string::utf8(b"Hello, Token"), + amount, + token_max, + string::utf8(b"https://aptos.dev"), + signer::address_of(creator), + 100, + 0, + mutate_setting, + default_keys, + default_vals, + default_types, + ); + create_token_id_raw(signer::address_of(creator), get_collection_name(), get_token_name(), 0) + } + + #[test(creator = @0xFF)] + fun test_create_events_generation(creator: signer) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(&creator)); + create_collection_and_token( + &creator, + 1, + 2, + 1, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + let collections = borrow_global(signer::address_of(&creator)); + assert!(event::counter(&collections.create_collection_events) == 1, 1); + } + + #[test(creator = @0xAF)] + fun test_mint_token_from_tokendata(creator: &signer) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + + create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + let token_data_id = create_token_data_id( + signer::address_of(creator), + get_collection_name(), + get_token_name()); + + let token_id = mint_token( + creator, + token_data_id, + 1, + ); + + assert!(balance_of(signer::address_of(creator), token_id) == 3, 1); + } + + #[test(creator = @0xAF, owner = @0xBB)] + fun test_mutate_token_property_upsert(creator: &signer) acquires Collections, TokenStore { + use std::bcs; + account::create_account_for_test(signer::address_of(creator)); + + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[string::utf8(TOKEN_PROPERTY_MUTABLE)], + vector>[bcs::to_bytes(&true)], + vector[string::utf8(b"bool")], + vector[false, false, false], + vector[false, false, false, false, false], + ); + assert!(token_id.property_version == 0, 1); + // only be able to mutate the attributed defined when creating the token + let new_keys = vector[ + string::utf8(b"attack"), string::utf8(b"num_of_use"), string::utf8(b"new_attribute") + ]; + let new_vals = vector>[ + bcs::to_bytes(&1), bcs::to_bytes(&1), bcs::to_bytes(&1) + ]; + let new_types = vector[ + string::utf8(b"u64"), string::utf8(b"u64"), string::utf8(b"u64") + ]; + + mutate_token_properties( + creator, + token_id.token_data_id.creator, + token_id.token_data_id.creator, + token_id.token_data_id.collection, + token_id.token_data_id.name, + token_id.property_version, + 2, + new_keys, + new_vals, + new_types, + ); + } + + #[test(creator = @0xAF, owner = @0xBB)] + fun test_get_property_map_should_not_update_source_value(creator: &signer) acquires Collections, TokenStore { + use std::bcs; + account::create_account_for_test(signer::address_of(creator)); + + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, true], + ); + assert!(token_id.property_version == 0, 1); + // only be able to mutate the attributed defined when creating the token + let new_keys = vector[ + string::utf8(b"attack"), string::utf8(b"num_of_use") + ]; + let new_vals = vector>[ + bcs::to_bytes(&1), bcs::to_bytes(&1) + ]; + let new_types = vector[ + string::utf8(b"u64"), string::utf8(b"u64") + ]; + let pm = get_property_map(signer::address_of(creator), token_id); + assert!(property_map::length(&pm) == 2, 1); + let new_token_id = mutate_one_token( + creator, + signer::address_of(creator), + token_id, + new_keys, + new_vals, + new_types, + ); + let updated_pm = get_property_map(signer::address_of(creator), new_token_id); + assert!(property_map::length(&updated_pm) == 2, 1); + property_map::update_property_value( + &mut updated_pm, + &string::utf8(b"attack"), + property_map::create_property_value(&2), + ); + + assert!(property_map::read_u64(&updated_pm, &string::utf8(b"attack")) == 2, 1); + let og_pm = get_property_map(signer::address_of(creator), new_token_id); + assert!(property_map::read_u64(&og_pm, &string::utf8(b"attack")) == 1, 1); + } + + #[test(framework = @0x1, creator = @0xcafe)] + fun test_withdraw_with_proof(creator: &signer, framework: &signer): Token acquires TokenStore, Collections { + timestamp::set_time_has_started_for_testing(framework); + account::create_account_for_test(signer::address_of(creator)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + + timestamp::update_global_time_for_test(1000000); + + // provide the proof to the account + let cap = create_withdraw_capability( + creator, // ask user to provide address to avoid ambiguity from rotated keys + token_id, + 1, + 2000000, + ); + + withdraw_with_capability(cap) + } + + #[test(creator = @0xcafe, another_creator = @0xde)] + fun test_burn_token_from_both_limited_and_unlimited( + creator: &signer, + another_creator: &signer, + )acquires Collections, TokenStore { + // create limited token and collection + use std::bcs; + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(another_creator)); + + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[string::utf8(BURNABLE_BY_CREATOR)], + vector>[bcs::to_bytes(&true)], + vector[string::utf8(b"bool")], + vector[false, false, false], + vector[false, false, false, false, false], + ); + // burn token from limited token + let creator_addr = signer::address_of(creator); + let pre_amount = &mut get_token_supply(creator_addr, token_id.token_data_id); + burn_by_creator(creator, creator_addr, get_collection_name(), get_token_name(), 0, 1); + let aft_amount = &mut get_token_supply(creator_addr, token_id.token_data_id); + assert!((option::extract(pre_amount) - option::extract(aft_amount)) == 1, 1); + + // create unlimited token and collection + let new_addr = signer::address_of(another_creator); + let new_token_id = create_collection_and_token( + another_creator, + 2, + 0, + 0, + vector[string::utf8(BURNABLE_BY_OWNER)], + vector>[bcs::to_bytes(&true)], + vector[string::utf8(b"bool")], + vector[false, false, false], + vector[false, false, false, false, false], + ); + let pre = balance_of(new_addr, new_token_id); + // burn token from unlimited token and collection + burn(another_creator, new_addr, get_collection_name(), get_token_name(), 0, 1); + let aft = balance_of(new_addr, new_token_id); + assert!(pre - aft == 1, 1); + } + + #[test(creator = @0xcafe, owner = @0xafe)] + fun test_mint_token_to_different_address( + creator: &signer, + owner: &signer, + )acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(owner)); + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + let owner_addr = signer::address_of(owner); + opt_in_direct_transfer(owner, true); + mint_token_to(creator, owner_addr, token_id.token_data_id, 1); + assert!(balance_of(owner_addr, token_id) == 1, 1); + } + + #[test(creator = @0xcafe, owner = @0xafe)] + #[expected_failure(abort_code = 327696, location = Self)] + fun test_opt_in_direct_transfer_fail( + creator: &signer, + owner: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(owner)); + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + let owner_addr = signer::address_of(owner); + initialize_token_store(owner); + transfer(creator, token_id, owner_addr, 1); + } + + #[test(creator = @0xcafe, owner = @0xafe)] + #[expected_failure(abort_code = 327696, location = Self)] + fun test_opt_in_direct_deposit_fail( + creator: &signer, + owner: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(owner)); + + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + let owner_addr = signer::address_of(owner); + let token = withdraw_token(creator, token_id, 2); + initialize_token_store(owner); + direct_deposit_with_opt_in(owner_addr, token); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + opt_in_direct_transfer(owner, true); + initialize_token_store(owner); + transfer(creator, token_id, signer::address_of(owner), 2); + burn_by_creator(creator, signer::address_of(owner), get_collection_name(), get_token_name(), 0, 1); + } + + #[test(creator = @0xcafe, owner = @0x456)] + #[expected_failure(abort_code = 327710, location = Self)] + fun test_burn_token_by_owner_without_burnable_config( + creator: &signer, + owner: &signer, + )acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(owner)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + + opt_in_direct_transfer(owner, true); + initialize_token_store(owner); + transfer(creator, token_id, signer::address_of(owner), 2); + + burn(owner, signer::address_of(creator), get_collection_name(), get_token_name(), 0, 1); + } + + #[test(creator = @0xcafe, owner = @0x456)] + fun test_burn_token_by_owner_and_creator( + creator: &signer, + owner: &signer, + ) acquires TokenStore, Collections { + use std::bcs; + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(owner)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[string::utf8(BURNABLE_BY_CREATOR), string::utf8(BURNABLE_BY_OWNER)], + vector>[bcs::to_bytes(&true), bcs::to_bytes(&true)], + vector[string::utf8(b"bool"), string::utf8(b"bool")], + vector[false, false, false], + vector[false, false, false, false, false], + ); + opt_in_direct_transfer(owner, true); + initialize_token_store(owner); + transfer(creator, token_id, signer::address_of(owner), 2); + burn_by_creator(creator, signer::address_of(owner), get_collection_name(), get_token_name(), 0, 1); + burn(owner, signer::address_of(creator), get_collection_name(), get_token_name(), 0, 1); + assert!(balance_of(signer::address_of(owner), token_id) == 0, 1); + + // The corresponding token_data and collection_data should be deleted + let collections = borrow_global(signer::address_of(creator)); + assert!(!table::contains(&collections.collection_data, token_id.token_data_id.name), 1); + assert!(!table::contains(&collections.token_data, token_id.token_data_id), 1); + } + + #[test(creator = @0xcafe)] + fun test_mutate_collection_description( + creator: &signer, + ) acquires Collections, TokenStore { + let creator_address = signer::address_of(creator); + account::create_account_for_test(creator_address); + create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[true, false, false], + vector[false, false, false, false, false], + ); + + let description = string::utf8(b"test"); + let collection_name = get_collection_name(); + mutate_collection_description(creator, collection_name, description); + assert!(get_collection_description(creator_address, collection_name) == description, 1); + } + + #[test(creator = @0xcafe)] + fun test_mutate_collection_uri( + creator: &signer, + ) acquires Collections, TokenStore { + let creator_address = signer::address_of(creator); + account::create_account_for_test(creator_address); + create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, true, false], + vector[false, false, false, false, false], + ); + + let uri = string::utf8(b""); + let collection_name = get_collection_name(); + mutate_collection_uri(creator, collection_name, uri); + assert!(get_collection_uri(creator_address, collection_name) == uri, 1); + } + + #[test(creator = @0xcafe)] + fun test_mutate_collection_maximum( + creator: &signer, + ) acquires Collections, TokenStore { + let creator_address = signer::address_of(creator); + account::create_account_for_test(creator_address); + create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, true], + vector[false, false, false, false, false], + ); + + let collection_name = get_collection_name(); + mutate_collection_maximum(creator, collection_name, 10); + assert!(get_collection_maximum(creator_address, collection_name) == 10, 1); + } + + #[test(creator = @0xcafe, owner = @0x456)] + fun test_mutate_default_token_properties( + creator: &signer, + ) acquires Collections, TokenStore { + use std::bcs; + account::create_account_for_test(signer::address_of(creator)); + + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, true], + ); + assert!(token_id.property_version == 0, 1); + let new_keys = vector[ + string::utf8(b"attack"), string::utf8(b"num_of_use") + ]; + let new_vals = vector>[ + bcs::to_bytes(&1), bcs::to_bytes(&1) + ]; + let new_types = vector[ + string::utf8(b"u64"), string::utf8(b"u64") + ]; + + mutate_tokendata_property( + creator, + token_id.token_data_id, + new_keys, + new_vals, + new_types, + ); + + let all_token_data = &borrow_global(signer::address_of(creator)).token_data; + assert!(table::contains(all_token_data, token_id.token_data_id), 1); + let props = &table::borrow(all_token_data, token_id.token_data_id).default_properties; + assert!(property_map::read_u64(props, &string::utf8(b"attack")) == 1, 1); + } + + #[test(creator = @0xcafe)] + fun test_mutate_tokendata_maximum( + creator: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[true, false, false, false, false], + ); + mutate_tokendata_maximum(creator, token_id.token_data_id, 10); + assert!(get_tokendata_maximum(token_id.token_data_id) == 10, 1); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 65572, location = Self)] + fun test_mutate_tokendata_maximum_from_zero( + creator: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[true, false, false, false, false], + ); + mutate_tokendata_maximum(creator, token_id.token_data_id, 0); + } + + #[test(creator = @0xcafe)] + fun test_mutate_tokendata_uri( + creator: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, true, false, false, false], + ); + mutate_tokendata_uri(creator, token_id.token_data_id, string::utf8(b"")); + assert!(get_tokendata_uri(signer::address_of(creator), token_id.token_data_id) == string::utf8(b""), 1); + } + + #[test(creator = @0xcafe)] + fun test_mutate_tokendata_royalty( + creator: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, true, false, false], + ); + + let royalty = create_royalty(1, 3, signer::address_of(creator)); + mutate_tokendata_royalty(creator, token_id.token_data_id, royalty); + assert!(get_tokendata_royalty(token_id.token_data_id) == royalty, 1); + } + + #[test(creator = @0xcafe)] + fun test_mutate_tokendata_description( + creator: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, true, false], + ); + + let description = string::utf8(b"test"); + mutate_tokendata_description(creator, token_id.token_data_id, description); + assert!(get_tokendata_description(token_id.token_data_id) == description, 1); + } + + #[test(creator = @0xAF, owner = @0xBB)] + fun test_mutate_token_property(creator: &signer, owner: &signer) acquires Collections, TokenStore { + use std::bcs; + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(owner)); + + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, true], + ); + assert!(token_id.property_version == 0, 1); + let new_keys = vector[ + string::utf8(b"attack"), string::utf8(b"num_of_use") + ]; + let new_vals = vector>[ + bcs::to_bytes(&1), bcs::to_bytes(&1) + ]; + let new_types = vector[ + string::utf8(b"u64"), string::utf8(b"u64") + ]; + + mutate_token_properties( + creator, + token_id.token_data_id.creator, + token_id.token_data_id.creator, + token_id.token_data_id.collection, + token_id.token_data_id.name, + token_id.property_version, + 2, + new_keys, + new_vals, + new_types, + ); + + // should have two new property_version from the orignal two tokens + let largest_property_version = get_tokendata_largest_property_version(signer::address_of(creator), token_id.token_data_id); + assert!(largest_property_version == 2, largest_property_version); + + let new_id_1 = create_token_id(token_id.token_data_id, 1); + let new_id_2 = create_token_id(token_id.token_data_id, 2); + let new_id_3 = create_token_id(token_id.token_data_id, 3); + + assert!(balance_of(signer::address_of(creator), new_id_1) == 1, 1); + assert!(balance_of(signer::address_of(creator), new_id_2) == 1, 1); + assert!(balance_of(signer::address_of(creator), token_id) == 0, 1); + + let creator_props = &borrow_global(signer::address_of(creator)).tokens; + let token = table::borrow(creator_props, new_id_1); + + assert!(property_map::length(&token.token_properties) == 2, property_map::length(&token.token_properties)); + // mutate token with property_version > 0 should not generate new property_version + mutate_token_properties( + creator, + signer::address_of(creator), + new_id_1.token_data_id.creator, + new_id_1.token_data_id.collection, + new_id_1.token_data_id.name, + new_id_1.property_version, + 1, + new_keys, + new_vals, + new_types + ); + assert!(balance_of(signer::address_of(creator), new_id_3) == 0, 1); + // transfer token with property_version > 0 also transfer the token properties + direct_transfer(creator, owner, new_id_1, 1); + + let props = &borrow_global(signer::address_of(owner)).tokens; + assert!(table::contains(props, new_id_1), 1); + let token = table::borrow(props, new_id_1); + assert!(property_map::length(&token.token_properties) == 2, property_map::length(&token.token_properties)); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 65569, location = Self)] + fun test_no_zero_balance_token_deposit( + creator: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + // token owner mutate the token property + create_collection_and_token( + creator, + 0, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, true, false, false, false], + ); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 65548, location = Self)] + fun test_split_out_zero_token( + creator: &signer, + ) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 1, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, true, false, false, false], + ); + let token = withdraw_token(creator, token_id, 1); + let split_token = split(&mut token, 1); + let Token { + id: _, + amount: _, + token_properties: _, + } = split_token; + let Token { + id: _, + amount: _, + token_properties: _, + } = token; + } + + #[test] + #[expected_failure(abort_code = 65570, location = Self)] + public fun test_enter_illegal_royalty(){ + create_royalty(101, 100, @0xcafe); + } + + #[test(framework = @0x1, creator = @0xcafe)] + fun test_partial_withdraw_with_proof(creator: &signer, framework: &signer): Token acquires TokenStore, Collections { + timestamp::set_time_has_started_for_testing(framework); + account::create_account_for_test(signer::address_of(creator)); + let token_id = create_collection_and_token( + creator, + 4, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, false], + ); + + timestamp::update_global_time_for_test(1000000); + + // provide the proof to the account + let cap = create_withdraw_capability( + creator, // ask user to provide address to avoid ambiguity from rotated keys + token_id, + 3, + 2000000, + ); + + let (token, capability) = partial_withdraw_with_capability(cap, 1); + assert!(option::borrow(&capability).amount == 2, 1); + let (token_1, cap) = partial_withdraw_with_capability(option::extract(&mut capability), 2); + assert!(option::is_none(&cap), 1); + merge(&mut token, token_1); + token + } + + #[test(creator = @0xcafe)] + fun test_get_collection_mutability_config(creator: &signer) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + + // token owner mutate the token property + create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, true], + ); + + get_collection_mutability_config(@0xcafe, get_collection_name()); + } + + #[test(creator = @0xcafe)] + fun test_get_tokendata_mutability_config(creator: &signer) acquires Collections, TokenStore { + account::create_account_for_test(signer::address_of(creator)); + + // token owner mutate the token property + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[], + vector>[], + vector[], + vector[false, false, false], + vector[false, false, false, false, true], + ); + + get_tokendata_mutability_config(token_id.token_data_id); + } + + #[test(creator = @0xcafe, owner = @0x456)] + #[expected_failure(abort_code = 327720, location = Self)] + fun test_fail_to_add_burn_flag( + creator: &signer, + owner: &signer, + ) acquires TokenStore, Collections { + use std::bcs; + account::create_account_for_test(signer::address_of(creator)); + account::create_account_for_test(signer::address_of(owner)); + let token_id = create_collection_and_token( + creator, + 2, + 4, + 4, + vector[string::utf8(BURNABLE_BY_OWNER)], + vector>[bcs::to_bytes(&true)], + vector[string::utf8(b"bool")], + vector[false, false, false], + vector[true, true, true, true, true], + ); + let new_keys = vector[ + string::utf8(BURNABLE_BY_CREATOR), + ]; + let new_vals = vector>[ + bcs::to_bytes(&true), + ]; + let new_types = vector[ + string::utf8(b"bool"), + ]; + mutate_tokendata_property( + creator, + token_id.token_data_id, + new_keys, + new_vals, + new_types, + ); + } + + // + // Deprecated functions + // + + public entry fun initialize_token_script(_account: &signer) { + abort 0 + } + + public fun initialize_token(_account: &signer, _token_id: TokenId) { + abort 0 + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_coin_swap.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_coin_swap.move new file mode 100644 index 0000000..dafc8a1 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_coin_swap.move @@ -0,0 +1,162 @@ +/// Deprecated module +module aptos_token::token_coin_swap { + use std::string::String; + use std::error; + use aptos_std::table::Table; + use aptos_std::type_info::TypeInfo; + use aptos_framework::event::EventHandle; + use aptos_token::token::{Token, TokenId}; + + // + // Errors. + // + + /// Token already listed + const ETOKEN_ALREADY_LISTED: u64 = 1; + + /// Token listing no longer exists + const ETOKEN_LISTING_NOT_EXIST: u64 = 2; + + /// Token is not in escrow + const ETOKEN_NOT_IN_ESCROW: u64 = 3; + + /// Token cannot be moved out of escrow before the lockup time + const ETOKEN_CANNOT_MOVE_OUT_OF_ESCROW_BEFORE_LOCKUP_TIME: u64 = 4; + + /// Token buy price doesn't match listing price + const ETOKEN_MIN_PRICE_NOT_MATCH: u64 = 5; + + /// Token buy amount doesn't match listing amount + const ETOKEN_AMOUNT_NOT_MATCH: u64 = 6; + + /// Not enough coin to buy token + const ENOT_ENOUGH_COIN: u64 = 7; + + /// Deprecated module + const EDEPRECATED_MODULE: u64 = 8; + + /// TokenCoinSwap records a swap ask for swapping token_amount with CoinType with a minimal price per token + struct TokenCoinSwap has store, drop { + token_amount: u64, + min_price_per_token: u64, + } + + /// The listing of all tokens for swapping stored at token owner's account + struct TokenListings has key { + // key is the token id for swapping and value is the min price of target coin type. + listings: Table>, + listing_events: EventHandle, + swap_events: EventHandle, + } + + /// TokenEscrow holds the tokens that cannot be withdrawn or transferred + struct TokenEscrow has store { + token: Token, + // until the locked time runs out, the owner cannot move the token out of the escrow + // the default value is 0 meaning the owner can move the coin out anytime + locked_until_secs: u64, + } + + /// TokenStoreEscrow holds a map of token id to their tokenEscrow + struct TokenStoreEscrow has key { + token_escrows: Table, + } + + struct TokenListingEvent has drop, store { + token_id: TokenId, + amount: u64, + min_price: u64, + locked_until_secs: u64, + coin_type_info: TypeInfo, + } + + struct TokenSwapEvent has drop, store { + token_id: TokenId, + token_buyer: address, + token_amount: u64, + coin_amount: u64, + coin_type_info: TypeInfo, + } + + public fun does_listing_exist( + _token_owner: address, + _token_id: TokenId + ): bool { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Coin owner withdraw coin to swap with tokens listed for swapping at the token owner's address. + public fun exchange_coin_for_token( + _coin_owner: &signer, + _coin_amount: u64, + _token_owner: address, + _creators_address: address, + _collection: String, + _name: String, + _property_version: u64, + _token_amount: u64, + ) { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Token owner lists their token for swapping + public entry fun list_token_for_swap( + _token_owner: &signer, + _creators_address: address, + _collection: String, + _name: String, + _property_version: u64, + _token_amount: u64, + _min_coin_per_token: u64, + _locked_until_secs: u64 + ) { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Initalize the token listing for a token owner + fun initialize_token_listing(_token_owner: &signer) { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Intialize the token escrow + fun initialize_token_store_escrow(_token_owner: &signer) { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Put the token into escrow that cannot be transferred or withdrawed by the owner. + public fun deposit_token_to_escrow( + _token_owner: &signer, + _token_id: TokenId, + _tokens: Token, + _locked_until_secs: u64 + ) { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Private function for withdraw tokens from an escrow stored in token owner address + fun withdraw_token_from_escrow_internal( + _token_owner_addr: address, + _token_id: TokenId, + _amount: u64 + ): Token { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Withdraw tokens from the token escrow. It needs a signer to authorize + public fun withdraw_token_from_escrow( + _token_owner: &signer, + _token_id: TokenId, + _amount: u64 + ): Token { + abort error::invalid_argument(EDEPRECATED_MODULE) + } + + /// Cancel token listing for a fixed amount + public fun cancel_token_listing( + _token_owner: &signer, + _token_id: TokenId, + _token_amount: u64, + ) { + abort error::invalid_argument(EDEPRECATED_MODULE) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_event_store.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_event_store.move new file mode 100644 index 0000000..52ba6c7 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_event_store.move @@ -0,0 +1,340 @@ +/// This module provides utils to add and emit new token events that are not in token.move +module aptos_token::token_event_store { + use std::string::String; + use std::signer; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::account; + use std::option::Option; + use aptos_std::any::Any; + use std::option; + use aptos_token::property_map::PropertyValue; + + friend aptos_token::token; + + // + // Collection mutation events + // + + /// Event emitted when collection description is mutated + struct CollectionDescriptionMutateEvent has drop, store { + creator_addr: address, + collection_name: String, + old_description: String, + new_description: String, + } + + /// Event emitted when collection uri is mutated + struct CollectionUriMutateEvent has drop, store { + creator_addr: address, + collection_name: String, + old_uri: String, + new_uri: String, + } + + /// Event emitted when the collection maximum is mutated + struct CollectionMaxiumMutateEvent has drop, store { + creator_addr: address, + collection_name: String, + old_maximum: u64, + new_maximum: u64, + } + + // + // Token transfer related events + // + + /// Event emitted when an user opt-in the direct transfer + struct OptInTransferEvent has drop, store { + /// True if the user opt in, false if the user opt-out + opt_in: bool + } + + // + // Token mutation events + // + + /// Event emitted when the tokendata uri mutates + struct UriMutationEvent has drop, store { + creator: address, + collection: String, + token: String, + old_uri: String, + new_uri: String, + } + + /// Event emitted when mutating the default the token properties stored at tokendata + struct DefaultPropertyMutateEvent has drop, store { + creator: address, + collection: String, + token: String, + keys: vector, + /// we allow upsert so the old values might be none + old_values: vector>, + new_values: vector, + } + + /// Event emitted when the tokendata description is mutated + struct DescriptionMutateEvent has drop, store { + creator: address, + collection: String, + token: String, + old_description: String, + new_description: String, + } + + /// Event emitted when the token royalty is mutated + struct RoyaltyMutateEvent has drop, store { + creator: address, + collection: String, + token: String, + old_royalty_numerator: u64, + old_royalty_denominator: u64, + old_royalty_payee_addr: address, + new_royalty_numerator: u64, + new_royalty_denominator: u64, + new_royalty_payee_addr: address, + } + + /// Event emitted when the token maximum is mutated + struct MaxiumMutateEvent has drop, store { + creator: address, + collection: String, + token: String, + old_maximum: u64, + new_maximum: u64, + } + + struct TokenEventStoreV1 has key { + /// collection mutation events + collection_uri_mutate_events: EventHandle, + collection_maximum_mutate_events: EventHandle, + collection_description_mutate_events: EventHandle, + /// token transfer opt-in event + opt_in_events: EventHandle, + /// token mutation events + uri_mutate_events: EventHandle, + default_property_mutate_events: EventHandle, + description_mutate_events: EventHandle, + royalty_mutate_events: EventHandle, + maximum_mutate_events: EventHandle, + /// This is for adding new events in future + extension: Option, + } + + fun initialize_token_event_store(acct: &signer){ + if (!exists(signer::address_of(acct))) { + move_to(acct, TokenEventStoreV1 { + collection_uri_mutate_events: account::new_event_handle(acct), + collection_maximum_mutate_events: account::new_event_handle(acct), + collection_description_mutate_events: account::new_event_handle(acct), + opt_in_events: account::new_event_handle(acct), + uri_mutate_events: account::new_event_handle(acct), + default_property_mutate_events: account::new_event_handle(acct), + description_mutate_events: account::new_event_handle(acct), + royalty_mutate_events: account::new_event_handle(acct), + maximum_mutate_events: account::new_event_handle(acct), + extension: option::none(), + }); + }; + } + + /// Emit the collection uri mutation event + public(friend) fun emit_collection_uri_mutate_event(creator: &signer, collection: String, old_uri: String, new_uri: String) acquires TokenEventStoreV1 { + let event = CollectionUriMutateEvent { + creator_addr: signer::address_of(creator), + collection_name: collection, + old_uri, + new_uri, + }; + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(signer::address_of(creator)); + event::emit_event( + &mut token_event_store.collection_uri_mutate_events, + event, + ); + } + + /// Emit the collection description mutation event + public(friend) fun emit_collection_description_mutate_event(creator: &signer, collection: String, old_description: String, new_description: String) acquires TokenEventStoreV1 { + let event = CollectionDescriptionMutateEvent { + creator_addr: signer::address_of(creator), + collection_name: collection, + old_description, + new_description, + }; + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(signer::address_of(creator)); + event::emit_event( + &mut token_event_store.collection_description_mutate_events, + event, + ); + } + + /// Emit the collection maximum mutation event + public(friend) fun emit_collection_maximum_mutate_event(creator: &signer, collection: String, old_maximum: u64, new_maximum: u64) acquires TokenEventStoreV1 { + let event = CollectionMaxiumMutateEvent { + creator_addr: signer::address_of(creator), + collection_name: collection, + old_maximum, + new_maximum, + }; + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(signer::address_of(creator)); + event::emit_event( + &mut token_event_store.collection_maximum_mutate_events, + event, + ); + } + + /// Emit the direct opt-in event + public(friend) fun emit_token_opt_in_event(account: &signer, opt_in: bool) acquires TokenEventStoreV1 { + let opt_in_event = OptInTransferEvent { + opt_in, + }; + initialize_token_event_store(account); + let token_event_store = borrow_global_mut(signer::address_of(account)); + event::emit_event( + &mut token_event_store.opt_in_events, + opt_in_event, + ); + } + + /// Emit URI mutation event + public(friend) fun emit_token_uri_mutate_event( + creator: &signer, + collection: String, + token: String, + old_uri: String, + new_uri: String, + ) acquires TokenEventStoreV1 { + let creator_addr = signer::address_of(creator); + + let event = UriMutationEvent { + creator: creator_addr, + collection, + token, + old_uri, + new_uri, + }; + + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(creator_addr); + event::emit_event( + &mut token_event_store.uri_mutate_events, + event, + ); + } + + /// Emit tokendata property map mutation event + public(friend) fun emit_default_property_mutate_event( + creator: &signer, + collection: String, + token: String, + keys: vector, + old_values: vector>, + new_values: vector, + ) acquires TokenEventStoreV1 { + let creator_addr = signer::address_of(creator); + + let event = DefaultPropertyMutateEvent { + creator: creator_addr, + collection, + token, + keys, + old_values, + new_values, + }; + + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(creator_addr); + event::emit_event( + &mut token_event_store.default_property_mutate_events, + event, + ); + } + + /// Emit description mutation event + public(friend) fun emit_token_descrition_mutate_event( + creator: &signer, + collection: String, + token: String, + old_description: String, + new_description: String, + ) acquires TokenEventStoreV1 { + let creator_addr = signer::address_of(creator); + + let event = DescriptionMutateEvent { + creator: creator_addr, + collection, + token, + old_description, + new_description, + }; + + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(creator_addr); + event::emit_event( + &mut token_event_store.description_mutate_events, + event, + ); + } + + /// Emit royalty mutation event + public(friend) fun emit_token_royalty_mutate_event( + creator: &signer, + collection: String, + token: String, + old_royalty_numerator: u64, + old_royalty_denominator: u64, + old_royalty_payee_addr: address, + new_royalty_numerator: u64, + new_royalty_denominator: u64, + new_royalty_payee_addr: address, + ) acquires TokenEventStoreV1 { + let creator_addr = signer::address_of(creator); + let event = RoyaltyMutateEvent { + creator: creator_addr, + collection, + token, + old_royalty_numerator, + old_royalty_denominator, + old_royalty_payee_addr, + new_royalty_numerator, + new_royalty_denominator, + new_royalty_payee_addr, + }; + + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(creator_addr); + event::emit_event( + &mut token_event_store.royalty_mutate_events, + event, + ); + } + + /// Emit maximum mutation event + public(friend) fun emit_token_maximum_mutate_event( + creator: &signer, + collection: String, + token: String, + old_maximum: u64, + new_maximum: u64, + ) acquires TokenEventStoreV1 { + let creator_addr = signer::address_of(creator); + + let event = MaxiumMutateEvent { + creator: creator_addr, + collection, + token, + old_maximum, + new_maximum, + }; + + initialize_token_event_store(creator); + let token_event_store = borrow_global_mut(creator_addr); + event::emit_event( + &mut token_event_store.maximum_mutate_events, + event, + ); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_transfers.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_transfers.move new file mode 100644 index 0000000..19ec02c --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/AptosToken/token_transfers.move @@ -0,0 +1,275 @@ +/// This module provides the foundation for transferring of Tokens +module aptos_token::token_transfers { + use std::signer; + use std::string::String; + use std::error; + use aptos_std::table::{Self, Table}; + use aptos_token::token::{Self, Token, TokenId}; + use aptos_framework::account; + use aptos_framework::event::{Self, EventHandle}; + + // + // Errors. + // + + /// Token offer doesn't exist + const ETOKEN_OFFER_NOT_EXIST: u64 = 1; + + struct PendingClaims has key { + pending_claims: Table, + offer_events: EventHandle, + cancel_offer_events: EventHandle, + claim_events: EventHandle, + } + + struct TokenOfferId has copy, drop, store { + to_addr: address, + token_id: TokenId, + } + + struct TokenOfferEvent has drop, store { + to_address: address, + token_id: TokenId, + amount: u64, + } + + struct TokenCancelOfferEvent has drop, store { + to_address: address, + token_id: TokenId, + amount: u64, + } + + struct TokenClaimEvent has drop, store { + to_address: address, + token_id: TokenId, + amount: u64, + } + + fun initialize_token_transfers(account: &signer) { + move_to( + account, + PendingClaims { + pending_claims: table::new(), + offer_events: account::new_event_handle(account), + cancel_offer_events: account::new_event_handle(account), + claim_events: account::new_event_handle(account), + } + ) + } + + fun create_token_offer_id(to_addr: address, token_id: TokenId): TokenOfferId { + TokenOfferId { + to_addr, + token_id + } + } + + public entry fun offer_script( + sender: signer, + receiver: address, + creator: address, + collection: String, + name: String, + property_version: u64, + amount: u64, + ) acquires PendingClaims { + let token_id = token::create_token_id_raw(creator, collection, name, property_version); + offer(&sender, receiver, token_id, amount); + } + + public fun offer( + sender: &signer, + receiver: address, + token_id: TokenId, + amount: u64, + ) acquires PendingClaims { + let sender_addr = signer::address_of(sender); + if (!exists(sender_addr)) { + initialize_token_transfers(sender) + }; + + let pending_claims = + &mut borrow_global_mut(sender_addr).pending_claims; + let token_offer_id = create_token_offer_id(receiver, token_id); + let token = token::withdraw_token(sender, token_id, amount); + if (!table::contains(pending_claims, token_offer_id)) { + table::add(pending_claims, token_offer_id, token); + } else { + let dst_token = table::borrow_mut(pending_claims, token_offer_id); + token::merge(dst_token, token); + }; + + event::emit_event( + &mut borrow_global_mut(sender_addr).offer_events, + TokenOfferEvent { + to_address: receiver, + token_id, + amount, + }, + ); + } + + public entry fun claim_script( + receiver: signer, + sender: address, + creator: address, + collection: String, + name: String, + property_version: u64, + ) acquires PendingClaims { + let token_id = token::create_token_id_raw(creator, collection, name, property_version); + claim(&receiver, sender, token_id); + } + + public fun claim( + receiver: &signer, + sender: address, + token_id: TokenId, + ) acquires PendingClaims { + assert!(exists(sender), ETOKEN_OFFER_NOT_EXIST); + let pending_claims = + &mut borrow_global_mut(sender).pending_claims; + let token_offer_id = create_token_offer_id(signer::address_of(receiver), token_id); + assert!(table::contains(pending_claims, token_offer_id), error::not_found(ETOKEN_OFFER_NOT_EXIST)); + let tokens = table::remove(pending_claims, token_offer_id); + let amount = token::get_token_amount(&tokens); + token::deposit_token(receiver, tokens); + + event::emit_event( + &mut borrow_global_mut(sender).claim_events, + TokenClaimEvent { + to_address: signer::address_of(receiver), + token_id, + amount, + }, + ); + } + + public entry fun cancel_offer_script( + sender: signer, + receiver: address, + creator: address, + collection: String, + name: String, + property_version: u64, + ) acquires PendingClaims { + let token_id = token::create_token_id_raw(creator, collection, name, property_version); + cancel_offer(&sender, receiver, token_id); + } + + // Extra from our pending_claims and return to gallery + public fun cancel_offer( + sender: &signer, + receiver: address, + token_id: TokenId, + ) acquires PendingClaims { + let sender_addr = signer::address_of(sender); + let token_offer_id = create_token_offer_id(receiver, token_id); + assert!(exists(sender_addr), ETOKEN_OFFER_NOT_EXIST); + let pending_claims = + &mut borrow_global_mut(sender_addr).pending_claims; + let token = table::remove(pending_claims, token_offer_id); + let amount = token::get_token_amount(&token); + token::deposit_token(sender, token); + + event::emit_event( + &mut borrow_global_mut(sender_addr).cancel_offer_events, + TokenCancelOfferEvent { + to_address: receiver, + token_id, + amount, + }, + ); + } + + #[test(creator = @0x1, owner = @0x2)] + public fun test_nft(creator: signer, owner: signer) acquires PendingClaims { + let token_id = create_token(&creator, 1); + + let creator_addr = signer::address_of(&creator); + let owner_addr = signer::address_of(&owner); + aptos_framework::account::create_account_for_test(owner_addr); + offer(&creator, owner_addr, token_id, 1); + claim(&owner, creator_addr, token_id); + + + offer(&owner, creator_addr, token_id, 1); + cancel_offer(&owner, creator_addr, token_id); + } + + #[test(creator = @0x1, owner0 = @0x2, owner1 = @0x3)] + public fun test_editions( + creator: signer, + owner0: signer, + owner1: signer, + ) acquires PendingClaims { + let token_id = create_token(&creator, 2); + + let creator_addr = signer::address_of(&creator); + let owner0_addr = signer::address_of(&owner0); + aptos_framework::account::create_account_for_test(owner0_addr); + let owner1_addr = signer::address_of(&owner1); + aptos_framework::account::create_account_for_test(owner1_addr); + + offer(&creator, owner0_addr, token_id, 1); + offer(&creator, owner1_addr, token_id, 1); + + assert!(token::balance_of(signer::address_of(&creator), token_id) == 0, 1); + claim(&owner0, creator_addr, token_id); + assert!(token::balance_of(signer::address_of(&owner0), token_id) == 1, 1); + claim(&owner1, creator_addr, token_id); + assert!(token::balance_of(signer::address_of(&owner1), token_id) == 1, 1); + + offer(&owner0, owner1_addr, token_id, 1); + claim(&owner1, owner0_addr, token_id); + + offer(&owner1, creator_addr, token_id, 1); + offer(&owner1, creator_addr, token_id, 1); + claim(&creator, owner1_addr, token_id); + } + + #[test_only] + public entry fun create_token(creator: &signer, amount: u64): TokenId { + use std::string::{Self, String}; + + let collection_name = string::utf8(b"Hello, World"); + let collection_mutation_setting = vector[false, false, false]; + aptos_framework::account::create_account_for_test(signer::address_of(creator)); + + token::create_collection( + creator, + collection_name, + string::utf8(b"Collection: Hello, World"), + string::utf8(b"https://aptos.dev"), + 1, + collection_mutation_setting, + ); + + let token_mutation_setting = vector[false, false, false, false, true]; + let default_keys = vector[string::utf8(b"attack"), string::utf8(b"num_of_use")]; + let default_vals = vector>[b"10", b"5"]; + let default_types = vector[string::utf8(b"integer"), string::utf8(b"integer")]; + token::create_token_script( + creator, + collection_name, + string::utf8(b"Token: Hello, Token"), + string::utf8(b"Hello, Token"), + amount, + amount, + string::utf8(b"https://aptos.dev"), + signer::address_of(creator), + 100, + 0, + token_mutation_setting, + default_keys, + default_vals, + default_types, + ); + token::create_token_id_raw( + signer::address_of(creator), + collection_name, + string::utf8(b"Token: Hello, Token"), + 0 + ) + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/acl.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/acl.move new file mode 100644 index 0000000..5cf71e6 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/acl.move @@ -0,0 +1,46 @@ +/// Access control list (acl) module. An acl is a list of account addresses who +/// have the access permission to a certain object. +/// This module uses a `vector` to represent the list, but can be refactored to +/// use a "set" instead when it's available in the language in the future. + +module std::acl { + use std::vector; + use std::error; + + /// The ACL already contains the address. + const ECONTAIN: u64 = 0; + /// The ACL does not contain the address. + const ENOT_CONTAIN: u64 = 1; + + struct ACL has store, drop, copy { + list: vector
+ } + + /// Return an empty ACL. + public fun empty(): ACL { + ACL{ list: vector::empty
() } + } + + /// Add the address to the ACL. + public fun add(acl: &mut ACL, addr: address) { + assert!(!vector::contains(&mut acl.list, &addr), error::invalid_argument(ECONTAIN)); + vector::push_back(&mut acl.list, addr); + } + + /// Remove the address from the ACL. + public fun remove(acl: &mut ACL, addr: address) { + let (found, index) = vector::index_of(&mut acl.list, &addr); + assert!(found, error::invalid_argument(ENOT_CONTAIN)); + vector::remove(&mut acl.list, index); + } + + /// Return true iff the ACL contains the address. + public fun contains(acl: &ACL, addr: address): bool { + vector::contains(&acl.list, &addr) + } + + /// assert! that the ACL has the address. + public fun assert_contains(acl: &ACL, addr: address) { + assert!(contains(acl, addr), error::invalid_argument(ENOT_CONTAIN)); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bcs.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bcs.move new file mode 100644 index 0000000..79b4c98 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bcs.move @@ -0,0 +1,17 @@ +/// Utility for converting a Move value to its binary representation in BCS (Binary Canonical +/// Serialization). BCS is the binary encoding for Move resources and other non-module values +/// published on-chain. See https://github.com/aptos-labs/bcs#binary-canonical-serialization-bcs for more +/// details on BCS. +module std::bcs { + /// Return the binary representation of `v` in BCS (Binary Canonical Serialization) format + native public fun to_bytes(v: &MoveValue): vector; + + // ============================== + // Module Specification + spec module {} // switch to module documentation context + + spec module { + /// Native function which is defined in the prover's prelude. + native fun serialize(v: &MoveValue): vector; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bit_vector.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bit_vector.move new file mode 100644 index 0000000..e0202f1 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/bit_vector.move @@ -0,0 +1,157 @@ +module std::bit_vector { + use std::vector; + + /// The provided index is out of bounds + const EINDEX: u64 = 0x20000; + /// An invalid length of bitvector was given + const ELENGTH: u64 = 0x20001; + + const WORD_SIZE: u64 = 1; + /// The maximum allowed bitvector size + const MAX_SIZE: u64 = 1024; + + struct BitVector has copy, drop, store { + length: u64, + bit_field: vector, + } + + public fun new(length: u64): BitVector { + assert!(length > 0, ELENGTH); + assert!(length < MAX_SIZE, ELENGTH); + let counter = 0; + let bit_field = vector::empty(); + while ({spec { + invariant counter <= length; + invariant len(bit_field) == counter; + }; + (counter < length)}) { + vector::push_back(&mut bit_field, false); + counter = counter + 1; + }; + spec { + assert counter == length; + assert len(bit_field) == length; + }; + + BitVector { + length, + bit_field, + } + } + spec new { + include NewAbortsIf; + ensures result.length == length; + ensures len(result.bit_field) == length; + } + spec schema NewAbortsIf { + length: u64; + aborts_if length <= 0 with ELENGTH; + aborts_if length >= MAX_SIZE with ELENGTH; + } + + /// Set the bit at `bit_index` in the `bitvector` regardless of its previous state. + public fun set(bitvector: &mut BitVector, bit_index: u64) { + assert!(bit_index < vector::length(&bitvector.bit_field), EINDEX); + let x = vector::borrow_mut(&mut bitvector.bit_field, bit_index); + *x = true; + } + spec set { + include SetAbortsIf; + ensures bitvector.bit_field[bit_index]; + } + spec schema SetAbortsIf { + bitvector: BitVector; + bit_index: u64; + aborts_if bit_index >= length(bitvector) with EINDEX; + } + + /// Unset the bit at `bit_index` in the `bitvector` regardless of its previous state. + public fun unset(bitvector: &mut BitVector, bit_index: u64) { + assert!(bit_index < vector::length(&bitvector.bit_field), EINDEX); + let x = vector::borrow_mut(&mut bitvector.bit_field, bit_index); + *x = false; + } + spec unset { + include UnsetAbortsIf; + ensures !bitvector.bit_field[bit_index]; + } + spec schema UnsetAbortsIf { + bitvector: BitVector; + bit_index: u64; + aborts_if bit_index >= length(bitvector) with EINDEX; + } + + /// Shift the `bitvector` left by `amount`. If `amount` is greater than the + /// bitvector's length the bitvector will be zeroed out. + public fun shift_left(bitvector: &mut BitVector, amount: u64) { + if (amount >= bitvector.length) { + vector::for_each_mut(&mut bitvector.bit_field, |elem| { + *elem = false; + }); + } else { + let i = amount; + + while (i < bitvector.length) { + if (is_index_set(bitvector, i)) set(bitvector, i - amount) + else unset(bitvector, i - amount); + i = i + 1; + }; + + i = bitvector.length - amount; + + while (i < bitvector.length) { + unset(bitvector, i); + i = i + 1; + }; + } + } + + /// Return the value of the bit at `bit_index` in the `bitvector`. `true` + /// represents "1" and `false` represents a 0 + public fun is_index_set(bitvector: &BitVector, bit_index: u64): bool { + assert!(bit_index < vector::length(&bitvector.bit_field), EINDEX); + *vector::borrow(&bitvector.bit_field, bit_index) + } + spec is_index_set { + include IsIndexSetAbortsIf; + ensures result == bitvector.bit_field[bit_index]; + } + spec schema IsIndexSetAbortsIf { + bitvector: BitVector; + bit_index: u64; + aborts_if bit_index >= length(bitvector) with EINDEX; + } + spec fun spec_is_index_set(bitvector: BitVector, bit_index: u64): bool { + if (bit_index >= length(bitvector)) { + false + } else { + bitvector.bit_field[bit_index] + } + } + + /// Return the length (number of usable bits) of this bitvector + public fun length(bitvector: &BitVector): u64 { + vector::length(&bitvector.bit_field) + } + + /// Returns the length of the longest sequence of set bits starting at (and + /// including) `start_index` in the `bitvector`. If there is no such + /// sequence, then `0` is returned. + public fun longest_set_sequence_starting_at(bitvector: &BitVector, start_index: u64): u64 { + assert!(start_index < bitvector.length, EINDEX); + let index = start_index; + + // Find the greatest index in the vector such that all indices less than it are set. + while (index < bitvector.length) { + if (!is_index_set(bitvector, index)) break; + index = index + 1; + }; + + index - start_index + } + + #[test_only] + public fun word_size(): u64 { + WORD_SIZE + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/error.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/error.move new file mode 100644 index 0000000..1facaf0 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/error.move @@ -0,0 +1,88 @@ +/// This module defines a set of canonical error codes which are optional to use by applications for the +/// `abort` and `assert!` features. +/// +/// Canonical error codes use the 3 lowest bytes of the u64 abort code range (the upper 5 bytes are free for other use). +/// Of those, the highest byte represents the *error category* and the lower two bytes the *error reason*. +/// Given an error category `0x1` and a reason `0x3`, a canonical abort code looks as `0x10003`. +/// +/// A module can use a canonical code with a constant declaration of the following form: +/// +/// ``` +/// /// An invalid ASCII character was encountered when creating a string. +/// const EINVALID_CHARACTER: u64 = 0x010003; +/// ``` +/// +/// This code is both valid in the worlds with and without canonical errors. It can be used as a plain module local +/// error reason understand by the existing error map tooling, or as a canonical code. +/// +/// The actual canonical categories have been adopted from Google's canonical error codes, which in turn are derived +/// from Unix error codes [see here](https://cloud.google.com/apis/design/errors#handling_errors). Each code has an +/// associated HTTP error code which can be used in REST apis. The mapping from error code to http code is not 1:1; +/// error codes here are a bit richer than HTTP codes. +module std::error { + + /// Caller specified an invalid argument (http: 400) + const INVALID_ARGUMENT: u64 = 0x1; + + /// An input or result of a computation is out of range (http: 400) + const OUT_OF_RANGE: u64 = 0x2; + + /// The system is not in a state where the operation can be performed (http: 400) + const INVALID_STATE: u64 = 0x3; + + /// Request not authenticated due to missing, invalid, or expired auth token (http: 401) + const UNAUTHENTICATED: u64 = 0x4; + + /// client does not have sufficient permission (http: 403) + const PERMISSION_DENIED: u64 = 0x5; + + /// A specified resource is not found (http: 404) + const NOT_FOUND: u64 = 0x6; + + /// Concurrency conflict, such as read-modify-write conflict (http: 409) + const ABORTED: u64 = 0x7; + + /// The resource that a client tried to create already exists (http: 409) + const ALREADY_EXISTS: u64 = 0x8; + + /// Out of gas or other forms of quota (http: 429) + const RESOURCE_EXHAUSTED: u64 = 0x9; + + /// Request cancelled by the client (http: 499) + const CANCELLED: u64 = 0xA; + + /// Internal error (http: 500) + const INTERNAL: u64 = 0xB; + + /// Feature not implemented (http: 501) + const NOT_IMPLEMENTED: u64 = 0xC; + + /// The service is currently unavailable. Indicates that a retry could solve the issue (http: 503) + const UNAVAILABLE: u64 = 0xD; + + /// Construct a canonical error code from a category and a reason. + public fun canonical(category: u64, reason: u64): u64 { + (category << 16) + reason + } + spec canonical { + pragma opaque = true; + let shl_res = category << 16; + ensures [concrete] result == shl_res + reason; + aborts_if [abstract] false; + ensures [abstract] result == category; + } + + /// Functions to construct a canonical error code of the given category. + public fun invalid_argument(r: u64): u64 { canonical(INVALID_ARGUMENT, r) } + public fun out_of_range(r: u64): u64 { canonical(OUT_OF_RANGE, r) } + public fun invalid_state(r: u64): u64 { canonical(INVALID_STATE, r) } + public fun unauthenticated(r: u64): u64 { canonical(UNAUTHENTICATED, r) } + public fun permission_denied(r: u64): u64 { canonical(PERMISSION_DENIED, r) } + public fun not_found(r: u64): u64 { canonical(NOT_FOUND, r) } + public fun aborted(r: u64): u64 { canonical(ABORTED, r) } + public fun already_exists(r: u64): u64 { canonical(ALREADY_EXISTS, r) } + public fun resource_exhausted(r: u64): u64 { canonical(RESOURCE_EXHAUSTED, r) } + public fun internal(r: u64): u64 { canonical(INTERNAL, r) } + public fun not_implemented(r: u64): u64 { canonical(NOT_IMPLEMENTED, r) } + public fun unavailable(r: u64): u64 { canonical(UNAVAILABLE, r) } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/features.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/features.move new file mode 100644 index 0000000..14ca566 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/features.move @@ -0,0 +1,339 @@ +/// Defines feature flags for Aptos. Those are used in Aptos specific implementations of features in +/// the Move stdlib, the Aptos stdlib, and the Aptos framework. +/// +/// ============================================================================================ +/// Feature Flag Definitions +/// +/// Each feature flag should come with documentation which justifies the need of the flag. +/// Introduction of a new feature flag requires approval of framework owners. Be frugal when +/// introducing new feature flags, as too many can make it hard to understand the code. +/// +/// Each feature flag should come with a specification of a lifetime: +/// +/// - a *transient* feature flag is only needed until a related code rollout has happened. This +/// is typically associated with the introduction of new native Move functions, and is only used +/// from Move code. The owner of this feature is obliged to remove it once this can be done. +/// +/// - a *permanent* feature flag is required to stay around forever. Typically, those flags guard +/// behavior in native code, and the behavior with or without the feature need to be preserved +/// for playback. +/// +/// Note that removing a feature flag still requires the function which tests for the feature +/// (like `code_dependency_check_enabled` below) to stay around for compatibility reasons, as it +/// is a public function. However, once the feature flag is disabled, those functions can constantly +/// return true. +module std::features { + use std::error; + use std::signer; + use std::vector; + + // -------------------------------------------------------------------------------------------- + // Code Publishing + + /// Whether validation of package dependencies is enabled, and the related native function is + /// available. This is needed because of introduction of a new native function. + /// Lifetime: transient + const CODE_DEPENDENCY_CHECK: u64 = 1; + + public fun code_dependency_check_enabled(): bool acquires Features { + is_enabled(CODE_DEPENDENCY_CHECK) + } + + /// Whether during upgrade compatibility checking, friend functions should be treated similar like + /// private functions. + /// Lifetime: permanent + const TREAT_FRIEND_AS_PRIVATE: u64 = 2; + + public fun treat_friend_as_private(): bool acquires Features { + is_enabled(TREAT_FRIEND_AS_PRIVATE) + } + + /// Whether the new SHA2-512, SHA3-512 and RIPEMD-160 hash function natives are enabled. + /// This is needed because of the introduction of new native functions. + /// Lifetime: transient + const SHA_512_AND_RIPEMD_160_NATIVES: u64 = 3; + public fun get_sha_512_and_ripemd_160_feature(): u64 { SHA_512_AND_RIPEMD_160_NATIVES } + public fun sha_512_and_ripemd_160_enabled(): bool acquires Features { + is_enabled(SHA_512_AND_RIPEMD_160_NATIVES) + } + + /// Whether the new `aptos_stdlib::type_info::chain_id()` native for fetching the chain ID is enabled. + /// This is needed because of the introduction of a new native function. + /// Lifetime: transient + const APTOS_STD_CHAIN_ID_NATIVES: u64 = 4; + public fun get_aptos_stdlib_chain_id_feature(): u64 { APTOS_STD_CHAIN_ID_NATIVES } + public fun aptos_stdlib_chain_id_enabled(): bool acquires Features { + is_enabled(APTOS_STD_CHAIN_ID_NATIVES) + } + + /// Whether to allow the use of binary format version v6. + /// Lifetime: transient + const VM_BINARY_FORMAT_V6: u64 = 5; + public fun get_vm_binary_format_v6(): u64 { VM_BINARY_FORMAT_V6 } + public fun allow_vm_binary_format_v6(): bool acquires Features { + is_enabled(VM_BINARY_FORMAT_V6) + } + + /// Whether gas fees are collected and distributed to the block proposers. + /// Lifetime: transient + const COLLECT_AND_DISTRIBUTE_GAS_FEES: u64 = 6; + public fun get_collect_and_distribute_gas_fees_feature(): u64 { COLLECT_AND_DISTRIBUTE_GAS_FEES } + public fun collect_and_distribute_gas_fees(): bool acquires Features { + is_enabled(COLLECT_AND_DISTRIBUTE_GAS_FEES) + } + + /// Whether the new `aptos_stdlib::multi_ed25519::public_key_validate_internal_v2()` native is enabled. + /// This is needed because of the introduction of a new native function. + /// Lifetime: transient + const MULTI_ED25519_PK_VALIDATE_V2_NATIVES: u64 = 7; + public fun multi_ed25519_pk_validate_v2_feature(): u64 { MULTI_ED25519_PK_VALIDATE_V2_NATIVES } + public fun multi_ed25519_pk_validate_v2_enabled(): bool acquires Features { + is_enabled(MULTI_ED25519_PK_VALIDATE_V2_NATIVES) + } + + /// Whether the new BLAKE2B-256 hash function native is enabled. + /// This is needed because of the introduction of new native function(s). + /// Lifetime: transient + const BLAKE2B_256_NATIVE: u64 = 8; + public fun get_blake2b_256_feature(): u64 { BLAKE2B_256_NATIVE } + public fun blake2b_256_enabled(): bool acquires Features { + is_enabled(BLAKE2B_256_NATIVE) + } + + /// Whether resource groups are enabled. + /// This is needed because of new attributes for structs and a change in storage representation. + const RESOURCE_GROUPS: u64 = 9; + public fun get_resource_groups_feature(): u64 { RESOURCE_GROUPS } + public fun resource_groups_enabled(): bool acquires Features { + is_enabled(RESOURCE_GROUPS) + } + + /// Whether multisig accounts (different from accounts with multi-ed25519 auth keys) are enabled. + const MULTISIG_ACCOUNTS: u64 = 10; + public fun get_multisig_accounts_feature(): u64 { MULTISIG_ACCOUNTS } + public fun multisig_accounts_enabled(): bool acquires Features { + is_enabled(MULTISIG_ACCOUNTS) + } + + /// Whether delegation pools are enabled. + /// Lifetime: transient + const DELEGATION_POOLS: u64 = 11; + public fun get_delegation_pools_feature(): u64 { DELEGATION_POOLS } + public fun delegation_pools_enabled(): bool acquires Features { + is_enabled(DELEGATION_POOLS) + } + + /// Whether generic algebra basic operation support in `crypto_algebra.move` are enabled. + /// + /// Lifetime: transient + const CRYPTOGRAPHY_ALGEBRA_NATIVES: u64 = 12; + + public fun get_cryptography_algebra_natives_feature(): u64 { CRYPTOGRAPHY_ALGEBRA_NATIVES } + + public fun cryptography_algebra_enabled(): bool acquires Features { + is_enabled(CRYPTOGRAPHY_ALGEBRA_NATIVES) + } + + /// Whether the generic algebra implementation for BLS12381 operations are enabled. + /// + /// Lifetime: transient + const BLS12_381_STRUCTURES: u64 = 13; + + public fun get_bls12_381_strutures_feature(): u64 { BLS12_381_STRUCTURES } + + public fun bls12_381_structures_enabled(): bool acquires Features { + is_enabled(BLS12_381_STRUCTURES) + } + + /// Whether native_public_key_validate aborts when a public key of the wrong length is given + /// Lifetime: ephemeral + const ED25519_PUBKEY_VALIDATE_RETURN_FALSE_WRONG_LENGTH: u64 = 14; + + /// Whether struct constructors are enabled + /// + /// Lifetime: transient + const STRUCT_CONSTRUCTORS: u64 = 15; + + /// Whether reward rate decreases periodically. + /// Lifetime: transient + const PERIODICAL_REWARD_RATE_DECREASE: u64 = 16; + + public fun get_periodical_reward_rate_decrease_feature(): u64 { PERIODICAL_REWARD_RATE_DECREASE } + + public fun periodical_reward_rate_decrease_enabled(): bool acquires Features { + is_enabled(PERIODICAL_REWARD_RATE_DECREASE) + } + + /// Whether enable paritial governance voting on aptos_governance. + /// Lifetime: transient + const PARTIAL_GOVERNANCE_VOTING: u64 = 17; + + public fun get_partial_governance_voting(): u64 { PARTIAL_GOVERNANCE_VOTING } + + public fun partial_governance_voting_enabled(): bool acquires Features { + is_enabled(PARTIAL_GOVERNANCE_VOTING) + } + + /// Charge invariant violation error. + /// Lifetime: transient + const CHARGE_INVARIANT_VIOLATION: u64 = 20; + + /// Whether enable paritial governance voting on delegation_pool. + /// Lifetime: transient + const DELEGATION_POOL_PARTIAL_GOVERNANCE_VOTING: u64 = 21; + + public fun get_delegation_pool_partial_governance_voting(): u64 { DELEGATION_POOL_PARTIAL_GOVERNANCE_VOTING } + + public fun delegation_pool_partial_governance_voting_enabled(): bool acquires Features { + is_enabled(DELEGATION_POOL_PARTIAL_GOVERNANCE_VOTING) + } + + /// Whether alternate gas payer is supported + /// Lifetime: transient + const FEE_PAYER_ENABLED: u64 = 22; + + public fun fee_payer_enabled(): bool acquires Features { + is_enabled(FEE_PAYER_ENABLED) + } + + /// Whether enable MOVE functions to call create_auid method to create AUIDs. + /// Lifetime: transient + const APTOS_UNIQUE_IDENTIFIERS: u64 = 23; + + public fun get_auids(): u64 { APTOS_UNIQUE_IDENTIFIERS } + + public fun auids_enabled(): bool acquires Features { + is_enabled(APTOS_UNIQUE_IDENTIFIERS) + } + + /// Whether the Bulletproofs zero-knowledge range proof module is enabled, and the related native function is + /// available. This is needed because of the introduction of a new native function. + /// Lifetime: transient + const BULLETPROOFS_NATIVES: u64 = 24; + public fun get_bulletproofs_feature(): u64 { BULLETPROOFS_NATIVES } + + public fun bulletproofs_enabled(): bool acquires Features { + is_enabled(BULLETPROOFS_NATIVES) + } + + /// Fix the native formatter for signer. + /// Lifetime: transient + const SIGNER_NATIVE_FORMAT_FIX: u64 = 25; + + public fun get_signer_native_format_fix_feature(): u64 { SIGNER_NATIVE_FORMAT_FIX } + + public fun signer_native_format_fix_enabled(): bool acquires Features { + is_enabled(SIGNER_NATIVE_FORMAT_FIX) + } + + /// Whether emit function in `event.move` are enabled for module events. + /// + /// Lifetime: transient + const MODULE_EVENT: u64 = 26; + + public fun get_module_event_feature(): u64 { MODULE_EVENT } + + public fun module_event_enabled(): bool acquires Features { + is_enabled(MODULE_EVENT) + } + + /// Whether the fix for a counting bug in the script path of the signature checker pass is enabled. + /// Lifetime: transient + const SIGNATURE_CHECKER_V2_SCRIPT_FIX: u64 = 29; + + /// Whether the aggregator snapshots feature is enabled. + /// Lifetime: transient + const AGGREGATOR_SNAPSHOTS: u64 = 30; + + public fun get_aggregator_snapshots_feature(): u64 { AGGREGATOR_SNAPSHOTS } + + public fun aggregator_snapshots_enabled(): bool acquires Features { + is_enabled(AGGREGATOR_SNAPSHOTS) + } + + // ============================================================================================ + // Feature Flag Implementation + + /// The provided signer has not a framework address. + const EFRAMEWORK_SIGNER_NEEDED: u64 = 1; + + /// The enabled features, represented by a bitset stored on chain. + struct Features has key { + features: vector, + } + + /// Function to enable and disable features. Can only be called by a signer of @std. + public fun change_feature_flags(framework: &signer, enable: vector, disable: vector) + acquires Features { + assert!(signer::address_of(framework) == @std, error::permission_denied(EFRAMEWORK_SIGNER_NEEDED)); + if (!exists(@std)) { + move_to(framework, Features { features: vector[] }) + }; + let features = &mut borrow_global_mut(@std).features; + vector::for_each_ref(&enable, |feature| { + set(features, *feature, true); + }); + vector::for_each_ref(&disable, |feature| { + set(features, *feature, false); + }); + } + + /// Check whether the feature is enabled. + fun is_enabled(feature: u64): bool acquires Features { + exists(@std) && + contains(&borrow_global(@std).features, feature) + } + + /// Helper to include or exclude a feature flag. + fun set(features: &mut vector, feature: u64, include: bool) { + let byte_index = feature / 8; + let bit_mask = 1 << ((feature % 8) as u8); + while (vector::length(features) <= byte_index) { + vector::push_back(features, 0) + }; + let entry = vector::borrow_mut(features, byte_index); + if (include) + *entry = *entry | bit_mask + else + *entry = *entry & (0xff ^ bit_mask) + } + + /// Helper to check whether a feature flag is enabled. + fun contains(features: &vector, feature: u64): bool { + let byte_index = feature / 8; + let bit_mask = 1 << ((feature % 8) as u8); + byte_index < vector::length(features) && (*vector::borrow(features, byte_index) & bit_mask) != 0 + } + + #[test] + fun test_feature_sets() { + let features = vector[]; + set(&mut features, 1, true); + set(&mut features, 5, true); + set(&mut features, 17, true); + set(&mut features, 23, true); + assert!(contains(&features, 1), 0); + assert!(contains(&features, 5), 1); + assert!(contains(&features, 17), 2); + assert!(contains(&features, 23), 3); + set(&mut features, 5, false); + set(&mut features, 17, false); + assert!(contains(&features, 1), 0); + assert!(!contains(&features, 5), 1); + assert!(!contains(&features, 17), 2); + assert!(contains(&features, 23), 3); + } + + #[test(fx = @std)] + fun test_change_feature_txn(fx: signer) acquires Features { + change_feature_flags(&fx, vector[1, 9, 23], vector[]); + assert!(is_enabled(1), 1); + assert!(is_enabled(9), 2); + assert!(is_enabled(23), 3); + change_feature_flags(&fx, vector[17], vector[9]); + assert!(is_enabled(1), 1); + assert!(!is_enabled(9), 2); + assert!(is_enabled(17), 3); + assert!(is_enabled(23), 4); + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/fixed_point32.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/fixed_point32.move new file mode 100644 index 0000000..96409a9 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/fixed_point32.move @@ -0,0 +1,295 @@ +/// Defines a fixed-point numeric type with a 32-bit integer part and +/// a 32-bit fractional part. + +module std::fixed_point32 { + + /// 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. This is a binary representation, so decimal + /// values may not be exactly representable, but it provides more + /// than 9 decimal digits of precision both before and after the + /// decimal point (18 digits total). For comparison, double precision + /// floating-point has less than 16 decimal digits of precision, so + /// be careful about using floating-point to convert these values to + /// decimal. + struct FixedPoint32 has copy, drop, store { value: u64 } + + const MAX_U64: u128 = 18446744073709551615; + + /// The denominator provided was zero + const EDENOMINATOR: u64 = 0x10001; + /// The quotient value would be too large to be held in a `u64` + const EDIVISION: u64 = 0x20002; + /// The multiplied value would be too large to be held in a `u64` + const EMULTIPLICATION: u64 = 0x20003; + /// A division by zero was encountered + const EDIVISION_BY_ZERO: u64 = 0x10004; + /// The computed ratio when converting to a `FixedPoint32` would be unrepresentable + const ERATIO_OUT_OF_RANGE: u64 = 0x20005; + + /// 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, EMULTIPLICATION); + (product as u64) + } + spec multiply_u64 { + pragma opaque; + 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 EMULTIPLICATION; + } + 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, 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, EDIVISION); + // the value may be too large, which will cause the cast to fail + // with an arithmetic error. + (quotient as u64) + } + spec divide_u64 { + pragma opaque; + include DivideAbortsIf; + ensures result == spec_divide_u64(val, divisor); + } + spec schema DivideAbortsIf { + val: num; + divisor: FixedPoint32; + aborts_if divisor.value == 0 with EDIVISION_BY_ZERO; + aborts_if spec_divide_u64(val, divisor) > MAX_U64 with EDIVISION; + } + 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. Calling this function should be preferred + /// for using `Self::create_from_raw_value` which is also available. + /// This will abort if the denominator is zero. It will also + /// abort if the numerator is nonzero and the ratio is not in the range + /// 2^-32 .. 2^32-1. When specifying decimal fractions, be careful about + /// rounding errors: if you round to display N digits after the decimal + /// point, you can use a denominator of 10^N to avoid numbers where the + /// very small imprecision in the binary representation could change the + /// rounding, e.g., 0.0125 will round down to 0.012 instead of up to 0.013. + 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, EDENOMINATOR); + let quotient = scaled_numerator / scaled_denominator; + assert!(quotient != 0 || numerator == 0, 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, ERATIO_OUT_OF_RANGE); + FixedPoint32 { value: (quotient as u64) } + } + spec create_from_rational { + pragma opaque; + include CreateFromRationalAbortsIf; + ensures result == spec_create_from_rational(numerator, denominator); + } + spec schema CreateFromRationalAbortsIf { + numerator: u64; + denominator: u64; + let scaled_numerator = (numerator as u128)<< 64; + let scaled_denominator = (denominator as u128) << 32; + let quotient = scaled_numerator / scaled_denominator; + aborts_if scaled_denominator == 0 with EDENOMINATOR; + aborts_if quotient == 0 && scaled_numerator != 0 with ERATIO_OUT_OF_RANGE; + aborts_if quotient > MAX_U64 with ERATIO_OUT_OF_RANGE; + } + spec fun spec_create_from_rational(numerator: num, denominator: num): FixedPoint32 { + FixedPoint32{value: (numerator << 64) / (denominator << 32)} + } + + /// Create a fixedpoint value from a raw value. + 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 + } + + /// Returns true if the ratio is zero. + public fun is_zero(num: FixedPoint32): bool { + num.value == 0 + } + + /// Returns the smaller of the two FixedPoint32 numbers. + public fun min(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + spec min { + pragma opaque; + aborts_if false; + ensures result == spec_min(num1, num2); + } + spec fun spec_min(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + + /// Returns the larger of the two FixedPoint32 numbers. + public fun max(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + spec max { + pragma opaque; + aborts_if false; + ensures result == spec_max(num1, num2); + } + spec fun spec_max(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + + /// Create a fixedpoint value from a u64 value. + public fun create_from_u64(val: u64): FixedPoint32 { + let value = (val as u128) << 32; + assert!(value <= MAX_U64, ERATIO_OUT_OF_RANGE); + FixedPoint32 {value: (value as u64)} + } + spec create_from_u64 { + pragma opaque; + include CreateFromU64AbortsIf; + ensures result == spec_create_from_u64(val); + } + spec schema CreateFromU64AbortsIf { + val: num; + let scaled_value = (val as u128) << 32; + aborts_if scaled_value > MAX_U64; + } + spec fun spec_create_from_u64(val: num): FixedPoint32 { + FixedPoint32 {value: val << 32} + } + + /// Returns the largest integer less than or equal to a given number. + public fun floor(num: FixedPoint32): u64 { + num.value >> 32 + } + spec floor { + pragma opaque; + aborts_if false; + ensures result == spec_floor(num); + } + spec fun spec_floor(val: FixedPoint32): u64 { + let fractional = val.value % (1 << 32); + if (fractional == 0) { + val.value >> 32 + } else { + (val.value - fractional) >> 32 + } + } + + /// Rounds up the given FixedPoint32 to the next largest integer. + public fun ceil(num: FixedPoint32): u64 { + let floored_num = floor(num) << 32; + if (num.value == floored_num) { + return floored_num >> 32 + }; + let val = ((floored_num as u128) + (1 << 32)); + (val >> 32 as u64) + } + spec ceil { + pragma verify_duration_estimate = 120; + pragma opaque; + aborts_if false; + ensures result == spec_ceil(num); + } + spec fun spec_ceil(val: FixedPoint32): u64 { + let fractional = val.value % (1 << 32); + let one = 1 << 32; + if (fractional == 0) { + val.value >> 32 + } else { + (val.value - fractional + one) >> 32 + } + } + + /// Returns the value of a FixedPoint32 to the nearest integer. + public fun round(num: FixedPoint32): u64 { + let floored_num = floor(num) << 32; + let boundary = floored_num + ((1 << 32) / 2); + if (num.value < boundary) { + floored_num >> 32 + } else { + ceil(num) + } + } + spec round { + pragma verify_duration_estimate = 120; + pragma opaque; + aborts_if false; + ensures result == spec_round(num); + } + spec fun spec_round(val: FixedPoint32): u64 { + let fractional = val.value % (1 << 32); + let boundary = (1 << 32) / 2; + let one = 1 << 32; + if (fractional < boundary) { + (val.value - fractional) >> 32 + } else { + (val.value - fractional + one) >> 32 + } + } + + // **************** SPECIFICATIONS **************** + + spec module {} // switch documentation context to module level + + spec module { + pragma aborts_if_is_strict; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/hash.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/hash.move new file mode 100644 index 0000000..daadc4e --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/hash.move @@ -0,0 +1,8 @@ +/// Module which defines SHA hashes for byte vectors. +/// +/// The functions in this module are natively declared both in the Move runtime +/// as in the Move prover's prelude. +module std::hash { + native public fun sha2_256(data: vector): vector; + native public fun sha3_256(data: vector): vector; +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/option.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/option.move new file mode 100644 index 0000000..1793abf --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/option.move @@ -0,0 +1,356 @@ +/// This module defines the Option type and its methods to represent and handle an optional value. +module std::option { + use std::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 = 0x40000; + /// 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 = 0x40001; + /// Cannot construct an option from a vector with 2 or more elements. + const EOPTION_VEC_TOO_LONG: u64 = 0x40002; + + /// 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) } + } + + public fun from_vec(vec: vector): Option { + assert!(vector::length(&vec) <= 1, EOPTION_VEC_TOO_LONG); + Option { vec } + } + + spec from_vec { + aborts_if vector::length(vec) > 1; + } + + /// 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 == spec_is_none(t); + } + spec fun spec_is_none(t: Option): bool { + vector::is_empty(t.vec) + } + + /// 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 == spec_is_some(t); + } + spec fun spec_is_some(t: Option): bool { + !vector::is_empty(t.vec) + } + + /// 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), EOPTION_NOT_SET); + vector::borrow(&t.vec, 0) + } + spec borrow { + pragma opaque; + include AbortsIfNone; + ensures result == spec_borrow(t); + } + spec fun spec_borrow(t: Option): Element { + t.vec[0] + } + + /// 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 (spec_is_some(t)) spec_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 (spec_is_some(t)) spec_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 EOPTION_IS_SET + } + spec fill { + pragma opaque; + aborts_if spec_is_some(t) with EOPTION_IS_SET; + ensures spec_is_some(t); + ensures spec_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), EOPTION_NOT_SET); + vector::pop_back(&mut t.vec) + } + spec extract { + pragma opaque; + include AbortsIfNone; + ensures result == spec_borrow(old(t)); + ensures spec_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), EOPTION_NOT_SET); + vector::borrow_mut(&mut t.vec, 0) + } + spec borrow_mut { + include AbortsIfNone; + ensures result == spec_borrow(t); + ensures t == old(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), 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 == spec_borrow(old(t)); + ensures spec_is_some(t); + ensures spec_borrow(t) == e; + } + + /// Swap the old value inside `t` with `e` and return the old value; + /// or if there is no old value, fill it with `e`. + /// Different from swap(), swap_or_fill() allows for `t` not holding a value. + public fun swap_or_fill(t: &mut Option, e: Element): Option { + let vec_ref = &mut t.vec; + let old_value = if (vector::is_empty(vec_ref)) none() + else some(vector::pop_back(vec_ref)); + vector::push_back(vec_ref, e); + old_value + } + spec swap_or_fill { + pragma opaque; + aborts_if false; + ensures result == old(t); + ensures spec_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 (spec_is_some(t)) spec_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), 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 == spec_borrow(t); + } + + /// Unpack `t` + /// Aborts if `t` holds a value + public fun destroy_none(t: Option) { + assert!(is_none(&t), EOPTION_IS_SET); + let Option { vec } = t; + vector::destroy_empty(vec) + } + spec destroy_none { + pragma opaque; + aborts_if spec_is_some(t) with EOPTION_IS_SET; + } + + /// Convert `t` into a vector of length 1 if it is `Some`, + /// and an empty vector otherwise + public fun to_vec(t: Option): vector { + let Option { vec } = t; + vec + } + spec to_vec { + pragma opaque; + aborts_if false; + ensures result == t.vec; + } + /// Apply the function to the optional element, consuming it. Does nothing if no value present. + public inline fun for_each(o: Option, f: |Element|) { + if (is_some(&o)) { + f(destroy_some(o)) + } else { + destroy_none(o) + } + } + + /// Apply the function to the optional element reference. Does nothing if no value present. + public inline fun for_each_ref(o: &Option, f: |&Element|) { + if (is_some(o)) { + f(borrow(o)) + } + } + + /// Apply the function to the optional element reference. Does nothing if no value present. + public inline fun for_each_mut(o: &mut Option, f: |&mut Element|) { + if (is_some(o)) { + f(borrow_mut(o)) + } + } + + /// Folds the function over the optional element. + public inline fun fold( + o: Option, + init: Accumulator, + f: |Accumulator,Element|Accumulator + ): Accumulator { + if (is_some(&o)) { + f(init, destroy_some(o)) + } else { + destroy_none(o); + init + } + } + + /// Maps the content of an option. + public inline fun map(o: Option, f: |Element|OtherElement): Option { + if (is_some(&o)) { + some(f(destroy_some(o))) + } else { + destroy_none(o); + none() + } + } + + /// Maps the content of an option without destroying the original option. + public inline fun map_ref( + o: &Option, f: |&Element|OtherElement): Option { + if (is_some(o)) { + some(f(borrow(o))) + } else { + none() + } + } + + /// Filters the content of an option + public inline fun filter(o: Option, f: |&Element|bool): Option { + if (is_some(&o) && f(borrow(&o))) { + o + } else { + none() + } + } + + /// Returns true if the option contains an element which satisfies predicate. + public inline fun any(o: &Option, p: |&Element|bool): bool { + is_some(o) && p(borrow(o)) + } + + /// Utility function to destroy an option that is not droppable. + public inline fun destroy(o: Option, d: |Element|) { + let vec = to_vec(o); + vector::destroy(vec, |e| d(e)); + } + + 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 spec_is_none(t) with EOPTION_NOT_SET; + } +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/signer.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/signer.move new file mode 100644 index 0000000..a4d8058 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/signer.move @@ -0,0 +1,21 @@ +module std::signer { + /// Borrows the address of the signer + /// Conceptually, you can think of the `signer` as being a struct wrapper arround an + /// address + /// ``` + /// struct signer has drop { 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) + } + + /// Return true only if `s` is a transaction signer. This is a spec function only available in spec. + spec native fun is_txn_signer(s: signer): bool; + + /// Return true only if `a` is a transaction signer address. This is a spec function only available in spec. + spec native fun is_txn_signer_addr(a: address): bool; +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/string.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/string.move new file mode 100644 index 0000000..6a2ca69 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/string.move @@ -0,0 +1,93 @@ +/// The `string` module defines the `String` type which represents UTF8 encoded strings. +module std::string { + use std::vector; + use std::option::{Self, Option}; + + /// An invalid UTF8 encoding. + const EINVALID_UTF8: u64 = 1; + + /// Index out of range. + const EINVALID_INDEX: u64 = 2; + + /// A `String` holds a sequence of bytes which is guaranteed to be in utf8 format. + struct String has copy, drop, store { + bytes: vector, + } + + /// Creates a new string from a sequence of bytes. Aborts if the bytes do not represent valid utf8. + public fun utf8(bytes: vector): String { + assert!(internal_check_utf8(&bytes), EINVALID_UTF8); + String{bytes} + } + + /// Tries to create a new string from a sequence of bytes. + public fun try_utf8(bytes: vector): Option { + if (internal_check_utf8(&bytes)) { + option::some(String{bytes}) + } else { + option::none() + } + } + + /// Returns a reference to the underlying byte vector. + public fun bytes(s: &String): &vector { + &s.bytes + } + + /// Checks whether this string is empty. + public fun is_empty(s: &String): bool { + vector::is_empty(&s.bytes) + } + + /// Returns the length of this string, in bytes. + public fun length(s: &String): u64 { + vector::length(&s.bytes) + } + + /// Appends a string. + public fun append(s: &mut String, r: String) { + vector::append(&mut s.bytes, r.bytes) + } + + /// Appends bytes which must be in valid utf8 format. + public fun append_utf8(s: &mut String, bytes: vector) { + append(s, utf8(bytes)) + } + + /// Insert the other string at the byte index in given string. The index must be at a valid utf8 char + /// boundary. + public fun insert(s: &mut String, at: u64, o: String) { + let bytes = &s.bytes; + assert!(at <= vector::length(bytes) && internal_is_char_boundary(bytes, at), EINVALID_INDEX); + let l = length(s); + let front = sub_string(s, 0, at); + let end = sub_string(s, at, l); + append(&mut front, o); + append(&mut front, end); + *s = front; + } + + /// Returns a sub-string using the given byte indices, where `i` is the first byte position and `j` is the start + /// of the first byte not included (or the length of the string). The indices must be at valid utf8 char boundaries, + /// guaranteeing that the result is valid utf8. + public fun sub_string(s: &String, i: u64, j: u64): String { + let bytes = &s.bytes; + let l = vector::length(bytes); + assert!( + j <= l && i <= j && internal_is_char_boundary(bytes, i) && internal_is_char_boundary(bytes, j), + EINVALID_INDEX + ); + String { bytes: internal_sub_string(bytes, i, j) } + } + + /// Computes the index of the first occurrence of a string. Returns `length(s)` if no occurrence found. + public fun index_of(s: &String, r: &String): u64 { + internal_index_of(&s.bytes, &r.bytes) + } + + // Native API + public native fun internal_check_utf8(v: &vector): bool; + native fun internal_is_char_boundary(v: &vector, i: u64): bool; + native fun internal_sub_string(v: &vector, i: u64, j: u64): vector; + native fun internal_index_of(v: &vector, r: &vector): u64; +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/vector.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/vector.move new file mode 100644 index 0000000..8857376 --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/dependencies/MoveStdlib/vector.move @@ -0,0 +1,633 @@ +/// 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 `singleton_vector`. 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 std::vector { + /// The index into the vector is out of bounds + const EINDEX_OUT_OF_BOUNDS: u64 = 0x20000; + + /// The index into the vector is out of bounds + const EINVALID_RANGE: u64 = 0x20001; + + /// The length of the vectors are not equal. + const EVECTORS_LENGTH_MISMATCH: u64 = 0x20002; + + #[bytecode_instruction] + /// Create an empty vector. + native public fun empty(): vector; + + #[bytecode_instruction] + /// Return the length of the vector. + native public fun length(v: &vector): u64; + + #[bytecode_instruction] + /// 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): ∈ + + #[bytecode_instruction] + /// Add element `e` to the end of the vector `v`. + native public fun push_back(v: &mut vector, e: Element); + + #[bytecode_instruction] + /// 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; + + #[bytecode_instruction] + /// Pop an element from the end of vector `v`. + /// Aborts if `v` is empty. + native public fun pop_back(v: &mut vector): Element; + + #[bytecode_instruction] + /// Destroy the vector `v`. + /// Aborts if `v` is not empty. + native public fun destroy_empty(v: vector); + + #[bytecode_instruction] + /// 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 { + aborts_if false; + ensures result == vec(e); + } + + /// Reverses the order of the elements in the vector `v` in place. + public fun reverse(v: &mut vector) { + let len = length(v); + reverse_slice(v, 0, len); + } + + spec reverse { + pragma intrinsic = true; + } + + /// Reverses the order of the elements [left, right) in the vector `v` in place. + public fun reverse_slice(v: &mut vector, left: u64, right: u64) { + assert!(left <= right, EINVALID_RANGE); + if (left == right) return; + right = right - 1; + while (left < right) { + swap(v, left, right); + left = left + 1; + right = right - 1; + } + } + spec reverse_slice { + pragma intrinsic = true; + } + + /// Pushes all of the elements of the `other` vector into the `lhs` vector. + public fun append(lhs: &mut vector, other: vector) { + reverse(&mut other); + reverse_append(lhs, other); + } + spec append { + pragma intrinsic = true; + } + spec is_empty { + pragma intrinsic = true; + } + + /// Pushes all of the elements of the `other` vector into the `lhs` vector. + public fun reverse_append(lhs: &mut vector, other: vector) { + let len = length(&other); + while (len > 0) { + push_back(lhs, pop_back(&mut other)); + len = len - 1; + }; + destroy_empty(other); + } + spec reverse_append { + pragma intrinsic = true; + } + + /// Trim a vector to a smaller size, returning the evicted elements in order + public fun trim(v: &mut vector, new_len: u64): vector { + let res = trim_reverse(v, new_len); + reverse(&mut res); + res + } + spec trim { + pragma intrinsic = true; + } + + /// Trim a vector to a smaller size, returning the evicted elements in reverse order + public fun trim_reverse(v: &mut vector, new_len: u64): vector { + let len = length(v); + assert!(new_len <= len, EINDEX_OUT_OF_BOUNDS); + let result = empty(); + while (new_len < len) { + push_back(&mut result, pop_back(v)); + len = len - 1; + }; + result + } + spec trim_reverse { + 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; + } + + /// Return `(true, i)` if there's an element that matches the predicate. If there are multiple elements that match + /// the predicate, only the index of the first one is returned. + /// Otherwise, returns `(false, 0)`. + public inline fun find(v: &vector, f: |&Element|bool): (bool, u64) { + let find = false; + let found_index = 0; + let i = 0; + let len = length(v); + while (i < len) { + // Cannot call return in an inline function so we need to resort to break here. + if (f(borrow(v, i))) { + find = true; + found_index = i; + break + }; + i = i + 1; + }; + (find, found_index) + } + + /// Insert a new element at position 0 <= i <= length, using O(length - i) time. + /// Aborts if out of bounds. + public fun insert(v: &mut vector, i: u64, e: Element) { + let len = length(v); + assert!(i <= len, EINDEX_OUT_OF_BOUNDS); + push_back(v, e); + while (i < len) { + swap(v, i, len); + i = i + 1; + }; + } + spec insert { + 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; + + len = len - 1; + while (i < len) swap(v, i, { i = i + 1; i }); + pop_back(v) + } + spec remove { + pragma intrinsic = true; + } + + /// Remove the first occurrence of a given value in the vector `v` and return it in a vector, shifting all + /// subsequent elements. + /// This is O(n) and preserves ordering of elements in the vector. + /// This returns an empty vector if the value isn't present in the vector. + /// Note that this cannot return an option as option uses vector and there'd be a circular dependency between option + /// and vector. + public fun remove_value(v: &mut vector, val: &Element): vector { + // This doesn't cost a O(2N) run time as index_of scans from left to right and stops when the element is found, + // while remove would continue from the identified index to the end of the vector. + let (found, index) = index_of(v, val); + if (found) { + vector[remove(v, index)] + } else { + vector[] + } + } + spec remove_value { + pragma intrinsic = true; + } + + /// 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 { + assert!(!is_empty(v), EINDEX_OUT_OF_BOUNDS); + let last_idx = length(v) - 1; + swap(v, i, last_idx); + pop_back(v) + } + spec swap_remove { + pragma intrinsic = true; + } + + /// Apply the function to each element in the vector, consuming it. + public inline fun for_each(v: vector, f: |Element|) { + reverse(&mut v); // We need to reverse the vector to consume it efficiently + for_each_reverse(v, |e| f(e)); + } + + /// Apply the function to each element in the vector, consuming it. + public inline fun for_each_reverse(v: vector, f: |Element|) { + let len = length(&v); + while (len > 0) { + f(pop_back(&mut v)); + len = len - 1; + }; + destroy_empty(v) + } + + /// Apply the function to a reference of each element in the vector. + public inline fun for_each_ref(v: &vector, f: |&Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(borrow(v, i)); + i = i + 1 + } + } + + /// Apply the function to each pair of elements in the two given vectors, consuming them. + public inline fun zip(v1: vector, v2: vector, f: |Element1, Element2|) { + // We need to reverse the vectors to consume it efficiently + reverse(&mut v1); + reverse(&mut v2); + zip_reverse(v1, v2, |e1, e2| f(e1, e2)); + } + + /// Apply the function to each pair of elements in the two given vectors in the reverse order, consuming them. + /// This errors out if the vectors are not of the same length. + public inline fun zip_reverse( + v1: vector, + v2: vector, + f: |Element1, Element2|, + ) { + let len = length(&v1); + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == length(&v2), 0x20002); + while (len > 0) { + f(pop_back(&mut v1), pop_back(&mut v2)); + len = len - 1; + }; + destroy_empty(v1); + destroy_empty(v2); + } + + /// Apply the function to the references of each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_ref( + v1: &vector, + v2: &vector, + f: |&Element1, &Element2|, + ) { + let len = length(v1); + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == length(v2), 0x20002); + let i = 0; + while (i < len) { + f(borrow(v1, i), borrow(v2, i)); + i = i + 1 + } + } + + /// Apply the function to a reference of each element in the vector with its index. + public inline fun enumerate_ref(v: &vector, f: |u64, &Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(i, borrow(v, i)); + i = i + 1; + }; + } + + /// Apply the function to a mutable reference to each element in the vector. + public inline fun for_each_mut(v: &mut vector, f: |&mut Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(borrow_mut(v, i)); + i = i + 1 + } + } + + /// Apply the function to mutable references to each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_mut( + v1: &mut vector, + v2: &mut vector, + f: |&mut Element1, &mut Element2|, + ) { + let i = 0; + let len = length(v1); + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == length(v2), 0x20002); + while (i < len) { + f(borrow_mut(v1, i), borrow_mut(v2, i)); + i = i + 1 + } + } + + /// Apply the function to a mutable reference of each element in the vector with its index. + public inline fun enumerate_mut(v: &mut vector, f: |u64, &mut Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(i, borrow_mut(v, i)); + i = i + 1; + }; + } + + /// Fold the function over the elements. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(f(f(0, 1), 2), 3)` + public inline fun fold( + v: vector, + init: Accumulator, + f: |Accumulator,Element|Accumulator + ): Accumulator { + let accu = init; + for_each(v, |elem| accu = f(accu, elem)); + accu + } + + /// Fold right like fold above but working right to left. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(1, f(2, f(3, 0)))` + public inline fun foldr( + v: vector, + init: Accumulator, + f: |Element, Accumulator|Accumulator + ): Accumulator { + let accu = init; + for_each_reverse(v, |elem| accu = f(elem, accu)); + accu + } + + /// Map the function over the references of the elements of the vector, producing a new vector without modifying the + /// original vector. + public inline fun map_ref( + v: &vector, + f: |&Element|NewElement + ): vector { + let result = vector[]; + for_each_ref(v, |elem| push_back(&mut result, f(elem))); + result + } + + /// Map the function over the references of the element pairs of two vectors, producing a new vector from the return + /// values without modifying the original vectors. + public inline fun zip_map_ref( + v1: &vector, + v2: &vector, + f: |&Element1, &Element2|NewElement + ): vector { + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(length(v1) == length(v2), 0x20002); + + let result = vector[]; + zip_ref(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + /// Map the function over the elements of the vector, producing a new vector. + public inline fun map( + v: vector, + f: |Element|NewElement + ): vector { + let result = vector[]; + for_each(v, |elem| push_back(&mut result, f(elem))); + result + } + + /// Map the function over the element pairs of the two vectors, producing a new vector. + public inline fun zip_map( + v1: vector, + v2: vector, + f: |Element1, Element2|NewElement + ): vector { + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(length(&v1) == length(&v2), 0x20002); + + let result = vector[]; + zip(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + /// Filter the vector using the boolean function, removing all elements for which `p(e)` is not true. + public inline fun filter( + v: vector, + p: |&Element|bool + ): vector { + let result = vector[]; + for_each(v, |elem| { + if (p(&elem)) push_back(&mut result, elem); + }); + result + } + + /// Partition, sorts all elements for which pred is true to the front. + /// Preserves the relative order of the elements for which pred is true, + /// BUT NOT for the elements for which pred is false. + public inline fun partition( + v: &mut vector, + pred: |&Element|bool + ): u64 { + let i = 0; + let len = length(v); + while (i < len) { + if (!pred(borrow(v, i))) break; + i = i + 1; + }; + let p = i; + i = i + 1; + while (i < len) { + if (pred(borrow(v, i))) { + swap(v, p, i); + p = p + 1; + }; + i = i + 1; + }; + p + } + + /// rotate(&mut [1, 2, 3, 4, 5], 2) -> [3, 4, 5, 1, 2] in place, returns the split point + /// ie. 3 in the example above + public fun rotate( + v: &mut vector, + rot: u64 + ): u64 { + let len = length(v); + rotate_slice(v, 0, rot, len) + } + spec rotate { + pragma intrinsic = true; + } + + /// Same as above but on a sub-slice of an array [left, right) with left <= rot <= right + /// returns the + public fun rotate_slice( + v: &mut vector, + left: u64, + rot: u64, + right: u64 + ): u64 { + reverse_slice(v, left, rot); + reverse_slice(v, rot, right); + reverse_slice(v, left, right); + left + (right - rot) + } + spec rotate_slice { + pragma intrinsic = true; + } + + /// Partition the array based on a predicate p, this routine is stable and thus + /// preserves the relative order of the elements in the two partitions. + public inline fun stable_partition( + v: &mut vector, + p: |&Element|bool + ): u64 { + let len = length(v); + let t = empty(); + let f = empty(); + while (len > 0) { + let e = pop_back(v); + if (p(&e)) { + push_back(&mut t, e); + } else { + push_back(&mut f, e); + }; + len = len - 1; + }; + let pos = length(&t); + reverse_append(v, t); + reverse_append(v, f); + pos + } + + /// Return true if any element in the vector satisfies the predicate. + public inline fun any( + v: &vector, + p: |&Element|bool + ): bool { + let result = false; + let i = 0; + while (i < length(v)) { + result = p(borrow(v, i)); + if (result) { + break + }; + i = i + 1 + }; + result + } + + /// Return true if all elements in the vector satisfy the predicate. + public inline fun all( + v: &vector, + p: |&Element|bool + ): bool { + let result = true; + let i = 0; + while (i < length(v)) { + result = p(borrow(v, i)); + if (!result) { + break + }; + i = i + 1 + }; + result + } + + /// Destroy a vector, just a wrapper around for_each_reverse with a descriptive name + /// when used in the context of destroying a vector. + public inline fun destroy( + v: vector, + d: |Element| + ) { + for_each_reverse(v, |e| d(e)) + } + + // ================================================================= + // Module Specification + + spec module {} // Switch to module documentation context + + /// # Helper Functions + + spec module { + /// Check if `v1` is equal to the result of adding `e` at the end of `v2` + 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` + 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` + 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`. + 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)] + } + + /// Check if `v` contains `e`. + fun spec_contains(v: vector, e: Element): bool { + exists x in v: x == e + } + } + +} diff --git a/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/sakutaro_poem.move b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/sakutaro_poem.move new file mode 100644 index 0000000..7a6eaff --- /dev/null +++ b/packages/contracts/aptos/sakutaro_poem/build/sakutaro_poem/sources/sakutaro_poem.move @@ -0,0 +1,378 @@ +module sakutaro_poem::sakutaro_poem { + use std::bcs; + use std::vector; + use std::option; + use std::hash::sha3_256; + use std::signer::address_of; + use std::string::{Self, String, utf8, append, append_utf8}; + use aptos_framework::account; + use aptos_framework::resource_account; + use aptos_framework::event::{Self, EventHandle}; + use aptos_token::token::{Self, TokenDataId}; + use aptos_token::property_map; + use aptos_std::string_utils::to_string; + use aptos_std::from_bcs; + use sakutaro_poem::base64; + + struct TokenMintingEvent has drop, store { + token_receiver_address: address, + token_data_id: TokenDataId, + } + + struct ModuleData has key { + signer_cap: account::SignerCapability, + token_minting_events: EventHandle, + } + + const EMAX_SUPPLY: u64 = 0; + + const COLLECTION_NAME: vector = b"Sakutaro Poem"; + + const COLLECTION_DESCRIPTION: vector = b"Thirty-nine poems from Sakutaro Hagiwara's late self-selected collection \"Shukumei\" have been inscribed on Blockchain as full-onchain NFTs. The content of this NFT changes depending on the owner."; + + const POEM_TITLES: vector> = vector[ + x"e38182e38182e59bbae38184e6b0b7e38292e7a0b4e381a4e381a6", + x"e88a9de7949fe381aee4b88ae381a7", + x"e8888ce381aee381aae38184e79c9ee79086", + x"e68588e682b2", + x"e7a78be699b4", + x"e999b8e6a98be38292e6b8a1e3828b", + x"e6b699e38190e381bee38197e38184e5a495e69aae", + x"e59cb0e79083e38292e8b7b3e8ba8de38197e381a6", + x"e5a49ce6b1bde8bb8ae381aee7aa93e381a7", + x"e698a5e381aee3818fe3828be69982", + x"e6a5b5e58589e59cb0e696b9e3818be38289", + x"e696b7e6a98b", + x"e9818be591bde381b8e381aee5bf8de8beb1", + x"e5af82e5afa5e381aee5b79de9828a", + x"e888b9e5aea4e3818be38289", + x"e8a898e686b6e38292e68da8e381a6e3828b", + x"e68385e7b792e38288efbc81e38080e5909be381afe6adb8e38289e38196e3828be3818b", + x"e6b8afe381aee99b9ce8b2a8e5ba97e381a7", + x"e98fa1", + x"e78b90", + x"e590b9e99baae381aee4b8ade381a7", + x"e98a83e599a8e5ba97e381aee5898de381a7", + x"e8999ae695b8e381aee8998e", + x"e887aae784b6e381aee4b8ade381a7", + x"e8a7b8e6898be38182e3828be7a9bae99693", + x"e5a4a7e4bd9b", + x"e5aeb6", + x"e9bb92e38184e6b48be58298", + x"e68190e3828de38197e3818de4babae5bda2e88a9de5b185", + x"e9bd92e38292e38282e381a6e3828be6848fe5bf97", + x"e5bbbae7af89e381ae204e6f7374616c676961", + x"e788b6", + x"e695b5", + x"e789a9e8b3aae381aee6849fe68385", + x"e789a9e9ab94", + x"e9be8d", + x"e6a98b", + x"e5b1b1e4b88ae381aee7a588", + x"e688b0e5a0b4e381a7e381aee5b9bbe683b3", + ]; + + const POEM_BODIES: vector> = vector[ + x"e38182e38182e59bbae38184e6b0b7e38292e7a0b4e381a4e381a6e7aa81e980b2e38199e3828be38081e4b880e381a4e381aee5af82e38197e38184e5b886e888b9e38288e38082e38182e381aee9ab98e38184e7a9bae381abe381b2e3828be3818ce381b8e3828be38081e6b5aae6b5aae381aee59bbae9ab94e38197e3819fe58db0e8b1a1e3818be38289e38081e3819de381aee99a94e99ba2e38197e3819fe59cb0e696b9e381aee789a9e4be98e38197e38184e586ace381aee58589e7b79ae3818be38289e38081e38182e381afe3828ce381abe785a4e381bce38191e381a6e8a68be38188e3828be5b08fe38195e381aae9bb92e38184e78db5e9afa8e888b9e38288e38082e5ada4e78da8e381aae792b0e5a283e381aee6b5b7e381abe6bc82e6b38ae38199e3828be888b9e381aee7be85e9879de3818ce38081e4b880e381a4e381aee98bade381a9e381843c727562793e3c72623ee6848fe5bf97e381aee5b096e8a7923c2f72623e3c72703eefbc883c2f72703e3c72743ee383bbe383bbe383bbe383bbe383bb3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee3818ce38081e38182e38182e5a682e4bd95e381abe59bbae38184e586ace381aee6b0b7e38292e7aa81e3818de7a0b4e381a4e381a6e9a980e980b2e38199e3828be38193e381a8e38288e38082", + x"e88ba5e88d89e381aee88abde3818ce8908ce38188e3828be38284e38186e381abe38081e38193e381aee697a5e795b6e3828ae381aee38288e38184e88a9de7949fe381aee4b88ae381a7e381afe38081e6809de683b3e3818ce5be8ce3818be38289e5be8ce3818be38289e381a8e68890e995b7e38197e381a6e3818fe3828be38082e38191e3828ce381a9e38282e3819de3828ce38289e381aee6809de683b3e381afe38081e7a781e381abe381bee381a7e4bd95e381aee4baa4e6b889e3818ce38182e38289e38186e3819ee38082e7a781e381afe3819fe381a0e99d92e7a9bae38292e79cbae38281e381a6e5b185e3819fe38184e38082e38182e381aee892bce5a4a9e381aee5a4a2e381aee4b8ade381abe6bab6e38191e381a6e38197e381bee381b5e38284e38186e381aae38081e38195e38186e38184e381b5e6809de683b3e381aee5b9bbe683b3e381a0e38191e38292e882b2e3818fe381bfe3819fe38184e381aee381a0e38082e7a781e887aae8baabe381aee68385e7b792e381aee5bdb1e381a7e38081e381aae381a4e3818be38197e38184e7b791e999b0e381aee5a4a2e38292e381a4e3818fe3828be38284e38186e381aae38081e3819de3828ce38289e381aee3808ce68385e8aabfe38182e3828be6809de683b3e3808de381a0e38191e38292e8aa9ee3828ae3819fe38184e381aee381a0e38082e7a9bae9a39be381b6e5b08fe9b3a5e38288e38082", + x"e381a8e38182e3828be5b9bbe78788e381aee4b8ade381a7e38081e99d92e799bde38184e99baae381aee9998de3828ae381a4e38282e381a4e381a6e38290e3828be38081e38197e381a5e3818be381aae38197e381a5e3818be381aae699afe889b2e381aee4b8ade381a7e38081e7a781e381afe4b880e381a4e381aee79c9ee79086e38292e381a4e3818be38293e381a0e38082e789a9e8a880e381b5e38193e381a8e381aee381a7e3818de381aae38184e38081e6b0b8e981a0e381abe6b0b8e981a0e381abe38186e38289e682b2e38197e38192e381aae38081e7a781e381afe3808ce8888ce381aee381aae38184e79c9ee79086e3808de38292e6849fe38198e3819fe38082e699afe889b2e381aee38081e5b9bbe78788e381aee38081e99baae381aee381a4e38282e3828be5bdb1e38292e9818ee3818ee58ebbe381a4e381a6e8a18ce3818fe38081e38195e381b3e38197e38184e99d92e78cabe381ae3c727562793e3c72623ee5838f3c2f72623e3c72703eefbc883c2f72703e3c72743ee3818be3819fe381a13c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e3818be38293e38198e3819fe38082", + x"e9a2a8e790b4e381ae3c727562793e3c72623ee98eade9ad82e6a8823c2f72623e3c72703eefbc883c2f72703e3c72743ee3828ce3818fe3828ce38188e382803c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e3818de3818fe38284e38186e381abe38081e586a5e683b3e381aee58e9ae38184e5a381e381aee5bdb1e381a7e38081e99d9ce3818be381abe6b9a7e3818de38182e3818ce381a4e381a6e3818fe3828be9bb92e38184e6849fe68385e38082e68385e685bee381aee5bcb7e38184e683b1e381bfe38292e68a91e381b8e38081e69e9ce695a2e381aae38184e9818be591bde381b8e381aee58f9be98086e38284e38081e4bd95e381a8e38184e381b5e38193e381a8e38282e381aae38184e7949fe6b4bbe381aee69a97e68481e38284e38081e38184e38289e38184e38289e38197e3819fe5bf83e381aee784a6e787a5e38284e38292e5bf98e3828ce38195e3819be38081e5ae89e38289e3818be381aae5ae89e38289e3818be381aae5afa2e887bae381aee4b88ae381a7e38081e99d88e9ad82e381aee6b7b1e381bfe38182e3828be79ca0e3828ae38292e38195e3819de381b5e38284e38186e381aae38081e4b880e381a4e381aee58a9be38182e3828be99d9ce3818be381aae6849fe68385e38082e3819de3828ce381afe7949fe6b4bbe381aee796b2e3828ce3819fe89684e69aaee381abe38081e99fbfe69dbfe381aee9888de38184e38186e381aae3828ae38292e3819fe381a6e3828be38081e5a4a7e3818de381aae5b985e381aee38182e3828be99d9ce3818be381aae6849fe68385e38082e28095e28095e4bd9be99980e381aee69599e381b8e3819fe68588e682b2e381aee593b2e5adb8efbc81", + x"e789a7e5a0b4e381aee7899be3818ce88d89e38292e9a39fe381a4e381a6e38290e3828be381aee38292e381bfe381a6e38081e99691e695a3e38284e680a0e683b0e381aee8b6a3e591b3e38292e8a7a3e38197e381aae38184e381bbe381a9e38081e3819de3828ce381bbe381a93c727562793e3c72623ee8bf91e4bba3e79a84e381abe381aae381a4e381a6e38197e381bee381a4e3819f3c2f72623e3c72703eefbc883c2f72703e3c72743ee383bbe383bbe383bbe383bbe383bbe383bbe383bbe383bbe383bbe383bbe383bb3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee4babae4babae381abe381bee381a7e38081e7a781e381afe38184e3818be381aae3828be69c83e8a9b1e38292e38282e38195e38191e3828be381a7e38182e38289e38186e38082e7a781e381aee8828ce381abe38197e381bfe8bebce38293e381a7e3818fe3828be38081e38193e381aee7a78be697a5e5928ce381aee789a9e580a6e38184e79ca0e3819fe38195e381abe5b0b1e38184e381a6e38081e38193e381aee58fa4e9a2a8e381aae3828be7a781e381aee6809de683b3e381aee68385e8aabfe381abe5b0b1e38184e381a6e38081e38193e381aee4b88ae38282e381afe38284e8aa9ee38289e381aae38184e381a7e38182e38289e38186e38082", + x"e68682e9acb1e381abe6b288e381bfe381aae3818ce38289e38081e381b2e381a8e3828ae5af82e38197e3818fe999b8e6a98be38292e6b8a1e381a4e381a6e8a18ce3818fe38082e3818be381a4e381a6e4bd95e789a9e381abe38195e381b8e5a6a5e58d94e3819be38196e3828be38081e4bd95e789a9e381abe38195e381b8e5ae89e69893e3819be38196e3828be38081e38193e381aee4b880e381a4e381aee6849fe68385e38292e381a9e38193e381b8e8a18ce3818be38186e3818be38082e890bde697a5e381afe59cb0e5b9b3e381abe4bd8ee3818fe38081e792b0e5a283e381afe68092e3828ae381abe78783e38188e381a6e3828be38082e4b880e58887e38292e6868ee683a1e38197e38081e7b289e7a28ee38197e38081e58f9be98086e38197e38081e598b2e7ac91e38197e38081e696ace5a5b8e38197e38081e695b5e684bee38199e3828be38081e38193e381aee4b880e5808be381aee9bb92e38184e5bdb1e38292e3839ee383b3e38388e381abe381a4e381a4e38293e381a7e38081e381b2e381a8e3828ae5af82e38197e3818fe999b8e6a98be38292e6b8a1e381a4e381a6e8a18ce3818fe38082e3818be381aee9ab98e38184e69eb6e7a9bae381aee6a98be38292e8b68ae38188e381a6e38081e381afe3828be3818be381aee5b9bbe78788e381aee5b882e8a197e381abe381bee381a7e38082", + x"e38193e3828ce38289e381aee5a495e69aaee381afe6b699e38190e381bee38197e3818fe38081e7a781e381aee69bb8e9bd8be381abe8a8aae3828ce381a6e3818fe3828be38082e6809de683b3e381afe68385e8aabfe381aee5bdb1e381abe381ace3828ce381a6e38081e6849fe38198e381aee38288e38184e6b8a9e99b85e381aee889b2e59088e38292e5b8b6e381b3e381a6e8a68be38188e3828be38082e38182e38182e38184e3818be381abe4bb8ae381aee7a781e381abe381bee381a7e38081e4b880e381a4e381aee683a0e381bee3828ce3819fe5beb3e381afe381aae38184e3818be38082e4bd95e789a9e381aee58d91e58aa3e381abe38199e38289e38081e4bd95e789a9e381aee8999ae5839ee381abe38199e38289e38081e38182e381b8e381a6e9ab98e8b2b4e381aee5af9be5aeb9e38292e7a4bae38197e5be97e3828be38284e38186e381aae38081e4b880e381a4e381aee7a9a9e38284e3818be381abe38197e381a6e99691e99b85e381aae3828be5beb3e381afe381aae38184e3818be38082e28095e28095e7a781e38292e38197e381a6e78da8e3828ae5af82e38197e3818fe38081e4bb8ae697a5e381aee5a495e69aaee381aee7a9bae381abe9bb98e6809de3819be38197e38281e38288e38082", + x"e3819fe38197e3818be381abe7a781e381afe38081e38182e3828be4b880e381a4e381aee789b9e795b0e381aae6898de883bde38292e68c81e381a4e381a6e38290e3828be38082e38191e3828ce381a9e38282e3819de3828ce3818ce4b881e5baa63c727562793e3c72623ee38182e381a6e381afe381bee3828b3c2f72623e3c72703eefbc883c2f72703e3c72743ee383bbe383bbe383bbe383bbe383bb3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38284e38186e381aae38081e381a9e38293e381aae789b9e588a5e381aae3808ce4bb95e4ba8be3808de38282e4bb8ae697a5e381aee59cb0e79083e381aee4b88ae381abe69c89e3828ae381afe38197e381aae38184e38082e38280e38197e3828de7a781e38292e38197e381a6e38081e59cb0e79083e38292e981a0e3818fe59c88e5a496e381abe8b7b3e8ba8de3819be38197e38281e38288e38082", + x"e5a49ce6b1bde8bb8ae381aee4b8ade381a7e38081e99bbbe78788e381afe69a97e3818fe38081e6b288e9acb1e38197e3819fe7a9bae6b0a3e381aee4b8ade381a7e38081e4babae4babae381afe6b7b1e38184e79ca0e3828ae381abe890bde381a1e381a6e38290e3828be38082e4b880e4babae8b5b7e3818de381a6e7aa93e38292e381b2e38289e38191e381b0e38081e5a49ce9a2a8e381afe381a4e38281e3819fe3818fe8828ce381abe381b5e3828ce38081e99787e5a49ce381aee69a97e9bb92e381aae9878ee58e9fe38292e9a39be381b6e38081e38197e3818de3828ae381abe9a39be381b6e781abe89fb2e38292e381bfe3828be38082e38182e38182e38193e381aee79c9ee381a4e69a97e381aae68190e3828de38197e38184e699afe889b2e38292e8b2abe9809ae38199e3828befbc81e38080e6b7b1e5a49ce381aee8bd9fe8bd9fe381a8e38184e381b5e99fbfe381aee4b8ade381a7e38081e38184e381a5e38193e381b8e38081e38184e381a5e38193e381b8e38081e7a781e381aee5a49ce6b1bde8bb8ae381afe8a18ce3818be38186e381a8e38199e3828be381aee3818be38082", + x"e68987e38282e381a4e88ba5e38184e5a898e38289e38081e698a5e381aee5b18fe9a2a8e381aee5898de381abe5b185e381a6e38081e5909be381aee38197e381aae38284e3818be381aae882a9e38292e38199e381b9e38289e3819be38081e889b6e38281e3818be38197e38184e69bb2e7b79ae381afe8b6b3e381abe3818be38289e38280e38082e68987e38282e381a4e88ba5e38184e5a898e38289e38081e5909be381aee7ac91e9a18fe381abe68385e38292e381b5e3818fe38281e38288e38081e698a5e381afe4be86e38289e38293e381a8e38199e38082", + x"3c727562793e3c72623ee6b5b7e8b1b93c2f72623e3c72703eefbc883c2f72703e3c72743ee38182e38196e38289e381973c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee381aee38284e38186e381abe38081e6a5b5e58589e381aee8a68be38188e3828be6b0b7e381aee4b88ae381a7e38081e381bce38293e38284e3828ae381a8e3808ce887aae58886e38292e5bf98e3828ce381a6e3808de59d90e381a4e381a6e38290e3819fe38184e38082e3819de38193e381abe69982e58aabe3818ce38199e3818ee58ebbe381a4e381a6e8a18ce3818fe38082e6999de5a49ce381aee381aae38184e6a5b5e58589e59cb0e696b9e381aee38081e38184e381a4e38282e69aaee3828ce696b9e381aee38284e38186e381aae58589e7b79ae3818ce38081e9888de3818fe682b2e38197e38192e381abe5b9bde6bb85e38199e3828be381a8e38193e3828de38082e38182e38182e3819de381aee981a0e38184e58c97e6a5b5e59c88e381aee6b0b7e381aee4b88ae381a7e38081e381bce38293e38284e3828ae381a8e6b5b7e8b1b9e381aee38284e38186e381abe59d90e381a4e381a6e5b185e3819fe38184e38082e6b0b8e981a0e381abe38081e6b0b8e981a0e381abe38081e887aae58886e38292e5bf98e3828ce381a6e38081e6809de6839fe381aee381bbe381aee69a97e38184e6b5b7e381abe6b5aee381b6e38081e4b880e381a4e381aee4be98e38197e38184e5b9bbe8b1a1e38292e79cbae38281e381a6e5b185e3819fe38184e381aee381a7e38199e38082", + x"e5a49ce98193e38292e8b5b0e3828be6b1bde8bb8ae381bee381a7e38081e4b880e381a4e381aee8b5a4e38184e78788e781abe38292e7a4bae3819be38288e38082e4bb8ae3819de38193e381abe58db1e99aaae3818ce38182e3828be38082e696b7e6a98befbc81e38080e696b7e6a98befbc81e38080e38182e38182e682b2e9b3b4e381afe9a2a8e38292e381a4e38293e38196e3818fe38082e381a0e3828ce3818ce3819de3828ce38292e79fa5e3828be3818be38082e7b2bee7a59ee381afe99787e381aee69ba0e9878ee38292e381b2e3819fe8b5b0e3828be38082e680a5e8a18ce38197e38081e680a5e8a18ce38197e38081e680a5e8a18ce38197e38081e5bdbce381aee682b2e58a87e381aee7b582e9a99be381b8e381a8e38082", + x"e381a8e381afe38184e381b8e792b0e5a283e381aee99787e38292e7aa81e7a0b4e38199e381b9e3818de38081e381a9e38293e381aae58a9be3818ce3819de38193e381abe38182e3828be3818be38082e9bd92e3818ce381bfe381a6e38193e38289e381b8e38288e38082e38193e38289e381b8e38288e38082e38193e38289e381b8e38288e38082", + x"e58fa4e9a99be381aee38081e69fb3e381aee38182e3828be5b79de381aee5b2b8e381a7e38081e3818be3828ce381afe4bd95e38292e987a3e38289e38186e381a8e38199e3828be381aee3818be38082e38284e3818ce381a6e7949fe6b4bbe381aee89684e69aaee3818ce3818fe3828be381bee381a7e38081e3819de38293e381aae381abe38282e995b7e38184e99693e38081e9879de381aee381aae38184e987a3e7abbfe381a7e280a6e280a6e38082e3808ce590a6e3808de381a8e3819de381aee694afe982a3e4babae3818ce7ad94e381b8e3819fe38082e3808ce9ad9ae381aee7be8ee38197e3818fe8b5b0e3828be38292e79cbae38281e38288e38081e6b0b4e381aee99d9ce3818be381abe8a18ce3818fe38292e79cbae38281e38288e38082e38184e3818be381abe5909be381afe38193e381aee99d9ce8ac90e38292e5a5bde381bee381aae38184e3818be38082e38193e381aee9a2a8e699afe381aee881b0e6988ee381aae68385e8b6a3e38292e38082e38280e38197e3828de7a781e381afe38081e7b582e697a53c727562793e3c72623ee987a3e3828ae5be97e381aae381843c2f72623e3c72703eefbc883c2f72703e3c72743ee383bbe383bbe383bbe383bbe383bb3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38193e381a8e38292e5b88ce69c9be38197e381a6e38290e3828be38082e38195e3828ce381b0e697a5e795b6e3828ae5a5bde38184e5af82e5afa5e381aee5b2b8e9828ae381abe59d90e38197e381a6e38081e7a781e381aee381a9e38293e381aae792b0e5a283e38292e38282e4ba82e38199e381aae3818be3828ce38082e3808d", + x"e5b590e38081e5b590e38081e6b5aae38081e6b5aae38081e5a4a7e6b5aae38081e5a4a7e6b5aae38081e5a4a7e6b5aae38082e582bee38280e3818fe59cb0e5b9b3e7b79ae38081e4b88ae69887e38199e3828be59cb0e5b9b3e7b79ae38081e890bde381a1e3818fe3828be59cb0e5b9b3e7b79ae38082e3818ce381a1e38284e3818ce381a1e38284e38081e3818ce381a1e38284e3818ce381a1e38284e38082e4b88ae794b2e69dbfe381b8e38081e4b88ae794b2e69dbfe381b8e380823c727562793e3c72623ee98e963c2f72623e3c72703eefbc883c2f72703e3c72743ee38381e382a8e383b33c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e58db7e38191e380813c727562793e3c72623ee98e963c2f72623e3c72703eefbc883c2f72703e3c72743ee38381e382a8e383b33c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e58db7e38191e38082e7aa81e980b2e38199e3828be38081e7aa81e980b2e38199e3828be6b0b4e5a4abe38289e38082e888b9e5aea4e381aee7aa93e38081e7aa93e38081e7aa93e38081e7aa93e38082e582bee38280e3818fe59cb0e5b9b3e7b79ae38081e4b88ae69887e38199e3828be59cb0e5b9b3e7b79ae380823c727562793e3c72623ee98e963c2f72623e3c72703eefbc883c2f72703e3c72743ee38381e382a8e383b33c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee380813c727562793e3c72623ee98e963c2f72623e3c72703eefbc883c2f72703e3c72743ee38381e382a8e383b33c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee380813c727562793e3c72623ee98e963c2f72623e3c72703eefbc883c2f72703e3c72743ee38381e382a8e383b33c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38082e9a2a8e38081e9a2a8e38081e9a2a8e38082e6b0b4e38081e6b0b4e38081e6b0b4e380823c727562793e3c72623ee888b9e7aa933c2f72623e3c72703eefbc883c2f72703e3c72743ee3838fe38384e383813c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e99689e38281e3828de380823c727562793e3c72623ee888b9e7aa933c2f72623e3c72703eefbc883c2f72703e3c72743ee3838fe38384e383813c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e99689e38281e3828de38082e58fb3e888b7e381b8e38081e5b7a6e888b7e381b8e38082e6b5aae38081e6b5aae38081e6b5aae38082e381bbe381b2e38286e383bce3828be38082e381bbe381b2e38286e383bce3828be38082e381bbe381b2e38286e383bce3828be38082", + x"e6a3aee3818be38289e3818be381b8e3828be381a8e3818de38081e7a781e381afe5b8bde5ad90e38292e381ace3818ee38199e381a6e3819fe38082e38182e38182e38081e8a898e686b6e38082e68190e3828de38197e3818fe7a0b4e3828ce381a1e3818ee381a4e3819fe8a898e686b6e38082e381bfe38198e38281e381aae38081e6b3a5e6b0b4e381aee4b8ade381abe88590e381a4e3819fe8a898e686b6e38082e38195e381b3e38197e38184e99ba8e699afe381aee98193e381abe381b5e3828be381b8e3828be7a781e381aee5b8bde5ad90e38082e8838ce5be8ce381abe68da8e381a6e381a6e8a18ce3818fe38082", + x"e69bb8e7949fe381afe794bae381abe8a18ce3818de38081e5b7a5e5a0b4e381aee4b88be38292e9809ae3828ae38081e6a99fe9979ce8bb8ae381aee9b3b4e3828be99fbfe38292e881bde38184e3819fe38082e781abe5a4abe381aee8b5b0e3828ae38081e8bb8ae8bcaae381aee5bbbbe3828ae38081e7bea4e9b489e381aee596a7e8999fe38199e3828be5b7b7e381aee4b8ade381a7e38081e381afe38284e4b880e381a4e381aee883a1e5bc93e381afe88db7e980a0e38195e3828ce38081e8b2a8e8bb8ae381abe7a98de381bee3828ce38081e38195e38186e38197e381a6e6b8afe381aee58089e5baabe381aee696b9e381b8e38081e7a88ee9979ce381aee99680e38292e3818fe38190e381a4e381a6e8a18ce381a4e3819fe380823c62722f3ee58d81e69c88e4b88be697ace38082e69bb8e7949fe381afe9a3afe38292e9a39fe381afe38186e381a8e38197e381a6e38081e69eafe3828ce3819fe88a9de88d89e381aee58089e5baabe381aee5bdb1e381abe38081e99fb3e6a882e381aee5bf8de381b3e5b185e3828ae38081e89f8be89f80e381aee38284e38186e381abe9b3b4e3818fe381aee38292e881bde38184e3819fe380823c62722f3ee28095e28095e68385e7b792e38288e38081e5909be381afe6adb8e38289e38196e3828be3818be38082", + x"e38193e381aee98b8fe381aee6a793e58a9be381a7e38282e38081e5a5b3e381aee98c86e381b3e381a4e38184e3819f3c727562793e3c72623ee98a85e7898c3c2f72623e3c72703eefbc883c2f72703e3c72743ee383a1e38380e383ab3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee3818ce58887e3828ce381aae38184e381aee3818be38082e6b0b4e5a4abe38288efbc81e38080e6b19de381ae3c727562793e3c72623ee99ab1e8a1a33c2f72623e3c72703eefbc883c2f72703e3c72743ee3818be3818fe381973c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee381aee98ca2e38292e3818be3819ee381b8e381a6e38081e784a1e794a8e381aee68385e786b1e38292e68da8e381a6e381a6e38197e381bee381b8efbc81", + x"e98fa1e381aee38186e38197e3828de381b8e5bbbbe381a4e381a6e381bfe381a6e38282e38081e3808ce7a781e3808de381afe3819de38193e381abe5b185e381aae38184e381aee381a7e38199e38288e38082e3818ae5ad83e38195e38293efbc81", + x"e8a68be38288efbc81e38080e5bdbce381afe9a2a8e381aee38284e38186e381abe4be86e3828be38082e3819de381aee9a18de381afe68682e9acb1e381abe99d92e38196e38281e381a6e38290e3828be38082e880b3e381afe38199e3828be381a9e3818fe58887e381a4e7ab8be381a1e38081e381bee381aae38198e3828ae381afe68092e381abe8a382e38191e381a6e38290e3828be380823c62722f3ee5909be38288efbc81e380803c727562793e3c72623ee78ba1e699ba3c2f72623e3c72703eefbc883c2f72703e3c72743ee383bbe383bb3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee381aee3818be3818fe381aee5a682e3818de7be8ee38197e3818de8a1a8e68385e38292e381a9e38193e381abe8a68be3819fe3818be38082", + x"e596aee381abe5ada4e78da8e381a7e38182e3828be381b0e3818be3828ae381a7e381aae38184e38082e695b5e38292e4bba5e381a6e58585e3819fe38195e3828ce381a6e38290e3828befbc81", + x"e6988ee3828be38184e7a19de5ad90e688b8e381aee5ba97e381aee4b8ade381a7e38081e4b880e381a4e381aee7a3a8e3818be3828ce3819fe98a83e599a8e38195e381b8e38282e38081e781abe897a5e38292e8a39de5a1abe38197e381a6e381aae38184e381aee381a7e38182e3828be38082e28095e28095e4bd95e3819fe3828be8999ae5a684e3819ee380823c727562793e3c72623ee687b6e788be3c2f72623e3c72703eefbc883c2f72703e3c72743ee38289e38293e381983c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee381a8e38197e381a6e7ac91e381b8efbc81", + x"e58d9ae5be92e7ad89e99b86e381bee3828ae38081e68a95e38192e381a4e38191e38289e3828ce3819fe3828be7949fe6b6afe381ae3c727562793e3c72623ee6a99fe59ba03c2f72623e3c72703eefbc883c2f72703e3c72743ee38381e383a4e383b3e382b93c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee381aee4b88ae381a7e38081e8999ae695b8e381aee68385e786b1e38292e8b3ade38191e59088e381a4e381a6e38290e3828be38082e381bfe381aae58587e69ab4e381aee381a4e382893c727562793e3c72623ee9ad823c2f72623e3c72703eefbc883c2f72703e3c72743ee381a0e381bee38197e381b23c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee380823c727562793e3c72623ee4bb81e7bea93c2f72623e3c72703eefbc883c2f72703e3c72743ee38198e38293e3818e3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e6a78be381b8e38081e8998ee381aee38284e38186e381aae7a9bae6b49ee381abe5b185e3828be38082", + x"e88d92e5afa5e381a8e38197e3819fe5b1b1e381aee4b8ade885b9e381a7e38081e5a381e381aee38284e38186e381abe6b288e9bb98e38197e381a6e38290e3828be38081e4b880e381aee5b7a8e5a4a7e381aae3828be880b3e38292e8a68be3819fe38082", + x"e5aebfe591bde79a84e381aae3828be69db1e6b48be381aee5bbbae7af89e381afe38081e3819de381aee5b18be6a0b9e381aee4b88be381a7e5bf8de5be9ee38197e381aae3818ce38289e380813c727562793e3c72623ee7948d3c2f72623e3c72703eefbc883c2f72703e3c72743ee38184e38289e3818b3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee381abe696bce381a6e68092e3828ae7ab8be381a4e381a6e38290e3828be38082", + x"e3819de381aee58685e983a8e381abe6a78be980a0e381aee694afe69fb1e38292e68c81e381a1e38081e69a97e38184e6a2afe5ad90e381a8e7b693e69687e38292e8978fe38199e3828be4bd9be99980e38288efbc81e38080e6b5b7e38288e3828ae38282e981a0e3818fe38081e4babae7959ce381aee4bd8fe38280e4b896e7958ce38292e8b68ae38188e381a6e38081e68c87e381aee38284e38186e381abe5b0a8e5a4a7e381aae3828cefbc81", + x"e4babae3818ce5aeb6e381aee4b8ade381abe4bd8fe38293e381a7e3828be381aee381afe38081e59cb0e4b88ae381aee682b2e38197e38184e9a2a8e699afe381a7e38182e3828be38082", + x"e68682e9acb1e381aee995b7e38184e69f84e3818be38289e38081e99ba8e3818ce38197e381a8e38197e381a8e381a83c727562793e3c72623ee6bbb43c2f72623e3c72703eefbc883c2f72703e3c72743ee38197e381a5e3818f3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e38197e381a6e38290e3828be38082e79c9ee9bb92e381aee5a4a7e3818de381aae6b48be58298efbc81", + x"e79086e9abaee5ba97e381aee99d92e38184e7aa93e3818be38289e38081e891b1e381aee38284e38186e381abe7aa81e3818de587bae38199e6a38de6a392e38082e3819de38184e381a4e381aee9a6ace9b9bfe38289e38197e38184e6a99fe6a2b0e4bb95e68e9be381a7e38081e5a4a2e4b8ade381abe381aae38190e38289e3828ce38081e381aae38190e38289e3828ce381a6e5b185e3828be38082", + x"e6848fe5bf97efbc81e38080e3819de381afe5a495e69aaee381aee6b5b7e38288e3828ae38197e381a6e38081e9b1b6e381aee5a682e3818fe381abe6b3b3e3818ee4be86e3828ae38081e9bd92e38292e4bba5e381a6e88289e381abe5999be381bfe381a4e38191e3828ae38082", + x"e5bbbae7af89e28095e28095e789b9e381abe7bea4e59c98e38197e3819fe5bbbae7af89e28095e28095e381aee6a8a3e5bc8fe381afe38081e7a9bae381aee7a9b9e7aabfe381abe5b08de38197e381a6e6a78be683b3e38195e3828ce381ade381b0e381aae38289e381ace38082e58db3e381a1e58887e696b7e38195e3828ce3819fe3828be79083e381aee5bca7e5bda2e381abe5b08de38197e381a6e38081e6a78de78ab6e381aee59e82e79bb4e7b79ae38284e38081e59c93e98c90e5bda2e38284e381aee4baa4e98cafe3819be3828be6a78be683b3e38292e794a8e6848fe38199e381b9e3818de381a7e38182e3828be380823c62722f3ee38193e381aee892bce7a9bae381aee4b88be381abe696bce38191e3828be38081e981a0e696b9e381aee983bde69c83e381aee58db0e8b1a1e381a8e38197e381a6e38081e3818ae381bbe38280e381ade381aee5bbbae7af89e381afe4b880e381a4e381aee9878de8a681e381aae6848fe58ca0e38292e5bf98e3828ce381a6e38290e3828be38082", + x"e788b6e381afe6b0b8e981a0e381abe682b2e5a3afe381a7e38182e3828be38082", + x"e695b5e381afe5b8b8e381abe59384e7ac91e38197e381a6e38290e3828be38082e38195e38186e381a7e38282e381aae38191e3828ce381b0e38081e4bd95e88085e381aee8a1a8e8b1a1e3818ce68092e38289e3819be3828be381aee3818befbc9f", + x"e6a99fe6a2b0e4babae99693e381abe38282e38197e6849fe68385e3818ce38182e3828be381a8e38199e3828ce381b0efbc9fe38080e784a1e99990e381aee59380e582b7e381aee381bbe3818be381aee4bd95e88085e381a7e38282e381aae38184e38082", + x"e7a781e3818ce38282e38197e789a9e9ab94e381a7e38182e38289e38186e381a8e38282e38081e7a59ee381afe5868de5baa6e69c97e38289e3818be381abe7ac91e381b2e381afe38197e381aae38184e38082e38182e38182e38081e790b4e381aee99fb3e3818ce881bde38188e381a6e4be86e3828be38082e28095e28095e5b08fe38195e381aae4b880e381a4e381ae3c727562793e3c72623ee580abe790863c2f72623e3c72703eefbc883c2f72703e3c72743ee383a2e383a9e383ab3c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee3818ce38081e596aae5a4b1e38197e381a6e38197e381bee381a4e3819fe381aee381a0e38082", + x"e9be8de381afe5b89de78e8be381aee6acb2e69c9be38292e8b1a1e5beb4e38197e381a6e38290e3828be38082e6ac8ae58a9be381aee7a5a5e99bb2e381abe4b998e381a4e381a6e5b185e381aae3818ce38289e38081e5b8b8e381abe686a4e381bbe3828de38197e38184e6819ae68092e381abe78783e38188e38081e4b88de696b7e381aee788ade9acaae381aee3819fe38281e381abe78999e38292e38280e38184e381a6e3828be38082", + x"e38199e381b9e381a6e381aee6a98be381afe38081e4b880e381a4e381aee5bbbae7af89e6848fe58ca0e38197e3818be68c81e381a4e381a6e38290e381aae38184e38082e69982e99693e38292e7a9bae99693e381aee4b88ae381abe69eb6e38191e38081e68896e3828be5a4a2e5b9bbe79a84e381aae4b880e381a4e381ae3c727562793e3c72623ee8a780e5bfb53c2f72623e3c72703eefbc883c2f72703e3c72743ee382a4e38387e382a23c2f72743e3c72703eefbc893c2f72703e3c2f727562793ee38292e38081e78fbee5afa6e79a84e381abe8bea8e8ad89e38199e3828be38193e381a8e381aee786b1e6848fe381a7e38182e3828be380823c62722f3ee6a98be381a8e381afe28095e28095e5a4a2e38292e69eb6e7a9bae38197e3819fe695b8e5adb8e381a7e38182e3828be38082", + x"e5a49ae3818fe381aee58588e5a4a9e79a84e381aee8a9a9e4babae38284e8979de8a193e5aeb6e7ad89e381afe38081e5bdbce7ad89e381aee5aebfe591bde381a5e38191e38289e3828ce3819fe4bb95e4ba8be381abe5b08de38197e381a6e38081e38182e381aee682b2e7979be381aae880b6e89887e381aee7a588e38292e38288e3818fe79fa5e381a4e381a6e3828be38082e3808ce7a59ee38288efbc81e38080e38282e38197e5bea1e5bf83e381abe981a9e381b5e381aae38289e381b0e38081e38193e381aee88ba6e3818de98592e79b83e38292e99ba2e38197e7b5a6e381b8e38082e38195e3828ce381a9e788bee381abe38197e381a6e6acb2e38199e3828be381aae38289e381b0e38081e5bea1e5bf83e381aee381bee381bee381abe788b2e38197e7b5a6e381b8e38082e3808d", + x"e6a99fe9979ce98a83e38288e3828ae38282e682b2e38197e38192e381abe38081e7b98be79599e6b0a3e79083e38288e3828ae38282e68682e9acb1e381abe38081e782b8e8a382e5bd88e38288e3828ae38282e6ae98e5bf8de381abe38081e6af92e793a6e696afe38288e3828ae38282e6b288e7979be381abe38081e69bb3e781abe5bd88e38288e3828ae38282e892bce799bde3818fe38081e5a4a7e7a0b2e38288e3828ae38282e383ade3839ee383b3e38381e38384e382afe381abe38081e78599e5b995e38288e3828ae38282e5af82e38197e38192e381abe38081e98a83e781abe381aee799bde3818fe99683e38281e3818fe38284e38186e381aae8a9a9e3818ce69bb8e3818de3819fe38184efbc81", + ]; + + const POEM_SVG_IPFS_CID: vector> = vector[ + b"QmNREv8ovF11ViuZSHtEcFzc5Hb8gMMRXEJgYtDVBu3NRr", + b"QmfKHsnjqhYQZKhcgEjEanNwyZehVzE5SuaipmKwTYjkqp", + b"QmSyve6wEBy8FfQbxZvsZhLL13TDGCbjremrWoGrQEMS5X", + b"QmPjU4Zp2BZobSFqu4Z9TZuiAVF2EmDQpHUpTSxNucod2i", + b"Qma8oQonq28pKo31xjKtwAGcFnnmnK7tDv2tPfKjHdGKtq", + b"Qmevof6HRQS2aJo7onM1SbdoKbD8T6BGp8Gw2ZPJWTFVah", + b"QmbfD8wcsHLSBzhvHjeBwVjexq7tv6TNYCtAARg7b3zgov", + b"QmQj6nx5RpjX7HvuZm384RmHwDRSzxyvJFVoacRb2sgDQD", + b"QmNNUzh371bM47dbh1ZxeFb8jC5NuAia653WPawatan29U", + b"QmQ4pugZXpSXuAbQaEpvF9JPEnpodgdAwdBn6LUYKQHNZP", + b"QmUMhCjwp4CptciYw4FW394W9dJcCQLLkaiLCjwomEsu2W", + b"QmNcCXPGaSSj4bCapWZnD2yHEsUGWKXBjPVJbtLscCi8zA", + b"QmPY1dAx5Gm67t2K9rN6ercU2RXdBiYMbbokmNG6FYxXXx", + b"Qmb3HnqAyRwhQS8TFiQFm6N5FkahCPjhoQCaXmSi11t2ck", + b"QmNqKJomkUseWsgQrypeJc4VrgsRrmy331vUVjN9RP9KVd", + b"QmXeMuWKnztTSYF798gXspSXJHZuymDTdAFpCGRirXkm7T", + b"QmVWAT6AuhLLF18Vo2YBBr7DtqUFzy4VpntKCFVEuhE9Ah", + b"QmaHFyTJx6h95i5J742D1dbe3XSs8Qjj74pBKwsEuzrxaq", + b"QmRNtnYcYVrSPGQ6QrtesQChL9W4CEHJmF5Kvc35bYFDvv", + b"QmS9zTrQMVRZdqv3Ew2t5UHiBp91mrdG5wC4PT2jDPrQSE", + b"QmXxD1my8MbuNFF5FDp7PZnWMqJsmdtTWyw43wx2fVDEV7", + b"QmdsLG5PhHhtV5EAwBEk2FicV8DppueRP4sn7BQhgi5yxF", + b"QmRPe9QKrExbUj4VB2HZzNS25xijDuxNPcxgid8pgsjvMR", + b"QmYZSs12a47ViGc7yM56VcQm1uebnrmdmFeGF2FvM6AVJb", + b"QmWqkbEHknifGDQQzmEN4jVRW5psAM9AGsEPfVg8czrqA4", + b"QmXdsCTik7YERw98u5kLtUEvSr284ar4odraQ6FSpCwSF2", + b"QmNtqRBrB551pT2FcW7FX4vySYcuZ7qMoHzv2mPzJvKSdw", + b"QmWET6N7SSjbZmm6cmqcGfrx11kYacT6bcqeHK9SSUo3CD", + b"QmSEZri6qJzqMPDt7uh6wCSqqzjMUXg4GUNJ431LuWy9YQ", + b"QmRugS4GCrWQB9iiLpDXLyztcXTpb2R7YnUxWXRZGz6azB", + b"QmYfAFkDmPBAdoL3rSVWwcepN3eXungT67gWBMwfvH5gP9", + b"QmWDy5VDpJAL3cjFJxTeTTZRgggDmmjr1hgvdxX8AWAk1a", + b"QmUQckgF6Tr5BSDQAjfeVk8qpJj1gAHryLN4X7i1VMwymg", + b"QmTBth13ZJAAKHJtRhtCou5QAsY9oi6FV2EmtsgduSdZN4", + b"QmZLEDYbgDD7XfFqEXD5Jyf6KfT31tUV8ghRE5AfZTRVQ5", + b"QmSPCxQVbCp8RRFb6xafpqqdVkk8r9r4P37D5xMKR4a4EL", + b"QmPVYxLLwcUXqXwyJbxgovfTnESgmQ743QkNVFCTF5XNb5", + b"QmcagR96QQSABketfAmzngjXSZoeagBKDdZPXMTH6DbeuN", + b"QmPds4nYmCsnZNe3DHDEY8X1DMm6GvdHFdTB8xPysqno7N", + ]; + + const ROYALTY_PAYEE_ADDRESS: address = @resource_address; + + const ROYALTY_POINTS_DENOMINATOR: u64 = 10; + + const ROYALTY_POINTS_NUMERATOR: u64 = 1; + + fun init_module(resource_signer: &signer) { + token::create_collection( + resource_signer, + utf8(COLLECTION_NAME), + utf8(COLLECTION_DESCRIPTION), + utf8(b""), // uri + 39, // maximum + vector[false, false, false // mutate_setting - description, uri, maximum + ]); + + move_to(resource_signer, ModuleData { + signer_cap: resource_account::retrieve_resource_account_cap(resource_signer, @source_address), + token_minting_events: account::new_event_handle(resource_signer), + }); + } + + public fun get_poem_id(owner: address): u64 { + let bytes = bcs::to_bytes(&owner); + return ((from_bcs::to_u256(sha3_256(bytes)) % 39) as u64) + } + + public fun get_poem_title(poem_id: u64): String { + return utf8(*vector::borrow(&POEM_TITLES, poem_id)) + } + + public fun get_poem_body(poem_id: u64): String { + return utf8(*vector::borrow(&POEM_BODIES, poem_id)) + } + + public fun get_poem_svg_ipfs_cid(poem_id: u64): String { + return utf8(*vector::borrow(&POEM_SVG_IPFS_CID, poem_id)) + } + + public fun get_poem_svg(poem_id: u64): String { + let svg = utf8(b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b""); + append_utf8(&mut svg, b"

"); + append(&mut svg, get_poem_title(poem_id)); + append_utf8(&mut svg, b"

"); + append(&mut svg, get_poem_body(poem_id)); + append_utf8(&mut svg, b"

"); + append_utf8(&mut svg, x"e2809520e890a9e58e9f20e69c94e5a4aae9838e"); + append_utf8(&mut svg, b"

"); + return svg + } + + public fun get_poem_svg_base64(poem_id: u64): String { + let svg = get_poem_svg(poem_id); + let svg_base64 = utf8(b"data:image/svg+xml;base64,"); + append_utf8(&mut svg_base64, base64::encode(string::bytes(&svg))); + return svg_base64 + } + + public fun get_token_uri(poem_id: u64): String { + let token_uri = utf8(b"ipfs://"); + append(&mut token_uri, get_poem_svg_ipfs_cid(poem_id)); + return token_uri + } + + public fun get_token_name(token_index: u64): String { + let token_name = utf8(b"#"); + append(&mut token_name, to_string(&token_index)); + return token_name + } + + public fun new_token_name(): String { + let collection_supply = token::get_collection_supply(@resource_address, utf8(COLLECTION_NAME)); + let token_index = option::extract(&mut collection_supply) + 1; + return get_token_name(token_index) + } + + public entry fun mint(receiver: &signer) acquires ModuleData { + let module_data = borrow_global_mut(@resource_address); + let resource_signer = account::create_signer_with_capability(&module_data.signer_cap); + + let poem_id = get_poem_id(address_of(receiver)); + + let token_data_id = token::create_tokendata( + &resource_signer, + utf8(COLLECTION_NAME), + new_token_name(), + utf8(COLLECTION_DESCRIPTION), + 1, // token_maximum, + get_token_uri(poem_id), + ROYALTY_PAYEE_ADDRESS, + ROYALTY_POINTS_DENOMINATOR, + ROYALTY_POINTS_NUMERATOR, + token::create_token_mutability_config(&vector[ false, false, false, false, true ]), // token_mutate_setting - maximum, uri, royalty, description, properties + vector[ // token_property_keys + utf8(b"poem_id"), + utf8(b"poem_title"), + utf8(b"poem_svg_base64"), + utf8(b"svg_ipfs_cid") + ], + vector>[ // token_property_values + bcs::to_bytes(&poem_id), + bcs::to_bytes(&get_poem_title(poem_id)), + bcs::to_bytes(&get_poem_svg_base64(poem_id)), + bcs::to_bytes(&get_poem_svg_ipfs_cid(poem_id)) + ], + vector[ // token_property_types + utf8(b"u64"), + utf8(b"0x1::string::String"), + utf8(b"0x1::string::String"), + utf8(b"0x1::string::String") + ], + ); + + let token_id = token::mint_token(&resource_signer, token_data_id, 1); + token::direct_transfer(&resource_signer, receiver, token_id, 1); + + event::emit_event( + &mut module_data.token_minting_events, + TokenMintingEvent { + token_receiver_address: address_of(receiver), + token_data_id, + } + ); + } + + public entry fun update(owner_address: address, token_index: u64) acquires ModuleData { + let module_data = borrow_global_mut(@resource_address); + let resource_signer = account::create_signer_with_capability(&module_data.signer_cap); + + let token_data_id = token::create_token_data_id(@resource_address, utf8(COLLECTION_NAME), get_token_name(token_index)); + let token_property_version = token::get_tokendata_largest_property_version(@resource_address, token_data_id); + let token_id = token::create_token_id(token_data_id, token_property_version); + let property_map = token::get_property_map(owner_address, token_id); + + let poem_id = get_poem_id(owner_address); + if (property_map::read_u64(&property_map, &utf8(b"poem_id")) == poem_id) { + return + }; + + token::mutate_token_properties( + &resource_signer, + owner_address, + @resource_address, + utf8(COLLECTION_NAME), + get_token_name(token_index), + token_property_version, + 1, // amount + vector[ // token_property_keys + utf8(b"poem_id"), + utf8(b"poem_title"), + utf8(b"poem_svg_base64"), + utf8(b"svg_ipfs_cid") + ], + vector>[ // token_property_values + bcs::to_bytes(&poem_id), + bcs::to_bytes(&get_poem_title(poem_id)), + bcs::to_bytes(&get_poem_svg_base64(poem_id)), + bcs::to_bytes(&get_poem_svg_ipfs_cid(poem_id)) + ], + vector[ // token_property_types + utf8(b"u64"), + utf8(b"0x1::string::String"), + utf8(b"0x1::string::String"), + utf8(b"0x1::string::String") + ], + ); + } + + // + // Tests + // + + #[test (origin_account = @0xb21de0e2a7419d35d5abde4baa2a72159cd3a7cea042defd0e54b1faa022a474, resource_account = @0x6a34f9589eac7a9f36dd0795f01e4c90fac7ff80abd703d1b66d31744fdaaf4e, nft_receiver = @0x123, nft_receiver2 = @0x234)] + public entry fun test_mint(origin_account: signer, resource_account: signer, nft_receiver: signer, nft_receiver2: signer) acquires ModuleData { + account::create_account_for_test(address_of(&origin_account)); + resource_account::create_resource_account(&origin_account, b"sakutaro", x""); + init_module(&resource_account); + + // let resource_addr = account::create_resource_address(&@0xb21de0e2a7419d35d5abde4baa2a72159cd3a7cea042defd0e54b1faa022a474, b"sakutaro"); + // std::debug::print(&b"sakutaro"); + // std::debug::print(&resource_addr); + + account::create_account_for_test(address_of(&nft_receiver)); + account::create_account_for_test(address_of(&nft_receiver2)); + + mint(&nft_receiver); + + let token_data_id = token::create_token_data_id(@resource_address, utf8(COLLECTION_NAME), utf8(b"#1")); + let token_property_version = token::get_tokendata_largest_property_version(@resource_address, token_data_id); + let token_id = token::create_token_id(token_data_id, token_property_version); + let property_map = token::get_property_map(address_of(&nft_receiver), token_id); + std::debug::print(&property_map::read_u64(&property_map, &utf8(b"poem_id"))); + std::debug::print(&property_map::read_string(&property_map, &utf8(b"poem_title"))); + std::debug::print(&property_map::read_string(&property_map, &utf8(b"poem_svg_base64"))); + + let amount = 1; + token::direct_transfer(&nft_receiver, &nft_receiver2, token_id, amount); + + // mint(&nft_receiver2); + + let token_index = 1; + update(address_of(&nft_receiver2), token_index); + + let token_data_id_2 = token::create_token_data_id(@resource_address, utf8(COLLECTION_NAME), utf8(b"#1")); + let updated_token_property_version = token::get_tokendata_largest_property_version(@resource_address, token_data_id_2); + let updated_token_id = token::create_token_id(token_data_id_2, updated_token_property_version); + let updated_property_map = token::get_property_map(address_of(&nft_receiver2), updated_token_id); + std::debug::print(&property_map::read_u64(&updated_property_map, &utf8(b"poem_id"))); + std::debug::print(&property_map::read_string(&updated_property_map, &utf8(b"poem_title"))); + std::debug::print(&property_map::read_string(&updated_property_map, &utf8(b"poem_svg_base64"))); + } +}