From 3940b57280b7dadf02eeb653d61b2f45e6626196 Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Wed, 17 Aug 2022 18:11:15 +0800 Subject: [PATCH 1/9] Create 2.1.0-2.1.1_testnet.sh --- scripts/cli-samples/2.1.0-2.1.1_testnet.sh | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 scripts/cli-samples/2.1.0-2.1.1_testnet.sh diff --git a/scripts/cli-samples/2.1.0-2.1.1_testnet.sh b/scripts/cli-samples/2.1.0-2.1.1_testnet.sh new file mode 100644 index 0000000..9cab679 --- /dev/null +++ b/scripts/cli-samples/2.1.0-2.1.1_testnet.sh @@ -0,0 +1,27 @@ +#!/bin/bash +set -e +# +export NEAR_CLI_TESTNET_RPC_SERVER_URL=https://near-testnet.infura.io/v3/4f80a04e6eb2437a9ed20cb874e10d55 +# export NEAR_CLI_TESTNET_RPC_SERVER_URL=https://public-rpc.blockpi.io/http/near-testnet +export NEAR_ENV=testnet +export APPCHAIN_ID=$1 +export REGISTRY_ACCOUNT_ID=registry.test_oct.testnet +export ANCHOR_ACCOUNT_ID=$APPCHAIN_ID'.'$REGISTRY_ACCOUNT_ID +export FAUCET_ACCOUNT_ID=wat-faucet.$ANCHOR_ACCOUNT_ID +# +# +# +cp ~/.near-credentials/testnet/$ANCHOR_ACCOUNT_ID.json ~/.near-credentials/testnet/$FAUCET_ACCOUNT_ID.json +sed -i '' "s/$ANCHOR_ACCOUNT_ID/$FAUCET_ACCOUNT_ID/" ~/.near-credentials/testnet/$FAUCET_ACCOUNT_ID.json +# +near create-account $FAUCET_ACCOUNT_ID --masterAccount $ANCHOR_ACCOUNT_ID --publicKey ed25519:99dtM6c33a1NCoRrhM7cwfDaJy123JLdsT9i4M9wYk3f --initialBalance 2 +near deploy --accountId $FAUCET_ACCOUNT_ID --wasmFile res/wat_faucet.wasm +near call $FAUCET_ACCOUNT_ID new '' --accountId $FAUCET_ACCOUNT_ID --gas 200000000000000 +# +near deploy --accountId $ANCHOR_ACCOUNT_ID --wasmFile res/appchain_anchor.wasm +# +near call $ANCHOR_ACCOUNT_ID migrate_state '' --accountId $ANCHOR_ACCOUNT_ID --gas 200000000000000 +# +near call $ANCHOR_ACCOUNT_ID set_bonus_for_new_validator '{"bonus_amount":"1000000000000000000"}' --accountId $ANCHOR_ACCOUNT_ID --gas 200000000000000 +# +near view $ANCHOR_ACCOUNT_ID get_appchain_settings From 0a8ca141cf242f6f67d08e973ed8d51a759b38dd Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Mon, 22 Aug 2022 10:47:11 +0800 Subject: [PATCH 2/9] Upgrade crate `workspaces` to version `0.4`. --- Cargo.lock | 322 ++++++++---------------- Cargo.toml | 2 +- tests/simulator/common/basic_actions.rs | 2 +- 3 files changed, 110 insertions(+), 216 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b9b6a9f..d147dea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,9 +10,9 @@ checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" [[package]] name = "actix" -version = "0.11.0-beta.2" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eb78f9871feb3519e06b947c2becbf2cc7f67ce786e510e6bd3f9a27da3dbf1" +checksum = "f728064aca1c318585bf4bb04ffcfac9e75e508ab4e8b1bd9ba5dfe04e2cbed5" dependencies = [ "actix-rt", "actix_derive", @@ -22,13 +22,14 @@ dependencies = [ "futures-core", "futures-sink", "futures-task", + "futures-util", "log", "once_cell", - "parking_lot 0.11.2", + "parking_lot", "pin-project-lite", "smallvec", "tokio", - "tokio-util 0.6.10", + "tokio-util", ] [[package]] @@ -43,9 +44,9 @@ dependencies = [ [[package]] name = "actix_derive" -version = "0.6.0-beta.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae749cf2582eb83efd288edd4e9704600fdce1bc4f69aa0c86ca1368a3e4c13f" +checksum = "6d44b8fee1ced9671ba043476deddef739dd0959bf77030b26b738cc591737a7" dependencies = [ "proc-macro2", "quote", @@ -1068,7 +1069,7 @@ dependencies = [ "indexmap", "slab", "tokio", - "tokio-util 0.7.3", + "tokio-util", "tracing", ] @@ -1087,15 +1088,6 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db0d4cf898abf0081f964436dc980e96670a0f36863e4b83aaacdb65c9d7ccc3" -[[package]] -name = "heck" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] - [[package]] name = "heck" version = "0.4.0" @@ -1481,9 +1473,9 @@ dependencies = [ [[package]] name = "near-account-id" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b81ee2cf429b8bc04046d94f725a4f192fe7b13f42d76649d0177fd9ea719d8" +checksum = "de83d74a9241be8cc4eb3055216966b58bf8c463e8e285c0dc553925acdd19fa" dependencies = [ "borsh", "serde", @@ -1491,9 +1483,9 @@ dependencies = [ [[package]] name = "near-account-id" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de83d74a9241be8cc4eb3055216966b58bf8c463e8e285c0dc553925acdd19fa" +checksum = "71d258582a1878e6db67400b0504a5099db85718d22c2e07f747fe1706ae7150" dependencies = [ "borsh", "serde", @@ -1501,62 +1493,63 @@ dependencies = [ [[package]] name = "near-chain-configs" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a830a8ea64328e4d2553873df848a97a90d111cb838ff5e199bfce79b62b6c2b" +checksum = "3632a1c691603cb32dd9944c95d8eadbf2c09f45abd95350ea6848c649036a0b" dependencies = [ "anyhow", "chrono", "derive_more", - "near-crypto 0.12.0", - "near-primitives 0.12.0", + "near-crypto 0.14.0", + "near-primitives 0.14.0", "num-rational", "serde", "serde_json", - "sha2 0.9.9", + "sha2 0.10.2", "smart-default", "tracing", ] [[package]] name = "near-chain-primitives" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff7984007ab1c73f101c5acf60a1e1f86a4afd47048df1e2412d4501794b43da" +checksum = "a734353027698b21633a49d478e564c61ae0171c32f6912bb8844add15d72ebe" dependencies = [ "chrono", - "failure", - "failure_derive", - "log", - "near-crypto 0.12.0", - "near-primitives 0.12.0", + "near-crypto 0.14.0", + "near-primitives 0.14.0", "thiserror", + "tracing", ] [[package]] name = "near-chunks-primitives" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "838c06b137c7452001fc826f2defa6328b2695aaa720df2f0d08e31e54f849f6" +checksum = "c17f6f22f1ab710731dfba4101f12a99cac120d6af80b99899bd335bb8971477" dependencies = [ "near-chain-primitives", + "near-primitives 0.14.0", ] [[package]] name = "near-client-primitives" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffc73ebfbb59defac9a17883467af98a14a37f53079dbcbdeec57c37d329de2b" +checksum = "e1065d86012eeea838661434549f33bb6267c9950fd2aadd2af617fe773def38" dependencies = [ "actix", "chrono", "near-chain-configs", "near-chain-primitives", "near-chunks-primitives", - "near-crypto 0.12.0", + "near-crypto 0.14.0", "near-network-primitives", - "near-primitives 0.12.0", - "strum 0.20.0", + "near-primitives 0.14.0", + "serde", + "serde_json", + "strum", "thiserror", ] @@ -1600,9 +1593,9 @@ dependencies = [ [[package]] name = "near-crypto" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d301d3ca4f59ab69c4b8ff625e7b2ef624345f69ab651d15c5fd59382096d2b1" +checksum = "b8ecf0b8b31aa7f4e60f629f72213a2617ca4a5f45cd1ae9ed2cf7cecfebdbb7" dependencies = [ "arrayref", "blake2", @@ -1613,7 +1606,7 @@ dependencies = [ "derive_more", "ed25519-dalek", "libc", - "near-account-id 0.12.0", + "near-account-id 0.13.0", "once_cell", "parity-secp256k1", "primitive-types", @@ -1627,9 +1620,9 @@ dependencies = [ [[package]] name = "near-crypto" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8ecf0b8b31aa7f4e60f629f72213a2617ca4a5f45cd1ae9ed2cf7cecfebdbb7" +checksum = "1e75673d69fd7365508f3d32483669fe45b03bfb34e4d9363e90adae9dfb416c" dependencies = [ "arrayref", "blake2", @@ -1639,8 +1632,7 @@ dependencies = [ "curve25519-dalek", "derive_more", "ed25519-dalek", - "libc", - "near-account-id 0.13.0", + "near-account-id 0.14.0", "once_cell", "parity-secp256k1", "primitive-types", @@ -1654,15 +1646,17 @@ dependencies = [ [[package]] name = "near-jsonrpc-client" -version = "0.3.0" +version = "0.4.0-beta.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf00d43006d0768aba1ff4d24386192a7aed2ad7548e9301055b6494917b2cc7" +checksum = "bba462f54bc35289a1013ed3a2ebfa67cc8b12699f81c12dd67687f200c7b871" dependencies = [ "borsh", "lazy_static", + "log", "near-chain-configs", + "near-crypto 0.14.0", "near-jsonrpc-primitives", - "near-primitives 0.12.0", + "near-primitives 0.14.0", "reqwest", "serde", "serde_json", @@ -1672,52 +1666,35 @@ dependencies = [ [[package]] name = "near-jsonrpc-primitives" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e636f8862e0f5f565fb02b752e16aa676fc684e81682bfbb39a964defea627" +checksum = "34a14ee8ca393c0140cb232789259ebc61b13b4cceb177267d0131f50d0eda6c" dependencies = [ - "actix", "near-chain-configs", "near-client-primitives", - "near-crypto 0.12.0", - "near-metrics", - "near-network-primitives", - "near-primitives 0.12.0", - "near-primitives-core 0.12.0", - "near-rpc-error-macro 0.12.0", - "once_cell", + "near-crypto 0.14.0", + "near-primitives 0.14.0", + "near-rpc-error-macro 0.14.0", "serde", "serde_json", "thiserror", - "tracing", "uuid", ] -[[package]] -name = "near-metrics" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df4074b56b24c73073b576bc27133182c8654d414be09ef666ad1e1d5ea8adb" -dependencies = [ - "lazy_static", - "log", - "prometheus", -] - [[package]] name = "near-network-primitives" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63ddab6f0376a0ce870947e1ea2e98eba746af2e7edfba5dc127bbd2a2508d6" +checksum = "5aa998a1e70ebf8cf3efa76c4562ef36038cc88b4aee60efb708d14273910357" dependencies = [ "actix", - "actix_derive", "anyhow", "borsh", "chrono", - "near-crypto 0.12.0", - "near-primitives 0.12.0", - "strum 0.20.0", + "near-crypto 0.14.0", + "near-primitives 0.14.0", + "serde", + "strum", "tokio", "tracing", ] @@ -1755,9 +1732,9 @@ dependencies = [ [[package]] name = "near-primitives" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad6a0b49d322ebda81ec4fdd99dca804526539673d0b12133286e0d7934f4802" +checksum = "0a2ba19282e79a4485a77736b679d276b09870bbf8042a18e0f0ae36347489c5" dependencies = [ "borsh", "byteorder", @@ -1766,24 +1743,27 @@ dependencies = [ "derive_more", "easy-ext", "hex 0.4.3", - "near-crypto 0.12.0", - "near-primitives-core 0.12.0", - "near-rpc-error-macro 0.12.0", - "near-vm-errors 0.12.0", + "near-crypto 0.13.0", + "near-primitives-core 0.13.0", + "near-rpc-error-macro 0.13.0", + "near-vm-errors 0.13.0", "num-rational", + "once_cell", "primitive-types", "rand 0.7.3", "reed-solomon-erasure", "serde", "serde_json", "smart-default", + "strum", + "thiserror", ] [[package]] name = "near-primitives" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a2ba19282e79a4485a77736b679d276b09870bbf8042a18e0f0ae36347489c5" +checksum = "8ad1a9a1640539c81f065425c31bffcfbf6b31ef1aeaade59ce905f5df6ac860" dependencies = [ "borsh", "byteorder", @@ -1792,10 +1772,10 @@ dependencies = [ "derive_more", "easy-ext", "hex 0.4.3", - "near-crypto 0.13.0", - "near-primitives-core 0.13.0", - "near-rpc-error-macro 0.13.0", - "near-vm-errors 0.13.0", + "near-crypto 0.14.0", + "near-primitives-core 0.14.0", + "near-rpc-error-macro 0.14.0", + "near-vm-errors 0.14.0", "num-rational", "once_cell", "primitive-types", @@ -1804,7 +1784,7 @@ dependencies = [ "serde", "serde_json", "smart-default", - "strum 0.24.1", + "strum", "thiserror", ] @@ -1829,35 +1809,36 @@ dependencies = [ [[package]] name = "near-primitives-core" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaae2d2271ecdb0e3d90c11724cdb46d7d5bb50838fdb3941bfc381634cf08a3" +checksum = "bb561feb392bb8c4f540256073446e6689af087bf6356e8dddcf75fc279f201f" dependencies = [ "base64 0.11.0", "borsh", "bs58", "derive_more", - "near-account-id 0.12.0", + "near-account-id 0.13.0", "num-rational", "serde", - "sha2 0.9.9", + "sha2 0.10.2", + "strum", ] [[package]] name = "near-primitives-core" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb561feb392bb8c4f540256073446e6689af087bf6356e8dddcf75fc279f201f" +checksum = "91d508f0fc340f6461e4e256417685720d3c4c00bb5a939b105160e49137caba" dependencies = [ "base64 0.11.0", "borsh", "bs58", "derive_more", - "near-account-id 0.13.0", + "near-account-id 0.14.0", "num-rational", "serde", "sha2 0.10.2", - "strum 0.24.1", + "strum", ] [[package]] @@ -1874,9 +1855,9 @@ dependencies = [ [[package]] name = "near-rpc-error-core" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5b9fd54b177a2efc1203cd605dc3369289d9c2a74ddbfdfb372feb13be38060" +checksum = "77fdd7ea8d8f786878651c37691515d5053f827ae60894aa40c16882b78f77c9" dependencies = [ "quote", "serde", @@ -1885,9 +1866,9 @@ dependencies = [ [[package]] name = "near-rpc-error-core" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77fdd7ea8d8f786878651c37691515d5053f827ae60894aa40c16882b78f77c9" +checksum = "93ee0b41c75ef859c193a8ff1dadfa0c8207bc0ac447cc22259721ad769a1408" dependencies = [ "quote", "serde", @@ -1910,31 +1891,31 @@ dependencies = [ [[package]] name = "near-rpc-error-macro" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a38f5469f86f3c8ce0f39828f10a9c6aca2581d71a5c176a1c9be7e7eb4511a3" +checksum = "e521842b6ae864dfe5391afbbe2df9e9d8427c26e9333b2e0b65cd42094f7607" dependencies = [ - "near-rpc-error-core 0.12.0", + "near-rpc-error-core 0.13.0", "serde", "syn", ] [[package]] name = "near-rpc-error-macro" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e521842b6ae864dfe5391afbbe2df9e9d8427c26e9333b2e0b65cd42094f7607" +checksum = "8e837bd4bacd807073ec5ceb85708da7f721b46a4c2a978de86027fb0034ce31" dependencies = [ - "near-rpc-error-core 0.13.0", + "near-rpc-error-core 0.14.0", "serde", "syn", ] [[package]] name = "near-sandbox-utils" -version = "0.2.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a543af5c633d7351ff92bbb523f040ffd393b7460d10ee7478282221a57abcf" +checksum = "bafbc6e0f88ba3c4dd41d947d6ef86367dc2d9b5e0112bde1a5ae8251a71b4f7" dependencies = [ "anyhow", "async-process", @@ -2016,25 +1997,25 @@ dependencies = [ [[package]] name = "near-vm-errors" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5092bbad4e16e48423d9be92e18b84af8e128c263df66d867a3f99c560b3cb28" +checksum = "0e02faf2bc1f6ef82b965cfe44389808fb5594f7aca4b596766117f4ce74df20" dependencies = [ "borsh", - "near-account-id 0.12.0", - "near-rpc-error-macro 0.12.0", + "near-account-id 0.13.0", + "near-rpc-error-macro 0.13.0", "serde", ] [[package]] name = "near-vm-errors" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e02faf2bc1f6ef82b965cfe44389808fb5594f7aca4b596766117f4ce74df20" +checksum = "d0da466a30f0446639cbd788c30865086fac3e8dcb07a79e51d2b0775ed4261e" dependencies = [ "borsh", - "near-account-id 0.13.0", - "near-rpc-error-macro 0.13.0", + "near-account-id 0.14.0", + "near-rpc-error-macro 0.14.0", "serde", ] @@ -2277,17 +2258,6 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72" -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core 0.8.5", -] - [[package]] name = "parking_lot" version = "0.12.1" @@ -2295,21 +2265,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" dependencies = [ "lock_api", - "parking_lot_core 0.9.3", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216" -dependencies = [ - "cfg-if 1.0.0", - "instant", - "libc", - "redox_syscall 0.2.13", - "smallvec", - "winapi", + "parking_lot_core", ] [[package]] @@ -2436,27 +2392,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "prometheus" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8425533e7122f0c3cc7a37e6244b16ad3a2cc32ae7ac6276e2a75da0d9c200d" -dependencies = [ - "cfg-if 1.0.0", - "fnv", - "lazy_static", - "parking_lot 0.11.2", - "protobuf", - "regex", - "thiserror", -] - -[[package]] -name = "protobuf" -version = "2.27.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf7e6d18738ecd0902d30d1ad232c9125985a3422929b16c65517b38adc14f96" - [[package]] name = "quote" version = "1.0.20" @@ -3063,34 +2998,13 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "strum" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7318c509b5ba57f18533982607f24070a55d353e90d4cae30c467cdb2ad5ac5c" -dependencies = [ - "strum_macros 0.20.1", -] - [[package]] name = "strum" version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" dependencies = [ - "strum_macros 0.24.0", -] - -[[package]] -name = "strum_macros" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee8bc6b87a5112aeeab1f4a9f7ab634fe6cbefc4850006df31267f4cfb9e3149" -dependencies = [ - "heck 0.3.3", - "proc-macro2", - "quote", - "syn", + "strum_macros", ] [[package]] @@ -3099,7 +3013,7 @@ version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6878079b17446e4d3eba6192bb0a2950d5b14f0ed8424b852310e5a94345d0ef" dependencies = [ - "heck 0.4.0", + "heck", "proc-macro2", "quote", "rustversion", @@ -3233,7 +3147,7 @@ dependencies = [ "mio", "num_cpus", "once_cell", - "parking_lot 0.12.1", + "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2", @@ -3273,20 +3187,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-util" -version = "0.6.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "log", - "pin-project-lite", - "tokio", -] - [[package]] name = "tokio-util" version = "0.7.3" @@ -3393,12 +3293,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-segmentation" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99" - [[package]] name = "unicode-xid" version = "0.2.3" @@ -3676,9 +3570,9 @@ dependencies = [ [[package]] name = "workspaces" -version = "0.3.1" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1bcb8cee0423b071bbbf0699cee998e48012d499c474780903de8233ae63fce" +checksum = "c8b8e4bc0367196fe6386e2c2325c13ee36066392682142d485237e355350e26" dependencies = [ "anyhow", "async-trait", @@ -3688,11 +3582,11 @@ dependencies = [ "dirs 3.0.2", "hex 0.4.3", "libc", - "near-account-id 0.12.0", - "near-crypto 0.12.0", + "near-account-id 0.14.0", + "near-crypto 0.14.0", "near-jsonrpc-client", "near-jsonrpc-primitives", - "near-primitives 0.12.0", + "near-primitives 0.14.0", "near-sandbox-utils", "portpicker", "rand 0.8.5", diff --git a/Cargo.toml b/Cargo.toml index b7f07bf..e5988bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ mock-oct-token = { path = "./mock-oct-token" } wrapped-appchain-token = { git = "https://github.com/octopus-network/wrapped-appchain-token.git", branch = "v2.0.0" } wrapped-appchain-nft = { git = "https://github.com/octopus-network/wrapped-appchain-nft.git", branch = "main" } tokio = { version = "1.14", features = ["full"] } -workspaces = "0.3" +workspaces = "0.4" [profile.release] codegen-units = 1 diff --git a/tests/simulator/common/basic_actions.rs b/tests/simulator/common/basic_actions.rs index 866c967..faa7d90 100644 --- a/tests/simulator/common/basic_actions.rs +++ b/tests/simulator/common/basic_actions.rs @@ -19,7 +19,7 @@ pub async fn initialize_contracts_and_users( Contract, Vec, )> { - let root = worker.root_account(); + let root = worker.root_account().unwrap(); let mut users: Vec = Vec::new(); // // deploy OCT token contract From d61213b0ba6228eeade82dd39ff30cc3ccb2bae7 Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Wed, 24 Aug 2022 15:07:35 +0800 Subject: [PATCH 3/9] Change implementation of some sudo functions. To resolve the problem that the gas they cost may exceed the gas limitation of a `function call`. --- appchain-anchor/src/appchain_messages.rs | 8 +- appchain-anchor/src/interfaces.rs | 26 +++- appchain-anchor/src/lib.rs | 24 +++- appchain-anchor/src/lookup_array.rs | 41 +++++-- .../distributing_rewards.rs | 2 +- .../src/permissionless_actions/mod.rs | 2 +- appchain-anchor/src/storage_migration.rs | 26 ++-- appchain-anchor/src/types.rs | 26 +++- .../src/user_actions/sudo_actions.rs | 116 +++++++++++++++--- appchain-anchor/src/user_staking_histories.rs | 14 ++- appchain-anchor/src/validator_set/mod.rs | 9 +- .../src/validator_set/next_validator_set.rs | 11 +- .../src/validator_set/validator_set_of_era.rs | 22 +++- tests/simulator/test_beefy_light_client_2.rs | 2 +- 14 files changed, 261 insertions(+), 68 deletions(-) diff --git a/appchain-anchor/src/appchain_messages.rs b/appchain-anchor/src/appchain_messages.rs index 819582a..8a60df2 100644 --- a/appchain-anchor/src/appchain_messages.rs +++ b/appchain-anchor/src/appchain_messages.rs @@ -98,8 +98,12 @@ impl IndexedAndClearable for u32 { () } // - fn clear_extra_storage(&mut self) { - () + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + MultiTxsOperationProcessingResult::NeedMoreGas + } else { + MultiTxsOperationProcessingResult::Ok + } } } diff --git a/appchain-anchor/src/interfaces.rs b/appchain-anchor/src/interfaces.rs index a6727de..c660c16 100644 --- a/appchain-anchor/src/interfaces.rs +++ b/appchain-anchor/src/interfaces.rs @@ -344,15 +344,21 @@ pub trait SudoActions { value: U128, ); /// - fn reset_validator_set_histories_to(&mut self, era_number: U64); + fn reset_validator_set_histories_to( + &mut self, + era_number: U64, + ) -> MultiTxsOperationProcessingResult; + /// + fn reset_staking_histories_to(&mut self, era_number: U64) -> MultiTxsOperationProcessingResult; /// - fn reset_staking_histories_to(&mut self, era_number: U64); + fn clear_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult; /// - fn refresh_user_staking_histories(&mut self); + fn regenerate_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult; /// - fn reset_next_validator_set_to(&mut self, era_number: U64); + fn reset_next_validator_set_to(&mut self, era_number: U64) + -> MultiTxsOperationProcessingResult; /// - fn clear_appchain_notification_histories(&mut self); + fn clear_appchain_notification_histories(&mut self) -> MultiTxsOperationProcessingResult; /// fn reset_beefy_light_client(&mut self, initial_public_keys: Vec); /// @@ -393,6 +399,16 @@ pub trait SudoActions { fn clear_appchain_messages(&mut self) -> MultiTxsOperationProcessingResult; /// fn try_complete_switching_era(&mut self) -> MultiTxsOperationProcessingResult; + /// + fn remove_validator_set_history_of( + &mut self, + era_number: U64, + ) -> MultiTxsOperationProcessingResult; + /// + fn remove_validator_set_histories_before( + &mut self, + era_number: U64, + ) -> MultiTxsOperationProcessingResult; } pub trait ValidatorActions { diff --git a/appchain-anchor/src/lib.rs b/appchain-anchor/src/lib.rs index c9763de..a57a38a 100644 --- a/appchain-anchor/src/lib.rs +++ b/appchain-anchor/src/lib.rs @@ -613,8 +613,12 @@ impl IndexedAndClearable for AppchainNotificationHistory { self.index = U64::from(*index); } // - fn clear_extra_storage(&mut self) { - () + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + MultiTxsOperationProcessingResult::NeedMoreGas + } else { + MultiTxsOperationProcessingResult::Ok + } } } @@ -624,8 +628,12 @@ impl IndexedAndClearable for StakingHistory { self.index = U64::from(*index); } // - fn clear_extra_storage(&mut self) { - () + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + MultiTxsOperationProcessingResult::NeedMoreGas + } else { + MultiTxsOperationProcessingResult::Ok + } } } @@ -635,7 +643,11 @@ impl IndexedAndClearable for AppchainChallenge { () } // - fn clear_extra_storage(&mut self) { - () + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + MultiTxsOperationProcessingResult::NeedMoreGas + } else { + MultiTxsOperationProcessingResult::Ok + } } } diff --git a/appchain-anchor/src/lookup_array.rs b/appchain-anchor/src/lookup_array.rs index 7d9303b..bbd1733 100644 --- a/appchain-anchor/src/lookup_array.rs +++ b/appchain-anchor/src/lookup_array.rs @@ -4,7 +4,7 @@ pub trait IndexedAndClearable { /// fn set_index(&mut self, index: &u64); /// - fn clear_extra_storage(&mut self); + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult; } #[derive(BorshDeserialize, BorshSerialize)] @@ -97,25 +97,33 @@ where self.lookup_map.get(&index).unwrap() } /// - pub fn remove_before(&mut self, index: &u64) { + pub fn remove_before(&mut self, index: &u64) -> MultiTxsOperationProcessingResult { if self.start_index >= *index { - return; + return MultiTxsOperationProcessingResult::Ok; } for index in self.start_index..*index { - self.remove_at(&index); + let result = self.remove_at(&index); + if !result.is_ok() { + return result; + } } self.start_index = *index; + MultiTxsOperationProcessingResult::Ok } /// - pub fn reset_to(&mut self, index: &u64) { + pub fn reset_to(&mut self, index: &u64) -> MultiTxsOperationProcessingResult { assert!( *index >= self.start_index && *index <= self.end_index, "Invalid history data index." ); for index in (*index + 1)..self.end_index + 1 { - self.remove_at(&index); + let result = self.remove_at(&index); + if !result.is_ok() { + return result; + } } self.end_index = *index; + MultiTxsOperationProcessingResult::Ok } /// pub fn clear(&mut self) -> MultiTxsOperationProcessingResult { @@ -125,10 +133,7 @@ where self.end_index ); let mut index = self.start_index; - while index <= self.end_index - && env::used_gas() < Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) - { - self.remove_at(&index); + while index <= self.end_index && self.remove_at(&index).is_ok() { index += 1; } if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { @@ -141,10 +146,20 @@ where } } /// - pub fn remove_at(&mut self, index: &u64) { + pub fn remove_at(&mut self, index: &u64) -> MultiTxsOperationProcessingResult { if let Some(mut record) = self.lookup_map.get(index) { - record.clear_extra_storage(); - self.lookup_map.remove_raw(&index.try_to_vec().unwrap()); + let result = record.clear_extra_storage(); + match result { + MultiTxsOperationProcessingResult::Ok => { + self.lookup_map.remove_raw(&index.try_to_vec().unwrap()); + } + MultiTxsOperationProcessingResult::NeedMoreGas => { + self.lookup_map.insert(index, &record); + } + MultiTxsOperationProcessingResult::Error(_) => (), + } + return result; } + MultiTxsOperationProcessingResult::Ok } } diff --git a/appchain-anchor/src/permissionless_actions/distributing_rewards.rs b/appchain-anchor/src/permissionless_actions/distributing_rewards.rs index ad1b13e..6f7608d 100644 --- a/appchain-anchor/src/permissionless_actions/distributing_rewards.rs +++ b/appchain-anchor/src/permissionless_actions/distributing_rewards.rs @@ -82,7 +82,7 @@ impl AppchainAnchor { appchain_message_nonce, processing_context, ); - if result.eq(&MultiTxsOperationProcessingResult::Ok) { + if result.is_ok() { result = MultiTxsOperationProcessingResult::NeedMoreGas; } result diff --git a/appchain-anchor/src/permissionless_actions/mod.rs b/appchain-anchor/src/permissionless_actions/mod.rs index 96ef32b..e9cd62e 100644 --- a/appchain-anchor/src/permissionless_actions/mod.rs +++ b/appchain-anchor/src/permissionless_actions/mod.rs @@ -286,7 +286,7 @@ impl PermissionlessActions for AppchainAnchor { self.permissionless_actions_status .set(processing_context.processing_status()); self.validator_set_histories.set(&validator_set_histories); - if result.eq(&MultiTxsOperationProcessingResult::Ok) + if result.is_ok() && processing_context.latest_applied_nonce() < processing_context.max_nonce() { result = MultiTxsOperationProcessingResult::NeedMoreGas; diff --git a/appchain-anchor/src/storage_migration.rs b/appchain-anchor/src/storage_migration.rs index f09f19d..47f79eb 100644 --- a/appchain-anchor/src/storage_migration.rs +++ b/appchain-anchor/src/storage_migration.rs @@ -298,7 +298,7 @@ impl OldAppchainAnchor { let mut anchor_event_histories = self.anchor_event_histories.get().unwrap(); let result = anchor_event_histories.clear(); self.anchor_event_histories.set(&anchor_event_histories); - if result.eq(&MultiTxsOperationProcessingResult::Ok) { + if result.is_ok() { self.anchor_event_histories.remove(); } else { panic!("Should clear old anchor events first."); @@ -312,8 +312,12 @@ impl IndexedAndClearable for OldAnchorEventHistory { self.index = U64::from(*index); } // - fn clear_extra_storage(&mut self) { - () + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + MultiTxsOperationProcessingResult::NeedMoreGas + } else { + MultiTxsOperationProcessingResult::Ok + } } } @@ -323,8 +327,12 @@ impl IndexedAndClearable for OldAppchainNotificationHistory { self.index = U64::from(*index); } // - fn clear_extra_storage(&mut self) { - () + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + MultiTxsOperationProcessingResult::NeedMoreGas + } else { + MultiTxsOperationProcessingResult::Ok + } } } @@ -334,8 +342,12 @@ impl IndexedAndClearable for OldStakingHistory { self.index = U64::from(*index); } // - fn clear_extra_storage(&mut self) { - () + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + MultiTxsOperationProcessingResult::NeedMoreGas + } else { + MultiTxsOperationProcessingResult::Ok + } } } diff --git a/appchain-anchor/src/types.rs b/appchain-anchor/src/types.rs index f1ec392..655c271 100644 --- a/appchain-anchor/src/types.rs +++ b/appchain-anchor/src/types.rs @@ -557,7 +557,7 @@ pub enum AppchainMessageProcessingResult { Error { nonce: u32, message: String }, } -#[derive(Serialize, Deserialize, Clone, PartialEq)] +#[derive(Serialize, Deserialize, Clone)] #[serde(crate = "near_sdk::serde")] pub enum MultiTxsOperationProcessingResult { NeedMoreGas, @@ -565,6 +565,30 @@ pub enum MultiTxsOperationProcessingResult { Error(String), } +impl MultiTxsOperationProcessingResult { + /// + pub fn is_ok(&self) -> bool { + match self { + MultiTxsOperationProcessingResult::Ok => true, + _ => false, + } + } + /// + pub fn is_need_more_gas(&self) -> bool { + match self { + MultiTxsOperationProcessingResult::NeedMoreGas => true, + _ => false, + } + } + /// + pub fn is_error(&self) -> bool { + match self { + MultiTxsOperationProcessingResult::Error(_) => true, + _ => false, + } + } +} + #[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Clone)] #[serde(crate = "near_sdk::serde")] pub struct ValidatorMerkleProof { diff --git a/appchain-anchor/src/user_actions/sudo_actions.rs b/appchain-anchor/src/user_actions/sudo_actions.rs index 6d17dc1..f2a2502 100644 --- a/appchain-anchor/src/user_actions/sudo_actions.rs +++ b/appchain-anchor/src/user_actions/sudo_actions.rs @@ -1,3 +1,5 @@ +use core::panic; + use crate::permissionless_actions::AppchainMessagesProcessingContext; use crate::*; use crate::{appchain_messages::AppchainMessage, interfaces::SudoActions}; @@ -47,61 +49,118 @@ impl SudoActions for AppchainAnchor { self.wrapped_appchain_token.set(&wrapped_appchain_token); } // - fn reset_validator_set_histories_to(&mut self, era_number: U64) { + fn reset_validator_set_histories_to( + &mut self, + era_number: U64, + ) -> MultiTxsOperationProcessingResult { self.assert_owner(); let mut validator_set_histories = self.validator_set_histories.get().unwrap(); - validator_set_histories.reset_to(&era_number.0); - self.validator_set_histories.set(&validator_set_histories); + let result = validator_set_histories.reset_to(&era_number.0); + if !result.is_error() { + self.validator_set_histories.set(&validator_set_histories); + } + result } // - fn reset_staking_histories_to(&mut self, era_number: U64) { + fn reset_staking_histories_to(&mut self, era_number: U64) -> MultiTxsOperationProcessingResult { self.assert_owner(); let validator_set_histories = self.validator_set_histories.get().unwrap(); if let Some(validator_set_of_era) = validator_set_histories.get(&era_number.0) { let mut staking_histories = self.staking_histories.get().unwrap(); - staking_histories.reset_to(&validator_set_of_era.staking_history_index()); - self.staking_histories.set(&staking_histories); + let result = staking_histories.reset_to(&validator_set_of_era.staking_history_index()); + if !result.is_error() { + self.staking_histories.set(&staking_histories); + } + return result; + } else { + panic!( + "Missing validator set history of era_number '{}'.", + era_number.0 + ); + } + } + // + fn clear_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult { + self.assert_owner(); + let mut user_staking_histories = self.user_staking_histories.get().unwrap(); + let result = user_staking_histories.clear(); + if !result.is_error() { + self.user_staking_histories.set(&user_staking_histories); } + result } // - fn refresh_user_staking_histories(&mut self) { + fn regenerate_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult { self.assert_owner(); let mut user_staking_histories = self.user_staking_histories.get().unwrap(); - user_staking_histories.clear(); let staking_histories = self.staking_histories.get().unwrap(); let index_range = staking_histories.index_range(); for index in index_range.start_index.0..index_range.end_index.0 + 1 { if let Some(staking_history) = staking_histories.get(&index) { user_staking_histories.add_staking_history(&staking_history); } + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + self.user_staking_histories.set(&user_staking_histories); + return MultiTxsOperationProcessingResult::NeedMoreGas; + } } self.user_staking_histories.set(&user_staking_histories); + MultiTxsOperationProcessingResult::Ok } // - fn reset_next_validator_set_to(&mut self, era_number: U64) { + // While using this function to reset data of next validator set, this contract must + // refuse any other actions which will change the state of next validator set. + // + fn reset_next_validator_set_to( + &mut self, + era_number: U64, + ) -> MultiTxsOperationProcessingResult { self.assert_owner(); let validator_set_histories = self.validator_set_histories.get().unwrap(); if let Some(validator_set_of_era) = validator_set_histories.get(&era_number.0) { let mut next_validator_set = self.next_validator_set.get().unwrap(); - next_validator_set.clear(); + let result = next_validator_set.clear(); + match result { + MultiTxsOperationProcessingResult::Ok => (), + MultiTxsOperationProcessingResult::NeedMoreGas => { + self.next_validator_set.set(&next_validator_set); + return result; + } + MultiTxsOperationProcessingResult::Error(_) => { + return result; + } + } let staking_history_index = validator_set_of_era.staking_history_index(); let staking_histories = self.staking_histories.get().unwrap(); for index in 0..staking_history_index + 1 { if let Some(staking_history) = staking_histories.get(&index) { next_validator_set.apply_staking_fact(&staking_history.staking_fact); } + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + self.next_validator_set.set(&next_validator_set); + return MultiTxsOperationProcessingResult::NeedMoreGas; + } } self.next_validator_set.set(&next_validator_set); + MultiTxsOperationProcessingResult::Ok + } else { + panic!( + "Missing validator set history of era_number '{}'.", + era_number.0 + ); } } // - fn clear_appchain_notification_histories(&mut self) { + fn clear_appchain_notification_histories(&mut self) -> MultiTxsOperationProcessingResult { self.assert_owner(); let mut appchain_notification_histories = self.appchain_notification_histories.get().unwrap(); - appchain_notification_histories.clear(); - self.appchain_notification_histories - .set(&appchain_notification_histories); + let result = appchain_notification_histories.clear(); + if !result.is_error() { + self.appchain_notification_histories + .set(&appchain_notification_histories); + } + result } // fn reset_beefy_light_client(&mut self, initial_public_keys: Vec) { @@ -296,7 +355,9 @@ impl SudoActions for AppchainAnchor { self.assert_owner(); let mut appchain_messages = self.appchain_messages.get().unwrap(); let result = appchain_messages.clear(); - self.appchain_messages.set(&appchain_messages); + if !result.is_error() { + self.appchain_messages.set(&appchain_messages); + } result } // @@ -318,4 +379,29 @@ impl SudoActions for AppchainAnchor { MultiTxsOperationProcessingResult::Ok } } + // + fn remove_validator_set_history_of( + &mut self, + era_number: U64, + ) -> MultiTxsOperationProcessingResult { + let mut validator_set_histories = self.validator_set_histories.get().unwrap(); + let result = validator_set_histories.remove_at(&era_number.0); + if !result.is_error() { + self.validator_set_histories.set(&validator_set_histories); + } + result + } + // + fn remove_validator_set_histories_before( + &mut self, + era_number: U64, + ) -> MultiTxsOperationProcessingResult { + self.assert_owner(); + let mut validator_set_histories = self.validator_set_histories.get().unwrap(); + let result = validator_set_histories.remove_before(&era_number.0); + if !result.is_error() { + self.validator_set_histories.set(&validator_set_histories); + } + result + } } diff --git a/appchain-anchor/src/user_staking_histories.rs b/appchain-anchor/src/user_staking_histories.rs index d9c04af..8988b58 100644 --- a/appchain-anchor/src/user_staking_histories.rs +++ b/appchain-anchor/src/user_staking_histories.rs @@ -53,10 +53,14 @@ impl UserStakingHistories { } } /// - pub fn clear(&mut self) { - self.account_id_set.to_vec().iter().for_each(|account_id| { - self.staking_histories_map.remove(account_id); - }); - self.account_id_set.clear(); + pub fn clear(&mut self) -> MultiTxsOperationProcessingResult { + for account_id in self.account_id_set.to_vec() { + self.staking_histories_map.remove(&account_id); + self.account_id_set.remove(&account_id); + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + return MultiTxsOperationProcessingResult::NeedMoreGas; + } + } + MultiTxsOperationProcessingResult::Ok } } diff --git a/appchain-anchor/src/validator_set/mod.rs b/appchain-anchor/src/validator_set/mod.rs index 6894e6e..73829af 100644 --- a/appchain-anchor/src/validator_set/mod.rs +++ b/appchain-anchor/src/validator_set/mod.rs @@ -114,7 +114,7 @@ impl ValidatorSet { } } /// - pub fn clear(&mut self) { + pub fn clear(&mut self) -> MultiTxsOperationProcessingResult { let validator_ids = self.validator_id_set.to_vec(); for validator_id in validator_ids { if let Some(mut delegator_id_set) = @@ -130,14 +130,21 @@ impl ValidatorSet { validator_id_set_of_delegator.clear(); self.delegator_id_to_validator_id_set.remove(&delegator_id); } + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + return MultiTxsOperationProcessingResult::NeedMoreGas; + } } delegator_id_set.clear(); self.validator_id_to_delegator_id_set.remove(&validator_id); self.validators.remove(&validator_id); + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + return MultiTxsOperationProcessingResult::NeedMoreGas; + } } } self.validator_id_set.clear(); self.total_stake = 0; + MultiTxsOperationProcessingResult::Ok } // fn apply_staking_fact(&mut self, staking_fact: &StakingFact) { diff --git a/appchain-anchor/src/validator_set/next_validator_set.rs b/appchain-anchor/src/validator_set/next_validator_set.rs index 5c46688..8a10ee5 100644 --- a/appchain-anchor/src/validator_set/next_validator_set.rs +++ b/appchain-anchor/src/validator_set/next_validator_set.rs @@ -34,10 +34,13 @@ impl NextValidatorSet { &self.validator_set } /// - pub fn clear(&mut self) { - self.validator_set.clear(); - self.unbonding_validator_ids.clear(); - self.auto_unbonding_validator_ids.clear(); + pub fn clear(&mut self) -> MultiTxsOperationProcessingResult { + let result = self.validator_set.clear(); + if result.is_ok() { + self.unbonding_validator_ids.clear(); + self.auto_unbonding_validator_ids.clear(); + } + result } /// pub fn apply_staking_fact(&mut self, staking_fact: &StakingFact) { diff --git a/appchain-anchor/src/validator_set/validator_set_of_era.rs b/appchain-anchor/src/validator_set/validator_set_of_era.rs index bd3c7fb..677bba2 100644 --- a/appchain-anchor/src/validator_set/validator_set_of_era.rs +++ b/appchain-anchor/src/validator_set/validator_set_of_era.rs @@ -217,7 +217,7 @@ impl ValidatorSetOfEra { } } /// - pub fn clear_reward_distribution_records(&mut self) { + pub fn clear_reward_distribution_records(&mut self) -> MultiTxsOperationProcessingResult { let validator_ids = self.validator_set.validator_id_set.to_vec(); for validator_id in validator_ids { if self.unprofitable_validator_id_set.contains(&validator_id) { @@ -232,16 +232,26 @@ impl ValidatorSetOfEra { for delegator_id in delegator_ids { self.delegator_rewards .remove(&(delegator_id.clone(), validator_id.clone())); + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + return MultiTxsOperationProcessingResult::NeedMoreGas; + } } } self.validator_rewards.remove(&validator_id); + if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { + return MultiTxsOperationProcessingResult::NeedMoreGas; + } } self.unprofitable_validator_id_set.clear(); + MultiTxsOperationProcessingResult::Ok } /// - pub fn clear(&mut self) { - self.clear_reward_distribution_records(); - self.validator_set.clear(); + pub fn clear(&mut self) -> MultiTxsOperationProcessingResult { + let mut result = self.clear_reward_distribution_records(); + if result.is_ok() { + result = self.validator_set.clear(); + } + result } // pub fn apply_staking_fact(&mut self, staking_fact: &StakingFact) { @@ -383,7 +393,7 @@ impl IndexedAndClearable for ValidatorSetOfEra { () } // - fn clear_extra_storage(&mut self) { - self.clear(); + fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult { + self.clear() } } diff --git a/tests/simulator/test_beefy_light_client_2.rs b/tests/simulator/test_beefy_light_client_2.rs index 999b0ec..32af53f 100644 --- a/tests/simulator/test_beefy_light_client_2.rs +++ b/tests/simulator/test_beefy_light_client_2.rs @@ -105,7 +105,7 @@ async fn test_beefy_light_client_2() -> anyhow::Result<()> { "Result of 'try_complete_updating_state_of_beefy_light_client': {}", serde_json::to_string::(&result).unwrap() ); - if !result.eq(&MultiTxsOperationProcessingResult::NeedMoreGas) { + if !result.is_need_more_gas() { break; } } From 73aaf339ef918eccbb896af4f6619a4818709dd1 Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Tue, 30 Aug 2022 15:09:31 +0800 Subject: [PATCH 4/9] Change condition of auto-unbonding validator. --- .../src/permissionless_actions/distributing_rewards.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/appchain-anchor/src/permissionless_actions/distributing_rewards.rs b/appchain-anchor/src/permissionless_actions/distributing_rewards.rs index 6f7608d..2b038da 100644 --- a/appchain-anchor/src/permissionless_actions/distributing_rewards.rs +++ b/appchain-anchor/src/permissionless_actions/distributing_rewards.rs @@ -179,7 +179,9 @@ impl AppchainAnchor { let validator_id = unprofitable_validators .get(usize::try_from(unprofitable_validator_index.0).unwrap()) .unwrap(); - if next_validator_set.contains_validator(validator_id) { + if validator_set.contains_validator(validator_id) + && next_validator_set.contains_validator(validator_id) + { let start_checking_index = match era_number >= u64::from(protocol_settings.maximum_allowed_unprofitable_era_count) { From cf29dbaf51c334bccf8095a07ed9b89a38c26bfa Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Fri, 2 Sep 2022 15:14:40 +0800 Subject: [PATCH 5/9] Fix bug in resolving fungible token transfer. --- appchain-anchor/src/assets/near_fungible_tokens.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/appchain-anchor/src/assets/near_fungible_tokens.rs b/appchain-anchor/src/assets/near_fungible_tokens.rs index ebf5fe4..e47b446 100644 --- a/appchain-anchor/src/assets/near_fungible_tokens.rs +++ b/appchain-anchor/src/assets/near_fungible_tokens.rs @@ -365,7 +365,7 @@ impl FungibleTokenContractResolver for AppchainAnchor { symbol: String, sender_id_in_appchain: String, receiver_id_in_near: AccountId, - _amount: U128, + amount: U128, appchain_message_nonce: u32, ) { assert_self(); @@ -385,8 +385,8 @@ impl FungibleTokenContractResolver for AppchainAnchor { &receiver_id_in_near, &symbol ); let message = format!( - "Failed to unlock near fungible token for appchain account '{}'. {}", - sender_id_in_appchain, reason + "Failed to unlock near fungible token '{}' with amount '{}' for appchain account '{}'. {}", + symbol, amount.0, sender_id_in_appchain, reason ); self.record_appchain_message_processing_result( &AppchainMessageProcessingResult::Error { From 0a3558580645188cc5fc8bb6268519bb3953bc14 Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Sat, 3 Sep 2022 01:27:41 +0800 Subject: [PATCH 6/9] Add a sudo function and fix bugs. --- .../src/assets/wrapped_appchain_token.rs | 23 +++--- appchain-anchor/src/interfaces.rs | 7 ++ .../distributing_rewards.rs | 17 +++- appchain-anchor/src/storage_migration.rs | 68 +++++++--------- .../src/user_actions/sudo_actions.rs | 81 ++++++++++++++++++- 5 files changed, 141 insertions(+), 55 deletions(-) diff --git a/appchain-anchor/src/assets/wrapped_appchain_token.rs b/appchain-anchor/src/assets/wrapped_appchain_token.rs index 0bc15cd..a355ac2 100644 --- a/appchain-anchor/src/assets/wrapped_appchain_token.rs +++ b/appchain-anchor/src/assets/wrapped_appchain_token.rs @@ -282,22 +282,19 @@ impl WrappedAppchainTokenContractResolver for AppchainAnchor { wrapped_appchain_token.changed_balance.0 + i128::try_from(amount.0).unwrap(), ); self.wrapped_appchain_token.set(&wrapped_appchain_token); - let message = match sender_id_in_appchain { - Some(sender_id) => format!( + if let Some(sender_id) = sender_id_in_appchain { + // Only generate appchain message processing result in cross-chain transfer case + let message = format!( "Wrapped appchain token minted by '{}' of appchain for '{}' with amount '{}'.", &sender_id, &receiver_id_in_near, &amount.0 - ), - None => format!( - "Wrapped appchain token minted by crosschain message for '{}' with amount '{}'.", - &receiver_id_in_near, &amount.0 - ), + ); + self.record_appchain_message_processing_result( + &AppchainMessageProcessingResult::Ok { + nonce: appchain_message_nonce, + message: Some(message), + }, + ); }; - self.record_appchain_message_processing_result( - &AppchainMessageProcessingResult::Ok { - nonce: appchain_message_nonce, - message: Some(message), - }, - ); } PromiseResult::Failed => { let reason = format!("Maybe the total supply will overflow."); diff --git a/appchain-anchor/src/interfaces.rs b/appchain-anchor/src/interfaces.rs index c660c16..7954523 100644 --- a/appchain-anchor/src/interfaces.rs +++ b/appchain-anchor/src/interfaces.rs @@ -409,6 +409,13 @@ pub trait SudoActions { &mut self, era_number: U64, ) -> MultiTxsOperationProcessingResult; + /// + fn unlock_auto_unbonded_stake_of( + &mut self, + delegator_id: Option, + validator_id: AccountId, + staking_history_index: U64, + ); } pub trait ValidatorActions { diff --git a/appchain-anchor/src/permissionless_actions/distributing_rewards.rs b/appchain-anchor/src/permissionless_actions/distributing_rewards.rs index 2b038da..818060e 100644 --- a/appchain-anchor/src/permissionless_actions/distributing_rewards.rs +++ b/appchain-anchor/src/permissionless_actions/distributing_rewards.rs @@ -170,11 +170,10 @@ impl AppchainAnchor { if unprofitable_validator_index.0 >= unprofitable_validators.len().try_into().unwrap() { - processing_context.clear_distributing_reward_era_number(); validator_set .set_processing_status(ValidatorSetProcessingStatus::Completed); validator_set_histories.insert(&era_number, &validator_set); - return MultiTxsOperationProcessingResult::Ok; + return MultiTxsOperationProcessingResult::NeedMoreGas; } let validator_id = unprofitable_validators .get(usize::try_from(unprofitable_validator_index.0).unwrap()) @@ -226,7 +225,19 @@ impl AppchainAnchor { validator_set_histories.insert(&era_number, &validator_set); MultiTxsOperationProcessingResult::NeedMoreGas } - ValidatorSetProcessingStatus::Completed => MultiTxsOperationProcessingResult::Ok, + ValidatorSetProcessingStatus::Completed => { + self.record_appchain_message_processing_result( + &AppchainMessageProcessingResult::Ok { + nonce: processing_context.processing_nonce().unwrap_or(0), + message: Some(format!( + "Completed distributing era rewards for validator set '{}'.", + era_number + )), + }, + ); + processing_context.clear_distributing_reward_era_number(); + MultiTxsOperationProcessingResult::Ok + } } } // diff --git a/appchain-anchor/src/storage_migration.rs b/appchain-anchor/src/storage_migration.rs index 47f79eb..03896b6 100644 --- a/appchain-anchor/src/storage_migration.rs +++ b/appchain-anchor/src/storage_migration.rs @@ -113,11 +113,11 @@ pub struct OldAppchainAnchor { /// The state of the corresponding appchain. appchain_state: AppchainState, /// The staking history data happened in this contract. - staking_histories: LazyOption>, + staking_histories: LazyOption>, /// The anchor event history data. anchor_event_histories: LazyOption>, /// The appchain notification history data. - appchain_notification_histories: LazyOption>, + appchain_notification_histories: LazyOption>, /// The status of permissionless actions. permissionless_actions_status: LazyOption, /// The state of beefy light client @@ -169,16 +169,8 @@ impl AppchainAnchor { anchor_settings: old_contract.anchor_settings, protocol_settings: old_contract.protocol_settings, appchain_state: old_contract.appchain_state, - staking_histories: LazyOption::new( - StorageKey::StakingHistories.into_bytes(), - Some(&LookupArray::new(StorageKey::StakingHistoriesMap)), - ), - appchain_notification_histories: LazyOption::new( - StorageKey::AppchainNotificationHistories.into_bytes(), - Some(&LookupArray::new( - StorageKey::AppchainNotificationHistoriesMap, - )), - ), + staking_histories: old_contract.staking_histories, + appchain_notification_histories: old_contract.appchain_notification_histories, permissionless_actions_status: old_contract.permissionless_actions_status, beefy_light_client_state: old_contract.beefy_light_client_state, reward_distribution_records: old_contract.reward_distribution_records, @@ -212,13 +204,14 @@ impl AppchainAnchor { &StorageKey::StakingHistoriesMap, &index, )) { - let old_version = OldStakingHistory::try_from_slice(&old_data).unwrap(); - env::storage_write( - &get_storage_key_in_lookup_array(&StorageKey::StakingHistoriesMap, &index), - &StakingHistory::from_old_version(old_version) - .try_to_vec() - .unwrap(), - ); + if let Ok(old_version) = OldStakingHistory::try_from_slice(&old_data) { + env::storage_write( + &get_storage_key_in_lookup_array(&StorageKey::StakingHistoriesMap, &index), + &StakingHistory::from_old_version(old_version) + .try_to_vec() + .unwrap(), + ); + } } } MultiTxsOperationProcessingResult::Ok @@ -242,17 +235,17 @@ impl AppchainAnchor { &StorageKey::AppchainNotificationHistoriesMap, &index, )) { - let old_version = - OldAppchainNotificationHistory::try_from_slice(&old_data).unwrap(); - env::storage_write( - &get_storage_key_in_lookup_array( - &StorageKey::AppchainNotificationHistoriesMap, - &index, - ), - &AppchainNotificationHistory::from_old_version(old_version) - .try_to_vec() - .unwrap(), - ); + if let Ok(old_version) = OldAppchainNotificationHistory::try_from_slice(&old_data) { + env::storage_write( + &get_storage_key_in_lookup_array( + &StorageKey::AppchainNotificationHistoriesMap, + &index, + ), + &AppchainNotificationHistory::from_old_version(old_version) + .try_to_vec() + .unwrap(), + ); + } } } MultiTxsOperationProcessingResult::Ok @@ -275,13 +268,14 @@ impl AppchainAnchor { &StorageKey::AppchainMessageMap, &nonce, )) { - let old_version = OldAppchainMessage::try_from_slice(&old_data).unwrap(); - env::storage_write( - &get_storage_key_in_lookup_array(&StorageKey::AppchainMessageMap, &nonce), - &AppchainMessage::from_old_version(old_version) - .try_to_vec() - .unwrap(), - ); + if let Ok(old_version) = OldAppchainMessage::try_from_slice(&old_data) { + env::storage_write( + &get_storage_key_in_lookup_array(&StorageKey::AppchainMessageMap, &nonce), + &AppchainMessage::from_old_version(old_version) + .try_to_vec() + .unwrap(), + ); + } } } MultiTxsOperationProcessingResult::Ok diff --git a/appchain-anchor/src/user_actions/sudo_actions.rs b/appchain-anchor/src/user_actions/sudo_actions.rs index f2a2502..fcb2d3c 100644 --- a/appchain-anchor/src/user_actions/sudo_actions.rs +++ b/appchain-anchor/src/user_actions/sudo_actions.rs @@ -1,9 +1,9 @@ -use core::panic; - use crate::permissionless_actions::AppchainMessagesProcessingContext; use crate::*; use crate::{appchain_messages::AppchainMessage, interfaces::SudoActions}; use codec::Decode; +use core::panic; +use near_contract_standards::fungible_token::core::ext_ft_core; use near_contract_standards::fungible_token::metadata::FungibleTokenMetadata; #[near_bindgen] @@ -404,4 +404,81 @@ impl SudoActions for AppchainAnchor { } result } + // + fn unlock_auto_unbonded_stake_of( + &mut self, + delegator_id: Option, + validator_id: AccountId, + staking_history_index: U64, + ) { + self.assert_owner(); + self.assert_asset_transfer_is_not_paused(); + let unbonded_stake_references = match delegator_id.clone() { + Some(delegator_id) => self.unbonded_stakes.get(&delegator_id).unwrap(), + None => self.unbonded_stakes.get(&validator_id).unwrap(), + }; + let staking_histories = self.staking_histories.get().unwrap(); + let mut remained_stakes = Vec::::new(); + let mut found = false; + for reference in unbonded_stake_references { + if reference.staking_history_index == staking_history_index.0 { + let staking_history = staking_histories.get(&staking_history_index.0).unwrap(); + match staking_history.staking_fact { + StakingFact::ValidatorAutoUnbonded { + validator_id: unbonded_validator_id @ _, + amount, + } => { + assert!( + validator_id.eq(&unbonded_validator_id), + "Invalid staking history for validator '{}'.", + validator_id + ); + ext_ft_core::ext(self.oct_token.get().unwrap().contract_account) + .with_attached_deposit(1) + .with_static_gas(Gas::ONE_TERA.mul(T_GAS_FOR_FT_TRANSFER)) + .with_unused_gas_weight(0) + .ft_transfer(validator_id.clone(), amount.clone(), None); + found = true; + break; + } + StakingFact::DelegatorAutoUnbonded { + delegator_id: unbonded_delegator_id @ _, + validator_id: unbonded_validator_id @ _, + amount, + } => { + let delegator_id = delegator_id + .clone() + .unwrap_or(AccountId::new_unchecked(String::new())); + assert!( + validator_id.eq(&unbonded_validator_id) + && delegator_id.eq(&unbonded_delegator_id), + "Invalid staking history for delegator '{}' of validator '{}'.", + delegator_id, + validator_id + ); + ext_ft_core::ext(self.oct_token.get().unwrap().contract_account) + .with_attached_deposit(1) + .with_static_gas(Gas::ONE_TERA.mul(T_GAS_FOR_FT_TRANSFER)) + .with_unused_gas_weight(0) + .ft_transfer(delegator_id.clone(), amount.clone(), None); + found = true; + break; + } + _ => { + remained_stakes.push(reference.clone()); + } + } + } else { + remained_stakes.push(reference.clone()); + } + } + assert!(found, "Specified staking history is not found."); + if remained_stakes.len() > 0 { + self.unbonded_stakes + .insert(&delegator_id.unwrap_or(validator_id), &remained_stakes); + } else { + self.unbonded_stakes + .remove(&delegator_id.unwrap_or(validator_id)); + } + } } From eb17d9f03537a14318a5677f953ff76d1b7c5dd8 Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Tue, 6 Sep 2022 11:39:18 +0800 Subject: [PATCH 7/9] Change a few messages for appchain processing result. --- appchain-anchor/src/assets/near_fungible_tokens.rs | 8 ++++++-- appchain-anchor/src/assets/wrapped_appchain_nfts.rs | 8 +++++++- appchain-anchor/src/assets/wrapped_appchain_token.rs | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/appchain-anchor/src/assets/near_fungible_tokens.rs b/appchain-anchor/src/assets/near_fungible_tokens.rs index e47b446..0f6d30e 100644 --- a/appchain-anchor/src/assets/near_fungible_tokens.rs +++ b/appchain-anchor/src/assets/near_fungible_tokens.rs @@ -372,16 +372,20 @@ impl FungibleTokenContractResolver for AppchainAnchor { match env::promise_result(0) { PromiseResult::NotReady => unreachable!(), PromiseResult::Successful(_) => { + let message = format!( + "Near fungible token '{}' with amount '{}' for appchain account '{}' is unlocked.", + symbol, amount.0, sender_id_in_appchain + ); self.record_appchain_message_processing_result( &AppchainMessageProcessingResult::Ok { nonce: appchain_message_nonce, - message: None, + message: Some(message), }, ); } PromiseResult::Failed => { let reason = format!( - "Maybe the receiver account '{}' is not registered in '{}' token contract.", + "Maybe the receiver account '{}' is not exised, or it is not registered in '{}' token contract.", &receiver_id_in_near, &symbol ); let message = format!( diff --git a/appchain-anchor/src/assets/wrapped_appchain_nfts.rs b/appchain-anchor/src/assets/wrapped_appchain_nfts.rs index 9c2e95c..c80634e 100644 --- a/appchain-anchor/src/assets/wrapped_appchain_nfts.rs +++ b/appchain-anchor/src/assets/wrapped_appchain_nfts.rs @@ -499,10 +499,16 @@ impl WrappedAppchainNFTContractResolver for AppchainAnchor { match env::promise_result(0) { PromiseResult::NotReady => unreachable!(), PromiseResult::Successful(_) => { + let message = format!( + "NFT '{}' from appchain account '{}' with metadata '{}' is minted.", + instance_id, + owner_id_in_appchain, + serde_json::to_string(&token_metadata).unwrap(), + ); self.record_appchain_message_processing_result( &AppchainMessageProcessingResult::Ok { nonce: appchain_message_nonce, - message: None, + message: Some(message), }, ); } diff --git a/appchain-anchor/src/assets/wrapped_appchain_token.rs b/appchain-anchor/src/assets/wrapped_appchain_token.rs index a355ac2..0945dd4 100644 --- a/appchain-anchor/src/assets/wrapped_appchain_token.rs +++ b/appchain-anchor/src/assets/wrapped_appchain_token.rs @@ -285,7 +285,7 @@ impl WrappedAppchainTokenContractResolver for AppchainAnchor { if let Some(sender_id) = sender_id_in_appchain { // Only generate appchain message processing result in cross-chain transfer case let message = format!( - "Wrapped appchain token minted by '{}' of appchain for '{}' with amount '{}'.", + "Wrapped appchain token is minted by '{}' of appchain for '{}' with amount '{}'.", &sender_id, &receiver_id_in_near, &amount.0 ); self.record_appchain_message_processing_result( From 4d029a9492a815ae9ae5004a4a46f1571adec262 Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Wed, 7 Sep 2022 12:23:22 +0800 Subject: [PATCH 8/9] Fix a typo. --- appchain-anchor/src/appchain_messages.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appchain-anchor/src/appchain_messages.rs b/appchain-anchor/src/appchain_messages.rs index 8a60df2..3d44bea 100644 --- a/appchain-anchor/src/appchain_messages.rs +++ b/appchain-anchor/src/appchain_messages.rs @@ -297,7 +297,7 @@ impl AppchainAnchor { raw_message.nonce as u32, &AppchainMessageProcessingResult::Error { nonce: raw_message.nonce as u32, - message: format!("Failed to deserialize raw message paylod: {}", err), + message: format!("Failed to deserialize raw message payload: {}", err), }, ), } From a620912a73ee454f7f7c42fffd9cb71975c88c43 Mon Sep 17 00:00:00 2001 From: Rivers Yang Date: Fri, 9 Sep 2022 07:57:21 +0800 Subject: [PATCH 9/9] Remove some dangerous sudo functions. And fix testing code. --- Cargo.lock | 1 + Cargo.toml | 1 + appchain-anchor/src/appchain_messages.rs | 20 +- appchain-anchor/src/interfaces.rs | 50 -- appchain-anchor/src/lib.rs | 2 +- .../src/permissionless_actions/mod.rs | 6 +- .../src/user_actions/sudo_actions.rs | 296 +----------- tests/simulator/common/basic_actions.rs | 8 + tests/simulator/common/complex_actions.rs | 71 ++- tests/simulator/common/mod.rs | 6 + tests/simulator/contract_interfaces/mod.rs | 1 - .../permissionless_actions.rs | 25 + .../contract_interfaces/settings_manager.rs | 32 ++ .../contract_interfaces/sudo_actions.rs | 91 ---- tests/simulator/test_anchor_actions.rs | 134 +++--- tests/simulator/test_beefy_light_client.rs | 70 ++- tests/simulator/test_beefy_light_client_2.rs | 5 + tests/simulator/test_transfer_nft.rs | 195 +++++--- .../simulator/test_wrapped_appchain_token.rs | 447 +++++++++++------- 19 files changed, 650 insertions(+), 811 deletions(-) delete mode 100644 tests/simulator/contract_interfaces/sudo_actions.rs diff --git a/Cargo.lock b/Cargo.lock index d147dea..d4ce143 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -124,6 +124,7 @@ dependencies = [ "near-sdk", "near-units", "num-format", + "parity-scale-codec 2.3.1", "parity-scale-codec 3.1.5", "secp256k1", "tokio", diff --git a/Cargo.toml b/Cargo.toml index e5988bd..45e0590 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ near-primitives = "0.5.0" near-units = "0.2.0" hex = "0.4.2" num-format = "0.4.0" +parity-scale-codec = "2.0.0" secp256k1-test = { package = "secp256k1", version = "0.20.3", features = ["rand-std", "recovery"] } beefy-light-client = { git = "https://github.com/octopus-network/beefy-light-client.git", branch = "main" } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } diff --git a/appchain-anchor/src/appchain_messages.rs b/appchain-anchor/src/appchain_messages.rs index 3d44bea..9fcbfb3 100644 --- a/appchain-anchor/src/appchain_messages.rs +++ b/appchain-anchor/src/appchain_messages.rs @@ -14,18 +14,18 @@ pub enum PayloadType { #[derive(Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)] #[serde(crate = "near_sdk::serde")] pub struct BurnAssetPayload { - token_id: String, - sender: String, - receiver_id: AccountId, - amount: u128, + pub token_id: String, + pub sender: String, + pub receiver_id: AccountId, + pub amount: u128, } #[derive(Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)] #[serde(crate = "near_sdk::serde")] pub struct LockPayload { - sender: String, - receiver_id: AccountId, - amount: u128, + pub sender: String, + pub receiver_id: AccountId, + pub amount: u128, } #[derive(Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)] @@ -81,9 +81,9 @@ pub enum MessagePayload { #[derive(Encode, Decode, Clone)] pub struct RawMessage { - nonce: u64, - payload_type: PayloadType, - payload: Vec, + pub nonce: u64, + pub payload_type: PayloadType, + pub payload: Vec, } impl RawMessage { diff --git a/appchain-anchor/src/interfaces.rs b/appchain-anchor/src/interfaces.rs index 7954523..a98dcce 100644 --- a/appchain-anchor/src/interfaces.rs +++ b/appchain-anchor/src/interfaces.rs @@ -331,10 +331,6 @@ pub trait StakingManager { pub trait SudoActions { /// fn set_owner_pk(&mut self, public_key: PublicKey); - /// Apply a certain `AppchainMessage` - fn stage_appchain_message(&mut self, appchain_message: AppchainMessage); - /// - fn stage_appchain_encoded_messages(&mut self, encoded_messages: Vec); /// fn set_metadata_of_wrapped_appchain_token(&mut self, metadata: FungibleTokenMetadata); /// @@ -344,38 +340,14 @@ pub trait SudoActions { value: U128, ); /// - fn reset_validator_set_histories_to( - &mut self, - era_number: U64, - ) -> MultiTxsOperationProcessingResult; - /// - fn reset_staking_histories_to(&mut self, era_number: U64) -> MultiTxsOperationProcessingResult; - /// - fn clear_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult; - /// fn regenerate_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult; /// - fn reset_next_validator_set_to(&mut self, era_number: U64) - -> MultiTxsOperationProcessingResult; - /// - fn clear_appchain_notification_histories(&mut self) -> MultiTxsOperationProcessingResult; - /// fn reset_beefy_light_client(&mut self, initial_public_keys: Vec); /// - fn clear_reward_distribution_records(&mut self, era_number: U64); - /// - fn clear_unbonded_stakes(&mut self); - /// - fn clear_unwithdrawn_rewards(&mut self, era_number: U64); - /// - fn reset_validator_profiles_to(&mut self, era_number: U64); - /// fn pause_asset_transfer(&mut self); /// fn resume_asset_transfer(&mut self); /// - fn remove_staking_history_at(&mut self, index: U64); - /// fn pause_rewards_withdrawal(&mut self); /// fn resume_rewards_withdrawal(&mut self); @@ -386,30 +358,8 @@ pub trait SudoActions { account_id_in_appchain: String, ); /// - fn force_change_account_id_in_appchain_of_staking_history( - &mut self, - index: U64, - account_id_in_appchain: String, - ); - /// - fn remove_duplicated_message_nonces_in_reward_distribution_records(&mut self, era_number: U64); - /// fn set_latest_applied_appchain_message_nonce(&mut self, nonce: u32); /// - fn clear_appchain_messages(&mut self) -> MultiTxsOperationProcessingResult; - /// - fn try_complete_switching_era(&mut self) -> MultiTxsOperationProcessingResult; - /// - fn remove_validator_set_history_of( - &mut self, - era_number: U64, - ) -> MultiTxsOperationProcessingResult; - /// - fn remove_validator_set_histories_before( - &mut self, - era_number: U64, - ) -> MultiTxsOperationProcessingResult; - /// fn unlock_auto_unbonded_stake_of( &mut self, delegator_id: Option, diff --git a/appchain-anchor/src/lib.rs b/appchain-anchor/src/lib.rs index a57a38a..9eb2f8c 100644 --- a/appchain-anchor/src/lib.rs +++ b/appchain-anchor/src/lib.rs @@ -1,6 +1,6 @@ mod anchor_viewer; pub mod appchain_challenge; -mod appchain_messages; +pub mod appchain_messages; mod assets; pub mod interfaces; mod lookup_array; diff --git a/appchain-anchor/src/permissionless_actions/mod.rs b/appchain-anchor/src/permissionless_actions/mod.rs index e9cd62e..fa73310 100644 --- a/appchain-anchor/src/permissionless_actions/mod.rs +++ b/appchain-anchor/src/permissionless_actions/mod.rs @@ -224,8 +224,10 @@ impl PermissionlessActions for AppchainAnchor { panic!("Failed in verifying appchain messages: {:?}", err); } } - let messages = Decode::decode(&mut &encoded_messages[..]).unwrap(); - self.internal_stage_appchain_messages(&messages); + match Decode::decode(&mut &encoded_messages[..]) { + Ok(messages) => self.internal_stage_appchain_messages(&messages), + Err(err) => panic!("Failed to decode messages: {}", err), + } } // fn process_appchain_messages(&mut self) -> MultiTxsOperationProcessingResult { diff --git a/appchain-anchor/src/user_actions/sudo_actions.rs b/appchain-anchor/src/user_actions/sudo_actions.rs index fcb2d3c..5e78e5d 100644 --- a/appchain-anchor/src/user_actions/sudo_actions.rs +++ b/appchain-anchor/src/user_actions/sudo_actions.rs @@ -1,8 +1,5 @@ -use crate::permissionless_actions::AppchainMessagesProcessingContext; +use crate::interfaces::SudoActions; use crate::*; -use crate::{appchain_messages::AppchainMessage, interfaces::SudoActions}; -use codec::Decode; -use core::panic; use near_contract_standards::fungible_token::core::ext_ft_core; use near_contract_standards::fungible_token::metadata::FungibleTokenMetadata; @@ -14,22 +11,6 @@ impl SudoActions for AppchainAnchor { self.owner_pk = public_key; } // - fn stage_appchain_message(&mut self, appchain_message: AppchainMessage) { - self.assert_owner(); - let mut processing_status = self.permissionless_actions_status.get().unwrap(); - let mut appchain_messages = self.appchain_messages.get().unwrap(); - appchain_messages.insert_message(&appchain_message); - self.appchain_messages.set(&appchain_messages); - processing_status.max_nonce_of_staged_appchain_messages = appchain_messages.max_nonce(); - self.permissionless_actions_status.set(&processing_status); - } - // - fn stage_appchain_encoded_messages(&mut self, encoded_messages: Vec) { - self.assert_owner(); - let messages = Decode::decode(&mut &encoded_messages[..]).unwrap(); - self.internal_stage_appchain_messages(&messages); - } - // fn set_metadata_of_wrapped_appchain_token(&mut self, metadata: FungibleTokenMetadata) { self.assert_owner(); let mut wrapped_appchain_token = self.wrapped_appchain_token.get().unwrap(); @@ -49,47 +30,6 @@ impl SudoActions for AppchainAnchor { self.wrapped_appchain_token.set(&wrapped_appchain_token); } // - fn reset_validator_set_histories_to( - &mut self, - era_number: U64, - ) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let mut validator_set_histories = self.validator_set_histories.get().unwrap(); - let result = validator_set_histories.reset_to(&era_number.0); - if !result.is_error() { - self.validator_set_histories.set(&validator_set_histories); - } - result - } - // - fn reset_staking_histories_to(&mut self, era_number: U64) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let validator_set_histories = self.validator_set_histories.get().unwrap(); - if let Some(validator_set_of_era) = validator_set_histories.get(&era_number.0) { - let mut staking_histories = self.staking_histories.get().unwrap(); - let result = staking_histories.reset_to(&validator_set_of_era.staking_history_index()); - if !result.is_error() { - self.staking_histories.set(&staking_histories); - } - return result; - } else { - panic!( - "Missing validator set history of era_number '{}'.", - era_number.0 - ); - } - } - // - fn clear_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let mut user_staking_histories = self.user_staking_histories.get().unwrap(); - let result = user_staking_histories.clear(); - if !result.is_error() { - self.user_staking_histories.set(&user_staking_histories); - } - result - } - // fn regenerate_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult { self.assert_owner(); let mut user_staking_histories = self.user_staking_histories.get().unwrap(); @@ -108,149 +48,12 @@ impl SudoActions for AppchainAnchor { MultiTxsOperationProcessingResult::Ok } // - // While using this function to reset data of next validator set, this contract must - // refuse any other actions which will change the state of next validator set. - // - fn reset_next_validator_set_to( - &mut self, - era_number: U64, - ) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let validator_set_histories = self.validator_set_histories.get().unwrap(); - if let Some(validator_set_of_era) = validator_set_histories.get(&era_number.0) { - let mut next_validator_set = self.next_validator_set.get().unwrap(); - let result = next_validator_set.clear(); - match result { - MultiTxsOperationProcessingResult::Ok => (), - MultiTxsOperationProcessingResult::NeedMoreGas => { - self.next_validator_set.set(&next_validator_set); - return result; - } - MultiTxsOperationProcessingResult::Error(_) => { - return result; - } - } - let staking_history_index = validator_set_of_era.staking_history_index(); - let staking_histories = self.staking_histories.get().unwrap(); - for index in 0..staking_history_index + 1 { - if let Some(staking_history) = staking_histories.get(&index) { - next_validator_set.apply_staking_fact(&staking_history.staking_fact); - } - if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) { - self.next_validator_set.set(&next_validator_set); - return MultiTxsOperationProcessingResult::NeedMoreGas; - } - } - self.next_validator_set.set(&next_validator_set); - MultiTxsOperationProcessingResult::Ok - } else { - panic!( - "Missing validator set history of era_number '{}'.", - era_number.0 - ); - } - } - // - fn clear_appchain_notification_histories(&mut self) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let mut appchain_notification_histories = - self.appchain_notification_histories.get().unwrap(); - let result = appchain_notification_histories.clear(); - if !result.is_error() { - self.appchain_notification_histories - .set(&appchain_notification_histories); - } - result - } - // fn reset_beefy_light_client(&mut self, initial_public_keys: Vec) { self.assert_owner(); self.beefy_light_client_state .set(&beefy_light_client::new(initial_public_keys)); } // - fn clear_reward_distribution_records(&mut self, era_number: U64) { - self.assert_owner(); - let mut reward_distribution_records = self.reward_distribution_records.get().unwrap(); - let mut validator_set_histories = self.validator_set_histories.get().unwrap(); - if let Some(mut validator_set_of_era) = validator_set_histories.get(&era_number.0) { - reward_distribution_records.clear(&validator_set_of_era, &era_number.0); - self.reward_distribution_records - .set(&reward_distribution_records); - validator_set_of_era.clear_reward_distribution_records(); - validator_set_histories.insert(&era_number.0, &validator_set_of_era); - } - } - // - fn clear_unbonded_stakes(&mut self) { - self.assert_owner(); - let staking_histories = self.staking_histories.get().unwrap(); - let index_range = staking_histories.index_range(); - for index in index_range.start_index.0..index_range.end_index.0 + 1 { - if let Some(staking_history) = staking_histories.get(&index) { - match staking_history.staking_fact { - StakingFact::StakeDecreased { validator_id, .. } - | StakingFact::ValidatorUnbonded { validator_id, .. } - | StakingFact::ValidatorAutoUnbonded { validator_id, .. } => { - self.unbonded_stakes.remove(&validator_id); - } - StakingFact::DelegationDecreased { delegator_id, .. } - | StakingFact::DelegatorUnbonded { delegator_id, .. } - | StakingFact::DelegatorAutoUnbonded { delegator_id, .. } => { - self.unbonded_stakes.remove(&delegator_id); - } - _ => (), - } - } - } - } - // - fn clear_unwithdrawn_rewards(&mut self, era_number: U64) { - self.assert_owner(); - let validator_set_histories = self.validator_set_histories.get().unwrap(); - if let Some(validator_set_of_era) = validator_set_histories.get(&era_number.0) { - validator_set_of_era - .get_validator_ids() - .iter() - .for_each(|validator_id| { - validator_set_of_era - .get_delegator_ids_of(validator_id) - .iter() - .for_each(|delegator_id| { - self.unwithdrawn_delegator_rewards.remove(&( - era_number.0, - delegator_id.clone(), - validator_id.clone(), - )); - }); - self.unwithdrawn_validator_rewards - .remove(&(era_number.0, validator_id.clone())); - }); - } - } - // - fn reset_validator_profiles_to(&mut self, era_number: U64) { - self.assert_owner(); - let mut validator_profiles = self.validator_profiles.get().unwrap(); - let validator_set_histories = self.validator_set_histories.get().unwrap(); - let mut data_changed = false; - if let Some(validator_set_of_era) = validator_set_histories.get(&era_number.0) { - validator_profiles - .get_validator_ids() - .iter() - .for_each(|validator_id| { - if !validator_set_of_era.contains_validator(validator_id) { - if validator_profiles.remove(validator_id) { - data_changed = true; - } - } - }); - } - if data_changed { - self.validator_profiles.set(&validator_profiles); - } - } - // fn pause_asset_transfer(&mut self) { self.assert_owner(); assert!( @@ -269,12 +72,6 @@ impl SudoActions for AppchainAnchor { self.asset_transfer_is_paused = false; } // - fn remove_staking_history_at(&mut self, index: U64) { - self.assert_owner(); - let mut staking_histories = self.staking_histories.get().unwrap(); - staking_histories.remove_at(&index.0); - } - // fn pause_rewards_withdrawal(&mut self) { self.assert_owner(); assert!( @@ -305,43 +102,6 @@ impl SudoActions for AppchainAnchor { ); } // - fn force_change_account_id_in_appchain_of_staking_history( - &mut self, - index: U64, - account_id_in_appchain: String, - ) { - self.assert_owner(); - let mut staking_histories = self.staking_histories.get().unwrap(); - if let Some(mut staking_history) = staking_histories.get(&index.0) { - match staking_history.staking_fact { - StakingFact::ValidatorRegistered { - validator_id, - validator_id_in_appchain: _, - amount, - can_be_delegated_to, - } => { - staking_history.staking_fact = StakingFact::ValidatorRegistered { - validator_id, - validator_id_in_appchain: account_id_in_appchain, - amount, - can_be_delegated_to, - }; - staking_histories.insert(&index.0, &staking_history); - self.staking_histories.set(&staking_histories); - } - _ => (), - } - } - } - // - fn remove_duplicated_message_nonces_in_reward_distribution_records(&mut self, era_number: U64) { - self.assert_owner(); - let mut reward_distribution_records = self.reward_distribution_records.get().unwrap(); - reward_distribution_records.remove_duplicated_message_nonces(era_number.0); - self.reward_distribution_records - .set(&reward_distribution_records); - } - // fn set_latest_applied_appchain_message_nonce(&mut self, nonce: u32) { self.assert_owner(); let mut permissionless_actions_status = self.permissionless_actions_status.get().unwrap(); @@ -351,60 +111,6 @@ impl SudoActions for AppchainAnchor { .set(&permissionless_actions_status); } // - fn clear_appchain_messages(&mut self) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let mut appchain_messages = self.appchain_messages.get().unwrap(); - let result = appchain_messages.clear(); - if !result.is_error() { - self.appchain_messages.set(&appchain_messages); - } - result - } - // - fn try_complete_switching_era(&mut self) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let processing_status = self.permissionless_actions_status.get().unwrap(); - let mut processing_context = AppchainMessagesProcessingContext::new(processing_status); - let mut validator_set_histories = self.validator_set_histories.get().unwrap(); - if let Some(era_number) = processing_context.switching_era_number() { - let result = self.complete_switching_era( - &mut processing_context, - &mut validator_set_histories, - era_number, - ); - self.permissionless_actions_status - .set(processing_context.processing_status()); - result - } else { - MultiTxsOperationProcessingResult::Ok - } - } - // - fn remove_validator_set_history_of( - &mut self, - era_number: U64, - ) -> MultiTxsOperationProcessingResult { - let mut validator_set_histories = self.validator_set_histories.get().unwrap(); - let result = validator_set_histories.remove_at(&era_number.0); - if !result.is_error() { - self.validator_set_histories.set(&validator_set_histories); - } - result - } - // - fn remove_validator_set_histories_before( - &mut self, - era_number: U64, - ) -> MultiTxsOperationProcessingResult { - self.assert_owner(); - let mut validator_set_histories = self.validator_set_histories.get().unwrap(); - let result = validator_set_histories.remove_before(&era_number.0); - if !result.is_error() { - self.validator_set_histories.set(&validator_set_histories); - } - result - } - // fn unlock_auto_unbonded_stake_of( &mut self, delegator_id: Option, diff --git a/tests/simulator/common/basic_actions.rs b/tests/simulator/common/basic_actions.rs index faa7d90..ec37f0d 100644 --- a/tests/simulator/common/basic_actions.rs +++ b/tests/simulator/common/basic_actions.rs @@ -199,6 +199,14 @@ pub async fn initialize_contracts_and_users( register_user_to_ft_contract(worker, &eve, &oct_token).await?; super::call_ft_transfer(worker, &root, &eve, total_supply / 10, &oct_token).await?; users.push(eve); + // relayer + let relayer = root + .create_subaccount(worker, "relayer") + .initial_balance(parse_near!("50 N")) + .transact() + .await? + .unwrap(); + users.push(relayer); // Return initialized UserAccounts Ok(( root, diff --git a/tests/simulator/common/complex_actions.rs b/tests/simulator/common/complex_actions.rs index 5ee01f5..c06cf60 100644 --- a/tests/simulator/common/complex_actions.rs +++ b/tests/simulator/common/complex_actions.rs @@ -7,13 +7,16 @@ use crate::{ print_wat_balance_of_anchor, }, }, - contract_interfaces::{anchor_viewer, permissionless_actions, staking_actions, sudo_actions}, + contract_interfaces::{anchor_viewer, permissionless_actions, staking_actions}, }; use appchain_anchor::{ + appchain_messages::{EraPayoutPayload, RawMessage}, + appchain_messages::{PayloadType, PlanNewEraPayload}, types::{AnchorStatus, MultiTxsOperationProcessingResult, ValidatorSetInfo}, - AppchainEvent, AppchainMessage, }; +use near_primitives::borsh::BorshSerialize; use near_sdk::{json_types::U64, serde_json}; +use parity_scale_codec::Encode; use workspaces::network::Sandbox; use workspaces::{Account, Contract, Worker}; @@ -44,22 +47,36 @@ pub async fn process_appchain_messages( pub async fn switch_era( worker: &Worker, - root: &Account, + relayer: &Account, anchor: &Contract, era_number: u32, appchain_message_nonce: u32, to_confirm_view_result: bool, ) -> anyhow::Result<()> { if era_number > 0 { - let appchain_message = AppchainMessage { - appchain_event: AppchainEvent::EraSwitchPlaned { era_number }, - nonce: appchain_message_nonce, + let payload = PlanNewEraPayload { + new_era: era_number, }; - sudo_actions::stage_appchain_message(worker, root, anchor, appchain_message) - .await - .expect("Failed to call 'stage_appchain_message'"); + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::PlanNewEra, + payload: payload.try_to_vec().unwrap(), + }; + let mut raw_messages = Vec::new(); + raw_messages.push(raw_message); + permissionless_actions::verify_and_stage_appchain_messages( + worker, + relayer, + anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); } - process_appchain_messages(worker, root, anchor).await?; + process_appchain_messages(worker, relayer, anchor).await?; if to_confirm_view_result { let anchor_status = anchor_viewer::get_anchor_status(worker, anchor).await?; println!( @@ -85,7 +102,7 @@ pub async fn switch_era( pub async fn distribute_reward_of( worker: &Worker, - root: &Account, + relayer: &Account, anchor: &Contract, wrapped_appchain_token: &Contract, nonce: u32, @@ -95,15 +112,29 @@ pub async fn distribute_reward_of( ) -> anyhow::Result<()> { let anchor_balance_of_wat = common::get_ft_balance_of(worker, &anchor.as_account(), &wrapped_appchain_token).await?; - let appchain_message = AppchainMessage { - appchain_event: AppchainEvent::EraRewardConcluded { - era_number, - unprofitable_validator_ids, - offenders: Vec::new(), - }, - nonce, + let payload = EraPayoutPayload { + end_era: era_number, + excluded_validators: unprofitable_validator_ids, + offenders: Vec::new(), + }; + let raw_message = RawMessage { + nonce: nonce as u64, + payload_type: PayloadType::EraPayout, + payload: payload.try_to_vec().unwrap(), }; - sudo_actions::stage_appchain_message(worker, root, anchor, appchain_message).await?; + let mut raw_messages = Vec::new(); + raw_messages.push(raw_message); + permissionless_actions::verify_and_stage_appchain_messages( + worker, + relayer, + anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); if to_confirm_view_result { let anchor_status = anchor_viewer::get_anchor_status(worker, anchor).await?; println!( @@ -112,7 +143,7 @@ pub async fn distribute_reward_of( ); println!(); } - process_appchain_messages(worker, root, anchor).await?; + process_appchain_messages(worker, relayer, anchor).await?; assert_eq!( common::get_ft_balance_of(worker, &anchor.as_account(), &wrapped_appchain_token) .await? diff --git a/tests/simulator/common/mod.rs b/tests/simulator/common/mod.rs index a58b2fe..ba37e49 100644 --- a/tests/simulator/common/mod.rs +++ b/tests/simulator/common/mod.rs @@ -522,6 +522,12 @@ pub async fn test_normal_actions( lifecycle_actions::initialize_beefy_light_client(worker, &root, &anchor, initial_public_keys) .await .expect("Failed in calling 'initialize_beefy_light_client'"); + settings_manager::turn_on_beefy_light_client_witness_mode(&worker, &root, &anchor) + .await + .expect("Failed in calling 'turn_on_beefy_light_client_witness_mode'"); + settings_manager::set_relayer_account(&worker, &root, &anchor, &users[5]) + .await + .expect("Failed to call 'set_relayer_account'"); // // Go live // diff --git a/tests/simulator/contract_interfaces/mod.rs b/tests/simulator/contract_interfaces/mod.rs index faffa7b..2787a03 100644 --- a/tests/simulator/contract_interfaces/mod.rs +++ b/tests/simulator/contract_interfaces/mod.rs @@ -4,7 +4,6 @@ pub mod near_fungible_token_manager; pub mod permissionless_actions; pub mod settings_manager; pub mod staking_actions; -pub mod sudo_actions; pub mod validator_actions; pub mod wrapped_appchain_nft_manager; pub mod wrapped_appchain_token_manager; diff --git a/tests/simulator/contract_interfaces/permissionless_actions.rs b/tests/simulator/contract_interfaces/permissionless_actions.rs index 96096d9..fd57660 100644 --- a/tests/simulator/contract_interfaces/permissionless_actions.rs +++ b/tests/simulator/contract_interfaces/permissionless_actions.rs @@ -2,6 +2,31 @@ use appchain_anchor::types::{MultiTxsOperationProcessingResult, ValidatorMerkleP use near_sdk::serde_json::json; use workspaces::{network::Sandbox, result::CallExecutionDetails, Account, Contract, Worker}; +pub async fn verify_and_stage_appchain_messages( + worker: &Worker, + signer: &Account, + anchor: &Contract, + encoded_messages: Vec, + header: Vec, + mmr_leaf: Vec, + mmr_proof: Vec, +) -> anyhow::Result { + let result = signer + .call(worker, anchor.id(), "verify_and_stage_appchain_messages") + .gas(300_000_000_000_000) + .args_json(json!({ + "encoded_messages": encoded_messages, + "header": header, + "mmr_leaf": mmr_leaf, + "mmr_proof": mmr_proof + }))? + .transact() + .await; + println!("{:?}", result); + println!(); + result +} + pub async fn process_appchain_messages( worker: &Worker, signer: &Account, diff --git a/tests/simulator/contract_interfaces/settings_manager.rs b/tests/simulator/contract_interfaces/settings_manager.rs index d27225d..fc77768 100644 --- a/tests/simulator/contract_interfaces/settings_manager.rs +++ b/tests/simulator/contract_interfaces/settings_manager.rs @@ -90,6 +90,22 @@ pub async fn set_token_price_maintainer_account( .await } +pub async fn set_relayer_account( + worker: &Worker, + signer: &Account, + anchor: &Contract, + account: &Account, +) -> anyhow::Result { + signer + .call(worker, anchor.id(), "set_relayer_account") + .args_json(json!({ + "account_id": account.id() + }))? + .gas(200_000_000_000_000) + .transact() + .await +} + pub async fn set_price_of_oct_token( worker: &Worker, signer: &Account, @@ -155,3 +171,19 @@ pub async fn turn_on_beefy_light_client_witness_mode( .transact() .await } + +pub async fn turn_off_beefy_light_client_witness_mode( + worker: &Worker, + signer: &Account, + anchor: &Contract, +) -> anyhow::Result { + signer + .call( + worker, + anchor.id(), + "turn_off_beefy_light_client_witness_mode", + ) + .gas(200_000_000_000_000) + .transact() + .await +} diff --git a/tests/simulator/contract_interfaces/sudo_actions.rs b/tests/simulator/contract_interfaces/sudo_actions.rs deleted file mode 100644 index 71e2a13..0000000 --- a/tests/simulator/contract_interfaces/sudo_actions.rs +++ /dev/null @@ -1,91 +0,0 @@ -use appchain_anchor::AppchainMessage; -use near_sdk::{ - json_types::U64, - serde_json::{self, json}, -}; -use workspaces::{network::Sandbox, result::CallExecutionDetails, Account, Contract, Worker}; - -pub async fn stage_appchain_message( - worker: &Worker, - signer: &Account, - anchor: &Contract, - message: AppchainMessage, -) -> anyhow::Result { - println!( - "Appchain message: {}", - serde_json::to_string::(&message).unwrap() - ); - println!(); - signer - .call(worker, anchor.id(), "stage_appchain_message") - .args_json(json!({ "appchain_message": message }))? - .gas(200_000_000_000_000) - .transact() - .await -} - -pub async fn reset_validator_set_histories_to( - worker: &Worker, - signer: &Account, - anchor: &Contract, - era_number: U64, -) -> anyhow::Result { - signer - .call(worker, anchor.id(), "reset_validator_set_histories_to") - .args_json(json!({ "era_number": era_number }))? - .gas(200_000_000_000_000) - .transact() - .await -} - -pub async fn clear_appchain_notification_histories( - worker: &Worker, - signer: &Account, - anchor: &Contract, -) -> anyhow::Result { - signer - .call(worker, anchor.id(), "clear_appchain_notification_histories") - .gas(200_000_000_000_000) - .transact() - .await -} - -pub async fn clear_reward_distribution_records( - worker: &Worker, - signer: &Account, - anchor: &Contract, - era_number: U64, -) -> anyhow::Result { - signer - .call(worker, anchor.id(), "clear_reward_distribution_records") - .args_json(json!({ "era_number": era_number }))? - .gas(200_000_000_000_000) - .transact() - .await -} - -pub async fn clear_unbonded_stakes( - worker: &Worker, - signer: &Account, - anchor: &Contract, -) -> anyhow::Result { - signer - .call(worker, anchor.id(), "clear_unbonded_stakes") - .gas(200_000_000_000_000) - .transact() - .await -} - -pub async fn clear_unwithdrawn_rewards( - worker: &Worker, - signer: &Account, - anchor: &Contract, - era_number: U64, -) -> anyhow::Result { - signer - .call(worker, anchor.id(), "clear_unwithdrawn_rewards") - .args_json(json!({ "era_number": era_number }))? - .gas(200_000_000_000_000) - .transact() - .await -} diff --git a/tests/simulator/test_anchor_actions.rs b/tests/simulator/test_anchor_actions.rs index 7f27983..db9b498 100644 --- a/tests/simulator/test_anchor_actions.rs +++ b/tests/simulator/test_anchor_actions.rs @@ -1,6 +1,6 @@ use crate::{ common, - contract_interfaces::{anchor_viewer, settings_manager, staking_actions, sudo_actions}, + contract_interfaces::{anchor_viewer, settings_manager, staking_actions}, }; use near_sdk::json_types::U64; use std::collections::HashMap; @@ -23,9 +23,16 @@ async fn test_anchor_actions() -> anyhow::Result<()> { // Try start and complete switching era1 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 1, appchain_message_nonce, false) - .await - .expect("Failed to switch era"); + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 1, + appchain_message_nonce, + false, + ) + .await + .expect("Failed to switch era"); common::complex_viewer::print_validator_set_info_of(&worker, &anchor, U64::from(1)).await?; common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(1)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 1, &users[0]).await?; @@ -35,7 +42,7 @@ async fn test_anchor_actions() -> anyhow::Result<()> { appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -74,61 +81,6 @@ async fn test_anchor_actions() -> anyhow::Result<()> { ) .await?; // - // Reset contract status - // - let result = - sudo_actions::clear_reward_distribution_records(&worker, &root, &anchor, U64::from(3)) - .await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_reward_distribution_records(&worker, &root, &anchor, U64::from(2)) - .await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_reward_distribution_records(&worker, &root, &anchor, U64::from(1)) - .await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_reward_distribution_records(&worker, &root, &anchor, U64::from(0)) - .await?; - assert!(result.is_success()); - let result = sudo_actions::clear_unbonded_stakes(&worker, &root, &anchor).await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_unwithdrawn_rewards(&worker, &root, &anchor, U64::from(3)).await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_unwithdrawn_rewards(&worker, &root, &anchor, U64::from(2)).await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_unwithdrawn_rewards(&worker, &root, &anchor, U64::from(1)).await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_unwithdrawn_rewards(&worker, &root, &anchor, U64::from(0)).await?; - assert!(result.is_success()); - let result = - sudo_actions::clear_appchain_notification_histories(&worker, &root, &anchor).await?; - assert!(result.is_success()); - let result = - sudo_actions::reset_validator_set_histories_to(&worker, &root, &anchor, U64::from(2)) - .await?; - assert!(result.is_success()); - let result = - sudo_actions::reset_validator_set_histories_to(&worker, &root, &anchor, U64::from(1)) - .await?; - assert!(result.is_success()); - let result = - sudo_actions::reset_validator_set_histories_to(&worker, &root, &anchor, U64::from(0)) - .await?; - assert!(result.is_success()); - common::complex_viewer::print_anchor_status(&worker, &anchor).await?; - common::complex_viewer::print_wrapped_appchain_token_info(&worker, &anchor).await?; - common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(0)).await?; - common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(1)).await?; - common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(2)).await?; - common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(3)).await?; - common::complex_viewer::print_staking_histories(&worker, &anchor).await?; - common::complex_viewer::print_appchain_notifications(&worker, &anchor).await?; Ok(()) } @@ -192,9 +144,16 @@ async fn test_staking_actions( // Try start and complete switching era2 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 2, appchain_message_nonce, true) - .await - .expect("Failed to switch era"); + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 2, + appchain_message_nonce, + true, + ) + .await + .expect("Failed to switch era"); common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(2)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 2, &users[0]).await?; // @@ -203,7 +162,7 @@ async fn test_staking_actions( appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -267,9 +226,16 @@ async fn test_staking_actions( // Try start and complete switching era3 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 3, appchain_message_nonce, true) - .await - .expect("Failed to switch era"); + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 3, + appchain_message_nonce, + true, + ) + .await + .expect("Failed to switch era"); common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(3)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 3, &users[0]).await?; // @@ -278,7 +244,7 @@ async fn test_staking_actions( appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -333,9 +299,16 @@ async fn test_staking_actions( // Try start and complete switching era4 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 4, appchain_message_nonce, true) - .await - .expect("Failed to switch era"); + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 4, + appchain_message_nonce, + true, + ) + .await + .expect("Failed to switch era"); common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(4)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 4, &users[0]).await?; // @@ -345,7 +318,7 @@ async fn test_staking_actions( appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -379,7 +352,7 @@ async fn test_staking_actions( appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -413,9 +386,16 @@ async fn test_staking_actions( // Try start and complete switching era5 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 5, appchain_message_nonce, true) - .await - .expect("Failed to switch era"); + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 5, + appchain_message_nonce, + true, + ) + .await + .expect("Failed to switch era"); common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(5)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 5, &users[0]).await?; // @@ -425,7 +405,7 @@ async fn test_staking_actions( appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, diff --git a/tests/simulator/test_beefy_light_client.rs b/tests/simulator/test_beefy_light_client.rs index aac2e42..9b438bb 100644 --- a/tests/simulator/test_beefy_light_client.rs +++ b/tests/simulator/test_beefy_light_client.rs @@ -1,7 +1,7 @@ use crate::{ common, contract_interfaces::{ - anchor_viewer, permissionless_actions, settings_manager, staking_actions, sudo_actions, + anchor_viewer, permissionless_actions, settings_manager, staking_actions, }, }; use appchain_anchor::types::{MultiTxsOperationProcessingResult, ValidatorMerkleProof}; @@ -9,7 +9,7 @@ use beefy_light_client::mmr::{MmrLeaf, MmrLeafProof}; use beefy_light_client::{beefy_ecdsa_to_ethereum, commitment::SignedCommitment}; use codec::Decode; use hex_literal::hex; -use near_sdk::{json_types::U64, serde_json}; +use near_sdk::serde_json; use workspaces::{network::Sandbox, Account, Contract, Worker}; #[tokio::test] @@ -33,6 +33,10 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { mut appchain_message_nonce, ) = common::test_normal_actions(&worker, false, true, initial_public_keys).await?; // + settings_manager::turn_off_beefy_light_client_witness_mode(&worker, &root, &anchor) + .await + .expect("Failed to call 'turn_off_beefy_light_client_witness_mode'"); + // // Update state of beefy light client // update_state_of_beefy_light_client_1(&worker, &anchor, &users[4]).await?; @@ -40,11 +44,22 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { update_state_of_beefy_light_client_2(&worker, &anchor, &users[1]).await?; common::complex_viewer::print_latest_appchain_commitment(&worker, &anchor).await?; // + settings_manager::turn_on_beefy_light_client_witness_mode(&worker, &root, &anchor) + .await + .expect("Failed to call 'turn_on_beefy_light_client_witness_mode'"); + // // Try start and complete switching era1 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 1, appchain_message_nonce, true) - .await?; + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 1, + appchain_message_nonce, + true, + ) + .await?; common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(1)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 1, &users[0]).await?; // @@ -53,7 +68,7 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -116,8 +131,15 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { // Try start and complete switching era2 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 2, appchain_message_nonce, true) - .await?; + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 2, + appchain_message_nonce, + true, + ) + .await?; common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(2)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 2, &users[0]).await?; // @@ -126,7 +148,7 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -189,8 +211,15 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { // Try start and complete switching era3 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 3, appchain_message_nonce, true) - .await?; + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 3, + appchain_message_nonce, + true, + ) + .await?; common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(3)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 3, &users[0]).await?; // @@ -199,7 +228,7 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -245,8 +274,15 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { // Try start and complete switching era3 // appchain_message_nonce += 1; - common::complex_actions::switch_era(&worker, &root, &anchor, 4, appchain_message_nonce, true) - .await?; + common::complex_actions::switch_era( + &worker, + &users[5], + &anchor, + 4, + appchain_message_nonce, + true, + ) + .await?; common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(4)).await?; common::complex_viewer::print_delegator_list_of(&worker, &anchor, 4, &users[0]).await?; // @@ -255,7 +291,7 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { appchain_message_nonce += 1; common::complex_actions::distribute_reward_of( &worker, - &root, + &users[5], &anchor, &wrapped_appchain_token, appchain_message_nonce, @@ -341,12 +377,8 @@ async fn test_beefy_light_client() -> anyhow::Result<()> { common::complex_actions::withdraw_stake_of(&worker, &anchor, &users[3], &oct_token).await?; common::complex_actions::withdraw_stake_of(&worker, &anchor, &users[4], &oct_token).await?; // - // Reset history data // - let result = - sudo_actions::reset_validator_set_histories_to(&worker, &root, &anchor, U64::from(0)) - .await?; - assert!(result.is_success()); + // common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(0)).await?; common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(1)).await?; common::complex_viewer::print_validator_list_of(&worker, &anchor, Some(2)).await?; diff --git a/tests/simulator/test_beefy_light_client_2.rs b/tests/simulator/test_beefy_light_client_2.rs index 32af53f..9610d9e 100644 --- a/tests/simulator/test_beefy_light_client_2.rs +++ b/tests/simulator/test_beefy_light_client_2.rs @@ -1,3 +1,4 @@ +use crate::contract_interfaces::settings_manager; use crate::{common, contract_interfaces::permissionless_actions}; use appchain_anchor::types::{MultiTxsOperationProcessingResult, ValidatorMerkleProof}; use beefy_light_client::commitment::{Commitment, Payload, Signature}; @@ -84,6 +85,10 @@ async fn test_beefy_light_client_2() -> anyhow::Result<()> { _appchain_message_nonce, ) = common::test_normal_actions(&worker, false, true, initial_public_keys).await?; // + settings_manager::turn_off_beefy_light_client_witness_mode(&worker, &root, &anchor) + .await + .expect("Failed to call 'turn_off_beefy_light_client_witness_mode'"); + // permissionless_actions::start_updating_state_of_beefy_light_client( &worker, &root, diff --git a/tests/simulator/test_transfer_nft.rs b/tests/simulator/test_transfer_nft.rs index 8961fb8..1f4c1ab 100644 --- a/tests/simulator/test_transfer_nft.rs +++ b/tests/simulator/test_transfer_nft.rs @@ -1,13 +1,20 @@ use crate::{ common, - contract_interfaces::{settings_manager, sudo_actions, wrapped_appchain_nft_manager}, + contract_interfaces::{permissionless_actions, wrapped_appchain_nft_manager}, +}; +use appchain_anchor::{ + appchain_messages::{LockNftPayload, PayloadType, RawMessage}, + types::NFTTransferMessage, }; -use appchain_anchor::{types::NFTTransferMessage, AppchainEvent, AppchainMessage}; use near_contract_standards::non_fungible_token::metadata::{ NFTContractMetadata, TokenMetadata, NFT_METADATA_SPEC, }; -use near_sdk::serde_json::{self, json}; +use near_sdk::{ + borsh::BorshSerialize, + serde_json::{self, json}, +}; use near_units::parse_near; +use parity_scale_codec::Encode; use std::str::FromStr; use workspaces::AccountId; @@ -75,7 +82,7 @@ async fn test_transfer_nft_to_near() -> anyhow::Result<()> { .await .expect("Failed in calling 'store_wasm_of_wrapped_appchain_nft_contract'"); // - let class_id = "nft_class1".to_string(); + let class_id = "1".to_string(); wrapped_appchain_nft_manager::register_wrapped_appchain_nft( &worker, &root, @@ -98,37 +105,48 @@ async fn test_transfer_nft_to_near() -> anyhow::Result<()> { // let user0_id_in_appchain = "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d".to_string(); - settings_manager::turn_on_beefy_light_client_witness_mode(&worker, &root, &anchor) - .await - .expect("Failed in calling 'turn_on_beefy_light_client_witness_mode'"); // // // appchain_message_nonce += 1; - let appchain_message = AppchainMessage { - appchain_event: AppchainEvent::NonFungibleTokenLocked { - owner_id_in_appchain: user0_id_in_appchain.clone(), - receiver_id_in_near: users[0].id().to_string().parse().unwrap(), - class_id: class_id.clone(), - instance_id: "token_id1".to_string(), - token_metadata: TokenMetadata { - title: Some("token_id1 title".to_string()), - description: Some("token_id1 description".to_string()), - media: None, - media_hash: None, - copies: Some(1), - issued_at: None, - expires_at: None, - starts_at: None, - updated_at: None, - extra: None, - reference: None, - reference_hash: None, - }, + let payload = LockNftPayload { + sender: user0_id_in_appchain.clone(), + receiver_id: users[0].id().to_string().parse().unwrap(), + class: 1 as u128, + instance: 1 as u128, + metadata: TokenMetadata { + title: Some("token_id1 title".to_string()), + description: Some("token_id1 description".to_string()), + media: None, + media_hash: None, + copies: Some(1), + issued_at: None, + expires_at: None, + starts_at: None, + updated_at: None, + extra: None, + reference: None, + reference_hash: None, }, - nonce: appchain_message_nonce, }; - sudo_actions::stage_appchain_message(&worker, &root, &anchor, appchain_message).await?; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::LockNft, + payload: payload.try_to_vec().unwrap(), + }; + let mut raw_messages = Vec::new(); + raw_messages.push(raw_message); + permissionless_actions::verify_and_stage_appchain_messages( + &worker, + &users[5], + &anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); common::complex_actions::process_appchain_messages(&worker, &users[4], &anchor).await?; common::complex_viewer::print_appchain_messages(&worker, &anchor).await?; common::complex_viewer::print_appchain_messages_processing_results(&worker, &anchor).await?; @@ -144,32 +162,45 @@ async fn test_transfer_nft_to_near() -> anyhow::Result<()> { ) .await?; assert!(result.is_success()); - let token_id = "token_id1".to_string(); appchain_message_nonce += 1; - let appchain_message = AppchainMessage { - appchain_event: AppchainEvent::NonFungibleTokenLocked { - owner_id_in_appchain: user0_id_in_appchain.clone(), - receiver_id_in_near: users[0].id().to_string().parse().unwrap(), - class_id: class_id.clone(), - instance_id: token_id.clone(), - token_metadata: TokenMetadata { - title: Some("token_id1 title".to_string()), - description: Some("token_id1 description".to_string()), - media: None, - media_hash: None, - copies: Some(1), - issued_at: None, - expires_at: None, - starts_at: None, - updated_at: None, - extra: None, - reference: None, - reference_hash: None, - }, + let payload = LockNftPayload { + sender: user0_id_in_appchain.clone(), + receiver_id: users[0].id().to_string().parse().unwrap(), + class: 1 as u128, + instance: 1 as u128, + metadata: TokenMetadata { + title: Some("token_id1 title".to_string()), + description: Some("token_id1 description".to_string()), + media: None, + media_hash: None, + copies: Some(1), + issued_at: None, + expires_at: None, + starts_at: None, + updated_at: None, + extra: None, + reference: None, + reference_hash: None, }, - nonce: appchain_message_nonce, }; - sudo_actions::stage_appchain_message(&worker, &root, &anchor, appchain_message).await?; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::LockNft, + payload: payload.try_to_vec().unwrap(), + }; + let mut raw_messages = Vec::new(); + raw_messages.push(raw_message); + permissionless_actions::verify_and_stage_appchain_messages( + &worker, + &users[5], + &anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); common::complex_actions::process_appchain_messages(&worker, &users[4], &anchor).await?; common::complex_viewer::print_appchain_messages(&worker, &anchor).await?; common::complex_viewer::print_appchain_messages_processing_results(&worker, &anchor).await?; @@ -188,7 +219,7 @@ async fn test_transfer_nft_to_near() -> anyhow::Result<()> { ) .args_json(json!({ "receiver_id": anchor.id(), - "token_id": token_id.clone(), + "token_id": "1".to_string(), "approval_Id": Option::::None, "memo": Option::::None, "msg": serde_json::ser::to_string(&NFTTransferMessage::BridgeToAppchain { @@ -205,30 +236,44 @@ async fn test_transfer_nft_to_near() -> anyhow::Result<()> { // // appchain_message_nonce += 1; - let appchain_message = AppchainMessage { - appchain_event: AppchainEvent::NonFungibleTokenLocked { - owner_id_in_appchain: user0_id_in_appchain.clone(), - receiver_id_in_near: users[0].id().to_string().parse().unwrap(), - class_id: class_id.clone(), - instance_id: "token_id1".to_string(), - token_metadata: TokenMetadata { - title: Some("token_id1 title".to_string()), - description: Some("token_id1 description".to_string()), - media: None, - media_hash: None, - copies: Some(1), - issued_at: None, - expires_at: None, - starts_at: None, - updated_at: None, - extra: None, - reference: None, - reference_hash: None, - }, + let payload = LockNftPayload { + sender: user0_id_in_appchain.clone(), + receiver_id: users[0].id().to_string().parse().unwrap(), + class: 1 as u128, + instance: 1 as u128, + metadata: TokenMetadata { + title: Some("token_id1 title".to_string()), + description: Some("token_id1 description".to_string()), + media: None, + media_hash: None, + copies: Some(1), + issued_at: None, + expires_at: None, + starts_at: None, + updated_at: None, + extra: None, + reference: None, + reference_hash: None, }, - nonce: appchain_message_nonce, }; - sudo_actions::stage_appchain_message(&worker, &root, &anchor, appchain_message).await?; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::LockNft, + payload: payload.try_to_vec().unwrap(), + }; + let mut raw_messages = Vec::new(); + raw_messages.push(raw_message); + permissionless_actions::verify_and_stage_appchain_messages( + &worker, + &users[5], + &anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); common::complex_actions::process_appchain_messages(&worker, &users[4], &anchor).await?; common::complex_viewer::print_appchain_messages(&worker, &anchor).await?; common::complex_viewer::print_appchain_messages_processing_results(&worker, &anchor).await?; diff --git a/tests/simulator/test_wrapped_appchain_token.rs b/tests/simulator/test_wrapped_appchain_token.rs index c90d11f..1ac319a 100644 --- a/tests/simulator/test_wrapped_appchain_token.rs +++ b/tests/simulator/test_wrapped_appchain_token.rs @@ -1,9 +1,12 @@ use crate::{ common, - contract_interfaces::{sudo_actions, wrapped_appchain_token_manager}, + contract_interfaces::{permissionless_actions, wrapped_appchain_token_manager}, }; -use appchain_anchor::{AppchainEvent, AppchainMessage}; -use near_sdk::{json_types::U128, AccountId}; +use appchain_anchor::appchain_messages::{ + EraPayoutPayload, LockPayload, PayloadType, PlanNewEraPayload, RawMessage, +}; +use near_sdk::{borsh::BorshSerialize, AccountId}; +use parity_scale_codec::Encode; use std::str::FromStr; const TOTAL_SUPPLY: u128 = 100_000_000; @@ -12,7 +15,7 @@ const TOTAL_SUPPLY: u128 = 100_000_000; async fn test_wrapped_appchain_token_bridging() -> anyhow::Result<()> { let worker = workspaces::sandbox().await?; let ( - root, + _root, _oct_token, wrapped_appchain_token, _registry, @@ -33,15 +36,29 @@ async fn test_wrapped_appchain_token_bridging() -> anyhow::Result<()> { let user1_wat_balance = common::get_ft_balance_of(&worker, &users[1], &wrapped_appchain_token).await?; appchain_message_nonce += 1; - let appchain_message = AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: AccountId::from_str("unknown.testnet").unwrap(), - amount: U128::from(total_supply / 10), - }, - nonce: appchain_message_nonce, + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: AccountId::from_str("unknown.testnet").unwrap(), + amount: total_supply / 10, + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), }; - sudo_actions::stage_appchain_message(&worker, &root, &anchor, appchain_message).await?; + let mut raw_messages = Vec::new(); + raw_messages.push(raw_message); + permissionless_actions::verify_and_stage_appchain_messages( + &worker, + &users[5], + &anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); common::complex_actions::process_appchain_messages(&worker, &users[4], &anchor).await?; common::complex_viewer::print_appchain_messages(&worker, &anchor).await?; common::complex_viewer::print_appchain_messages_processing_results(&worker, &anchor).await?; @@ -71,123 +88,184 @@ async fn test_wrapped_appchain_token_bridging() -> anyhow::Result<()> { // let user1_wat_balance = common::get_ft_balance_of(&worker, &users[1], &wrapped_appchain_token).await?; - let mut appchain_messages = Vec::::new(); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(60, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(40, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::EraSwitchPlaned { era_number: 1 }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(70, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(30, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(45, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(45, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(45, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(45, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::EraRewardConcluded { - era_number: 0, - unprofitable_validator_ids: Vec::new(), - offenders: Vec::new(), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(45, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(45, 18)), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::NativeTokenLocked { - owner_id_in_appchain: user4_id_in_appchain.clone(), - receiver_id_in_near: users[1].id().to_string().parse().unwrap(), - amount: U128::from(common::to_actual_amount(45, 18)), - }, - nonce: appchain_message_nonce, - }); - for appchain_message in appchain_messages { - sudo_actions::stage_appchain_message(&worker, &root, &anchor, appchain_message).await?; - } + let mut raw_messages = Vec::new(); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(60, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(40, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = PlanNewEraPayload { new_era: 1 }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::PlanNewEra, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(70, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(30, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(45, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(45, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(45, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(45, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = EraPayoutPayload { + end_era: 0, + excluded_validators: Vec::new(), + offenders: Vec::new(), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::EraPayout, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(45, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(45, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = LockPayload { + sender: user4_id_in_appchain.clone(), + receiver_id: users[1].id().to_string().parse().unwrap(), + amount: common::to_actual_amount(45, 18), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::Lock, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + permissionless_actions::verify_and_stage_appchain_messages( + &worker, + &users[5], + &anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); common::complex_actions::process_appchain_messages(&worker, &users[3], &anchor).await?; common::complex_viewer::print_appchain_messages(&worker, &anchor).await?; common::complex_viewer::print_appchain_messages_processing_results(&worker, &anchor).await?; @@ -202,47 +280,76 @@ async fn test_wrapped_appchain_token_bridging() -> anyhow::Result<()> { // // // - let mut appchain_messages = Vec::::new(); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::EraSwitchPlaned { era_number: 2 }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::EraRewardConcluded { - era_number: 1, - unprofitable_validator_ids: Vec::new(), - offenders: Vec::new(), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::EraSwitchPlaned { era_number: 3 }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::EraRewardConcluded { - era_number: 2, - unprofitable_validator_ids: Vec::new(), - offenders: Vec::new(), - }, - nonce: appchain_message_nonce, - }); - appchain_message_nonce += 1; - appchain_messages.push(AppchainMessage { - appchain_event: AppchainEvent::EraRewardConcluded { - era_number: 1, - unprofitable_validator_ids: Vec::new(), - offenders: Vec::new(), - }, - nonce: appchain_message_nonce, - }); - for appchain_message in appchain_messages { - sudo_actions::stage_appchain_message(&worker, &root, &anchor, appchain_message).await?; - } + let mut raw_messages = Vec::new(); + // + appchain_message_nonce += 1; + let payload = PlanNewEraPayload { new_era: 2 }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::PlanNewEra, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = EraPayoutPayload { + end_era: 1, + excluded_validators: Vec::new(), + offenders: Vec::new(), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::EraPayout, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = PlanNewEraPayload { new_era: 3 }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::PlanNewEra, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = EraPayoutPayload { + end_era: 2, + excluded_validators: Vec::new(), + offenders: Vec::new(), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::EraPayout, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + appchain_message_nonce += 1; + let payload = EraPayoutPayload { + end_era: 1, + excluded_validators: Vec::new(), + offenders: Vec::new(), + }; + let raw_message = RawMessage { + nonce: appchain_message_nonce as u64, + payload_type: PayloadType::EraPayout, + payload: payload.try_to_vec().unwrap(), + }; + raw_messages.push(raw_message); + // + permissionless_actions::verify_and_stage_appchain_messages( + &worker, + &users[5], + &anchor, + raw_messages.encode(), + Vec::new(), + Vec::new(), + Vec::new(), + ) + .await + .expect("Failed to call 'verify_and_stage_appchain_messages'"); common::complex_actions::process_appchain_messages(&worker, &users[3], &anchor).await?; common::complex_viewer::print_appchain_messages(&worker, &anchor).await?; common::complex_viewer::print_appchain_messages_processing_results(&worker, &anchor).await?;