From 7c2eac2b9dd24c2a50eba53cdd6670bba2f51f8c Mon Sep 17 00:00:00 2001 From: R0GUE Date: Fri, 5 Apr 2024 17:58:06 +0200 Subject: [PATCH 01/27] feat: pallet assets pop api integration --- Cargo.lock | 312 +++++------ .../examples/trust_backed_assets/.gitignore | 9 + .../examples/trust_backed_assets/Cargo.toml | 25 + pop-api/examples/trust_backed_assets/lib.rs | 69 +++ pop-api/src/lib.rs | 6 +- pop-api/src/v0/assets/mod.rs | 1 + pop-api/src/v0/assets/trust_backed.rs | 519 ++++++++++++++++++ pop-api/src/v0/mod.rs | 3 + pop-api/src/v0/nfts.rs | 2 +- primitives/src/lib.rs | 6 +- primitives/src/storage_keys.rs | 7 + runtime/devnet/src/config/assets.rs | 16 +- runtime/devnet/src/extensions.rs | 139 ++++- runtime/devnet/src/lib.rs | 103 ++-- runtime/testnet/src/config/assets.rs | 16 +- runtime/testnet/src/extensions.rs | 150 ++++- runtime/testnet/src/lib.rs | 103 ++-- 17 files changed, 1221 insertions(+), 265 deletions(-) create mode 100755 pop-api/examples/trust_backed_assets/.gitignore create mode 100755 pop-api/examples/trust_backed_assets/Cargo.toml create mode 100755 pop-api/examples/trust_backed_assets/lib.rs create mode 100644 pop-api/src/v0/assets/mod.rs create mode 100644 pop-api/src/v0/assets/trust_backed.rs diff --git a/Cargo.lock b/Cargo.lock index 4dc89da6..e43d2b18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -214,7 +214,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -578,16 +578,16 @@ checksum = "f28243a43d821d11341ab73c80bed182dc015c514b951616cf79bd4af39af0c3" dependencies = [ "concurrent-queue", "event-listener 5.2.0", - "event-listener-strategy 0.5.0", + "event-listener-strategy 0.5.1", "futures-core", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] name = "async-executor" -version = "1.8.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ae5ebefcc48e7452b4987947920dac9450be1110cadf34d1b8c116bdbaf97c" +checksum = "10b3e585719c2358d2660232671ca8ca4ddb4be4ce8a1842d6c2dc8685303316" dependencies = [ "async-lock 3.3.0", "async-task", @@ -676,7 +676,7 @@ checksum = "d034b430882f8381900d3fe6f0aaa3ad94f2cb4ac519b429692a1bc2dda4ae7b" dependencies = [ "event-listener 4.0.3", "event-listener-strategy 0.4.0", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -768,7 +768,7 @@ checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -781,7 +781,7 @@ dependencies = [ "futures-sink", "futures-util", "memchr", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -899,7 +899,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1526,9 +1526,9 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.35" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" +checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e" dependencies = [ "android-tzdata", "iana-time-zone", @@ -1610,7 +1610,7 @@ dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim 0.11.0", + "strsim 0.11.1", "terminal_size", ] @@ -1623,7 +1623,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2337,7 +2337,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2658,7 +2658,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2698,7 +2698,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2715,7 +2715,7 @@ checksum = "b404f596046b0bb2d903a9c786b875a126261b52b7c3a64bbb66382c41c771df" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2763,7 +2763,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2785,7 +2785,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core 0.20.8", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2816,9 +2816,9 @@ dependencies = [ [[package]] name = "der" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" +checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" dependencies = [ "const-oid", "zeroize", @@ -2869,6 +2869,17 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "derive-syn-parse" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.58", +] + [[package]] name = "derive_more" version = "0.99.17" @@ -2968,31 +2979,31 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] name = "docify" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc4fd38aaa9fb98ac70794c82a00360d1e165a87fbf96a8a91f9dfc602aaee2" +checksum = "43a2f138ad521dc4a2ced1a4576148a6a610b4c5923933b062a263130a6802ce" dependencies = [ "docify_macros", ] [[package]] name = "docify_macros" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63fa215f3a0d40fb2a221b3aa90d8e1fbb8379785a990cb60d62ac71ebdc6460" +checksum = "1a081e51fb188742f5a7a1164ad752121abcb22874b21e2c3b0dd040c515fdad" dependencies = [ "common-path", - "derive-syn-parse", + "derive-syn-parse 0.2.0", "once_cell", "proc-macro2", "quote", "regex", - "syn 2.0.55", + "syn 2.0.58", "termcolor", "toml 0.8.12", "walkdir", @@ -3204,7 +3215,7 @@ checksum = "5c785274071b1b420972453b306eeca06acf4633829db4223b58a2a8c5953bc4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3215,7 +3226,7 @@ checksum = "6fd000fd6988e73bbe993ea3db9b1aa64906ab88766d654973924340c8cddb42" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3331,7 +3342,7 @@ checksum = "d93877bcde0eb80ca09131a08d23f0a5c18a620b01db137dba666d18cd9b30c2" dependencies = [ "concurrent-queue", "parking", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -3342,7 +3353,7 @@ checksum = "67b215c49b2b248c855fb73579eb1f4f26c38ffdc12973e20e07b91d78d5646e" dependencies = [ "concurrent-queue", "parking", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -3353,7 +3364,7 @@ checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" dependencies = [ "concurrent-queue", "parking", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -3363,17 +3374,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "958e4d70b6d5e81971bebec42271ec641e7ff4e170a6fa605f2b8a8b65cb97d3" dependencies = [ "event-listener 4.0.3", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] name = "event-listener-strategy" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "feedafcaa9b749175d5ac357452a9d41ea2911da598fde46ce1fe02c37751291" +checksum = "332f51cb23d20b0de8458b86580878211da09bcd4503cb579c225b3d124cabb3" dependencies = [ "event-listener 5.2.0", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -3408,7 +3419,7 @@ dependencies = [ "prettier-please", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3673,7 +3684,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3761,9 +3772,9 @@ dependencies = [ [[package]] name = "frame-support" -version = "29.0.0" +version = "29.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3b24824d29c43d0af94be3356bbf30338ededed649f6841d315a9ae067ce872" +checksum = "b8e52c84b611d2049d9253f83a62ab0f093e4be5c42a7ef42ea5bb16d6611e32" dependencies = [ "aquamarine", "array-bytes 6.2.2", @@ -3809,7 +3820,7 @@ checksum = "3bf1d648c4007d421b9677b3c893256913498fff159dc2d85022cdd9cc432f3c" dependencies = [ "Inflector", "cfg-expr", - "derive-syn-parse", + "derive-syn-parse 0.1.5", "expander 2.1.0", "frame-support-procedural-tools", "itertools 0.10.5", @@ -3818,7 +3829,7 @@ dependencies = [ "proc-macro2", "quote", "sp-crypto-hashing", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3831,7 +3842,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3842,7 +3853,7 @@ checksum = "68672b9ec6fe72d259d3879dc212c5e42e977588cdac830c76f54d9f492aeb58" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -4010,7 +4021,7 @@ dependencies = [ "futures-io", "memchr", "parking", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "waker-fn", ] @@ -4024,7 +4035,7 @@ dependencies = [ "futures-core", "futures-io", "parking", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -4035,7 +4046,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -4080,7 +4091,7 @@ dependencies = [ "futures-sink", "futures-task", "memchr", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "pin-utils", "slab", ] @@ -4404,7 +4415,7 @@ checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ "bytes", "http", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", ] [[package]] @@ -4447,8 +4458,8 @@ dependencies = [ "httparse", "httpdate", "itoa", - "pin-project-lite 0.2.13", - "socket2 0.4.10", + "pin-project-lite 0.2.14", + "socket2 0.5.6", "tokio", "tower-service", "tracing", @@ -4806,9 +4817,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jobserver" @@ -5125,9 +5136,9 @@ dependencies = [ [[package]] name = "landlock" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1530c5b973eeed4ac216af7e24baf5737645a6272e361f1fb95710678b67d9cc" +checksum = "9baa9eeb6e315942429397e617a190f4fdc696ef1ee0342939d641029cbb4ea7" dependencies = [ "enumflags2", "libc", @@ -5563,13 +5574,12 @@ dependencies = [ [[package]] name = "libredox" -version = "0.0.1" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85c833ca1e66078851dba29046874e38f08b2c883700aa29a03ddd3b23814ee8" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags 2.5.0", "libc", - "redox_syscall 0.4.1", ] [[package]] @@ -5805,7 +5815,7 @@ dependencies = [ "macro_magic_core", "macro_magic_macros", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -5815,11 +5825,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "468155613a44cfd825f1fb0ffa532b018253920d404e6fca1e8d43155198a46d" dependencies = [ "const-random", - "derive-syn-parse", + "derive-syn-parse 0.1.5", "macro_magic_core_macros", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -5830,7 +5840,7 @@ checksum = "9ea73aa640dc01d62a590d48c0c3521ed739d53b27f919b25c3551e233481654" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -5841,7 +5851,7 @@ checksum = "ef9d79ae96aaba821963320eb2b6e34d17df1e5a83d8a1985c29cc5be59577b3" dependencies = [ "macro_magic_core", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -5892,9 +5902,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.7.1" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" [[package]] name = "memfd" @@ -6229,9 +6239,9 @@ dependencies = [ [[package]] name = "nalgebra" -version = "0.32.4" +version = "0.32.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4541eb06dce09c0241ebbaab7102f0a01a0c8994afed2e5d0d66775016e25ac2" +checksum = "3ea4908d4f23254adda3daa60ffef0f1ac7b8c3e9a864cf3cc154b251908a2ef" dependencies = [ "approx", "matrixmultiply", @@ -6324,9 +6334,9 @@ dependencies = [ [[package]] name = "netlink-sys" -version = "0.8.5" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6471bf08e7ac0135876a9581bf3217ef0333c191c128d34878079f42ee150411" +checksum = "416060d346fbaf1f23f9512963e3e878f1a78e707cb699ba9215761754244307" dependencies = [ "bytes", "futures", @@ -6763,9 +6773,9 @@ dependencies = [ [[package]] name = "pallet-balances" -version = "29.0.0" +version = "29.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942007f4f7aace74b77009db1675e7ca98683a42dde5e2d85bba2a9f404d2e5a" +checksum = "e27946a57494d7c6231ae8909275bbd3cb5460ee3d27b7a5774a8b8e64d3ab92" dependencies = [ "docify", "frame-benchmarking", @@ -7045,7 +7055,7 @@ checksum = "3163c6bc21b55a0ccb74c546ba784d9c9e69beb9240c059d28a3052f4cbce509" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -7682,9 +7692,9 @@ dependencies = [ [[package]] name = "pallet-staking" -version = "29.0.0" +version = "29.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a94127295cf027a26e933ea6788b0824e9fedd90740013673e2d36b5d707efe" +checksum = "668b7d28c499f0d9f295fad26cf6c342472e21842e3b13bcaaac8536358b2d6c" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -7713,7 +7723,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -8274,9 +8284,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f8023d0fb78c8e03784ea1c7f3fa36e68a723138990b8d5a47d916b651e7a8" +checksum = "311fb059dee1a7b802f036316d790138c613a4e8b180c822e3925a662e9f0c95" dependencies = [ "memchr", "thiserror", @@ -8285,9 +8295,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0d24f72393fd16ab6ac5738bc33cdb6a9aa73f8b902e8fe29cf4e67d7dd1026" +checksum = "f73541b156d32197eecda1a4014d7f868fd2bcb3c550d5386087cfba442bf69c" dependencies = [ "pest", "pest_generator", @@ -8295,22 +8305,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc17e2a6c7d0a492f0158d7a4bd66cc17280308bbaff78d5bef566dca35ab80" +checksum = "c35eeed0a3fab112f75165fdc026b3913f4183133f19b49be773ac9ea966e8bd" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] name = "pest_meta" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934cd7631c050f4674352a6e835d5f6711ffbfb9345c2fc0107155ac495ae293" +checksum = "2adbf29bb9776f28caece835398781ab24435585fe0d4dc1374a61db5accedca" dependencies = [ "once_cell", "pest", @@ -8344,7 +8354,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -8355,9 +8365,9 @@ checksum = "257b64915a082f7811703966789728173279bdebb956b143dbcd23f6f970a777" [[package]] name = "pin-project-lite" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "pin-utils" @@ -8394,9 +8404,9 @@ checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "platforms" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626dec3cac7cc0e1577a2ec3fc496277ec2baa084bebad95bb6fdbfae235f84c" +checksum = "db23d408679286588f4d4644f965003d056e3dd5abcaaa938116871d7ce2fee7" [[package]] name = "polkadot-approval-distribution" @@ -9524,7 +9534,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6380dbe1fb03ecc74ad55d841cfc75480222d153ba69ddcb00977866cbdabdb8" dependencies = [ "polkavm-derive-impl", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -9536,7 +9546,7 @@ dependencies = [ "polkavm-common", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -9551,7 +9561,7 @@ dependencies = [ "concurrent-queue", "libc", "log", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "windows-sys 0.48.0", ] @@ -9564,7 +9574,7 @@ dependencies = [ "cfg-if", "concurrent-queue", "hermit-abi", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "rustix 0.38.32", "tracing", "windows-sys 0.52.0", @@ -9710,19 +9720,16 @@ dependencies = [ "pallet-collator-selection", "pallet-contracts", "pallet-message-queue", - "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", "pallet-nfts-runtime-api", "pallet-preimage", - "pallet-proxy", "pallet-scheduler", "pallet-session", "pallet-sudo", "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", "pallet-xcm", "parachains-common", "parity-scale-codec", @@ -9783,19 +9790,16 @@ dependencies = [ "pallet-collator-selection", "pallet-contracts", "pallet-message-queue", - "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", "pallet-nfts-runtime-api", "pallet-preimage", - "pallet-proxy", "pallet-scheduler", "pallet-session", "pallet-sudo", "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", "pallet-xcm", "parachains-common", "parity-scale-codec", @@ -9880,7 +9884,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22020dfcf177fcc7bf5deaf7440af371400c67c0de14c399938d8ed4fb4645d3" dependencies = [ "proc-macro2", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -9900,7 +9904,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d3928fb5db768cb86f891ff014f0144589297e3c6a1aba6ed7cecfdace270c7" dependencies = [ "proc-macro2", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -9994,7 +9998,7 @@ checksum = "834da187cfe638ae8abb0203f0b33e5ccdb02a28e7199f2f47b3e2754f50edca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -10040,7 +10044,7 @@ checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -10108,7 +10112,7 @@ dependencies = [ "itertools 0.11.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -10327,9 +10331,9 @@ dependencies = [ [[package]] name = "redox_users" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18479200779601e498ada4e8c1e1f50e3ee19deb0259c25825a98b5603b2cb4" +checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" dependencies = [ "getrandom 0.2.12", "libredox", @@ -10365,7 +10369,7 @@ checksum = "5fddb4f8d99b0a2ebafc65a87a69a7b9875e4b1ae1f00db265d300ef7f28bccc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -10389,7 +10393,7 @@ dependencies = [ "aho-corasick", "memchr", "regex-automata 0.4.6", - "regex-syntax 0.8.2", + "regex-syntax 0.8.3", ] [[package]] @@ -10409,7 +10413,7 @@ checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.2", + "regex-syntax 0.8.3", ] [[package]] @@ -10420,9 +10424,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" [[package]] name = "resolv-conf" @@ -11025,7 +11029,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -12039,7 +12043,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -12205,7 +12209,7 @@ dependencies = [ "proc-macro2", "quote", "scale-info", - "syn 2.0.55", + "syn 2.0.58", "thiserror", ] @@ -12358,9 +12362,9 @@ dependencies = [ [[package]] name = "security-framework" -version = "2.9.2" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" +checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6" dependencies = [ "bitflags 1.3.2", "core-foundation", @@ -12371,9 +12375,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.9.1" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" +checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef" dependencies = [ "core-foundation-sys", "libc", @@ -12438,14 +12442,14 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd" dependencies = [ "itoa", "ryu", @@ -13057,7 +13061,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -13323,7 +13327,7 @@ checksum = "b85d0f1f1e44bd8617eb2a48203ee854981229e3e79e6f468c7175d5fd37489b" dependencies = [ "quote", "sp-crypto-hashing", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -13344,7 +13348,7 @@ checksum = "48d09fa0a5f7299fb81ee25ae3853d26200f7a348148aed6de76be905c007dbe" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -13593,7 +13597,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -13800,7 +13804,7 @@ dependencies = [ "parity-scale-codec", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -14044,9 +14048,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "strsim" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "strum" @@ -14086,7 +14090,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -14262,7 +14266,7 @@ dependencies = [ "scale-info", "scale-typegen", "subxt-metadata", - "syn 2.0.55", + "syn 2.0.58", "thiserror", "tokio", ] @@ -14296,7 +14300,7 @@ dependencies = [ "quote", "scale-typegen", "subxt-codegen", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -14347,9 +14351,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.55" +version = "2.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "002a1b3dbf967edfafc32655d0f377ab0bb7b994aa1d32c8cc7e9b8bf3ebb8f0" +checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687" dependencies = [ "proc-macro2", "quote", @@ -14479,7 +14483,7 @@ checksum = "e4c60d69f36615a077cc7663b9cb8e42275722d23e58a7fa3d2c7f2915d09d04" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -14490,7 +14494,7 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -14619,7 +14623,7 @@ dependencies = [ "mio", "num_cpus", "parking_lot 0.12.1", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "signal-hook-registry", "socket2 0.5.6", "tokio-macros", @@ -14634,7 +14638,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -14676,7 +14680,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af" dependencies = [ "futures-core", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "tokio", "tokio-util", ] @@ -14691,7 +14695,7 @@ dependencies = [ "futures-core", "futures-io", "futures-sink", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "tokio", "tracing", ] @@ -14781,7 +14785,7 @@ dependencies = [ "futures-core", "futures-util", "pin-project", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "tower-layer", "tower-service", "tracing", @@ -14800,7 +14804,7 @@ dependencies = [ "http", "http-body", "http-range-header", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "tower-layer", "tower-service", ] @@ -14824,7 +14828,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "log", - "pin-project-lite 0.2.13", + "pin-project-lite 0.2.14", "tracing-attributes", "tracing-core", ] @@ -14837,7 +14841,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -14882,7 +14886,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -15308,7 +15312,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", "wasm-bindgen-shared", ] @@ -15342,7 +15346,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -15364,9 +15368,9 @@ dependencies = [ [[package]] name = "wasm-opt" -version = "0.116.0" +version = "0.116.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc942673e7684671f0c5708fc18993569d184265fd5223bb51fc8e5b9b6cfd52" +checksum = "2fd87a4c135535ffed86123b6fb0f0a5a0bc89e50416c942c5f0662c645f679c" dependencies = [ "anyhow", "libc", @@ -16222,7 +16226,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -16271,7 +16275,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -16291,7 +16295,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -16334,9 +16338,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.9+zstd.1.5.5" +version = "2.0.10+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e16efa8a874a0481a574084d34cc26fdb3b99627480f785888deb6386506656" +checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa" dependencies = [ "cc", "pkg-config", diff --git a/pop-api/examples/trust_backed_assets/.gitignore b/pop-api/examples/trust_backed_assets/.gitignore new file mode 100755 index 00000000..8de8f877 --- /dev/null +++ b/pop-api/examples/trust_backed_assets/.gitignore @@ -0,0 +1,9 @@ +# Ignore build artifacts from the local tests sub-crate. +/target/ + +# Ignore backup files creates by cargo fmt. +**/*.rs.bk + +# Remove Cargo.lock when creating an executable, leave it for libraries +# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock +Cargo.lock diff --git a/pop-api/examples/trust_backed_assets/Cargo.toml b/pop-api/examples/trust_backed_assets/Cargo.toml new file mode 100755 index 00000000..3c3716fc --- /dev/null +++ b/pop-api/examples/trust_backed_assets/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "pop_api_trust_backed_assets_example" +version = "0.1.0" +authors = ["[your_name] <[your_email]>"] +edition = "2021" + +[dependencies] +ink = { version = "5.0.0", default-features = false } +pop-api = { path = "../../../pop-api", default-features = false } +scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } +scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } + +[lib] +path = "lib.rs" + +[features] +default = ["std"] +std = [ + "ink/std", + "pop-api/std", + "scale/std", + "scale-info/std", +] +ink-as-dependency = [] +e2e-tests = [] diff --git a/pop-api/examples/trust_backed_assets/lib.rs b/pop-api/examples/trust_backed_assets/lib.rs new file mode 100755 index 00000000..8b2fbda6 --- /dev/null +++ b/pop-api/examples/trust_backed_assets/lib.rs @@ -0,0 +1,69 @@ +#![cfg_attr(not(feature = "std"), no_std, no_main)] + +use pop_api::assets::trust_backed as trust_backed_assets; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum ContractError { + TrustBackedAssetsError(trust_backed_assets::Error), + UnknownAsset, +} + +impl From for ContractError { + fn from(value: trust_backed_assets::Error) -> Self { + ContractError::TrustBackedAssetsError(value) + } +} + +#[ink::contract(env = pop_api::Environment)] +mod pop_api_extension_demo { + use super::*; + + #[ink(storage)] + #[derive(Default)] + pub struct PopApiExtensionDemo; + + impl PopApiExtensionDemo { + #[ink(constructor, payable)] + pub fn new() -> Self { + ink::env::debug_println!("Contract::new"); + Default::default() + } + + #[ink(message)] + pub fn mint_asset_through_runtime( + &mut self, + id: u32, + beneficiary: AccountId, + amount: Balance, + ) -> Result<(), ContractError> { + ink::env::debug_println!( + "Contract::mint_asset_through_runtime: id: {:?} beneficiary: {:?} amount: {:?}", + id, + beneficiary, + amount + ); + + // Check if asset doesn't exist. + if !trust_backed_assets::asset_exists(id)? { + return Err(ContractError::UnknownAsset); + } + + // Mint asset via pop api. + trust_backed_assets::mint(id, beneficiary, amount)?; + ink::env::debug_println!("Contract::mint_asset_through_runtime: asset(s) minted successfully"); + Ok(()) + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[ink::test] + fn default_works() { + PopApiExtensionDemo::new(); + } + } +} + diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index e4590c89..68ce6906 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -3,12 +3,12 @@ pub mod primitives; pub mod v0; -use crate::PopApiError::{Balances, Nfts, UnknownStatusCode}; +use crate::PopApiError::{Balances, Nfts, TrustBackedAssets, UnknownStatusCode}; use ink::{prelude::vec::Vec, ChainExtensionInstance}; use primitives::{cross_chain::*, storage_keys::*}; pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; use v0::RuntimeCall; -pub use v0::{balances, cross_chain, nfts, relay_chain_block_number, state}; +pub use v0::{balances, cross_chain, nfts, relay_chain_block_number, state, assets}; type AccountId = ::AccountId; type Balance = ::Balance; @@ -26,6 +26,7 @@ pub enum PopApiError { SystemCallFiltered, Balances(balances::Error), Nfts(nfts::Error), + TrustBackedAssets(assets::trust_backed::Error), Xcm(cross_chain::Error), } @@ -37,6 +38,7 @@ impl ink::env::chain_extension::FromStatusCode for PopApiError { 5 => Err(PopApiError::SystemCallFiltered), 10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)), 50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)), + 52_000..=52_999 => Err(TrustBackedAssets((status_code - 52_000).try_into()?)), _ => Err(UnknownStatusCode(status_code)), } } diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs new file mode 100644 index 00000000..7ad40f15 --- /dev/null +++ b/pop-api/src/v0/assets/mod.rs @@ -0,0 +1 @@ +pub mod trust_backed; \ No newline at end of file diff --git a/pop-api/src/v0/assets/trust_backed.rs b/pop-api/src/v0/assets/trust_backed.rs new file mode 100644 index 00000000..fb413413 --- /dev/null +++ b/pop-api/src/v0/assets/trust_backed.rs @@ -0,0 +1,519 @@ +use crate::{Balance, PopApiError::UnknownStatusCode, RuntimeCall, *}; +use ink::prelude::vec::Vec; +use primitives::{AssetId, MultiAddress}; +use scale::{Compact, Encode}; + +type Result = core::result::Result; + +/// https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/lib.rs +/// +/// Extrinsics within pallet assets (TrustBackedAssets Instance) that can be used via the pop api on Pop Network: +/// 1. create +/// 2. start_destroy +/// 3. destroy_accounts +/// 4. destroy_approvals +/// 5. finish_destroy +/// 6. mint +/// 7. burn +/// 8. transfer +/// 9. transfer_keep_alive +/// 10. force_transfer +/// 11. freeze +/// 12. thaw +/// 13. freeze_asset +/// 14. thaw_asset +/// 15. transfer_ownership +/// 16. set_team +/// 17. set_metadata +/// 18. clear_metadata +/// 19. approve_transfer +/// 20. cancel_approval +/// 21. force_cancel_approval +/// 22. transfer_approved +/// 23. touch +/// 24. refund +/// 25. set_min_balance +/// 26. touch_other +/// 27. refund_other +/// 28. block + + +/// Issue a new class of fungible assets from a public origin. +pub fn create( + id: AssetId, + admin: impl Into>, + min_balance: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Create { + id: id.into(), + admin: admin.into(), + min_balance: Compact(min_balance), + }))?) +} + +/// Start the process of destroying a fungible asset class. +pub fn start_destroy(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::StartDestroy { + id: id.into(), + }))?) +} + +/// Destroy all accounts associated with a given asset. +pub fn destroy_accounts(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::DestroyAccounts { + id: id.into(), + }))?) +} + +/// Destroy all approvals associated with a given asset up to the max (see runtime configuration TrustBackedAssets `RemoveItemsLimit`). +pub fn destroy_approvals(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::DestroyApprovals { + id: id.into(), + }))?) +} + +/// Complete destroying asset and unreserve currency. +pub fn finish_destroy(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::FinishDestroy { + id: id.into(), + }))?) +} + +/// Mint assets of a particular class. +pub fn mint( + id: AssetId, + beneficiary: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Mint { + id: id.into(), + beneficiary: beneficiary.into(), + amount: Compact(amount), + }))?) +} + +/// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`. +pub fn burn( + id: AssetId, + who: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Burn { + id: id.into(), + who: who.into(), + amount: Compact(amount), + }))?) +} + +/// Move some assets from the sender account to another. +pub fn transfer( + id: AssetId, + target: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Transfer { + id: id.into(), + target: target.into(), + amount: Compact(amount), + }))?) +} + +/// Move some assets from the sender account to another, keeping the sender account alive. +pub fn transfer_keep_alive( + id: AssetId, + target: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TransferKeepAlive { + id: id.into(), + target: target.into(), + amount: Compact(amount), + }))?) +} + +/// Move some assets from one account to another. Sender should be the Admin of the asset `id`. +pub fn force_transfer( + id: AssetId, + source: impl Into>, + dest: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ForceTransfer { + id: id.into(), + source: source.into(), + dest: dest.into(), + amount: Compact(amount), + }))?) +} + +/// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` +/// must already exist as an entry in `Account`s of the asset. If you want to freeze an +/// account that does not have an entry, use `touch_other` first. +pub fn freeze(id: AssetId, who: impl Into>) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Freeze { + id: id.into(), + who: who.into(), + }))?) +} + +/// Allow unprivileged transfers to and from an account again. +pub fn thaw(id: AssetId, who: impl Into>) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Thaw { + id: id.into(), + who: who.into(), + }))?) +} + +/// Disallow further unprivileged transfers for the asset class. +pub fn freeze_asset(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::FreezeAsset { + id: id.into(), + }))?) +} + +/// Allow unprivileged transfers for the asset again. +pub fn thaw_asset(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ThawAsset { + id: id.into(), + }))?) +} + +/// Change the Owner of an asset. +pub fn transfer_ownership( + id: AssetId, + owner: impl Into>, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TransferOwnership { + id: id.into(), + owner: owner.into(), + }))?) +} + +/// Change the Issuer, Admin and Freezer of an asset. +pub fn set_team( + id: AssetId, + issuer: impl Into>, + admin: impl Into>, + freezer: impl Into>, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::SetTeam { + id: id.into(), + issuer: issuer.into(), + admin: admin.into(), + freezer: freezer.into(), + }))?) +} + +/// Set the metadata for an asset. +pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::SetMetadata { + id: id.into(), + name, + symbol, + decimals, + }))?) +} + +/// Clear the metadata for an asset. +pub fn clear_metadata(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ClearMetadata { + id: id.into(), + }))?) +} + +/// Approve an amount of asset for transfer by a delegated third-party account. +pub fn approve_transfer( + id: AssetId, + delegate: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ApproveTransfer { + id: id.into(), + delegate: delegate.into(), + amount: Compact(amount), + }))?) +} + +/// Cancel all of some asset approved for delegated transfer by a third-party account. +pub fn cancel_approval( + id: AssetId, + delegate: impl Into>, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::CancelApproval { + id: id.into(), + delegate: delegate.into(), + }))?) +} + +/// Cancel all of some asset approved for delegated transfer by a third-party account. +pub fn force_cancel_approval( + id: AssetId, + owner: impl Into>, + delegate: impl Into>, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ForceCancelApproval { + id: id.into(), + owner: owner.into(), + delegate: delegate.into(), + }))?) +} + +/// Transfer some asset balance from a previously delegated account to some third-party +/// account. +pub fn transfer_approved( + id: AssetId, + owner: impl Into>, + destination: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TransferApproved { + id: id.into(), + owner: owner.into(), + destination: destination.into(), + amount: Compact(amount), + }))?) +} + +/// Create an asset account for non-provider assets. +pub fn touch(id: AssetId) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Touch { + id: id.into(), + }))?) +} + +/// Return the deposit (if any) of an asset account or a consumer reference (if any) of an +/// account. +pub fn refund(id: AssetId, allow_burn: bool) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Refund { + id: id.into(), + allow_burn, + }))?) +} + +/// Sets the minimum balance of an asset. +pub fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::SetMinBalance { + id: id.into(), + min_balance: Compact(min_balance), + }))?) +} + +/// Create an asset account for `who`. +pub fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TouchOther { + id: id.into(), + who: who.into(), + }))?) +} + +/// Return the deposit (if any) of a target asset account. Useful if you are the depositor. +pub fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::RefundOther { + id: id.into(), + who: who.into(), + }))?) +} + +/// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. +pub fn block(id: AssetId, who: impl Into>) -> Result<()> { + Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Block { + id: id.into(), + who: who.into(), + }))?) +} + +pub fn asset_exists(id: AssetId) -> Result { + Ok(state::read(RuntimeStateKeys::TrustBackedAssets(TrustBackedAssetsKeys::AssetExists(id)))?) +} + +// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected +// to be compact encoded. The pop api handles that for the developer. +// +// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development +// +// Asset id that is compact encoded. +type AssetIdParameter = Compact; +// Balance amount that is compact encoded. +type BalanceParameter = Compact; + +#[derive(Encode)] +pub(crate) enum TrustBackedAssetsCalls { + #[codec(index = 0)] + Create { + id: AssetIdParameter, + admin: MultiAddress, + min_balance: BalanceParameter, + }, + #[codec(index = 2)] + StartDestroy { id: AssetIdParameter }, + #[codec(index = 3)] + DestroyAccounts { id: AssetIdParameter }, + #[codec(index = 4)] + DestroyApprovals { id: AssetIdParameter }, + #[codec(index = 5)] + FinishDestroy { id: AssetIdParameter }, + #[codec(index = 6)] + Mint { + id: AssetIdParameter, + beneficiary: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 7)] + Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, + #[codec(index = 8)] + Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, + #[codec(index = 9)] + TransferKeepAlive { + id: AssetIdParameter, + target: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 10)] + ForceTransfer { + id: AssetIdParameter, + source: MultiAddress, + dest: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 11)] + Freeze { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 12)] + Thaw { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 13)] + FreezeAsset { id: AssetIdParameter }, + #[codec(index = 14)] + ThawAsset { id: AssetIdParameter }, + #[codec(index = 15)] + TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, + #[codec(index = 16)] + SetTeam { + id: AssetIdParameter, + issuer: MultiAddress, + admin: MultiAddress, + freezer: MultiAddress, + }, + #[codec(index = 17)] + SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, + #[codec(index = 18)] + ClearMetadata { id: AssetIdParameter }, + #[codec(index = 22)] + ApproveTransfer { + id: AssetIdParameter, + delegate: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 23)] + CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, + #[codec(index = 24)] + ForceCancelApproval { + id: AssetIdParameter, + owner: MultiAddress, + delegate: MultiAddress, + }, + #[codec(index = 25)] + TransferApproved { + id: AssetIdParameter, + owner: MultiAddress, + destination: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 26)] + Touch { id: AssetIdParameter }, + #[codec(index = 27)] + Refund { id: AssetIdParameter, allow_burn: bool }, + #[codec(index = 28)] + SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, + #[codec(index = 29)] + TouchOther { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 30)] + RefundOther { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 31)] + Block { id: AssetIdParameter, who: MultiAddress }, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum Error { + /// Account balance must be greater than or equal to the transfer amount. + BalanceLow, + /// The account to alter does not exist. + NoAccount, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + /// The origin account is frozen. + Frozen, + /// The asset ID is already taken. + InUse, + /// Invalid witness data given. + BadWitness, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// Unable to increment the consumer reference counters on the account. Either no provider + /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one + /// fewer then the maximum number of consumers has been reached. + UnavailableConsumer, + /// Invalid metadata given. + BadMetadata, + /// No approval exists that would allow the transfer. + Unapproved, + /// The source account would not survive the transfer and it needs to stay alive. + WouldDie, + /// The asset-account already exists. + AlreadyExists, + /// The asset-account doesn't have an associated deposit. + NoDeposit, + /// The operation would result in funds being burned. + WouldBurn, + /// The asset is a live asset and is actively being used. Usually emit for operations such + /// as `start_destroy` which require the asset to be in a destroying state. + LiveAsset, + /// The asset is not live, and likely being destroyed. + AssetNotLive, + /// The asset status is not the expected status. + IncorrectStatus, + /// The asset should be frozen before the given operation. + NotFrozen, + /// Callback action resulted in error + CallbackFailed, +} + +impl TryFrom for Error { + type Error = PopApiError; + + fn try_from(status_code: u32) -> core::result::Result { + use Error::*; + match status_code { + 0 => Ok(BalanceLow), + 1 => Ok(NoAccount), + 2 => Ok(NoPermission), + 3 => Ok(Unknown), + 4 => Ok(Frozen), + 5 => Ok(InUse), + 6 => Ok(BadWitness), + 7 => Ok(MinBalanceZero), + 8 => Ok(UnavailableConsumer), + 9 => Ok(BadMetadata), + 10 => Ok(Unapproved), + 11 => Ok(WouldDie), + 12 => Ok(AlreadyExists), + 13 => Ok(NoDeposit), + 14 => Ok(WouldBurn), + 15 => Ok(LiveAsset), + 16 => Ok(AssetNotLive), + 17 => Ok(IncorrectStatus), + 18 => Ok(NotFrozen), + _ => Err(UnknownStatusCode(status_code)), + } + } +} + +impl From for Error { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::TrustBackedAssets(e) => e, + _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), + } + } +} diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 2ae0b821..d914db24 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -7,6 +7,7 @@ pub mod balances; pub mod cross_chain; pub mod nfts; pub mod state; +pub mod assets; pub fn relay_chain_block_number() -> Result { state::read(RuntimeStateKeys::ParachainSystem(ParachainSystemKeys::LastRelayChainBlockNumber)) @@ -18,4 +19,6 @@ pub(crate) enum RuntimeCall { Balances(balances::BalancesCall), #[codec(index = 50)] Nfts(nfts::NftCalls), + #[codec(index = 52)] + TrustBackedAssets(assets::trust_backed::TrustBackedAssetsCalls), } diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index 3db08cd1..5a55154f 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -669,7 +669,7 @@ impl From for Error { fn from(error: PopApiError) -> Self { match error { PopApiError::Nfts(e) => e, - _ => panic!("expected nfts error"), + _ => panic!("unexpected pallet nfts error. This error is unknown to pallet nfts"), } } } diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 8ad74ade..ebad36d3 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -1,14 +1,12 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] pub use bounded_collections::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec, ConstU32}; -//use scale::{Decode, Encode, MaxEncodedLen}; pub mod cross_chain; pub mod storage_keys; -// /// Some way of identifying an account on the chain. -// #[derive(Encode, Decode, Debug, MaxEncodedLen)] -// pub struct AccountId([u8; 32]); +// Identifier for the class of asset. +pub type AssetId = u32; // Id used for identifying non-fungible collections. pub type CollectionId = u32; // Id used for identifying non-fungible items. diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index 2bcb41ec..a03b3a09 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -5,6 +5,7 @@ use scale::{Decode, Encode, MaxEncodedLen}; pub enum RuntimeStateKeys { Nfts(NftsKeys), ParachainSystem(ParachainSystemKeys), + TrustBackedAssets(TrustBackedAssetsKeys), } #[derive(Encode, Decode, Debug, MaxEncodedLen)] @@ -33,3 +34,9 @@ pub enum NftsKeys { /// Get the attribute value of `item` of `collection` corresponding to `key`. CollectionAttribute(CollectionId, BoundedVec), } + +#[derive(Encode, Decode, Debug, MaxEncodedLen)] +pub enum TrustBackedAssetsKeys { + /// Check if the asset exists. + AssetExists(AssetId), +} diff --git a/runtime/devnet/src/config/assets.rs b/runtime/devnet/src/config/assets.rs index 34035c1f..f51f8875 100644 --- a/runtime/devnet/src/config/assets.rs +++ b/runtime/devnet/src/config/assets.rs @@ -1,6 +1,6 @@ use crate::{ - deposit, AccountId, Assets, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, - RuntimeHoldReason, DAYS, EXISTENTIAL_DEPOSIT, UNIT, + deposit, AccountId, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, + RuntimeHoldReason, TrustBackedAssets, DAYS, EXISTENTIAL_DEPOSIT, UNIT, }; use frame_support::{ parameter_types, @@ -84,9 +84,9 @@ impl pallet_nft_fractionalization::Config for Runtime { type StringLimit = AssetsStringLimit; type NftCollectionId = ::CollectionId; type NftId = ::ItemId; - type AssetBalance = >::Balance; - type AssetId = >::AssetId; - type Assets = Assets; + type AssetBalance = >::Balance; + type AssetId = >::AssetId; + type Assets = TrustBackedAssets; type Nfts = Nfts; type PalletId = NftFractionalizationPalletId; type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight; @@ -95,9 +95,9 @@ impl pallet_nft_fractionalization::Config for Runtime { type BenchmarkHelper = (); } -pub type TrustBackedAssets = pallet_assets::Instance1; -pub type TrustBackedAssetsCall = pallet_assets::Call; -impl pallet_assets::Config for Runtime { +pub type TrustBackedAssetsInstance = pallet_assets::Instance1; +pub(crate) type TrustBackedAssetsCall = pallet_assets::Call; +impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type AssetId = AssetIdForTrustBackedAssets; diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs index 7e2a53c0..c8e88eb2 100644 --- a/runtime/devnet/src/extensions.rs +++ b/runtime/devnet/src/extensions.rs @@ -3,15 +3,15 @@ use frame_support::traits::{Contains, OriginTrait}; use frame_support::{ dispatch::{GetDispatchInfo, RawOrigin}, pallet_prelude::*, - traits::nonfungibles_v2::Inspect, + traits::{fungibles::Inspect, nonfungibles_v2::Inspect as NonFungiblesInspect}, }; use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, }; use pop_primitives::{ cross_chain::CrossChainMessage, - storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, - CollectionId, ItemId, + storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys, TrustBackedAssetsKeys}, + AssetId, CollectionId, ItemId, }; use sp_core::crypto::UncheckedFrom; use sp_runtime::{ @@ -24,7 +24,10 @@ use xcm::{ VersionedXcm, }; -use crate::{AccountId, AllowedApiCalls, RuntimeCall, RuntimeOrigin, UNIT}; +use crate::{ + assets_config::TrustBackedAssetsInstance, AccountId, AllowedPopApiCalls, RuntimeCall, + RuntimeOrigin, UNIT, +}; const LOG_TARGET: &str = "pop-api::extension"; @@ -37,6 +40,7 @@ impl ChainExtension for PopApiExtension where T: pallet_contracts::Config + pallet_xcm::Config + + pallet_assets::Config + pallet_nfts::Config + cumulus_pallet_parachain_system::Config + frame_system::Config< @@ -120,7 +124,7 @@ where log::debug!(target:LOG_TARGET, "{} inputted RuntimeCall: {:?}", log_prefix, call); - origin.add_filter(AllowedApiCalls::contains); + origin.add_filter(AllowedPopApiCalls::contains); match call.dispatch(origin) { Ok(info) => { @@ -192,6 +196,7 @@ where fn read_state(env: Environment) -> Result<(), DispatchError> where T: pallet_contracts::Config + + pallet_assets::Config + pallet_nfts::Config + cumulus_pallet_parachain_system::Config + frame_system::Config, @@ -217,6 +222,9 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, + RuntimeStateKeys::TrustBackedAssets(key) => { + read_trust_backed_assets_state::(key, &mut env) + }, }? .encode(); @@ -292,6 +300,23 @@ where } } +fn read_trust_backed_assets_state( + key: TrustBackedAssetsKeys, + env: &mut Environment, +) -> Result, DispatchError> +where + T: pallet_contracts::Config + + pallet_assets::Config, + E: Ext, +{ + match key { + TrustBackedAssetsKeys::AssetExists(id) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::asset_exists(id).encode()) + }, + } +} + fn send_xcm(env: Environment) -> Result<(), DispatchError> where T: pallet_contracts::Config @@ -828,6 +853,110 @@ mod tests { }); } + #[test] + #[ignore] + fn dispatch_trust_backed_assets_mint_from_contract_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + + let (wasm_binary, _) = load_wasm_module::( + "../../pop-api/examples/trust_backed_assets/target/ink/pop_api_trust_backed_assets_example.wasm", + ) + .unwrap(); + + let init_value = 100; + + let result = Contracts::bare_instantiate( + ALICE, + init_value, + GAS_LIMIT, + None, + Code::Upload(wasm_binary), + function_selector("new"), + vec![], + DEBUG_OUTPUT, + pallet_contracts::CollectEvents::Skip, + ) + .result + .unwrap(); + + assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); + let addr = result.account_id; + + let asset_id: u32 = 1; + let min_balance = 1; + let amount: u128 = 100 * UNIT; + let function = function_selector("mint_asset_through_runtime"); + let params = [function, asset_id.encode(), BOB.encode(), amount.encode()].concat(); + + // Mint asset which does not exist. + let result = Contracts::bare_call( + ALICE, + addr.clone(), + 0, + GAS_LIMIT, + None, + params.clone(), + DEBUG_OUTPUT, + pallet_contracts::CollectEvents::Skip, + pallet_contracts::Determinism::Enforced, + ); + + if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { + log::debug!( + "Contract debug buffer - {:?}", + String::from_utf8(result.debug_message.clone()) + ); + log::debug!("result: {:?}", result); + } + + // Check for revert. + assert!(result.result.unwrap().did_revert(), "Contract should have been reverted!"); + + // Create asset with contract as owner. + assert_eq!( + TrustBackedAssets::force_create( + RuntimeOrigin::root(), + asset_id.into(), + addr.clone().into(), + true, + min_balance, + ), + Ok(()) + ); + + // Check Bob's asset balance before minting through contract. + let bob_balance_before = TrustBackedAssets::balance(asset_id, &BOB); + assert_eq!(bob_balance_before, 0); + + let result = Contracts::bare_call( + ALICE, + addr.clone(), + 0, + GAS_LIMIT, + None, + params, + DEBUG_OUTPUT, + pallet_contracts::CollectEvents::Skip, + pallet_contracts::Determinism::Enforced, + ); + + if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { + log::debug!( + "Contract debug buffer - {:?}", + String::from_utf8(result.debug_message.clone()) + ); + log::debug!("result: {:?}", result); + } + + // Check for revert + assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); + + let bob_balance_after = TrustBackedAssets::balance(asset_id, &BOB); + assert_eq!(bob_balance_after, bob_balance_before + amount); + }); + } + #[test] #[ignore] fn allow_call_filter_blocks_call() { diff --git a/runtime/devnet/src/lib.rs b/runtime/devnet/src/lib.rs index ffca8a12..52a0938f 100644 --- a/runtime/devnet/src/lib.rs +++ b/runtime/devnet/src/lib.rs @@ -251,46 +251,77 @@ impl Contains for FilteredCalls { } /// A type to identify allowed calls to the Runtime from contracts. Used by Pop API -pub struct AllowedApiCalls; -impl Contains for crate::AllowedApiCalls { +pub struct AllowedPopApiCalls; +impl Contains for crate::AllowedPopApiCalls { fn contains(c: &RuntimeCall) -> bool { + use assets_config::TrustBackedAssetsCall; use pallet_nfts::Call as NftsCall; matches!( c, RuntimeCall::Balances(BalancesCall::transfer_keep_alive { .. }) - | RuntimeCall::Nfts( - NftsCall::create { .. } - | NftsCall::destroy { .. } - | NftsCall::mint { .. } | NftsCall::burn { .. } - | NftsCall::transfer { .. } - | NftsCall::redeposit { .. } - | NftsCall::lock_item_transfer { .. } - | NftsCall::unlock_item_transfer { .. } - | NftsCall::lock_collection { .. } - | NftsCall::transfer_ownership { .. } - | NftsCall::set_team { .. } - | NftsCall::approve_transfer { .. } - | NftsCall::cancel_approval { .. } - | NftsCall::clear_all_transfer_approvals { .. } - | NftsCall::lock_item_properties { .. } - | NftsCall::set_attribute { .. } - | NftsCall::clear_attribute { .. } - | NftsCall::approve_item_attributes { .. } - | NftsCall::cancel_item_attributes_approval { .. } - | NftsCall::set_metadata { .. } - | NftsCall::clear_metadata { .. } - | NftsCall::set_collection_metadata { .. } - | NftsCall::clear_collection_metadata { .. } - | NftsCall::set_accept_ownership { .. } - | NftsCall::set_collection_max_supply { .. } - | NftsCall::update_mint_settings { .. } - | NftsCall::set_price { .. } - | NftsCall::buy_item { .. } - | NftsCall::pay_tips { .. } - | NftsCall::create_swap { .. } - | NftsCall::cancel_swap { .. } - | NftsCall::claim_swap { .. } - ) + | RuntimeCall::TrustBackedAssets( + TrustBackedAssetsCall::create { .. } + | TrustBackedAssetsCall::start_destroy { .. } + | TrustBackedAssetsCall::destroy_accounts { .. } + | TrustBackedAssetsCall::destroy_approvals { .. } + | TrustBackedAssetsCall::finish_destroy { .. } + | TrustBackedAssetsCall::mint { .. } + | TrustBackedAssetsCall::burn { .. } + | TrustBackedAssetsCall::transfer { .. } + | TrustBackedAssetsCall::transfer_keep_alive { .. } + | TrustBackedAssetsCall::force_transfer { .. } + | TrustBackedAssetsCall::freeze { .. } + | TrustBackedAssetsCall::thaw { .. } + | TrustBackedAssetsCall::freeze_asset { .. } + | TrustBackedAssetsCall::thaw_asset { .. } + | TrustBackedAssetsCall::transfer_ownership { .. } + | TrustBackedAssetsCall::set_team { .. } + | TrustBackedAssetsCall::set_metadata { .. } + | TrustBackedAssetsCall::clear_metadata { .. } + | TrustBackedAssetsCall::approve_transfer { .. } + | TrustBackedAssetsCall::cancel_approval { .. } + | TrustBackedAssetsCall::force_cancel_approval { .. } + | TrustBackedAssetsCall::transfer_approved { .. } + | TrustBackedAssetsCall::touch { .. } + | TrustBackedAssetsCall::refund { .. } + | TrustBackedAssetsCall::set_min_balance { .. } + | TrustBackedAssetsCall::touch_other { .. } + | TrustBackedAssetsCall::refund_other { .. } + | TrustBackedAssetsCall::block { .. } + ) | RuntimeCall::Nfts( + NftsCall::create { .. } + | NftsCall::destroy { .. } + | NftsCall::mint { .. } + | NftsCall::burn { .. } + | NftsCall::transfer { .. } + | NftsCall::redeposit { .. } + | NftsCall::lock_item_transfer { .. } + | NftsCall::unlock_item_transfer { .. } + | NftsCall::lock_collection { .. } + | NftsCall::transfer_ownership { .. } + | NftsCall::set_team { .. } + | NftsCall::approve_transfer { .. } + | NftsCall::cancel_approval { .. } + | NftsCall::clear_all_transfer_approvals { .. } + | NftsCall::lock_item_properties { .. } + | NftsCall::set_attribute { .. } + | NftsCall::clear_attribute { .. } + | NftsCall::approve_item_attributes { .. } + | NftsCall::cancel_item_attributes_approval { .. } + | NftsCall::set_metadata { .. } + | NftsCall::clear_metadata { .. } + | NftsCall::set_collection_metadata { .. } + | NftsCall::clear_collection_metadata { .. } + | NftsCall::set_accept_ownership { .. } + | NftsCall::set_collection_max_supply { .. } + | NftsCall::update_mint_settings { .. } + | NftsCall::set_price { .. } + | NftsCall::buy_item { .. } + | NftsCall::pay_tips { .. } + | NftsCall::create_swap { .. } + | NftsCall::cancel_swap { .. } + | NftsCall::claim_swap { .. } + ) ) } } @@ -631,7 +662,7 @@ construct_runtime!( // Assets Nfts: pallet_nfts = 50, NftFractionalization: pallet_nft_fractionalization = 51, - Assets: pallet_assets:: = 52, + TrustBackedAssets: pallet_assets:: = 52, } ); diff --git a/runtime/testnet/src/config/assets.rs b/runtime/testnet/src/config/assets.rs index 34035c1f..f51f8875 100644 --- a/runtime/testnet/src/config/assets.rs +++ b/runtime/testnet/src/config/assets.rs @@ -1,6 +1,6 @@ use crate::{ - deposit, AccountId, Assets, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, - RuntimeHoldReason, DAYS, EXISTENTIAL_DEPOSIT, UNIT, + deposit, AccountId, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, + RuntimeHoldReason, TrustBackedAssets, DAYS, EXISTENTIAL_DEPOSIT, UNIT, }; use frame_support::{ parameter_types, @@ -84,9 +84,9 @@ impl pallet_nft_fractionalization::Config for Runtime { type StringLimit = AssetsStringLimit; type NftCollectionId = ::CollectionId; type NftId = ::ItemId; - type AssetBalance = >::Balance; - type AssetId = >::AssetId; - type Assets = Assets; + type AssetBalance = >::Balance; + type AssetId = >::AssetId; + type Assets = TrustBackedAssets; type Nfts = Nfts; type PalletId = NftFractionalizationPalletId; type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight; @@ -95,9 +95,9 @@ impl pallet_nft_fractionalization::Config for Runtime { type BenchmarkHelper = (); } -pub type TrustBackedAssets = pallet_assets::Instance1; -pub type TrustBackedAssetsCall = pallet_assets::Call; -impl pallet_assets::Config for Runtime { +pub type TrustBackedAssetsInstance = pallet_assets::Instance1; +pub(crate) type TrustBackedAssetsCall = pallet_assets::Call; +impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type AssetId = AssetIdForTrustBackedAssets; diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index d6f2d656..0d552090 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -3,23 +3,25 @@ use frame_support::traits::{Contains, OriginTrait}; use frame_support::{ dispatch::{GetDispatchInfo, RawOrigin}, pallet_prelude::*, - traits::nonfungibles_v2::Inspect, + traits::{fungibles::Inspect, nonfungibles_v2::Inspect as NonFungiblesInspect}, }; use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, }; use pop_primitives::{ - storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, - CollectionId, ItemId, + storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys, TrustBackedAssetsKeys}, + AssetId, CollectionId, ItemId, }; use sp_core::crypto::UncheckedFrom; use sp_runtime::{ traits::{BlockNumberProvider, Dispatchable}, DispatchError, }; -use sp_std::vec::Vec; -use crate::{AccountId, AllowedApiCalls, RuntimeCall, RuntimeOrigin}; +use crate::{ + assets_config::TrustBackedAssetsInstance, AccountId, AllowedPopApiCalls, RuntimeCall, + RuntimeOrigin, +}; const LOG_TARGET: &str = "pop-api::extension"; @@ -32,6 +34,7 @@ impl ChainExtension for PopApiExtension where T: pallet_contracts::Config + pallet_xcm::Config + + pallet_assets::Config + pallet_nfts::Config + cumulus_pallet_parachain_system::Config + frame_system::Config< @@ -109,7 +112,7 @@ where log::debug!(target:LOG_TARGET, "{} inputted RuntimeCall: {:?}", log_prefix, call); - origin.add_filter(AllowedApiCalls::contains); + origin.add_filter(AllowedPopApiCalls::contains); match call.dispatch(origin) { Ok(info) => { @@ -181,6 +184,7 @@ where fn read_state(env: Environment) -> Result<(), DispatchError> where T: pallet_contracts::Config + + pallet_assets::Config + pallet_nfts::Config + cumulus_pallet_parachain_system::Config + frame_system::Config, @@ -206,6 +210,9 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, + RuntimeStateKeys::TrustBackedAssets(key) => { + read_trust_backed_assets_state::(key, &mut env) + }, }? .encode(); @@ -281,6 +288,23 @@ where } } +fn read_trust_backed_assets_state( + key: TrustBackedAssetsKeys, + env: &mut Environment, +) -> Result, DispatchError> +where + T: pallet_contracts::Config + + pallet_assets::Config, + E: Ext, +{ + match key { + TrustBackedAssetsKeys::AssetExists(id) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::asset_exists(id).encode()) + }, + } +} + #[cfg(test)] mod tests { pub use super::*; @@ -481,7 +505,7 @@ mod tests { log::debug!("result: {:?}", result); } - // check for revert + // Check for revert. assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); assert_eq!(Nfts::owner(collection_id, item_id), Some(BOB.into())); @@ -546,7 +570,7 @@ mod tests { log::debug!("result: {:?}", result); } - // check for revert with expected error + // Check for revert with expected error. let result = result.result.unwrap(); assert!(result.did_revert()); }); @@ -606,7 +630,7 @@ mod tests { log::debug!("result: {:?}", result); } - // check for revert + // Check for revert. assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); }); } @@ -669,7 +693,7 @@ mod tests { log::debug!("result: {:?}", result); } - // check for revert + // Check for revert. assert!( result.result.is_err(), "Contract execution should have failed - unimplemented runtime call!" @@ -677,6 +701,110 @@ mod tests { }); } + #[test] + #[ignore] + fn dispatch_trust_backed_assets_mint_from_contract_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + + let (wasm_binary, _) = load_wasm_module::( + "../../pop-api/examples/trust_backed_assets/target/ink/pop_api_trust_backed_assets_example.wasm", + ) + .unwrap(); + + let init_value = 100; + + let result = Contracts::bare_instantiate( + ALICE, + init_value, + GAS_LIMIT, + None, + Code::Upload(wasm_binary), + function_selector("new"), + vec![], + DEBUG_OUTPUT, + pallet_contracts::CollectEvents::Skip, + ) + .result + .unwrap(); + + assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); + let addr = result.account_id; + + let asset_id: u32 = 1; + let min_balance = 1; + let amount: u128 = 100 * UNIT; + let function = function_selector("mint_asset_through_runtime"); + let params = [function, asset_id.encode(), BOB.encode(), amount.encode()].concat(); + + // Mint asset which does not exist. + let result = Contracts::bare_call( + ALICE, + addr.clone(), + 0, + GAS_LIMIT, + None, + params.clone(), + DEBUG_OUTPUT, + pallet_contracts::CollectEvents::Skip, + pallet_contracts::Determinism::Enforced, + ); + + if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { + log::debug!( + "Contract debug buffer - {:?}", + String::from_utf8(result.debug_message.clone()) + ); + log::debug!("result: {:?}", result); + } + + // Check for revert. + assert!(result.result.unwrap().did_revert(), "Contract should have been reverted!"); + + // Create asset with contract as owner. + assert_eq!( + TrustBackedAssets::force_create( + RuntimeOrigin::root(), + asset_id.into(), + addr.clone().into(), + true, + min_balance, + ), + Ok(()) + ); + + // Check Bob's asset balance before minting through contract. + let bob_balance_before = TrustBackedAssets::balance(asset_id, &BOB); + assert_eq!(bob_balance_before, 0); + + let result = Contracts::bare_call( + ALICE, + addr.clone(), + 0, + GAS_LIMIT, + None, + params, + DEBUG_OUTPUT, + pallet_contracts::CollectEvents::Skip, + pallet_contracts::Determinism::Enforced, + ); + + if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { + log::debug!( + "Contract debug buffer - {:?}", + String::from_utf8(result.debug_message.clone()) + ); + log::debug!("result: {:?}", result); + } + + // Check for revert + assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); + + let bob_balance_after = TrustBackedAssets::balance(asset_id, &BOB); + assert_eq!(bob_balance_after, bob_balance_before + amount); + }); + } + #[test] #[ignore] fn allow_call_filter_blocks_call() { @@ -731,7 +859,7 @@ mod tests { log::debug!("filtered result: {:?}", result); } - // check for revert + // Check for revert. assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); }); } diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index 37f378f7..312d9b50 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -250,46 +250,77 @@ impl Contains for FilteredCalls { } /// A type to identify allowed calls to the Runtime from contracts. Used by Pop API -pub struct AllowedApiCalls; -impl Contains for crate::AllowedApiCalls { +pub struct AllowedPopApiCalls; +impl Contains for crate::AllowedPopApiCalls { fn contains(c: &RuntimeCall) -> bool { + use assets_config::TrustBackedAssetsCall; use pallet_nfts::Call as NftsCall; matches!( c, RuntimeCall::Balances(BalancesCall::transfer_keep_alive { .. }) - | RuntimeCall::Nfts( - NftsCall::create { .. } - | NftsCall::destroy { .. } - | NftsCall::mint { .. } | NftsCall::burn { .. } - | NftsCall::transfer { .. } - | NftsCall::redeposit { .. } - | NftsCall::lock_item_transfer { .. } - | NftsCall::unlock_item_transfer { .. } - | NftsCall::lock_collection { .. } - | NftsCall::transfer_ownership { .. } - | NftsCall::set_team { .. } - | NftsCall::approve_transfer { .. } - | NftsCall::cancel_approval { .. } - | NftsCall::clear_all_transfer_approvals { .. } - | NftsCall::lock_item_properties { .. } - | NftsCall::set_attribute { .. } - | NftsCall::clear_attribute { .. } - | NftsCall::approve_item_attributes { .. } - | NftsCall::cancel_item_attributes_approval { .. } - | NftsCall::set_metadata { .. } - | NftsCall::clear_metadata { .. } - | NftsCall::set_collection_metadata { .. } - | NftsCall::clear_collection_metadata { .. } - | NftsCall::set_accept_ownership { .. } - | NftsCall::set_collection_max_supply { .. } - | NftsCall::update_mint_settings { .. } - | NftsCall::set_price { .. } - | NftsCall::buy_item { .. } - | NftsCall::pay_tips { .. } - | NftsCall::create_swap { .. } - | NftsCall::cancel_swap { .. } - | NftsCall::claim_swap { .. } - ) + | RuntimeCall::TrustBackedAssets( + TrustBackedAssetsCall::create { .. } + | TrustBackedAssetsCall::start_destroy { .. } + | TrustBackedAssetsCall::destroy_accounts { .. } + | TrustBackedAssetsCall::destroy_approvals { .. } + | TrustBackedAssetsCall::finish_destroy { .. } + | TrustBackedAssetsCall::mint { .. } + | TrustBackedAssetsCall::burn { .. } + | TrustBackedAssetsCall::transfer { .. } + | TrustBackedAssetsCall::transfer_keep_alive { .. } + | TrustBackedAssetsCall::force_transfer { .. } + | TrustBackedAssetsCall::freeze { .. } + | TrustBackedAssetsCall::thaw { .. } + | TrustBackedAssetsCall::freeze_asset { .. } + | TrustBackedAssetsCall::thaw_asset { .. } + | TrustBackedAssetsCall::transfer_ownership { .. } + | TrustBackedAssetsCall::set_team { .. } + | TrustBackedAssetsCall::set_metadata { .. } + | TrustBackedAssetsCall::clear_metadata { .. } + | TrustBackedAssetsCall::approve_transfer { .. } + | TrustBackedAssetsCall::cancel_approval { .. } + | TrustBackedAssetsCall::force_cancel_approval { .. } + | TrustBackedAssetsCall::transfer_approved { .. } + | TrustBackedAssetsCall::touch { .. } + | TrustBackedAssetsCall::refund { .. } + | TrustBackedAssetsCall::set_min_balance { .. } + | TrustBackedAssetsCall::touch_other { .. } + | TrustBackedAssetsCall::refund_other { .. } + | TrustBackedAssetsCall::block { .. } + ) | RuntimeCall::Nfts( + NftsCall::create { .. } + | NftsCall::destroy { .. } + | NftsCall::mint { .. } + | NftsCall::burn { .. } + | NftsCall::transfer { .. } + | NftsCall::redeposit { .. } + | NftsCall::lock_item_transfer { .. } + | NftsCall::unlock_item_transfer { .. } + | NftsCall::lock_collection { .. } + | NftsCall::transfer_ownership { .. } + | NftsCall::set_team { .. } + | NftsCall::approve_transfer { .. } + | NftsCall::cancel_approval { .. } + | NftsCall::clear_all_transfer_approvals { .. } + | NftsCall::lock_item_properties { .. } + | NftsCall::set_attribute { .. } + | NftsCall::clear_attribute { .. } + | NftsCall::approve_item_attributes { .. } + | NftsCall::cancel_item_attributes_approval { .. } + | NftsCall::set_metadata { .. } + | NftsCall::clear_metadata { .. } + | NftsCall::set_collection_metadata { .. } + | NftsCall::clear_collection_metadata { .. } + | NftsCall::set_accept_ownership { .. } + | NftsCall::set_collection_max_supply { .. } + | NftsCall::update_mint_settings { .. } + | NftsCall::set_price { .. } + | NftsCall::buy_item { .. } + | NftsCall::pay_tips { .. } + | NftsCall::create_swap { .. } + | NftsCall::cancel_swap { .. } + | NftsCall::claim_swap { .. } + ) ) } } @@ -630,7 +661,7 @@ construct_runtime!( // Assets Nfts: pallet_nfts = 50, NftFractionalization: pallet_nft_fractionalization = 51, - Assets: pallet_assets:: = 52, + TrustBackedAssets: pallet_assets:: = 52, } ); From 418aa6311498112ec43a23ea72962a43464826b3 Mon Sep 17 00:00:00 2001 From: R0GUE Date: Fri, 12 Apr 2024 15:33:32 +0200 Subject: [PATCH 02/27] style: renaming assets example --- pop-api/examples/trust_backed_assets/lib.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/pop-api/examples/trust_backed_assets/lib.rs b/pop-api/examples/trust_backed_assets/lib.rs index 8b2fbda6..3606f852 100755 --- a/pop-api/examples/trust_backed_assets/lib.rs +++ b/pop-api/examples/trust_backed_assets/lib.rs @@ -1,5 +1,9 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] +// Utilizing Trust Backed Assets with the Pop API. +// +// This example demonstrates interaction with trust backed assets via the assets pallet. Trust backed assets are originated +// and managed within Pop Network, harnessing the platform's inherent trust, security, and governance models. use pop_api::assets::trust_backed as trust_backed_assets; #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] @@ -16,14 +20,14 @@ impl From for ContractError { } #[ink::contract(env = pop_api::Environment)] -mod pop_api_extension_demo { +mod pop_api_tb_assets_example { use super::*; #[ink(storage)] #[derive(Default)] - pub struct PopApiExtensionDemo; + pub struct PopApiTBAssetsExample; - impl PopApiExtensionDemo { + impl PopApiTBAssetsExample { #[ink(constructor, payable)] pub fn new() -> Self { ink::env::debug_println!("Contract::new"); @@ -45,13 +49,15 @@ mod pop_api_extension_demo { ); // Check if asset doesn't exist. - if !trust_backed_assets::asset_exists(id)? { + if !trust_backed_assets::asset_exists(id)? { return Err(ContractError::UnknownAsset); } // Mint asset via pop api. trust_backed_assets::mint(id, beneficiary, amount)?; - ink::env::debug_println!("Contract::mint_asset_through_runtime: asset(s) minted successfully"); + ink::env::debug_println!( + "Contract::mint_asset_through_runtime: asset(s) minted successfully" + ); Ok(()) } } @@ -62,8 +68,7 @@ mod pop_api_extension_demo { #[ink::test] fn default_works() { - PopApiExtensionDemo::new(); + PopApiTBAssetsExample::new(); } } } - From 3d385df789e84a678badd94a70a6833d61329437 Mon Sep 17 00:00:00 2001 From: R0GUE Date: Mon, 22 Apr 2024 15:05:31 +0200 Subject: [PATCH 03/27] refactor: chain extension tests --- Cargo.lock | 8 + pop-api/Cargo.toml | 2 +- .../.gitignore | 0 .../Cargo.toml | 2 +- pop-api/examples/fungibles/expanded.rs | 2766 +++++++++++++++++ pop-api/examples/fungibles/lib.rs | 176 ++ pop-api/examples/trust_backed_assets/lib.rs | 74 - pop-api/src/lib.rs | 15 +- pop-api/src/v0/assets/fungibles.rs | 554 ++++ pop-api/src/v0/assets/mod.rs | 2 +- pop-api/src/v0/assets/trust_backed.rs | 519 ---- pop-api/src/v0/balances.rs | 2 +- pop-api/src/v0/contracts.rs | 156 + pop-api/src/v0/mod.rs | 3 +- primitives/Cargo.toml | 14 +- primitives/src/lib.rs | 12 + primitives/src/storage_keys.rs | 14 +- runtime/devnet/Cargo.toml | 2 +- runtime/devnet/src/config/assets.rs | 8 +- runtime/devnet/src/config/mod.rs | 2 +- runtime/devnet/src/config/proxy.rs | 40 +- runtime/devnet/src/extensions.rs | 1018 ------ runtime/devnet/src/extensions/mod.rs | 896 ++++++ .../src/extensions/tests/local_fungibles.rs | 302 ++ runtime/devnet/src/extensions/tests/mod.rs | 86 + runtime/devnet/src/lib.rs | 62 +- runtime/testnet/Cargo.toml | 2 +- runtime/testnet/src/config/assets.rs | 8 +- runtime/testnet/src/config/proxy.rs | 40 +- runtime/testnet/src/extensions.rs | 138 +- runtime/testnet/src/lib.rs | 99 +- 31 files changed, 5116 insertions(+), 1906 deletions(-) rename pop-api/examples/{trust_backed_assets => fungibles}/.gitignore (100%) rename pop-api/examples/{trust_backed_assets => fungibles}/Cargo.toml (93%) create mode 100644 pop-api/examples/fungibles/expanded.rs create mode 100755 pop-api/examples/fungibles/lib.rs delete mode 100755 pop-api/examples/trust_backed_assets/lib.rs create mode 100644 pop-api/src/v0/assets/fungibles.rs delete mode 100644 pop-api/src/v0/assets/trust_backed.rs create mode 100644 pop-api/src/v0/contracts.rs delete mode 100644 runtime/devnet/src/extensions.rs create mode 100644 runtime/devnet/src/extensions/mod.rs create mode 100644 runtime/devnet/src/extensions/tests/local_fungibles.rs create mode 100644 runtime/devnet/src/extensions/tests/mod.rs diff --git a/Cargo.lock b/Cargo.lock index e43d2b18..17cc70e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9673,6 +9673,8 @@ version = "0.0.0" dependencies = [ "bounded-collections 0.1.9", "parity-scale-codec", + "scale-decode", + "scale-encode", "scale-info", ] @@ -9720,16 +9722,19 @@ dependencies = [ "pallet-collator-selection", "pallet-contracts", "pallet-message-queue", + "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", "pallet-nfts-runtime-api", "pallet-preimage", + "pallet-proxy", "pallet-scheduler", "pallet-session", "pallet-sudo", "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", + "pallet-utility", "pallet-xcm", "parachains-common", "parity-scale-codec", @@ -9790,16 +9795,19 @@ dependencies = [ "pallet-collator-selection", "pallet-contracts", "pallet-message-queue", + "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", "pallet-nfts-runtime-api", "pallet-preimage", + "pallet-proxy", "pallet-scheduler", "pallet-session", "pallet-sudo", "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", + "pallet-utility", "pallet-xcm", "parachains-common", "parity-scale-codec", diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index 0fa1119c..80818235 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -13,7 +13,7 @@ scale-info = { version = "2.6", default-features = false, features = ["derive"] sp-io = { version = "23.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } sp-runtime = { version = "24.0", default-features = false } -pop-primitives = { path = "../primitives", default-features = false } +pop-primitives = { path = "../primitives", features = ["devnet"], default-features = false } [lib] name = "pop_api" diff --git a/pop-api/examples/trust_backed_assets/.gitignore b/pop-api/examples/fungibles/.gitignore similarity index 100% rename from pop-api/examples/trust_backed_assets/.gitignore rename to pop-api/examples/fungibles/.gitignore diff --git a/pop-api/examples/trust_backed_assets/Cargo.toml b/pop-api/examples/fungibles/Cargo.toml similarity index 93% rename from pop-api/examples/trust_backed_assets/Cargo.toml rename to pop-api/examples/fungibles/Cargo.toml index 3c3716fc..1fe32d6d 100755 --- a/pop-api/examples/trust_backed_assets/Cargo.toml +++ b/pop-api/examples/fungibles/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "pop_api_trust_backed_assets_example" +name = "fungibles" version = "0.1.0" authors = ["[your_name] <[your_email]>"] edition = "2021" diff --git a/pop-api/examples/fungibles/expanded.rs b/pop-api/examples/fungibles/expanded.rs new file mode 100644 index 00000000..c73cdeb7 --- /dev/null +++ b/pop-api/examples/fungibles/expanded.rs @@ -0,0 +1,2766 @@ +#![feature(prelude_import)] +#[prelude_import] +use std::prelude::rust_2021::*; +#[macro_use] +extern crate std; +use pop_api::{ + primitives::{AccountId as AccountId32, AssetId}, + assets::fungibles::*, +}; +pub enum FungiblesError { + /// Not enough balance to fulfill a request is available. + InsufficientBalance, + /// Not enough allowance to fulfill a request is available. + InsufficientAllowance, + /// The asset status is not the expected status. + IncorrectStatus, + /// The asset ID is already taken. + InUse, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + /// Recipient's address is zero. + ZeroRecipientAddress, + /// Sender's address is zero. + ZeroSenderAddress, +} +#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] +const _: () = { + impl ::scale_info::TypeInfo for FungiblesError { + type Identity = Self; + fn type_info() -> ::scale_info::Type { + ::scale_info::Type::builder() + .path( + ::scale_info::Path::new_with_replace( + "FungiblesError", + "fungibles", + &[], + ), + ) + .type_params(::alloc::vec::Vec::new()) + .variant( + ::scale_info::build::Variants::new() + .variant( + "InsufficientBalance", + |v| { + v + .index(0usize as ::core::primitive::u8) + .docs( + &["Not enough balance to fulfill a request is available."], + ) + }, + ) + .variant( + "InsufficientAllowance", + |v| { + v + .index(1usize as ::core::primitive::u8) + .docs( + &["Not enough allowance to fulfill a request is available."], + ) + }, + ) + .variant( + "IncorrectStatus", + |v| { + v + .index(2usize as ::core::primitive::u8) + .docs(&["The asset status is not the expected status."]) + }, + ) + .variant( + "InUse", + |v| { + v + .index(3usize as ::core::primitive::u8) + .docs(&["The asset ID is already taken."]) + }, + ) + .variant( + "MinBalanceZero", + |v| { + v + .index(4usize as ::core::primitive::u8) + .docs(&["Minimum balance should be non-zero."]) + }, + ) + .variant( + "NoPermission", + |v| { + v + .index(5usize as ::core::primitive::u8) + .docs( + &[ + "The signing account has no permission to do the operation.", + ], + ) + }, + ) + .variant( + "Unknown", + |v| { + v + .index(6usize as ::core::primitive::u8) + .docs(&["The given asset ID is unknown."]) + }, + ) + .variant( + "ZeroRecipientAddress", + |v| { + v + .index(7usize as ::core::primitive::u8) + .docs(&["Recipient's address is zero."]) + }, + ) + .variant( + "ZeroSenderAddress", + |v| { + v + .index(8usize as ::core::primitive::u8) + .docs(&["Sender's address is zero."]) + }, + ), + ) + } + } +}; +#[automatically_derived] +impl ::core::fmt::Debug for FungiblesError { + #[inline] + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + ::core::fmt::Formatter::write_str( + f, + match self { + FungiblesError::InsufficientBalance => "InsufficientBalance", + FungiblesError::InsufficientAllowance => "InsufficientAllowance", + FungiblesError::IncorrectStatus => "IncorrectStatus", + FungiblesError::InUse => "InUse", + FungiblesError::MinBalanceZero => "MinBalanceZero", + FungiblesError::NoPermission => "NoPermission", + FungiblesError::Unknown => "Unknown", + FungiblesError::ZeroRecipientAddress => "ZeroRecipientAddress", + FungiblesError::ZeroSenderAddress => "ZeroSenderAddress", + }, + ) + } +} +#[automatically_derived] +impl ::core::marker::Copy for FungiblesError {} +#[automatically_derived] +impl ::core::clone::Clone for FungiblesError { + #[inline] + fn clone(&self) -> FungiblesError { + *self + } +} +#[automatically_derived] +impl ::core::marker::StructuralPartialEq for FungiblesError {} +#[automatically_derived] +impl ::core::cmp::PartialEq for FungiblesError { + #[inline] + fn eq(&self, other: &FungiblesError) -> bool { + let __self_tag = ::core::intrinsics::discriminant_value(self); + let __arg1_tag = ::core::intrinsics::discriminant_value(other); + __self_tag == __arg1_tag + } +} +#[automatically_derived] +impl ::core::cmp::Eq for FungiblesError { + #[inline] + #[doc(hidden)] + #[coverage(off)] + fn assert_receiver_is_total_eq(&self) -> () {} +} +#[allow(deprecated)] +const _: () = { + #[automatically_derived] + impl ::scale::Encode for FungiblesError { + fn size_hint(&self) -> usize { + 1_usize + + match *self { + FungiblesError::InsufficientBalance => 0_usize, + FungiblesError::InsufficientAllowance => 0_usize, + FungiblesError::IncorrectStatus => 0_usize, + FungiblesError::InUse => 0_usize, + FungiblesError::MinBalanceZero => 0_usize, + FungiblesError::NoPermission => 0_usize, + FungiblesError::Unknown => 0_usize, + FungiblesError::ZeroRecipientAddress => 0_usize, + FungiblesError::ZeroSenderAddress => 0_usize, + _ => 0_usize, + } + } + fn encode_to<__CodecOutputEdqy: ::scale::Output + ?::core::marker::Sized>( + &self, + __codec_dest_edqy: &mut __CodecOutputEdqy, + ) { + match *self { + FungiblesError::InsufficientBalance => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(0usize as ::core::primitive::u8); + } + FungiblesError::InsufficientAllowance => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(1usize as ::core::primitive::u8); + } + FungiblesError::IncorrectStatus => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(2usize as ::core::primitive::u8); + } + FungiblesError::InUse => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(3usize as ::core::primitive::u8); + } + FungiblesError::MinBalanceZero => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(4usize as ::core::primitive::u8); + } + FungiblesError::NoPermission => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(5usize as ::core::primitive::u8); + } + FungiblesError::Unknown => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(6usize as ::core::primitive::u8); + } + FungiblesError::ZeroRecipientAddress => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(7usize as ::core::primitive::u8); + } + FungiblesError::ZeroSenderAddress => { + #[allow(clippy::unnecessary_cast)] + __codec_dest_edqy.push_byte(8usize as ::core::primitive::u8); + } + _ => {} + } + } + } + #[automatically_derived] + impl ::scale::EncodeLike for FungiblesError {} +}; +#[allow(deprecated)] +const _: () = { + #[automatically_derived] + impl ::scale::Decode for FungiblesError { + fn decode<__CodecInputEdqy: ::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + match __codec_input_edqy + .read_byte() + .map_err(|e| { + e + .chain( + "Could not decode `FungiblesError`, failed to read variant byte", + ) + })? + { + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 0usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::InsufficientBalance) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 1usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::InsufficientAllowance) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 2usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::IncorrectStatus) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 3usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::InUse) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 4usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::MinBalanceZero) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 5usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::NoPermission) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 6usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::Unknown) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 7usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::ZeroRecipientAddress) + })(); + } + #[allow(clippy::unnecessary_cast)] + __codec_x_edqy if __codec_x_edqy == 8usize as ::core::primitive::u8 => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Ok(FungiblesError::ZeroSenderAddress) + })(); + } + _ => { + #[allow(clippy::redundant_closure_call)] + return (move || { + ::core::result::Result::Err( + <_ as ::core::convert::Into< + _, + >>::into( + "Could not decode `FungiblesError`, variant doesn't exist", + ), + ) + })(); + } + } + } + } +}; +impl From for FungiblesError { + fn from(error: Error) -> Self { + match error { + Error::InUse => FungiblesError::InUse, + Error::MinBalanceZero => FungiblesError::MinBalanceZero, + Error::Unknown => FungiblesError::Unknown, + _ => ::core::panicking::panic("not yet implemented"), + } + } +} +/// The fungibles result type. +pub type Result = core::result::Result; +mod fungibles { + impl ::ink::env::ContractEnv for Fungibles { + type Env = pop_api::Environment; + } + type Environment = ::Env; + type AccountId = <::Env as ::ink::env::Environment>::AccountId; + type Balance = <::Env as ::ink::env::Environment>::Balance; + type Hash = <::Env as ::ink::env::Environment>::Hash; + type Timestamp = <::Env as ::ink::env::Environment>::Timestamp; + type BlockNumber = <::Env as ::ink::env::Environment>::BlockNumber; + type ChainExtension = <::Env as ::ink::env::Environment>::ChainExtension; + const MAX_EVENT_TOPICS: usize = <::Env as ::ink::env::Environment>::MAX_EVENT_TOPICS; + const _: () = { + struct Check { + salt: (), + } + }; + #[scale_info(crate = ::ink::scale_info)] + #[cfg(not(feature = "__ink_dylint_Storage"))] + pub struct Fungibles {} + const _: () = { + impl< + __ink_generic_salt: ::ink::storage::traits::StorageKey, + > ::ink::storage::traits::StorableHint<__ink_generic_salt> for Fungibles { + type Type = Fungibles; + type PreferredKey = ::ink::storage::traits::AutoKey; + } + }; + const _: () = { + impl ::ink::storage::traits::StorageKey for Fungibles { + const KEY: ::ink::primitives::Key = <() as ::ink::storage::traits::StorageKey>::KEY; + } + }; + const _: () = { + impl ::ink::storage::traits::Storable for Fungibles { + #[inline(always)] + #[allow(non_camel_case_types)] + fn decode<__ink_I: ::ink::scale::Input>( + __input: &mut __ink_I, + ) -> ::core::result::Result { + ::core::result::Result::Ok(Fungibles {}) + } + #[inline(always)] + #[allow(non_camel_case_types)] + fn encode<__ink_O: ::ink::scale::Output + ?::core::marker::Sized>( + &self, + __dest: &mut __ink_O, + ) { + match self { + Fungibles {} => {} + } + } + #[inline(always)] + #[allow(non_camel_case_types)] + fn encoded_size(&self) -> ::core::primitive::usize { + match self { + Fungibles {} => ::core::primitive::usize::MIN, + } + } + } + }; + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const _: () = { + impl ::ink::scale_info::TypeInfo for Fungibles { + type Identity = Self; + fn type_info() -> ::ink::scale_info::Type { + ::ink::scale_info::Type::builder() + .path( + ::ink::scale_info::Path::new_with_replace( + "Fungibles", + "fungibles::fungibles", + &[], + ), + ) + .type_params(::alloc::vec::Vec::new()) + .composite(::ink::scale_info::build::Fields::named()) + } + } + }; + const _: () = { + impl ::ink::storage::traits::StorageLayout for Fungibles { + fn layout( + __key: &::ink::primitives::Key, + ) -> ::ink::metadata::layout::Layout { + ::ink::metadata::layout::Layout::Struct( + ::ink::metadata::layout::StructLayout::new("Fungibles", []), + ) + } + } + }; + #[automatically_derived] + impl ::core::default::Default for Fungibles { + #[inline] + fn default() -> Fungibles { + Fungibles {} + } + } + const _: () = { + impl ::ink::reflect::ContractName for Fungibles { + const NAME: &'static str = "Fungibles"; + } + }; + const _: () = { + impl<'a> ::ink::codegen::Env for &'a Fungibles { + type EnvAccess = ::ink::EnvAccess< + 'a, + ::Env, + >; + fn env(self) -> Self::EnvAccess { + <::EnvAccess as ::core::default::Default>::default() + } + } + impl<'a> ::ink::codegen::StaticEnv for Fungibles { + type EnvAccess = ::ink::EnvAccess< + 'static, + ::Env, + >; + fn env() -> Self::EnvAccess { + <::EnvAccess as ::core::default::Default>::default() + } + } + }; + const _: () = { + #[allow(unused_imports)] + use ::ink::codegen::{Env as _, StaticEnv as _}; + }; + impl ::ink::reflect::DispatchableConstructorInfo<0x9BAE9D5E_u32> for Fungibles { + type Input = (); + type Output = Self; + type Storage = Fungibles; + type Error = <::ink::reflect::ConstructorOutputValue< + Self, + > as ::ink::reflect::ConstructorOutput>::Error; + const IS_RESULT: ::core::primitive::bool = <::ink::reflect::ConstructorOutputValue< + Self, + > as ::ink::reflect::ConstructorOutput>::IS_RESULT; + const CALLABLE: fn(Self::Input) -> Self::Output = |_| { Fungibles::new() }; + const PAYABLE: ::core::primitive::bool = true; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0x9B_u8, + 0xAE_u8, + 0x9D_u8, + 0x5E_u8, + ]; + const LABEL: &'static ::core::primitive::str = "new"; + } + impl ::ink::reflect::DispatchableMessageInfo<0xDB6375A8_u32> for Fungibles { + type Input = AssetId; + type Output = Result; + type Storage = Fungibles; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + __ink_binding_0| + { Fungibles::total_supply(storage, __ink_binding_0) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0xDB_u8, + 0x63_u8, + 0x75_u8, + 0xA8_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "total_supply"; + } + impl ::ink::reflect::DispatchableMessageInfo<0x0F755A56_u32> for Fungibles { + type Input = (AssetId, AccountId32); + type Output = Result; + type Storage = Fungibles; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + (__ink_binding_0, __ink_binding_1)| + { Fungibles::balance_of(storage, __ink_binding_0, __ink_binding_1) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0x0F_u8, + 0x75_u8, + 0x5A_u8, + 0x56_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "balance_of"; + } + impl ::ink::reflect::DispatchableMessageInfo<0x6A00165E_u32> for Fungibles { + type Input = (AssetId, AccountId32, AccountId32); + type Output = Result; + type Storage = Fungibles; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + (__ink_binding_0, __ink_binding_1, __ink_binding_2)| + { + Fungibles::allowance( + storage, + __ink_binding_0, + __ink_binding_1, + __ink_binding_2, + ) + }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0x6A_u8, + 0x00_u8, + 0x16_u8, + 0x5E_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "allowance"; + } + impl ::ink::reflect::DispatchableMessageInfo<0xAA6B65DB_u32> for Fungibles { + type Input = AssetId; + type Output = Result; + type Storage = Fungibles; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + __ink_binding_0| + { Fungibles::asset_exists(storage, __ink_binding_0) }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0xAA_u8, + 0x6B_u8, + 0x65_u8, + 0xDB_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "asset_exists"; + } + impl ::ink::reflect::DispatchableMessageInfo<0x1F8E8E22_u32> for Fungibles { + type Input = (u32, AccountId32, Balance); + type Output = Result<()>; + type Storage = Fungibles; + const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | + storage, + (__ink_binding_0, __ink_binding_1, __ink_binding_2)| + { + Fungibles::mint_asset( + storage, + __ink_binding_0, + __ink_binding_1, + __ink_binding_2, + ) + }; + const SELECTOR: [::core::primitive::u8; 4usize] = [ + 0x1F_u8, + 0x8E_u8, + 0x8E_u8, + 0x22_u8, + ]; + const PAYABLE: ::core::primitive::bool = false; + const MUTATES: ::core::primitive::bool = false; + const LABEL: &'static ::core::primitive::str = "mint_asset"; + } + const _: () = { + #[allow(non_camel_case_types)] + pub enum __ink_ConstructorDecoder { + Constructor0( + >::Input, + ), + } + impl ::ink::reflect::DecodeDispatch for __ink_ConstructorDecoder { + fn decode_dispatch( + input: &mut I, + ) -> ::core::result::Result + where + I: ::ink::scale::Input, + { + const CONSTRUCTOR_0: [::core::primitive::u8; 4usize] = >::SELECTOR; + match <[::core::primitive::u8; 4usize] as ::ink::scale::Decode>::decode( + input, + ) + .map_err(|_| ::ink::reflect::DispatchError::InvalidSelector)? + { + CONSTRUCTOR_0 => { + ::core::result::Result::Ok( + Self::Constructor0( + <>::Input as ::ink::scale::Decode>::decode(input) + .map_err(|_| { + ::ink::reflect::DispatchError::InvalidParameters + })?, + ), + ) + } + _invalid => { + ::core::result::Result::Err( + ::ink::reflect::DispatchError::UnknownSelector, + ) + } + } + } + } + impl ::ink::scale::Decode for __ink_ConstructorDecoder { + fn decode( + input: &mut I, + ) -> ::core::result::Result + where + I: ::ink::scale::Input, + { + ::decode_dispatch(input) + .map_err(::core::convert::Into::into) + } + } + impl ::ink::reflect::ExecuteDispatchable for __ink_ConstructorDecoder { + #[allow(clippy::nonminimal_bool)] + fn execute_dispatchable( + self, + ) -> ::core::result::Result<(), ::ink::reflect::DispatchError> { + match self { + Self::Constructor0(input) => { + if { + false + || { + let constructor_0 = false; + let constructor_0 = >::PAYABLE; + constructor_0 + } + } + && !>::PAYABLE + { + ::ink::codegen::deny_payment::< + ::Env, + >()?; + } + let result: >::Output = >::CALLABLE(input); + let output_value = ::ink::reflect::ConstructorOutputValue::new( + result, + ); + let output_result = <::ink::reflect::ConstructorOutputValue< + >::Output, + > as ::ink::reflect::ConstructorOutput< + Fungibles, + >>::as_result(&output_value); + if let ::core::result::Result::Ok(contract) = output_result + .as_ref() + { + ::ink::env::set_contract_storage::< + ::ink::primitives::Key, + Fungibles, + >( + &::KEY, + contract, + ); + } + let mut flag = ::ink::env::ReturnFlags::empty(); + if output_result.is_err() { + flag = ::ink::env::ReturnFlags::REVERT; + } + ::ink::env::return_value::< + ::ink::ConstructorResult< + ::core::result::Result< + (), + &<::ink::reflect::ConstructorOutputValue< + >::Output, + > as ::ink::reflect::ConstructorOutput>::Error, + >, + >, + >( + flag, + &::ink::ConstructorResult::Ok(output_result.map(|_| ())), + ); + } + } + } + } + impl ::ink::reflect::ContractConstructorDecoder for Fungibles { + type Type = __ink_ConstructorDecoder; + } + }; + const _: () = { + #[allow(non_camel_case_types)] + pub enum __ink_MessageDecoder { + Message0( + >::Input, + ), + Message1( + >::Input, + ), + Message2( + >::Input, + ), + Message3( + >::Input, + ), + Message4( + >::Input, + ), + } + impl ::ink::reflect::DecodeDispatch for __ink_MessageDecoder { + fn decode_dispatch( + input: &mut I, + ) -> ::core::result::Result + where + I: ::ink::scale::Input, + { + const MESSAGE_0: [::core::primitive::u8; 4usize] = >::SELECTOR; + const MESSAGE_1: [::core::primitive::u8; 4usize] = >::SELECTOR; + const MESSAGE_2: [::core::primitive::u8; 4usize] = >::SELECTOR; + const MESSAGE_3: [::core::primitive::u8; 4usize] = >::SELECTOR; + const MESSAGE_4: [::core::primitive::u8; 4usize] = >::SELECTOR; + match <[::core::primitive::u8; 4usize] as ::ink::scale::Decode>::decode( + input, + ) + .map_err(|_| ::ink::reflect::DispatchError::InvalidSelector)? + { + MESSAGE_0 => { + ::core::result::Result::Ok( + Self::Message0( + <>::Input as ::ink::scale::Decode>::decode(input) + .map_err(|_| { + ::ink::reflect::DispatchError::InvalidParameters + })?, + ), + ) + } + MESSAGE_1 => { + ::core::result::Result::Ok( + Self::Message1( + <>::Input as ::ink::scale::Decode>::decode(input) + .map_err(|_| { + ::ink::reflect::DispatchError::InvalidParameters + })?, + ), + ) + } + MESSAGE_2 => { + ::core::result::Result::Ok( + Self::Message2( + <>::Input as ::ink::scale::Decode>::decode(input) + .map_err(|_| { + ::ink::reflect::DispatchError::InvalidParameters + })?, + ), + ) + } + MESSAGE_3 => { + ::core::result::Result::Ok( + Self::Message3( + <>::Input as ::ink::scale::Decode>::decode(input) + .map_err(|_| { + ::ink::reflect::DispatchError::InvalidParameters + })?, + ), + ) + } + MESSAGE_4 => { + ::core::result::Result::Ok( + Self::Message4( + <>::Input as ::ink::scale::Decode>::decode(input) + .map_err(|_| { + ::ink::reflect::DispatchError::InvalidParameters + })?, + ), + ) + } + _invalid => { + ::core::result::Result::Err( + ::ink::reflect::DispatchError::UnknownSelector, + ) + } + } + } + } + impl ::ink::scale::Decode for __ink_MessageDecoder { + fn decode( + input: &mut I, + ) -> ::core::result::Result + where + I: ::ink::scale::Input, + { + ::decode_dispatch(input) + .map_err(::core::convert::Into::into) + } + } + fn push_contract(contract: ::core::mem::ManuallyDrop, mutates: bool) { + if mutates { + ::ink::env::set_contract_storage::< + ::ink::primitives::Key, + Fungibles, + >(&::KEY, &contract); + } + } + impl ::ink::reflect::ExecuteDispatchable for __ink_MessageDecoder { + #[allow(clippy::nonminimal_bool, clippy::let_unit_value)] + fn execute_dispatchable( + self, + ) -> ::core::result::Result<(), ::ink::reflect::DispatchError> { + let key = ::KEY; + let mut contract: ::core::mem::ManuallyDrop = ::core::mem::ManuallyDrop::new( + match ::ink::env::get_contract_storage(&key) { + ::core::result::Result::Ok( + ::core::option::Option::Some(value), + ) => value, + ::core::result::Result::Ok(::core::option::Option::None) => { + ::core::panicking::panic_fmt( + format_args!("storage entry was empty"), + ); + } + ::core::result::Result::Err(_) => { + ::core::panicking::panic_fmt( + format_args!("could not properly decode storage entry"), + ); + } + }, + ); + match self { + Self::Message0(input) => { + if { + false + || { + let message_0 = false; + let message_0 = >::PAYABLE; + message_0 + } + || { + let message_1 = false; + let message_1 = >::PAYABLE; + message_1 + } + || { + let message_2 = false; + let message_2 = >::PAYABLE; + message_2 + } + || { + let message_3 = false; + let message_3 = >::PAYABLE; + message_3 + } + || { + let message_4 = false; + let message_4 = >::PAYABLE; + message_4 + } + } + && !>::PAYABLE + { + ::ink::codegen::deny_payment::< + ::Env, + >()?; + } + let result: >::Output = >::CALLABLE(&mut contract, input); + let is_reverted = { + #[allow(unused_imports)] + use ::ink::result_info::IsResultTypeFallback as _; + ::ink::result_info::IsResultType::< + >::Output, + >::VALUE + } + && { + #[allow(unused_imports)] + use ::ink::result_info::IsResultErrFallback as _; + ::ink::result_info::IsResultErr(&result).value() + }; + let mut flag = ::ink::env::ReturnFlags::REVERT; + if !is_reverted { + flag = ::ink::env::ReturnFlags::empty(); + push_contract( + contract, + >::MUTATES, + ); + } + ::ink::env::return_value::< + ::ink::MessageResult< + >::Output, + >, + >(flag, &::ink::MessageResult::Ok(result)) + } + Self::Message1(input) => { + if { + false + || { + let message_0 = false; + let message_0 = >::PAYABLE; + message_0 + } + || { + let message_1 = false; + let message_1 = >::PAYABLE; + message_1 + } + || { + let message_2 = false; + let message_2 = >::PAYABLE; + message_2 + } + || { + let message_3 = false; + let message_3 = >::PAYABLE; + message_3 + } + || { + let message_4 = false; + let message_4 = >::PAYABLE; + message_4 + } + } + && !>::PAYABLE + { + ::ink::codegen::deny_payment::< + ::Env, + >()?; + } + let result: >::Output = >::CALLABLE(&mut contract, input); + let is_reverted = { + #[allow(unused_imports)] + use ::ink::result_info::IsResultTypeFallback as _; + ::ink::result_info::IsResultType::< + >::Output, + >::VALUE + } + && { + #[allow(unused_imports)] + use ::ink::result_info::IsResultErrFallback as _; + ::ink::result_info::IsResultErr(&result).value() + }; + let mut flag = ::ink::env::ReturnFlags::REVERT; + if !is_reverted { + flag = ::ink::env::ReturnFlags::empty(); + push_contract( + contract, + >::MUTATES, + ); + } + ::ink::env::return_value::< + ::ink::MessageResult< + >::Output, + >, + >(flag, &::ink::MessageResult::Ok(result)) + } + Self::Message2(input) => { + if { + false + || { + let message_0 = false; + let message_0 = >::PAYABLE; + message_0 + } + || { + let message_1 = false; + let message_1 = >::PAYABLE; + message_1 + } + || { + let message_2 = false; + let message_2 = >::PAYABLE; + message_2 + } + || { + let message_3 = false; + let message_3 = >::PAYABLE; + message_3 + } + || { + let message_4 = false; + let message_4 = >::PAYABLE; + message_4 + } + } + && !>::PAYABLE + { + ::ink::codegen::deny_payment::< + ::Env, + >()?; + } + let result: >::Output = >::CALLABLE(&mut contract, input); + let is_reverted = { + #[allow(unused_imports)] + use ::ink::result_info::IsResultTypeFallback as _; + ::ink::result_info::IsResultType::< + >::Output, + >::VALUE + } + && { + #[allow(unused_imports)] + use ::ink::result_info::IsResultErrFallback as _; + ::ink::result_info::IsResultErr(&result).value() + }; + let mut flag = ::ink::env::ReturnFlags::REVERT; + if !is_reverted { + flag = ::ink::env::ReturnFlags::empty(); + push_contract( + contract, + >::MUTATES, + ); + } + ::ink::env::return_value::< + ::ink::MessageResult< + >::Output, + >, + >(flag, &::ink::MessageResult::Ok(result)) + } + Self::Message3(input) => { + if { + false + || { + let message_0 = false; + let message_0 = >::PAYABLE; + message_0 + } + || { + let message_1 = false; + let message_1 = >::PAYABLE; + message_1 + } + || { + let message_2 = false; + let message_2 = >::PAYABLE; + message_2 + } + || { + let message_3 = false; + let message_3 = >::PAYABLE; + message_3 + } + || { + let message_4 = false; + let message_4 = >::PAYABLE; + message_4 + } + } + && !>::PAYABLE + { + ::ink::codegen::deny_payment::< + ::Env, + >()?; + } + let result: >::Output = >::CALLABLE(&mut contract, input); + let is_reverted = { + #[allow(unused_imports)] + use ::ink::result_info::IsResultTypeFallback as _; + ::ink::result_info::IsResultType::< + >::Output, + >::VALUE + } + && { + #[allow(unused_imports)] + use ::ink::result_info::IsResultErrFallback as _; + ::ink::result_info::IsResultErr(&result).value() + }; + let mut flag = ::ink::env::ReturnFlags::REVERT; + if !is_reverted { + flag = ::ink::env::ReturnFlags::empty(); + push_contract( + contract, + >::MUTATES, + ); + } + ::ink::env::return_value::< + ::ink::MessageResult< + >::Output, + >, + >(flag, &::ink::MessageResult::Ok(result)) + } + Self::Message4(input) => { + if { + false + || { + let message_0 = false; + let message_0 = >::PAYABLE; + message_0 + } + || { + let message_1 = false; + let message_1 = >::PAYABLE; + message_1 + } + || { + let message_2 = false; + let message_2 = >::PAYABLE; + message_2 + } + || { + let message_3 = false; + let message_3 = >::PAYABLE; + message_3 + } + || { + let message_4 = false; + let message_4 = >::PAYABLE; + message_4 + } + } + && !>::PAYABLE + { + ::ink::codegen::deny_payment::< + ::Env, + >()?; + } + let result: >::Output = >::CALLABLE(&mut contract, input); + let is_reverted = { + #[allow(unused_imports)] + use ::ink::result_info::IsResultTypeFallback as _; + ::ink::result_info::IsResultType::< + >::Output, + >::VALUE + } + && { + #[allow(unused_imports)] + use ::ink::result_info::IsResultErrFallback as _; + ::ink::result_info::IsResultErr(&result).value() + }; + let mut flag = ::ink::env::ReturnFlags::REVERT; + if !is_reverted { + flag = ::ink::env::ReturnFlags::empty(); + push_contract( + contract, + >::MUTATES, + ); + } + ::ink::env::return_value::< + ::ink::MessageResult< + >::Output, + >, + >(flag, &::ink::MessageResult::Ok(result)) + } + }; + } + } + impl ::ink::reflect::ContractMessageDecoder for Fungibles { + type Type = __ink_MessageDecoder; + } + }; + const _: () = { + use ::ink::codegen::{Env as _, StaticEnv as _}; + const _: ::ink::codegen::utils::IsSameType = ::ink::codegen::utils::IsSameType::< + Fungibles, + >::new(); + impl Fungibles { + #[cfg(not(feature = "__ink_dylint_Constructor"))] + pub fn new() -> Self { + ::ink_env::debug_message( + &{ + let res = ::alloc::fmt::format( + format_args!( + "{0}\n", + { + let res = ::alloc::fmt::format( + format_args!("PopApiAssetsExample::new"), + ); + res + }, + ), + ); + res + }, + ); + Default::default() + } + pub fn total_supply(&self, id: AssetId) -> Result { + total_supply(id).map_err(From::from) + } + pub fn balance_of( + &self, + id: AssetId, + owner: AccountId32, + ) -> Result { + balance_of(id, owner).map_err(From::from) + } + pub fn allowance( + &self, + id: AssetId, + owner: AccountId32, + spender: AccountId32, + ) -> Result { + allowance(id, owner, spender).map_err(From::from) + } + pub fn asset_exists(&self, id: AssetId) -> Result { + asset_exists(id).map_err(From::from) + } + pub fn mint_asset( + &self, + id: u32, + beneficiary: AccountId32, + amount: Balance, + ) -> Result<()> { + ::ink_env::debug_message( + &{ + let res = ::alloc::fmt::format( + format_args!( + "{0}\n", + { + let res = ::alloc::fmt::format( + format_args!( + "PopApiAssetsExample::mint_asset_through_runtime: id: {0:?} beneficiary: {1:?} amount: {2:?}", + id, + beneficiary, + amount, + ), + ); + res + }, + ), + ); + res + }, + ); + let result = mint(id, beneficiary, amount)?; + ::ink_env::debug_message( + &{ + let res = ::alloc::fmt::format( + format_args!( + "{0}\n", + { + let res = ::alloc::fmt::format( + format_args!("Result: {0:?}", result), + ); + res + }, + ), + ); + res + }, + ); + Ok(()) + } + } + const _: () = { + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchOutput>, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchOutput>, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchOutput>, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchOutput>, + >(); + ::ink::codegen::utils::consume_type::<::ink::codegen::DispatchInput>(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchInput, + >(); + ::ink::codegen::utils::consume_type::< + ::ink::codegen::DispatchOutput>, + >(); + }; + }; + const _: () = { + #[codec(crate = ::ink::scale)] + #[scale_info(crate = ::ink::scale_info)] + /// The ink! smart contract's call builder. + /// + /// Implements the underlying on-chain calling of the ink! smart contract + /// messages and trait implementations in a type safe way. + #[repr(transparent)] + pub struct CallBuilder { + account_id: AccountId, + } + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const _: () = { + impl ::ink::scale_info::TypeInfo for CallBuilder { + type Identity = Self; + fn type_info() -> ::ink::scale_info::Type { + ::ink::scale_info::Type::builder() + .path( + ::ink::scale_info::Path::new_with_replace( + "CallBuilder", + "fungibles::fungibles", + &[], + ), + ) + .type_params(::alloc::vec::Vec::new()) + .docs( + &[ + "The ink! smart contract's call builder.", + "", + "Implements the underlying on-chain calling of the ink! smart contract", + "messages and trait implementations in a type safe way.", + ], + ) + .composite( + ::ink::scale_info::build::Fields::named() + .field(|f| { + f + .ty::() + .name("account_id") + .type_name("AccountId") + }), + ) + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Decode for CallBuilder { + fn decode<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + ::core::result::Result::Ok(CallBuilder { + account_id: { + let __codec_res_edqy = ::decode( + __codec_input_edqy, + ); + match __codec_res_edqy { + ::core::result::Result::Err(e) => { + return ::core::result::Result::Err( + e.chain("Could not decode `CallBuilder::account_id`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => { + __codec_res_edqy + } + } + }, + }) + } + fn decode_into<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + dst_: &mut ::core::mem::MaybeUninit, + ) -> ::core::result::Result< + ::ink::scale::DecodeFinished, + ::ink::scale::Error, + > { + match ( + &::core::mem::size_of::(), + &::core::mem::size_of::(), + ) { + (left_val, right_val) => { + if !(*left_val == *right_val) { + let kind = ::core::panicking::AssertKind::Eq; + ::core::panicking::assert_failed( + kind, + &*left_val, + &*right_val, + ::core::option::Option::None, + ); + } + } + }; + if !(if ::core::mem::size_of::() > 0 { 1 } else { 0 } + <= 1) + { + ::core::panicking::panic( + "assertion failed: if ::core::mem::size_of::() > 0 { 1 } else { 0 } <= 1", + ) + } + { + let dst_: &mut ::core::mem::MaybeUninit = dst_; + let dst_: &mut ::core::mem::MaybeUninit = unsafe { + &mut *dst_ + .as_mut_ptr() + .cast::<::core::mem::MaybeUninit>() + }; + ::decode_into( + __codec_input_edqy, + dst_, + )?; + } + unsafe { + ::core::result::Result::Ok( + ::ink::scale::DecodeFinished::assert_decoding_finished(), + ) + } + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Encode for CallBuilder { + fn size_hint(&self) -> usize { + ::ink::scale::Encode::size_hint(&&self.account_id) + } + fn encode_to< + __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, + >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { + ::ink::scale::Encode::encode_to(&&self.account_id, __codec_dest_edqy) + } + fn encode( + &self, + ) -> ::ink::scale::alloc::vec::Vec<::core::primitive::u8> { + ::ink::scale::Encode::encode(&&self.account_id) + } + fn using_encoded< + __CodecOutputReturn, + __CodecUsingEncodedCallback: ::core::ops::FnOnce( + &[::core::primitive::u8], + ) -> __CodecOutputReturn, + >(&self, f: __CodecUsingEncodedCallback) -> __CodecOutputReturn { + ::ink::scale::Encode::using_encoded(&&self.account_id, f) + } + } + #[automatically_derived] + impl ::ink::scale::EncodeLike for CallBuilder {} + }; + #[automatically_derived] + impl ::core::fmt::Debug for CallBuilder { + #[inline] + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + ::core::fmt::Formatter::debug_struct_field1_finish( + f, + "CallBuilder", + "account_id", + &&self.account_id, + ) + } + } + #[automatically_derived] + impl ::core::hash::Hash for CallBuilder { + #[inline] + fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () { + ::core::hash::Hash::hash(&self.account_id, state) + } + } + #[automatically_derived] + impl ::core::marker::StructuralPartialEq for CallBuilder {} + #[automatically_derived] + impl ::core::cmp::PartialEq for CallBuilder { + #[inline] + fn eq(&self, other: &CallBuilder) -> bool { + self.account_id == other.account_id + } + } + #[automatically_derived] + impl ::core::cmp::Eq for CallBuilder { + #[inline] + #[doc(hidden)] + #[coverage(off)] + fn assert_receiver_is_total_eq(&self) -> () { + let _: ::core::cmp::AssertParamIsEq; + } + } + #[automatically_derived] + impl ::core::clone::Clone for CallBuilder { + #[inline] + fn clone(&self) -> CallBuilder { + CallBuilder { + account_id: ::core::clone::Clone::clone(&self.account_id), + } + } + } + const _: () = { + impl ::ink::storage::traits::StorageLayout for CallBuilder { + fn layout( + __key: &::ink::primitives::Key, + ) -> ::ink::metadata::layout::Layout { + ::ink::metadata::layout::Layout::Struct( + ::ink::metadata::layout::StructLayout::new( + "CallBuilder", + [ + ::ink::metadata::layout::FieldLayout::new( + "account_id", + ::layout( + __key, + ), + ), + ], + ), + ) + } + } + }; + const _: () = { + impl ::ink::codegen::ContractCallBuilder for Fungibles { + type Type = CallBuilder; + } + impl ::ink::env::ContractEnv for CallBuilder { + type Env = ::Env; + } + }; + impl ::ink::env::call::FromAccountId for CallBuilder { + #[inline] + fn from_account_id(account_id: AccountId) -> Self { + Self { account_id } + } + } + impl ::ink::ToAccountId for CallBuilder { + #[inline] + fn to_account_id(&self) -> AccountId { + ::clone(&self.account_id) + } + } + impl ::core::convert::AsRef for CallBuilder { + fn as_ref(&self) -> &AccountId { + &self.account_id + } + } + impl ::core::convert::AsMut for CallBuilder { + fn as_mut(&mut self) -> &mut AccountId { + &mut self.account_id + } + } + impl CallBuilder { + #[allow(clippy::type_complexity)] + #[inline] + pub fn total_supply( + &self, + __ink_binding_0: AssetId, + ) -> ::ink::env::call::CallBuilder< + Environment, + ::ink::env::call::utils::Set<::ink::env::call::Call>, + ::ink::env::call::utils::Set< + ::ink::env::call::ExecutionInput< + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::EmptyArgumentList, + >, + >, + >, + ::ink::env::call::utils::Set< + ::ink::env::call::utils::ReturnType>, + >, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAccountId::to_account_id(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0xDB_u8, + 0x63_u8, + 0x75_u8, + 0xA8_u8, + ]), + ) + .push_arg(__ink_binding_0), + ) + .returns::>() + } + #[allow(clippy::type_complexity)] + #[inline] + pub fn balance_of( + &self, + __ink_binding_0: AssetId, + __ink_binding_1: AccountId32, + ) -> ::ink::env::call::CallBuilder< + Environment, + ::ink::env::call::utils::Set<::ink::env::call::Call>, + ::ink::env::call::utils::Set< + ::ink::env::call::ExecutionInput< + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::EmptyArgumentList, + >, + >, + >, + >, + ::ink::env::call::utils::Set< + ::ink::env::call::utils::ReturnType>, + >, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAccountId::to_account_id(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x0F_u8, + 0x75_u8, + 0x5A_u8, + 0x56_u8, + ]), + ) + .push_arg(__ink_binding_0) + .push_arg(__ink_binding_1), + ) + .returns::>() + } + #[allow(clippy::type_complexity)] + #[inline] + pub fn allowance( + &self, + __ink_binding_0: AssetId, + __ink_binding_1: AccountId32, + __ink_binding_2: AccountId32, + ) -> ::ink::env::call::CallBuilder< + Environment, + ::ink::env::call::utils::Set<::ink::env::call::Call>, + ::ink::env::call::utils::Set< + ::ink::env::call::ExecutionInput< + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::EmptyArgumentList, + >, + >, + >, + >, + >, + ::ink::env::call::utils::Set< + ::ink::env::call::utils::ReturnType>, + >, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAccountId::to_account_id(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x6A_u8, + 0x00_u8, + 0x16_u8, + 0x5E_u8, + ]), + ) + .push_arg(__ink_binding_0) + .push_arg(__ink_binding_1) + .push_arg(__ink_binding_2), + ) + .returns::>() + } + #[allow(clippy::type_complexity)] + #[inline] + pub fn asset_exists( + &self, + __ink_binding_0: AssetId, + ) -> ::ink::env::call::CallBuilder< + Environment, + ::ink::env::call::utils::Set<::ink::env::call::Call>, + ::ink::env::call::utils::Set< + ::ink::env::call::ExecutionInput< + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::EmptyArgumentList, + >, + >, + >, + ::ink::env::call::utils::Set< + ::ink::env::call::utils::ReturnType>, + >, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAccountId::to_account_id(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0xAA_u8, + 0x6B_u8, + 0x65_u8, + 0xDB_u8, + ]), + ) + .push_arg(__ink_binding_0), + ) + .returns::>() + } + #[allow(clippy::type_complexity)] + #[inline] + pub fn mint_asset( + &self, + __ink_binding_0: u32, + __ink_binding_1: AccountId32, + __ink_binding_2: Balance, + ) -> ::ink::env::call::CallBuilder< + Environment, + ::ink::env::call::utils::Set<::ink::env::call::Call>, + ::ink::env::call::utils::Set< + ::ink::env::call::ExecutionInput< + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::ArgumentList< + ::ink::env::call::utils::Argument, + ::ink::env::call::utils::EmptyArgumentList, + >, + >, + >, + >, + >, + ::ink::env::call::utils::Set< + ::ink::env::call::utils::ReturnType>, + >, + > { + ::ink::env::call::build_call::() + .call(::ink::ToAccountId::to_account_id(self)) + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x1F_u8, + 0x8E_u8, + 0x8E_u8, + 0x22_u8, + ]), + ) + .push_arg(__ink_binding_0) + .push_arg(__ink_binding_1) + .push_arg(__ink_binding_2), + ) + .returns::>() + } + } + }; + #[codec(crate = ::ink::scale)] + #[scale_info(crate = ::ink::scale_info)] + pub struct FungiblesRef { + inner: ::Type, + } + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const _: () = { + impl ::ink::scale_info::TypeInfo for FungiblesRef { + type Identity = Self; + fn type_info() -> ::ink::scale_info::Type { + ::ink::scale_info::Type::builder() + .path( + ::ink::scale_info::Path::new_with_replace( + "FungiblesRef", + "fungibles::fungibles", + &[], + ), + ) + .type_params(::alloc::vec::Vec::new()) + .composite( + ::ink::scale_info::build::Fields::named() + .field(|f| { + f + .ty::< + ::Type, + >() + .name("inner") + .type_name( + "::Type", + ) + }), + ) + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Decode for FungiblesRef { + fn decode<__CodecInputEdqy: ::ink::scale::Input>( + __codec_input_edqy: &mut __CodecInputEdqy, + ) -> ::core::result::Result { + ::core::result::Result::Ok(FungiblesRef { + inner: { + let __codec_res_edqy = <::Type as ::ink::scale::Decode>::decode( + __codec_input_edqy, + ); + match __codec_res_edqy { + ::core::result::Result::Err(e) => { + return ::core::result::Result::Err( + e.chain("Could not decode `FungiblesRef::inner`"), + ); + } + ::core::result::Result::Ok(__codec_res_edqy) => { + __codec_res_edqy + } + } + }, + }) + } + } + }; + #[allow(deprecated)] + const _: () = { + #[automatically_derived] + impl ::ink::scale::Encode for FungiblesRef { + fn size_hint(&self) -> usize { + ::ink::scale::Encode::size_hint(&&self.inner) + } + fn encode_to< + __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, + >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { + ::ink::scale::Encode::encode_to(&&self.inner, __codec_dest_edqy) + } + fn encode(&self) -> ::ink::scale::alloc::vec::Vec<::core::primitive::u8> { + ::ink::scale::Encode::encode(&&self.inner) + } + fn using_encoded< + __CodecOutputReturn, + __CodecUsingEncodedCallback: ::core::ops::FnOnce( + &[::core::primitive::u8], + ) -> __CodecOutputReturn, + >(&self, f: __CodecUsingEncodedCallback) -> __CodecOutputReturn { + ::ink::scale::Encode::using_encoded(&&self.inner, f) + } + } + #[automatically_derived] + impl ::ink::scale::EncodeLike for FungiblesRef {} + }; + #[automatically_derived] + impl ::core::fmt::Debug for FungiblesRef { + #[inline] + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + ::core::fmt::Formatter::debug_struct_field1_finish( + f, + "FungiblesRef", + "inner", + &&self.inner, + ) + } + } + #[automatically_derived] + impl ::core::hash::Hash for FungiblesRef { + #[inline] + fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () { + ::core::hash::Hash::hash(&self.inner, state) + } + } + #[automatically_derived] + impl ::core::marker::StructuralPartialEq for FungiblesRef {} + #[automatically_derived] + impl ::core::cmp::PartialEq for FungiblesRef { + #[inline] + fn eq(&self, other: &FungiblesRef) -> bool { + self.inner == other.inner + } + } + #[automatically_derived] + impl ::core::cmp::Eq for FungiblesRef { + #[inline] + #[doc(hidden)] + #[coverage(off)] + fn assert_receiver_is_total_eq(&self) -> () { + let _: ::core::cmp::AssertParamIsEq< + ::Type, + >; + } + } + #[automatically_derived] + impl ::core::clone::Clone for FungiblesRef { + #[inline] + fn clone(&self) -> FungiblesRef { + FungiblesRef { + inner: ::core::clone::Clone::clone(&self.inner), + } + } + } + const _: () = { + impl ::ink::storage::traits::StorageLayout for FungiblesRef { + fn layout( + __key: &::ink::primitives::Key, + ) -> ::ink::metadata::layout::Layout { + ::ink::metadata::layout::Layout::Struct( + ::ink::metadata::layout::StructLayout::new( + "FungiblesRef", + [ + ::ink::metadata::layout::FieldLayout::new( + "inner", + <::Type as ::ink::storage::traits::StorageLayout>::layout( + __key, + ), + ), + ], + ), + ) + } + } + }; + const _: () = { + impl ::ink::env::ContractReference for Fungibles { + type Type = FungiblesRef; + } + impl ::ink::env::call::ConstructorReturnType for Fungibles { + type Output = FungiblesRef; + type Error = (); + fn ok(value: FungiblesRef) -> Self::Output { + value + } + } + impl ::ink::env::call::ConstructorReturnType + for ::core::result::Result + where + E: ::ink::scale::Decode, + { + const IS_RESULT: bool = true; + type Output = ::core::result::Result; + type Error = E; + fn ok(value: FungiblesRef) -> Self::Output { + ::core::result::Result::Ok(value) + } + fn err(err: Self::Error) -> ::core::option::Option { + ::core::option::Option::Some(::core::result::Result::Err(err)) + } + } + impl ::ink::env::ContractEnv for FungiblesRef { + type Env = ::Env; + } + }; + impl FungiblesRef { + #[inline] + #[allow(clippy::type_complexity)] + pub fn new() -> ::ink::env::call::CreateBuilder< + Environment, + Self, + ::ink::env::call::utils::Unset, + ::ink::env::call::utils::Set< + ::ink::env::call::LimitParamsV2< + ::Env, + >, + >, + ::ink::env::call::utils::Unset, + ::ink::env::call::utils::Set< + ::ink::env::call::ExecutionInput< + ::ink::env::call::utils::EmptyArgumentList, + >, + >, + ::ink::env::call::utils::Unset<::ink::env::call::state::Salt>, + ::ink::env::call::utils::Set<::ink::env::call::utils::ReturnType>, + > { + ::ink::env::call::build_create::() + .exec_input( + ::ink::env::call::ExecutionInput::new( + ::ink::env::call::Selector::new([ + 0x9B_u8, + 0xAE_u8, + 0x9D_u8, + 0x5E_u8, + ]), + ), + ) + .returns::() + } + #[inline] + pub fn total_supply(&self, id: AssetId) -> Result { + self.try_total_supply(id) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "total_supply", + error, + ), + ); + }) + } + #[inline] + pub fn try_total_supply( + &self, + id: AssetId, + ) -> ::ink::MessageResult> { + ::call(self) + .total_supply(id) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "total_supply", + error, + ), + ); + }) + } + #[inline] + pub fn balance_of(&self, id: AssetId, owner: AccountId32) -> Result { + self.try_balance_of(id, owner) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "balance_of", + error, + ), + ); + }) + } + #[inline] + pub fn try_balance_of( + &self, + id: AssetId, + owner: AccountId32, + ) -> ::ink::MessageResult> { + ::call(self) + .balance_of(id, owner) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "balance_of", + error, + ), + ); + }) + } + #[inline] + pub fn allowance( + &self, + id: AssetId, + owner: AccountId32, + spender: AccountId32, + ) -> Result { + self.try_allowance(id, owner, spender) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "allowance", + error, + ), + ); + }) + } + #[inline] + pub fn try_allowance( + &self, + id: AssetId, + owner: AccountId32, + spender: AccountId32, + ) -> ::ink::MessageResult> { + ::call(self) + .allowance(id, owner, spender) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "allowance", + error, + ), + ); + }) + } + #[inline] + pub fn asset_exists(&self, id: AssetId) -> Result { + self.try_asset_exists(id) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "asset_exists", + error, + ), + ); + }) + } + #[inline] + pub fn try_asset_exists( + &self, + id: AssetId, + ) -> ::ink::MessageResult> { + ::call(self) + .asset_exists(id) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "asset_exists", + error, + ), + ); + }) + } + #[inline] + pub fn mint_asset( + &self, + id: u32, + beneficiary: AccountId32, + amount: Balance, + ) -> Result<()> { + self.try_mint_asset(id, beneficiary, amount) + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "mint_asset", + error, + ), + ); + }) + } + #[inline] + pub fn try_mint_asset( + &self, + id: u32, + beneficiary: AccountId32, + amount: Balance, + ) -> ::ink::MessageResult> { + ::call(self) + .mint_asset(id, beneficiary, amount) + .try_invoke() + .unwrap_or_else(|error| { + ::core::panicking::panic_fmt( + format_args!( + "encountered error while calling {0}::{1}: {2:?}", + "Fungibles", + "mint_asset", + error, + ), + ); + }) + } + } + const _: () = { + impl ::ink::codegen::TraitCallBuilder for FungiblesRef { + type Builder = ::Type; + #[inline] + fn call(&self) -> &Self::Builder { + &self.inner + } + #[inline] + fn call_mut(&mut self) -> &mut Self::Builder { + &mut self.inner + } + } + }; + impl ::ink::env::call::FromAccountId for FungiblesRef { + #[inline] + fn from_account_id(account_id: AccountId) -> Self { + Self { + inner: <::Type as ::ink::env::call::FromAccountId< + Environment, + >>::from_account_id(account_id), + } + } + } + impl ::ink::ToAccountId for FungiblesRef { + #[inline] + fn to_account_id(&self) -> AccountId { + <::Type as ::ink::ToAccountId< + Environment, + >>::to_account_id(&self.inner) + } + } + impl ::core::convert::AsRef for FungiblesRef { + fn as_ref(&self) -> &AccountId { + <_ as ::core::convert::AsRef>::as_ref(&self.inner) + } + } + impl ::core::convert::AsMut for FungiblesRef { + fn as_mut(&mut self) -> &mut AccountId { + <_ as ::core::convert::AsMut>::as_mut(&mut self.inner) + } + } + #[cfg(feature = "std")] + #[cfg(not(feature = "ink-as-dependency"))] + const _: () = { + #[no_mangle] + pub fn __ink_generate_metadata() -> ::ink::metadata::InkProject { + let layout = ::ink::metadata::layout::Layout::Root( + ::ink::metadata::layout::RootLayout::new( + <::ink::metadata::layout::LayoutKey as ::core::convert::From< + ::ink::primitives::Key, + >>::from(::KEY), + ::layout( + &::KEY, + ), + ::ink::scale_info::meta_type::(), + ), + ); + ::ink::metadata::layout::ValidateLayout::validate(&layout) + .unwrap_or_else(|error| { + { + ::core::panicking::panic_fmt( + format_args!("metadata ink! generation failed: {0}", error), + ); + } + }); + ::ink::metadata::InkProject::new( + layout, + ::ink::metadata::ContractSpec::new() + .constructors([ + ::ink::metadata::ConstructorSpec::from_label("new") + .selector([0x9B_u8, 0xAE_u8, 0x9D_u8, 0x5E_u8]) + .args([]) + .payable(true) + .default(false) + .returns( + ::ink::metadata::ReturnTypeSpec::new( + if >::IS_RESULT { + ::ink::metadata::TypeSpec::with_name_str::< + ::ink::ConstructorResult< + ::core::result::Result< + (), + >::Error, + >, + >, + >("ink_primitives::ConstructorResult") + } else { + ::ink::metadata::TypeSpec::with_name_str::< + ::ink::ConstructorResult<()>, + >("ink_primitives::ConstructorResult") + }, + ), + ) + .docs([]) + .done(), + ]) + .messages([ + ::ink::metadata::MessageSpec::from_label("total_supply") + .selector([0xDB_u8, 0x63_u8, 0x75_u8, 0xA8_u8]) + .args([ + ::ink::metadata::MessageParamSpec::new("id") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AssetId, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AssetId"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ]) + .returns( + ::ink::metadata::ReturnTypeSpec::new( + ::ink::metadata::TypeSpec::with_name_segs::< + ::ink::MessageResult>, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter([ + "ink", + "MessageResult", + ]), + ::core::convert::AsRef::as_ref, + ), + ), + ), + ) + .mutates(false) + .payable(false) + .default(false) + .docs([]) + .done(), + ::ink::metadata::MessageSpec::from_label("balance_of") + .selector([0x0F_u8, 0x75_u8, 0x5A_u8, 0x56_u8]) + .args([ + ::ink::metadata::MessageParamSpec::new("id") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AssetId, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AssetId"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ::ink::metadata::MessageParamSpec::new("owner") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AccountId32, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AccountId32"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ]) + .returns( + ::ink::metadata::ReturnTypeSpec::new( + ::ink::metadata::TypeSpec::with_name_segs::< + ::ink::MessageResult>, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter([ + "ink", + "MessageResult", + ]), + ::core::convert::AsRef::as_ref, + ), + ), + ), + ) + .mutates(false) + .payable(false) + .default(false) + .docs([]) + .done(), + ::ink::metadata::MessageSpec::from_label("allowance") + .selector([0x6A_u8, 0x00_u8, 0x16_u8, 0x5E_u8]) + .args([ + ::ink::metadata::MessageParamSpec::new("id") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AssetId, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AssetId"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ::ink::metadata::MessageParamSpec::new("owner") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AccountId32, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AccountId32"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ::ink::metadata::MessageParamSpec::new("spender") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AccountId32, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AccountId32"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ]) + .returns( + ::ink::metadata::ReturnTypeSpec::new( + ::ink::metadata::TypeSpec::with_name_segs::< + ::ink::MessageResult>, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter([ + "ink", + "MessageResult", + ]), + ::core::convert::AsRef::as_ref, + ), + ), + ), + ) + .mutates(false) + .payable(false) + .default(false) + .docs([]) + .done(), + ::ink::metadata::MessageSpec::from_label("asset_exists") + .selector([0xAA_u8, 0x6B_u8, 0x65_u8, 0xDB_u8]) + .args([ + ::ink::metadata::MessageParamSpec::new("id") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AssetId, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AssetId"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ]) + .returns( + ::ink::metadata::ReturnTypeSpec::new( + ::ink::metadata::TypeSpec::with_name_segs::< + ::ink::MessageResult>, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter([ + "ink", + "MessageResult", + ]), + ::core::convert::AsRef::as_ref, + ), + ), + ), + ) + .mutates(false) + .payable(false) + .default(false) + .docs([]) + .done(), + ::ink::metadata::MessageSpec::from_label("mint_asset") + .selector([0x1F_u8, 0x8E_u8, 0x8E_u8, 0x22_u8]) + .args([ + ::ink::metadata::MessageParamSpec::new("id") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + u32, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["u32"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ::ink::metadata::MessageParamSpec::new("beneficiary") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + AccountId32, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AccountId32"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ::ink::metadata::MessageParamSpec::new("amount") + .of_type( + ::ink::metadata::TypeSpec::with_name_segs::< + Balance, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["Balance"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .done(), + ]) + .returns( + ::ink::metadata::ReturnTypeSpec::new( + ::ink::metadata::TypeSpec::with_name_segs::< + ::ink::MessageResult>, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter([ + "ink", + "MessageResult", + ]), + ::core::convert::AsRef::as_ref, + ), + ), + ), + ) + .mutates(false) + .payable(false) + .default(false) + .docs([]) + .done(), + ]) + .collect_events() + .docs([]) + .lang_error( + ::ink::metadata::TypeSpec::with_name_segs::< + ::ink::LangError, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["ink", "LangError"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .environment( + ::ink::metadata::EnvironmentSpec::new() + .account_id( + ::ink::metadata::TypeSpec::with_name_segs::< + AccountId, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["AccountId"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .balance( + ::ink::metadata::TypeSpec::with_name_segs::< + Balance, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["Balance"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .hash( + ::ink::metadata::TypeSpec::with_name_segs::< + Hash, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["Hash"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .timestamp( + ::ink::metadata::TypeSpec::with_name_segs::< + Timestamp, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["Timestamp"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .block_number( + ::ink::metadata::TypeSpec::with_name_segs::< + BlockNumber, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["BlockNumber"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .chain_extension( + ::ink::metadata::TypeSpec::with_name_segs::< + ChainExtension, + _, + >( + ::core::iter::Iterator::map( + ::core::iter::IntoIterator::into_iter(["ChainExtension"]), + ::core::convert::AsRef::as_ref, + ), + ), + ) + .max_event_topics(MAX_EVENT_TOPICS) + .static_buffer_size(::ink::env::BUFFER_SIZE) + .done(), + ) + .done(), + ) + } + }; + use super::*; +} diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs new file mode 100755 index 00000000..9c0ae754 --- /dev/null +++ b/pop-api/examples/fungibles/lib.rs @@ -0,0 +1,176 @@ +#![cfg_attr(not(feature = "std"), no_std, no_main)] + +// Fungibles wrapper contract to allow contracts to interact with local fungibles without the pop api. +use ink::prelude::vec::Vec; +use pop_api::{ + assets::fungibles::*, + primitives::{AccountId as AccountId32, AssetId}, +}; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum ContractError { + // AssetsError(Error), + // /// The origin of the call doesn't have the right permission. + // BadOrigin, + // /// Custom error type for cases in which an implementation adds its own restrictions. + // Custom(String), + /// Not enough balance to fulfill a request is available. + InsufficientBalance, + /// Not enough allowance to fulfill a request is available. + InsufficientAllowance, + /// The asset status is not the expected status. + IncorrectStatus, + /// The asset ID is already taken. + InUse, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// The signing account has no permission to do the operation. + NoPermission, + // /// Safe transfer check fails (e.g. if the receiving contract does not accept tokens). + // SafeTransferCheckFailed(String), + /// The given asset ID is unknown. + Unknown, + /// Recipient's address is zero. + ZeroRecipientAddress, + /// Sender's address is zero. + ZeroSenderAddress, + UndefinedError, +} + +impl From for ContractError { + fn from(error: FungiblesError) -> Self { + match error { + // Error::BalanceLow => Err(InsufficientBalance), + FungiblesError::InUse => ContractError::InUse, + FungiblesError::MinBalanceZero => ContractError::MinBalanceZero, + FungiblesError::Unknown => ContractError::Unknown, + _ => ContractError::UndefinedError, + } + } +} + +/// The fungibles result type. +pub type Result = core::result::Result; + +#[ink::contract(env = pop_api::Environment)] +mod fungibles { + use super::*; + + #[ink(storage)] + #[derive(Default)] + pub struct Fungibles; + + impl Fungibles { + #[ink(constructor, payable)] + pub fn new() -> Self { + ink::env::debug_println!("PopApiAssetsExample::new"); + Default::default() + } + + #[ink(message)] + pub fn total_supply(&self, id: AssetId) -> Result { + total_supply(id).map_err(From::from) + } + + #[ink(message)] + pub fn balance_of(&self, id: AssetId, owner: AccountId32) -> Result { + balance_of(id, owner).map_err(From::from) + } + + #[ink(message)] + pub fn allowance( + &self, + id: AssetId, + owner: AccountId32, + spender: AccountId32, + ) -> Result { + allowance(id, owner, spender).map_err(From::from) + } + + #[ink(message)] + pub fn asset_exists(&self, id: AssetId) -> Result { + asset_exists(id).map_err(From::from) + } + + #[ink(message)] + pub fn create(&self, id: AssetId, admin: AccountId32, min_balance: Balance) -> Result<()> { + // create(id, admin, min_balance).map_err(From::from) + ink::env::debug_println!( + "PopApiAssetsExample::create: id: {:?} admin: {:?} min_balance: {:?}", + id, + admin, + min_balance, + ); + let result = create(id, admin, min_balance); + ink::env::debug_println!("Result: {:?}", result); + result.map_err(From::from) + } + + #[ink(message)] + pub fn set_metadata( + &self, + id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, + ) -> Result<()> { + // set_metadata(id, name, symbol, decimals).map_err(From::from) + ink::env::debug_println!( + "PopApiAssetsExample::set_metadata: id: {:?} name: {:?} symbol: {:?}, decimals: {:?}", + id, + name, + symbol, + decimals, + ); + let result = set_metadata(id, name, symbol, decimals); + ink::env::debug_println!("Result: {:?}", result); + result.map_err(From::from) + } + + #[ink(message)] + pub fn mint(&self, id: AssetId, beneficiary: AccountId32, amount: Balance) -> Result<()> { + ink::env::debug_println!( + "PopApiAssetsExample::mint: id: {:?}, beneficiary: {:?} amount: {:?}", + id, + beneficiary, + amount, + ); + + let result = mint(id, beneficiary, amount); + ink::env::debug_println!("Result: {:?}", result); + result.map_err(From::from) + } + + // #[ink(message)] + // pub fn transfer_from( + // id: AssetId, + // from: Option, + // to: Option, + // value: Balance, + // data: [u8], + // ) -> Result<()> { + // ink::env::debug_println!( + // "PopApiAssetsExample::transfer_from: id: {:?}, from: {:?}, to: {:?} value: {:?}", + // id, + // from, + // to, + // value, + // ); + // + // let result = transfer_from(id, from, to, value)?; + // ink::env::debug_println!("Result: {:?}", result); + // result + // } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[ink::test] + fn default_works() { + PopApiAssetsExample::new(); + } + } +} diff --git a/pop-api/examples/trust_backed_assets/lib.rs b/pop-api/examples/trust_backed_assets/lib.rs deleted file mode 100755 index 3606f852..00000000 --- a/pop-api/examples/trust_backed_assets/lib.rs +++ /dev/null @@ -1,74 +0,0 @@ -#![cfg_attr(not(feature = "std"), no_std, no_main)] - -// Utilizing Trust Backed Assets with the Pop API. -// -// This example demonstrates interaction with trust backed assets via the assets pallet. Trust backed assets are originated -// and managed within Pop Network, harnessing the platform's inherent trust, security, and governance models. -use pop_api::assets::trust_backed as trust_backed_assets; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum ContractError { - TrustBackedAssetsError(trust_backed_assets::Error), - UnknownAsset, -} - -impl From for ContractError { - fn from(value: trust_backed_assets::Error) -> Self { - ContractError::TrustBackedAssetsError(value) - } -} - -#[ink::contract(env = pop_api::Environment)] -mod pop_api_tb_assets_example { - use super::*; - - #[ink(storage)] - #[derive(Default)] - pub struct PopApiTBAssetsExample; - - impl PopApiTBAssetsExample { - #[ink(constructor, payable)] - pub fn new() -> Self { - ink::env::debug_println!("Contract::new"); - Default::default() - } - - #[ink(message)] - pub fn mint_asset_through_runtime( - &mut self, - id: u32, - beneficiary: AccountId, - amount: Balance, - ) -> Result<(), ContractError> { - ink::env::debug_println!( - "Contract::mint_asset_through_runtime: id: {:?} beneficiary: {:?} amount: {:?}", - id, - beneficiary, - amount - ); - - // Check if asset doesn't exist. - if !trust_backed_assets::asset_exists(id)? { - return Err(ContractError::UnknownAsset); - } - - // Mint asset via pop api. - trust_backed_assets::mint(id, beneficiary, amount)?; - ink::env::debug_println!( - "Contract::mint_asset_through_runtime: asset(s) minted successfully" - ); - Ok(()) - } - } - - #[cfg(test)] - mod tests { - use super::*; - - #[ink::test] - fn default_works() { - PopApiTBAssetsExample::new(); - } - } -} diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 68ce6906..0ca4a817 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -3,14 +3,15 @@ pub mod primitives; pub mod v0; -use crate::PopApiError::{Balances, Nfts, TrustBackedAssets, UnknownStatusCode}; +use crate::PopApiError::{Assets, Balances, Contracts, Nfts, UnknownStatusCode}; use ink::{prelude::vec::Vec, ChainExtensionInstance}; -use primitives::{cross_chain::*, storage_keys::*}; +use primitives::{cross_chain::*, storage_keys::*, AccountId as AccountId32}; pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; use v0::RuntimeCall; -pub use v0::{balances, cross_chain, nfts, relay_chain_block_number, state, assets}; +pub use v0::{assets, balances, contracts, cross_chain, nfts, relay_chain_block_number, state}; -type AccountId = ::AccountId; +// type AccountId = ::AccountId; +type AccountId = AccountId32; type Balance = ::Balance; type BlockNumber = ::BlockNumber; type StringLimit = u32; @@ -25,8 +26,9 @@ pub enum PopApiError { DecodingFailed, SystemCallFiltered, Balances(balances::Error), + Contracts(contracts::Error), Nfts(nfts::Error), - TrustBackedAssets(assets::trust_backed::Error), + Assets(assets::fungibles::AssetsError), Xcm(cross_chain::Error), } @@ -37,8 +39,9 @@ impl ink::env::chain_extension::FromStatusCode for PopApiError { // CallFiltered originates from `frame_system` with pallet-index 0. The CallFiltered error is at index 5 5 => Err(PopApiError::SystemCallFiltered), 10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)), + 40_000..=40_999 => Err(Contracts((status_code - 40_000).try_into()?)), 50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)), - 52_000..=52_999 => Err(TrustBackedAssets((status_code - 52_000).try_into()?)), + 52_000..=52_999 => Err(Assets((status_code - 52_000).try_into()?)), _ => Err(UnknownStatusCode(status_code)), } } diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs new file mode 100644 index 00000000..f2d87a0e --- /dev/null +++ b/pop-api/src/v0/assets/fungibles.rs @@ -0,0 +1,554 @@ +use crate::{AccountId, Balance, PopApiError::UnknownStatusCode, RuntimeCall, *}; +use ink::prelude::vec::Vec; +use primitives::AssetId; +use scale::{Compact, Encode}; + +type Result = core::result::Result; + +/// Local Fungibles: +/// 1. PSP-22 Interface +/// 2. PSP-22 Metadata Interface +/// 3. Asset Management + +/// 1. PSP-22 Interface: +/// - total_supply +/// - balance_of +/// - allowance +/// - transfer +/// - transfer_from +/// - approve +/// - increase_allowance +/// - decrease_allowance + +/// Returns the total token supply for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The total supply of the token, or an error if the operation fails. +pub fn total_supply(id: AssetId) -> Result { + Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id)))?) +} + +/// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if +/// the account is non-existent. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `owner` - The account whose balance is being queried. +/// +/// # Returns +/// The balance of the specified account, or an error if the operation fails. +pub fn balance_of(id: AssetId, owner: AccountId) -> Result { + Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner)))?) +} + +/// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given +/// asset ID. Returns `0` if no allowance has been set. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `owner` - The account that owns the tokens. +/// * `spender` - The account that is allowed to spend the tokens. +/// +/// # Returns +/// The remaining allowance, or an error if the operation fails. +pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { + Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender)))?) +} + +/// Create a new token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `admin` - The account that will administer the asset. +/// * `min_balance` - The minimum balance required for accounts holding this asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the creation fails. +// pub fn create(id: AssetId, admin: impl Into>, min_balance: Balance) -> Result<()> { +pub fn create( + id: AssetId, + admin: impl Into>, + min_balance: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::Assets(AssetsCall::Create { + id: id.into(), + admin: admin.into(), + min_balance, + }))?) +} + +/// Transfers `value` amount of tokens from the caller's account to account `to`, with additional +/// `data` in unspecified format. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `to` - The recipient account. +/// * `value` - The number of tokens to transfer. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the transfer fails. +// #[allow(unused_variables)] +// pub fn transfer( +// id: AssetId, +// to: impl Into>, +// value: Balance, +// ) -> Result<()> { +// todo!() +// // TODO: transfer or transfer_keep_alive +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::Transfer { +// // id: id.into(), +// // target: target.into(), +// // amount: Compact(amount), +// // }))?) +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { +// // id: id.into(), +// // target: target.into(), +// // amount: Compact(amount), +// // }))?) +// } + +/// Transfers `value` tokens on the behalf of `from` to the account `to` with additional `data` +/// in unspecified format. This can be used to allow a contract to transfer tokens on ones behalf +/// and/or to charge fees in sub-currencies, for example. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `from` - The account from which the tokens are transferred. +/// * `to` - The recipient account. +/// * `value` - The number of tokens to transfer. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the transfer fails. +// pub fn transfer_from( +// id: AssetId, +// from: impl Into>, +// to: impl Into>, +// value: Balance, +// ) -> Result<()> { +//todo!() +// TODO: depending on `from` and `to`, decide whether to mint, burn or transfer_approved. +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::Mint { +// id: id.into(), +// beneficiary: beneficiary.into(), +// amount: Compact(amount), +// }))?) +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::Burn { +// id: id.into(), +// who: who.into(), +// amount: Compact(amount), +// }))?) +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { +// id: id.into(), +// owner: from.into(), +// destination: to.into(), +// amount: Compact(value), +// }))?) +// } + +/// Mint assets of a particular class. +pub fn mint( + id: AssetId, + beneficiary: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::Assets(AssetsCall::Mint { + id: id.into(), + beneficiary: beneficiary.into(), + amount: Compact(amount), + }))?) +} + +/// Approves an account to spend a specified number of tokens on behalf of the caller. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `spender` - The account that is allowed to spend the tokens. +/// * `value` - The number of tokens to approve. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the approval fails. +// #[allow(unused_variables)] +// fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { +// todo!() +// // TODO: read allowance and increase or decrease. +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { +// // id: id.into(), +// // delegate: spender.into(), +// // amount: Compact(value), +// // }))?) +// } + +/// Increases the allowance of a spender. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `spender` - The account that is allowed to spend the tokens. +/// * `value` - The number of tokens to increase the allowance by. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn increase_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { +// id: id.into(), +// delegate: spender.into(), +// amount: Compact(value), +// }))?) +// } + +/// Decreases the allowance of a spender. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `spender` - The account that is allowed to spend the tokens. +/// * `value` - The number of tokens to decrease the allowance by. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// #[allow(unused_variables)] +// fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { +// todo!() +// // TODO: cancel_approval + approve_transfer +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { +// // id: id.into(), +// // delegate: delegate.into(), +// // }))?) +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { +// // id: id.into(), +// // delegate: spender.into(), +// // amount: Compact(value), +// // }))?) +// } + +/// 2. PSP-22 Metadata Interface: +/// - token_name +/// - token_symbol +/// - token_decimals + +/// Returns the token name for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The name of the token as a byte vector, or an error if the operation fails. +// #[allow(unused_variables)] +// pub fn token_name(id: AssetId) -> Result>> { +// todo!() +// // Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id)))?) +// } + +/// Returns the token symbol for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The symbol of the token as a byte vector, or an error if the operation fails. +// #[allow(unused_variables)] +// fn token_symbol(id: AssetId) -> Result>> { +// todo!() +// } + +/// Returns the token decimals for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The number of decimals of the token as a byte vector, or an error if the operation fails. +// #[allow(unused_variables)] +// fn token_decimals(id: AssetId) -> Result>> { +// todo!() +// } + +/// 3. Asset Management: +/// - create +/// - start_destroy +/// - destroy_accounts +/// - destroy_approvals +/// - finish_destroy +/// - set_metadata +/// - clear_metadata + +/// Start the process of destroying a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn start_destroy(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { +// id: id.into(), +// }))?) +// } + +/// Destroy all accounts associated with a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn destroy_accounts(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { +// id: id.into(), +// }))?) +// } + +/// Destroy all approvals associated with a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn destroy_approvals(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { +// id: id.into(), +// }))?) +// } + +/// Complete the process of destroying a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn finish_destroy(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { +// id: id.into(), +// }))?) +// } + +/// Set the metadata for a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { + Ok(dispatch(RuntimeCall::Assets(AssetsCall::SetMetadata { + id: id.into(), + name, + symbol, + decimals, + }))?) +} + +/// Clear the metadata for a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn clear_metadata(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { +// id: id.into(), +// }))?) +// } + +pub fn asset_exists(id: AssetId) -> Result { + Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id)))?) +} + +// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected +// to be compact encoded. The pop api handles that for the developer. +// +// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development +// +// Asset id that is compact encoded. +type AssetIdParameter = Compact; +// Balance amount that is compact encoded. +type BalanceParameter = Compact; + +#[allow(warnings, unused)] +#[derive(Encode)] +pub(crate) enum AssetsCall { + #[codec(index = 0)] + Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, + #[codec(index = 2)] + StartDestroy { id: AssetIdParameter }, + #[codec(index = 3)] + DestroyAccounts { id: AssetIdParameter }, + #[codec(index = 4)] + DestroyApprovals { id: AssetIdParameter }, + #[codec(index = 5)] + FinishDestroy { id: AssetIdParameter }, + #[codec(index = 6)] + Mint { + id: AssetIdParameter, + beneficiary: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 7)] + Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, + // TODO: ED or not + // #[codec(index = 8)] + // Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, + #[codec(index = 9)] + TransferKeepAlive { + id: AssetIdParameter, + target: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 17)] + SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, + #[codec(index = 18)] + ClearMetadata { id: AssetIdParameter }, + #[codec(index = 22)] + ApproveTransfer { + id: AssetIdParameter, + delegate: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 23)] + CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, + #[codec(index = 25)] + TransferApproved { + id: AssetIdParameter, + owner: MultiAddress, + destination: MultiAddress, + amount: BalanceParameter, + }, +} + +// TODO: remove unnecessary errors +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub(crate) enum AssetsError { + /// Account balance must be greater than or equal to the transfer amount. + BalanceLow, + /// The account to alter does not exist. + NoAccount, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + /// The origin account is frozen. + Frozen, + /// The asset ID is already taken. + InUse, + /// Invalid witness data given. + BadWitness, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// Unable to increment the consumer reference counters on the account. Either no provider + /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one + /// fewer then the maximum number of consumers has been reached. + UnavailableConsumer, + /// Invalid metadata given. + BadMetadata, + /// No approval exists that would allow the transfer. + Unapproved, + /// The source account would not survive the transfer and it needs to stay alive. + WouldDie, + /// The asset-account already exists. + AlreadyExists, + /// The asset-account doesn't have an associated deposit. + NoDeposit, + /// The operation would result in funds being burned. + WouldBurn, + /// The asset is a live asset and is actively being used. Usually emit for operations such + /// as `start_destroy` which require the asset to be in a destroying state. + LiveAsset, + /// The asset is not live, and likely being destroyed. + AssetNotLive, + /// The asset status is not the expected status. + IncorrectStatus, + /// The asset should be frozen before the given operation. + NotFrozen, + /// Callback action resulted in error + CallbackFailed, +} + +impl From for AssetsError { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::Assets(e) => e, + _ => panic!("Expected AssetsError"), + } + } +} + +impl TryFrom for AssetsError { + type Error = PopApiError; + + fn try_from(status_code: u32) -> core::result::Result { + use AssetsError::*; + match status_code { + 0 => Ok(BalanceLow), + 1 => Ok(NoAccount), + 2 => Ok(NoPermission), + 3 => Ok(Unknown), + 4 => Ok(Frozen), + 5 => Ok(InUse), + 6 => Ok(BadWitness), + 7 => Ok(MinBalanceZero), + 8 => Ok(UnavailableConsumer), + 9 => Ok(BadMetadata), + 10 => Ok(Unapproved), + 11 => Ok(WouldDie), + 12 => Ok(AlreadyExists), + 13 => Ok(NoDeposit), + 14 => Ok(WouldBurn), + 15 => Ok(LiveAsset), + 16 => Ok(AssetNotLive), + 17 => Ok(IncorrectStatus), + 18 => Ok(NotFrozen), + _ => Err(UnknownStatusCode(status_code)), + } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum FungiblesError { + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + InsufficientBalance, + /// The asset ID is already taken. + InUse, + /// Minimum balance should be non-zero. + MinBalanceZero, +} + +impl From for FungiblesError { + fn from(error: balances::Error) -> Self { + match error { + balances::Error::InsufficientBalance => FungiblesError::InsufficientBalance, + _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), + } + } +} + +impl From for FungiblesError { + fn from(error: AssetsError) -> Self { + match error { + AssetsError::InUse => FungiblesError::InUse, + _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), + } + } +} + +impl From for FungiblesError { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::Assets(e) => e.into(), + // PopApiError::Balances(e) => todo!("balances: {:?}", e), + PopApiError::Balances(e) => e.into(), + // PopApiError::Contracts(_e) => todo!("contracts"), + // PopApiError::SystemCallFiltered => 100, + // PopApiError::UnknownStatusCode(u) => u, + _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), + } + } +} diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 7ad40f15..d6b0261c 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1 +1 @@ -pub mod trust_backed; \ No newline at end of file +pub mod fungibles; \ No newline at end of file diff --git a/pop-api/src/v0/assets/trust_backed.rs b/pop-api/src/v0/assets/trust_backed.rs deleted file mode 100644 index fb413413..00000000 --- a/pop-api/src/v0/assets/trust_backed.rs +++ /dev/null @@ -1,519 +0,0 @@ -use crate::{Balance, PopApiError::UnknownStatusCode, RuntimeCall, *}; -use ink::prelude::vec::Vec; -use primitives::{AssetId, MultiAddress}; -use scale::{Compact, Encode}; - -type Result = core::result::Result; - -/// https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/lib.rs -/// -/// Extrinsics within pallet assets (TrustBackedAssets Instance) that can be used via the pop api on Pop Network: -/// 1. create -/// 2. start_destroy -/// 3. destroy_accounts -/// 4. destroy_approvals -/// 5. finish_destroy -/// 6. mint -/// 7. burn -/// 8. transfer -/// 9. transfer_keep_alive -/// 10. force_transfer -/// 11. freeze -/// 12. thaw -/// 13. freeze_asset -/// 14. thaw_asset -/// 15. transfer_ownership -/// 16. set_team -/// 17. set_metadata -/// 18. clear_metadata -/// 19. approve_transfer -/// 20. cancel_approval -/// 21. force_cancel_approval -/// 22. transfer_approved -/// 23. touch -/// 24. refund -/// 25. set_min_balance -/// 26. touch_other -/// 27. refund_other -/// 28. block - - -/// Issue a new class of fungible assets from a public origin. -pub fn create( - id: AssetId, - admin: impl Into>, - min_balance: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Create { - id: id.into(), - admin: admin.into(), - min_balance: Compact(min_balance), - }))?) -} - -/// Start the process of destroying a fungible asset class. -pub fn start_destroy(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::StartDestroy { - id: id.into(), - }))?) -} - -/// Destroy all accounts associated with a given asset. -pub fn destroy_accounts(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::DestroyAccounts { - id: id.into(), - }))?) -} - -/// Destroy all approvals associated with a given asset up to the max (see runtime configuration TrustBackedAssets `RemoveItemsLimit`). -pub fn destroy_approvals(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::DestroyApprovals { - id: id.into(), - }))?) -} - -/// Complete destroying asset and unreserve currency. -pub fn finish_destroy(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::FinishDestroy { - id: id.into(), - }))?) -} - -/// Mint assets of a particular class. -pub fn mint( - id: AssetId, - beneficiary: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Mint { - id: id.into(), - beneficiary: beneficiary.into(), - amount: Compact(amount), - }))?) -} - -/// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`. -pub fn burn( - id: AssetId, - who: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Burn { - id: id.into(), - who: who.into(), - amount: Compact(amount), - }))?) -} - -/// Move some assets from the sender account to another. -pub fn transfer( - id: AssetId, - target: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Transfer { - id: id.into(), - target: target.into(), - amount: Compact(amount), - }))?) -} - -/// Move some assets from the sender account to another, keeping the sender account alive. -pub fn transfer_keep_alive( - id: AssetId, - target: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TransferKeepAlive { - id: id.into(), - target: target.into(), - amount: Compact(amount), - }))?) -} - -/// Move some assets from one account to another. Sender should be the Admin of the asset `id`. -pub fn force_transfer( - id: AssetId, - source: impl Into>, - dest: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ForceTransfer { - id: id.into(), - source: source.into(), - dest: dest.into(), - amount: Compact(amount), - }))?) -} - -/// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` -/// must already exist as an entry in `Account`s of the asset. If you want to freeze an -/// account that does not have an entry, use `touch_other` first. -pub fn freeze(id: AssetId, who: impl Into>) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Freeze { - id: id.into(), - who: who.into(), - }))?) -} - -/// Allow unprivileged transfers to and from an account again. -pub fn thaw(id: AssetId, who: impl Into>) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Thaw { - id: id.into(), - who: who.into(), - }))?) -} - -/// Disallow further unprivileged transfers for the asset class. -pub fn freeze_asset(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::FreezeAsset { - id: id.into(), - }))?) -} - -/// Allow unprivileged transfers for the asset again. -pub fn thaw_asset(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ThawAsset { - id: id.into(), - }))?) -} - -/// Change the Owner of an asset. -pub fn transfer_ownership( - id: AssetId, - owner: impl Into>, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TransferOwnership { - id: id.into(), - owner: owner.into(), - }))?) -} - -/// Change the Issuer, Admin and Freezer of an asset. -pub fn set_team( - id: AssetId, - issuer: impl Into>, - admin: impl Into>, - freezer: impl Into>, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::SetTeam { - id: id.into(), - issuer: issuer.into(), - admin: admin.into(), - freezer: freezer.into(), - }))?) -} - -/// Set the metadata for an asset. -pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::SetMetadata { - id: id.into(), - name, - symbol, - decimals, - }))?) -} - -/// Clear the metadata for an asset. -pub fn clear_metadata(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ClearMetadata { - id: id.into(), - }))?) -} - -/// Approve an amount of asset for transfer by a delegated third-party account. -pub fn approve_transfer( - id: AssetId, - delegate: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ApproveTransfer { - id: id.into(), - delegate: delegate.into(), - amount: Compact(amount), - }))?) -} - -/// Cancel all of some asset approved for delegated transfer by a third-party account. -pub fn cancel_approval( - id: AssetId, - delegate: impl Into>, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::CancelApproval { - id: id.into(), - delegate: delegate.into(), - }))?) -} - -/// Cancel all of some asset approved for delegated transfer by a third-party account. -pub fn force_cancel_approval( - id: AssetId, - owner: impl Into>, - delegate: impl Into>, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::ForceCancelApproval { - id: id.into(), - owner: owner.into(), - delegate: delegate.into(), - }))?) -} - -/// Transfer some asset balance from a previously delegated account to some third-party -/// account. -pub fn transfer_approved( - id: AssetId, - owner: impl Into>, - destination: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TransferApproved { - id: id.into(), - owner: owner.into(), - destination: destination.into(), - amount: Compact(amount), - }))?) -} - -/// Create an asset account for non-provider assets. -pub fn touch(id: AssetId) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Touch { - id: id.into(), - }))?) -} - -/// Return the deposit (if any) of an asset account or a consumer reference (if any) of an -/// account. -pub fn refund(id: AssetId, allow_burn: bool) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Refund { - id: id.into(), - allow_burn, - }))?) -} - -/// Sets the minimum balance of an asset. -pub fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::SetMinBalance { - id: id.into(), - min_balance: Compact(min_balance), - }))?) -} - -/// Create an asset account for `who`. -pub fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::TouchOther { - id: id.into(), - who: who.into(), - }))?) -} - -/// Return the deposit (if any) of a target asset account. Useful if you are the depositor. -pub fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::RefundOther { - id: id.into(), - who: who.into(), - }))?) -} - -/// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. -pub fn block(id: AssetId, who: impl Into>) -> Result<()> { - Ok(dispatch(RuntimeCall::TrustBackedAssets(TrustBackedAssetsCalls::Block { - id: id.into(), - who: who.into(), - }))?) -} - -pub fn asset_exists(id: AssetId) -> Result { - Ok(state::read(RuntimeStateKeys::TrustBackedAssets(TrustBackedAssetsKeys::AssetExists(id)))?) -} - -// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected -// to be compact encoded. The pop api handles that for the developer. -// -// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development -// -// Asset id that is compact encoded. -type AssetIdParameter = Compact; -// Balance amount that is compact encoded. -type BalanceParameter = Compact; - -#[derive(Encode)] -pub(crate) enum TrustBackedAssetsCalls { - #[codec(index = 0)] - Create { - id: AssetIdParameter, - admin: MultiAddress, - min_balance: BalanceParameter, - }, - #[codec(index = 2)] - StartDestroy { id: AssetIdParameter }, - #[codec(index = 3)] - DestroyAccounts { id: AssetIdParameter }, - #[codec(index = 4)] - DestroyApprovals { id: AssetIdParameter }, - #[codec(index = 5)] - FinishDestroy { id: AssetIdParameter }, - #[codec(index = 6)] - Mint { - id: AssetIdParameter, - beneficiary: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 7)] - Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, - #[codec(index = 8)] - Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, - #[codec(index = 9)] - TransferKeepAlive { - id: AssetIdParameter, - target: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 10)] - ForceTransfer { - id: AssetIdParameter, - source: MultiAddress, - dest: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 11)] - Freeze { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 12)] - Thaw { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 13)] - FreezeAsset { id: AssetIdParameter }, - #[codec(index = 14)] - ThawAsset { id: AssetIdParameter }, - #[codec(index = 15)] - TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, - #[codec(index = 16)] - SetTeam { - id: AssetIdParameter, - issuer: MultiAddress, - admin: MultiAddress, - freezer: MultiAddress, - }, - #[codec(index = 17)] - SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, - #[codec(index = 18)] - ClearMetadata { id: AssetIdParameter }, - #[codec(index = 22)] - ApproveTransfer { - id: AssetIdParameter, - delegate: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 23)] - CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, - #[codec(index = 24)] - ForceCancelApproval { - id: AssetIdParameter, - owner: MultiAddress, - delegate: MultiAddress, - }, - #[codec(index = 25)] - TransferApproved { - id: AssetIdParameter, - owner: MultiAddress, - destination: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 26)] - Touch { id: AssetIdParameter }, - #[codec(index = 27)] - Refund { id: AssetIdParameter, allow_burn: bool }, - #[codec(index = 28)] - SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, - #[codec(index = 29)] - TouchOther { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 30)] - RefundOther { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 31)] - Block { id: AssetIdParameter, who: MultiAddress }, -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { - /// Account balance must be greater than or equal to the transfer amount. - BalanceLow, - /// The account to alter does not exist. - NoAccount, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, - /// The origin account is frozen. - Frozen, - /// The asset ID is already taken. - InUse, - /// Invalid witness data given. - BadWitness, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// Unable to increment the consumer reference counters on the account. Either no provider - /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one - /// fewer then the maximum number of consumers has been reached. - UnavailableConsumer, - /// Invalid metadata given. - BadMetadata, - /// No approval exists that would allow the transfer. - Unapproved, - /// The source account would not survive the transfer and it needs to stay alive. - WouldDie, - /// The asset-account already exists. - AlreadyExists, - /// The asset-account doesn't have an associated deposit. - NoDeposit, - /// The operation would result in funds being burned. - WouldBurn, - /// The asset is a live asset and is actively being used. Usually emit for operations such - /// as `start_destroy` which require the asset to be in a destroying state. - LiveAsset, - /// The asset is not live, and likely being destroyed. - AssetNotLive, - /// The asset status is not the expected status. - IncorrectStatus, - /// The asset should be frozen before the given operation. - NotFrozen, - /// Callback action resulted in error - CallbackFailed, -} - -impl TryFrom for Error { - type Error = PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use Error::*; - match status_code { - 0 => Ok(BalanceLow), - 1 => Ok(NoAccount), - 2 => Ok(NoPermission), - 3 => Ok(Unknown), - 4 => Ok(Frozen), - 5 => Ok(InUse), - 6 => Ok(BadWitness), - 7 => Ok(MinBalanceZero), - 8 => Ok(UnavailableConsumer), - 9 => Ok(BadMetadata), - 10 => Ok(Unapproved), - 11 => Ok(WouldDie), - 12 => Ok(AlreadyExists), - 13 => Ok(NoDeposit), - 14 => Ok(WouldBurn), - 15 => Ok(LiveAsset), - 16 => Ok(AssetNotLive), - 17 => Ok(IncorrectStatus), - 18 => Ok(NotFrozen), - _ => Err(UnknownStatusCode(status_code)), - } - } -} - -impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::TrustBackedAssets(e) => e, - _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), - } - } -} diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index bf029178..bc48711e 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -28,7 +28,7 @@ pub(crate) enum BalancesCall { #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { +pub(crate) enum Error { /// Vesting balance too high to send value. VestingBalance, /// Account liquidity restrictions prevent withdrawal. diff --git a/pop-api/src/v0/contracts.rs b/pop-api/src/v0/contracts.rs new file mode 100644 index 00000000..d7a1a5dd --- /dev/null +++ b/pop-api/src/v0/contracts.rs @@ -0,0 +1,156 @@ +use crate::{ + PopApiError, + PopApiError::UnknownStatusCode, +}; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum Error { + /// Invalid schedule supplied, e.g. with zero weight of a basic operation. + InvalidSchedule, + /// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`. + InvalidCallFlags, + /// The executed contract exhausted its gas limit. + OutOfGas, + /// The output buffer supplied to a contract API call was too small. + OutputBufferTooSmall, + /// Performing the requested transfer failed. Probably because there isn't enough + /// free balance in the sender's account. + TransferFailed, + /// Performing a call was denied because the calling depth reached the limit + /// of what is specified in the schedule. + MaxCallDepthReached, + /// No contract was found at the specified address. + ContractNotFound, + /// The code supplied to `instantiate_with_code` exceeds the limit specified in the + /// current schedule. + CodeTooLarge, + /// No code could be found at the supplied code hash. + CodeNotFound, + /// No code info could be found at the supplied code hash. + CodeInfoNotFound, + /// A buffer outside of sandbox memory was passed to a contract API function. + OutOfBounds, + /// Input passed to a contract API function failed to decode as expected type. + DecodingFailed, + /// Contract trapped during execution. + ContractTrapped, + /// The size defined in `T::MaxValueSize` was exceeded. + ValueTooLarge, + /// Termination of a contract is not allowed while the contract is already + /// on the call stack. Can be triggered by `seal_terminate`. + TerminatedWhileReentrant, + /// `seal_call` forwarded this contracts input. It therefore is no longer available. + InputForwarded, + /// The subject passed to `seal_random` exceeds the limit. + RandomSubjectTooLong, + /// The amount of topics passed to `seal_deposit_events` exceeds the limit. + TooManyTopics, + /// The chain does not provide a chain extension. Calling the chain extension results + /// in this error. Note that this usually shouldn't happen as deploying such contracts + /// is rejected. + NoChainExtension, + /// Failed to decode the XCM program. + XCMDecodeFailed, + /// A contract with the same AccountId already exists. + DuplicateContract, + /// A contract self destructed in its constructor. + /// + /// This can be triggered by a call to `seal_terminate`. + TerminatedInConstructor, + /// A call tried to invoke a contract that is flagged as non-reentrant. + /// The only other cause is that a call from a contract into the runtime tried to call back + /// into `pallet-contracts`. This would make the whole pallet reentrant with regard to + /// contract code execution which is not supported. + ReentranceDenied, + /// Origin doesn't have enough balance to pay the required storage deposits. + StorageDepositNotEnoughFunds, + /// More storage was created than allowed by the storage deposit limit. + StorageDepositLimitExhausted, + /// Code removal was denied because the code is still in use by at least one contract. + CodeInUse, + /// The contract ran to completion but decided to revert its storage changes. + /// Please note that this error is only returned from extrinsics. When called directly + /// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags + /// to determine whether a reversion has taken place. + ContractReverted, + /// The contract's code was found to be invalid during validation. + /// + /// The most likely cause of this is that an API was used which is not supported by the + /// node. This happens if an older node is used with a new version of ink!. Try updating + /// your node to the newest available version. + /// + /// A more detailed error can be found on the node console if debug messages are enabled + /// by supplying `-lruntime::contracts=debug`. + CodeRejected, + /// An indeterministic code was used in a context where this is not permitted. + Indeterministic, + /// A pending migration needs to complete before the extrinsic can be called. + MigrationInProgress, + /// Migrate dispatch call was attempted but no migration was performed. + NoMigrationPerformed, + /// The contract has reached its maximum number of delegate dependencies. + MaxDelegateDependenciesReached, + /// The dependency was not found in the contract's delegate dependencies. + DelegateDependencyNotFound, + /// The contract already depends on the given delegate dependency. + DelegateDependencyAlreadyExists, + /// Can not add a delegate dependency to the code hash of the contract itself. + CannotAddSelfAsDelegateDependency, +} + + +impl TryFrom for Error { + type Error = PopApiError; + + fn try_from(status_code: u32) -> core::result::Result { + use Error::*; + match status_code { + 0 => Ok(InvalidSchedule), + 1 => Ok(InvalidCallFlags), + 2 => Ok(OutOfGas), + 3 => Ok(OutputBufferTooSmall), + 4 => Ok(TransferFailed), + 5 => Ok(MaxCallDepthReached), + 6 => Ok(ContractNotFound), + 7 => Ok(CodeTooLarge), + 8 => Ok(CodeNotFound), + 9 => Ok(CodeInfoNotFound), + 10 => Ok(OutOfBounds), + 11 => Ok(DecodingFailed), + 12 => Ok(ContractTrapped), + 13 => Ok(ValueTooLarge), + 14 => Ok(TerminatedWhileReentrant), + 15 => Ok(InputForwarded), + 16 => Ok(RandomSubjectTooLong), + 17 => Ok(TooManyTopics), + 18 => Ok(NoChainExtension), + 19 => Ok(XCMDecodeFailed), + 20 => Ok(DuplicateContract), + 21 => Ok(TerminatedInConstructor), + 22 => Ok(ReentranceDenied), + 23 => Ok(StorageDepositNotEnoughFunds), + 24 => Ok(StorageDepositLimitExhausted), + 25 => Ok(CodeInUse), + 26 => Ok(ContractReverted), + 27 => Ok(CodeRejected), + 28 => Ok(Indeterministic), + 29 => Ok(MigrationInProgress), + 30 => Ok(NoMigrationPerformed), + 31 => Ok(MaxDelegateDependenciesReached), + 32 => Ok(DelegateDependencyNotFound), + 33 => Ok(DelegateDependencyAlreadyExists), + 34 => Ok(CannotAddSelfAsDelegateDependency), + _ => Err(UnknownStatusCode(status_code)), + } + } +} + +impl From for Error { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::Contracts(e) => e, + _ => panic!("expected balances error"), + } + } +} \ No newline at end of file diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index d914db24..def37e55 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -4,6 +4,7 @@ use crate::{ }; pub mod balances; +pub mod contracts; pub mod cross_chain; pub mod nfts; pub mod state; @@ -20,5 +21,5 @@ pub(crate) enum RuntimeCall { #[codec(index = 50)] Nfts(nfts::NftCalls), #[codec(index = 52)] - TrustBackedAssets(assets::trust_backed::TrustBackedAssetsCalls), + Assets(assets::fungibles::AssetsCall), } diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index b6f9adaa..1098b557 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -6,13 +6,25 @@ edition = "2021" [dependencies] bounded-collections = { version = "0.1", default-features = false } -scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } + +scale = { package = "parity-scale-codec", version = "3.6.9", default-features = false, features = ["derive"] } +scale-decode = { version = "0.10.0", default-features = false, features = ["derive"], optional = true } +scale-encode = { version = "0.5.0", default-features = false, features = ["derive"], optional = true } scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } +#scale = { workspace = true, features = ["max-encoded-len"] } +#scale-decode = { workspace = true, features = ["derive"], optional = true } +#scale-encode = { workspace = true, features = ["derive"], optional = true } +#scale-info = { workspace = true, features = ["derive"], optional = true } + [features] default = ["std"] std = [ "bounded-collections/std", "scale/std", + "scale-decode/std", + "scale-encode/std", "scale-info/std", ] +devnet = [] +testnet = [] \ No newline at end of file diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index ebad36d3..7c1672b8 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -1,10 +1,22 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] pub use bounded_collections::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec, ConstU32}; +use scale::{Decode, Encode, MaxEncodedLen}; +#[cfg(feature = "std")] +use { + scale_decode::DecodeAsType, + scale_encode::EncodeAsType, + scale_info::TypeInfo, +}; + pub mod cross_chain; pub mod storage_keys; +#[derive(Encode, Decode, Debug, MaxEncodedLen, Eq, PartialEq, Ord, PartialOrd)] +#[cfg_attr(feature = "std", derive(TypeInfo, DecodeAsType, EncodeAsType))] +pub struct AccountId(pub [u8; 32]); + // Identifier for the class of asset. pub type AssetId = u32; // Id used for identifying non-fungible collections. diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index a03b3a09..67448842 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -1,11 +1,12 @@ use super::*; -use scale::{Decode, Encode, MaxEncodedLen}; +// use scale::{Decode, Encode, MaxEncodedLen}; #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum RuntimeStateKeys { Nfts(NftsKeys), ParachainSystem(ParachainSystemKeys), - TrustBackedAssets(TrustBackedAssetsKeys), + #[cfg(feature = "devnet")] + Assets(AssetsKeys), } #[derive(Encode, Decode, Debug, MaxEncodedLen)] @@ -35,8 +36,15 @@ pub enum NftsKeys { CollectionAttribute(CollectionId, BoundedVec), } +/// The required input for state queries in pallet assets. +#[cfg(feature = "devnet")] #[derive(Encode, Decode, Debug, MaxEncodedLen)] -pub enum TrustBackedAssetsKeys { +pub enum AssetsKeys { + Allowance(AssetId, AccountId, AccountId), /// Check if the asset exists. AssetExists(AssetId), + /// Check balance. + BalanceOf(AssetId, AccountId), + /// Returns the total token supply for a given asset ID. + TotalSupply(AssetId), } diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index 55d9942d..d4fe2923 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -22,7 +22,7 @@ scale-info.workspace = true smallvec.workspace = true # Local -pop-primitives.workspace = true +pop-primitives = { workspace = true, default-features = false, features = ["devnet"] } pop-runtime-common = { workspace = true, default-features = false } # Substrate diff --git a/runtime/devnet/src/config/assets.rs b/runtime/devnet/src/config/assets.rs index f51f8875..2c8ea952 100644 --- a/runtime/devnet/src/config/assets.rs +++ b/runtime/devnet/src/config/assets.rs @@ -1,6 +1,6 @@ use crate::{ - deposit, AccountId, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, - RuntimeHoldReason, TrustBackedAssets, DAYS, EXISTENTIAL_DEPOSIT, UNIT, + deposit, AccountId, Assets, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, + RuntimeHoldReason, DAYS, EXISTENTIAL_DEPOSIT, UNIT, }; use frame_support::{ parameter_types, @@ -86,7 +86,7 @@ impl pallet_nft_fractionalization::Config for Runtime { type NftId = ::ItemId; type AssetBalance = >::Balance; type AssetId = >::AssetId; - type Assets = TrustBackedAssets; + type Assets = Assets; type Nfts = Nfts; type PalletId = NftFractionalizationPalletId; type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight; @@ -96,7 +96,7 @@ impl pallet_nft_fractionalization::Config for Runtime { } pub type TrustBackedAssetsInstance = pallet_assets::Instance1; -pub(crate) type TrustBackedAssetsCall = pallet_assets::Call; +pub(crate) type AssetsCall = pallet_assets::Call; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; diff --git a/runtime/devnet/src/config/mod.rs b/runtime/devnet/src/config/mod.rs index a3a64c92..c370bb1d 100644 --- a/runtime/devnet/src/config/mod.rs +++ b/runtime/devnet/src/config/mod.rs @@ -1,4 +1,4 @@ -mod assets; +pub(crate) mod assets; mod contracts; mod proxy; // Public due to integration tests crate. diff --git a/runtime/devnet/src/config/proxy.rs b/runtime/devnet/src/config/proxy.rs index a4fd479a..07d5f0f8 100644 --- a/runtime/devnet/src/config/proxy.rs +++ b/runtime/devnet/src/config/proxy.rs @@ -1,4 +1,4 @@ -use super::assets::TrustBackedAssetsCall; +use super::assets::AssetsCall; use crate::{Balances, Runtime, RuntimeCall, RuntimeEvent}; use frame_support::traits::InstanceFilter; use pop_runtime_common::proxy::{ @@ -34,16 +34,16 @@ impl InstanceFilter for ProxyType { }, ProxyType::AssetOwner => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) + RuntimeCall::Assets(AssetsCall::create { .. }) + | RuntimeCall::Assets(AssetsCall::start_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_accounts { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_approvals { .. }) + | RuntimeCall::Assets(AssetsCall::finish_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::transfer_ownership { .. }) + | RuntimeCall::Assets(AssetsCall::set_team { .. }) + | RuntimeCall::Assets(AssetsCall::set_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::clear_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::set_min_balance { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::create { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::destroy { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::redeposit { .. }) @@ -56,15 +56,15 @@ impl InstanceFilter for ProxyType { ), ProxyType::AssetManager => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) + RuntimeCall::Assets(AssetsCall::mint { .. }) + | RuntimeCall::Assets(AssetsCall::burn { .. }) + | RuntimeCall::Assets(AssetsCall::freeze { .. }) + | RuntimeCall::Assets(AssetsCall::block { .. }) + | RuntimeCall::Assets(AssetsCall::thaw { .. }) + | RuntimeCall::Assets(AssetsCall::freeze_asset { .. }) + | RuntimeCall::Assets(AssetsCall::thaw_asset { .. }) + | RuntimeCall::Assets(AssetsCall::touch_other { .. }) + | RuntimeCall::Assets(AssetsCall::refund_other { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::force_mint { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::update_mint_settings { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::mint_pre_signed { .. }) diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs deleted file mode 100644 index c8e88eb2..00000000 --- a/runtime/devnet/src/extensions.rs +++ /dev/null @@ -1,1018 +0,0 @@ -use cumulus_pallet_parachain_system::RelaychainDataProvider; -use frame_support::traits::{Contains, OriginTrait}; -use frame_support::{ - dispatch::{GetDispatchInfo, RawOrigin}, - pallet_prelude::*, - traits::{fungibles::Inspect, nonfungibles_v2::Inspect as NonFungiblesInspect}, -}; -use pallet_contracts::chain_extension::{ - BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, -}; -use pop_primitives::{ - cross_chain::CrossChainMessage, - storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys, TrustBackedAssetsKeys}, - AssetId, CollectionId, ItemId, -}; -use sp_core::crypto::UncheckedFrom; -use sp_runtime::{ - traits::{BlockNumberProvider, Dispatchable}, - DispatchError, -}; -use sp_std::{boxed::Box, vec::Vec}; -use xcm::{ - latest::{prelude::*, OriginKind::SovereignAccount}, - VersionedXcm, -}; - -use crate::{ - assets_config::TrustBackedAssetsInstance, AccountId, AllowedPopApiCalls, RuntimeCall, - RuntimeOrigin, UNIT, -}; - -const LOG_TARGET: &str = "pop-api::extension"; - -type ContractSchedule = ::Schedule; - -#[derive(Default)] -pub struct PopApiExtension; - -impl ChainExtension for PopApiExtension -where - T: pallet_contracts::Config - + pallet_xcm::Config - + pallet_assets::Config - + pallet_nfts::Config - + cumulus_pallet_parachain_system::Config - + frame_system::Config< - RuntimeOrigin = RuntimeOrigin, - AccountId = AccountId, - RuntimeCall = RuntimeCall, - >, - T::AccountId: UncheckedFrom + AsRef<[u8]>, -{ - fn call(&mut self, env: Environment) -> Result - where - E: Ext, - T::AccountId: UncheckedFrom + AsRef<[u8]>, - { - log::debug!(target:LOG_TARGET, " extension called "); - match v0::FuncId::try_from(env.func_id())? { - v0::FuncId::Dispatch => { - match dispatch::(env) { - Ok(()) => Ok(RetVal::Converging(0)), - Err(DispatchError::Module(error)) => { - // encode status code = pallet index in runtime + error index, allowing for - // 999 errors - Ok(RetVal::Converging( - (error.index as u32 * 1_000) + u32::from_le_bytes(error.error), - )) - }, - Err(e) => Err(e), - } - }, - v0::FuncId::ReadState => { - read_state::(env)?; - Ok(RetVal::Converging(0)) - }, - v0::FuncId::SendXcm => { - send_xcm::(env)?; - Ok(RetVal::Converging(0)) - }, - } - } -} - -pub mod v0 { - #[derive(Debug)] - pub enum FuncId { - Dispatch, - ReadState, - SendXcm, - } -} - -impl TryFrom for v0::FuncId { - type Error = DispatchError; - - fn try_from(func_id: u16) -> Result { - let id = match func_id { - 0x0 => Self::Dispatch, - 0x1 => Self::ReadState, - 0x2 => Self::SendXcm, - _ => { - log::error!("called an unregistered `func_id`: {:}", func_id); - return Err(DispatchError::Other("unimplemented func_id")); - }, - }; - - Ok(id) - } -} - -fn dispatch_call( - env: &mut Environment, - call: RuntimeCall, - mut origin: RuntimeOrigin, - log_prefix: &str, -) -> Result<(), DispatchError> -where - T: frame_system::Config, - RuntimeOrigin: From>, - E: Ext, -{ - let charged_dispatch_weight = env.charge_weight(call.get_dispatch_info().weight)?; - - log::debug!(target:LOG_TARGET, "{} inputted RuntimeCall: {:?}", log_prefix, call); - - origin.add_filter(AllowedPopApiCalls::contains); - - match call.dispatch(origin) { - Ok(info) => { - log::debug!(target:LOG_TARGET, "{} success, actual weight: {:?}", log_prefix, info.actual_weight); - - // refund weight if the actual weight is less than the charged weight - if let Some(actual_weight) = info.actual_weight { - env.adjust_weight(charged_dispatch_weight, actual_weight); - } - - Ok(()) - }, - Err(err) => { - log::debug!(target:LOG_TARGET, "{} failed: error: {:?}", log_prefix, err.error); - Err(err.error) - }, - } -} - -fn charge_overhead_weight( - env: &mut Environment, - len: u32, - log_prefix: &str, -) -> Result -where - T: pallet_contracts::Config, - E: Ext, -{ - let contract_host_weight = ContractSchedule::::get().host_fn_weights; - - // calculate weight for reading bytes of `len` - // reference: https://github.com/paritytech/polkadot-sdk/blob/117a9433dac88d5ac00c058c9b39c511d47749d2/substrate/frame/contracts/src/wasm/runtime.rs#L267 - let base_weight: Weight = contract_host_weight.return_per_byte.saturating_mul(len.into()); - - // debug_message weight is a good approximation of the additional overhead of going - // from contract layer to substrate layer. - // reference: https://github.com/paritytech/ink-examples/blob/b8d2caa52cf4691e0ddd7c919e4462311deb5ad0/psp22-extension/runtime/psp22-extension-example.rs#L236 - let overhead = contract_host_weight.debug_message; - - let charged_weight = env.charge_weight(base_weight.saturating_add(overhead))?; - log::debug!(target: LOG_TARGET, "{} charged weight: {:?}", log_prefix, charged_weight); - - Ok(charged_weight) -} - -fn dispatch(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config - + frame_system::Config, - RuntimeOrigin: From>, - E: Ext, -{ - const LOG_PREFIX: &str = " dispatch |"; - - let mut env = env.buf_in_buf_out(); - let len = env.in_len(); - - charge_overhead_weight::(&mut env, len, LOG_PREFIX)?; - - // read the input as RuntimeCall - let call: RuntimeCall = env.read_as_unbounded(len)?; - - // contract is the origin by default - let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into(); - - dispatch_call::(&mut env, call, origin, LOG_PREFIX) -} - -fn read_state(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config - + pallet_assets::Config - + pallet_nfts::Config - + cumulus_pallet_parachain_system::Config - + frame_system::Config, - E: Ext, -{ - const LOG_PREFIX: &str = " read_state |"; - - let mut env = env.buf_in_buf_out(); - - // To be conservative, we charge the weight for reading the input bytes of a fixed-size type. - let base_weight: Weight = ContractSchedule::::get() - .host_fn_weights - .return_per_byte - .saturating_mul(env.in_len().into()); - let charged_weight = env.charge_weight(base_weight)?; - - log::debug!(target:LOG_TARGET, "{} charged weight: {:?}", LOG_PREFIX, charged_weight); - - let key: RuntimeStateKeys = env.read_as()?; - - let result = match key { - RuntimeStateKeys::Nfts(key) => read_nfts_state::(key, &mut env), - RuntimeStateKeys::ParachainSystem(key) => { - read_parachain_system_state::(key, &mut env) - }, - RuntimeStateKeys::TrustBackedAssets(key) => { - read_trust_backed_assets_state::(key, &mut env) - }, - }? - .encode(); - - log::trace!( - target:LOG_TARGET, - "{} result: {:?}.", LOG_PREFIX, result - ); - env.write(&result, false, None).map_err(|e| { - log::trace!(target: LOG_TARGET, "{:?}", e); - DispatchError::Other("unable to write results to contract memory") - }) -} - -fn read_parachain_system_state( - key: ParachainSystemKeys, - env: &mut Environment, -) -> Result, DispatchError> -where - T: pallet_contracts::Config + cumulus_pallet_parachain_system::Config, - E: Ext, -{ - match key { - ParachainSystemKeys::LastRelayChainBlockNumber => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(RelaychainDataProvider::::current_block_number().encode()) - }, - } -} - -fn read_nfts_state( - key: NftsKeys, - env: &mut Environment, -) -> Result, DispatchError> -where - T: pallet_contracts::Config + pallet_nfts::Config, - E: Ext, -{ - match key { - NftsKeys::Collection(collection) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_nfts::Collection::::get(collection).encode()) - }, - NftsKeys::CollectionOwner(collection) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_nfts::Pallet::::collection_owner(collection).encode()) - }, - NftsKeys::Item(collection, item) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_nfts::Item::::get(collection, item).encode()) - }, - NftsKeys::Owner(collection, item) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_nfts::Pallet::::owner(collection, item).encode()) - }, - NftsKeys::Attribute(collection, item, key) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_nfts::Pallet::::attribute(&collection, &item, &key).encode()) - }, - // NftsKeys::CustomAttribute(account, collection, item, key) => { - // env.charge_weight(T::DbWeight::get().reads(1_u64))?; - // Ok(pallet_nfts::Pallet::::custom_attribute(&account, &collection, &item, &key) - // .encode()) - // }, - NftsKeys::SystemAttribute(collection, item, key) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_nfts::Pallet::::system_attribute(&collection, item.as_ref(), &key) - .encode()) - }, - NftsKeys::CollectionAttribute(collection, key) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_nfts::Pallet::::collection_attribute(&collection, &key).encode()) - }, - } -} - -fn read_trust_backed_assets_state( - key: TrustBackedAssetsKeys, - env: &mut Environment, -) -> Result, DispatchError> -where - T: pallet_contracts::Config - + pallet_assets::Config, - E: Ext, -{ - match key { - TrustBackedAssetsKeys::AssetExists(id) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_assets::Pallet::::asset_exists(id).encode()) - }, - } -} - -fn send_xcm(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config - + frame_system::Config< - RuntimeOrigin = RuntimeOrigin, - AccountId = AccountId, - RuntimeCall = RuntimeCall, - >, - E: Ext, -{ - const LOG_PREFIX: &str = " send_xcm |"; - - let mut env = env.buf_in_buf_out(); - let len = env.in_len(); - - let _ = charge_overhead_weight::(&mut env, len, LOG_PREFIX)?; - - // read the input as CrossChainMessage - let xc_call: CrossChainMessage = env.read_as::()?; - - // Determine the call to dispatch - let (dest, message) = match xc_call { - CrossChainMessage::Relay(message) => { - let dest = Location::parent().into_versioned(); - let assets: Asset = (Here, 10 * UNIT).into(); - let beneficiary: Location = - AccountId32 { id: (env.ext().address().clone()).into(), network: None }.into(); - let message = Xcm::builder() - .withdraw_asset(assets.clone().into()) - .buy_execution(assets.clone(), Unlimited) - .transact( - SovereignAccount, - Weight::from_parts(250_000_000, 10_000), - message.encode().into(), - ) - .refund_surplus() - .deposit_asset(assets.into(), beneficiary) - .build(); - (dest, message) - }, - }; - - // TODO: revisit to replace with signed contract origin - let origin: RuntimeOrigin = RawOrigin::Root.into(); - - // Generate runtime call to dispatch - let call = RuntimeCall::PolkadotXcm(pallet_xcm::Call::send { - dest: Box::new(dest), - message: Box::new(VersionedXcm::V4(message)), - }); - - dispatch_call::(&mut env, call, origin, LOG_PREFIX) -} - -#[cfg(test)] -mod tests { - pub use super::*; - pub use crate::*; - use enumflags2::BitFlags; - pub use pallet_contracts::Code; - use pallet_nfts::{CollectionConfig, CollectionSetting, CollectionSettings, MintSettings}; - use parachains_common::CollectionId; - pub use sp_runtime::{traits::Hash, AccountId32}; - - const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; - - const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); - const BOB: AccountId32 = AccountId32::new([2_u8; 32]); - const INITIAL_AMOUNT: u128 = 100_000 * UNIT; - const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); - - fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default() - .build_storage() - .expect("Frame system builds valid default genesis config"); - - pallet_balances::GenesisConfig:: { - balances: vec![(ALICE, INITIAL_AMOUNT), (BOB, INITIAL_AMOUNT)], - } - .assimilate_storage(&mut t) - .expect("Pallet balances storage can be assimilated"); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext - } - - fn load_wasm_module(path: &str) -> std::io::Result<(Vec, ::Output)> - where - T: frame_system::Config, - { - let wasm_binary = std::fs::read(path)?; - let code_hash = T::Hashing::hash(&wasm_binary); - Ok((wasm_binary, code_hash)) - } - - fn function_selector(name: &str) -> Vec { - let hash = sp_io::hashing::blake2_256(name.as_bytes()); - [hash[0..4].to_vec()].concat() - } - - // NFT helper functions - fn collection_config_from_disabled_settings( - settings: BitFlags, - ) -> CollectionConfig { - CollectionConfig { - settings: CollectionSettings::from_disabled(settings), - max_supply: None, - mint_settings: MintSettings::default(), - } - } - - fn default_collection_config() -> CollectionConfig { - collection_config_from_disabled_settings(CollectionSetting::DepositRequired.into()) - } - - #[test] - #[ignore] - fn dispatch_balance_transfer_from_contract_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = load_wasm_module::( - "../../pop-api/examples/balance-transfer/target/ink/balance_transfer.wasm", - ) - .unwrap(); - - let init_value = 100 * UNIT; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - - let addr = result.account_id; - - let function = function_selector("transfer_through_runtime"); - let value_to_send: u128 = 10 * UNIT; - let params = [function, BOB.encode(), value_to_send.encode()].concat(); - - let bob_balance_before = Balances::free_balance(&BOB); - assert_eq!(bob_balance_before, INITIAL_AMOUNT); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // check for revert - assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); - - let bob_balance_after = Balances::free_balance(&BOB); - assert_eq!(bob_balance_before + value_to_send, bob_balance_after); - }); - } - - // Create a test for tesing create_nft_collection - #[test] - #[ignore] - fn dispatch_nfts_create_nft_collection() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = load_wasm_module::( - "../../pop-api/examples/nfts/target/ink/pop_api_nft_example.wasm", - ) - .unwrap(); - - let init_value = 100 * UNIT; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - - let addr = result.account_id; - - let function = function_selector("create_nft_collection"); - - let params = [function].concat(); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // check that the nft collection was created - assert_eq!(Nfts::collection_owner(0), Some(addr.clone().into())); - - // test reading the collection - let function = function_selector("read_collection"); - - let params = [function, 0.encode()].concat(); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // assert that the collection was read successfully - assert_eq!(result.result.clone().unwrap().data, vec![1, 1]); - }); - } - - #[test] - #[ignore] - fn dispatch_nfts_mint_from_contract_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = - load_wasm_module::("../../pop-api/examples/nfts/target/ink/nfts.wasm") - .unwrap(); - - let init_value = 100; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - - let addr = result.account_id; - - let collection_id: u32 = 0; - let item_id: u32 = 1; - - // create nft collection with contract as owner - assert_eq!( - Nfts::force_create( - RuntimeOrigin::root(), - addr.clone().into(), - default_collection_config() - ), - Ok(()) - ); - - assert_eq!(Nfts::collection_owner(collection_id), Some(addr.clone().into())); - // assert that the item does not exist yet - assert_eq!(Nfts::owner(collection_id, item_id), None); - - let function = function_selector("mint_through_runtime"); - - let params = - [function, collection_id.encode(), item_id.encode(), BOB.encode()].concat(); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // check for revert - assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); - - assert_eq!(Nfts::owner(collection_id, item_id), Some(BOB.into())); - }); - } - - #[test] - #[ignore] - fn nfts_mint_surfaces_error() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = - load_wasm_module::("../../pop-api/examples/nfts/target/ink/nfts.wasm") - .unwrap(); - - let init_value = 100; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - - let addr = result.account_id; - - let collection_id: u32 = 0; - let item_id: u32 = 1; - - let function = function_selector("mint_through_runtime"); - - let params = - [function, collection_id.encode(), item_id.encode(), BOB.encode()].concat(); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // check for revert with expected error - let result = result.result.unwrap(); - assert!(result.did_revert()); - }); - } - - #[test] - #[ignore] - fn reading_last_relay_chain_block_number_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = load_wasm_module::( - "../../pop-api/examples/read-runtime-state/target/ink/read_relay_blocknumber.wasm", - ) - .unwrap(); - - let init_value = 100; - - let contract = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!contract.result.did_revert(), "deploying contract reverted {:?}", contract); - - let addr = contract.account_id; - - let function = function_selector("read_relay_block_number"); - let params = [function].concat(); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::UnsafeCollect, - pallet_contracts::Determinism::Relaxed, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // check for revert - assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); - }); - } - - #[test] - #[ignore] - fn place_spot_order_from_contract_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = load_wasm_module::( - "../../pop-api/examples/place-spot-order/target/ink/spot_order.wasm", - ) - .unwrap(); - - let init_value = 100 * UNIT; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - - let addr = result.account_id; - - let function = function_selector("place_spot_order"); - - let max_amount = 1 * UNIT; - let para_id = 2000; - - let params = [function, max_amount.encode(), para_id.encode()].concat(); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // check for revert - assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); - }); - } - - #[test] - #[ignore] - fn dispatch_trust_backed_assets_mint_from_contract_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = load_wasm_module::( - "../../pop-api/examples/trust_backed_assets/target/ink/pop_api_trust_backed_assets_example.wasm", - ) - .unwrap(); - - let init_value = 100; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - let addr = result.account_id; - - let asset_id: u32 = 1; - let min_balance = 1; - let amount: u128 = 100 * UNIT; - let function = function_selector("mint_asset_through_runtime"); - let params = [function, asset_id.encode(), BOB.encode(), amount.encode()].concat(); - - // Mint asset which does not exist. - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - GAS_LIMIT, - None, - params.clone(), - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // Check for revert. - assert!(result.result.unwrap().did_revert(), "Contract should have been reverted!"); - - // Create asset with contract as owner. - assert_eq!( - TrustBackedAssets::force_create( - RuntimeOrigin::root(), - asset_id.into(), - addr.clone().into(), - true, - min_balance, - ), - Ok(()) - ); - - // Check Bob's asset balance before minting through contract. - let bob_balance_before = TrustBackedAssets::balance(asset_id, &BOB); - assert_eq!(bob_balance_before, 0); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - GAS_LIMIT, - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // Check for revert - assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); - - let bob_balance_after = TrustBackedAssets::balance(asset_id, &BOB); - assert_eq!(bob_balance_after, bob_balance_before + amount); - }); - } - - #[test] - #[ignore] - fn allow_call_filter_blocks_call() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = load_wasm_module::( - "../../tests/contracts/filtered-call/target/ink/pop_api_filtered_call.wasm", - ) - .unwrap(); - - let init_value = 100 * UNIT; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - - let addr = result.account_id; - - let function = function_selector("get_filtered"); - let params = [function].concat(); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("filtered result: {:?}", result); - } - - // check for revert - assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); - }); - } -} diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs new file mode 100644 index 00000000..096f21c9 --- /dev/null +++ b/runtime/devnet/src/extensions/mod.rs @@ -0,0 +1,896 @@ +use cumulus_pallet_parachain_system::RelaychainDataProvider; +use frame_support::traits::{Contains, OriginTrait}; +use frame_support::{ + dispatch::{GetDispatchInfo, RawOrigin}, + pallet_prelude::*, + traits::{ + fungibles::{approvals::Inspect as ApprovalInspect, Inspect}, + nonfungibles_v2::Inspect as NonFungiblesInspect, + }, +}; +use pallet_contracts::chain_extension::{ + BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, +}; +use pop_primitives::{ + cross_chain::CrossChainMessage, + storage_keys::{AssetsKeys, NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, + AssetId, CollectionId, ItemId, +}; +use sp_core::crypto::UncheckedFrom; +use sp_runtime::{ + traits::{BlockNumberProvider, Dispatchable}, + DispatchError, +}; +use sp_std::{boxed::Box, vec::Vec}; +use xcm::{ + latest::{prelude::*, OriginKind::SovereignAccount}, + VersionedXcm, +}; + +use crate::{ + config::assets::TrustBackedAssetsInstance, AccountId, AllowedPopApiCalls, RuntimeCall, + RuntimeOrigin, UNIT, +}; + +#[cfg(test)] +mod tests; + +const LOG_TARGET: &str = "pop-api::extension"; + +type ContractSchedule = ::Schedule; + +#[derive(Default)] +pub struct PopApiExtension; + +impl ChainExtension for PopApiExtension +where + T: pallet_contracts::Config + + pallet_xcm::Config + + pallet_assets::Config + + pallet_nfts::Config + + cumulus_pallet_parachain_system::Config + + frame_system::Config< + RuntimeOrigin = RuntimeOrigin, + AccountId = AccountId, + RuntimeCall = RuntimeCall, + >, + T::AccountId: UncheckedFrom + AsRef<[u8]>, +{ + fn call(&mut self, env: Environment) -> Result + where + E: Ext, + // T::AccountId: UncheckedFrom + AsRef<[u8]>, + { + log::debug!(target:LOG_TARGET, " extension called "); + match v0::FuncId::try_from(env.func_id())? { + v0::FuncId::Dispatch => { + match dispatch::(env) { + Ok(()) => Ok(RetVal::Converging(0)), + Err(DispatchError::Module(error)) => { + // encode status code = pallet index in runtime + error index, allowing for + // 999 errors + Ok(RetVal::Converging( + (error.index as u32 * 1_000) + u32::from_le_bytes(error.error), + )) + }, + Err(e) => Err(e), + } + }, + v0::FuncId::ReadState => { + read_state::(env)?; + Ok(RetVal::Converging(0)) + }, + v0::FuncId::SendXcm => { + send_xcm::(env)?; + Ok(RetVal::Converging(0)) + }, + } + } +} + +pub mod v0 { + #[derive(Debug)] + pub enum FuncId { + Dispatch, + ReadState, + SendXcm, + } +} + +impl TryFrom for v0::FuncId { + type Error = DispatchError; + + fn try_from(func_id: u16) -> Result { + let id = match func_id { + 0x0 => Self::Dispatch, + 0x1 => Self::ReadState, + 0x2 => Self::SendXcm, + _ => { + log::error!("called an unregistered `func_id`: {:}", func_id); + return Err(DispatchError::Other("unimplemented func_id")); + }, + }; + + Ok(id) + } +} + +fn dispatch_call( + env: &mut Environment, + call: RuntimeCall, + mut origin: RuntimeOrigin, + log_prefix: &str, +) -> Result<(), DispatchError> +where + T: frame_system::Config, + RuntimeOrigin: From>, + E: Ext, +{ + let charged_dispatch_weight = env.charge_weight(call.get_dispatch_info().weight)?; + + log::debug!(target:LOG_TARGET, "{} Inputted RuntimeCall: {:?}", log_prefix, call); + + origin.add_filter(AllowedPopApiCalls::contains); + + match call.dispatch(origin) { + Ok(info) => { + log::debug!(target:LOG_TARGET, "{} success, actual weight: {:?}", log_prefix, info.actual_weight); + + // refund weight if the actual weight is less than the charged weight + if let Some(actual_weight) = info.actual_weight { + env.adjust_weight(charged_dispatch_weight, actual_weight); + } + + Ok(()) + }, + Err(err) => { + log::debug!(target:LOG_TARGET, "{} failed: error: {:?}", log_prefix, err.error); + Err(err.error) + }, + } +} + +fn charge_overhead_weight( + env: &mut Environment, + len: u32, + log_prefix: &str, +) -> Result +where + T: pallet_contracts::Config, + E: Ext, +{ + let contract_host_weight = ContractSchedule::::get().host_fn_weights; + + // calculate weight for reading bytes of `len` + // reference: https://github.com/paritytech/polkadot-sdk/blob/117a9433dac88d5ac00c058c9b39c511d47749d2/substrate/frame/contracts/src/wasm/runtime.rs#L267 + let base_weight: Weight = contract_host_weight.return_per_byte.saturating_mul(len.into()); + + // debug_message weight is a good approximation of the additional overhead of going + // from contract layer to substrate layer. + // reference: https://github.com/paritytech/ink-examples/blob/b8d2caa52cf4691e0ddd7c919e4462311deb5ad0/psp22-extension/runtime/psp22-extension-example.rs#L236 + let overhead = contract_host_weight.debug_message; + + let charged_weight = env.charge_weight(base_weight.saturating_add(overhead))?; + log::debug!(target: LOG_TARGET, "{} charged weight: {:?}", log_prefix, charged_weight); + + Ok(charged_weight) +} + +fn dispatch(env: Environment) -> Result<(), DispatchError> +where + T: pallet_contracts::Config + + frame_system::Config, + RuntimeOrigin: From>, + E: Ext, +{ + const LOG_PREFIX: &str = " dispatch |"; + + let mut env = env.buf_in_buf_out(); + let len = env.in_len(); + + charge_overhead_weight::(&mut env, len, LOG_PREFIX)?; + + // read the input as RuntimeCall + let call: RuntimeCall = env.read_as_unbounded(len)?; + + log::debug!(target: LOG_TARGET, "Read input as call successfully"); + + // contract is the origin by default + let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into(); + + dispatch_call::(&mut env, call, origin, LOG_PREFIX) +} + +fn read_state(env: Environment) -> Result<(), DispatchError> +where + T: pallet_contracts::Config + + pallet_assets::Config + + pallet_nfts::Config + + cumulus_pallet_parachain_system::Config + + frame_system::Config, + E: Ext, +{ + const LOG_PREFIX: &str = " read_state |"; + + let mut env = env.buf_in_buf_out(); + + // To be conservative, we charge the weight for reading the input bytes of a fixed-size type. + let base_weight: Weight = ContractSchedule::::get() + .host_fn_weights + .return_per_byte + .saturating_mul(env.in_len().into()); + let charged_weight = env.charge_weight(base_weight)?; + + log::debug!(target:LOG_TARGET, "{} charged weight: {:?}", LOG_PREFIX, charged_weight); + + let key: RuntimeStateKeys = env.read_as()?; + + let result = match key { + RuntimeStateKeys::Nfts(key) => read_nfts_state::(key, &mut env), + RuntimeStateKeys::ParachainSystem(key) => { + read_parachain_system_state::(key, &mut env) + }, + RuntimeStateKeys::Assets(key) => read_trust_backed_assets_state::(key, &mut env), + }? + .encode(); + + log::trace!( + target:LOG_TARGET, + "{} result: {:?}.", LOG_PREFIX, result + ); + env.write(&result, false, None).map_err(|e| { + log::trace!(target: LOG_TARGET, "{:?}", e); + DispatchError::Other("unable to write results to contract memory") + }) +} + +fn read_parachain_system_state( + key: ParachainSystemKeys, + env: &mut Environment, +) -> Result, DispatchError> +where + T: pallet_contracts::Config + cumulus_pallet_parachain_system::Config, + E: Ext, +{ + match key { + ParachainSystemKeys::LastRelayChainBlockNumber => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(RelaychainDataProvider::::current_block_number().encode()) + }, + } +} + +fn read_nfts_state( + key: NftsKeys, + env: &mut Environment, +) -> Result, DispatchError> +where + T: pallet_contracts::Config + pallet_nfts::Config, + E: Ext, +{ + match key { + NftsKeys::Collection(collection) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_nfts::Collection::::get(collection).encode()) + }, + NftsKeys::CollectionOwner(collection) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_nfts::Pallet::::collection_owner(collection).encode()) + }, + NftsKeys::Item(collection, item) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_nfts::Item::::get(collection, item).encode()) + }, + NftsKeys::Owner(collection, item) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_nfts::Pallet::::owner(collection, item).encode()) + }, + NftsKeys::Attribute(collection, item, key) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_nfts::Pallet::::attribute(&collection, &item, &key).encode()) + }, + // NftsKeys::CustomAttribute(account, collection, item, key) => { + // env.charge_weight(T::DbWeight::get().reads(1_u64))?; + // Ok(pallet_nfts::Pallet::::custom_attribute(&account, &collection, &item, &key) + // .encode()) + // }, + NftsKeys::SystemAttribute(collection, item, key) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_nfts::Pallet::::system_attribute(&collection, item.as_ref(), &key) + .encode()) + }, + NftsKeys::CollectionAttribute(collection, key) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_nfts::Pallet::::collection_attribute(&collection, &key).encode()) + }, + } +} + +fn read_trust_backed_assets_state( + key: AssetsKeys, + env: &mut Environment, +) -> Result, DispatchError> +where + T: pallet_contracts::Config + + pallet_assets::Config, + E: Ext, + T: frame_system::Config, +{ + match key { + AssetsKeys::Allowance(id, owner, spender) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::allowance( + id, + &owner.0.into(), + &spender.0.into(), + ) + .encode()) + }, + AssetsKeys::AssetExists(id) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::asset_exists(id).encode()) + }, + AssetsKeys::BalanceOf(id, owner) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::balance(id, &owner.0.into()) + .encode()) + }, + AssetsKeys::TotalSupply(id) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::total_supply(id).encode()) + }, + } +} + +fn send_xcm(env: Environment) -> Result<(), DispatchError> +where + T: pallet_contracts::Config + + frame_system::Config< + RuntimeOrigin = RuntimeOrigin, + AccountId = AccountId, + RuntimeCall = RuntimeCall, + >, + E: Ext, +{ + const LOG_PREFIX: &str = " send_xcm |"; + + let mut env = env.buf_in_buf_out(); + let len = env.in_len(); + + let _ = charge_overhead_weight::(&mut env, len, LOG_PREFIX)?; + + // read the input as CrossChainMessage + let xc_call: CrossChainMessage = env.read_as::()?; + + // Determine the call to dispatch + let (dest, message) = match xc_call { + CrossChainMessage::Relay(message) => { + let dest = Location::parent().into_versioned(); + let assets: Asset = (Here, 10 * UNIT).into(); + let beneficiary: Location = + AccountId32 { id: (env.ext().address().clone()).into(), network: None }.into(); + let message = Xcm::builder() + .withdraw_asset(assets.clone().into()) + .buy_execution(assets.clone(), Unlimited) + .transact( + SovereignAccount, + Weight::from_parts(250_000_000, 10_000), + message.encode().into(), + ) + .refund_surplus() + .deposit_asset(assets.into(), beneficiary) + .build(); + (dest, message) + }, + }; + + // TODO: revisit to replace with signed contract origin + let origin: RuntimeOrigin = RawOrigin::Root.into(); + + // Generate runtime call to dispatch + let call = RuntimeCall::PolkadotXcm(pallet_xcm::Call::send { + dest: Box::new(dest), + message: Box::new(VersionedXcm::V4(message)), + }); + + dispatch_call::(&mut env, call, origin, LOG_PREFIX) +} + +// use enumflags2::BitFlags; +// use pallet_nfts::{CollectionConfig, CollectionSetting, CollectionSettings, MintSettings}; +// use parachains_common::CollectionId; +// { +// // NFT helper functions +// fn collection_config_from_disabled_settings( +// settings: BitFlags, +// ) -> CollectionConfig { +// CollectionConfig { +// settings: CollectionSettings::from_disabled(settings), +// max_supply: None, +// mint_settings: MintSettings::default(), +// } +// } +// +// fn default_collection_config() -> CollectionConfig { +// collection_config_from_disabled_settings(CollectionSetting::DepositRequired.into()) +// } +// +// #[test] +// #[ignore] +// fn dispatch_balance_transfer_from_contract_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// +// let (wasm_binary, _) = load_wasm_module::( +// "../../pop-api/examples/balance-transfer/target/ink/balance_transfer.wasm", +// ) +// .unwrap(); +// +// let init_value = 100 * UNIT; +// +// let result = Contracts::bare_instantiate( +// ALICE, +// init_value, +// GAS_LIMIT, +// None, +// Code::Upload(wasm_binary), +// function_selector("new"), +// vec![], +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// ) +// .result +// .unwrap(); +// +// assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); +// +// let addr = result.account_id; +// +// let function = function_selector("transfer_through_runtime"); +// let value_to_send: u128 = 10 * UNIT; +// let params = [function, BOB.encode(), value_to_send.encode()].concat(); +// +// let bob_balance_before = Balances::free_balance(&BOB); +// assert_eq!(bob_balance_before, INITIAL_AMOUNT); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// pallet_contracts::Determinism::Enforced, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("result: {:?}", result); +// } +// +// // check for revert +// assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); +// +// let bob_balance_after = Balances::free_balance(&BOB); +// assert_eq!(bob_balance_before + value_to_send, bob_balance_after); +// }); +// } +// +// // Create a test for tesing create_nft_collection +// #[test] +// #[ignore] +// fn dispatch_nfts_create_nft_collection() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// +// let (wasm_binary, _) = load_wasm_module::( +// "../../pop-api/examples/nfts/target/ink/pop_api_nft_example.wasm", +// ) +// .unwrap(); +// +// let init_value = 100 * UNIT; +// +// let result = Contracts::bare_instantiate( +// ALICE, +// init_value, +// GAS_LIMIT, +// None, +// Code::Upload(wasm_binary), +// function_selector("new"), +// vec![], +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// ) +// .result +// .unwrap(); +// +// assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); +// +// let addr = result.account_id; +// +// let function = function_selector("create_nft_collection"); +// +// let params = [function].concat(); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// pallet_contracts::Determinism::Enforced, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("result: {:?}", result); +// } +// +// // check that the nft collection was created +// assert_eq!(Nfts::collection_owner(0), Some(addr.clone().into())); +// +// // test reading the collection +// let function = function_selector("read_collection"); +// +// let params = [function, 0.encode()].concat(); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// pallet_contracts::Determinism::Enforced, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("result: {:?}", result); +// } +// +// // assert that the collection was read successfully +// assert_eq!(result.result.clone().unwrap().data, vec![1, 1]); +// }); +// } +// +// #[test] +// #[ignore] +// fn dispatch_nfts_mint_from_contract_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// +// let (wasm_binary, _) = +// load_wasm_module::("../../pop-api/examples/nfts/target/ink/nfts.wasm") +// .unwrap(); +// +// let init_value = 100; +// +// let result = Contracts::bare_instantiate( +// ALICE, +// init_value, +// GAS_LIMIT, +// None, +// Code::Upload(wasm_binary), +// function_selector("new"), +// vec![], +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// ) +// .result +// .unwrap(); +// +// assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); +// +// let addr = result.account_id; +// +// let collection_id: u32 = 0; +// let item_id: u32 = 1; +// +// // create nft collection with contract as owner +// assert_eq!( +// Nfts::force_create( +// RuntimeOrigin::root(), +// addr.clone().into(), +// default_collection_config() +// ), +// Ok(()) +// ); +// +// assert_eq!(Nfts::collection_owner(collection_id), Some(addr.clone().into())); +// // assert that the item does not exist yet +// assert_eq!(Nfts::owner(collection_id, item_id), None); +// +// let function = function_selector("mint_through_runtime"); +// +// let params = +// [function, collection_id.encode(), item_id.encode(), BOB.encode()].concat(); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// pallet_contracts::Determinism::Enforced, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("result: {:?}", result); +// } +// +// // check for revert +// assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); +// +// assert_eq!(Nfts::owner(collection_id, item_id), Some(BOB.into())); +// }); +// } +// +// #[test] +// #[ignore] +// fn nfts_mint_surfaces_error() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// +// let (wasm_binary, _) = +// load_wasm_module::("../../pop-api/examples/nfts/target/ink/nfts.wasm") +// .unwrap(); +// +// let init_value = 100; +// +// let result = Contracts::bare_instantiate( +// ALICE, +// init_value, +// GAS_LIMIT, +// None, +// Code::Upload(wasm_binary), +// function_selector("new"), +// vec![], +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// ) +// .result +// .unwrap(); +// +// assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); +// +// let addr = result.account_id; +// +// let collection_id: u32 = 0; +// let item_id: u32 = 1; +// +// let function = function_selector("mint_through_runtime"); +// +// let params = +// [function, collection_id.encode(), item_id.encode(), BOB.encode()].concat(); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// pallet_contracts::Determinism::Enforced, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("result: {:?}", result); +// } +// +// // check for revert with expected error +// let result = result.result.unwrap(); +// assert!(result.did_revert()); +// }); +// } +// +// #[test] +// #[ignore] +// fn reading_last_relay_chain_block_number_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// +// let (wasm_binary, _) = load_wasm_module::( +// "../../pop-api/examples/read-runtime-state/target/ink/read_relay_blocknumber.wasm", +// ) +// .unwrap(); +// +// let init_value = 100; +// +// let contract = Contracts::bare_instantiate( +// ALICE, +// init_value, +// GAS_LIMIT, +// None, +// Code::Upload(wasm_binary), +// function_selector("new"), +// vec![], +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// ) +// .result +// .unwrap(); +// +// assert!(!contract.result.did_revert(), "deploying contract reverted {:?}", contract); +// +// let addr = contract.account_id; +// +// let function = function_selector("read_relay_block_number"); +// let params = [function].concat(); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::UnsafeCollect, +// pallet_contracts::Determinism::Relaxed, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("result: {:?}", result); +// } +// +// // check for revert +// assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); +// }); +// } +// +// #[test] +// #[ignore] +// fn place_spot_order_from_contract_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// +// let (wasm_binary, _) = load_wasm_module::( +// "../../pop-api/examples/place-spot-order/target/ink/spot_order.wasm", +// ) +// .unwrap(); +// +// let init_value = 100 * UNIT; +// +// let result = Contracts::bare_instantiate( +// ALICE, +// init_value, +// GAS_LIMIT, +// None, +// Code::Upload(wasm_binary), +// function_selector("new"), +// vec![], +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// ) +// .result +// .unwrap(); +// +// assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); +// +// let addr = result.account_id; +// +// let function = function_selector("place_spot_order"); +// +// let max_amount = 1 * UNIT; +// let para_id = 2000; +// +// let params = [function, max_amount.encode(), para_id.encode()].concat(); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// pallet_contracts::Determinism::Enforced, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("result: {:?}", result); +// } +// +// // check for revert +// assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); +// }); +// } +// +// #[test] +// #[ignore] +// fn allow_call_filter_blocks_call() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// +// let (wasm_binary, _) = load_wasm_module::( +// "../../tests/contracts/filtered-call/target/ink/pop_api_filtered_call.wasm", +// ) +// .unwrap(); +// +// let init_value = 100 * UNIT; +// +// let result = Contracts::bare_instantiate( +// ALICE, +// init_value, +// GAS_LIMIT, +// None, +// Code::Upload(wasm_binary), +// function_selector("new"), +// vec![], +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// ) +// .result +// .unwrap(); +// +// assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); +// +// let addr = result.account_id; +// +// let function = function_selector("get_filtered"); +// let params = [function].concat(); +// +// let result = Contracts::bare_call( +// ALICE, +// addr.clone(), +// 0, +// Weight::from_parts(100_000_000_000, 3 * 1024 * 1024), +// None, +// params, +// DEBUG_OUTPUT, +// pallet_contracts::CollectEvents::Skip, +// pallet_contracts::Determinism::Enforced, +// ); +// +// if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { +// log::debug!( +// "Contract debug buffer - {:?}", +// String::from_utf8(result.debug_message.clone()) +// ); +// log::debug!("filtered result: {:?}", result); +// } +// +// // check for revert +// assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); +// }); +// } +// } diff --git a/runtime/devnet/src/extensions/tests/local_fungibles.rs b/runtime/devnet/src/extensions/tests/local_fungibles.rs new file mode 100644 index 00000000..2d752361 --- /dev/null +++ b/runtime/devnet/src/extensions/tests/local_fungibles.rs @@ -0,0 +1,302 @@ +#![cfg(test)] + +use super::*; +use pallet_contracts::debug::ExecResult; + +#[derive(Decode, Encode, Debug, Eq, PartialEq)] +enum FungiblesError { + // AssetsError(Error), + // /// The origin of the call doesn't have the right permission. + // BadOrigin, + // /// Custom error type for cases in which an implementation adds its own restrictions. + // Custom(String), + /// Not enough balance to fulfill a request is available. + InsufficientBalance, + /// Not enough allowance to fulfill a request is available. + InsufficientAllowance, + /// The asset status is not the expected status. + IncorrectStatus, + /// The asset ID is already taken. + InUse, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// The signing account has no permission to do the operation. + NoPermission, + // /// Safe transfer check fails (e.g. if the receiving contract does not accept tokens). + // SafeTransferCheckFailed(String), + /// The given asset ID is unknown. + Unknown, + /// Recipient's address is zero. + ZeroRecipientAddress, + /// Sender's address is zero. + ZeroSenderAddress, + UndefinedError, +} + +const ASSET_ID: u32 = 1; + +fn allowance( + addr: AccountId32, + asset_id: u32, + owner: AccountId32, + spender: AccountId32, +) -> ExecReturnValue { + let function = function_selector("allowance"); + let params = [function, asset_id.encode(), owner.encode(), spender.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + +// Call balance_of contract message. +fn balance_of(addr: AccountId32, asset_id: u32, owner: AccountId32) -> ExecReturnValue { + let function = function_selector("balance_of"); + let params = [function, asset_id.encode(), owner.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + +// Call total_supply contract message. +fn total_supply(addr: AccountId32, asset_id: u32) -> ExecReturnValue { + let function = function_selector("total_supply"); + let params = [function, asset_id.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + +fn asset_exists(addr: AccountId32, asset_id: u32) -> ExecReturnValue { + let function = function_selector("asset_exists"); + let params = [function, asset_id.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + +fn create( + addr: AccountId32, + asset_id: u32, + admin: AccountId32, + min_balance: u128, +) -> ExecReturnValue { + let function = function_selector("create"); + let params = [function, asset_id.encode(), admin.encode(), min_balance.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + +fn set_metadata( + addr: AccountId32, + asset_id: u32, + name: Vec, + symbol: Vec, + decimals: u8, +) -> ExecReturnValue { + let function = function_selector("set_metadata"); + let params = + [function, asset_id.encode(), name.encode(), symbol.encode(), decimals.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + +fn transfer_from( + addr: AccountId32, + asset_id: u32, + _from: Option, + to: Option, + value: u128, + _data: &[u8], +) -> ExecReturnValue { + // let function = function_selector("transfer_from"); + // let params = + // [function, asset_id.encode(), from.encode(), to.encode(), value.encode(), data.encode()] + // .concat(); + // do_bare_call(addr, params, 0) + let function = function_selector("mint"); + let params = [function, asset_id.encode(), to.unwrap().encode(), value.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + +// Create an asset and mint to owner. +fn create_asset(asset_id: u32, owner: AccountId32) { + assert_eq!( + Assets::create(RuntimeOrigin::signed(owner.clone()), asset_id.into(), owner.into(), 1), + Ok(()) + ); +} + +// Create an asset and mint to owner. +fn create_asset_and_mint_to(asset_id: u32, owner: AccountId32, to: AccountId32, value: u128) { + create_asset(asset_id, owner.clone()); + assert_eq!( + Assets::mint(RuntimeOrigin::signed(owner.into()), asset_id.into(), to.into(), value,), + Ok(()) + ); +} + +// Create an asset, mints to, and approves spender. +fn create_asset_mint_and_approve( + asset_id: u32, + owner: AccountId32, + to: AccountId32, + mint: u128, + spender: AccountId32, + approve: u128, +) { + create_asset_and_mint_to(asset_id, owner.clone(), to.clone(), mint); + assert_eq!( + Assets::approve_transfer( + RuntimeOrigin::signed(to.into()), + asset_id.into(), + spender.into(), + approve, + ), + Ok(()) + ); +} + +#[test] +#[ignore] +fn total_supply_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + + // No tokens in circulation. + assert_eq!( + Assets::total_supply(ASSET_ID).encode(), + total_supply(addr.clone(), ASSET_ID).data[2..] + ); + + // Tokens in circulation. + create_asset_and_mint_to(ASSET_ID, addr.clone(), BOB, 100); + assert_eq!(Assets::total_supply(ASSET_ID).encode(), total_supply(addr, ASSET_ID).data[2..]); + }); +} + +#[test] +#[ignore] +fn balance_of_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + + // No tokens in circulation. + assert_eq!( + Assets::balance(ASSET_ID, BOB).encode(), + balance_of(addr.clone(), ASSET_ID, BOB).data[2..] + ); + + // Tokens in circulation. + create_asset_and_mint_to(ASSET_ID, addr.clone(), BOB, 100); + assert_eq!( + Assets::balance(ASSET_ID, BOB).encode(), + balance_of(addr, ASSET_ID, BOB).data[2..] + ); + }); +} + +#[test] +#[ignore] +fn allowance_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + + // No tokens in circulation. + assert_eq!( + Assets::allowance(ASSET_ID, &BOB, &ALICE).encode(), + allowance(addr.clone(), ASSET_ID, BOB, ALICE).data[2..] + ); + + // Tokens in circulation. + create_asset_mint_and_approve(ASSET_ID, addr.clone(), BOB, 100, ALICE, 50); + assert_eq!( + Assets::allowance(ASSET_ID, &BOB, &ALICE).encode(), + allowance(addr, ASSET_ID, BOB, ALICE).data[2..] + ); + }); +} + +#[test] +#[ignore] +fn asset_exists_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + + // No tokens in circulation. + assert_eq!( + Assets::asset_exists(ASSET_ID).encode(), + asset_exists(addr.clone(), ASSET_ID).data[2..] + ); + + // Tokens in circulation. + create_asset(ASSET_ID, addr.clone()); + assert_eq!(Assets::asset_exists(ASSET_ID).encode(), asset_exists(addr, ASSET_ID).data[2..]); + }); +} + +fn decode_error(result: ExecReturnValue) -> FungiblesError { + FungiblesError::decode(&mut &result.data[2..]).unwrap() +} + +#[test] +#[ignore] +fn create_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 0); + let new_asset = 2; + + assert_eq!( + decode_error(create(addr.clone(), new_asset, BOB, 1)), + FungiblesError::UndefinedError + ); + // Todo: errors Badorigin, Lookup, reserve(), Callback + // create_asset(ASSET_ID, ALICE); + // // Error `InUse`. + // assert_eq!(decode_error(create(addr.clone(), ASSET_ID, BOB, 1)), FungiblesError::InUse); + // // Error `MinBalanceZero`. + // assert_eq!( + // decode_error(create(addr.clone(), new_asset, BOB, 0)), + // FungiblesError::MinBalanceZero + // ); + // assert!( + // !create(addr.clone(), new_asset, BOB, 1).did_revert(), + // "Contract should have been reverted!" + // ); + }); +} + +#[test] +#[ignore] +fn set_metadata_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + + create_asset(ASSET_ID, addr.clone()); + + let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); + assert!(!result.did_revert(), "Contract should have been reverted!"); + }); +} + +#[test] +#[ignore] +fn transfer_from_aka_mint_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + + let amount: u128 = 100 * UNIT; + // Create asset with contract as owner. + create_asset(ASSET_ID, addr.clone()); + // Check Bob's asset balance before minting through contract. + let bob_balance_before = Assets::balance(ASSET_ID, &BOB); + + let result = transfer_from(addr.clone(), ASSET_ID, None, Some(BOB), 100 * UNIT, &[0u8]); + assert!(!result.did_revert(), "Contract reverted!"); + + let bob_balance_after = Assets::balance(ASSET_ID, &BOB); + assert_eq!(bob_balance_after, bob_balance_before + amount); + }); +} diff --git a/runtime/devnet/src/extensions/tests/mod.rs b/runtime/devnet/src/extensions/tests/mod.rs new file mode 100644 index 00000000..30d1a924 --- /dev/null +++ b/runtime/devnet/src/extensions/tests/mod.rs @@ -0,0 +1,86 @@ +#![cfg(test)] +use super::*; +use crate::{Assets, Balances, Contracts, Runtime, System}; +use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; +use sp_runtime::{traits::Hash, AccountId32, BuildStorage}; + +mod local_fungibles; + +const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; + +const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); +const BOB: AccountId32 = AccountId32::new([2_u8; 32]); +const INIT_VALUE: u128 = 100_000_000 * UNIT; +const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); + +fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INIT_VALUE), (BOB, INIT_VALUE)], + } + .assimilate_storage(&mut t) + .expect("Pallet balances storage can be assimilated"); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +fn load_wasm_module(path: &str) -> std::io::Result<(Vec, ::Output)> +where + T: frame_system::Config, +{ + let wasm_binary = std::fs::read(path)?; + let code_hash = T::Hashing::hash(&wasm_binary); + Ok((wasm_binary, code_hash)) +} + +fn function_selector(name: &str) -> Vec { + let hash = sp_io::hashing::blake2_256(name.as_bytes()); + [hash[0..4].to_vec()].concat() +} + +fn do_bare_call( + addr: AccountId32, + input: Vec, + value: u128, +) -> Result { + let result = Contracts::bare_call( + ALICE, + addr.into(), + value.into(), + GAS_LIMIT, + None, + input, + DEBUG_OUTPUT, + CollectEvents::Skip, + Determinism::Enforced, + ); + log::debug!("Contract debug buffer - {:?}", String::from_utf8(result.debug_message.clone())); + log::debug!("result: {:?}", result); + result.result +} + +// Deploy, instantiate and return contract address. +fn instantiate(contract: &str, init_value: u128) -> AccountId32 { + let (wasm_binary, _) = + load_wasm_module::(contract).expect("could not read .wasm file"); + let result = Contracts::bare_instantiate( + ALICE, + init_value, + GAS_LIMIT, + None, + Code::Upload(wasm_binary), + function_selector("new"), + vec![], + DEBUG_OUTPUT, + CollectEvents::Skip, + ) + .result + .unwrap(); + assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); + result.account_id +} diff --git a/runtime/devnet/src/lib.rs b/runtime/devnet/src/lib.rs index 52a0938f..a82be804 100644 --- a/runtime/devnet/src/lib.rs +++ b/runtime/devnet/src/lib.rs @@ -254,40 +254,40 @@ impl Contains for FilteredCalls { pub struct AllowedPopApiCalls; impl Contains for crate::AllowedPopApiCalls { fn contains(c: &RuntimeCall) -> bool { - use assets_config::TrustBackedAssetsCall; + use config::assets::AssetsCall; use pallet_nfts::Call as NftsCall; matches!( c, RuntimeCall::Balances(BalancesCall::transfer_keep_alive { .. }) - | RuntimeCall::TrustBackedAssets( - TrustBackedAssetsCall::create { .. } - | TrustBackedAssetsCall::start_destroy { .. } - | TrustBackedAssetsCall::destroy_accounts { .. } - | TrustBackedAssetsCall::destroy_approvals { .. } - | TrustBackedAssetsCall::finish_destroy { .. } - | TrustBackedAssetsCall::mint { .. } - | TrustBackedAssetsCall::burn { .. } - | TrustBackedAssetsCall::transfer { .. } - | TrustBackedAssetsCall::transfer_keep_alive { .. } - | TrustBackedAssetsCall::force_transfer { .. } - | TrustBackedAssetsCall::freeze { .. } - | TrustBackedAssetsCall::thaw { .. } - | TrustBackedAssetsCall::freeze_asset { .. } - | TrustBackedAssetsCall::thaw_asset { .. } - | TrustBackedAssetsCall::transfer_ownership { .. } - | TrustBackedAssetsCall::set_team { .. } - | TrustBackedAssetsCall::set_metadata { .. } - | TrustBackedAssetsCall::clear_metadata { .. } - | TrustBackedAssetsCall::approve_transfer { .. } - | TrustBackedAssetsCall::cancel_approval { .. } - | TrustBackedAssetsCall::force_cancel_approval { .. } - | TrustBackedAssetsCall::transfer_approved { .. } - | TrustBackedAssetsCall::touch { .. } - | TrustBackedAssetsCall::refund { .. } - | TrustBackedAssetsCall::set_min_balance { .. } - | TrustBackedAssetsCall::touch_other { .. } - | TrustBackedAssetsCall::refund_other { .. } - | TrustBackedAssetsCall::block { .. } + | RuntimeCall::Assets( + AssetsCall::create { .. } + | AssetsCall::start_destroy { .. } + | AssetsCall::destroy_accounts { .. } + | AssetsCall::destroy_approvals { .. } + | AssetsCall::finish_destroy { .. } + | AssetsCall::mint { .. } + | AssetsCall::burn { .. } + | AssetsCall::transfer { .. } + | AssetsCall::transfer_keep_alive { .. } + | AssetsCall::force_transfer { .. } + | AssetsCall::freeze { .. } + | AssetsCall::thaw { .. } + | AssetsCall::freeze_asset { .. } + | AssetsCall::thaw_asset { .. } + | AssetsCall::transfer_ownership { .. } + | AssetsCall::set_team { .. } + | AssetsCall::set_metadata { .. } + | AssetsCall::clear_metadata { .. } + | AssetsCall::approve_transfer { .. } + | AssetsCall::cancel_approval { .. } + | AssetsCall::force_cancel_approval { .. } + | AssetsCall::transfer_approved { .. } + | AssetsCall::touch { .. } + | AssetsCall::refund { .. } + | AssetsCall::set_min_balance { .. } + | AssetsCall::touch_other { .. } + | AssetsCall::refund_other { .. } + | AssetsCall::block { .. } ) | RuntimeCall::Nfts( NftsCall::create { .. } | NftsCall::destroy { .. } @@ -662,7 +662,7 @@ construct_runtime!( // Assets Nfts: pallet_nfts = 50, NftFractionalization: pallet_nft_fractionalization = 51, - TrustBackedAssets: pallet_assets:: = 52, + Assets: pallet_assets:: = 52, } ); diff --git a/runtime/testnet/Cargo.toml b/runtime/testnet/Cargo.toml index d68bfd15..43b1e310 100644 --- a/runtime/testnet/Cargo.toml +++ b/runtime/testnet/Cargo.toml @@ -22,7 +22,7 @@ scale-info.workspace = true smallvec.workspace = true # Local -pop-primitives.workspace = true +pop-primitives = { workspace = true, features = ["testnet"] } pop-runtime-common = { workspace = true, default-features = false } # Substrate diff --git a/runtime/testnet/src/config/assets.rs b/runtime/testnet/src/config/assets.rs index f51f8875..2c8ea952 100644 --- a/runtime/testnet/src/config/assets.rs +++ b/runtime/testnet/src/config/assets.rs @@ -1,6 +1,6 @@ use crate::{ - deposit, AccountId, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, - RuntimeHoldReason, TrustBackedAssets, DAYS, EXISTENTIAL_DEPOSIT, UNIT, + deposit, AccountId, Assets, Balance, Balances, BlockNumber, Nfts, Runtime, RuntimeEvent, + RuntimeHoldReason, DAYS, EXISTENTIAL_DEPOSIT, UNIT, }; use frame_support::{ parameter_types, @@ -86,7 +86,7 @@ impl pallet_nft_fractionalization::Config for Runtime { type NftId = ::ItemId; type AssetBalance = >::Balance; type AssetId = >::AssetId; - type Assets = TrustBackedAssets; + type Assets = Assets; type Nfts = Nfts; type PalletId = NftFractionalizationPalletId; type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight; @@ -96,7 +96,7 @@ impl pallet_nft_fractionalization::Config for Runtime { } pub type TrustBackedAssetsInstance = pallet_assets::Instance1; -pub(crate) type TrustBackedAssetsCall = pallet_assets::Call; +pub(crate) type AssetsCall = pallet_assets::Call; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; diff --git a/runtime/testnet/src/config/proxy.rs b/runtime/testnet/src/config/proxy.rs index a4fd479a..07d5f0f8 100644 --- a/runtime/testnet/src/config/proxy.rs +++ b/runtime/testnet/src/config/proxy.rs @@ -1,4 +1,4 @@ -use super::assets::TrustBackedAssetsCall; +use super::assets::AssetsCall; use crate::{Balances, Runtime, RuntimeCall, RuntimeEvent}; use frame_support::traits::InstanceFilter; use pop_runtime_common::proxy::{ @@ -34,16 +34,16 @@ impl InstanceFilter for ProxyType { }, ProxyType::AssetOwner => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) + RuntimeCall::Assets(AssetsCall::create { .. }) + | RuntimeCall::Assets(AssetsCall::start_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_accounts { .. }) + | RuntimeCall::Assets(AssetsCall::destroy_approvals { .. }) + | RuntimeCall::Assets(AssetsCall::finish_destroy { .. }) + | RuntimeCall::Assets(AssetsCall::transfer_ownership { .. }) + | RuntimeCall::Assets(AssetsCall::set_team { .. }) + | RuntimeCall::Assets(AssetsCall::set_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::clear_metadata { .. }) + | RuntimeCall::Assets(AssetsCall::set_min_balance { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::create { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::destroy { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::redeposit { .. }) @@ -56,15 +56,15 @@ impl InstanceFilter for ProxyType { ), ProxyType::AssetManager => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) - | RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) + RuntimeCall::Assets(AssetsCall::mint { .. }) + | RuntimeCall::Assets(AssetsCall::burn { .. }) + | RuntimeCall::Assets(AssetsCall::freeze { .. }) + | RuntimeCall::Assets(AssetsCall::block { .. }) + | RuntimeCall::Assets(AssetsCall::thaw { .. }) + | RuntimeCall::Assets(AssetsCall::freeze_asset { .. }) + | RuntimeCall::Assets(AssetsCall::thaw_asset { .. }) + | RuntimeCall::Assets(AssetsCall::touch_other { .. }) + | RuntimeCall::Assets(AssetsCall::refund_other { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::force_mint { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::update_mint_settings { .. }) | RuntimeCall::Nfts(pallet_nfts::Call::mint_pre_signed { .. }) diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index 0d552090..6bbfaa36 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -3,25 +3,23 @@ use frame_support::traits::{Contains, OriginTrait}; use frame_support::{ dispatch::{GetDispatchInfo, RawOrigin}, pallet_prelude::*, - traits::{fungibles::Inspect, nonfungibles_v2::Inspect as NonFungiblesInspect}, + traits::nonfungibles_v2::Inspect as NonFungiblesInspect, }; use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, }; use pop_primitives::{ - storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys, TrustBackedAssetsKeys}, - AssetId, CollectionId, ItemId, + storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, + CollectionId, ItemId, }; use sp_core::crypto::UncheckedFrom; use sp_runtime::{ traits::{BlockNumberProvider, Dispatchable}, DispatchError, }; +use sp_std::vec::Vec; -use crate::{ - assets_config::TrustBackedAssetsInstance, AccountId, AllowedPopApiCalls, RuntimeCall, - RuntimeOrigin, -}; +use crate::{AccountId, AllowedPopApiCalls, RuntimeCall, RuntimeOrigin}; const LOG_TARGET: &str = "pop-api::extension"; @@ -34,7 +32,6 @@ impl ChainExtension for PopApiExtension where T: pallet_contracts::Config + pallet_xcm::Config - + pallet_assets::Config + pallet_nfts::Config + cumulus_pallet_parachain_system::Config + frame_system::Config< @@ -184,7 +181,6 @@ where fn read_state(env: Environment) -> Result<(), DispatchError> where T: pallet_contracts::Config - + pallet_assets::Config + pallet_nfts::Config + cumulus_pallet_parachain_system::Config + frame_system::Config, @@ -210,9 +206,6 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, - RuntimeStateKeys::TrustBackedAssets(key) => { - read_trust_backed_assets_state::(key, &mut env) - }, }? .encode(); @@ -288,23 +281,6 @@ where } } -fn read_trust_backed_assets_state( - key: TrustBackedAssetsKeys, - env: &mut Environment, -) -> Result, DispatchError> -where - T: pallet_contracts::Config - + pallet_assets::Config, - E: Ext, -{ - match key { - TrustBackedAssetsKeys::AssetExists(id) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_assets::Pallet::::asset_exists(id).encode()) - }, - } -} - #[cfg(test)] mod tests { pub use super::*; @@ -701,110 +677,6 @@ mod tests { }); } - #[test] - #[ignore] - fn dispatch_trust_backed_assets_mint_from_contract_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - - let (wasm_binary, _) = load_wasm_module::( - "../../pop-api/examples/trust_backed_assets/target/ink/pop_api_trust_backed_assets_example.wasm", - ) - .unwrap(); - - let init_value = 100; - - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - vec![], - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - ) - .result - .unwrap(); - - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - let addr = result.account_id; - - let asset_id: u32 = 1; - let min_balance = 1; - let amount: u128 = 100 * UNIT; - let function = function_selector("mint_asset_through_runtime"); - let params = [function, asset_id.encode(), BOB.encode(), amount.encode()].concat(); - - // Mint asset which does not exist. - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - GAS_LIMIT, - None, - params.clone(), - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // Check for revert. - assert!(result.result.unwrap().did_revert(), "Contract should have been reverted!"); - - // Create asset with contract as owner. - assert_eq!( - TrustBackedAssets::force_create( - RuntimeOrigin::root(), - asset_id.into(), - addr.clone().into(), - true, - min_balance, - ), - Ok(()) - ); - - // Check Bob's asset balance before minting through contract. - let bob_balance_before = TrustBackedAssets::balance(asset_id, &BOB); - assert_eq!(bob_balance_before, 0); - - let result = Contracts::bare_call( - ALICE, - addr.clone(), - 0, - GAS_LIMIT, - None, - params, - DEBUG_OUTPUT, - pallet_contracts::CollectEvents::Skip, - pallet_contracts::Determinism::Enforced, - ); - - if DEBUG_OUTPUT == pallet_contracts::DebugInfo::UnsafeDebug { - log::debug!( - "Contract debug buffer - {:?}", - String::from_utf8(result.debug_message.clone()) - ); - log::debug!("result: {:?}", result); - } - - // Check for revert - assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); - - let bob_balance_after = TrustBackedAssets::balance(asset_id, &BOB); - assert_eq!(bob_balance_after, bob_balance_before + amount); - }); - } - #[test] #[ignore] fn allow_call_filter_blocks_call() { diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index 312d9b50..66a5092c 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -253,74 +253,43 @@ impl Contains for FilteredCalls { pub struct AllowedPopApiCalls; impl Contains for crate::AllowedPopApiCalls { fn contains(c: &RuntimeCall) -> bool { - use assets_config::TrustBackedAssetsCall; use pallet_nfts::Call as NftsCall; matches!( c, RuntimeCall::Balances(BalancesCall::transfer_keep_alive { .. }) - | RuntimeCall::TrustBackedAssets( - TrustBackedAssetsCall::create { .. } - | TrustBackedAssetsCall::start_destroy { .. } - | TrustBackedAssetsCall::destroy_accounts { .. } - | TrustBackedAssetsCall::destroy_approvals { .. } - | TrustBackedAssetsCall::finish_destroy { .. } - | TrustBackedAssetsCall::mint { .. } - | TrustBackedAssetsCall::burn { .. } - | TrustBackedAssetsCall::transfer { .. } - | TrustBackedAssetsCall::transfer_keep_alive { .. } - | TrustBackedAssetsCall::force_transfer { .. } - | TrustBackedAssetsCall::freeze { .. } - | TrustBackedAssetsCall::thaw { .. } - | TrustBackedAssetsCall::freeze_asset { .. } - | TrustBackedAssetsCall::thaw_asset { .. } - | TrustBackedAssetsCall::transfer_ownership { .. } - | TrustBackedAssetsCall::set_team { .. } - | TrustBackedAssetsCall::set_metadata { .. } - | TrustBackedAssetsCall::clear_metadata { .. } - | TrustBackedAssetsCall::approve_transfer { .. } - | TrustBackedAssetsCall::cancel_approval { .. } - | TrustBackedAssetsCall::force_cancel_approval { .. } - | TrustBackedAssetsCall::transfer_approved { .. } - | TrustBackedAssetsCall::touch { .. } - | TrustBackedAssetsCall::refund { .. } - | TrustBackedAssetsCall::set_min_balance { .. } - | TrustBackedAssetsCall::touch_other { .. } - | TrustBackedAssetsCall::refund_other { .. } - | TrustBackedAssetsCall::block { .. } - ) | RuntimeCall::Nfts( - NftsCall::create { .. } - | NftsCall::destroy { .. } - | NftsCall::mint { .. } - | NftsCall::burn { .. } - | NftsCall::transfer { .. } - | NftsCall::redeposit { .. } - | NftsCall::lock_item_transfer { .. } - | NftsCall::unlock_item_transfer { .. } - | NftsCall::lock_collection { .. } - | NftsCall::transfer_ownership { .. } - | NftsCall::set_team { .. } - | NftsCall::approve_transfer { .. } - | NftsCall::cancel_approval { .. } - | NftsCall::clear_all_transfer_approvals { .. } - | NftsCall::lock_item_properties { .. } - | NftsCall::set_attribute { .. } - | NftsCall::clear_attribute { .. } - | NftsCall::approve_item_attributes { .. } - | NftsCall::cancel_item_attributes_approval { .. } - | NftsCall::set_metadata { .. } - | NftsCall::clear_metadata { .. } - | NftsCall::set_collection_metadata { .. } - | NftsCall::clear_collection_metadata { .. } - | NftsCall::set_accept_ownership { .. } - | NftsCall::set_collection_max_supply { .. } - | NftsCall::update_mint_settings { .. } - | NftsCall::set_price { .. } - | NftsCall::buy_item { .. } - | NftsCall::pay_tips { .. } - | NftsCall::create_swap { .. } - | NftsCall::cancel_swap { .. } - | NftsCall::claim_swap { .. } - ) + | RuntimeCall::Nfts( + NftsCall::create { .. } + | NftsCall::destroy { .. } + | NftsCall::mint { .. } | NftsCall::burn { .. } + | NftsCall::transfer { .. } + | NftsCall::redeposit { .. } + | NftsCall::lock_item_transfer { .. } + | NftsCall::unlock_item_transfer { .. } + | NftsCall::lock_collection { .. } + | NftsCall::transfer_ownership { .. } + | NftsCall::set_team { .. } + | NftsCall::approve_transfer { .. } + | NftsCall::cancel_approval { .. } + | NftsCall::clear_all_transfer_approvals { .. } + | NftsCall::lock_item_properties { .. } + | NftsCall::set_attribute { .. } + | NftsCall::clear_attribute { .. } + | NftsCall::approve_item_attributes { .. } + | NftsCall::cancel_item_attributes_approval { .. } + | NftsCall::set_metadata { .. } + | NftsCall::clear_metadata { .. } + | NftsCall::set_collection_metadata { .. } + | NftsCall::clear_collection_metadata { .. } + | NftsCall::set_accept_ownership { .. } + | NftsCall::set_collection_max_supply { .. } + | NftsCall::update_mint_settings { .. } + | NftsCall::set_price { .. } + | NftsCall::buy_item { .. } + | NftsCall::pay_tips { .. } + | NftsCall::create_swap { .. } + | NftsCall::cancel_swap { .. } + | NftsCall::claim_swap { .. } + ) ) } } @@ -661,7 +630,7 @@ construct_runtime!( // Assets Nfts: pallet_nfts = 50, NftFractionalization: pallet_nft_fractionalization = 51, - TrustBackedAssets: pallet_assets:: = 52, + Assets: pallet_assets:: = 52, } ); From fd46a279073abd855c327df6de32b2e155a74840 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Tue, 4 Jun 2024 15:49:03 +0200 Subject: [PATCH 04/27] fix: add error handling other than ModuleError --- pop-api/examples/fungibles/lib.rs | 36 +-- pop-api/src/lib.rs | 53 +++- pop-api/src/v0/assets/fungibles.rs | 60 +++- pop-api/src/v0/balances.rs | 6 +- pop-api/src/v0/contracts.rs | 286 +++++++++--------- pop-api/src/v0/cross_chain/mod.rs | 4 +- pop-api/src/v0/dispatch_error.rs | 57 ++++ pop-api/src/v0/mod.rs | 3 +- pop-api/src/v0/nfts.rs | 4 +- runtime/devnet/src/extensions/mod.rs | 11 +- .../src/extensions/tests/local_fungibles.rs | 214 ++++++++----- runtime/devnet/src/extensions/tests/mod.rs | 10 +- 12 files changed, 462 insertions(+), 282 deletions(-) create mode 100644 pop-api/src/v0/dispatch_error.rs diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 9c0ae754..e44c4347 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -10,42 +10,42 @@ use pop_api::{ #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum ContractError { - // AssetsError(Error), - // /// The origin of the call doesn't have the right permission. - // BadOrigin, - // /// Custom error type for cases in which an implementation adds its own restrictions. - // Custom(String), - /// Not enough balance to fulfill a request is available. - InsufficientBalance, + /// The amount to mint is less than the existential deposit. + BelowMinimum, + /// Unspecified dispatch error, providing the index and its error index (if none `0`). + DispatchError { index: u8, error: u8 }, /// Not enough allowance to fulfill a request is available. InsufficientAllowance, - /// The asset status is not the expected status. - IncorrectStatus, + /// Not enough balance to fulfill a request is available. + InsufficientBalance, /// The asset ID is already taken. InUse, /// Minimum balance should be non-zero. MinBalanceZero, + /// Unspecified pallet error, providing pallet index and error index. + ModuleError { pallet: u8, error: u16 }, /// The signing account has no permission to do the operation. NoPermission, - // /// Safe transfer check fails (e.g. if the receiving contract does not accept tokens). - // SafeTransferCheckFailed(String), /// The given asset ID is unknown. Unknown, - /// Recipient's address is zero. - ZeroRecipientAddress, - /// Sender's address is zero. - ZeroSenderAddress, - UndefinedError, } impl From for ContractError { fn from(error: FungiblesError) -> Self { match error { - // Error::BalanceLow => Err(InsufficientBalance), + FungiblesError::BelowMinimum => ContractError::BelowMinimum, + FungiblesError::DispatchError { index, error } => { + ContractError::DispatchError { index, error } + }, + FungiblesError::InsufficientAllowance => ContractError::InsufficientAllowance, + FungiblesError::InsufficientBalance => ContractError::InsufficientBalance, FungiblesError::InUse => ContractError::InUse, FungiblesError::MinBalanceZero => ContractError::MinBalanceZero, + FungiblesError::ModuleError { pallet, error } => { + ContractError::ModuleError { pallet, error } + }, + FungiblesError::NoPermission => ContractError::NoPermission, FungiblesError::Unknown => ContractError::Unknown, - _ => ContractError::UndefinedError, } } } diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 0ca4a817..014b5a29 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,14 +1,16 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -pub mod primitives; -pub mod v0; - -use crate::PopApiError::{Assets, Balances, Contracts, Nfts, UnknownStatusCode}; +use core::convert::TryInto; use ink::{prelude::vec::Vec, ChainExtensionInstance}; use primitives::{cross_chain::*, storage_keys::*, AccountId as AccountId32}; pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; use v0::RuntimeCall; -pub use v0::{assets, balances, contracts, cross_chain, nfts, relay_chain_block_number, state}; +pub use v0::{ + assets, balances, contracts, cross_chain, dispatch_error, nfts, relay_chain_block_number, state, +}; + +pub mod primitives; +pub mod v0; // type AccountId = ::AccountId; type AccountId = AccountId32; @@ -19,30 +21,49 @@ type MaxTips = u32; pub type Result = core::result::Result; +struct ModuleError { + pallet: u8, + error: u16, +} + #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum PopApiError { - UnknownStatusCode(u32), - DecodingFailed, - SystemCallFiltered, + Assets(assets::fungibles::AssetsError), Balances(balances::Error), Contracts(contracts::Error), + DecodingFailed, Nfts(nfts::Error), - Assets(assets::fungibles::AssetsError), + SystemCallFiltered, + TokenError(dispatch_error::TokenError), + UnknownModuleStatusCode(u32), + UnknownDispatchStatusCode(u32), Xcm(cross_chain::Error), } impl ink::env::chain_extension::FromStatusCode for PopApiError { fn from_status_code(status_code: u32) -> core::result::Result<(), Self> { + use crate::PopApiError::{ + Assets, Balances, Contracts, Nfts, TokenError, UnknownDispatchStatusCode, + UnknownModuleStatusCode, + }; + match status_code { 0 => Ok(()), - // CallFiltered originates from `frame_system` with pallet-index 0. The CallFiltered error is at index 5 - 5 => Err(PopApiError::SystemCallFiltered), - 10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)), - 40_000..=40_999 => Err(Contracts((status_code - 40_000).try_into()?)), - 50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)), - 52_000..=52_999 => Err(Assets((status_code - 52_000).try_into()?)), - _ => Err(UnknownStatusCode(status_code)), + 3_000_000..=3_999_999 => { + let status_code = status_code - 3_000_000; + match status_code { + // CallFiltered originates from `frame_system` with pallet-index 0. The CallFiltered error is at index 5 + 5 => Err(PopApiError::SystemCallFiltered), + 10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)), + 40_000..=40_999 => Err(Contracts((status_code - 40_000).try_into()?)), + 50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)), + 52_000..=52_999 => Err(Assets((status_code - 52_000).try_into()?)), + _ => Err(UnknownModuleStatusCode(status_code)), + } + }, + 7_000_000..=7_999_999 => Err(TokenError((status_code - 7_000_000).try_into()?)), + _ => Err(UnknownDispatchStatusCode(status_code)), } } } diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index f2d87a0e..de624938 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -1,4 +1,8 @@ -use crate::{AccountId, Balance, PopApiError::UnknownStatusCode, RuntimeCall, *}; +use crate::{ + AccountId, Balance, + PopApiError::{UnknownDispatchStatusCode, UnknownModuleStatusCode}, + RuntimeCall, *, +}; use ink::prelude::vec::Vec; use primitives::AssetId; use scale::{Compact, Encode}; @@ -502,7 +506,7 @@ impl TryFrom for AssetsError { 16 => Ok(AssetNotLive), 17 => Ok(IncorrectStatus), 18 => Ok(NotFrozen), - _ => Err(UnknownStatusCode(status_code)), + _ => Err(UnknownModuleStatusCode(status_code)), } } } @@ -510,22 +514,41 @@ impl TryFrom for AssetsError { #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum FungiblesError { - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, + /// The amount to mint is less than the existential deposit. + BelowMinimum, + /// Unspecified dispatch error, providing the index and its error index (if none `0`). + DispatchError { index: u8, error: u8 }, + /// Not enough allowance to fulfill a request is available. + InsufficientAllowance, + /// Not enough balance to fulfill a request is available. InsufficientBalance, /// The asset ID is already taken. InUse, /// Minimum balance should be non-zero. MinBalanceZero, + /// Unspecified pallet error, providing pallet index and error index. + ModuleError { pallet: u8, error: u16 }, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, } impl From for FungiblesError { fn from(error: balances::Error) -> Self { match error { balances::Error::InsufficientBalance => FungiblesError::InsufficientBalance, - _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), + _ => FungiblesError::ModuleError { pallet: 40, error: error as u16 }, + } + } +} + +impl From for FungiblesError { + fn from(error: dispatch_error::TokenError) -> Self { + match error { + dispatch_error::TokenError::UnknownAsset => FungiblesError::Unknown, + dispatch_error::TokenError::BelowMinimum => FungiblesError::BelowMinimum, + _ => FungiblesError::DispatchError { index: 7, error: error as u8 }, } } } @@ -533,8 +556,12 @@ impl From for FungiblesError { impl From for FungiblesError { fn from(error: AssetsError) -> Self { match error { + AssetsError::Unapproved => FungiblesError::InsufficientAllowance, AssetsError::InUse => FungiblesError::InUse, - _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), + AssetsError::MinBalanceZero => FungiblesError::MinBalanceZero, + AssetsError::NoPermission => FungiblesError::NoPermission, + AssetsError::Unknown => FungiblesError::Unknown, + _ => FungiblesError::ModuleError { pallet: 40, error: error as u16 }, } } } @@ -543,12 +570,19 @@ impl From for FungiblesError { fn from(error: PopApiError) -> Self { match error { PopApiError::Assets(e) => e.into(), - // PopApiError::Balances(e) => todo!("balances: {:?}", e), PopApiError::Balances(e) => e.into(), - // PopApiError::Contracts(_e) => todo!("contracts"), - // PopApiError::SystemCallFiltered => 100, - // PopApiError::UnknownStatusCode(u) => u, - _ => panic!("Unexpected pallet assets error. This error is unknown to pallet assets"), + PopApiError::TokenError(e) => e.into(), + PopApiError::UnknownModuleStatusCode(e) => { + let pallet = (e / 1_000) as u8; + let error = (e % 1_000) as u16; + FungiblesError::ModuleError { pallet, error } + }, + PopApiError::UnknownDispatchStatusCode(e) => { + let index = (e / 1_000_000) as u8; + let error = (3 % 1_000_000) as u8; + FungiblesError::DispatchError { index, error } + }, + _ => todo!(), } } } diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index bc48711e..bc422ef4 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -1,6 +1,6 @@ use crate::{ dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, PopApiError, - PopApiError::UnknownStatusCode, + PopApiError::UnknownModuleStatusCode, }; type Result = core::result::Result; @@ -73,7 +73,7 @@ impl TryFrom for Error { 9 => Ok(TooManyFreezes), 10 => Ok(IssuanceDeactivated), 11 => Ok(DeltaZero), - _ => Err(UnknownStatusCode(status_code)), + _ => Err(UnknownModuleStatusCode(status_code)), } } } @@ -82,7 +82,7 @@ impl From for Error { fn from(error: PopApiError) -> Self { match error { PopApiError::Balances(e) => e, - _ => panic!("expected balances error"), + _ => todo!(), } } } diff --git a/pop-api/src/v0/contracts.rs b/pop-api/src/v0/contracts.rs index d7a1a5dd..5d4a3692 100644 --- a/pop-api/src/v0/contracts.rs +++ b/pop-api/src/v0/contracts.rs @@ -1,156 +1,152 @@ -use crate::{ - PopApiError, - PopApiError::UnknownStatusCode, -}; +use crate::{PopApiError, PopApiError::UnknownModuleStatusCode}; #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum Error { - /// Invalid schedule supplied, e.g. with zero weight of a basic operation. - InvalidSchedule, - /// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`. - InvalidCallFlags, - /// The executed contract exhausted its gas limit. - OutOfGas, - /// The output buffer supplied to a contract API call was too small. - OutputBufferTooSmall, - /// Performing the requested transfer failed. Probably because there isn't enough - /// free balance in the sender's account. - TransferFailed, - /// Performing a call was denied because the calling depth reached the limit - /// of what is specified in the schedule. - MaxCallDepthReached, - /// No contract was found at the specified address. - ContractNotFound, - /// The code supplied to `instantiate_with_code` exceeds the limit specified in the - /// current schedule. - CodeTooLarge, - /// No code could be found at the supplied code hash. - CodeNotFound, - /// No code info could be found at the supplied code hash. - CodeInfoNotFound, - /// A buffer outside of sandbox memory was passed to a contract API function. - OutOfBounds, - /// Input passed to a contract API function failed to decode as expected type. - DecodingFailed, - /// Contract trapped during execution. - ContractTrapped, - /// The size defined in `T::MaxValueSize` was exceeded. - ValueTooLarge, - /// Termination of a contract is not allowed while the contract is already - /// on the call stack. Can be triggered by `seal_terminate`. - TerminatedWhileReentrant, - /// `seal_call` forwarded this contracts input. It therefore is no longer available. - InputForwarded, - /// The subject passed to `seal_random` exceeds the limit. - RandomSubjectTooLong, - /// The amount of topics passed to `seal_deposit_events` exceeds the limit. - TooManyTopics, - /// The chain does not provide a chain extension. Calling the chain extension results - /// in this error. Note that this usually shouldn't happen as deploying such contracts - /// is rejected. - NoChainExtension, - /// Failed to decode the XCM program. - XCMDecodeFailed, - /// A contract with the same AccountId already exists. - DuplicateContract, - /// A contract self destructed in its constructor. - /// - /// This can be triggered by a call to `seal_terminate`. - TerminatedInConstructor, - /// A call tried to invoke a contract that is flagged as non-reentrant. - /// The only other cause is that a call from a contract into the runtime tried to call back - /// into `pallet-contracts`. This would make the whole pallet reentrant with regard to - /// contract code execution which is not supported. - ReentranceDenied, - /// Origin doesn't have enough balance to pay the required storage deposits. - StorageDepositNotEnoughFunds, - /// More storage was created than allowed by the storage deposit limit. - StorageDepositLimitExhausted, - /// Code removal was denied because the code is still in use by at least one contract. - CodeInUse, - /// The contract ran to completion but decided to revert its storage changes. - /// Please note that this error is only returned from extrinsics. When called directly - /// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags - /// to determine whether a reversion has taken place. - ContractReverted, - /// The contract's code was found to be invalid during validation. - /// - /// The most likely cause of this is that an API was used which is not supported by the - /// node. This happens if an older node is used with a new version of ink!. Try updating - /// your node to the newest available version. - /// - /// A more detailed error can be found on the node console if debug messages are enabled - /// by supplying `-lruntime::contracts=debug`. - CodeRejected, - /// An indeterministic code was used in a context where this is not permitted. - Indeterministic, - /// A pending migration needs to complete before the extrinsic can be called. - MigrationInProgress, - /// Migrate dispatch call was attempted but no migration was performed. - NoMigrationPerformed, - /// The contract has reached its maximum number of delegate dependencies. - MaxDelegateDependenciesReached, - /// The dependency was not found in the contract's delegate dependencies. - DelegateDependencyNotFound, - /// The contract already depends on the given delegate dependency. - DelegateDependencyAlreadyExists, - /// Can not add a delegate dependency to the code hash of the contract itself. - CannotAddSelfAsDelegateDependency, + /// Invalid schedule supplied, e.g. with zero weight of a basic operation. + InvalidSchedule, + /// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`. + InvalidCallFlags, + /// The executed contract exhausted its gas limit. + OutOfGas, + /// The output buffer supplied to a contract API call was too small. + OutputBufferTooSmall, + /// Performing the requested transfer failed. Probably because there isn't enough + /// free balance in the sender's account. + TransferFailed, + /// Performing a call was denied because the calling depth reached the limit + /// of what is specified in the schedule. + MaxCallDepthReached, + /// No contract was found at the specified address. + ContractNotFound, + /// The code supplied to `instantiate_with_code` exceeds the limit specified in the + /// current schedule. + CodeTooLarge, + /// No code could be found at the supplied code hash. + CodeNotFound, + /// No code info could be found at the supplied code hash. + CodeInfoNotFound, + /// A buffer outside of sandbox memory was passed to a contract API function. + OutOfBounds, + /// Input passed to a contract API function failed to decode as expected type. + DecodingFailed, + /// Contract trapped during execution. + ContractTrapped, + /// The size defined in `T::MaxValueSize` was exceeded. + ValueTooLarge, + /// Termination of a contract is not allowed while the contract is already + /// on the call stack. Can be triggered by `seal_terminate`. + TerminatedWhileReentrant, + /// `seal_call` forwarded this contracts input. It therefore is no longer available. + InputForwarded, + /// The subject passed to `seal_random` exceeds the limit. + RandomSubjectTooLong, + /// The amount of topics passed to `seal_deposit_events` exceeds the limit. + TooManyTopics, + /// The chain does not provide a chain extension. Calling the chain extension results + /// in this error. Note that this usually shouldn't happen as deploying such contracts + /// is rejected. + NoChainExtension, + /// Failed to decode the XCM program. + XCMDecodeFailed, + /// A contract with the same AccountId already exists. + DuplicateContract, + /// A contract self destructed in its constructor. + /// + /// This can be triggered by a call to `seal_terminate`. + TerminatedInConstructor, + /// A call tried to invoke a contract that is flagged as non-reentrant. + /// The only other cause is that a call from a contract into the runtime tried to call back + /// into `pallet-contracts`. This would make the whole pallet reentrant with regard to + /// contract code execution which is not supported. + ReentranceDenied, + /// Origin doesn't have enough balance to pay the required storage deposits. + StorageDepositNotEnoughFunds, + /// More storage was created than allowed by the storage deposit limit. + StorageDepositLimitExhausted, + /// Code removal was denied because the code is still in use by at least one contract. + CodeInUse, + /// The contract ran to completion but decided to revert its storage changes. + /// Please note that this error is only returned from extrinsics. When called directly + /// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags + /// to determine whether a reversion has taken place. + ContractReverted, + /// The contract's code was found to be invalid during validation. + /// + /// The most likely cause of this is that an API was used which is not supported by the + /// node. This happens if an older node is used with a new version of ink!. Try updating + /// your node to the newest available version. + /// + /// A more detailed error can be found on the node console if debug messages are enabled + /// by supplying `-lruntime::contracts=debug`. + CodeRejected, + /// An indeterministic code was used in a context where this is not permitted. + Indeterministic, + /// A pending migration needs to complete before the extrinsic can be called. + MigrationInProgress, + /// Migrate dispatch call was attempted but no migration was performed. + NoMigrationPerformed, + /// The contract has reached its maximum number of delegate dependencies. + MaxDelegateDependenciesReached, + /// The dependency was not found in the contract's delegate dependencies. + DelegateDependencyNotFound, + /// The contract already depends on the given delegate dependency. + DelegateDependencyAlreadyExists, + /// Can not add a delegate dependency to the code hash of the contract itself. + CannotAddSelfAsDelegateDependency, } - impl TryFrom for Error { - type Error = PopApiError; + type Error = PopApiError; - fn try_from(status_code: u32) -> core::result::Result { - use Error::*; - match status_code { - 0 => Ok(InvalidSchedule), - 1 => Ok(InvalidCallFlags), - 2 => Ok(OutOfGas), - 3 => Ok(OutputBufferTooSmall), - 4 => Ok(TransferFailed), - 5 => Ok(MaxCallDepthReached), - 6 => Ok(ContractNotFound), - 7 => Ok(CodeTooLarge), - 8 => Ok(CodeNotFound), - 9 => Ok(CodeInfoNotFound), - 10 => Ok(OutOfBounds), - 11 => Ok(DecodingFailed), - 12 => Ok(ContractTrapped), - 13 => Ok(ValueTooLarge), - 14 => Ok(TerminatedWhileReentrant), - 15 => Ok(InputForwarded), - 16 => Ok(RandomSubjectTooLong), - 17 => Ok(TooManyTopics), - 18 => Ok(NoChainExtension), - 19 => Ok(XCMDecodeFailed), - 20 => Ok(DuplicateContract), - 21 => Ok(TerminatedInConstructor), - 22 => Ok(ReentranceDenied), - 23 => Ok(StorageDepositNotEnoughFunds), - 24 => Ok(StorageDepositLimitExhausted), - 25 => Ok(CodeInUse), - 26 => Ok(ContractReverted), - 27 => Ok(CodeRejected), - 28 => Ok(Indeterministic), - 29 => Ok(MigrationInProgress), - 30 => Ok(NoMigrationPerformed), - 31 => Ok(MaxDelegateDependenciesReached), - 32 => Ok(DelegateDependencyNotFound), - 33 => Ok(DelegateDependencyAlreadyExists), - 34 => Ok(CannotAddSelfAsDelegateDependency), - _ => Err(UnknownStatusCode(status_code)), - } - } + fn try_from(status_code: u32) -> core::result::Result { + use Error::*; + match status_code { + 0 => Ok(InvalidSchedule), + 1 => Ok(InvalidCallFlags), + 2 => Ok(OutOfGas), + 3 => Ok(OutputBufferTooSmall), + 4 => Ok(TransferFailed), + 5 => Ok(MaxCallDepthReached), + 6 => Ok(ContractNotFound), + 7 => Ok(CodeTooLarge), + 8 => Ok(CodeNotFound), + 9 => Ok(CodeInfoNotFound), + 10 => Ok(OutOfBounds), + 11 => Ok(DecodingFailed), + 12 => Ok(ContractTrapped), + 13 => Ok(ValueTooLarge), + 14 => Ok(TerminatedWhileReentrant), + 15 => Ok(InputForwarded), + 16 => Ok(RandomSubjectTooLong), + 17 => Ok(TooManyTopics), + 18 => Ok(NoChainExtension), + 19 => Ok(XCMDecodeFailed), + 20 => Ok(DuplicateContract), + 21 => Ok(TerminatedInConstructor), + 22 => Ok(ReentranceDenied), + 23 => Ok(StorageDepositNotEnoughFunds), + 24 => Ok(StorageDepositLimitExhausted), + 25 => Ok(CodeInUse), + 26 => Ok(ContractReverted), + 27 => Ok(CodeRejected), + 28 => Ok(Indeterministic), + 29 => Ok(MigrationInProgress), + 30 => Ok(NoMigrationPerformed), + 31 => Ok(MaxDelegateDependenciesReached), + 32 => Ok(DelegateDependencyNotFound), + 33 => Ok(DelegateDependencyAlreadyExists), + 34 => Ok(CannotAddSelfAsDelegateDependency), + _ => Err(UnknownModuleStatusCode(status_code)), + } + } } impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Contracts(e) => e, - _ => panic!("expected balances error"), - } - } -} \ No newline at end of file + fn from(error: PopApiError) -> Self { + match error { + PopApiError::Contracts(e) => e, + _ => panic!("expected balances error"), + } + } +} diff --git a/pop-api/src/v0/cross_chain/mod.rs b/pop-api/src/v0/cross_chain/mod.rs index 6732c119..1e5afbf5 100644 --- a/pop-api/src/v0/cross_chain/mod.rs +++ b/pop-api/src/v0/cross_chain/mod.rs @@ -1,6 +1,6 @@ pub mod coretime; -use crate::{PopApiError::UnknownStatusCode, *}; +use crate::{PopApiError::UnknownModuleStatusCode, *}; type Result = core::result::Result; @@ -92,7 +92,7 @@ impl TryFrom for Error { 21 => Ok(InvalidAssetUnknownReserve), 22 => Ok(InvalidAssetUnsupportedReserve), 23 => Ok(TooManyReserves), - _ => Err(UnknownStatusCode(status_code)), + _ => Err(UnknownModuleStatusCode(status_code)), } } } diff --git a/pop-api/src/v0/dispatch_error.rs b/pop-api/src/v0/dispatch_error.rs new file mode 100644 index 00000000..6ed40ce5 --- /dev/null +++ b/pop-api/src/v0/dispatch_error.rs @@ -0,0 +1,57 @@ +use super::*; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub(crate) enum TokenError { + /// Funds are unavailable. + FundsUnavailable, + /// Some part of the balance gives the only provider reference to the account and thus cannot + /// be (re)moved. + OnlyProvider, + /// Account cannot exist with the funds that would be given. + BelowMinimum, + /// Account cannot be created. + CannotCreate, + /// The asset in question is unknown. + UnknownAsset, + /// Funds exist but are frozen. + Frozen, + /// Operation is not supported by the asset. + Unsupported, + /// Account cannot be created for a held balance. + CannotCreateHold, + /// Withdrawal would cause unwanted loss of account. + NotExpendable, + /// Account cannot receive the assets. + Blocked, +} + +impl TryFrom for TokenError { + type Error = crate::PopApiError; + + fn try_from(status_code: u32) -> core::result::Result { + use TokenError::*; + match status_code { + 0 => Ok(FundsUnavailable), + 1 => Ok(OnlyProvider), + 2 => Ok(BelowMinimum), + 3 => Ok(CannotCreate), + 4 => Ok(UnknownAsset), + 5 => Ok(Frozen), + 6 => Ok(Unsupported), + 7 => Ok(CannotCreateHold), + 8 => Ok(NotExpendable), + 9 => Ok(Blocked), + _ => todo!(), + } + } +} + +impl From for TokenError { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::TokenError(e) => e, + _ => todo!(), + } + } +} diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index def37e55..02169c22 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -3,12 +3,13 @@ use crate::{ BlockNumber, PopApiError, }; +pub mod assets; pub mod balances; pub mod contracts; pub mod cross_chain; +pub mod dispatch_error; pub mod nfts; pub mod state; -pub mod assets; pub fn relay_chain_block_number() -> Result { state::read(RuntimeStateKeys::ParachainSystem(ParachainSystemKeys::LastRelayChainBlockNumber)) diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index 5a55154f..946a3eca 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -1,5 +1,5 @@ use super::RuntimeCall; -use crate::{PopApiError::UnknownStatusCode, *}; +use crate::{PopApiError::UnknownModuleStatusCode, *}; use ink::prelude::vec::Vec; use primitives::{ApprovalsLimit, BoundedBTreeMap, KeyLimit, MultiAddress}; pub use primitives::{CollectionId, ItemId}; @@ -660,7 +660,7 @@ impl TryFrom for Error { 42 => Ok(WrongNamespace), 43 => Ok(CollectionNotEmpty), 44 => Ok(WitnessRequired), - _ => Err(UnknownStatusCode(status_code)), + _ => Err(UnknownModuleStatusCode(status_code)), } } } diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index 096f21c9..d2129c4f 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -69,10 +69,19 @@ where Err(DispatchError::Module(error)) => { // encode status code = pallet index in runtime + error index, allowing for // 999 errors + let first = (3u32 * 1_000_000u32) + + (error.index as u32 * 1_000u32) + + u32::from_le_bytes(error.error); Ok(RetVal::Converging( - (error.index as u32 * 1_000) + u32::from_le_bytes(error.error), + // (3u32 * 1_000_000u32) + // + (error.index as u32 * 1_000u32) + // + u32::from_le_bytes(error.error), + first, )) }, + Err(DispatchError::Token(error)) => { + Ok(RetVal::Converging((7u32 * 1_000_000u32) + error as u32)) + }, Err(e) => Err(e), } }, diff --git a/runtime/devnet/src/extensions/tests/local_fungibles.rs b/runtime/devnet/src/extensions/tests/local_fungibles.rs index 2d752361..5bd7dac0 100644 --- a/runtime/devnet/src/extensions/tests/local_fungibles.rs +++ b/runtime/devnet/src/extensions/tests/local_fungibles.rs @@ -5,36 +5,32 @@ use pallet_contracts::debug::ExecResult; #[derive(Decode, Encode, Debug, Eq, PartialEq)] enum FungiblesError { - // AssetsError(Error), - // /// The origin of the call doesn't have the right permission. - // BadOrigin, - // /// Custom error type for cases in which an implementation adds its own restrictions. - // Custom(String), - /// Not enough balance to fulfill a request is available. - InsufficientBalance, + /// The amount to mint is less than the existential deposit. + BelowMinimum, + /// Unspecified dispatch error, providing the index and optionally its error index. + DispatchError { index: u8, error: Option }, /// Not enough allowance to fulfill a request is available. InsufficientAllowance, - /// The asset status is not the expected status. - IncorrectStatus, + /// Not enough balance to fulfill a request is available. + InsufficientBalance, /// The asset ID is already taken. InUse, /// Minimum balance should be non-zero. MinBalanceZero, + /// Unspecified pallet error, providing pallet index and error index. + ModuleError { pallet: u8, error: u16 }, /// The signing account has no permission to do the operation. NoPermission, - // /// Safe transfer check fails (e.g. if the receiving contract does not accept tokens). - // SafeTransferCheckFailed(String), /// The given asset ID is unknown. Unknown, - /// Recipient's address is zero. - ZeroRecipientAddress, - /// Sender's address is zero. - ZeroSenderAddress, - UndefinedError, } const ASSET_ID: u32 = 1; +fn decoded(result: ExecReturnValue) -> T { + ::decode(&mut &result.data[2..]).unwrap() +} + fn allowance( addr: AccountId32, asset_id: u32, @@ -54,10 +50,11 @@ fn balance_of(addr: AccountId32, asset_id: u32, owner: AccountId32) -> ExecRetur } // Call total_supply contract message. -fn total_supply(addr: AccountId32, asset_id: u32) -> ExecReturnValue { +fn total_supply(addr: AccountId32, asset_id: u32) -> Balance { let function = function_selector("total_supply"); let params = [function, asset_id.encode()].concat(); - do_bare_call(addr, params, 0).expect("should work") + let result = do_bare_call(addr, params, 0).expect("should work"); + decoded::(result) } fn asset_exists(addr: AccountId32, asset_id: u32) -> ExecReturnValue { @@ -70,7 +67,7 @@ fn create( addr: AccountId32, asset_id: u32, admin: AccountId32, - min_balance: u128, + min_balance: Balance, ) -> ExecReturnValue { let function = function_selector("create"); let params = [function, asset_id.encode(), admin.encode(), min_balance.encode()].concat(); @@ -95,7 +92,7 @@ fn transfer_from( asset_id: u32, _from: Option, to: Option, - value: u128, + value: Balance, _data: &[u8], ) -> ExecReturnValue { // let function = function_selector("transfer_from"); @@ -109,16 +106,21 @@ fn transfer_from( } // Create an asset and mint to owner. -fn create_asset(asset_id: u32, owner: AccountId32) { +fn create_asset(asset_id: u32, owner: AccountId32, min_balance: Balance) { assert_eq!( - Assets::create(RuntimeOrigin::signed(owner.clone()), asset_id.into(), owner.into(), 1), + Assets::create( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + owner.into(), + min_balance + ), Ok(()) ); } // Create an asset and mint to owner. -fn create_asset_and_mint_to(asset_id: u32, owner: AccountId32, to: AccountId32, value: u128) { - create_asset(asset_id, owner.clone()); +fn create_asset_and_mint_to(asset_id: u32, owner: AccountId32, to: AccountId32, value: Balance) { + create_asset(asset_id, owner.clone(), 1); assert_eq!( Assets::mint(RuntimeOrigin::signed(owner.into()), asset_id.into(), to.into(), value,), Ok(()) @@ -130,9 +132,9 @@ fn create_asset_mint_and_approve( asset_id: u32, owner: AccountId32, to: AccountId32, - mint: u128, + mint: Balance, spender: AccountId32, - approve: u128, + approve: Balance, ) { create_asset_and_mint_to(asset_id, owner.clone(), to.clone(), mint); assert_eq!( @@ -151,18 +153,18 @@ fn create_asset_mint_and_approve( fn total_supply_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); // No tokens in circulation. - assert_eq!( - Assets::total_supply(ASSET_ID).encode(), - total_supply(addr.clone(), ASSET_ID).data[2..] - ); + assert_eq!(Assets::total_supply(ASSET_ID), total_supply(addr.clone(), ASSET_ID)); // Tokens in circulation. create_asset_and_mint_to(ASSET_ID, addr.clone(), BOB, 100); - assert_eq!(Assets::total_supply(ASSET_ID).encode(), total_supply(addr, ASSET_ID).data[2..]); + assert_eq!(Assets::total_supply(ASSET_ID), total_supply(addr, ASSET_ID)); }); } @@ -171,8 +173,11 @@ fn total_supply_works() { fn balance_of_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); // No tokens in circulation. assert_eq!( @@ -194,8 +199,11 @@ fn balance_of_works() { fn allowance_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); // No tokens in circulation. assert_eq!( @@ -217,8 +225,11 @@ fn allowance_works() { fn asset_exists_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); // No tokens in circulation. assert_eq!( @@ -227,40 +238,45 @@ fn asset_exists_works() { ); // Tokens in circulation. - create_asset(ASSET_ID, addr.clone()); + create_asset(ASSET_ID, addr.clone(), 1); assert_eq!(Assets::asset_exists(ASSET_ID).encode(), asset_exists(addr, ASSET_ID).data[2..]); }); } -fn decode_error(result: ExecReturnValue) -> FungiblesError { - FungiblesError::decode(&mut &result.data[2..]).unwrap() -} - +// Todo - errors: +// - Badorigin: contract is always signed +// - Lookup: is a valid AccountId due to the contract +// - reserve(): Overflow, LiquidityRestrictions; frozen +// - Callback +// - StorageDepositLimitExhausted #[test] #[ignore] fn create_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 0); let new_asset = 2; + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); assert_eq!( - decode_error(create(addr.clone(), new_asset, BOB, 1)), - FungiblesError::UndefinedError + decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), + FungiblesError::InsufficientBalance ); - // Todo: errors Badorigin, Lookup, reserve(), Callback - // create_asset(ASSET_ID, ALICE); - // // Error `InUse`. - // assert_eq!(decode_error(create(addr.clone(), ASSET_ID, BOB, 1)), FungiblesError::InUse); - // // Error `MinBalanceZero`. - // assert_eq!( - // decode_error(create(addr.clone(), new_asset, BOB, 0)), - // FungiblesError::MinBalanceZero - // ); - // assert!( - // !create(addr.clone(), new_asset, BOB, 1).did_revert(), - // "Contract should have been reverted!" - // ); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![1], + ); + create_asset(ASSET_ID, ALICE, 1); + assert_eq!( + decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), + FungiblesError::InUse + ); + assert_eq!( + decoded::(create(addr.clone(), new_asset, BOB, 0)), + FungiblesError::MinBalanceZero + ); + assert!(!create(addr.clone(), new_asset, BOB, 1).did_revert(), "Contract reverted!"); }); } @@ -269,34 +285,78 @@ fn create_works() { fn set_metadata_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); - create_asset(ASSET_ID, addr.clone()); + create_asset(ASSET_ID, addr.clone(), 1); let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); - assert!(!result.did_revert(), "Contract should have been reverted!"); + assert!(!result.did_revert(), "Contract reverted!"); }); } +// todo: errors: +// - AssetNotLive: when frozen or being destroyed +// - TokenErrors: https://github.com/paritytech/polkadot-sdk/blob/3977f389cce4a00fd7100f95262e0563622b9aa4/substrate/frame/assets/src/functions.rs#L125 #[test] #[ignore] -fn transfer_from_aka_mint_works() { +fn mint_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE); - - let amount: u128 = 100 * UNIT; - // Create asset with contract as owner. - create_asset(ASSET_ID, addr.clone()); - // Check Bob's asset balance before minting through contract. - let bob_balance_before = Assets::balance(ASSET_ID, &BOB); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); + let amount: Balance = 100 * UNIT; - let result = transfer_from(addr.clone(), ASSET_ID, None, Some(BOB), 100 * UNIT, &[0u8]); + assert_eq!( + decoded::(transfer_from( + addr.clone(), + ASSET_ID, + None, + Some(BOB), + amount, + &[0u8] + )), + FungiblesError::Unknown + ); + create_asset(ASSET_ID, ALICE, 2); + assert_eq!( + decoded::(transfer_from( + addr.clone(), + ASSET_ID, + None, + Some(BOB), + amount, + &[0u8] + )), + FungiblesError::NoPermission + ); + assert_eq!( + decoded::(transfer_from( + addr.clone(), + ASSET_ID, + None, + Some(BOB), + 1, + &[0u8] + )), + FungiblesError::BelowMinimum + ); + let asset = 2; + create_asset(asset, addr.clone(), 2); + let bob_balance_before_mint = Assets::balance(asset, &BOB); + let result = transfer_from(addr.clone(), asset, None, Some(BOB), 100 * UNIT, &[0u8]); assert!(!result.did_revert(), "Contract reverted!"); - - let bob_balance_after = Assets::balance(ASSET_ID, &BOB); - assert_eq!(bob_balance_after, bob_balance_before + amount); + let bob_balance_after_mint = Assets::balance(asset, &BOB); + assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount); }); } + +#[test] +#[ignore] +fn transfer_works() {} diff --git a/runtime/devnet/src/extensions/tests/mod.rs b/runtime/devnet/src/extensions/tests/mod.rs index 30d1a924..03cda2cd 100644 --- a/runtime/devnet/src/extensions/tests/mod.rs +++ b/runtime/devnet/src/extensions/tests/mod.rs @@ -6,11 +6,13 @@ use sp_runtime::{traits::Hash, AccountId32, BuildStorage}; mod local_fungibles; +type Balance = u128; const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); const BOB: AccountId32 = AccountId32::new([2_u8; 32]); -const INIT_VALUE: u128 = 100_000_000 * UNIT; +const INIT_AMOUNT: Balance = 100_000_000 * UNIT; +const INIT_VALUE: Balance = 100 * UNIT; const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); fn new_test_ext() -> sp_io::TestExternalities { @@ -19,7 +21,7 @@ fn new_test_ext() -> sp_io::TestExternalities { .expect("Frame system builds valid default genesis config"); pallet_balances::GenesisConfig:: { - balances: vec![(ALICE, INIT_VALUE), (BOB, INIT_VALUE)], + balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT)], } .assimilate_storage(&mut t) .expect("Pallet balances storage can be assimilated"); @@ -65,7 +67,7 @@ fn do_bare_call( } // Deploy, instantiate and return contract address. -fn instantiate(contract: &str, init_value: u128) -> AccountId32 { +fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { let (wasm_binary, _) = load_wasm_module::(contract).expect("could not read .wasm file"); let result = Contracts::bare_instantiate( @@ -75,7 +77,7 @@ fn instantiate(contract: &str, init_value: u128) -> AccountId32 { None, Code::Upload(wasm_binary), function_selector("new"), - vec![], + salt, DEBUG_OUTPUT, CollectEvents::Skip, ) From 1022926e0d35ee56930a0757655df3c7f12b6ec4 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 6 Jun 2024 11:48:55 +0200 Subject: [PATCH 05/27] test: add transfer --- pop-api/examples/fungibles/lib.rs | 108 +++++---- pop-api/src/lib.rs | 7 +- pop-api/src/v0/assets/fungibles.rs | 206 ++++++++++-------- pop-api/src/v0/balances.rs | 10 +- .../src/extensions/tests/local_fungibles.rs | 205 ++++++++++++----- runtime/devnet/src/extensions/tests/mod.rs | 1 + 6 files changed, 344 insertions(+), 193 deletions(-) diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index e44c4347..68e43865 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -1,6 +1,10 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -// Fungibles wrapper contract to allow contracts to interact with local fungibles without the pop api. +/// Local Fungibles: +/// 1. PSP-22 Interface +/// 2. PSP-22 Metadata Interface +/// 3. Asset Management +/// use ink::prelude::vec::Vec; use pop_api::{ assets::fungibles::*, @@ -10,6 +14,8 @@ use pop_api::{ #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum ContractError { + /// The asset is not live; either frozen or being destroyed. + AssetNotLive, /// The amount to mint is less than the existential deposit. BelowMinimum, /// Unspecified dispatch error, providing the index and its error index (if none `0`). @@ -24,6 +30,8 @@ pub enum ContractError { MinBalanceZero, /// Unspecified pallet error, providing pallet index and error index. ModuleError { pallet: u8, error: u16 }, + /// The account to alter does not exist. + NoAccount, /// The signing account has no permission to do the operation. NoPermission, /// The given asset ID is unknown. @@ -33,6 +41,7 @@ pub enum ContractError { impl From for ContractError { fn from(error: FungiblesError) -> Self { match error { + FungiblesError::AssetNotLive => ContractError::AssetNotLive, FungiblesError::BelowMinimum => ContractError::BelowMinimum, FungiblesError::DispatchError { index, error } => { ContractError::DispatchError { index, error } @@ -44,6 +53,7 @@ impl From for ContractError { FungiblesError::ModuleError { pallet, error } => { ContractError::ModuleError { pallet, error } }, + FungiblesError::NoAccount => ContractError::NoAccount, FungiblesError::NoPermission => ContractError::NoPermission, FungiblesError::Unknown => ContractError::Unknown, } @@ -68,6 +78,16 @@ mod fungibles { Default::default() } + /// 1. PSP-22 Interface: + /// - total_supply + /// - balance_of + /// - allowance + /// - transfer + /// - transfer_from + /// - approve + /// - increase_allowance + /// - decrease_allowance + #[ink(message)] pub fn total_supply(&self, id: AssetId) -> Result { total_supply(id).map_err(From::from) @@ -89,13 +109,58 @@ mod fungibles { } #[ink(message)] - pub fn asset_exists(&self, id: AssetId) -> Result { - asset_exists(id).map_err(From::from) + pub fn transfer(&self, id: AssetId, to: AccountId32, value: Balance) -> Result<()> { + ink::env::debug_println!( + "PopApiAssetsExample::transfer: id: {:?}, to: {:?} value: {:?}", + id, + to, + value, + ); + + let result = transfer(id, to, value); + ink::env::debug_println!("Result: {:?}", result); + result.map_err(From::from) + } + + #[ink(message)] + pub fn transfer_from( + &self, + id: AssetId, + from: Option, + to: Option, + value: Balance, + // Size needs to be known at compile time or ink's `Vec` + data: Vec, + ) -> Result<()> { + ink::env::debug_println!( + "PopApiAssetsExample::transfer_from: id: {:?}, from: {:?}, to: {:?} value: {:?}", + id, + from, + to, + value, + ); + + let result = transfer_from(id, from, to, value, &data); + ink::env::debug_println!("Result: {:?}", result); + result.map_err(From::from) } + /// 2. PSP-22 Metadata Interface: + /// - token_name + /// - token_symbol + /// - token_decimals + + /// 3. Asset Management: + /// - create + /// - start_destroy + /// - destroy_accounts + /// - destroy_approvals + /// - finish_destroy + /// - set_metadata + /// - clear_metadata + #[ink(message)] pub fn create(&self, id: AssetId, admin: AccountId32, min_balance: Balance) -> Result<()> { - // create(id, admin, min_balance).map_err(From::from) ink::env::debug_println!( "PopApiAssetsExample::create: id: {:?} admin: {:?} min_balance: {:?}", id, @@ -115,7 +180,6 @@ mod fungibles { symbol: Vec, decimals: u8, ) -> Result<()> { - // set_metadata(id, name, symbol, decimals).map_err(From::from) ink::env::debug_println!( "PopApiAssetsExample::set_metadata: id: {:?} name: {:?} symbol: {:?}, decimals: {:?}", id, @@ -129,39 +193,9 @@ mod fungibles { } #[ink(message)] - pub fn mint(&self, id: AssetId, beneficiary: AccountId32, amount: Balance) -> Result<()> { - ink::env::debug_println!( - "PopApiAssetsExample::mint: id: {:?}, beneficiary: {:?} amount: {:?}", - id, - beneficiary, - amount, - ); - - let result = mint(id, beneficiary, amount); - ink::env::debug_println!("Result: {:?}", result); - result.map_err(From::from) + pub fn asset_exists(&self, id: AssetId) -> Result { + asset_exists(id).map_err(From::from) } - - // #[ink(message)] - // pub fn transfer_from( - // id: AssetId, - // from: Option, - // to: Option, - // value: Balance, - // data: [u8], - // ) -> Result<()> { - // ink::env::debug_println!( - // "PopApiAssetsExample::transfer_from: id: {:?}, from: {:?}, to: {:?} value: {:?}", - // id, - // from, - // to, - // value, - // ); - // - // let result = transfer_from(id, from, to, value)?; - // ink::env::debug_println!("Result: {:?}", result); - // result - // } } #[cfg(test)] diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 014b5a29..be448890 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -21,16 +21,11 @@ type MaxTips = u32; pub type Result = core::result::Result; -struct ModuleError { - pallet: u8, - error: u16, -} - #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum PopApiError { Assets(assets::fungibles::AssetsError), - Balances(balances::Error), + Balances(balances::BalancesError), Contracts(contracts::Error), DecodingFailed, Nfts(nfts::Error), diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index de624938..df9033c7 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -1,7 +1,6 @@ use crate::{ - AccountId, Balance, - PopApiError::{UnknownDispatchStatusCode, UnknownModuleStatusCode}, - RuntimeCall, *, + balances::BalancesError, AccountId, Balance, PopApiError::UnknownModuleStatusCode, RuntimeCall, + *, }; use ink::prelude::vec::Vec; use primitives::AssetId; @@ -62,28 +61,6 @@ pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result>, min_balance: Balance) -> Result<()> { -pub fn create( - id: AssetId, - admin: impl Into>, - min_balance: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Assets(AssetsCall::Create { - id: id.into(), - admin: admin.into(), - min_balance, - }))?) -} - /// Transfers `value` amount of tokens from the caller's account to account `to`, with additional /// `data` in unspecified format. /// @@ -94,29 +71,27 @@ pub fn create( /// /// # Returns /// Returns `Ok(())` if successful, or an error if the transfer fails. -// #[allow(unused_variables)] -// pub fn transfer( -// id: AssetId, -// to: impl Into>, -// value: Balance, -// ) -> Result<()> { -// todo!() -// // TODO: transfer or transfer_keep_alive -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::Transfer { -// // id: id.into(), -// // target: target.into(), -// // amount: Compact(amount), -// // }))?) -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { -// // id: id.into(), -// // target: target.into(), -// // amount: Compact(amount), -// // }))?) -// } +pub fn transfer( + id: AssetId, + to: impl Into>, + value: Balance, +) -> Result<()> { + // TODO: transfer or transfer_keep_alive + // Ok(dispatch(RuntimeCall::Assets(AssetsCall::Transfer { + // id: id.into(), + // target: target.into(), + // amount: Compact(amount), + // }))?) + Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { + id: id.into(), + target: to.into(), + amount: Compact(value), + }))?) +} -/// Transfers `value` tokens on the behalf of `from` to the account `to` with additional `data` -/// in unspecified format. This can be used to allow a contract to transfer tokens on ones behalf -/// and/or to charge fees in sub-currencies, for example. +/// Transfers `value` tokens on behalf of `from` to account `to` with additional `data` +/// in unspecified format. If `from` is equal to `None`, tokens will be minted to account `to`. If +/// `to` is equal to `None`, tokens will be burned from account `from`. /// /// # Arguments /// * `id` - The ID of the asset. @@ -126,43 +101,26 @@ pub fn create( /// /// # Returns /// Returns `Ok(())` if successful, or an error if the transfer fails. -// pub fn transfer_from( -// id: AssetId, -// from: impl Into>, -// to: impl Into>, -// value: Balance, -// ) -> Result<()> { -//todo!() -// TODO: depending on `from` and `to`, decide whether to mint, burn or transfer_approved. -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::Mint { -// id: id.into(), -// beneficiary: beneficiary.into(), -// amount: Compact(amount), -// }))?) -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::Burn { -// id: id.into(), -// who: who.into(), -// amount: Compact(amount), -// }))?) -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { -// id: id.into(), -// owner: from.into(), -// destination: to.into(), -// amount: Compact(value), -// }))?) -// } - -/// Mint assets of a particular class. -pub fn mint( +pub fn transfer_from( id: AssetId, - beneficiary: impl Into>, - amount: Balance, + from: Option>>, + to: Option>>, + value: Balance, + _data: &[u8], ) -> Result<()> { - Ok(dispatch(RuntimeCall::Assets(AssetsCall::Mint { - id: id.into(), - beneficiary: beneficiary.into(), - amount: Compact(amount), - }))?) + match (from, to) { + (None, Some(to)) => mint(id, to, value), + // (Some(from), None) => burn(id, from, value), + (Some(from), Some(to)) => { + Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { + id: id.into(), + owner: from.into(), + destination: to.into(), + amount: Compact(value), + }))?) + }, + _ => Ok(()), + } } /// Approves an account to spend a specified number of tokens on behalf of the caller. @@ -277,6 +235,27 @@ pub fn mint( /// - set_metadata /// - clear_metadata +/// Create a new token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `admin` - The account that will administer the asset. +/// * `min_balance` - The minimum balance required for accounts holding this asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the creation fails. +pub fn create( + id: AssetId, + admin: impl Into>, + min_balance: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::Assets(AssetsCall::Create { + id: id.into(), + admin: admin.into(), + min_balance, + }))?) +} + /// Start the process of destroying a token with a given asset ID. /// /// # Arguments @@ -362,10 +341,22 @@ pub fn asset_exists(id: AssetId) -> Result { Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id)))?) } -// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected -// to be compact encoded. The pop api handles that for the developer. -// -// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development +/// Mint assets of a particular class. +fn mint( + id: AssetId, + beneficiary: impl Into>, + amount: Balance, +) -> Result<()> { + Ok(dispatch(RuntimeCall::Assets(AssetsCall::Mint { + id: id.into(), + beneficiary: beneficiary.into(), + amount: Compact(amount), + }))?) +} + +// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount +// (`Balance`) are expected to be compact encoded. The pop api handles that for the developer. +// https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development // // Asset id that is compact encoded. type AssetIdParameter = Compact; @@ -423,7 +414,6 @@ pub(crate) enum AssetsCall { }, } -// TODO: remove unnecessary errors #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub(crate) enum AssetsError { @@ -514,6 +504,8 @@ impl TryFrom for AssetsError { #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum FungiblesError { + /// The asset is not live; either frozen or being destroyed. + AssetNotLive, /// The amount to mint is less than the existential deposit. BelowMinimum, /// Unspecified dispatch error, providing the index and its error index (if none `0`). @@ -528,16 +520,20 @@ pub enum FungiblesError { MinBalanceZero, /// Unspecified pallet error, providing pallet index and error index. ModuleError { pallet: u8, error: u16 }, + /// The account to alter does not exist. + NoAccount, /// The signing account has no permission to do the operation. NoPermission, /// The given asset ID is unknown. Unknown, } -impl From for FungiblesError { - fn from(error: balances::Error) -> Self { +impl From for FungiblesError { + fn from(error: BalancesError) -> Self { match error { - balances::Error::InsufficientBalance => FungiblesError::InsufficientBalance, + // TODO: this insufficient balance is different than the assets variant. This one is + // for a deposit of creating an asset, the latter is for transfer tokens. + BalancesError::InsufficientBalance => FungiblesError::InsufficientBalance, _ => FungiblesError::ModuleError { pallet: 40, error: error as u16 }, } } @@ -546,8 +542,10 @@ impl From for FungiblesError { impl From for FungiblesError { fn from(error: dispatch_error::TokenError) -> Self { match error { - dispatch_error::TokenError::UnknownAsset => FungiblesError::Unknown, dispatch_error::TokenError::BelowMinimum => FungiblesError::BelowMinimum, + // ED is not respected. + dispatch_error::TokenError::OnlyProvider => FungiblesError::InsufficientBalance, + dispatch_error::TokenError::UnknownAsset => FungiblesError::Unknown, _ => FungiblesError::DispatchError { index: 7, error: error as u8 }, } } @@ -556,12 +554,15 @@ impl From for FungiblesError { impl From for FungiblesError { fn from(error: AssetsError) -> Self { match error { + AssetsError::AssetNotLive => FungiblesError::AssetNotLive, + AssetsError::BalanceLow => FungiblesError::InsufficientBalance, AssetsError::Unapproved => FungiblesError::InsufficientAllowance, AssetsError::InUse => FungiblesError::InUse, AssetsError::MinBalanceZero => FungiblesError::MinBalanceZero, AssetsError::NoPermission => FungiblesError::NoPermission, + AssetsError::NoAccount => FungiblesError::NoAccount, AssetsError::Unknown => FungiblesError::Unknown, - _ => FungiblesError::ModuleError { pallet: 40, error: error as u16 }, + _ => FungiblesError::ModuleError { pallet: 52, error: error as u16 }, } } } @@ -586,3 +587,24 @@ impl From for FungiblesError { } } } + +// macro_rules! impl_error_conversion { +// ($pallet_index:, $pallet_error:ty, $interface_error:ty, $($variant:ident),*) => { +// impl From<$pallet_error> for $interface_error { +// fn from(error: $pallet_error) -> Self { +// match error { +// $( +// <$pallet_error>::$variant => <$interface_error>::$variant, +// )* +// _ => <$interface_error>::ModuleError { pallet: 0, error: [255, 0, 0, 0] }, // Default case +// } +// } +// } +// +// impl FromPalletError<$pallet_error> for $interface_error { +// fn from_pallet_error(error: $pallet_error) -> Self { +// Self::from(error) +// } +// } +// }; +// } diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index bc422ef4..08db0a75 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -3,7 +3,7 @@ use crate::{ PopApiError::UnknownModuleStatusCode, }; -type Result = core::result::Result; +type Result = core::result::Result; pub fn transfer_keep_alive( dest: impl Into>, @@ -28,7 +28,7 @@ pub(crate) enum BalancesCall { #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub(crate) enum Error { +pub(crate) enum BalancesError { /// Vesting balance too high to send value. VestingBalance, /// Account liquidity restrictions prevent withdrawal. @@ -55,11 +55,11 @@ pub(crate) enum Error { DeltaZero, } -impl TryFrom for Error { +impl TryFrom for BalancesError { type Error = PopApiError; fn try_from(status_code: u32) -> core::result::Result { - use Error::*; + use BalancesError::*; match status_code { 0 => Ok(VestingBalance), 1 => Ok(LiquidityRestrictions), @@ -78,7 +78,7 @@ impl TryFrom for Error { } } -impl From for Error { +impl From for BalancesError { fn from(error: PopApiError) -> Self { match error { PopApiError::Balances(e) => e, diff --git a/runtime/devnet/src/extensions/tests/local_fungibles.rs b/runtime/devnet/src/extensions/tests/local_fungibles.rs index 5bd7dac0..5de162c9 100644 --- a/runtime/devnet/src/extensions/tests/local_fungibles.rs +++ b/runtime/devnet/src/extensions/tests/local_fungibles.rs @@ -1,10 +1,11 @@ #![cfg(test)] use super::*; -use pallet_contracts::debug::ExecResult; #[derive(Decode, Encode, Debug, Eq, PartialEq)] enum FungiblesError { + /// The asset is not live; either frozen or being destroyed. + AssetNotLive, /// The amount to mint is less than the existential deposit. BelowMinimum, /// Unspecified dispatch error, providing the index and optionally its error index. @@ -19,13 +20,15 @@ enum FungiblesError { MinBalanceZero, /// Unspecified pallet error, providing pallet index and error index. ModuleError { pallet: u8, error: u16 }, + /// The account to alter does not exist. + NoAccount, /// The signing account has no permission to do the operation. NoPermission, /// The given asset ID is unknown. Unknown, } -const ASSET_ID: u32 = 1; +const ASSET_ID: AssetId = 1; fn decoded(result: ExecReturnValue) -> T { ::decode(&mut &result.data[2..]).unwrap() @@ -33,39 +36,42 @@ fn decoded(result: ExecReturnValue) -> T { fn allowance( addr: AccountId32, - asset_id: u32, + asset_id: AssetId, owner: AccountId32, spender: AccountId32, -) -> ExecReturnValue { +) -> Balance { let function = function_selector("allowance"); let params = [function, asset_id.encode(), owner.encode(), spender.encode()].concat(); - do_bare_call(addr, params, 0).expect("should work") + let result = do_bare_call(addr, params, 0).expect("should work"); + decoded::(result) } // Call balance_of contract message. -fn balance_of(addr: AccountId32, asset_id: u32, owner: AccountId32) -> ExecReturnValue { +fn balance_of(addr: AccountId32, asset_id: AssetId, owner: AccountId32) -> Balance { let function = function_selector("balance_of"); let params = [function, asset_id.encode(), owner.encode()].concat(); - do_bare_call(addr, params, 0).expect("should work") + let result = do_bare_call(addr, params, 0).expect("should work"); + decoded::(result) } // Call total_supply contract message. -fn total_supply(addr: AccountId32, asset_id: u32) -> Balance { +fn total_supply(addr: AccountId32, asset_id: AssetId) -> Balance { let function = function_selector("total_supply"); let params = [function, asset_id.encode()].concat(); let result = do_bare_call(addr, params, 0).expect("should work"); decoded::(result) } -fn asset_exists(addr: AccountId32, asset_id: u32) -> ExecReturnValue { +fn asset_exists(addr: AccountId32, asset_id: AssetId) -> bool { let function = function_selector("asset_exists"); let params = [function, asset_id.encode()].concat(); - do_bare_call(addr, params, 0).expect("should work") + let result = do_bare_call(addr, params, 0).expect("should work"); + decoded::(result) } fn create( addr: AccountId32, - asset_id: u32, + asset_id: AssetId, admin: AccountId32, min_balance: Balance, ) -> ExecReturnValue { @@ -76,7 +82,7 @@ fn create( fn set_metadata( addr: AccountId32, - asset_id: u32, + asset_id: AssetId, name: Vec, symbol: Vec, decimals: u8, @@ -87,26 +93,34 @@ fn set_metadata( do_bare_call(addr, params, 0).expect("should work") } +fn transfer( + addr: AccountId32, + asset_id: AssetId, + to: AccountId32, + value: Balance, +) -> ExecReturnValue { + let function = function_selector("transfer"); + let params = [function, asset_id.encode(), to.encode(), value.encode()].concat(); + do_bare_call(addr, params, 0).expect("should work") +} + fn transfer_from( addr: AccountId32, - asset_id: u32, - _from: Option, + asset_id: AssetId, + from: Option, to: Option, value: Balance, - _data: &[u8], + data: &[u8], ) -> ExecReturnValue { - // let function = function_selector("transfer_from"); - // let params = - // [function, asset_id.encode(), from.encode(), to.encode(), value.encode(), data.encode()] - // .concat(); - // do_bare_call(addr, params, 0) - let function = function_selector("mint"); - let params = [function, asset_id.encode(), to.unwrap().encode(), value.encode()].concat(); + let function = function_selector("transfer_from"); + let params = + [function, asset_id.encode(), from.encode(), to.encode(), value.encode(), data.encode()] + .concat(); do_bare_call(addr, params, 0).expect("should work") } // Create an asset and mint to owner. -fn create_asset(asset_id: u32, owner: AccountId32, min_balance: Balance) { +fn create_asset(asset_id: AssetId, owner: AccountId32, min_balance: Balance) -> AssetId { assert_eq!( Assets::create( RuntimeOrigin::signed(owner.clone()), @@ -116,20 +130,27 @@ fn create_asset(asset_id: u32, owner: AccountId32, min_balance: Balance) { ), Ok(()) ); + asset_id } // Create an asset and mint to owner. -fn create_asset_and_mint_to(asset_id: u32, owner: AccountId32, to: AccountId32, value: Balance) { +fn create_asset_and_mint_to( + asset_id: AssetId, + owner: AccountId32, + to: AccountId32, + value: Balance, +) -> AssetId { create_asset(asset_id, owner.clone(), 1); assert_eq!( Assets::mint(RuntimeOrigin::signed(owner.into()), asset_id.into(), to.into(), value,), Ok(()) ); + asset_id } // Create an asset, mints to, and approves spender. fn create_asset_mint_and_approve( - asset_id: u32, + asset_id: AssetId, owner: AccountId32, to: AccountId32, mint: Balance, @@ -148,6 +169,21 @@ fn create_asset_mint_and_approve( ); } +// Freeze an asset. +fn freeze_asset(asset_id: AssetId, owner: AccountId32) { + assert_eq!(Assets::freeze_asset(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); +} + +// Thaw an asset. +fn thaw_asset(asset_id: AssetId, owner: AccountId32) { + assert_eq!(Assets::thaw_asset(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); +} + +// Start destroying an asset. +fn start_destroy_asset(asset_id: AssetId, owner: AccountId32) { + assert_eq!(Assets::start_destroy(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); +} + #[test] #[ignore] fn total_supply_works() { @@ -180,17 +216,11 @@ fn balance_of_works() { ); // No tokens in circulation. - assert_eq!( - Assets::balance(ASSET_ID, BOB).encode(), - balance_of(addr.clone(), ASSET_ID, BOB).data[2..] - ); + assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr.clone(), ASSET_ID, BOB)); // Tokens in circulation. create_asset_and_mint_to(ASSET_ID, addr.clone(), BOB, 100); - assert_eq!( - Assets::balance(ASSET_ID, BOB).encode(), - balance_of(addr, ASSET_ID, BOB).data[2..] - ); + assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr, ASSET_ID, BOB)); }); } @@ -207,15 +237,15 @@ fn allowance_works() { // No tokens in circulation. assert_eq!( - Assets::allowance(ASSET_ID, &BOB, &ALICE).encode(), - allowance(addr.clone(), ASSET_ID, BOB, ALICE).data[2..] + Assets::allowance(ASSET_ID, &BOB, &ALICE), + allowance(addr.clone(), ASSET_ID, BOB, ALICE) ); // Tokens in circulation. create_asset_mint_and_approve(ASSET_ID, addr.clone(), BOB, 100, ALICE, 50); assert_eq!( - Assets::allowance(ASSET_ID, &BOB, &ALICE).encode(), - allowance(addr, ASSET_ID, BOB, ALICE).data[2..] + Assets::allowance(ASSET_ID, &BOB, &ALICE), + allowance(addr, ASSET_ID, BOB, ALICE) ); }); } @@ -232,14 +262,11 @@ fn asset_exists_works() { ); // No tokens in circulation. - assert_eq!( - Assets::asset_exists(ASSET_ID).encode(), - asset_exists(addr.clone(), ASSET_ID).data[2..] - ); + assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr.clone(), ASSET_ID)); // Tokens in circulation. create_asset(ASSET_ID, addr.clone(), 1); - assert_eq!(Assets::asset_exists(ASSET_ID).encode(), asset_exists(addr, ASSET_ID).data[2..]); + assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr, ASSET_ID)); }); } @@ -299,11 +326,12 @@ fn set_metadata_works() { } // todo: errors: -// - AssetNotLive: when frozen or being destroyed -// - TokenErrors: https://github.com/paritytech/polkadot-sdk/blob/3977f389cce4a00fd7100f95262e0563622b9aa4/substrate/frame/assets/src/functions.rs#L125 +// - TokenErrors +// - Arithmetic +// - https://github.com/paritytech/polkadot-sdk/blob/3977f389cce4a00fd7100f95262e0563622b9aa4/substrate/frame/assets/src/functions.rs#L125 #[test] #[ignore] -fn mint_works() { +fn transfer_from_mint_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); let addr = instantiate( @@ -316,7 +344,7 @@ fn mint_works() { assert_eq!( decoded::(transfer_from( addr.clone(), - ASSET_ID, + 1, None, Some(BOB), amount, @@ -324,11 +352,11 @@ fn mint_works() { )), FungiblesError::Unknown ); - create_asset(ASSET_ID, ALICE, 2); + let asset = create_asset(1, ALICE, 2); assert_eq!( decoded::(transfer_from( addr.clone(), - ASSET_ID, + asset, None, Some(BOB), amount, @@ -339,7 +367,7 @@ fn mint_works() { assert_eq!( decoded::(transfer_from( addr.clone(), - ASSET_ID, + asset, None, Some(BOB), 1, @@ -347,16 +375,87 @@ fn mint_works() { )), FungiblesError::BelowMinimum ); - let asset = 2; - create_asset(asset, addr.clone(), 2); + let asset = create_asset(2, addr.clone(), 2); + freeze_asset(asset, addr.clone()); + assert_eq!( + decoded::(transfer_from( + addr.clone(), + asset, + None, + Some(BOB), + amount, + &[0u8] + )), + FungiblesError::AssetNotLive + ); + thaw_asset(asset, addr.clone()); let bob_balance_before_mint = Assets::balance(asset, &BOB); - let result = transfer_from(addr.clone(), asset, None, Some(BOB), 100 * UNIT, &[0u8]); + let result = transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8]); assert!(!result.did_revert(), "Contract reverted!"); let bob_balance_after_mint = Assets::balance(asset, &BOB); assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount); + start_destroy_asset(asset, addr.clone()); + assert_eq!( + decoded::(transfer_from( + addr.clone(), + asset, + None, + Some(BOB), + amount, + &[0u8] + )), + FungiblesError::AssetNotLive + ); }); } +// Todo: error: +// - Frozen: account is frozen, who do you freeze an account? +// - https://github.com/paritytech/polkadot-sdk/blob/2460cddf57660a88844d201f769eb17a7accce5a/substrate/frame/assets/src/functions.rs#L161 +// - ArithmeticError: Underflow, Overflow +// - https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/functions.rs#L125 +// - #[test] #[ignore] -fn transfer_works() {} +fn transfer_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); + let amount: Balance = 100 * UNIT; + + assert_eq!( + decoded::(transfer(addr.clone(), 1, BOB, amount,)), + FungiblesError::Unknown + ); + let asset = create_asset_and_mint_to(1, ALICE, addr.clone(), amount); + freeze_asset(asset, ALICE); + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount,)), + FungiblesError::AssetNotLive + ); + thaw_asset(asset, ALICE); + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), + FungiblesError::InsufficientBalance + ); + // Errors due to ED. Could be Belowminimum + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount)), + FungiblesError::InsufficientBalance + ); + let bob_balance_before_mint = Assets::balance(asset, &BOB); + let result = transfer(addr.clone(), asset, BOB, amount / 2); + assert!(!result.did_revert(), "Contract reverted!"); + let bob_balance_after_mint = Assets::balance(asset, &BOB); + assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); + start_destroy_asset(asset, ALICE); + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), + FungiblesError::AssetNotLive + ); + }); +} diff --git a/runtime/devnet/src/extensions/tests/mod.rs b/runtime/devnet/src/extensions/tests/mod.rs index 03cda2cd..cbd13d62 100644 --- a/runtime/devnet/src/extensions/tests/mod.rs +++ b/runtime/devnet/src/extensions/tests/mod.rs @@ -7,6 +7,7 @@ use sp_runtime::{traits::Hash, AccountId32, BuildStorage}; mod local_fungibles; type Balance = u128; +type AssetId = u32; const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); From ecc82e266d772bbe6d57b3feb9049e3228152f8a Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 6 Jun 2024 11:51:10 +0200 Subject: [PATCH 06/27] chore: remove polkadot launch --- polkadot-launch/config.json | 39 ------------------------------------- 1 file changed, 39 deletions(-) delete mode 100644 polkadot-launch/config.json diff --git a/polkadot-launch/config.json b/polkadot-launch/config.json deleted file mode 100644 index f03f983a..00000000 --- a/polkadot-launch/config.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "relaychain": { - "bin": "../../polkadot/target/release/polkadot", - "chain": "rococo-local", - "nodes": [ - { - "name": "alice", - "wsPort": 9944, - "port": 30444 - }, - { - "name": "bob", - "wsPort": 9955, - "port": 30555 - } - ] - }, - "parachains": [ - { - "bin": "../target/release/polkadot-parachain", - "id": "200", - "balance": "1000000000000000000000", - "nodes": [ - { - "wsPort": 9988, - "name": "alice", - "port": 31200, - "flags": [ - "--force-authoring", - "--", - "--execution=wasm" - ] - } - ] - } - ], - "types": { - } -} From e81f78a957ff3773bc45e93a61f8bf3c17538bc0 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 6 Jun 2024 14:04:31 +0200 Subject: [PATCH 07/27] # This is a combination of 8 commits. # This is the 1st commit message: refactor: general # This is the commit message #2: init # This is the commit message #3: begin refactor # This is the commit message #4: refactor: error handling # This is the commit message #5: tests: add error handling tests # This is the commit message #6: WIP # This is the commit message #7: finalise error handling # This is the commit message #8: refactor: easier review --- Cargo.lock | 2723 ++++++++++------ pop-api/examples/fungibles/expanded.rs | 2766 ----------------- pop-api/examples/fungibles/lib.rs | 94 +- pop-api/src/error.rs | 255 ++ pop-api/src/lib.rs | 58 +- pop-api/src/v0/assets/fungibles.rs | 610 ---- pop-api/src/v0/assets/mod.rs | 3 +- pop-api/src/v0/assets/pallets/assets.rs | 491 +++ pop-api/src/v0/assets/pallets/mod.rs | 1 + pop-api/src/v0/assets/use_cases/fungibles.rs | 372 +++ pop-api/src/v0/assets/use_cases/mod.rs | 1 + pop-api/src/v0/balances.rs | 21 +- pop-api/src/v0/contracts.rs | 152 - pop-api/src/v0/cross_chain/mod.rs | 15 +- pop-api/src/v0/dispatch_error.rs | 57 - pop-api/src/v0/mod.rs | 4 +- pop-api/src/v0/nfts.rs | 15 +- primitives/src/storage_keys.rs | 3 - runtime/devnet/Cargo.toml | 2 + .../src/{extensions/mod.rs => extensions.rs} | 45 +- runtime/devnet/src/extensions/tests/mod.rs | 89 - runtime/devnet/src/lib.rs | 2 + .../{extensions => }/tests/local_fungibles.rs | 199 +- runtime/devnet/src/tests/mod.rs | 262 ++ 24 files changed, 3335 insertions(+), 4905 deletions(-) delete mode 100644 pop-api/examples/fungibles/expanded.rs create mode 100644 pop-api/src/error.rs delete mode 100644 pop-api/src/v0/assets/fungibles.rs create mode 100644 pop-api/src/v0/assets/pallets/assets.rs create mode 100644 pop-api/src/v0/assets/pallets/mod.rs create mode 100644 pop-api/src/v0/assets/use_cases/fungibles.rs create mode 100644 pop-api/src/v0/assets/use_cases/mod.rs delete mode 100644 pop-api/src/v0/contracts.rs delete mode 100644 pop-api/src/v0/dispatch_error.rs rename runtime/devnet/src/{extensions/mod.rs => extensions.rs} (97%) delete mode 100644 runtime/devnet/src/extensions/tests/mod.rs rename runtime/devnet/src/{extensions => }/tests/local_fungibles.rs (70%) create mode 100644 runtime/devnet/src/tests/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 17cc70e5..77c563fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -343,7 +343,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" dependencies = [ "num-traits", - "rand", + "rand 0.8.5", ] [[package]] @@ -358,6 +358,12 @@ version = "6.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f840fb7195bcfc5e17ea40c26e5ce6d5b9ce5d584466e17703209657e459ae0" +[[package]] +name = "array-init" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" + [[package]] name = "arrayref" version = "0.3.7" @@ -373,6 +379,12 @@ dependencies = [ "nodrop", ] +[[package]] +name = "arrayvec" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" + [[package]] name = "arrayvec" version = "0.7.4" @@ -404,7 +416,7 @@ dependencies = [ "proc-macro2", "quote", "syn 1.0.109", - "synstructure", + "synstructure 0.12.6", ] [[package]] @@ -486,17 +498,17 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-consensus-aura", - "sp-core", + "sp-core 29.0.0", "sp-genesis-builder", "sp-inherents", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", - "sp-std", - "sp-storage", + "sp-std 14.0.0", + "sp-storage 20.0.0", "sp-transaction-pool", "sp-version", - "sp-weights", + "sp-weights 28.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -525,9 +537,9 @@ dependencies = [ "parachains-common", "parachains-runtimes-test-utils", "parity-scale-codec", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -551,8 +563,8 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -909,7 +921,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93f2635620bf0b9d4576eb7bb9a38a55df78bd1205d26fa994b25911a69f212f" dependencies = [ "bitcoin_hashes", - "rand", + "rand 0.8.5", "rand_core 0.6.4", "serde", "unicode-normalization", @@ -1012,6 +1024,18 @@ dependencies = [ "constant_time_eq 0.3.0", ] +[[package]] +name = "block-buffer" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" +dependencies = [ + "block-padding", + "byte-tools", + "byteorder", + "generic-array 0.12.4", +] + [[package]] name = "block-buffer" version = "0.9.0" @@ -1030,6 +1054,15 @@ dependencies = [ "generic-array 0.14.7", ] +[[package]] +name = "block-padding" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" +dependencies = [ + "byte-tools", +] + [[package]] name = "blocking" version = "1.5.1" @@ -1116,7 +1149,7 @@ dependencies = [ "frame-system", "polkadot-primitives", "sp-api", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -1130,8 +1163,8 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -1145,8 +1178,8 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -1162,9 +1195,9 @@ dependencies = [ "scale-info", "serde", "sp-consensus-grandpa", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -1179,8 +1212,8 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-std", + "sp-core 29.0.0", + "sp-std 14.0.0", ] [[package]] @@ -1196,9 +1229,9 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -1215,9 +1248,9 @@ dependencies = [ "parity-util-mem", "scale-info", "serde", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -1231,8 +1264,8 @@ dependencies = [ "frame-support", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -1250,13 +1283,13 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-state-machine", - "sp-std", - "sp-trie", - "trie-db", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", + "trie-db 0.28.0", ] [[package]] @@ -1269,15 +1302,15 @@ dependencies = [ "bp-parachains", "bp-polkadot-core", "bp-runtime", - "ed25519-dalek", + "ed25519-dalek 2.1.1", "finality-grandpa", "parity-scale-codec", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-grandpa", - "sp-core", - "sp-runtime", - "sp-std", - "sp-trie", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", ] [[package]] @@ -1286,7 +1319,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6663e0179d475e30cfcf28cf597cdc8f4bb1c2c39a557b4cbe0057db0657fb67" dependencies = [ - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -1297,8 +1330,8 @@ checksum = "86ff4abe93be7bc1663adc41817b1aa3476fbec953ce361537419924310d5dd4" dependencies = [ "parity-scale-codec", "scale-info", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", ] [[package]] @@ -1328,11 +1361,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-trie", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", "staging-xcm", "staging-xcm-builder", ] @@ -1745,6 +1778,26 @@ dependencies = [ "tiny-keccak", ] +[[package]] +name = "const_env" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e9e4f72c6e3398ca6da372abd9affd8f89781fe728869bbf986206e9af9627e" +dependencies = [ + "const_env_impl", +] + +[[package]] +name = "const_env_impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a4f51209740b5e1589e702b3044cdd4562cef41b6da404904192ffffb852d62" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "constant_time_eq" version = "0.1.5" @@ -2044,8 +2097,8 @@ dependencies = [ "sc-client-api", "sc-service", "sp-blockchain", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "url", ] @@ -2068,8 +2121,8 @@ dependencies = [ "sc-client-api", "sp-api", "sp-consensus", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "tracing", ] @@ -2101,16 +2154,16 @@ dependencies = [ "sc-telemetry", "schnellru", "sp-api", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-keystore", - "sp-runtime", - "sp-state-machine", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "sp-timestamp", "substrate-prometheus-endpoint", "tracing", @@ -2138,10 +2191,10 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-slots", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "sp-timestamp", - "sp-trie", + "sp-trie 30.0.0", "substrate-prometheus-endpoint", "tracing", ] @@ -2157,8 +2210,8 @@ dependencies = [ "cumulus-primitives-parachain-inherent", "sp-consensus", "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "thiserror", ] @@ -2180,9 +2233,9 @@ dependencies = [ "sc-client-api", "sp-blockchain", "sp-consensus", - "sp-core", - "sp-runtime", - "sp-state-machine", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "tracing", ] @@ -2203,11 +2256,11 @@ dependencies = [ "sp-api", "sp-crypto-hashing", "sp-inherents", - "sp-runtime", - "sp-state-machine", - "sp-std", - "sp-storage", - "sp-trie", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-storage 20.0.0", + "sp-trie 30.0.0", "tracing", ] @@ -2227,12 +2280,12 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-overseer", "polkadot-primitives", - "rand", + "rand 0.8.5", "sc-client-api", "sc-consensus", "sp-consensus", "sp-maybe-compressed-blob", - "sp-runtime", + "sp-runtime 32.0.0", "tracing", ] @@ -2268,8 +2321,8 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "sp-transaction-pool", ] @@ -2286,10 +2339,10 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-aura", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -2315,17 +2368,17 @@ dependencies = [ "polkadot-runtime-common", "polkadot-runtime-parachains", "scale-info", - "sp-core", - "sp-externalities", + "sp-core 29.0.0", + "sp-externalities 0.26.0", "sp-inherents", - "sp-io", - "sp-runtime", - "sp-state-machine", - "sp-std", - "sp-trie", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", "sp-version", "staging-xcm", - "trie-db", + "trie-db 0.28.0", ] [[package]] @@ -2351,8 +2404,8 @@ dependencies = [ "frame-system", "pallet-session", "parity-scale-codec", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -2366,9 +2419,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", ] @@ -2390,10 +2443,10 @@ dependencies = [ "polkadot-runtime-common", "polkadot-runtime-parachains", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-executor", ] @@ -2409,8 +2462,8 @@ dependencies = [ "polkadot-primitives", "sp-api", "sp-consensus-aura", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -2425,9 +2478,9 @@ dependencies = [ "polkadot-primitives", "scale-info", "sp-api", - "sp-runtime", - "sp-std", - "sp-trie", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", "staging-xcm", ] @@ -2441,10 +2494,10 @@ dependencies = [ "cumulus-primitives-core", "parity-scale-codec", "scale-info", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-std", - "sp-trie", + "sp-std 14.0.0", + "sp-trie 30.0.0", ] [[package]] @@ -2453,9 +2506,9 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b74f9141190b9f4bf96a947ade46da64097b77f1ebfa8d611c81724250e119" dependencies = [ - "sp-externalities", - "sp-runtime-interface", - "sp-trie", + "sp-externalities 0.26.0", + "sp-runtime-interface 25.0.0", + "sp-trie 30.0.0", ] [[package]] @@ -2471,9 +2524,9 @@ dependencies = [ "parity-scale-codec", "polkadot-runtime-common", "polkadot-runtime-parachains", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -2499,9 +2552,9 @@ dependencies = [ "sc-tracing", "sp-api", "sp-consensus", - "sp-core", - "sp-runtime", - "sp-state-machine", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", ] [[package]] @@ -2519,7 +2572,7 @@ dependencies = [ "sc-client-api", "sp-api", "sp-blockchain", - "sp-state-machine", + "sp-state-machine 0.36.0", "thiserror", ] @@ -2559,7 +2612,7 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-runtime", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "tokio", "tracing", @@ -2581,7 +2634,7 @@ dependencies = [ "parity-scale-codec", "pin-project", "polkadot-overseer", - "rand", + "rand 0.8.5", "sc-client-api", "sc-rpc-api", "sc-service", @@ -2593,10 +2646,10 @@ dependencies = [ "sp-api", "sp-authority-discovery", "sp-consensus-babe", - "sp-core", - "sp-runtime", - "sp-state-machine", - "sp-storage", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-storage 20.0.0", "sp-version", "thiserror", "tokio", @@ -2614,10 +2667,23 @@ dependencies = [ "cumulus-primitives-core", "parity-scale-codec", "polkadot-primitives", - "sp-runtime", - "sp-state-machine", - "sp-std", - "sp-trie", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", +] + +[[package]] +name = "curve25519-dalek" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a9b85542f99a2dfa2a1b8e192662741c9859a846b296bef1c92ef9b58b5a216" +dependencies = [ + "byteorder", + "digest 0.8.1", + "rand_core 0.5.1", + "subtle 2.5.0", + "zeroize", ] [[package]] @@ -3064,10 +3130,19 @@ dependencies = [ "digest 0.10.7", "elliptic-curve", "rfc6979", - "signature", + "signature 2.2.0", "spki", ] +[[package]] +name = "ed25519" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7" +dependencies = [ + "signature 1.6.4", +] + [[package]] name = "ed25519" version = "2.2.3" @@ -3075,7 +3150,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ "pkcs8", - "signature", + "signature 2.2.0", +] + +[[package]] +name = "ed25519-dalek" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d" +dependencies = [ + "curve25519-dalek 3.2.0", + "ed25519 1.5.3", + "sha2 0.9.9", + "zeroize", ] [[package]] @@ -3085,7 +3172,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" dependencies = [ "curve25519-dalek 4.1.2", - "ed25519", + "ed25519 2.2.3", "rand_core 0.6.4", "serde", "sha2 0.10.8", @@ -3114,7 +3201,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d9ce6874da5d4415896cd45ffbc4d1cfc0c4f9c079427bd870742c30f2f65a9" dependencies = [ "curve25519-dalek 4.1.2", - "ed25519", + "ed25519 2.2.3", "hashbrown 0.14.3", "hex", "rand_core 0.6.4", @@ -3174,8 +3261,8 @@ dependencies = [ "sc-consensus-grandpa", "sp-authority-discovery", "sp-consensus-babe", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "staging-xcm", "xcm-emulator", ] @@ -3422,6 +3509,12 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "fake-simd" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" + [[package]] name = "fallible-iterator" version = "0.2.0" @@ -3539,7 +3632,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" dependencies = [ "byteorder", - "rand", + "rand 0.8.5", "rustc-hex", "static_assertions", ] @@ -3616,13 +3709,13 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto", - "sp-core", - "sp-io", - "sp-runtime", - "sp-runtime-interface", - "sp-std", - "sp-storage", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-runtime-interface 25.0.0", + "sp-std 14.0.0", + "sp-storage 20.0.0", "static_assertions", ] @@ -3647,7 +3740,7 @@ dependencies = [ "linked-hash-map", "log", "parity-scale-codec", - "rand", + "rand 0.8.5", "rand_pcg", "sc-block-builder", "sc-cli", @@ -3660,17 +3753,17 @@ dependencies = [ "serde_json", "sp-api", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-database", - "sp-externalities", + "sp-externalities 0.26.0", "sp-inherents", - "sp-io", - "sp-keystore", - "sp-runtime", - "sp-state-machine", - "sp-storage", - "sp-trie", - "sp-wasm-interface", + "sp-io 31.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-storage 20.0.0", + "sp-trie 30.0.0", + "sp-wasm-interface 20.0.0", "thiserror", "thousands", ] @@ -3698,11 +3791,11 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-arithmetic", - "sp-core", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", "sp-npos-elections", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -3717,11 +3810,11 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-tracing", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", ] [[package]] @@ -3759,11 +3852,11 @@ dependencies = [ "log", "parity-scale-codec", "serde", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-io", - "sp-runtime", - "sp-state-machine", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "spinners", "substrate-rpc-client", "tokio", @@ -3794,20 +3887,20 @@ dependencies = [ "serde_json", "smallvec", "sp-api", - "sp-arithmetic", - "sp-core", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", "sp-crypto-hashing-proc-macro", - "sp-debug-derive", + "sp-debug-derive 14.0.0", "sp-genesis-builder", "sp-inherents", - "sp-io", + "sp-io 31.0.0", "sp-metadata-ir", - "sp-runtime", + "sp-runtime 32.0.0", "sp-staking", - "sp-state-machine", - "sp-std", - "sp-tracing", - "sp-weights", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", + "sp-weights 28.0.0", "static_assertions", "tt-call", ] @@ -3869,12 +3962,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "sp-version", - "sp-weights", + "sp-weights 28.0.0", ] [[package]] @@ -3888,9 +3981,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -3912,8 +4005,8 @@ dependencies = [ "frame-support", "parity-scale-codec", "sp-api", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -4163,7 +4256,7 @@ version = "0.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea1015b5a70616b688dc230cfe50c8af89d972cb132d5a622814d29773b10b9" dependencies = [ - "rand", + "rand 0.8.5", "rand_core 0.6.4", ] @@ -4669,6 +4762,206 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "ink" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d4a862aedbfda93175ddf75c9aaa2ae4c4b39ee5cee06c16d50bccce05bf5c7" +dependencies = [ + "derive_more", + "ink_env", + "ink_macro", + "ink_metadata", + "ink_prelude", + "ink_primitives", + "ink_storage", + "pallet-contracts-uapi-next", + "parity-scale-codec", + "scale-info", +] + +[[package]] +name = "ink_allocator" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cee56055bac6d928d425e944c5f3b69baa33c9635822fd1c00cd4afc70fde3e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "ink_codegen" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70a1f8473fa09e0f9b6f3cb3f8d18c07c14ebf9ea1f7cdfee270f009d45ee8e9" +dependencies = [ + "blake2 0.10.6", + "derive_more", + "either", + "heck 0.4.1", + "impl-serde", + "ink_ir", + "ink_primitives", + "itertools 0.12.1", + "parity-scale-codec", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.58", +] + +[[package]] +name = "ink_engine" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f357e2e867f4e222ffc4015a6e61d1073548de89f70a4e36a8b0385562777fa" +dependencies = [ + "blake2 0.10.6", + "derive_more", + "ink_primitives", + "pallet-contracts-uapi-next", + "parity-scale-codec", + "secp256k1 0.28.2", + "sha2 0.10.8", + "sha3", +] + +[[package]] +name = "ink_env" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42cec50b7e4f8406aab25801b015d3802a52d76cfbe48ce11cfb4200fa88e296" +dependencies = [ + "blake2 0.10.6", + "cfg-if", + "const_env", + "derive_more", + "ink_allocator", + "ink_engine", + "ink_prelude", + "ink_primitives", + "ink_storage_traits", + "num-traits", + "pallet-contracts-uapi-next", + "parity-scale-codec", + "paste", + "rlibc", + "scale-decode", + "scale-encode", + "scale-info", + "schnorrkel 0.11.4", + "secp256k1 0.28.2", + "sha2 0.10.8", + "sha3", + "static_assertions", +] + +[[package]] +name = "ink_ir" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1ad2975551c4ed800af971289ed6d2c68ac41ffc03a42010b3e01d7360dfb2" +dependencies = [ + "blake2 0.10.6", + "either", + "impl-serde", + "ink_prelude", + "itertools 0.12.1", + "proc-macro2", + "quote", + "syn 2.0.58", +] + +[[package]] +name = "ink_macro" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aee1a546f37eae3b3cd223832d31702033c5369dcfa3405899587c110a7908d3" +dependencies = [ + "ink_codegen", + "ink_ir", + "ink_primitives", + "parity-scale-codec", + "proc-macro2", + "quote", + "syn 2.0.58", + "synstructure 0.13.1", +] + +[[package]] +name = "ink_metadata" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a98fcc0ff9292ff68c7ee7b84c93533c9ff13859ec3b148faa822e2da9954fe6" +dependencies = [ + "derive_more", + "impl-serde", + "ink_prelude", + "ink_primitives", + "linkme", + "parity-scale-codec", + "scale-info", + "schemars", + "serde", +] + +[[package]] +name = "ink_prelude" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea1734d058c80aa72e59c8ae75624fd8a51791efba21469f273156c0f4cad5c9" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "ink_primitives" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec35ef7f45e67a53b6142d7e7f18e6d9292d76c3a2a1da14cf8423e481813d" +dependencies = [ + "derive_more", + "ink_prelude", + "parity-scale-codec", + "scale-decode", + "scale-encode", + "scale-info", + "xxhash-rust", +] + +[[package]] +name = "ink_storage" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbdb04cad74df858c05bc9cb6f30bbf12da33c3e2cb7ca211749c001fa761aa9" +dependencies = [ + "array-init", + "cfg-if", + "derive_more", + "ink_env", + "ink_metadata", + "ink_prelude", + "ink_primitives", + "ink_storage_traits", + "pallet-contracts-uapi-next", + "parity-scale-codec", + "scale-info", +] + +[[package]] +name = "ink_storage_traits" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83ce49e3d2935fc1ec3e73117119712b187d3123339f6a31624e92f75fa2293d" +dependencies = [ + "ink_metadata", + "ink_prelude", + "ink_primitives", + "parity-scale-codec", + "scale-info", +] + [[package]] name = "inout" version = "0.1.3" @@ -4726,8 +5019,8 @@ dependencies = [ "sp-consensus-babe", "sp-consensus-beefy", "sp-consensus-grandpa", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "staging-xcm", "staging-xcm-executor", "tracing-subscriber 0.3.18", @@ -4923,7 +5216,7 @@ dependencies = [ "hyper", "jsonrpsee-types 0.20.3", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "rustc-hash", "serde", "serde_json", @@ -5256,7 +5549,7 @@ dependencies = [ "parking_lot 0.12.1", "pin-project", "quick-protobuf", - "rand", + "rand 0.8.5", "rw-stream-sink", "smallvec", "thiserror", @@ -5307,12 +5600,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "276bb57e7af15d8f100d3c11cbdd32c6752b7eef4ba7a18ecf464972c07abcce" dependencies = [ "bs58 0.4.0", - "ed25519-dalek", + "ed25519-dalek 2.1.1", "log", "multiaddr", "multihash 0.17.0", "quick-protobuf", - "rand", + "rand 0.8.5", "sha2 0.10.8", "thiserror", "zeroize", @@ -5337,7 +5630,7 @@ dependencies = [ "libp2p-swarm", "log", "quick-protobuf", - "rand", + "rand 0.8.5", "sha2 0.10.8", "smallvec", "thiserror", @@ -5359,7 +5652,7 @@ dependencies = [ "libp2p-identity", "libp2p-swarm", "log", - "rand", + "rand 0.8.5", "smallvec", "socket2 0.4.10", "tokio", @@ -5395,7 +5688,7 @@ dependencies = [ "log", "once_cell", "quick-protobuf", - "rand", + "rand 0.8.5", "sha2 0.10.8", "snow", "static_assertions", @@ -5417,7 +5710,7 @@ dependencies = [ "libp2p-core", "libp2p-swarm", "log", - "rand", + "rand 0.8.5", "void", ] @@ -5437,7 +5730,7 @@ dependencies = [ "log", "parking_lot 0.12.1", "quinn-proto", - "rand", + "rand 0.8.5", "rustls 0.20.9", "thiserror", "tokio", @@ -5455,7 +5748,7 @@ dependencies = [ "libp2p-core", "libp2p-identity", "libp2p-swarm", - "rand", + "rand 0.8.5", "smallvec", ] @@ -5474,7 +5767,7 @@ dependencies = [ "libp2p-identity", "libp2p-swarm-derive", "log", - "rand", + "rand 0.8.5", "smallvec", "tokio", "void", @@ -5610,7 +5903,7 @@ dependencies = [ "libsecp256k1-core", "libsecp256k1-gen-ecmult", "libsecp256k1-gen-genmult", - "rand", + "rand 0.8.5", "serde", "sha2 0.9.9", "typenum", @@ -5680,6 +5973,26 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "linkme" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccb76662d78edc9f9bf56360d6919bdacc8b7761227727e5082f128eeb90bbf5" +dependencies = [ + "linkme-impl", +] + +[[package]] +name = "linkme-impl" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dccda732e04fa3baf2e17cf835bfe2601c7c2edafd64417c627dabae3a8cda" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.58", +] + [[package]] name = "linregress" version = "0.5.3" @@ -5951,6 +6264,18 @@ dependencies = [ "hash-db", ] +[[package]] +name = "merlin" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e261cf0f8b3c42ded9f7d2bb59dea03aa52bc8a1cbc7482f9fc3fd1229d3b42" +dependencies = [ + "byteorder", + "keccak", + "rand_core 0.5.1", + "zeroize", +] + [[package]] name = "merlin" version = "3.0.0" @@ -5970,7 +6295,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69672161530e8aeca1d1400fbf3f1a1747ff60ea604265a4e906c2442df20532" dependencies = [ "futures", - "rand", + "rand 0.8.5", "thrift", ] @@ -6017,7 +6342,7 @@ dependencies = [ "lioness", "log", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "rand_distr", "subtle 2.5.0", @@ -6040,9 +6365,9 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-beefy", - "sp-core", + "sp-core 29.0.0", "sp-mmr-primitives", - "sp-runtime", + "sp-runtime 32.0.0", ] [[package]] @@ -6056,9 +6381,9 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-mmr-primitives", - "sp-runtime", + "sp-runtime 32.0.0", ] [[package]] @@ -6189,7 +6514,7 @@ dependencies = [ "proc-macro2", "quote", "syn 1.0.109", - "synstructure", + "synstructure 0.12.6", ] [[package]] @@ -6214,7 +6539,7 @@ dependencies = [ "proc-macro2", "quote", "syn 1.0.109", - "synstructure", + "synstructure 0.12.6", ] [[package]] @@ -6270,7 +6595,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7bddcd3bf5144b6392de80e04c347cd7fab2508f6df16a85fc496ecd5cec39bc" dependencies = [ - "rand", + "rand 0.8.5", ] [[package]] @@ -6598,11 +6923,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6617,8 +6942,8 @@ dependencies = [ "pallet-transaction-payment", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6632,9 +6957,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6650,10 +6975,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6668,9 +6993,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6685,10 +7010,10 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-aura", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6702,10 +7027,10 @@ dependencies = [ "pallet-session", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-authority-discovery", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6719,8 +7044,8 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6738,14 +7063,14 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-babe", - "sp-core", - "sp-io", - "sp-runtime", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -6764,11 +7089,11 @@ dependencies = [ "pallet-balances", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-tracing", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", ] [[package]] @@ -6784,8 +7109,8 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6803,10 +7128,10 @@ dependencies = [ "scale-info", "serde", "sp-consensus-beefy", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -6828,11 +7153,11 @@ dependencies = [ "serde", "sp-api", "sp-consensus-beefy", - "sp-core", - "sp-io", - "sp-runtime", - "sp-state-machine", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", ] [[package]] @@ -6848,10 +7173,10 @@ dependencies = [ "pallet-treasury", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6871,9 +7196,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-consensus-grandpa", - "sp-runtime", - "sp-std", - "sp-trie", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", ] [[package]] @@ -6891,8 +7216,8 @@ dependencies = [ "num-traits", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6912,9 +7237,9 @@ dependencies = [ "pallet-bridge-grandpa", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", - "sp-trie", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", ] [[package]] @@ -6933,9 +7258,9 @@ dependencies = [ "pallet-bridge-messages", "parity-scale-codec", "scale-info", - "sp-arithmetic", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6950,10 +7275,10 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-arithmetic", - "sp-core", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6970,10 +7295,10 @@ dependencies = [ "pallet-treasury", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -6989,11 +7314,11 @@ dependencies = [ "pallet-authorship", "pallet-session", "parity-scale-codec", - "rand", + "rand 0.8.5", "scale-info", - "sp-runtime", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7008,10 +7333,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7031,16 +7356,16 @@ dependencies = [ "pallet-contracts-proc-macro", "pallet-contracts-uapi", "parity-scale-codec", - "rand", + "rand 0.8.5", "rand_pcg", "scale-info", "serde", "smallvec", "sp-api", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "wasm-instrument", @@ -7071,6 +7396,17 @@ dependencies = [ "scale-info", ] +[[package]] +name = "pallet-contracts-uapi-next" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd549c16296ea5b2eb7c65c56aba548b286c1be4d7675b424ff6ccb8319c97a9" +dependencies = [ + "bitflags 1.3.2", + "paste", + "polkavm-derive", +] + [[package]] name = "pallet-conviction-voting" version = "29.0.0" @@ -7084,9 +7420,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7102,10 +7438,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7121,14 +7457,14 @@ dependencies = [ "log", "pallet-election-provider-support-benchmarking", "parity-scale-codec", - "rand", + "rand 0.8.5", "scale-info", - "sp-arithmetic", - "sp-core", - "sp-io", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", "sp-npos-elections", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "strum 0.24.1", ] @@ -7143,8 +7479,8 @@ dependencies = [ "frame-system", "parity-scale-codec", "sp-npos-elections", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7159,12 +7495,12 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", + "sp-core 29.0.0", + "sp-io 31.0.0", "sp-npos-elections", - "sp-runtime", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7181,10 +7517,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", + "sp-io 31.0.0", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7201,14 +7537,14 @@ dependencies = [ "pallet-session", "parity-scale-codec", "scale-info", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-grandpa", - "sp-core", - "sp-io", - "sp-runtime", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7224,9 +7560,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7242,12 +7578,12 @@ dependencies = [ "pallet-authorship", "parity-scale-codec", "scale-info", - "sp-application-crypto", - "sp-core", - "sp-io", - "sp-runtime", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7261,11 +7597,11 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", + "sp-core 29.0.0", + "sp-io 31.0.0", "sp-keyring", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7280,10 +7616,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7299,12 +7635,12 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-weights", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-weights 28.0.0", ] [[package]] @@ -7319,11 +7655,11 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", + "sp-core 29.0.0", + "sp-io 31.0.0", "sp-mmr-primitives", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7338,9 +7674,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7357,8 +7693,8 @@ dependencies = [ "pallet-nfts", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7374,10 +7710,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7389,7 +7725,7 @@ dependencies = [ "pallet-nfts", "parity-scale-codec", "sp-api", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7403,10 +7739,10 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-arithmetic", - "sp-core", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7421,12 +7757,12 @@ dependencies = [ "pallet-balances", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 14.0.0", + "sp-tracing 16.0.0", ] [[package]] @@ -7444,10 +7780,10 @@ dependencies = [ "pallet-staking", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-runtime-interface", + "sp-runtime 32.0.0", + "sp-runtime-interface 25.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7459,7 +7795,7 @@ dependencies = [ "pallet-nomination-pools", "parity-scale-codec", "sp-api", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7475,9 +7811,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-runtime", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7500,9 +7836,9 @@ dependencies = [ "pallet-staking", "parity-scale-codec", "scale-info", - "sp-runtime", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7517,10 +7853,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7534,9 +7870,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7552,11 +7888,11 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7570,9 +7906,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7589,10 +7925,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-arithmetic", - "sp-io", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7605,10 +7941,10 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7624,10 +7960,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", - "sp-weights", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-weights 28.0.0", ] [[package]] @@ -7643,14 +7979,14 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-state-machine", - "sp-std", - "sp-trie", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", ] [[package]] @@ -7665,10 +8001,10 @@ dependencies = [ "pallet-session", "pallet-staking", "parity-scale-codec", - "rand", - "sp-runtime", + "rand 0.8.5", + "sp-runtime 32.0.0", "sp-session", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7684,10 +8020,10 @@ dependencies = [ "parity-scale-codec", "rand_chacha 0.2.2", "scale-info", - "sp-arithmetic", - "sp-io", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7707,11 +8043,11 @@ dependencies = [ "rand_chacha 0.2.2", "scale-info", "serde", - "sp-application-crypto", - "sp-io", - "sp-runtime", + "sp-application-crypto 31.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -7733,7 +8069,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "505d45e08bad052f55fb51f00a6b6244d23ee46ffdc8091f6cddf4e3a880319d" dependencies = [ "log", - "sp-arithmetic", + "sp-arithmetic 24.0.0", ] [[package]] @@ -7759,10 +8095,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7777,9 +8113,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7796,10 +8132,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-inherents", - "sp-io", - "sp-runtime", - "sp-std", - "sp-storage", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-storage 20.0.0", "sp-timestamp", ] @@ -7817,10 +8153,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7834,10 +8170,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7851,10 +8187,10 @@ dependencies = [ "parity-scale-codec", "sp-api", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-rpc", - "sp-runtime", - "sp-weights", + "sp-runtime 32.0.0", + "sp-weights 28.0.0", ] [[package]] @@ -7866,8 +8202,8 @@ dependencies = [ "pallet-transaction-payment", "parity-scale-codec", "sp-api", - "sp-runtime", - "sp-weights", + "sp-runtime 32.0.0", + "sp-weights 28.0.0", ] [[package]] @@ -7885,9 +8221,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7902,8 +8238,8 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7917,10 +8253,10 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7935,8 +8271,8 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7951,8 +8287,8 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -7970,10 +8306,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -7991,9 +8327,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io", - "sp-runtime", - "sp-std", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -8012,9 +8348,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", ] @@ -8041,10 +8377,10 @@ dependencies = [ "polkadot-primitives", "scale-info", "sp-consensus-aura", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-executor", @@ -8071,11 +8407,11 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "sp-consensus-aura", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-tracing", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-executor", @@ -8103,7 +8439,7 @@ dependencies = [ "lz4", "memmap2 0.5.10", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "siphasher 0.3.11", "snap", "winapi", @@ -8168,7 +8504,7 @@ checksum = "f557c32c6d268a07c921471619c0295f5efad3a0e76d4f97a05c091a51d110b2" dependencies = [ "proc-macro2", "syn 1.0.109", - "synstructure", + "synstructure 0.12.6", ] [[package]] @@ -8252,6 +8588,15 @@ dependencies = [ "crypto-mac 0.11.0", ] +[[package]] +name = "pbkdf2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "pbkdf2" version = "0.12.2" @@ -8425,7 +8770,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand", + "rand 0.8.5", "tracing-gum", ] @@ -8442,7 +8787,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand", + "rand 0.8.5", "tracing-gum", ] @@ -8462,10 +8807,10 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand", + "rand 0.8.5", "schnellru", - "sp-core", - "sp-keystore", + "sp-core 29.0.0", + "sp-keystore 0.35.0", "thiserror", "tracing-gum", ] @@ -8486,7 +8831,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand", + "rand 0.8.5", "sc-network", "schnellru", "thiserror", @@ -8514,8 +8859,8 @@ dependencies = [ "sc-storage-monitor", "sc-sysinfo", "sc-tracing", - "sp-core", - "sp-io", + "sp-core 29.0.0", + "sp-io 31.0.0", "sp-keyring", "sp-maybe-compressed-blob", "substrate-build-script-utils", @@ -8538,9 +8883,9 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-core", - "sp-keystore", - "sp-runtime", + "sp-core 29.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "thiserror", "tokio-util", "tracing-gum", @@ -8554,9 +8899,9 @@ checksum = "b6a08e4e014c853b252ecbbe3ccd67b2d33d78e46988d309b8cccf4ac06e25ef" dependencies = [ "parity-scale-codec", "scale-info", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -8579,8 +8924,8 @@ dependencies = [ "polkadot-primitives", "sc-network", "schnellru", - "sp-application-crypto", - "sp-keystore", + "sp-application-crypto 31.0.0", + "sp-keystore 0.35.0", "thiserror", "tracing-gum", ] @@ -8595,8 +8940,8 @@ dependencies = [ "polkadot-node-primitives", "polkadot-primitives", "reed-solomon-novelpoly", - "sp-core", - "sp-trie", + "sp-core 29.0.0", + "sp-trie 30.0.0", "thiserror", ] @@ -8612,14 +8957,14 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "sc-network", "sc-network-common", - "sp-application-crypto", - "sp-core", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-keystore", + "sp-keystore 0.35.0", "tracing-gum", ] @@ -8660,7 +9005,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-core", + "sp-core 29.0.0", "sp-maybe-compressed-blob", "thiserror", "tracing-gum", @@ -8678,7 +9023,7 @@ dependencies = [ "futures-timer", "itertools 0.10.5", "kvdb", - "merlin", + "merlin 3.0.0", "parity-scale-codec", "polkadot-node-jaeger", "polkadot-node-primitives", @@ -8686,16 +9031,16 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "rand_core 0.6.4", "sc-keystore", "schnellru", "schnorrkel 0.11.4", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus", "sp-consensus-slots", - "sp-runtime", + "sp-runtime 32.0.0", "thiserror", "tracing-gum", ] @@ -8739,7 +9084,7 @@ dependencies = [ "polkadot-primitives", "polkadot-statement-table", "schnellru", - "sp-keystore", + "sp-keystore 0.35.0", "thiserror", "tracing-gum", ] @@ -8754,7 +9099,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-keystore", + "sp-keystore 0.35.0", "thiserror", "tracing-gum", "wasm-timer", @@ -8912,11 +9257,11 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-parachain-primitives", "polkadot-primitives", - "rand", + "rand 0.8.5", "slotmap", - "sp-core", + "sp-core 29.0.0", "sp-maybe-compressed-blob", - "sp-wasm-interface", + "sp-wasm-interface 20.0.0", "tempfile", "thiserror", "tokio", @@ -8935,7 +9280,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", - "sp-keystore", + "sp-keystore 0.35.0", "thiserror", "tracing-gum", ] @@ -8959,11 +9304,11 @@ dependencies = [ "sc-executor-common", "sc-executor-wasmtime", "seccompiler", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-externalities", - "sp-io", - "sp-tracing", + "sp-externalities 0.26.0", + "sp-io 31.0.0", + "sp-tracing 16.0.0", "thiserror", "tracing-gum", ] @@ -8998,7 +9343,7 @@ dependencies = [ "polkadot-node-primitives", "polkadot-primitives", "sc-network", - "sp-core", + "sp-core 29.0.0", "thiserror", "tokio", ] @@ -9040,7 +9385,7 @@ dependencies = [ "polkadot-node-jaeger", "polkadot-node-primitives", "polkadot-primitives", - "rand", + "rand 0.8.5", "sc-authority-discovery", "sc-network", "strum 0.24.1", @@ -9062,12 +9407,12 @@ dependencies = [ "polkadot-primitives", "schnorrkel 0.11.4", "serde", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-babe", - "sp-core", - "sp-keystore", + "sp-core 29.0.0", + "sp-keystore 0.35.0", "sp-maybe-compressed-blob", - "sp-runtime", + "sp-runtime 32.0.0", "thiserror", "zstd 0.12.4", ] @@ -9107,7 +9452,7 @@ dependencies = [ "sp-authority-discovery", "sp-blockchain", "sp-consensus-babe", - "sp-runtime", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -9138,12 +9483,12 @@ dependencies = [ "polkadot-overseer", "polkadot-primitives", "prioritized-metered-channel", - "rand", + "rand 0.8.5", "sc-client-api", "schnellru", - "sp-application-crypto", - "sp-core", - "sp-keystore", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", + "sp-keystore 0.35.0", "thiserror", "tracing-gum", ] @@ -9166,7 +9511,7 @@ dependencies = [ "polkadot-primitives", "sc-client-api", "sp-api", - "sp-core", + "sp-core 29.0.0", "tikv-jemalloc-ctl", "tracing-gum", ] @@ -9183,10 +9528,10 @@ dependencies = [ "polkadot-core-primitives", "scale-info", "serde", - "sp-core", - "sp-runtime", - "sp-std", - "sp-weights", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-weights 28.0.0", ] [[package]] @@ -9204,17 +9549,17 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto", - "sp-arithmetic", + "sp-application-crypto 31.0.0", + "sp-arithmetic 24.0.0", "sp-authority-discovery", "sp-consensus-slots", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-io", - "sp-keystore", - "sp-runtime", + "sp-io 31.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -9245,8 +9590,8 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-keystore", - "sp-runtime", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "substrate-frame-rpc-system", "substrate-state-trie-migration-rpc", ] @@ -9289,14 +9634,14 @@ dependencies = [ "serde_derive", "slot-range-helper", "sp-api", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-io", + "sp-io 31.0.0", "sp-npos-elections", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-std", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -9313,8 +9658,8 @@ dependencies = [ "frame-benchmarking", "parity-scale-codec", "polkadot-primitives", - "sp-std", - "sp-tracing", + "sp-std 14.0.0", + "sp-tracing 16.0.0", ] [[package]] @@ -9346,22 +9691,22 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-metrics", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "rustc-hex", "scale-info", "serde", "sp-api", - "sp-application-crypto", - "sp-arithmetic", - "sp-core", + "sp-application-crypto 31.0.0", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", "sp-inherents", - "sp-io", - "sp-keystore", - "sp-runtime", + "sp-io 31.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-std", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-executor", "static_assertions", @@ -9464,21 +9809,21 @@ dependencies = [ "sp-consensus-babe", "sp-consensus-beefy", "sp-consensus-grandpa", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-io", + "sp-io 31.0.0", "sp-keyring", - "sp-keystore", + "sp-keystore 0.35.0", "sp-mmr-primitives", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", - "sp-state-machine", - "sp-storage", + "sp-state-machine 0.36.0", + "sp-storage 20.0.0", "sp-timestamp", "sp-transaction-pool", "sp-version", - "sp-weights", + "sp-weights 28.0.0", "substrate-prometheus-endpoint", "thiserror", "tracing-gum", @@ -9503,7 +9848,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-keystore", + "sp-keystore 0.35.0", "sp-staking", "thiserror", "tracing-gum", @@ -9517,7 +9862,7 @@ checksum = "de5e010da3c6a65d8f263d0f825a04d995ffc8a37f886f674fcbbc73bf158d01" dependencies = [ "parity-scale-codec", "polkadot-primitives", - "sp-core", + "sp-core 29.0.0", "tracing-gum", ] @@ -9603,6 +9948,19 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "pop-api" +version = "0.0.0" +dependencies = [ + "enumflags2", + "ink", + "parity-scale-codec", + "pop-primitives", + "scale-info", + "sp-io 23.0.0", + "sp-runtime 24.0.0", +] + [[package]] name = "pop-node" version = "0.1.0-alpha" @@ -9653,11 +10011,11 @@ dependencies = [ "sp-block-builder", "sp-blockchain", "sp-consensus-aura", - "sp-core", - "sp-io", - "sp-keystore", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-keystore 0.35.0", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", "sp-timestamp", "sp-transaction-pool", @@ -9687,8 +10045,8 @@ dependencies = [ "parity-scale-codec", "polkadot-primitives", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -9740,6 +10098,7 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "polkadot-runtime-common", + "pop-api", "pop-primitives", "pop-runtime-common", "scale-info", @@ -9747,14 +10106,14 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-consensus-aura", - "sp-core", + "sp-core 29.0.0", "sp-genesis-builder", "sp-inherents", - "sp-io", + "sp-io 31.0.0", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", - "sp-std", + "sp-std 14.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -9820,14 +10179,14 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-consensus-aura", - "sp-core", + "sp-core 29.0.0", "sp-genesis-builder", "sp-inherents", - "sp-io", + "sp-io 31.0.0", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", - "sp-std", + "sp-std 14.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -10187,7 +10546,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94b0b33c13a79f669c85defaf4c275dc86a0c0372807d0ca3d78e0bb87274863" dependencies = [ "bytes", - "rand", + "rand 0.8.5", "ring 0.16.20", "rustc-hash", "rustls 0.20.9", @@ -10215,7 +10574,20 @@ checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" [[package]] name = "rand" -version = "0.8.5" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc", +] + +[[package]] +name = "rand" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ @@ -10269,7 +10641,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ "num-traits", - "rand", + "rand 0.8.5", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", ] [[package]] @@ -10495,6 +10876,12 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "rlibc" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc874b127765f014d792f16763a81245ab80500e2ad921ed4ee9e82481ee08fe" + [[package]] name = "rlp" version = "0.5.2" @@ -10587,22 +10974,22 @@ dependencies = [ "serde_derive", "smallvec", "sp-api", - "sp-arithmetic", + "sp-arithmetic 24.0.0", "sp-authority-discovery", "sp-block-builder", "sp-consensus-babe", "sp-consensus-beefy", - "sp-core", + "sp-core 29.0.0", "sp-genesis-builder", "sp-inherents", - "sp-io", + "sp-io 31.0.0", "sp-mmr-primitives", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-std", - "sp-storage", + "sp-std 14.0.0", + "sp-storage 20.0.0", "sp-transaction-pool", "sp-version", "staging-xcm", @@ -10622,9 +11009,9 @@ dependencies = [ "polkadot-primitives", "polkadot-runtime-common", "smallvec", - "sp-core", - "sp-runtime", - "sp-weights", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-weights 28.0.0", "staging-xcm", "staging-xcm-builder", ] @@ -10927,8 +11314,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357127c91373ed6d1ae582f6e3300ab5b13bcde43bbf270a891f44194ef48b70" dependencies = [ "log", - "sp-core", - "sp-wasm-interface", + "sp-core 29.0.0", + "sp-wasm-interface 20.0.0", "thiserror", ] @@ -10949,15 +11336,15 @@ dependencies = [ "parity-scale-codec", "prost 0.12.3", "prost-build", - "rand", + "rand 0.8.5", "sc-client-api", "sc-network", "sp-api", "sp-authority-discovery", "sp-blockchain", - "sp-core", - "sp-keystore", - "sp-runtime", + "sp-core 29.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -10979,9 +11366,9 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-runtime", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", ] @@ -10995,10 +11382,10 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-runtime", - "sp-trie", + "sp-runtime 32.0.0", + "sp-trie 30.0.0", ] [[package]] @@ -11020,12 +11407,12 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", "sp-genesis-builder", - "sp-io", - "sp-runtime", - "sp-state-machine", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", ] [[package]] @@ -11057,7 +11444,7 @@ dependencies = [ "log", "names", "parity-scale-codec", - "rand", + "rand 0.8.5", "regex", "rpassword", "sc-client-api", @@ -11072,11 +11459,11 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-keyring", - "sp-keystore", - "sp-panic-handler", - "sp-runtime", + "sp-keystore 0.35.0", + "sp-panic-handler 13.0.0", + "sp-runtime 32.0.0", "sp-version", "thiserror", "tokio", @@ -11099,14 +11486,14 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core", + "sp-core 29.0.0", "sp-database", - "sp-externalities", - "sp-runtime", - "sp-state-machine", + "sp-externalities 0.26.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "sp-statement-store", - "sp-storage", - "sp-trie", + "sp-storage 20.0.0", + "sp-trie 30.0.0", "substrate-prometheus-endpoint", ] @@ -11128,13 +11515,13 @@ dependencies = [ "sc-client-api", "sc-state-db", "schnellru", - "sp-arithmetic", + "sp-arithmetic 24.0.0", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-database", - "sp-runtime", - "sp-state-machine", - "sp-trie", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-trie 30.0.0", ] [[package]] @@ -11156,9 +11543,9 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core", - "sp-runtime", - "sp-state-machine", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -11179,16 +11566,16 @@ dependencies = [ "sc-consensus-slots", "sc-telemetry", "sp-api", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", "sp-consensus-slots", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-keystore", - "sp-runtime", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -11215,17 +11602,17 @@ dependencies = [ "sc-telemetry", "sc-transaction-pool-api", "sp-api", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-babe", "sp-consensus-slots", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", "sp-inherents", - "sp-keystore", - "sp-runtime", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -11243,13 +11630,13 @@ dependencies = [ "sc-rpc-api", "serde", "sp-api", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-core", - "sp-keystore", - "sp-runtime", + "sp-core 29.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "thiserror", ] @@ -11274,16 +11661,16 @@ dependencies = [ "sc-network-sync", "sc-utils", "sp-api", - "sp-application-crypto", - "sp-arithmetic", + "sp-application-crypto 31.0.0", + "sp-arithmetic 24.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-beefy", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-keystore", + "sp-keystore 0.35.0", "sp-mmr-primitives", - "sp-runtime", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -11305,8 +11692,8 @@ dependencies = [ "sc-rpc", "serde", "sp-consensus-beefy", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "thiserror", ] @@ -11321,7 +11708,7 @@ dependencies = [ "sc-client-api", "sc-consensus", "sp-blockchain", - "sp-runtime", + "sp-runtime 32.0.0", ] [[package]] @@ -11341,7 +11728,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -11355,15 +11742,15 @@ dependencies = [ "sc-utils", "serde_json", "sp-api", - "sp-application-crypto", - "sp-arithmetic", + "sp-application-crypto 31.0.0", + "sp-arithmetic 24.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-grandpa", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-keystore", - "sp-runtime", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", ] @@ -11384,8 +11771,8 @@ dependencies = [ "sc-rpc", "serde", "sp-blockchain", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "thiserror", ] @@ -11403,14 +11790,14 @@ dependencies = [ "sc-client-api", "sc-consensus", "sc-telemetry", - "sp-arithmetic", + "sp-arithmetic 24.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-slots", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", ] [[package]] @@ -11425,14 +11812,14 @@ dependencies = [ "sc-executor-wasmtime", "schnellru", "sp-api", - "sp-core", - "sp-externalities", - "sp-io", - "sp-panic-handler", - "sp-runtime-interface", - "sp-trie", + "sp-core 29.0.0", + "sp-externalities 0.26.0", + "sp-io 31.0.0", + "sp-panic-handler 13.0.0", + "sp-runtime-interface 25.0.0", + "sp-trie 30.0.0", "sp-version", - "sp-wasm-interface", + "sp-wasm-interface 20.0.0", "tracing", ] @@ -11444,7 +11831,7 @@ checksum = "07498138dee3ddf2c71299ca372d8449880bb3a8a8a299a483094e9c26b0823e" dependencies = [ "sc-allocator", "sp-maybe-compressed-blob", - "sp-wasm-interface", + "sp-wasm-interface 20.0.0", "thiserror", "wasm-instrument", ] @@ -11463,8 +11850,8 @@ dependencies = [ "rustix 0.36.17", "sc-allocator", "sc-executor-common", - "sp-runtime-interface", - "sp-wasm-interface", + "sp-runtime-interface 25.0.0", + "sp-wasm-interface 20.0.0", "wasmtime", ] @@ -11483,7 +11870,7 @@ dependencies = [ "sc-network-common", "sc-network-sync", "sp-blockchain", - "sp-runtime", + "sp-runtime 32.0.0", ] [[package]] @@ -11495,9 +11882,9 @@ dependencies = [ "array-bytes 6.2.2", "parking_lot 0.12.1", "serde_json", - "sp-application-crypto", - "sp-core", - "sp-keystore", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", + "sp-keystore 0.35.0", "thiserror", ] @@ -11524,10 +11911,10 @@ dependencies = [ "sc-transaction-pool-api", "sp-api", "sp-consensus", - "sp-core", - "sp-keystore", + "sp-core 29.0.0", + "sp-keystore 0.35.0", "sp-mixnet", - "sp-runtime", + "sp-runtime 32.0.0", "thiserror", ] @@ -11555,17 +11942,17 @@ dependencies = [ "parking_lot 0.12.1", "partial_sort", "pin-project", - "rand", + "rand 0.8.5", "sc-client-api", "sc-network-common", "sc-utils", "serde", "serde_json", "smallvec", - "sp-arithmetic", + "sp-arithmetic 24.0.0", "sp-blockchain", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -11591,7 +11978,7 @@ dependencies = [ "sc-client-api", "sc-network", "sp-blockchain", - "sp-runtime", + "sp-runtime 32.0.0", "thiserror", "unsigned-varint", ] @@ -11611,7 +11998,7 @@ dependencies = [ "sc-consensus", "sp-consensus", "sp-consensus-grandpa", - "sp-runtime", + "sp-runtime 32.0.0", ] [[package]] @@ -11629,7 +12016,7 @@ dependencies = [ "sc-network-common", "sc-network-sync", "schnellru", - "sp-runtime", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "tracing", ] @@ -11651,8 +12038,8 @@ dependencies = [ "sc-client-api", "sc-network", "sp-blockchain", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "thiserror", ] @@ -11681,12 +12068,12 @@ dependencies = [ "sc-utils", "schnellru", "smallvec", - "sp-arithmetic", + "sp-arithmetic 24.0.0", "sp-blockchain", "sp-consensus", "sp-consensus-grandpa", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -11709,7 +12096,7 @@ dependencies = [ "sc-network-sync", "sc-utils", "sp-consensus", - "sp-runtime", + "sp-runtime 32.0.0", "substrate-prometheus-endpoint", ] @@ -11732,18 +12119,18 @@ dependencies = [ "once_cell", "parity-scale-codec", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "sc-client-api", "sc-network", "sc-network-common", "sc-transaction-pool-api", "sc-utils", "sp-api", - "sp-core", - "sp-externalities", - "sp-keystore", + "sp-core 29.0.0", + "sp-externalities 0.26.0", + "sp-keystore 0.35.0", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "threadpool", "tracing", ] @@ -11780,11 +12167,11 @@ dependencies = [ "serde_json", "sp-api", "sp-blockchain", - "sp-core", - "sp-keystore", + "sp-core 29.0.0", + "sp-keystore 0.35.0", "sp-offchain", "sp-rpc", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", "sp-statement-store", "sp-version", @@ -11805,9 +12192,9 @@ dependencies = [ "scale-info", "serde", "serde_json", - "sp-core", + "sp-core 29.0.0", "sp-rpc", - "sp-runtime", + "sp-runtime 32.0.0", "sp-version", "thiserror", ] @@ -11850,9 +12237,9 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-rpc", - "sp-runtime", + "sp-runtime 32.0.0", "sp-version", "thiserror", "tokio", @@ -11875,7 +12262,7 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.1", "pin-project", - "rand", + "rand 0.8.5", "sc-chain-spec", "sc-client-api", "sc-client-db", @@ -11903,16 +12290,16 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core", - "sp-externalities", - "sp-keystore", - "sp-runtime", + "sp-core 29.0.0", + "sp-externalities 0.26.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "sp-session", - "sp-state-machine", - "sp-storage", + "sp-state-machine 0.36.0", + "sp-storage 20.0.0", "sp-transaction-pool", "sp-transaction-storage-proof", - "sp-trie", + "sp-trie 30.0.0", "sp-version", "static_init", "substrate-prometheus-endpoint", @@ -11932,7 +12319,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", - "sp-core", + "sp-core 29.0.0", ] [[package]] @@ -11944,7 +12331,7 @@ dependencies = [ "clap", "fs4", "log", - "sp-core", + "sp-core 29.0.0", "thiserror", "tokio", ] @@ -11965,7 +12352,7 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-runtime", + "sp-runtime 32.0.0", "thiserror", ] @@ -11979,16 +12366,16 @@ dependencies = [ "futures", "libc", "log", - "rand", + "rand 0.8.5", "rand_pcg", "regex", "sc-telemetry", "serde", "serde_json", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-io", - "sp-std", + "sp-io 31.0.0", + "sp-std 14.0.0", ] [[package]] @@ -12003,7 +12390,7 @@ dependencies = [ "log", "parking_lot 0.12.1", "pin-project", - "rand", + "rand 0.8.5", "sc-utils", "serde", "serde_json", @@ -12032,10 +12419,10 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-rpc", - "sp-runtime", - "sp-tracing", + "sp-runtime 32.0.0", + "sp-tracing 16.0.0", "thiserror", "tracing", "tracing-log 0.1.4", @@ -12073,10 +12460,10 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-runtime", - "sp-tracing", + "sp-runtime 32.0.0", + "sp-tracing 16.0.0", "sp-transaction-pool", "substrate-prometheus-endpoint", "thiserror", @@ -12094,8 +12481,8 @@ dependencies = [ "parity-scale-codec", "serde", "sp-blockchain", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "thiserror", ] @@ -12112,7 +12499,7 @@ dependencies = [ "log", "parking_lot 0.12.1", "prometheus", - "sp-arithmetic", + "sp-arithmetic 24.0.0", ] [[package]] @@ -12193,6 +12580,7 @@ dependencies = [ "derive_more", "parity-scale-codec", "scale-info-derive", + "schemars", "serde", ] @@ -12250,6 +12638,30 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "schemars" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09c024468a378b7e36765cd36702b7a90cc3cba11654f6685c8f233408e89e92" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1eee588578aff73f856ab961cd2f79e36bc45d7ded33a7562adba4667aecc0e" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.58", +] + [[package]] name = "schnellru" version = "0.2.1" @@ -12261,6 +12673,24 @@ dependencies = [ "hashbrown 0.13.2", ] +[[package]] +name = "schnorrkel" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "021b403afe70d81eea68f6ea12f6b3c9588e5d536a94c3bf80f15e7faa267862" +dependencies = [ + "arrayref", + "arrayvec 0.5.2", + "curve25519-dalek 2.1.3", + "getrandom 0.1.16", + "merlin 2.0.1", + "rand 0.7.3", + "rand_core 0.5.1", + "sha2 0.8.2", + "subtle 2.5.0", + "zeroize", +] + [[package]] name = "schnorrkel" version = "0.10.2" @@ -12270,7 +12700,7 @@ dependencies = [ "arrayref", "arrayvec 0.7.4", "curve25519-dalek-ng", - "merlin", + "merlin 3.0.0", "rand_core 0.6.4", "sha2 0.9.9", "subtle-ng", @@ -12288,7 +12718,7 @@ dependencies = [ "arrayvec 0.7.4", "curve25519-dalek 4.1.2", "getrandom_or_panic", - "merlin", + "merlin 3.0.0", "rand_core 0.6.4", "serde_bytes", "sha2 0.10.8", @@ -12341,13 +12771,31 @@ dependencies = [ "libc", ] +[[package]] +name = "secp256k1" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1629c9c557ef9b293568b338dddfc8208c98a18c59d722a9d53f859d9c9b62" +dependencies = [ + "secp256k1-sys 0.6.1", +] + [[package]] name = "secp256k1" version = "0.28.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d24b59d129cdadea20aea4fb2352fa053712e5d713eee47d700cd4b2bc002f10" dependencies = [ - "secp256k1-sys", + "secp256k1-sys 0.9.2", +] + +[[package]] +name = "secp256k1-sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83080e2c2fc1006e625be82e5d1eb6a43b7fd9578b617fcc55814daf286bba4b" +dependencies = [ + "cc", ] [[package]] @@ -12453,6 +12901,17 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.58", +] + [[package]] name = "serde_json" version = "1.0.115" @@ -12497,6 +12956,18 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69" +dependencies = [ + "block-buffer 0.7.3", + "digest 0.8.1", + "fake-simd", + "opaque-debug 0.2.3", +] + [[package]] name = "sha2" version = "0.9.9" @@ -12555,6 +13026,12 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "1.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" + [[package]] name = "signature" version = "2.2.0" @@ -12620,8 +13097,8 @@ dependencies = [ "enumn", "parity-scale-codec", "paste", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -12700,7 +13177,7 @@ dependencies = [ "hmac 0.12.1", "itertools 0.11.0", "libsecp256k1", - "merlin", + "merlin 3.0.0", "no-std-net", "nom", "num-bigint", @@ -12709,7 +13186,7 @@ dependencies = [ "pbkdf2 0.12.2", "pin-project", "poly1305", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "ruzstd 0.4.0", "schnorrkel 0.10.2", @@ -12755,7 +13232,7 @@ dependencies = [ "itertools 0.12.1", "libm", "libsecp256k1", - "merlin", + "merlin 3.0.0", "no-std-net", "nom", "num-bigint", @@ -12764,7 +13241,7 @@ dependencies = [ "pbkdf2 0.12.2", "pin-project", "poly1305", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "ruzstd 0.5.0", "schnorrkel 0.11.4", @@ -12807,7 +13284,7 @@ dependencies = [ "no-std-net", "parking_lot 0.12.1", "pin-project", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "serde", "serde_json", @@ -12843,7 +13320,7 @@ dependencies = [ "no-std-net", "parking_lot 0.12.1", "pin-project", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "serde", "serde_json", @@ -12903,10 +13380,10 @@ dependencies = [ "serde", "snowbridge-ethereum", "snowbridge-milagro-bls", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "ssz_rs", "ssz_rs_derive", "static_assertions", @@ -12927,11 +13404,11 @@ dependencies = [ "scale-info", "serde", "snowbridge-beacon-primitives", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", ] @@ -12953,10 +13430,10 @@ dependencies = [ "scale-info", "serde", "serde-big-array", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -12968,7 +13445,7 @@ dependencies = [ "hex", "lazy_static", "parity-scale-codec", - "rand", + "rand 0.8.5", "scale-info", "snowbridge-amcl", "zeroize", @@ -12989,10 +13466,10 @@ dependencies = [ "scale-info", "serde", "snowbridge-core", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -13031,7 +13508,7 @@ dependencies = [ "http", "httparse", "log", - "rand", + "rand 0.8.5", "sha-1", ] @@ -13046,13 +13523,13 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api-proc-macro", - "sp-core", - "sp-externalities", + "sp-core 29.0.0", + "sp-externalities 0.26.0", "sp-metadata-ir", - "sp-runtime", - "sp-state-machine", - "sp-std", - "sp-trie", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", "sp-version", "thiserror", ] @@ -13072,6 +13549,20 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "sp-application-crypto" +version = "23.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899492ea547816d5dfe9a5a2ecc32f65a7110805af6da3380aa4902371b31dc2" +dependencies = [ + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 21.0.0", + "sp-io 23.0.0", + "sp-std 8.0.0", +] + [[package]] name = "sp-application-crypto" version = "31.0.0" @@ -13081,9 +13572,24 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-io", - "sp-std", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-std 14.0.0", +] + +[[package]] +name = "sp-arithmetic" +version = "16.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb6020576e544c6824a51d651bc8df8e6ab67cd59f1c9ac09868bb81a5199ded" +dependencies = [ + "integer-sqrt", + "num-traits", + "parity-scale-codec", + "scale-info", + "serde", + "sp-std 8.0.0", + "static_assertions", ] [[package]] @@ -13097,7 +13603,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std", + "sp-std 14.0.0", "static_assertions", ] @@ -13110,9 +13616,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-application-crypto", - "sp-runtime", - "sp-std", + "sp-application-crypto 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13123,8 +13629,8 @@ checksum = "1b36ce171caa7eb2bbe682c089f755fdefa71d3702e4fb1ba30d10146aef99d5" dependencies = [ "sp-api", "sp-inherents", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13141,8 +13647,8 @@ dependencies = [ "sp-api", "sp-consensus", "sp-database", - "sp-runtime", - "sp-state-machine", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "thiserror", ] @@ -13155,10 +13661,10 @@ dependencies = [ "async-trait", "futures", "log", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-runtime", - "sp-state-machine", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "thiserror", ] @@ -13172,11 +13678,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-slots", "sp-inherents", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "sp-timestamp", ] @@ -13191,12 +13697,12 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto", + "sp-application-crypto 31.0.0", "sp-consensus-slots", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "sp-timestamp", ] @@ -13211,13 +13717,13 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto", - "sp-core", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-io", + "sp-io 31.0.0", "sp-mmr-primitives", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "strum 0.24.1", ] @@ -13233,11 +13739,11 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto", - "sp-core", - "sp-keystore", - "sp-runtime", - "sp-std", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13249,10 +13755,55 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std", + "sp-std 14.0.0", "sp-timestamp", ] +[[package]] +name = "sp-core" +version = "21.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f18d9e2f67d8661f9729f35347069ac29d92758b59135176799db966947a7336" +dependencies = [ + "array-bytes 4.2.0", + "bitflags 1.3.2", + "blake2 0.10.6", + "bounded-collections 0.1.9", + "bs58 0.4.0", + "dyn-clonable", + "ed25519-zebra 3.1.0", + "futures", + "hash-db", + "hash256-std-hasher", + "impl-serde", + "lazy_static", + "libsecp256k1", + "log", + "merlin 2.0.1", + "parity-scale-codec", + "parking_lot 0.12.1", + "paste", + "primitive-types", + "rand 0.8.5", + "regex", + "scale-info", + "schnorrkel 0.9.1", + "secp256k1 0.24.3", + "secrecy", + "serde", + "sp-core-hashing 9.0.0", + "sp-debug-derive 8.0.0", + "sp-externalities 0.19.0", + "sp-runtime-interface 17.0.0", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "ss58-registry", + "substrate-bip39", + "thiserror", + "tiny-bip39", + "zeroize", +] + [[package]] name = "sp-core" version = "29.0.0" @@ -13274,23 +13825,23 @@ dependencies = [ "itertools 0.10.5", "libsecp256k1", "log", - "merlin", + "merlin 3.0.0", "parity-scale-codec", "parking_lot 0.12.1", "paste", "primitive-types", - "rand", + "rand 0.8.5", "scale-info", "schnorrkel 0.11.4", - "secp256k1", + "secp256k1 0.28.2", "secrecy", "serde", "sp-crypto-hashing", - "sp-debug-derive", - "sp-externalities", - "sp-runtime-interface", - "sp-std", - "sp-storage", + "sp-debug-derive 14.0.0", + "sp-externalities 0.26.0", + "sp-runtime-interface 25.0.0", + "sp-std 14.0.0", + "sp-storage 20.0.0", "ss58-registry", "substrate-bip39", "thiserror", @@ -13299,6 +13850,21 @@ dependencies = [ "zeroize", ] +[[package]] +name = "sp-core-hashing" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee599a8399448e65197f9a6cee338ad192e9023e35e31f22382964c3c174c68" +dependencies = [ + "blake2b_simd", + "byteorder", + "digest 0.10.7", + "sha2 0.10.8", + "sha3", + "sp-std 8.0.0", + "twox-hash", +] + [[package]] name = "sp-core-hashing" version = "15.0.0" @@ -13348,6 +13914,17 @@ dependencies = [ "parking_lot 0.12.1", ] +[[package]] +name = "sp-debug-derive" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f531814d2f16995144c74428830ccf7d94ff4a7749632b83ad8199b181140c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.58", +] + [[package]] name = "sp-debug-derive" version = "14.0.0" @@ -13359,6 +13936,18 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "sp-externalities" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0f71c671e01a8ca60da925d43a1b351b69626e268b8837f8371e320cf1dd100" +dependencies = [ + "environmental", + "parity-scale-codec", + "sp-std 8.0.0", + "sp-storage 13.0.0", +] + [[package]] name = "sp-externalities" version = "0.26.0" @@ -13367,8 +13956,8 @@ checksum = "e7096ed024cec397804864898b093b51e14c7299f1d00c67dd5800330e02bb82" dependencies = [ "environmental", "parity-scale-codec", - "sp-std", - "sp-storage", + "sp-std 14.0.0", + "sp-storage 20.0.0", ] [[package]] @@ -13379,8 +13968,8 @@ checksum = "fd865540ec19479c7349b584ccd78cc34c3f3a628a2a69dbb6365ceec36295ee" dependencies = [ "serde_json", "sp-api", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13393,11 +13982,38 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "thiserror", ] +[[package]] +name = "sp-io" +version = "23.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d597e35a9628fe7454b08965b2442e3ec0f264b0a90d41328e87422cec02e99" +dependencies = [ + "bytes", + "ed25519 1.5.3", + "ed25519-dalek 1.0.1", + "futures", + "libsecp256k1", + "log", + "parity-scale-codec", + "rustversion", + "secp256k1 0.24.3", + "sp-core 21.0.0", + "sp-externalities 0.19.0", + "sp-keystore 0.27.0", + "sp-runtime-interface 17.0.0", + "sp-state-machine 0.28.0", + "sp-std 8.0.0", + "sp-tracing 10.0.0", + "sp-trie 22.0.0", + "tracing", + "tracing-core", +] + [[package]] name = "sp-io" version = "31.0.0" @@ -13405,21 +14021,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec43aa073eab35fcb920d7592474d5427ea3be2bf938706a3ad955d7ba54fd8d" dependencies = [ "bytes", - "ed25519-dalek", + "ed25519-dalek 2.1.1", "libsecp256k1", "log", "parity-scale-codec", "rustversion", - "secp256k1", - "sp-core", + "secp256k1 0.28.2", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-externalities", - "sp-keystore", - "sp-runtime-interface", - "sp-state-machine", - "sp-std", - "sp-tracing", - "sp-trie", + "sp-externalities 0.26.0", + "sp-keystore 0.35.0", + "sp-runtime-interface 25.0.0", + "sp-state-machine 0.36.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", + "sp-trie 30.0.0", "tracing", "tracing-core", ] @@ -13430,11 +14046,25 @@ version = "32.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cf0a2f881958466fc92bc9b39bbc2c0d815ded4a21f8f953372b0ac2e11b02" dependencies = [ - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", "strum 0.24.1", ] +[[package]] +name = "sp-keystore" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be3cdd67cc1d9c1db17c5cbc4ec4924054a8437009d167f21f6590797e4aa45" +dependencies = [ + "futures", + "parity-scale-codec", + "parking_lot 0.12.1", + "sp-core 21.0.0", + "sp-externalities 0.19.0", + "thiserror", +] + [[package]] name = "sp-keystore" version = "0.35.0" @@ -13443,8 +14073,8 @@ checksum = "444f2d53968b1ce5e908882710ff1f3873fcf3e95f59d57432daf685bbacb959" dependencies = [ "parity-scale-codec", "parking_lot 0.12.1", - "sp-core", - "sp-externalities", + "sp-core 29.0.0", + "sp-externalities 0.26.0", "thiserror", ] @@ -13467,7 +14097,7 @@ dependencies = [ "frame-metadata 16.0.0", "parity-scale-codec", "scale-info", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -13479,8 +14109,8 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-application-crypto", - "sp-std", + "sp-application-crypto 31.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13495,10 +14125,10 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-core", - "sp-debug-derive", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-debug-derive 14.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "thiserror", ] @@ -13511,10 +14141,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-arithmetic", - "sp-core", - "sp-runtime", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13524,8 +14154,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d83b955dce0b6d143bec3f60571311168f362b1c16cf044da7037a407b66c19" dependencies = [ "sp-api", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", +] + +[[package]] +name = "sp-panic-handler" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebd2de46003fa8212426838ca71cd42ee36a26480ba9ffea983506ce03131033" +dependencies = [ + "backtrace", + "lazy_static", + "regex", ] [[package]] @@ -13547,7 +14188,30 @@ checksum = "9af4b73fe7ddd88b1641cca90048c4e525e721763199e6fd29c4f590884f4d16" dependencies = [ "rustc-hash", "serde", - "sp-core", + "sp-core 29.0.0", +] + +[[package]] +name = "sp-runtime" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21c5bfc764a1a8259d7e8f7cfd22c84006275a512c958d3ff966c92151e134d5" +dependencies = [ + "either", + "hash256-std-hasher", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", + "paste", + "rand 0.8.5", + "scale-info", + "serde", + "sp-application-crypto 23.0.0", + "sp-arithmetic 16.0.0", + "sp-core 21.0.0", + "sp-io 23.0.0", + "sp-std 8.0.0", + "sp-weights 20.0.0", ] [[package]] @@ -13563,16 +14227,35 @@ dependencies = [ "log", "parity-scale-codec", "paste", - "rand", + "rand 0.8.5", "scale-info", "serde", "simple-mermaid", - "sp-application-crypto", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-std", - "sp-weights", + "sp-application-crypto 31.0.0", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-std 14.0.0", + "sp-weights 28.0.0", +] + +[[package]] +name = "sp-runtime-interface" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e676128182f90015e916f806cba635c8141e341e7abbc45d25525472e1bbce8" +dependencies = [ + "bytes", + "impl-trait-for-tuples", + "parity-scale-codec", + "primitive-types", + "sp-externalities 0.19.0", + "sp-runtime-interface-proc-macro 11.0.0", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-tracing 10.0.0", + "sp-wasm-interface 14.0.0", + "static_assertions", ] [[package]] @@ -13585,15 +14268,28 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "primitive-types", - "sp-externalities", - "sp-runtime-interface-proc-macro", - "sp-std", - "sp-storage", - "sp-tracing", - "sp-wasm-interface", + "sp-externalities 0.26.0", + "sp-runtime-interface-proc-macro 17.0.0", + "sp-std 14.0.0", + "sp-storage 20.0.0", + "sp-tracing 16.0.0", + "sp-wasm-interface 20.0.0", "static_assertions", ] +[[package]] +name = "sp-runtime-interface-proc-macro" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d5bd5566fe5633ec48dfa35ab152fd29f8a577c21971e1c6db9f28afb9bbb9" +dependencies = [ + "Inflector", + "proc-macro-crate 1.3.1", + "proc-macro2", + "quote", + "syn 2.0.58", +] + [[package]] name = "sp-runtime-interface-proc-macro" version = "17.0.0" @@ -13617,11 +14313,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-core", - "sp-keystore", - "sp-runtime", + "sp-core 29.0.0", + "sp-keystore 0.35.0", + "sp-runtime 32.0.0", "sp-staking", - "sp-std", + "sp-std 14.0.0", ] [[package]] @@ -13634,9 +14330,30 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core", - "sp-runtime", - "sp-std", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", +] + +[[package]] +name = "sp-state-machine" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef45d31f9e7ac648f8899a0cd038a3608f8499028bff55b6c799702592325b6" +dependencies = [ + "hash-db", + "log", + "parity-scale-codec", + "parking_lot 0.12.1", + "rand 0.8.5", + "smallvec", + "sp-core 21.0.0", + "sp-externalities 0.19.0", + "sp-panic-handler 8.0.0", + "sp-std 8.0.0", + "sp-trie 22.0.0", + "thiserror", + "tracing", ] [[package]] @@ -13649,16 +14366,16 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "smallvec", - "sp-core", - "sp-externalities", - "sp-panic-handler", - "sp-std", - "sp-trie", + "sp-core 29.0.0", + "sp-externalities 0.26.0", + "sp-panic-handler 13.0.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", "thiserror", "tracing", - "trie-db", + "trie-db 0.28.0", ] [[package]] @@ -13669,30 +14386,50 @@ checksum = "309a9ae4e8134bbed8ffc510cf4d461a4a651f9250b556de782cedd876abe1ff" dependencies = [ "aes-gcm", "curve25519-dalek 4.1.2", - "ed25519-dalek", + "ed25519-dalek 2.1.1", "hkdf", "parity-scale-codec", - "rand", + "rand 0.8.5", "scale-info", "sha2 0.10.8", "sp-api", - "sp-application-crypto", - "sp-core", + "sp-application-crypto 31.0.0", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-externalities", - "sp-runtime", - "sp-runtime-interface", - "sp-std", + "sp-externalities 0.26.0", + "sp-runtime 32.0.0", + "sp-runtime-interface 25.0.0", + "sp-std 14.0.0", "thiserror", "x25519-dalek 2.0.1", ] +[[package]] +name = "sp-std" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53458e3c57df53698b3401ec0934bea8e8cfce034816873c0b0abbd83d7bac0d" + [[package]] name = "sp-std" version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12f8ee986414b0a9ad741776762f4083cd3a5128449b982a3919c4df36874834" +[[package]] +name = "sp-storage" +version = "13.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94294be83f11d4958cfea89ed5798f0b6605f5defc3a996948848458abbcc18e" +dependencies = [ + "impl-serde", + "parity-scale-codec", + "ref-cast", + "serde", + "sp-debug-derive 8.0.0", + "sp-std 8.0.0", +] + [[package]] name = "sp-storage" version = "20.0.0" @@ -13703,8 +14440,8 @@ dependencies = [ "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive", - "sp-std", + "sp-debug-derive 14.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13716,11 +14453,24 @@ dependencies = [ "async-trait", "parity-scale-codec", "sp-inherents", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "thiserror", ] +[[package]] +name = "sp-tracing" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357f7591980dd58305956d32f8f6646d0a8ea9ea0e7e868e46f53b68ddf00cec" +dependencies = [ + "parity-scale-codec", + "sp-std 8.0.0", + "tracing", + "tracing-core", + "tracing-subscriber 0.2.25", +] + [[package]] name = "sp-tracing" version = "16.0.0" @@ -13728,7 +14478,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0351810b9d074df71c4514c5228ed05c250607cba131c1c9d1526760ab69c05c" dependencies = [ "parity-scale-codec", - "sp-std", + "sp-std 14.0.0", "tracing", "tracing-core", "tracing-subscriber 0.2.25", @@ -13741,7 +14491,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9742861c5330bdcb42856a6eed3d3745b58ee1c92ca4c9260032ff4e6c387165" dependencies = [ "sp-api", - "sp-runtime", + "sp-runtime 32.0.0", ] [[package]] @@ -13753,11 +14503,35 @@ dependencies = [ "async-trait", "parity-scale-codec", "scale-info", - "sp-core", + "sp-core 29.0.0", "sp-inherents", - "sp-runtime", - "sp-std", - "sp-trie", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-trie 30.0.0", +] + +[[package]] +name = "sp-trie" +version = "22.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4eeb7ef23f79eba8609db79ef9cef242f994f1f87a3c0387b4b5f177fda74" +dependencies = [ + "ahash 0.8.11", + "hash-db", + "hashbrown 0.13.2", + "lazy_static", + "memory-db", + "nohash-hasher", + "parity-scale-codec", + "parking_lot 0.12.1", + "scale-info", + "schnellru", + "sp-core 21.0.0", + "sp-std 8.0.0", + "thiserror", + "tracing", + "trie-db 0.27.1", + "trie-root", ] [[package]] @@ -13773,15 +14547,15 @@ dependencies = [ "nohash-hasher", "parity-scale-codec", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "scale-info", "schnellru", - "sp-core", - "sp-externalities", - "sp-std", + "sp-core 29.0.0", + "sp-externalities 0.26.0", + "sp-std 14.0.0", "thiserror", "tracing", - "trie-db", + "trie-db 0.28.0", "trie-root", ] @@ -13797,8 +14571,8 @@ dependencies = [ "scale-info", "serde", "sp-crypto-hashing-proc-macro", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", "sp-version-proc-macro", "thiserror", ] @@ -13815,6 +14589,20 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "sp-wasm-interface" +version = "14.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a19c122609ca5d8246be6386888596320d03c7bc880959eaa2c36bcd5acd6846" +dependencies = [ + "anyhow", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", + "sp-std 8.0.0", + "wasmtime", +] + [[package]] name = "sp-wasm-interface" version = "20.0.0" @@ -13825,10 +14613,26 @@ dependencies = [ "impl-trait-for-tuples", "log", "parity-scale-codec", - "sp-std", + "sp-std 14.0.0", "wasmtime", ] +[[package]] +name = "sp-weights" +version = "20.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45d084c735544f70625b821c3acdbc7a2fc1893ca98b85f1942631284692c75b" +dependencies = [ + "parity-scale-codec", + "scale-info", + "serde", + "smallvec", + "sp-arithmetic 16.0.0", + "sp-core 21.0.0", + "sp-debug-derive 8.0.0", + "sp-std 8.0.0", +] + [[package]] name = "sp-weights" version = "28.0.0" @@ -13840,9 +14644,9 @@ dependencies = [ "scale-info", "serde", "smallvec", - "sp-arithmetic", - "sp-debug-derive", - "sp-std", + "sp-arithmetic 24.0.0", + "sp-debug-derive 14.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13933,8 +14737,8 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-runtime", - "sp-std", + "sp-runtime 32.0.0", + "sp-std 14.0.0", ] [[package]] @@ -13952,7 +14756,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-weights", + "sp-weights 28.0.0", "xcm-procedural", ] @@ -13970,11 +14774,11 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "scale-info", - "sp-arithmetic", - "sp-io", - "sp-runtime", - "sp-std", - "sp-weights", + "sp-arithmetic 24.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-weights 28.0.0", "staging-xcm", "staging-xcm-executor", ] @@ -13992,12 +14796,12 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-weights", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-weights 28.0.0", "staging-xcm", ] @@ -14136,8 +14940,8 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-blockchain", - "sp-core", - "sp-runtime", + "sp-core 29.0.0", + "sp-runtime 32.0.0", ] [[package]] @@ -14164,7 +14968,7 @@ dependencies = [ "log", "sc-rpc-api", "serde", - "sp-runtime", + "sp-runtime 32.0.0", ] [[package]] @@ -14178,11 +14982,11 @@ dependencies = [ "sc-client-api", "sc-rpc-api", "serde", - "sp-core", - "sp-runtime", - "sp-state-machine", - "sp-trie", - "trie-db", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", + "sp-trie 30.0.0", + "trie-db 0.28.0", ] [[package]] @@ -14248,7 +15052,7 @@ dependencies = [ "scale-value", "serde", "serde_json", - "sp-core-hashing", + "sp-core-hashing 15.0.0", "subxt-lightclient", "subxt-macro", "subxt-metadata", @@ -14320,7 +15124,7 @@ dependencies = [ "frame-metadata 16.0.0", "parity-scale-codec", "scale-info", - "sp-core-hashing", + "sp-core-hashing 15.0.0", "thiserror", ] @@ -14337,10 +15141,10 @@ dependencies = [ "pbkdf2 0.12.2", "regex", "schnorrkel 0.11.4", - "secp256k1", + "secp256k1 0.28.2", "secrecy", "sha2 0.10.8", - "sp-core-hashing", + "sp-core-hashing 15.0.0", "subxt", "thiserror", "zeroize", @@ -14380,6 +15184,17 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.58", +] + [[package]] name = "system-configuration" version = "0.5.1" @@ -14460,7 +15275,7 @@ dependencies = [ "polkadot-core-primitives", "rococo-runtime-constants", "smallvec", - "sp-runtime", + "sp-runtime 32.0.0", "staging-xcm", "westend-runtime-constants", ] @@ -14595,6 +15410,25 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-bip39" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62cc94d358b5a1e84a5cb9109f559aa3c4d634d2b1b4de3d0fa4adc7c78e2861" +dependencies = [ + "anyhow", + "hmac 0.12.1", + "once_cell", + "pbkdf2 0.11.0", + "rand 0.8.5", + "rustc-hash", + "sha2 0.10.8", + "thiserror", + "unicode-normalization", + "wasm-bindgen", + "zeroize", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -14656,7 +15490,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f57eb36ecbe0fc510036adff84824dd3c24bb781e21bfa67b69d556aa85214f" dependencies = [ "pin-project", - "rand", + "rand 0.8.5", "tokio", ] @@ -14968,6 +15802,19 @@ dependencies = [ "tracing-log 0.2.0", ] +[[package]] +name = "trie-db" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "767abe6ffed88a1889671a102c2861ae742726f52e0a5a425b92c9fbfa7e9c85" +dependencies = [ + "hash-db", + "hashbrown 0.13.2", + "log", + "rustc-hex", + "smallvec", +] + [[package]] name = "trie-db" version = "0.28.0" @@ -15006,7 +15853,7 @@ dependencies = [ "idna 0.2.3", "ipnet", "lazy_static", - "rand", + "rand 0.8.5", "smallvec", "socket2 0.4.10", "thiserror", @@ -15062,19 +15909,19 @@ dependencies = [ "sp-api", "sp-consensus-aura", "sp-consensus-babe", - "sp-core", - "sp-debug-derive", - "sp-externalities", + "sp-core 29.0.0", + "sp-debug-derive 14.0.0", + "sp-externalities 0.26.0", "sp-inherents", - "sp-io", - "sp-keystore", + "sp-io 31.0.0", + "sp-keystore 0.35.0", "sp-rpc", - "sp-runtime", - "sp-state-machine", + "sp-runtime 32.0.0", + "sp-state-machine 0.36.0", "sp-timestamp", "sp-transaction-storage-proof", "sp-version", - "sp-weights", + "sp-weights 28.0.0", "substrate-rpc-client", "zstd 0.12.4", ] @@ -15093,7 +15940,7 @@ checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", "digest 0.10.7", - "rand", + "rand 0.8.5", "static_assertions", ] @@ -15244,7 +16091,7 @@ dependencies = [ "arrayref", "constcat", "digest 0.10.7", - "rand", + "rand 0.8.5", "rand_chacha 0.3.1", "rand_core 0.6.4", "sha2 0.10.8", @@ -15654,7 +16501,7 @@ dependencies = [ "memfd", "memoffset", "paste", - "rand", + "rand 0.8.5", "rustix 0.36.17", "wasmtime-asm-macros", "wasmtime-environ", @@ -15783,24 +16630,24 @@ dependencies = [ "serde_derive", "smallvec", "sp-api", - "sp-application-crypto", - "sp-arithmetic", + "sp-application-crypto 31.0.0", + "sp-arithmetic 24.0.0", "sp-authority-discovery", "sp-block-builder", "sp-consensus-babe", "sp-consensus-beefy", - "sp-core", + "sp-core 29.0.0", "sp-genesis-builder", "sp-inherents", - "sp-io", + "sp-io 31.0.0", "sp-mmr-primitives", "sp-npos-elections", "sp-offchain", - "sp-runtime", + "sp-runtime 32.0.0", "sp-session", "sp-staking", - "sp-std", - "sp-storage", + "sp-std 14.0.0", + "sp-storage 20.0.0", "sp-transaction-pool", "sp-version", "staging-xcm", @@ -15820,9 +16667,9 @@ dependencies = [ "polkadot-primitives", "polkadot-runtime-common", "smallvec", - "sp-core", - "sp-runtime", - "sp-weights", + "sp-core 29.0.0", + "sp-runtime 32.0.0", + "sp-weights 28.0.0", "staging-xcm", "staging-xcm-builder", ] @@ -16214,13 +17061,13 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-parachains", - "sp-arithmetic", - "sp-core", + "sp-arithmetic 24.0.0", + "sp-core 29.0.0", "sp-crypto-hashing", - "sp-io", - "sp-runtime", - "sp-std", - "sp-tracing", + "sp-io 31.0.0", + "sp-runtime 32.0.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", "staging-xcm", "staging-xcm-executor", ] @@ -16237,6 +17084,12 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "xxhash-rust" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "927da81e25be1e1a2901d59b81b37dd2efd1fc9c9345a55007f09bf5a2d3ee03" + [[package]] name = "yamux" version = "0.10.2" @@ -16247,7 +17100,7 @@ dependencies = [ "log", "nohash-hasher", "parking_lot 0.12.1", - "rand", + "rand 0.8.5", "static_assertions", ] diff --git a/pop-api/examples/fungibles/expanded.rs b/pop-api/examples/fungibles/expanded.rs deleted file mode 100644 index c73cdeb7..00000000 --- a/pop-api/examples/fungibles/expanded.rs +++ /dev/null @@ -1,2766 +0,0 @@ -#![feature(prelude_import)] -#[prelude_import] -use std::prelude::rust_2021::*; -#[macro_use] -extern crate std; -use pop_api::{ - primitives::{AccountId as AccountId32, AssetId}, - assets::fungibles::*, -}; -pub enum FungiblesError { - /// Not enough balance to fulfill a request is available. - InsufficientBalance, - /// Not enough allowance to fulfill a request is available. - InsufficientAllowance, - /// The asset status is not the expected status. - IncorrectStatus, - /// The asset ID is already taken. - InUse, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, - /// Recipient's address is zero. - ZeroRecipientAddress, - /// Sender's address is zero. - ZeroSenderAddress, -} -#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] -const _: () = { - impl ::scale_info::TypeInfo for FungiblesError { - type Identity = Self; - fn type_info() -> ::scale_info::Type { - ::scale_info::Type::builder() - .path( - ::scale_info::Path::new_with_replace( - "FungiblesError", - "fungibles", - &[], - ), - ) - .type_params(::alloc::vec::Vec::new()) - .variant( - ::scale_info::build::Variants::new() - .variant( - "InsufficientBalance", - |v| { - v - .index(0usize as ::core::primitive::u8) - .docs( - &["Not enough balance to fulfill a request is available."], - ) - }, - ) - .variant( - "InsufficientAllowance", - |v| { - v - .index(1usize as ::core::primitive::u8) - .docs( - &["Not enough allowance to fulfill a request is available."], - ) - }, - ) - .variant( - "IncorrectStatus", - |v| { - v - .index(2usize as ::core::primitive::u8) - .docs(&["The asset status is not the expected status."]) - }, - ) - .variant( - "InUse", - |v| { - v - .index(3usize as ::core::primitive::u8) - .docs(&["The asset ID is already taken."]) - }, - ) - .variant( - "MinBalanceZero", - |v| { - v - .index(4usize as ::core::primitive::u8) - .docs(&["Minimum balance should be non-zero."]) - }, - ) - .variant( - "NoPermission", - |v| { - v - .index(5usize as ::core::primitive::u8) - .docs( - &[ - "The signing account has no permission to do the operation.", - ], - ) - }, - ) - .variant( - "Unknown", - |v| { - v - .index(6usize as ::core::primitive::u8) - .docs(&["The given asset ID is unknown."]) - }, - ) - .variant( - "ZeroRecipientAddress", - |v| { - v - .index(7usize as ::core::primitive::u8) - .docs(&["Recipient's address is zero."]) - }, - ) - .variant( - "ZeroSenderAddress", - |v| { - v - .index(8usize as ::core::primitive::u8) - .docs(&["Sender's address is zero."]) - }, - ), - ) - } - } -}; -#[automatically_derived] -impl ::core::fmt::Debug for FungiblesError { - #[inline] - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - ::core::fmt::Formatter::write_str( - f, - match self { - FungiblesError::InsufficientBalance => "InsufficientBalance", - FungiblesError::InsufficientAllowance => "InsufficientAllowance", - FungiblesError::IncorrectStatus => "IncorrectStatus", - FungiblesError::InUse => "InUse", - FungiblesError::MinBalanceZero => "MinBalanceZero", - FungiblesError::NoPermission => "NoPermission", - FungiblesError::Unknown => "Unknown", - FungiblesError::ZeroRecipientAddress => "ZeroRecipientAddress", - FungiblesError::ZeroSenderAddress => "ZeroSenderAddress", - }, - ) - } -} -#[automatically_derived] -impl ::core::marker::Copy for FungiblesError {} -#[automatically_derived] -impl ::core::clone::Clone for FungiblesError { - #[inline] - fn clone(&self) -> FungiblesError { - *self - } -} -#[automatically_derived] -impl ::core::marker::StructuralPartialEq for FungiblesError {} -#[automatically_derived] -impl ::core::cmp::PartialEq for FungiblesError { - #[inline] - fn eq(&self, other: &FungiblesError) -> bool { - let __self_tag = ::core::intrinsics::discriminant_value(self); - let __arg1_tag = ::core::intrinsics::discriminant_value(other); - __self_tag == __arg1_tag - } -} -#[automatically_derived] -impl ::core::cmp::Eq for FungiblesError { - #[inline] - #[doc(hidden)] - #[coverage(off)] - fn assert_receiver_is_total_eq(&self) -> () {} -} -#[allow(deprecated)] -const _: () = { - #[automatically_derived] - impl ::scale::Encode for FungiblesError { - fn size_hint(&self) -> usize { - 1_usize - + match *self { - FungiblesError::InsufficientBalance => 0_usize, - FungiblesError::InsufficientAllowance => 0_usize, - FungiblesError::IncorrectStatus => 0_usize, - FungiblesError::InUse => 0_usize, - FungiblesError::MinBalanceZero => 0_usize, - FungiblesError::NoPermission => 0_usize, - FungiblesError::Unknown => 0_usize, - FungiblesError::ZeroRecipientAddress => 0_usize, - FungiblesError::ZeroSenderAddress => 0_usize, - _ => 0_usize, - } - } - fn encode_to<__CodecOutputEdqy: ::scale::Output + ?::core::marker::Sized>( - &self, - __codec_dest_edqy: &mut __CodecOutputEdqy, - ) { - match *self { - FungiblesError::InsufficientBalance => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(0usize as ::core::primitive::u8); - } - FungiblesError::InsufficientAllowance => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(1usize as ::core::primitive::u8); - } - FungiblesError::IncorrectStatus => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(2usize as ::core::primitive::u8); - } - FungiblesError::InUse => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(3usize as ::core::primitive::u8); - } - FungiblesError::MinBalanceZero => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(4usize as ::core::primitive::u8); - } - FungiblesError::NoPermission => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(5usize as ::core::primitive::u8); - } - FungiblesError::Unknown => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(6usize as ::core::primitive::u8); - } - FungiblesError::ZeroRecipientAddress => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(7usize as ::core::primitive::u8); - } - FungiblesError::ZeroSenderAddress => { - #[allow(clippy::unnecessary_cast)] - __codec_dest_edqy.push_byte(8usize as ::core::primitive::u8); - } - _ => {} - } - } - } - #[automatically_derived] - impl ::scale::EncodeLike for FungiblesError {} -}; -#[allow(deprecated)] -const _: () = { - #[automatically_derived] - impl ::scale::Decode for FungiblesError { - fn decode<__CodecInputEdqy: ::scale::Input>( - __codec_input_edqy: &mut __CodecInputEdqy, - ) -> ::core::result::Result { - match __codec_input_edqy - .read_byte() - .map_err(|e| { - e - .chain( - "Could not decode `FungiblesError`, failed to read variant byte", - ) - })? - { - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 0usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::InsufficientBalance) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 1usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::InsufficientAllowance) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 2usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::IncorrectStatus) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 3usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::InUse) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 4usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::MinBalanceZero) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 5usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::NoPermission) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 6usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::Unknown) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 7usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::ZeroRecipientAddress) - })(); - } - #[allow(clippy::unnecessary_cast)] - __codec_x_edqy if __codec_x_edqy == 8usize as ::core::primitive::u8 => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Ok(FungiblesError::ZeroSenderAddress) - })(); - } - _ => { - #[allow(clippy::redundant_closure_call)] - return (move || { - ::core::result::Result::Err( - <_ as ::core::convert::Into< - _, - >>::into( - "Could not decode `FungiblesError`, variant doesn't exist", - ), - ) - })(); - } - } - } - } -}; -impl From for FungiblesError { - fn from(error: Error) -> Self { - match error { - Error::InUse => FungiblesError::InUse, - Error::MinBalanceZero => FungiblesError::MinBalanceZero, - Error::Unknown => FungiblesError::Unknown, - _ => ::core::panicking::panic("not yet implemented"), - } - } -} -/// The fungibles result type. -pub type Result = core::result::Result; -mod fungibles { - impl ::ink::env::ContractEnv for Fungibles { - type Env = pop_api::Environment; - } - type Environment = ::Env; - type AccountId = <::Env as ::ink::env::Environment>::AccountId; - type Balance = <::Env as ::ink::env::Environment>::Balance; - type Hash = <::Env as ::ink::env::Environment>::Hash; - type Timestamp = <::Env as ::ink::env::Environment>::Timestamp; - type BlockNumber = <::Env as ::ink::env::Environment>::BlockNumber; - type ChainExtension = <::Env as ::ink::env::Environment>::ChainExtension; - const MAX_EVENT_TOPICS: usize = <::Env as ::ink::env::Environment>::MAX_EVENT_TOPICS; - const _: () = { - struct Check { - salt: (), - } - }; - #[scale_info(crate = ::ink::scale_info)] - #[cfg(not(feature = "__ink_dylint_Storage"))] - pub struct Fungibles {} - const _: () = { - impl< - __ink_generic_salt: ::ink::storage::traits::StorageKey, - > ::ink::storage::traits::StorableHint<__ink_generic_salt> for Fungibles { - type Type = Fungibles; - type PreferredKey = ::ink::storage::traits::AutoKey; - } - }; - const _: () = { - impl ::ink::storage::traits::StorageKey for Fungibles { - const KEY: ::ink::primitives::Key = <() as ::ink::storage::traits::StorageKey>::KEY; - } - }; - const _: () = { - impl ::ink::storage::traits::Storable for Fungibles { - #[inline(always)] - #[allow(non_camel_case_types)] - fn decode<__ink_I: ::ink::scale::Input>( - __input: &mut __ink_I, - ) -> ::core::result::Result { - ::core::result::Result::Ok(Fungibles {}) - } - #[inline(always)] - #[allow(non_camel_case_types)] - fn encode<__ink_O: ::ink::scale::Output + ?::core::marker::Sized>( - &self, - __dest: &mut __ink_O, - ) { - match self { - Fungibles {} => {} - } - } - #[inline(always)] - #[allow(non_camel_case_types)] - fn encoded_size(&self) -> ::core::primitive::usize { - match self { - Fungibles {} => ::core::primitive::usize::MIN, - } - } - } - }; - #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] - const _: () = { - impl ::ink::scale_info::TypeInfo for Fungibles { - type Identity = Self; - fn type_info() -> ::ink::scale_info::Type { - ::ink::scale_info::Type::builder() - .path( - ::ink::scale_info::Path::new_with_replace( - "Fungibles", - "fungibles::fungibles", - &[], - ), - ) - .type_params(::alloc::vec::Vec::new()) - .composite(::ink::scale_info::build::Fields::named()) - } - } - }; - const _: () = { - impl ::ink::storage::traits::StorageLayout for Fungibles { - fn layout( - __key: &::ink::primitives::Key, - ) -> ::ink::metadata::layout::Layout { - ::ink::metadata::layout::Layout::Struct( - ::ink::metadata::layout::StructLayout::new("Fungibles", []), - ) - } - } - }; - #[automatically_derived] - impl ::core::default::Default for Fungibles { - #[inline] - fn default() -> Fungibles { - Fungibles {} - } - } - const _: () = { - impl ::ink::reflect::ContractName for Fungibles { - const NAME: &'static str = "Fungibles"; - } - }; - const _: () = { - impl<'a> ::ink::codegen::Env for &'a Fungibles { - type EnvAccess = ::ink::EnvAccess< - 'a, - ::Env, - >; - fn env(self) -> Self::EnvAccess { - <::EnvAccess as ::core::default::Default>::default() - } - } - impl<'a> ::ink::codegen::StaticEnv for Fungibles { - type EnvAccess = ::ink::EnvAccess< - 'static, - ::Env, - >; - fn env() -> Self::EnvAccess { - <::EnvAccess as ::core::default::Default>::default() - } - } - }; - const _: () = { - #[allow(unused_imports)] - use ::ink::codegen::{Env as _, StaticEnv as _}; - }; - impl ::ink::reflect::DispatchableConstructorInfo<0x9BAE9D5E_u32> for Fungibles { - type Input = (); - type Output = Self; - type Storage = Fungibles; - type Error = <::ink::reflect::ConstructorOutputValue< - Self, - > as ::ink::reflect::ConstructorOutput>::Error; - const IS_RESULT: ::core::primitive::bool = <::ink::reflect::ConstructorOutputValue< - Self, - > as ::ink::reflect::ConstructorOutput>::IS_RESULT; - const CALLABLE: fn(Self::Input) -> Self::Output = |_| { Fungibles::new() }; - const PAYABLE: ::core::primitive::bool = true; - const SELECTOR: [::core::primitive::u8; 4usize] = [ - 0x9B_u8, - 0xAE_u8, - 0x9D_u8, - 0x5E_u8, - ]; - const LABEL: &'static ::core::primitive::str = "new"; - } - impl ::ink::reflect::DispatchableMessageInfo<0xDB6375A8_u32> for Fungibles { - type Input = AssetId; - type Output = Result; - type Storage = Fungibles; - const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | - storage, - __ink_binding_0| - { Fungibles::total_supply(storage, __ink_binding_0) }; - const SELECTOR: [::core::primitive::u8; 4usize] = [ - 0xDB_u8, - 0x63_u8, - 0x75_u8, - 0xA8_u8, - ]; - const PAYABLE: ::core::primitive::bool = false; - const MUTATES: ::core::primitive::bool = false; - const LABEL: &'static ::core::primitive::str = "total_supply"; - } - impl ::ink::reflect::DispatchableMessageInfo<0x0F755A56_u32> for Fungibles { - type Input = (AssetId, AccountId32); - type Output = Result; - type Storage = Fungibles; - const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | - storage, - (__ink_binding_0, __ink_binding_1)| - { Fungibles::balance_of(storage, __ink_binding_0, __ink_binding_1) }; - const SELECTOR: [::core::primitive::u8; 4usize] = [ - 0x0F_u8, - 0x75_u8, - 0x5A_u8, - 0x56_u8, - ]; - const PAYABLE: ::core::primitive::bool = false; - const MUTATES: ::core::primitive::bool = false; - const LABEL: &'static ::core::primitive::str = "balance_of"; - } - impl ::ink::reflect::DispatchableMessageInfo<0x6A00165E_u32> for Fungibles { - type Input = (AssetId, AccountId32, AccountId32); - type Output = Result; - type Storage = Fungibles; - const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | - storage, - (__ink_binding_0, __ink_binding_1, __ink_binding_2)| - { - Fungibles::allowance( - storage, - __ink_binding_0, - __ink_binding_1, - __ink_binding_2, - ) - }; - const SELECTOR: [::core::primitive::u8; 4usize] = [ - 0x6A_u8, - 0x00_u8, - 0x16_u8, - 0x5E_u8, - ]; - const PAYABLE: ::core::primitive::bool = false; - const MUTATES: ::core::primitive::bool = false; - const LABEL: &'static ::core::primitive::str = "allowance"; - } - impl ::ink::reflect::DispatchableMessageInfo<0xAA6B65DB_u32> for Fungibles { - type Input = AssetId; - type Output = Result; - type Storage = Fungibles; - const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | - storage, - __ink_binding_0| - { Fungibles::asset_exists(storage, __ink_binding_0) }; - const SELECTOR: [::core::primitive::u8; 4usize] = [ - 0xAA_u8, - 0x6B_u8, - 0x65_u8, - 0xDB_u8, - ]; - const PAYABLE: ::core::primitive::bool = false; - const MUTATES: ::core::primitive::bool = false; - const LABEL: &'static ::core::primitive::str = "asset_exists"; - } - impl ::ink::reflect::DispatchableMessageInfo<0x1F8E8E22_u32> for Fungibles { - type Input = (u32, AccountId32, Balance); - type Output = Result<()>; - type Storage = Fungibles; - const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output = | - storage, - (__ink_binding_0, __ink_binding_1, __ink_binding_2)| - { - Fungibles::mint_asset( - storage, - __ink_binding_0, - __ink_binding_1, - __ink_binding_2, - ) - }; - const SELECTOR: [::core::primitive::u8; 4usize] = [ - 0x1F_u8, - 0x8E_u8, - 0x8E_u8, - 0x22_u8, - ]; - const PAYABLE: ::core::primitive::bool = false; - const MUTATES: ::core::primitive::bool = false; - const LABEL: &'static ::core::primitive::str = "mint_asset"; - } - const _: () = { - #[allow(non_camel_case_types)] - pub enum __ink_ConstructorDecoder { - Constructor0( - >::Input, - ), - } - impl ::ink::reflect::DecodeDispatch for __ink_ConstructorDecoder { - fn decode_dispatch( - input: &mut I, - ) -> ::core::result::Result - where - I: ::ink::scale::Input, - { - const CONSTRUCTOR_0: [::core::primitive::u8; 4usize] = >::SELECTOR; - match <[::core::primitive::u8; 4usize] as ::ink::scale::Decode>::decode( - input, - ) - .map_err(|_| ::ink::reflect::DispatchError::InvalidSelector)? - { - CONSTRUCTOR_0 => { - ::core::result::Result::Ok( - Self::Constructor0( - <>::Input as ::ink::scale::Decode>::decode(input) - .map_err(|_| { - ::ink::reflect::DispatchError::InvalidParameters - })?, - ), - ) - } - _invalid => { - ::core::result::Result::Err( - ::ink::reflect::DispatchError::UnknownSelector, - ) - } - } - } - } - impl ::ink::scale::Decode for __ink_ConstructorDecoder { - fn decode( - input: &mut I, - ) -> ::core::result::Result - where - I: ::ink::scale::Input, - { - ::decode_dispatch(input) - .map_err(::core::convert::Into::into) - } - } - impl ::ink::reflect::ExecuteDispatchable for __ink_ConstructorDecoder { - #[allow(clippy::nonminimal_bool)] - fn execute_dispatchable( - self, - ) -> ::core::result::Result<(), ::ink::reflect::DispatchError> { - match self { - Self::Constructor0(input) => { - if { - false - || { - let constructor_0 = false; - let constructor_0 = >::PAYABLE; - constructor_0 - } - } - && !>::PAYABLE - { - ::ink::codegen::deny_payment::< - ::Env, - >()?; - } - let result: >::Output = >::CALLABLE(input); - let output_value = ::ink::reflect::ConstructorOutputValue::new( - result, - ); - let output_result = <::ink::reflect::ConstructorOutputValue< - >::Output, - > as ::ink::reflect::ConstructorOutput< - Fungibles, - >>::as_result(&output_value); - if let ::core::result::Result::Ok(contract) = output_result - .as_ref() - { - ::ink::env::set_contract_storage::< - ::ink::primitives::Key, - Fungibles, - >( - &::KEY, - contract, - ); - } - let mut flag = ::ink::env::ReturnFlags::empty(); - if output_result.is_err() { - flag = ::ink::env::ReturnFlags::REVERT; - } - ::ink::env::return_value::< - ::ink::ConstructorResult< - ::core::result::Result< - (), - &<::ink::reflect::ConstructorOutputValue< - >::Output, - > as ::ink::reflect::ConstructorOutput>::Error, - >, - >, - >( - flag, - &::ink::ConstructorResult::Ok(output_result.map(|_| ())), - ); - } - } - } - } - impl ::ink::reflect::ContractConstructorDecoder for Fungibles { - type Type = __ink_ConstructorDecoder; - } - }; - const _: () = { - #[allow(non_camel_case_types)] - pub enum __ink_MessageDecoder { - Message0( - >::Input, - ), - Message1( - >::Input, - ), - Message2( - >::Input, - ), - Message3( - >::Input, - ), - Message4( - >::Input, - ), - } - impl ::ink::reflect::DecodeDispatch for __ink_MessageDecoder { - fn decode_dispatch( - input: &mut I, - ) -> ::core::result::Result - where - I: ::ink::scale::Input, - { - const MESSAGE_0: [::core::primitive::u8; 4usize] = >::SELECTOR; - const MESSAGE_1: [::core::primitive::u8; 4usize] = >::SELECTOR; - const MESSAGE_2: [::core::primitive::u8; 4usize] = >::SELECTOR; - const MESSAGE_3: [::core::primitive::u8; 4usize] = >::SELECTOR; - const MESSAGE_4: [::core::primitive::u8; 4usize] = >::SELECTOR; - match <[::core::primitive::u8; 4usize] as ::ink::scale::Decode>::decode( - input, - ) - .map_err(|_| ::ink::reflect::DispatchError::InvalidSelector)? - { - MESSAGE_0 => { - ::core::result::Result::Ok( - Self::Message0( - <>::Input as ::ink::scale::Decode>::decode(input) - .map_err(|_| { - ::ink::reflect::DispatchError::InvalidParameters - })?, - ), - ) - } - MESSAGE_1 => { - ::core::result::Result::Ok( - Self::Message1( - <>::Input as ::ink::scale::Decode>::decode(input) - .map_err(|_| { - ::ink::reflect::DispatchError::InvalidParameters - })?, - ), - ) - } - MESSAGE_2 => { - ::core::result::Result::Ok( - Self::Message2( - <>::Input as ::ink::scale::Decode>::decode(input) - .map_err(|_| { - ::ink::reflect::DispatchError::InvalidParameters - })?, - ), - ) - } - MESSAGE_3 => { - ::core::result::Result::Ok( - Self::Message3( - <>::Input as ::ink::scale::Decode>::decode(input) - .map_err(|_| { - ::ink::reflect::DispatchError::InvalidParameters - })?, - ), - ) - } - MESSAGE_4 => { - ::core::result::Result::Ok( - Self::Message4( - <>::Input as ::ink::scale::Decode>::decode(input) - .map_err(|_| { - ::ink::reflect::DispatchError::InvalidParameters - })?, - ), - ) - } - _invalid => { - ::core::result::Result::Err( - ::ink::reflect::DispatchError::UnknownSelector, - ) - } - } - } - } - impl ::ink::scale::Decode for __ink_MessageDecoder { - fn decode( - input: &mut I, - ) -> ::core::result::Result - where - I: ::ink::scale::Input, - { - ::decode_dispatch(input) - .map_err(::core::convert::Into::into) - } - } - fn push_contract(contract: ::core::mem::ManuallyDrop, mutates: bool) { - if mutates { - ::ink::env::set_contract_storage::< - ::ink::primitives::Key, - Fungibles, - >(&::KEY, &contract); - } - } - impl ::ink::reflect::ExecuteDispatchable for __ink_MessageDecoder { - #[allow(clippy::nonminimal_bool, clippy::let_unit_value)] - fn execute_dispatchable( - self, - ) -> ::core::result::Result<(), ::ink::reflect::DispatchError> { - let key = ::KEY; - let mut contract: ::core::mem::ManuallyDrop = ::core::mem::ManuallyDrop::new( - match ::ink::env::get_contract_storage(&key) { - ::core::result::Result::Ok( - ::core::option::Option::Some(value), - ) => value, - ::core::result::Result::Ok(::core::option::Option::None) => { - ::core::panicking::panic_fmt( - format_args!("storage entry was empty"), - ); - } - ::core::result::Result::Err(_) => { - ::core::panicking::panic_fmt( - format_args!("could not properly decode storage entry"), - ); - } - }, - ); - match self { - Self::Message0(input) => { - if { - false - || { - let message_0 = false; - let message_0 = >::PAYABLE; - message_0 - } - || { - let message_1 = false; - let message_1 = >::PAYABLE; - message_1 - } - || { - let message_2 = false; - let message_2 = >::PAYABLE; - message_2 - } - || { - let message_3 = false; - let message_3 = >::PAYABLE; - message_3 - } - || { - let message_4 = false; - let message_4 = >::PAYABLE; - message_4 - } - } - && !>::PAYABLE - { - ::ink::codegen::deny_payment::< - ::Env, - >()?; - } - let result: >::Output = >::CALLABLE(&mut contract, input); - let is_reverted = { - #[allow(unused_imports)] - use ::ink::result_info::IsResultTypeFallback as _; - ::ink::result_info::IsResultType::< - >::Output, - >::VALUE - } - && { - #[allow(unused_imports)] - use ::ink::result_info::IsResultErrFallback as _; - ::ink::result_info::IsResultErr(&result).value() - }; - let mut flag = ::ink::env::ReturnFlags::REVERT; - if !is_reverted { - flag = ::ink::env::ReturnFlags::empty(); - push_contract( - contract, - >::MUTATES, - ); - } - ::ink::env::return_value::< - ::ink::MessageResult< - >::Output, - >, - >(flag, &::ink::MessageResult::Ok(result)) - } - Self::Message1(input) => { - if { - false - || { - let message_0 = false; - let message_0 = >::PAYABLE; - message_0 - } - || { - let message_1 = false; - let message_1 = >::PAYABLE; - message_1 - } - || { - let message_2 = false; - let message_2 = >::PAYABLE; - message_2 - } - || { - let message_3 = false; - let message_3 = >::PAYABLE; - message_3 - } - || { - let message_4 = false; - let message_4 = >::PAYABLE; - message_4 - } - } - && !>::PAYABLE - { - ::ink::codegen::deny_payment::< - ::Env, - >()?; - } - let result: >::Output = >::CALLABLE(&mut contract, input); - let is_reverted = { - #[allow(unused_imports)] - use ::ink::result_info::IsResultTypeFallback as _; - ::ink::result_info::IsResultType::< - >::Output, - >::VALUE - } - && { - #[allow(unused_imports)] - use ::ink::result_info::IsResultErrFallback as _; - ::ink::result_info::IsResultErr(&result).value() - }; - let mut flag = ::ink::env::ReturnFlags::REVERT; - if !is_reverted { - flag = ::ink::env::ReturnFlags::empty(); - push_contract( - contract, - >::MUTATES, - ); - } - ::ink::env::return_value::< - ::ink::MessageResult< - >::Output, - >, - >(flag, &::ink::MessageResult::Ok(result)) - } - Self::Message2(input) => { - if { - false - || { - let message_0 = false; - let message_0 = >::PAYABLE; - message_0 - } - || { - let message_1 = false; - let message_1 = >::PAYABLE; - message_1 - } - || { - let message_2 = false; - let message_2 = >::PAYABLE; - message_2 - } - || { - let message_3 = false; - let message_3 = >::PAYABLE; - message_3 - } - || { - let message_4 = false; - let message_4 = >::PAYABLE; - message_4 - } - } - && !>::PAYABLE - { - ::ink::codegen::deny_payment::< - ::Env, - >()?; - } - let result: >::Output = >::CALLABLE(&mut contract, input); - let is_reverted = { - #[allow(unused_imports)] - use ::ink::result_info::IsResultTypeFallback as _; - ::ink::result_info::IsResultType::< - >::Output, - >::VALUE - } - && { - #[allow(unused_imports)] - use ::ink::result_info::IsResultErrFallback as _; - ::ink::result_info::IsResultErr(&result).value() - }; - let mut flag = ::ink::env::ReturnFlags::REVERT; - if !is_reverted { - flag = ::ink::env::ReturnFlags::empty(); - push_contract( - contract, - >::MUTATES, - ); - } - ::ink::env::return_value::< - ::ink::MessageResult< - >::Output, - >, - >(flag, &::ink::MessageResult::Ok(result)) - } - Self::Message3(input) => { - if { - false - || { - let message_0 = false; - let message_0 = >::PAYABLE; - message_0 - } - || { - let message_1 = false; - let message_1 = >::PAYABLE; - message_1 - } - || { - let message_2 = false; - let message_2 = >::PAYABLE; - message_2 - } - || { - let message_3 = false; - let message_3 = >::PAYABLE; - message_3 - } - || { - let message_4 = false; - let message_4 = >::PAYABLE; - message_4 - } - } - && !>::PAYABLE - { - ::ink::codegen::deny_payment::< - ::Env, - >()?; - } - let result: >::Output = >::CALLABLE(&mut contract, input); - let is_reverted = { - #[allow(unused_imports)] - use ::ink::result_info::IsResultTypeFallback as _; - ::ink::result_info::IsResultType::< - >::Output, - >::VALUE - } - && { - #[allow(unused_imports)] - use ::ink::result_info::IsResultErrFallback as _; - ::ink::result_info::IsResultErr(&result).value() - }; - let mut flag = ::ink::env::ReturnFlags::REVERT; - if !is_reverted { - flag = ::ink::env::ReturnFlags::empty(); - push_contract( - contract, - >::MUTATES, - ); - } - ::ink::env::return_value::< - ::ink::MessageResult< - >::Output, - >, - >(flag, &::ink::MessageResult::Ok(result)) - } - Self::Message4(input) => { - if { - false - || { - let message_0 = false; - let message_0 = >::PAYABLE; - message_0 - } - || { - let message_1 = false; - let message_1 = >::PAYABLE; - message_1 - } - || { - let message_2 = false; - let message_2 = >::PAYABLE; - message_2 - } - || { - let message_3 = false; - let message_3 = >::PAYABLE; - message_3 - } - || { - let message_4 = false; - let message_4 = >::PAYABLE; - message_4 - } - } - && !>::PAYABLE - { - ::ink::codegen::deny_payment::< - ::Env, - >()?; - } - let result: >::Output = >::CALLABLE(&mut contract, input); - let is_reverted = { - #[allow(unused_imports)] - use ::ink::result_info::IsResultTypeFallback as _; - ::ink::result_info::IsResultType::< - >::Output, - >::VALUE - } - && { - #[allow(unused_imports)] - use ::ink::result_info::IsResultErrFallback as _; - ::ink::result_info::IsResultErr(&result).value() - }; - let mut flag = ::ink::env::ReturnFlags::REVERT; - if !is_reverted { - flag = ::ink::env::ReturnFlags::empty(); - push_contract( - contract, - >::MUTATES, - ); - } - ::ink::env::return_value::< - ::ink::MessageResult< - >::Output, - >, - >(flag, &::ink::MessageResult::Ok(result)) - } - }; - } - } - impl ::ink::reflect::ContractMessageDecoder for Fungibles { - type Type = __ink_MessageDecoder; - } - }; - const _: () = { - use ::ink::codegen::{Env as _, StaticEnv as _}; - const _: ::ink::codegen::utils::IsSameType = ::ink::codegen::utils::IsSameType::< - Fungibles, - >::new(); - impl Fungibles { - #[cfg(not(feature = "__ink_dylint_Constructor"))] - pub fn new() -> Self { - ::ink_env::debug_message( - &{ - let res = ::alloc::fmt::format( - format_args!( - "{0}\n", - { - let res = ::alloc::fmt::format( - format_args!("PopApiAssetsExample::new"), - ); - res - }, - ), - ); - res - }, - ); - Default::default() - } - pub fn total_supply(&self, id: AssetId) -> Result { - total_supply(id).map_err(From::from) - } - pub fn balance_of( - &self, - id: AssetId, - owner: AccountId32, - ) -> Result { - balance_of(id, owner).map_err(From::from) - } - pub fn allowance( - &self, - id: AssetId, - owner: AccountId32, - spender: AccountId32, - ) -> Result { - allowance(id, owner, spender).map_err(From::from) - } - pub fn asset_exists(&self, id: AssetId) -> Result { - asset_exists(id).map_err(From::from) - } - pub fn mint_asset( - &self, - id: u32, - beneficiary: AccountId32, - amount: Balance, - ) -> Result<()> { - ::ink_env::debug_message( - &{ - let res = ::alloc::fmt::format( - format_args!( - "{0}\n", - { - let res = ::alloc::fmt::format( - format_args!( - "PopApiAssetsExample::mint_asset_through_runtime: id: {0:?} beneficiary: {1:?} amount: {2:?}", - id, - beneficiary, - amount, - ), - ); - res - }, - ), - ); - res - }, - ); - let result = mint(id, beneficiary, amount)?; - ::ink_env::debug_message( - &{ - let res = ::alloc::fmt::format( - format_args!( - "{0}\n", - { - let res = ::alloc::fmt::format( - format_args!("Result: {0:?}", result), - ); - res - }, - ), - ); - res - }, - ); - Ok(()) - } - } - const _: () = { - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchOutput>, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchOutput>, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchOutput>, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchOutput>, - >(); - ::ink::codegen::utils::consume_type::<::ink::codegen::DispatchInput>(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchInput, - >(); - ::ink::codegen::utils::consume_type::< - ::ink::codegen::DispatchOutput>, - >(); - }; - }; - const _: () = { - #[codec(crate = ::ink::scale)] - #[scale_info(crate = ::ink::scale_info)] - /// The ink! smart contract's call builder. - /// - /// Implements the underlying on-chain calling of the ink! smart contract - /// messages and trait implementations in a type safe way. - #[repr(transparent)] - pub struct CallBuilder { - account_id: AccountId, - } - #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] - const _: () = { - impl ::ink::scale_info::TypeInfo for CallBuilder { - type Identity = Self; - fn type_info() -> ::ink::scale_info::Type { - ::ink::scale_info::Type::builder() - .path( - ::ink::scale_info::Path::new_with_replace( - "CallBuilder", - "fungibles::fungibles", - &[], - ), - ) - .type_params(::alloc::vec::Vec::new()) - .docs( - &[ - "The ink! smart contract's call builder.", - "", - "Implements the underlying on-chain calling of the ink! smart contract", - "messages and trait implementations in a type safe way.", - ], - ) - .composite( - ::ink::scale_info::build::Fields::named() - .field(|f| { - f - .ty::() - .name("account_id") - .type_name("AccountId") - }), - ) - } - } - }; - #[allow(deprecated)] - const _: () = { - #[automatically_derived] - impl ::ink::scale::Decode for CallBuilder { - fn decode<__CodecInputEdqy: ::ink::scale::Input>( - __codec_input_edqy: &mut __CodecInputEdqy, - ) -> ::core::result::Result { - ::core::result::Result::Ok(CallBuilder { - account_id: { - let __codec_res_edqy = ::decode( - __codec_input_edqy, - ); - match __codec_res_edqy { - ::core::result::Result::Err(e) => { - return ::core::result::Result::Err( - e.chain("Could not decode `CallBuilder::account_id`"), - ); - } - ::core::result::Result::Ok(__codec_res_edqy) => { - __codec_res_edqy - } - } - }, - }) - } - fn decode_into<__CodecInputEdqy: ::ink::scale::Input>( - __codec_input_edqy: &mut __CodecInputEdqy, - dst_: &mut ::core::mem::MaybeUninit, - ) -> ::core::result::Result< - ::ink::scale::DecodeFinished, - ::ink::scale::Error, - > { - match ( - &::core::mem::size_of::(), - &::core::mem::size_of::(), - ) { - (left_val, right_val) => { - if !(*left_val == *right_val) { - let kind = ::core::panicking::AssertKind::Eq; - ::core::panicking::assert_failed( - kind, - &*left_val, - &*right_val, - ::core::option::Option::None, - ); - } - } - }; - if !(if ::core::mem::size_of::() > 0 { 1 } else { 0 } - <= 1) - { - ::core::panicking::panic( - "assertion failed: if ::core::mem::size_of::() > 0 { 1 } else { 0 } <= 1", - ) - } - { - let dst_: &mut ::core::mem::MaybeUninit = dst_; - let dst_: &mut ::core::mem::MaybeUninit = unsafe { - &mut *dst_ - .as_mut_ptr() - .cast::<::core::mem::MaybeUninit>() - }; - ::decode_into( - __codec_input_edqy, - dst_, - )?; - } - unsafe { - ::core::result::Result::Ok( - ::ink::scale::DecodeFinished::assert_decoding_finished(), - ) - } - } - } - }; - #[allow(deprecated)] - const _: () = { - #[automatically_derived] - impl ::ink::scale::Encode for CallBuilder { - fn size_hint(&self) -> usize { - ::ink::scale::Encode::size_hint(&&self.account_id) - } - fn encode_to< - __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, - >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { - ::ink::scale::Encode::encode_to(&&self.account_id, __codec_dest_edqy) - } - fn encode( - &self, - ) -> ::ink::scale::alloc::vec::Vec<::core::primitive::u8> { - ::ink::scale::Encode::encode(&&self.account_id) - } - fn using_encoded< - __CodecOutputReturn, - __CodecUsingEncodedCallback: ::core::ops::FnOnce( - &[::core::primitive::u8], - ) -> __CodecOutputReturn, - >(&self, f: __CodecUsingEncodedCallback) -> __CodecOutputReturn { - ::ink::scale::Encode::using_encoded(&&self.account_id, f) - } - } - #[automatically_derived] - impl ::ink::scale::EncodeLike for CallBuilder {} - }; - #[automatically_derived] - impl ::core::fmt::Debug for CallBuilder { - #[inline] - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - ::core::fmt::Formatter::debug_struct_field1_finish( - f, - "CallBuilder", - "account_id", - &&self.account_id, - ) - } - } - #[automatically_derived] - impl ::core::hash::Hash for CallBuilder { - #[inline] - fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () { - ::core::hash::Hash::hash(&self.account_id, state) - } - } - #[automatically_derived] - impl ::core::marker::StructuralPartialEq for CallBuilder {} - #[automatically_derived] - impl ::core::cmp::PartialEq for CallBuilder { - #[inline] - fn eq(&self, other: &CallBuilder) -> bool { - self.account_id == other.account_id - } - } - #[automatically_derived] - impl ::core::cmp::Eq for CallBuilder { - #[inline] - #[doc(hidden)] - #[coverage(off)] - fn assert_receiver_is_total_eq(&self) -> () { - let _: ::core::cmp::AssertParamIsEq; - } - } - #[automatically_derived] - impl ::core::clone::Clone for CallBuilder { - #[inline] - fn clone(&self) -> CallBuilder { - CallBuilder { - account_id: ::core::clone::Clone::clone(&self.account_id), - } - } - } - const _: () = { - impl ::ink::storage::traits::StorageLayout for CallBuilder { - fn layout( - __key: &::ink::primitives::Key, - ) -> ::ink::metadata::layout::Layout { - ::ink::metadata::layout::Layout::Struct( - ::ink::metadata::layout::StructLayout::new( - "CallBuilder", - [ - ::ink::metadata::layout::FieldLayout::new( - "account_id", - ::layout( - __key, - ), - ), - ], - ), - ) - } - } - }; - const _: () = { - impl ::ink::codegen::ContractCallBuilder for Fungibles { - type Type = CallBuilder; - } - impl ::ink::env::ContractEnv for CallBuilder { - type Env = ::Env; - } - }; - impl ::ink::env::call::FromAccountId for CallBuilder { - #[inline] - fn from_account_id(account_id: AccountId) -> Self { - Self { account_id } - } - } - impl ::ink::ToAccountId for CallBuilder { - #[inline] - fn to_account_id(&self) -> AccountId { - ::clone(&self.account_id) - } - } - impl ::core::convert::AsRef for CallBuilder { - fn as_ref(&self) -> &AccountId { - &self.account_id - } - } - impl ::core::convert::AsMut for CallBuilder { - fn as_mut(&mut self) -> &mut AccountId { - &mut self.account_id - } - } - impl CallBuilder { - #[allow(clippy::type_complexity)] - #[inline] - pub fn total_supply( - &self, - __ink_binding_0: AssetId, - ) -> ::ink::env::call::CallBuilder< - Environment, - ::ink::env::call::utils::Set<::ink::env::call::Call>, - ::ink::env::call::utils::Set< - ::ink::env::call::ExecutionInput< - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::EmptyArgumentList, - >, - >, - >, - ::ink::env::call::utils::Set< - ::ink::env::call::utils::ReturnType>, - >, - > { - ::ink::env::call::build_call::() - .call(::ink::ToAccountId::to_account_id(self)) - .exec_input( - ::ink::env::call::ExecutionInput::new( - ::ink::env::call::Selector::new([ - 0xDB_u8, - 0x63_u8, - 0x75_u8, - 0xA8_u8, - ]), - ) - .push_arg(__ink_binding_0), - ) - .returns::>() - } - #[allow(clippy::type_complexity)] - #[inline] - pub fn balance_of( - &self, - __ink_binding_0: AssetId, - __ink_binding_1: AccountId32, - ) -> ::ink::env::call::CallBuilder< - Environment, - ::ink::env::call::utils::Set<::ink::env::call::Call>, - ::ink::env::call::utils::Set< - ::ink::env::call::ExecutionInput< - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::EmptyArgumentList, - >, - >, - >, - >, - ::ink::env::call::utils::Set< - ::ink::env::call::utils::ReturnType>, - >, - > { - ::ink::env::call::build_call::() - .call(::ink::ToAccountId::to_account_id(self)) - .exec_input( - ::ink::env::call::ExecutionInput::new( - ::ink::env::call::Selector::new([ - 0x0F_u8, - 0x75_u8, - 0x5A_u8, - 0x56_u8, - ]), - ) - .push_arg(__ink_binding_0) - .push_arg(__ink_binding_1), - ) - .returns::>() - } - #[allow(clippy::type_complexity)] - #[inline] - pub fn allowance( - &self, - __ink_binding_0: AssetId, - __ink_binding_1: AccountId32, - __ink_binding_2: AccountId32, - ) -> ::ink::env::call::CallBuilder< - Environment, - ::ink::env::call::utils::Set<::ink::env::call::Call>, - ::ink::env::call::utils::Set< - ::ink::env::call::ExecutionInput< - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::EmptyArgumentList, - >, - >, - >, - >, - >, - ::ink::env::call::utils::Set< - ::ink::env::call::utils::ReturnType>, - >, - > { - ::ink::env::call::build_call::() - .call(::ink::ToAccountId::to_account_id(self)) - .exec_input( - ::ink::env::call::ExecutionInput::new( - ::ink::env::call::Selector::new([ - 0x6A_u8, - 0x00_u8, - 0x16_u8, - 0x5E_u8, - ]), - ) - .push_arg(__ink_binding_0) - .push_arg(__ink_binding_1) - .push_arg(__ink_binding_2), - ) - .returns::>() - } - #[allow(clippy::type_complexity)] - #[inline] - pub fn asset_exists( - &self, - __ink_binding_0: AssetId, - ) -> ::ink::env::call::CallBuilder< - Environment, - ::ink::env::call::utils::Set<::ink::env::call::Call>, - ::ink::env::call::utils::Set< - ::ink::env::call::ExecutionInput< - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::EmptyArgumentList, - >, - >, - >, - ::ink::env::call::utils::Set< - ::ink::env::call::utils::ReturnType>, - >, - > { - ::ink::env::call::build_call::() - .call(::ink::ToAccountId::to_account_id(self)) - .exec_input( - ::ink::env::call::ExecutionInput::new( - ::ink::env::call::Selector::new([ - 0xAA_u8, - 0x6B_u8, - 0x65_u8, - 0xDB_u8, - ]), - ) - .push_arg(__ink_binding_0), - ) - .returns::>() - } - #[allow(clippy::type_complexity)] - #[inline] - pub fn mint_asset( - &self, - __ink_binding_0: u32, - __ink_binding_1: AccountId32, - __ink_binding_2: Balance, - ) -> ::ink::env::call::CallBuilder< - Environment, - ::ink::env::call::utils::Set<::ink::env::call::Call>, - ::ink::env::call::utils::Set< - ::ink::env::call::ExecutionInput< - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::ArgumentList< - ::ink::env::call::utils::Argument, - ::ink::env::call::utils::EmptyArgumentList, - >, - >, - >, - >, - >, - ::ink::env::call::utils::Set< - ::ink::env::call::utils::ReturnType>, - >, - > { - ::ink::env::call::build_call::() - .call(::ink::ToAccountId::to_account_id(self)) - .exec_input( - ::ink::env::call::ExecutionInput::new( - ::ink::env::call::Selector::new([ - 0x1F_u8, - 0x8E_u8, - 0x8E_u8, - 0x22_u8, - ]), - ) - .push_arg(__ink_binding_0) - .push_arg(__ink_binding_1) - .push_arg(__ink_binding_2), - ) - .returns::>() - } - } - }; - #[codec(crate = ::ink::scale)] - #[scale_info(crate = ::ink::scale_info)] - pub struct FungiblesRef { - inner: ::Type, - } - #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] - const _: () = { - impl ::ink::scale_info::TypeInfo for FungiblesRef { - type Identity = Self; - fn type_info() -> ::ink::scale_info::Type { - ::ink::scale_info::Type::builder() - .path( - ::ink::scale_info::Path::new_with_replace( - "FungiblesRef", - "fungibles::fungibles", - &[], - ), - ) - .type_params(::alloc::vec::Vec::new()) - .composite( - ::ink::scale_info::build::Fields::named() - .field(|f| { - f - .ty::< - ::Type, - >() - .name("inner") - .type_name( - "::Type", - ) - }), - ) - } - } - }; - #[allow(deprecated)] - const _: () = { - #[automatically_derived] - impl ::ink::scale::Decode for FungiblesRef { - fn decode<__CodecInputEdqy: ::ink::scale::Input>( - __codec_input_edqy: &mut __CodecInputEdqy, - ) -> ::core::result::Result { - ::core::result::Result::Ok(FungiblesRef { - inner: { - let __codec_res_edqy = <::Type as ::ink::scale::Decode>::decode( - __codec_input_edqy, - ); - match __codec_res_edqy { - ::core::result::Result::Err(e) => { - return ::core::result::Result::Err( - e.chain("Could not decode `FungiblesRef::inner`"), - ); - } - ::core::result::Result::Ok(__codec_res_edqy) => { - __codec_res_edqy - } - } - }, - }) - } - } - }; - #[allow(deprecated)] - const _: () = { - #[automatically_derived] - impl ::ink::scale::Encode for FungiblesRef { - fn size_hint(&self) -> usize { - ::ink::scale::Encode::size_hint(&&self.inner) - } - fn encode_to< - __CodecOutputEdqy: ::ink::scale::Output + ?::core::marker::Sized, - >(&self, __codec_dest_edqy: &mut __CodecOutputEdqy) { - ::ink::scale::Encode::encode_to(&&self.inner, __codec_dest_edqy) - } - fn encode(&self) -> ::ink::scale::alloc::vec::Vec<::core::primitive::u8> { - ::ink::scale::Encode::encode(&&self.inner) - } - fn using_encoded< - __CodecOutputReturn, - __CodecUsingEncodedCallback: ::core::ops::FnOnce( - &[::core::primitive::u8], - ) -> __CodecOutputReturn, - >(&self, f: __CodecUsingEncodedCallback) -> __CodecOutputReturn { - ::ink::scale::Encode::using_encoded(&&self.inner, f) - } - } - #[automatically_derived] - impl ::ink::scale::EncodeLike for FungiblesRef {} - }; - #[automatically_derived] - impl ::core::fmt::Debug for FungiblesRef { - #[inline] - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - ::core::fmt::Formatter::debug_struct_field1_finish( - f, - "FungiblesRef", - "inner", - &&self.inner, - ) - } - } - #[automatically_derived] - impl ::core::hash::Hash for FungiblesRef { - #[inline] - fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () { - ::core::hash::Hash::hash(&self.inner, state) - } - } - #[automatically_derived] - impl ::core::marker::StructuralPartialEq for FungiblesRef {} - #[automatically_derived] - impl ::core::cmp::PartialEq for FungiblesRef { - #[inline] - fn eq(&self, other: &FungiblesRef) -> bool { - self.inner == other.inner - } - } - #[automatically_derived] - impl ::core::cmp::Eq for FungiblesRef { - #[inline] - #[doc(hidden)] - #[coverage(off)] - fn assert_receiver_is_total_eq(&self) -> () { - let _: ::core::cmp::AssertParamIsEq< - ::Type, - >; - } - } - #[automatically_derived] - impl ::core::clone::Clone for FungiblesRef { - #[inline] - fn clone(&self) -> FungiblesRef { - FungiblesRef { - inner: ::core::clone::Clone::clone(&self.inner), - } - } - } - const _: () = { - impl ::ink::storage::traits::StorageLayout for FungiblesRef { - fn layout( - __key: &::ink::primitives::Key, - ) -> ::ink::metadata::layout::Layout { - ::ink::metadata::layout::Layout::Struct( - ::ink::metadata::layout::StructLayout::new( - "FungiblesRef", - [ - ::ink::metadata::layout::FieldLayout::new( - "inner", - <::Type as ::ink::storage::traits::StorageLayout>::layout( - __key, - ), - ), - ], - ), - ) - } - } - }; - const _: () = { - impl ::ink::env::ContractReference for Fungibles { - type Type = FungiblesRef; - } - impl ::ink::env::call::ConstructorReturnType for Fungibles { - type Output = FungiblesRef; - type Error = (); - fn ok(value: FungiblesRef) -> Self::Output { - value - } - } - impl ::ink::env::call::ConstructorReturnType - for ::core::result::Result - where - E: ::ink::scale::Decode, - { - const IS_RESULT: bool = true; - type Output = ::core::result::Result; - type Error = E; - fn ok(value: FungiblesRef) -> Self::Output { - ::core::result::Result::Ok(value) - } - fn err(err: Self::Error) -> ::core::option::Option { - ::core::option::Option::Some(::core::result::Result::Err(err)) - } - } - impl ::ink::env::ContractEnv for FungiblesRef { - type Env = ::Env; - } - }; - impl FungiblesRef { - #[inline] - #[allow(clippy::type_complexity)] - pub fn new() -> ::ink::env::call::CreateBuilder< - Environment, - Self, - ::ink::env::call::utils::Unset, - ::ink::env::call::utils::Set< - ::ink::env::call::LimitParamsV2< - ::Env, - >, - >, - ::ink::env::call::utils::Unset, - ::ink::env::call::utils::Set< - ::ink::env::call::ExecutionInput< - ::ink::env::call::utils::EmptyArgumentList, - >, - >, - ::ink::env::call::utils::Unset<::ink::env::call::state::Salt>, - ::ink::env::call::utils::Set<::ink::env::call::utils::ReturnType>, - > { - ::ink::env::call::build_create::() - .exec_input( - ::ink::env::call::ExecutionInput::new( - ::ink::env::call::Selector::new([ - 0x9B_u8, - 0xAE_u8, - 0x9D_u8, - 0x5E_u8, - ]), - ), - ) - .returns::() - } - #[inline] - pub fn total_supply(&self, id: AssetId) -> Result { - self.try_total_supply(id) - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "total_supply", - error, - ), - ); - }) - } - #[inline] - pub fn try_total_supply( - &self, - id: AssetId, - ) -> ::ink::MessageResult> { - ::call(self) - .total_supply(id) - .try_invoke() - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "total_supply", - error, - ), - ); - }) - } - #[inline] - pub fn balance_of(&self, id: AssetId, owner: AccountId32) -> Result { - self.try_balance_of(id, owner) - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "balance_of", - error, - ), - ); - }) - } - #[inline] - pub fn try_balance_of( - &self, - id: AssetId, - owner: AccountId32, - ) -> ::ink::MessageResult> { - ::call(self) - .balance_of(id, owner) - .try_invoke() - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "balance_of", - error, - ), - ); - }) - } - #[inline] - pub fn allowance( - &self, - id: AssetId, - owner: AccountId32, - spender: AccountId32, - ) -> Result { - self.try_allowance(id, owner, spender) - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "allowance", - error, - ), - ); - }) - } - #[inline] - pub fn try_allowance( - &self, - id: AssetId, - owner: AccountId32, - spender: AccountId32, - ) -> ::ink::MessageResult> { - ::call(self) - .allowance(id, owner, spender) - .try_invoke() - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "allowance", - error, - ), - ); - }) - } - #[inline] - pub fn asset_exists(&self, id: AssetId) -> Result { - self.try_asset_exists(id) - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "asset_exists", - error, - ), - ); - }) - } - #[inline] - pub fn try_asset_exists( - &self, - id: AssetId, - ) -> ::ink::MessageResult> { - ::call(self) - .asset_exists(id) - .try_invoke() - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "asset_exists", - error, - ), - ); - }) - } - #[inline] - pub fn mint_asset( - &self, - id: u32, - beneficiary: AccountId32, - amount: Balance, - ) -> Result<()> { - self.try_mint_asset(id, beneficiary, amount) - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "mint_asset", - error, - ), - ); - }) - } - #[inline] - pub fn try_mint_asset( - &self, - id: u32, - beneficiary: AccountId32, - amount: Balance, - ) -> ::ink::MessageResult> { - ::call(self) - .mint_asset(id, beneficiary, amount) - .try_invoke() - .unwrap_or_else(|error| { - ::core::panicking::panic_fmt( - format_args!( - "encountered error while calling {0}::{1}: {2:?}", - "Fungibles", - "mint_asset", - error, - ), - ); - }) - } - } - const _: () = { - impl ::ink::codegen::TraitCallBuilder for FungiblesRef { - type Builder = ::Type; - #[inline] - fn call(&self) -> &Self::Builder { - &self.inner - } - #[inline] - fn call_mut(&mut self) -> &mut Self::Builder { - &mut self.inner - } - } - }; - impl ::ink::env::call::FromAccountId for FungiblesRef { - #[inline] - fn from_account_id(account_id: AccountId) -> Self { - Self { - inner: <::Type as ::ink::env::call::FromAccountId< - Environment, - >>::from_account_id(account_id), - } - } - } - impl ::ink::ToAccountId for FungiblesRef { - #[inline] - fn to_account_id(&self) -> AccountId { - <::Type as ::ink::ToAccountId< - Environment, - >>::to_account_id(&self.inner) - } - } - impl ::core::convert::AsRef for FungiblesRef { - fn as_ref(&self) -> &AccountId { - <_ as ::core::convert::AsRef>::as_ref(&self.inner) - } - } - impl ::core::convert::AsMut for FungiblesRef { - fn as_mut(&mut self) -> &mut AccountId { - <_ as ::core::convert::AsMut>::as_mut(&mut self.inner) - } - } - #[cfg(feature = "std")] - #[cfg(not(feature = "ink-as-dependency"))] - const _: () = { - #[no_mangle] - pub fn __ink_generate_metadata() -> ::ink::metadata::InkProject { - let layout = ::ink::metadata::layout::Layout::Root( - ::ink::metadata::layout::RootLayout::new( - <::ink::metadata::layout::LayoutKey as ::core::convert::From< - ::ink::primitives::Key, - >>::from(::KEY), - ::layout( - &::KEY, - ), - ::ink::scale_info::meta_type::(), - ), - ); - ::ink::metadata::layout::ValidateLayout::validate(&layout) - .unwrap_or_else(|error| { - { - ::core::panicking::panic_fmt( - format_args!("metadata ink! generation failed: {0}", error), - ); - } - }); - ::ink::metadata::InkProject::new( - layout, - ::ink::metadata::ContractSpec::new() - .constructors([ - ::ink::metadata::ConstructorSpec::from_label("new") - .selector([0x9B_u8, 0xAE_u8, 0x9D_u8, 0x5E_u8]) - .args([]) - .payable(true) - .default(false) - .returns( - ::ink::metadata::ReturnTypeSpec::new( - if >::IS_RESULT { - ::ink::metadata::TypeSpec::with_name_str::< - ::ink::ConstructorResult< - ::core::result::Result< - (), - >::Error, - >, - >, - >("ink_primitives::ConstructorResult") - } else { - ::ink::metadata::TypeSpec::with_name_str::< - ::ink::ConstructorResult<()>, - >("ink_primitives::ConstructorResult") - }, - ), - ) - .docs([]) - .done(), - ]) - .messages([ - ::ink::metadata::MessageSpec::from_label("total_supply") - .selector([0xDB_u8, 0x63_u8, 0x75_u8, 0xA8_u8]) - .args([ - ::ink::metadata::MessageParamSpec::new("id") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AssetId, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AssetId"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ]) - .returns( - ::ink::metadata::ReturnTypeSpec::new( - ::ink::metadata::TypeSpec::with_name_segs::< - ::ink::MessageResult>, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter([ - "ink", - "MessageResult", - ]), - ::core::convert::AsRef::as_ref, - ), - ), - ), - ) - .mutates(false) - .payable(false) - .default(false) - .docs([]) - .done(), - ::ink::metadata::MessageSpec::from_label("balance_of") - .selector([0x0F_u8, 0x75_u8, 0x5A_u8, 0x56_u8]) - .args([ - ::ink::metadata::MessageParamSpec::new("id") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AssetId, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AssetId"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ::ink::metadata::MessageParamSpec::new("owner") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AccountId32, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AccountId32"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ]) - .returns( - ::ink::metadata::ReturnTypeSpec::new( - ::ink::metadata::TypeSpec::with_name_segs::< - ::ink::MessageResult>, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter([ - "ink", - "MessageResult", - ]), - ::core::convert::AsRef::as_ref, - ), - ), - ), - ) - .mutates(false) - .payable(false) - .default(false) - .docs([]) - .done(), - ::ink::metadata::MessageSpec::from_label("allowance") - .selector([0x6A_u8, 0x00_u8, 0x16_u8, 0x5E_u8]) - .args([ - ::ink::metadata::MessageParamSpec::new("id") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AssetId, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AssetId"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ::ink::metadata::MessageParamSpec::new("owner") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AccountId32, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AccountId32"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ::ink::metadata::MessageParamSpec::new("spender") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AccountId32, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AccountId32"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ]) - .returns( - ::ink::metadata::ReturnTypeSpec::new( - ::ink::metadata::TypeSpec::with_name_segs::< - ::ink::MessageResult>, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter([ - "ink", - "MessageResult", - ]), - ::core::convert::AsRef::as_ref, - ), - ), - ), - ) - .mutates(false) - .payable(false) - .default(false) - .docs([]) - .done(), - ::ink::metadata::MessageSpec::from_label("asset_exists") - .selector([0xAA_u8, 0x6B_u8, 0x65_u8, 0xDB_u8]) - .args([ - ::ink::metadata::MessageParamSpec::new("id") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AssetId, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AssetId"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ]) - .returns( - ::ink::metadata::ReturnTypeSpec::new( - ::ink::metadata::TypeSpec::with_name_segs::< - ::ink::MessageResult>, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter([ - "ink", - "MessageResult", - ]), - ::core::convert::AsRef::as_ref, - ), - ), - ), - ) - .mutates(false) - .payable(false) - .default(false) - .docs([]) - .done(), - ::ink::metadata::MessageSpec::from_label("mint_asset") - .selector([0x1F_u8, 0x8E_u8, 0x8E_u8, 0x22_u8]) - .args([ - ::ink::metadata::MessageParamSpec::new("id") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - u32, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["u32"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ::ink::metadata::MessageParamSpec::new("beneficiary") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - AccountId32, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AccountId32"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ::ink::metadata::MessageParamSpec::new("amount") - .of_type( - ::ink::metadata::TypeSpec::with_name_segs::< - Balance, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["Balance"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .done(), - ]) - .returns( - ::ink::metadata::ReturnTypeSpec::new( - ::ink::metadata::TypeSpec::with_name_segs::< - ::ink::MessageResult>, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter([ - "ink", - "MessageResult", - ]), - ::core::convert::AsRef::as_ref, - ), - ), - ), - ) - .mutates(false) - .payable(false) - .default(false) - .docs([]) - .done(), - ]) - .collect_events() - .docs([]) - .lang_error( - ::ink::metadata::TypeSpec::with_name_segs::< - ::ink::LangError, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["ink", "LangError"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .environment( - ::ink::metadata::EnvironmentSpec::new() - .account_id( - ::ink::metadata::TypeSpec::with_name_segs::< - AccountId, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["AccountId"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .balance( - ::ink::metadata::TypeSpec::with_name_segs::< - Balance, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["Balance"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .hash( - ::ink::metadata::TypeSpec::with_name_segs::< - Hash, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["Hash"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .timestamp( - ::ink::metadata::TypeSpec::with_name_segs::< - Timestamp, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["Timestamp"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .block_number( - ::ink::metadata::TypeSpec::with_name_segs::< - BlockNumber, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["BlockNumber"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .chain_extension( - ::ink::metadata::TypeSpec::with_name_segs::< - ChainExtension, - _, - >( - ::core::iter::Iterator::map( - ::core::iter::IntoIterator::into_iter(["ChainExtension"]), - ::core::convert::AsRef::as_ref, - ), - ), - ) - .max_event_topics(MAX_EVENT_TOPICS) - .static_buffer_size(::ink::env::BUFFER_SIZE) - .done(), - ) - .done(), - ) - } - }; - use super::*; -} diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 68e43865..59040590 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -7,61 +7,12 @@ /// use ink::prelude::vec::Vec; use pop_api::{ - assets::fungibles::*, + assets::use_cases::fungibles as api, + error::PopApiError, primitives::{AccountId as AccountId32, AssetId}, }; -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum ContractError { - /// The asset is not live; either frozen or being destroyed. - AssetNotLive, - /// The amount to mint is less than the existential deposit. - BelowMinimum, - /// Unspecified dispatch error, providing the index and its error index (if none `0`). - DispatchError { index: u8, error: u8 }, - /// Not enough allowance to fulfill a request is available. - InsufficientAllowance, - /// Not enough balance to fulfill a request is available. - InsufficientBalance, - /// The asset ID is already taken. - InUse, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// Unspecified pallet error, providing pallet index and error index. - ModuleError { pallet: u8, error: u16 }, - /// The account to alter does not exist. - NoAccount, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, -} - -impl From for ContractError { - fn from(error: FungiblesError) -> Self { - match error { - FungiblesError::AssetNotLive => ContractError::AssetNotLive, - FungiblesError::BelowMinimum => ContractError::BelowMinimum, - FungiblesError::DispatchError { index, error } => { - ContractError::DispatchError { index, error } - }, - FungiblesError::InsufficientAllowance => ContractError::InsufficientAllowance, - FungiblesError::InsufficientBalance => ContractError::InsufficientBalance, - FungiblesError::InUse => ContractError::InUse, - FungiblesError::MinBalanceZero => ContractError::MinBalanceZero, - FungiblesError::ModuleError { pallet, error } => { - ContractError::ModuleError { pallet, error } - }, - FungiblesError::NoAccount => ContractError::NoAccount, - FungiblesError::NoPermission => ContractError::NoPermission, - FungiblesError::Unknown => ContractError::Unknown, - } - } -} - -/// The fungibles result type. -pub type Result = core::result::Result; +pub type Result = core::result::Result; #[ink::contract(env = pop_api::Environment)] mod fungibles { @@ -74,7 +25,7 @@ mod fungibles { impl Fungibles { #[ink(constructor, payable)] pub fn new() -> Self { - ink::env::debug_println!("PopApiAssetsExample::new"); + ink::env::debug_println!("PopApiFungiblesExample::new"); Default::default() } @@ -90,12 +41,12 @@ mod fungibles { #[ink(message)] pub fn total_supply(&self, id: AssetId) -> Result { - total_supply(id).map_err(From::from) + api::total_supply(id) } #[ink(message)] pub fn balance_of(&self, id: AssetId, owner: AccountId32) -> Result { - balance_of(id, owner).map_err(From::from) + api::balance_of(id, owner) } #[ink(message)] @@ -105,21 +56,21 @@ mod fungibles { owner: AccountId32, spender: AccountId32, ) -> Result { - allowance(id, owner, spender).map_err(From::from) + api::allowance(id, owner, spender) } #[ink(message)] pub fn transfer(&self, id: AssetId, to: AccountId32, value: Balance) -> Result<()> { ink::env::debug_println!( - "PopApiAssetsExample::transfer: id: {:?}, to: {:?} value: {:?}", + "PopApiFungiblesExample::transfer: id: {:?}, to: {:?} value: {:?}", id, to, value, ); - let result = transfer(id, to, value); + let result = api::transfer(id, to, value); ink::env::debug_println!("Result: {:?}", result); - result.map_err(From::from) + result } #[ink(message)] @@ -129,20 +80,21 @@ mod fungibles { from: Option, to: Option, value: Balance, - // Size needs to be known at compile time or ink's `Vec` + // In the standard a `[u8]`, but the size needs to be known at compile time ink's `Vec` + // has to be used. data: Vec, ) -> Result<()> { ink::env::debug_println!( - "PopApiAssetsExample::transfer_from: id: {:?}, from: {:?}, to: {:?} value: {:?}", + "PopApiFungiblesExample::transfer_from: id: {:?}, from: {:?}, to: {:?} value: {:?}", id, from, to, value, ); - let result = transfer_from(id, from, to, value, &data); + let result = api::transfer_from(id, from, to, value, &data); ink::env::debug_println!("Result: {:?}", result); - result.map_err(From::from) + result } /// 2. PSP-22 Metadata Interface: @@ -162,14 +114,14 @@ mod fungibles { #[ink(message)] pub fn create(&self, id: AssetId, admin: AccountId32, min_balance: Balance) -> Result<()> { ink::env::debug_println!( - "PopApiAssetsExample::create: id: {:?} admin: {:?} min_balance: {:?}", + "PopApiFungiblesExample::create: id: {:?} admin: {:?} min_balance: {:?}", id, admin, min_balance, ); - let result = create(id, admin, min_balance); + let result = api::create(id, admin, min_balance); ink::env::debug_println!("Result: {:?}", result); - result.map_err(From::from) + result } #[ink(message)] @@ -181,20 +133,20 @@ mod fungibles { decimals: u8, ) -> Result<()> { ink::env::debug_println!( - "PopApiAssetsExample::set_metadata: id: {:?} name: {:?} symbol: {:?}, decimals: {:?}", + "PopApiFungiblesExample::set_metadata: id: {:?} name: {:?} symbol: {:?}, decimals: {:?}", id, name, symbol, decimals, ); - let result = set_metadata(id, name, symbol, decimals); + let result = api::set_metadata(id, name, symbol, decimals); ink::env::debug_println!("Result: {:?}", result); - result.map_err(From::from) + result } #[ink(message)] pub fn asset_exists(&self, id: AssetId) -> Result { - asset_exists(id).map_err(From::from) + api::asset_exists(id) } } @@ -204,7 +156,7 @@ mod fungibles { #[ink::test] fn default_works() { - PopApiAssetsExample::new(); + PopApiFungiblesExample::new(); } } } diff --git a/pop-api/src/error.rs b/pop-api/src/error.rs new file mode 100644 index 00000000..92da4045 --- /dev/null +++ b/pop-api/src/error.rs @@ -0,0 +1,255 @@ +use crate::assets::use_cases::fungibles::{convert_to_fungibles_error, FungiblesError}; +use ink::env::chain_extension::FromStatusCode; +use scale::{Decode, Encode}; +use PopApiError::*; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[repr(u8)] +pub enum PopApiError { + /// Some unknown error occurred. Go to the Pop API docs section `Pop API error`. + Other { + // Index within the `DispatchError` + dispatch_error_index: u8, + // Index within the `DispatchError` variant. + error_index: u8, + // Index for further nesting, e.g. pallet error. + error: u8, + } = 0, + /// Failed to lookup some data. + CannotLookup = 1, + /// A bad origin. + BadOrigin = 2, + /// A custom error in a module. + Module { + index: u8, + error: u8, + } = 3, + /// At least one consumer is remaining so the account cannot be destroyed. + ConsumerRemaining = 4, + /// There are no providers so the account cannot be created. + NoProviders = 5, + /// There are too many consumers so the account cannot be created. + TooManyConsumers = 6, + /// An error to do with tokens. + Token(TokenError) = 7, + /// An arithmetic error. + Arithmetic(ArithmeticError) = 8, + /// The number of transactional layers has been reached, or we are not in a transactional + /// layer. + Transactional(TransactionalError) = 9, + /// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate. + Exhausted = 10, + /// The state is corrupt; this is generally not going to fix itself. + Corruption = 11, + /// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later. + Unavailable = 12, + /// Root origin is not allowed. + RootNotAllowed = 13, + // TODO: make generic and add docs. + UseCaseError(FungiblesError) = 254, + DecodingFailed = 255, +} + +impl FromStatusCode for PopApiError { + fn from_status_code(status_code: u32) -> core::result::Result<(), Self> { + match status_code { + 0 => Ok(()), + _ => Err(convert_to_pop_api_error(status_code)), + } + } +} + +// `pub` because it is used in `runtime/devnet/src/extensions/tests/mod.rs`'s test: +// `dispatch_error_to_status_code_to_pop_api_error_works` +// +// This function converts a given `status_code` (u32) into a `PopApiError`. First it encodes the +// status code into a 4-byte array and checks for unknown nested errors. If decoding into +// `PopApiError` fails (e.g. a breaking change in the `DispatchError`), it handles the error by +// converting it to the `Other` variant by shifting each byte one position forward (the last byte is +// not used for anything)and setting the first byte to 0. If decoding succeeds, it checks if the +// error is of the `Module` variant and performs any necessary conversion based on the use case. +pub fn convert_to_pop_api_error(status_code: u32) -> PopApiError { + let mut encoded: [u8; 4] = + status_code.encode().try_into().expect("qid u32 always encodes to 4 bytes"); + encoded = check_for_unknown_nesting(encoded); + let error = match PopApiError::decode(&mut &encoded[..]) { + Err(_) => { + encoded[3] = encoded[2]; + encoded[2] = encoded[1]; + encoded[1] = encoded[0]; + encoded[0] = 0; + PopApiError::decode(&mut &encoded[..]).unwrap().into() + }, + Ok(error) => { + if let crate::PopApiError::Module { index, error } = error { + // TODO: make generic. + convert_to_fungibles_error(index, error) + } else { + error + } + }, + }; + ink::env::debug_println!("PopApiError: {:?}", error); + error +} + +// If a unknown nested variant of the `DispatchError` is detected meaning any of the subsequent +// bytes are non-zero (e.g. breaking change in the DispatchError), the error needs to be converted +// into `PopApiError::Other`'s encoded value. This conversion is done by shifting the bytes one +// position forward (the last byte is discarded as it is not being used) and replacing the first +// byte with the `Other` encoded value (0u8). This ensures that the error is correctly categorized +// as an `Other` variant. +fn check_for_unknown_nesting(encoded_error: [u8; 4]) -> [u8; 4] { + if non_nested_pop_api_errors().contains(&encoded_error[0]) + && encoded_error[1..].iter().any(|x| *x != 0u8) + { + [0u8, encoded_error[0], encoded_error[1], encoded_error[2]] + } else if singular_nested_pop_api_errors().contains(&encoded_error[0]) + && encoded_error[2..].iter().any(|x| *x != 0u8) + { + [0u8, encoded_error[0], encoded_error[1], encoded_error[2]] + } else { + encoded_error + } +} + +impl From for PopApiError { + fn from(_: scale::Error) -> Self { + DecodingFailed + } +} +#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum TokenError { + /// Funds are unavailable. + FundsUnavailable, + /// Some part of the balance gives the only provider reference to the account and thus cannot + /// be (re)moved. + OnlyProvider, + /// Account cannot exist with the funds that would be given. + BelowMinimum, + /// Account cannot be created. + CannotCreate, + /// The asset in question is unknown. + UnknownAsset, + /// Funds exist but are frozen. + Frozen, + /// Operation is not supported by the asset. + Unsupported, + /// Account cannot be created for a held balance. + CannotCreateHold, + /// Withdrawal would cause unwanted loss of account. + NotExpendable, + /// Account cannot receive the assets. + Blocked, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum ArithmeticError { + /// Underflow. + Underflow, + /// Overflow. + Overflow, + /// Division by zero. + DivisionByZero, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum TransactionalError { + /// Too many transactional layers have been spawned. + LimitReached, + /// A transactional layer was expected, but does not exist. + NoLayer, +} + +fn singular_nested_pop_api_errors() -> [u8; 3] { + const TOKEN_ERROR: u8 = 7; + const ARITHMETIC_ERROR: u8 = 8; + const TRANSACTION_ERROR: u8 = 9; + [TOKEN_ERROR, ARITHMETIC_ERROR, TRANSACTION_ERROR] +} + +fn non_nested_pop_api_errors() -> [u8; 9] { + const CANNOT_LOOKUP: u8 = 1; + const BAD_ORIGIN: u8 = 2; + const CONSUMER_REMAINING: u8 = 4; + const NO_PROVIDERS: u8 = 5; + const TOO_MANY_CONSUMERS: u8 = 6; + const EXHAUSTED: u8 = 10; + const CORRUPTION: u8 = 11; + const UNAVAILABLE: u8 = 12; + const ROOT_NOT_ALLOWED: u8 = 13; + [ + CANNOT_LOOKUP, + BAD_ORIGIN, + CONSUMER_REMAINING, + NO_PROVIDERS, + TOO_MANY_CONSUMERS, + EXHAUSTED, + CORRUPTION, + UNAVAILABLE, + ROOT_NOT_ALLOWED, + ] +} + +#[test] +fn u32_always_encodes_to_4_bytes() { + assert_eq!(0u32.encode().len(), 4); + assert_eq!(u32::MAX.encode().len(), 4); +} + +// If decoding failed the encoded value is converted to the `PopApiError::Other`. This handles +// unknown errors coming from the runtime. This could happen if a contract is not upgraded to the +// latest Pop API version. +#[test] +fn test_non_existing_pop_api_errors() { + let encoded_error = [7u8, 100u8, 0u8, 0u8]; + let status_code = u32::decode(&mut &encoded_error[..]).unwrap(); + let pop_api_error = ::from_status_code(status_code); + assert_eq!(Err(Other { dispatch_error_index: 7, error_index: 100, error: 0 }), pop_api_error); +} + +// If the encoded value indicates a nested PopApiError which is not handled by the Pop API version, +// the encoded value is converted into `PopApiError::Other`. +#[test] +fn check_for_unknown_nested_pop_api_errors_works() { + for &error_code in &non_nested_pop_api_errors() { + let encoded_error = [error_code, 1, 2, 3]; + let result = check_for_unknown_nesting(encoded_error); + let decoded = PopApiError::decode(&mut &result[..]).unwrap(); + + assert_eq!( + decoded, + Other { dispatch_error_index: error_code, error_index: 1, error: 2 }, + "Failed for error code: {}", + error_code + ); + } + for &error_code in &singular_nested_pop_api_errors() { + let encoded_error = [error_code, 1, 2, 3]; + let result = check_for_unknown_nesting(encoded_error); + let decoded = PopApiError::decode(&mut &result[..]).unwrap(); + + assert_eq!( + decoded, + Other { dispatch_error_index: error_code, error_index: 1, error: 2 }, + "Failed for error code: {}", + error_code + ); + } +} + +// This test ensures that a non-zero value for unused bytes does not interfere with the correct +// decoding of the error. It verifies that even with an additional byte, the errors are correctly +// decoded and represented in its correct variant. +#[test] +fn extra_byte_does_not_mess_up_decoding() { + // Module error + let encoded_error = [3u8, 4u8, 5u8, 6u8]; + let status_code = u32::decode(&mut &encoded_error[..]).unwrap(); + let pop_api_error = ::from_status_code(status_code); + assert_eq!(Err(Module { index: 4, error: 5 }), pop_api_error); +} diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index be448890..a785aebe 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,19 +1,19 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -use core::convert::TryInto; +use crate::error::PopApiError; use ink::{prelude::vec::Vec, ChainExtensionInstance}; use primitives::{cross_chain::*, storage_keys::*, AccountId as AccountId32}; +use scale::Encode; pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; use v0::RuntimeCall; -pub use v0::{ - assets, balances, contracts, cross_chain, dispatch_error, nfts, relay_chain_block_number, state, -}; +pub use v0::{assets, balances, cross_chain, nfts, relay_chain_block_number, state}; +pub mod error; pub mod primitives; pub mod v0; -// type AccountId = ::AccountId; type AccountId = AccountId32; +// TODO: do the same as above and check expanded code. type Balance = ::Balance; type BlockNumber = ::BlockNumber; type StringLimit = u32; @@ -21,54 +21,6 @@ type MaxTips = u32; pub type Result = core::result::Result; -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum PopApiError { - Assets(assets::fungibles::AssetsError), - Balances(balances::BalancesError), - Contracts(contracts::Error), - DecodingFailed, - Nfts(nfts::Error), - SystemCallFiltered, - TokenError(dispatch_error::TokenError), - UnknownModuleStatusCode(u32), - UnknownDispatchStatusCode(u32), - Xcm(cross_chain::Error), -} - -impl ink::env::chain_extension::FromStatusCode for PopApiError { - fn from_status_code(status_code: u32) -> core::result::Result<(), Self> { - use crate::PopApiError::{ - Assets, Balances, Contracts, Nfts, TokenError, UnknownDispatchStatusCode, - UnknownModuleStatusCode, - }; - - match status_code { - 0 => Ok(()), - 3_000_000..=3_999_999 => { - let status_code = status_code - 3_000_000; - match status_code { - // CallFiltered originates from `frame_system` with pallet-index 0. The CallFiltered error is at index 5 - 5 => Err(PopApiError::SystemCallFiltered), - 10_000..=10_999 => Err(Balances((status_code - 10_000).try_into()?)), - 40_000..=40_999 => Err(Contracts((status_code - 40_000).try_into()?)), - 50_000..=50_999 => Err(Nfts((status_code - 50_000).try_into()?)), - 52_000..=52_999 => Err(Assets((status_code - 52_000).try_into()?)), - _ => Err(UnknownModuleStatusCode(status_code)), - } - }, - 7_000_000..=7_999_999 => Err(TokenError((status_code - 7_000_000).try_into()?)), - _ => Err(UnknownDispatchStatusCode(status_code)), - } - } -} - -impl From for PopApiError { - fn from(_: scale::Error) -> Self { - panic!("encountered unexpected invalid SCALE encoding") - } -} - #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum Environment {} diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs deleted file mode 100644 index df9033c7..00000000 --- a/pop-api/src/v0/assets/fungibles.rs +++ /dev/null @@ -1,610 +0,0 @@ -use crate::{ - balances::BalancesError, AccountId, Balance, PopApiError::UnknownModuleStatusCode, RuntimeCall, - *, -}; -use ink::prelude::vec::Vec; -use primitives::AssetId; -use scale::{Compact, Encode}; - -type Result = core::result::Result; - -/// Local Fungibles: -/// 1. PSP-22 Interface -/// 2. PSP-22 Metadata Interface -/// 3. Asset Management - -/// 1. PSP-22 Interface: -/// - total_supply -/// - balance_of -/// - allowance -/// - transfer -/// - transfer_from -/// - approve -/// - increase_allowance -/// - decrease_allowance - -/// Returns the total token supply for a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// The total supply of the token, or an error if the operation fails. -pub fn total_supply(id: AssetId) -> Result { - Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id)))?) -} - -/// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if -/// the account is non-existent. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `owner` - The account whose balance is being queried. -/// -/// # Returns -/// The balance of the specified account, or an error if the operation fails. -pub fn balance_of(id: AssetId, owner: AccountId) -> Result { - Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner)))?) -} - -/// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given -/// asset ID. Returns `0` if no allowance has been set. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `owner` - The account that owns the tokens. -/// * `spender` - The account that is allowed to spend the tokens. -/// -/// # Returns -/// The remaining allowance, or an error if the operation fails. -pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { - Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender)))?) -} - -/// Transfers `value` amount of tokens from the caller's account to account `to`, with additional -/// `data` in unspecified format. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `to` - The recipient account. -/// * `value` - The number of tokens to transfer. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the transfer fails. -pub fn transfer( - id: AssetId, - to: impl Into>, - value: Balance, -) -> Result<()> { - // TODO: transfer or transfer_keep_alive - // Ok(dispatch(RuntimeCall::Assets(AssetsCall::Transfer { - // id: id.into(), - // target: target.into(), - // amount: Compact(amount), - // }))?) - Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { - id: id.into(), - target: to.into(), - amount: Compact(value), - }))?) -} - -/// Transfers `value` tokens on behalf of `from` to account `to` with additional `data` -/// in unspecified format. If `from` is equal to `None`, tokens will be minted to account `to`. If -/// `to` is equal to `None`, tokens will be burned from account `from`. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `from` - The account from which the tokens are transferred. -/// * `to` - The recipient account. -/// * `value` - The number of tokens to transfer. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the transfer fails. -pub fn transfer_from( - id: AssetId, - from: Option>>, - to: Option>>, - value: Balance, - _data: &[u8], -) -> Result<()> { - match (from, to) { - (None, Some(to)) => mint(id, to, value), - // (Some(from), None) => burn(id, from, value), - (Some(from), Some(to)) => { - Ok(dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { - id: id.into(), - owner: from.into(), - destination: to.into(), - amount: Compact(value), - }))?) - }, - _ => Ok(()), - } -} - -/// Approves an account to spend a specified number of tokens on behalf of the caller. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `spender` - The account that is allowed to spend the tokens. -/// * `value` - The number of tokens to approve. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the approval fails. -// #[allow(unused_variables)] -// fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { -// todo!() -// // TODO: read allowance and increase or decrease. -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { -// // id: id.into(), -// // delegate: spender.into(), -// // amount: Compact(value), -// // }))?) -// } - -/// Increases the allowance of a spender. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `spender` - The account that is allowed to spend the tokens. -/// * `value` - The number of tokens to increase the allowance by. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn increase_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { -// id: id.into(), -// delegate: spender.into(), -// amount: Compact(value), -// }))?) -// } - -/// Decreases the allowance of a spender. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `spender` - The account that is allowed to spend the tokens. -/// * `value` - The number of tokens to decrease the allowance by. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// #[allow(unused_variables)] -// fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { -// todo!() -// // TODO: cancel_approval + approve_transfer -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { -// // id: id.into(), -// // delegate: delegate.into(), -// // }))?) -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { -// // id: id.into(), -// // delegate: spender.into(), -// // amount: Compact(value), -// // }))?) -// } - -/// 2. PSP-22 Metadata Interface: -/// - token_name -/// - token_symbol -/// - token_decimals - -/// Returns the token name for a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// The name of the token as a byte vector, or an error if the operation fails. -// #[allow(unused_variables)] -// pub fn token_name(id: AssetId) -> Result>> { -// todo!() -// // Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id)))?) -// } - -/// Returns the token symbol for a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// The symbol of the token as a byte vector, or an error if the operation fails. -// #[allow(unused_variables)] -// fn token_symbol(id: AssetId) -> Result>> { -// todo!() -// } - -/// Returns the token decimals for a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// The number of decimals of the token as a byte vector, or an error if the operation fails. -// #[allow(unused_variables)] -// fn token_decimals(id: AssetId) -> Result>> { -// todo!() -// } - -/// 3. Asset Management: -/// - create -/// - start_destroy -/// - destroy_accounts -/// - destroy_approvals -/// - finish_destroy -/// - set_metadata -/// - clear_metadata - -/// Create a new token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `admin` - The account that will administer the asset. -/// * `min_balance` - The minimum balance required for accounts holding this asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the creation fails. -pub fn create( - id: AssetId, - admin: impl Into>, - min_balance: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Assets(AssetsCall::Create { - id: id.into(), - admin: admin.into(), - min_balance, - }))?) -} - -/// Start the process of destroying a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn start_destroy(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { -// id: id.into(), -// }))?) -// } - -/// Destroy all accounts associated with a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn destroy_accounts(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { -// id: id.into(), -// }))?) -// } - -/// Destroy all approvals associated with a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn destroy_approvals(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { -// id: id.into(), -// }))?) -// } - -/// Complete the process of destroying a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn finish_destroy(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { -// id: id.into(), -// }))?) -// } - -/// Set the metadata for a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { - Ok(dispatch(RuntimeCall::Assets(AssetsCall::SetMetadata { - id: id.into(), - name, - symbol, - decimals, - }))?) -} - -/// Clear the metadata for a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn clear_metadata(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { -// id: id.into(), -// }))?) -// } - -pub fn asset_exists(id: AssetId) -> Result { - Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id)))?) -} - -/// Mint assets of a particular class. -fn mint( - id: AssetId, - beneficiary: impl Into>, - amount: Balance, -) -> Result<()> { - Ok(dispatch(RuntimeCall::Assets(AssetsCall::Mint { - id: id.into(), - beneficiary: beneficiary.into(), - amount: Compact(amount), - }))?) -} - -// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount -// (`Balance`) are expected to be compact encoded. The pop api handles that for the developer. -// https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development -// -// Asset id that is compact encoded. -type AssetIdParameter = Compact; -// Balance amount that is compact encoded. -type BalanceParameter = Compact; - -#[allow(warnings, unused)] -#[derive(Encode)] -pub(crate) enum AssetsCall { - #[codec(index = 0)] - Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, - #[codec(index = 2)] - StartDestroy { id: AssetIdParameter }, - #[codec(index = 3)] - DestroyAccounts { id: AssetIdParameter }, - #[codec(index = 4)] - DestroyApprovals { id: AssetIdParameter }, - #[codec(index = 5)] - FinishDestroy { id: AssetIdParameter }, - #[codec(index = 6)] - Mint { - id: AssetIdParameter, - beneficiary: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 7)] - Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, - // TODO: ED or not - // #[codec(index = 8)] - // Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, - #[codec(index = 9)] - TransferKeepAlive { - id: AssetIdParameter, - target: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 17)] - SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, - #[codec(index = 18)] - ClearMetadata { id: AssetIdParameter }, - #[codec(index = 22)] - ApproveTransfer { - id: AssetIdParameter, - delegate: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 23)] - CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, - #[codec(index = 25)] - TransferApproved { - id: AssetIdParameter, - owner: MultiAddress, - destination: MultiAddress, - amount: BalanceParameter, - }, -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub(crate) enum AssetsError { - /// Account balance must be greater than or equal to the transfer amount. - BalanceLow, - /// The account to alter does not exist. - NoAccount, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, - /// The origin account is frozen. - Frozen, - /// The asset ID is already taken. - InUse, - /// Invalid witness data given. - BadWitness, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// Unable to increment the consumer reference counters on the account. Either no provider - /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one - /// fewer then the maximum number of consumers has been reached. - UnavailableConsumer, - /// Invalid metadata given. - BadMetadata, - /// No approval exists that would allow the transfer. - Unapproved, - /// The source account would not survive the transfer and it needs to stay alive. - WouldDie, - /// The asset-account already exists. - AlreadyExists, - /// The asset-account doesn't have an associated deposit. - NoDeposit, - /// The operation would result in funds being burned. - WouldBurn, - /// The asset is a live asset and is actively being used. Usually emit for operations such - /// as `start_destroy` which require the asset to be in a destroying state. - LiveAsset, - /// The asset is not live, and likely being destroyed. - AssetNotLive, - /// The asset status is not the expected status. - IncorrectStatus, - /// The asset should be frozen before the given operation. - NotFrozen, - /// Callback action resulted in error - CallbackFailed, -} - -impl From for AssetsError { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Assets(e) => e, - _ => panic!("Expected AssetsError"), - } - } -} - -impl TryFrom for AssetsError { - type Error = PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use AssetsError::*; - match status_code { - 0 => Ok(BalanceLow), - 1 => Ok(NoAccount), - 2 => Ok(NoPermission), - 3 => Ok(Unknown), - 4 => Ok(Frozen), - 5 => Ok(InUse), - 6 => Ok(BadWitness), - 7 => Ok(MinBalanceZero), - 8 => Ok(UnavailableConsumer), - 9 => Ok(BadMetadata), - 10 => Ok(Unapproved), - 11 => Ok(WouldDie), - 12 => Ok(AlreadyExists), - 13 => Ok(NoDeposit), - 14 => Ok(WouldBurn), - 15 => Ok(LiveAsset), - 16 => Ok(AssetNotLive), - 17 => Ok(IncorrectStatus), - 18 => Ok(NotFrozen), - _ => Err(UnknownModuleStatusCode(status_code)), - } - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum FungiblesError { - /// The asset is not live; either frozen or being destroyed. - AssetNotLive, - /// The amount to mint is less than the existential deposit. - BelowMinimum, - /// Unspecified dispatch error, providing the index and its error index (if none `0`). - DispatchError { index: u8, error: u8 }, - /// Not enough allowance to fulfill a request is available. - InsufficientAllowance, - /// Not enough balance to fulfill a request is available. - InsufficientBalance, - /// The asset ID is already taken. - InUse, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// Unspecified pallet error, providing pallet index and error index. - ModuleError { pallet: u8, error: u16 }, - /// The account to alter does not exist. - NoAccount, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, -} - -impl From for FungiblesError { - fn from(error: BalancesError) -> Self { - match error { - // TODO: this insufficient balance is different than the assets variant. This one is - // for a deposit of creating an asset, the latter is for transfer tokens. - BalancesError::InsufficientBalance => FungiblesError::InsufficientBalance, - _ => FungiblesError::ModuleError { pallet: 40, error: error as u16 }, - } - } -} - -impl From for FungiblesError { - fn from(error: dispatch_error::TokenError) -> Self { - match error { - dispatch_error::TokenError::BelowMinimum => FungiblesError::BelowMinimum, - // ED is not respected. - dispatch_error::TokenError::OnlyProvider => FungiblesError::InsufficientBalance, - dispatch_error::TokenError::UnknownAsset => FungiblesError::Unknown, - _ => FungiblesError::DispatchError { index: 7, error: error as u8 }, - } - } -} - -impl From for FungiblesError { - fn from(error: AssetsError) -> Self { - match error { - AssetsError::AssetNotLive => FungiblesError::AssetNotLive, - AssetsError::BalanceLow => FungiblesError::InsufficientBalance, - AssetsError::Unapproved => FungiblesError::InsufficientAllowance, - AssetsError::InUse => FungiblesError::InUse, - AssetsError::MinBalanceZero => FungiblesError::MinBalanceZero, - AssetsError::NoPermission => FungiblesError::NoPermission, - AssetsError::NoAccount => FungiblesError::NoAccount, - AssetsError::Unknown => FungiblesError::Unknown, - _ => FungiblesError::ModuleError { pallet: 52, error: error as u16 }, - } - } -} - -impl From for FungiblesError { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Assets(e) => e.into(), - PopApiError::Balances(e) => e.into(), - PopApiError::TokenError(e) => e.into(), - PopApiError::UnknownModuleStatusCode(e) => { - let pallet = (e / 1_000) as u8; - let error = (e % 1_000) as u16; - FungiblesError::ModuleError { pallet, error } - }, - PopApiError::UnknownDispatchStatusCode(e) => { - let index = (e / 1_000_000) as u8; - let error = (3 % 1_000_000) as u8; - FungiblesError::DispatchError { index, error } - }, - _ => todo!(), - } - } -} - -// macro_rules! impl_error_conversion { -// ($pallet_index:, $pallet_error:ty, $interface_error:ty, $($variant:ident),*) => { -// impl From<$pallet_error> for $interface_error { -// fn from(error: $pallet_error) -> Self { -// match error { -// $( -// <$pallet_error>::$variant => <$interface_error>::$variant, -// )* -// _ => <$interface_error>::ModuleError { pallet: 0, error: [255, 0, 0, 0] }, // Default case -// } -// } -// } -// -// impl FromPalletError<$pallet_error> for $interface_error { -// fn from_pallet_error(error: $pallet_error) -> Self { -// Self::from(error) -// } -// } -// }; -// } diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index d6b0261c..736ccc0e 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1 +1,2 @@ -pub mod fungibles; \ No newline at end of file +pub(crate) mod pallets; +pub mod use_cases; diff --git a/pop-api/src/v0/assets/pallets/assets.rs b/pop-api/src/v0/assets/pallets/assets.rs new file mode 100644 index 00000000..7a575e08 --- /dev/null +++ b/pop-api/src/v0/assets/pallets/assets.rs @@ -0,0 +1,491 @@ +// TODO: what to put in this file? +#![allow(dead_code)] + +use crate::{Balance, RuntimeCall, *}; +use ink::prelude::vec::Vec; +use primitives::{AssetId, MultiAddress}; +use scale::{Compact, Encode}; + +type Result = core::result::Result; + +/// [Pallet Assets](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/lib.rs): +/// 1. Dispatchables +/// 2. Read state functions +/// +/// 1. Dispatchables within pallet assets (TrustBackedAssets instance) that can be used via the pop api on Pop Network: +/// - create +/// - start_destroy +/// - destroy_accounts +/// - destroy_approvals +/// - finish_destroy +/// - mint +/// - burn +/// - transfer +/// - transfer_keep_alive +/// - force_transfer +/// - freeze +/// - thaw +/// - freeze_asset +/// - thaw_asset +/// - transfer_ownership +/// - set_team +/// - set_metadata +/// - clear_metadata +/// - approve_transfer +/// - cancel_approval +/// - force_cancel_approval +/// - transfer_approved +/// - touch +/// - refund +/// - set_min_balance +/// - touch_other +/// - refund_other +/// - block + +/// Issue a new class of fungible assets from a public origin. +pub(crate) fn create( + id: AssetId, + admin: impl Into>, + min_balance: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Create { + id: id.into(), + admin: admin.into(), + min_balance, + })) +} + +/// Start the process of destroying a fungible asset class. +pub(crate) fn start_destroy(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { id: id.into() })) +} + +/// Destroy all accounts associated with a given asset. +pub(crate) fn destroy_accounts(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { id: id.into() })) +} + +/// Destroy all approvals associated with a given asset up to the max (see runtime configuration Assets `RemoveItemsLimit`). +pub(crate) fn destroy_approvals(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { id: id.into() })) +} + +/// Complete destroying asset and unreserve currency. +pub(crate) fn finish_destroy(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { id: id.into() })) +} + +/// Mint assets of a particular class. +pub(crate) fn mint( + id: AssetId, + beneficiary: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Mint { + id: id.into(), + beneficiary: beneficiary.into(), + amount: Compact(amount), + })) +} + +/// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`. +pub(crate) fn burn( + id: AssetId, + who: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Burn { + id: id.into(), + who: who.into(), + amount: Compact(amount), + })) +} + +/// Move some assets from the sender account to another. +pub(crate) fn transfer( + id: AssetId, + target: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { + id: id.into(), + target: target.into(), + amount: Compact(amount), + })) +} + +/// Move some assets from the sender account to another, keeping the sender account alive. +pub(crate) fn transfer_keep_alive( + id: AssetId, + target: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { + id: id.into(), + target: target.into(), + amount: Compact(amount), + })) +} + +/// Move some assets from one account to another. Sender should be the Admin of the asset `id`. +pub(crate) fn force_transfer( + id: AssetId, + source: impl Into>, + dest: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ForceTransfer { + id: id.into(), + source: source.into(), + dest: dest.into(), + amount: Compact(amount), + })) +} + +/// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` +/// must already exist as an entry in `Account`s of the asset. If you want to freeze an +/// account that does not have an entry, use `touch_other` first. +pub(crate) fn freeze(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Freeze { id: id.into(), who: who.into() })) +} + +/// Allow unprivileged transfers to and from an account again. +pub(crate) fn thaw(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Thaw { id: id.into(), who: who.into() })) +} + +/// Disallow further unprivileged transfers for the asset class. +pub(crate) fn freeze_asset(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::FreezeAsset { id: id.into() })) +} + +/// Allow unprivileged transfers for the asset again. +pub(crate) fn thaw_asset(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ThawAsset { id: id.into() })) +} + +/// Change the Owner of an asset. +pub(crate) fn transfer_ownership( + id: AssetId, + owner: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferOwnership { + id: id.into(), + owner: owner.into(), + })) +} + +/// Change the Issuer, Admin and Freezer of an asset. +pub(crate) fn set_team( + id: AssetId, + issuer: impl Into>, + admin: impl Into>, + freezer: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::SetTeam { + id: id.into(), + issuer: issuer.into(), + admin: admin.into(), + freezer: freezer.into(), + })) +} + +/// Set the metadata for an asset. +pub(crate) fn set_metadata( + id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::SetMetadata { id: id.into(), name, symbol, decimals })) +} + +/// Clear the metadata for an asset. +pub(crate) fn clear_metadata(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { id: id.into() })) +} + +/// Approve an amount of asset for transfer by a delegated third-party account. +pub(crate) fn approve_transfer( + id: AssetId, + delegate: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { + id: id.into(), + delegate: delegate.into(), + amount: Compact(amount), + })) +} + +/// Cancel all of some asset approved for delegated transfer by a third-party account. +pub(crate) fn cancel_approval( + id: AssetId, + delegate: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { + id: id.into(), + delegate: delegate.into(), + })) +} + +/// Cancel all of some asset approved for delegated transfer by a third-party account. +pub(crate) fn force_cancel_approval( + id: AssetId, + owner: impl Into>, + delegate: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ForceCancelApproval { + id: id.into(), + owner: owner.into(), + delegate: delegate.into(), + })) +} + +/// Transfer some asset balance from a previously delegated account to some third-party +/// account. +pub(crate) fn transfer_approved( + id: AssetId, + owner: impl Into>, + destination: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { + id: id.into(), + owner: owner.into(), + destination: destination.into(), + amount: Compact(amount), + })) +} + +/// Create an asset account for non-provider assets. +pub(crate) fn touch(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Touch { id: id.into() })) +} + +/// Return the deposit (if any) of an asset account or a consumer reference (if any) of an +/// account. +pub(crate) fn refund(id: AssetId, allow_burn: bool) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Refund { id: id.into(), allow_burn })) +} + +/// Sets the minimum balance of an asset. +pub(crate) fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::SetMinBalance { + id: id.into(), + min_balance: Compact(min_balance), + })) +} + +/// Create an asset account for `who`. +pub(crate) fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TouchOther { id: id.into(), who: who.into() })) +} + +/// Return the deposit (if any) of a target asset account. Useful if you are the depositor. +pub(crate) fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::RefundOther { id: id.into(), who: who.into() })) +} + +/// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. +pub(crate) fn block(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Block { id: id.into(), who: who.into() })) +} + +/// 2. Read state functions +/// - total_supply +/// - + +pub(crate) fn total_supply(id: AssetId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))).into() +} + +pub(crate) fn balance_of(id: AssetId, owner: AccountId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))).into() +} + +pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))).into() +} +pub(crate) fn asset_exists(id: AssetId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))).into() +} + +// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected +// to be compact encoded. The pop api handles that for the developer. +// +// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development +// +// Asset id that is compact encoded. +type AssetIdParameter = Compact; +// Balance amount that is compact encoded. +type BalanceParameter = Compact; + +#[derive(Encode)] +pub(crate) enum AssetsCall { + #[codec(index = 0)] + Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, + #[codec(index = 2)] + StartDestroy { id: AssetIdParameter }, + #[codec(index = 3)] + DestroyAccounts { id: AssetIdParameter }, + #[codec(index = 4)] + DestroyApprovals { id: AssetIdParameter }, + #[codec(index = 5)] + FinishDestroy { id: AssetIdParameter }, + #[codec(index = 6)] + Mint { + id: AssetIdParameter, + beneficiary: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 7)] + Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, + #[codec(index = 8)] + Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, + #[codec(index = 9)] + TransferKeepAlive { + id: AssetIdParameter, + target: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 10)] + ForceTransfer { + id: AssetIdParameter, + source: MultiAddress, + dest: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 11)] + Freeze { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 12)] + Thaw { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 13)] + FreezeAsset { id: AssetIdParameter }, + #[codec(index = 14)] + ThawAsset { id: AssetIdParameter }, + #[codec(index = 15)] + TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, + #[codec(index = 16)] + SetTeam { + id: AssetIdParameter, + issuer: MultiAddress, + admin: MultiAddress, + freezer: MultiAddress, + }, + #[codec(index = 17)] + SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, + #[codec(index = 18)] + ClearMetadata { id: AssetIdParameter }, + #[codec(index = 22)] + ApproveTransfer { + id: AssetIdParameter, + delegate: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 23)] + CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, + #[codec(index = 24)] + ForceCancelApproval { + id: AssetIdParameter, + owner: MultiAddress, + delegate: MultiAddress, + }, + #[codec(index = 25)] + TransferApproved { + id: AssetIdParameter, + owner: MultiAddress, + destination: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 26)] + Touch { id: AssetIdParameter }, + #[codec(index = 27)] + Refund { id: AssetIdParameter, allow_burn: bool }, + #[codec(index = 28)] + SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, + #[codec(index = 29)] + TouchOther { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 30)] + RefundOther { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 31)] + Block { id: AssetIdParameter, who: MultiAddress }, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum AssetsError { + /// Account balance must be greater than or equal to the transfer amount. + BalanceLow, + /// The account to alter does not exist. + NoAccount, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + /// The origin account is frozen. + Frozen, + /// The asset ID is already taken. + InUse, + /// Invalid witness data given. + BadWitness, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// Unable to increment the consumer reference counters on the account. Either no provider + /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one + /// fewer then the maximum number of consumers has been reached. + UnavailableConsumer, + /// Invalid metadata given. + BadMetadata, + /// No approval exists that would allow the transfer. + Unapproved, + /// The source account would not survive the transfer and it needs to stay alive. + WouldDie, + /// The asset-account already exists. + AlreadyExists, + /// The asset-account doesn't have an associated deposit. + NoDeposit, + /// The operation would result in funds being burned. + WouldBurn, + /// The asset is a live asset and is actively being used. Usually emit for operations such + /// as `start_destroy` which require the asset to be in a destroying state. + LiveAsset, + /// The asset is not live, and likely being destroyed. + AssetNotLive, + /// The asset status is not the expected status. + IncorrectStatus, + /// The asset should be frozen before the given operation. + NotFrozen, + /// Callback action resulted in error. + CallbackFailed, +} + +impl TryFrom for AssetsError { + type Error = PopApiError; + + fn try_from(status_code: u32) -> core::result::Result { + use AssetsError::*; + match status_code { + 0 => Ok(BalanceLow), + 1 => Ok(NoAccount), + 2 => Ok(NoPermission), + 3 => Ok(Unknown), + 4 => Ok(Frozen), + 5 => Ok(InUse), + 6 => Ok(BadWitness), + 7 => Ok(MinBalanceZero), + 8 => Ok(UnavailableConsumer), + 9 => Ok(BadMetadata), + 10 => Ok(Unapproved), + 11 => Ok(WouldDie), + 12 => Ok(AlreadyExists), + 13 => Ok(NoDeposit), + 14 => Ok(WouldBurn), + 15 => Ok(LiveAsset), + 16 => Ok(AssetNotLive), + 17 => Ok(IncorrectStatus), + 18 => Ok(NotFrozen), + _ => todo!(), + } + } +} diff --git a/pop-api/src/v0/assets/pallets/mod.rs b/pop-api/src/v0/assets/pallets/mod.rs new file mode 100644 index 00000000..0b8a53a0 --- /dev/null +++ b/pop-api/src/v0/assets/pallets/mod.rs @@ -0,0 +1 @@ +pub(crate) mod assets; diff --git a/pop-api/src/v0/assets/use_cases/fungibles.rs b/pop-api/src/v0/assets/use_cases/fungibles.rs new file mode 100644 index 00000000..4af5d97e --- /dev/null +++ b/pop-api/src/v0/assets/use_cases/fungibles.rs @@ -0,0 +1,372 @@ +use crate::{ + assets::pallets, + error::PopApiError::{self, *}, + AccountId, Balance, *, +}; +use ink::prelude::vec::Vec; +use primitives::AssetId; + +type Result = core::result::Result; + +/// Local Fungibles: +/// 1. PSP-22 Interface +/// 2. PSP-22 Metadata Interface +/// 3. Asset Management + +/// 1. PSP-22 Interface: +/// - total_supply +/// - balance_of +/// - allowance +/// - transfer +/// - transfer_from +/// - approve +/// - increase_allowance +/// - decrease_allowance + +/// Returns the total token supply for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The total supply of the token, or an error if the operation fails. +pub fn total_supply(id: AssetId) -> Result { + pallets::assets::total_supply(id) +} + +/// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if +/// the account is non-existent. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `owner` - The account whose balance is being queried. +/// +/// # Returns +/// The balance of the specified account, or an error if the operation fails. +pub fn balance_of(id: AssetId, owner: AccountId) -> Result { + pallets::assets::balance_of(id, owner) +} + +/// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given +/// asset ID. Returns `0` if no allowance has been set. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `owner` - The account that owns the tokens. +/// * `spender` - The account that is allowed to spend the tokens. +/// +/// # Returns +/// The remaining allowance, or an error if the operation fails. +pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { + pallets::assets::allowance(id, owner, spender) +} + +/// Transfers `value` amount of tokens from the caller's account to account `to`, with additional +/// `data` in unspecified format. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `to` - The recipient account. +/// * `value` - The number of tokens to transfer. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the transfer fails. +pub fn transfer( + id: AssetId, + to: impl Into>, + value: Balance, +) -> Result<()> { + pallets::assets::transfer(id, to, value) +} + +/// Transfers `value` tokens on behalf of `from` to account `to` with additional `data` +/// in unspecified format. If `from` is equal to `None`, tokens will be minted to account `to`. If +/// `to` is equal to `None`, tokens will be burned from account `from`. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `from` - The account from which the tokens are transferred. +/// * `to` - The recipient account. +/// * `value` - The number of tokens to transfer. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the transfer fails. +pub fn transfer_from( + id: AssetId, + from: Option>>, + to: Option>>, + value: Balance, + _data: &[u8], +) -> Result<()> { + match (from, to) { + (None, Some(to)) => pallets::assets::mint(id, to, value), + (Some(from), None) => pallets::assets::burn(id, from, value), + (Some(from), Some(to)) => pallets::assets::transfer_approved(id, from, to, value), + _ => Ok(()), + } +} + +/// Approves an account to spend a specified number of tokens on behalf of the caller. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `spender` - The account that is allowed to spend the tokens. +/// * `value` - The number of tokens to approve. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the approval fails. +// #[allow(unused_variables)] +// fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { +// todo!() +// // TODO: read allowance and increase or decrease. +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { +// // id: id.into(), +// // delegate: spender.into(), +// // amount: Compact(value), +// // }))?) +// } + +/// Increases the allowance of a spender. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `spender` - The account that is allowed to spend the tokens. +/// * `value` - The number of tokens to increase the allowance by. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn increase_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { +// id: id.into(), +// delegate: spender.into(), +// amount: Compact(value), +// }))?) +// } + +/// Decreases the allowance of a spender. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `spender` - The account that is allowed to spend the tokens. +/// * `value` - The number of tokens to decrease the allowance by. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// #[allow(unused_variables)] +// fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { +// todo!() +// // TODO: cancel_approval + approve_transfer +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { +// // id: id.into(), +// // delegate: delegate.into(), +// // }))?) +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { +// // id: id.into(), +// // delegate: spender.into(), +// // amount: Compact(value), +// // }))?) +// } + +/// 2. PSP-22 Metadata Interface: +/// - token_name +/// - token_symbol +/// - token_decimals + +/// Returns the token name for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The name of the token as a byte vector, or an error if the operation fails. +// #[allow(unused_variables)] +// pub fn token_name(id: AssetId) -> Result>> { +// todo!() +// // Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id)))?) +// } + +/// Returns the token symbol for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The symbol of the token as a byte vector, or an error if the operation fails. +// #[allow(unused_variables)] +// fn token_symbol(id: AssetId) -> Result>> { +// todo!() +// } + +/// Returns the token decimals for a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// The number of decimals of the token as a byte vector, or an error if the operation fails. +// #[allow(unused_variables)] +// fn token_decimals(id: AssetId) -> Result>> { +// todo!() +// } + +/// 3. Asset Management: +/// - create +/// - start_destroy +/// - destroy_accounts +/// - destroy_approvals +/// - finish_destroy +/// - set_metadata +/// - clear_metadata + +/// Create a new token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// * `admin` - The account that will administer the asset. +/// * `min_balance` - The minimum balance required for accounts holding this asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the creation fails. +pub fn create( + id: AssetId, + admin: impl Into>, + min_balance: Balance, +) -> Result<()> { + pallets::assets::create(id, admin, min_balance) +} + +/// Start the process of destroying a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn start_destroy(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { +// id: id.into(), +// }))?) +// } + +/// Destroy all accounts associated with a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn destroy_accounts(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { +// id: id.into(), +// }))?) +// } + +/// Destroy all approvals associated with a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn destroy_approvals(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { +// id: id.into(), +// }))?) +// } + +/// Complete the process of destroying a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn finish_destroy(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { +// id: id.into(), +// }))?) +// } + +/// Set the metadata for a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { + pallets::assets::set_metadata(id, name, symbol, decimals) +} + +/// Clear the metadata for a token with a given asset ID. +/// +/// # Arguments +/// * `id` - The ID of the asset. +/// +/// # Returns +/// Returns `Ok(())` if successful, or an error if the operation fails. +// fn clear_metadata(id: AssetId) -> Result<()> { +// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { +// id: id.into(), +// }))?) +// } + +pub fn asset_exists(id: AssetId) -> Result { + pallets::assets::asset_exists(id) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum FungiblesError { + /// The asset is not live; either frozen or being destroyed. + AssetNotLive, + /// Not enough allowance to fulfill a request is available. + InsufficientAllowance, + /// Not enough balance to fulfill a request is available. + InsufficientBalance, + /// The asset ID is already taken. + InUse, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// The account to alter does not exist. + NoAccount, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + // // TODO: + // // - Originally `InsufficientBalance` for the deposit but this would result in the same error + // // as the error when there is insufficient balance for transferring an asset. + /// No balance for creation of assets or fees. + NoBalance, +} + +// TODO: make generic. +pub(crate) fn convert_to_fungibles_error(index: u8, error: u8) -> PopApiError { + match index { + 10 => balance_into(error), + 52 => assets_into(error), + _ => Module { index, error }, + } +} + +fn balance_into(error: u8) -> PopApiError { + match error { + 2 => UseCaseError(FungiblesError::NoBalance), + _ => Module { index: 10, error }, + } +} + +fn assets_into(error: u8) -> PopApiError { + match error { + 0 => UseCaseError(FungiblesError::InsufficientBalance), + 1 => UseCaseError(FungiblesError::NoAccount), + 2 => UseCaseError(FungiblesError::NoPermission), + 3 => UseCaseError(FungiblesError::Unknown), + 5 => UseCaseError(FungiblesError::InUse), + 7 => UseCaseError(FungiblesError::MinBalanceZero), + 10 => UseCaseError(FungiblesError::InsufficientAllowance), + 16 => UseCaseError(FungiblesError::AssetNotLive), + _ => Module { index: 52, error }, + } +} diff --git a/pop-api/src/v0/assets/use_cases/mod.rs b/pop-api/src/v0/assets/use_cases/mod.rs new file mode 100644 index 00000000..182590df --- /dev/null +++ b/pop-api/src/v0/assets/use_cases/mod.rs @@ -0,0 +1 @@ +pub mod fungibles; diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index 08db0a75..5d38d851 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -1,9 +1,7 @@ -use crate::{ - dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, PopApiError, - PopApiError::UnknownModuleStatusCode, -}; +// TODO: what to put in this file? +use crate::{dispatch, error::PopApiError, primitives::MultiAddress, v0::RuntimeCall, AccountId}; -type Result = core::result::Result; +type Result = core::result::Result; pub fn transfer_keep_alive( dest: impl Into>, @@ -17,7 +15,7 @@ pub fn transfer_keep_alive( #[derive(scale::Encode)] #[allow(dead_code)] -pub(crate) enum BalancesCall { +pub enum BalancesCall { #[codec(index = 3)] TransferKeepAlive { dest: MultiAddress, @@ -28,7 +26,7 @@ pub(crate) enum BalancesCall { #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub(crate) enum BalancesError { +pub enum BalancesError { /// Vesting balance too high to send value. VestingBalance, /// Account liquidity restrictions prevent withdrawal. @@ -73,15 +71,6 @@ impl TryFrom for BalancesError { 9 => Ok(TooManyFreezes), 10 => Ok(IssuanceDeactivated), 11 => Ok(DeltaZero), - _ => Err(UnknownModuleStatusCode(status_code)), - } - } -} - -impl From for BalancesError { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Balances(e) => e, _ => todo!(), } } diff --git a/pop-api/src/v0/contracts.rs b/pop-api/src/v0/contracts.rs deleted file mode 100644 index 5d4a3692..00000000 --- a/pop-api/src/v0/contracts.rs +++ /dev/null @@ -1,152 +0,0 @@ -use crate::{PopApiError, PopApiError::UnknownModuleStatusCode}; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { - /// Invalid schedule supplied, e.g. with zero weight of a basic operation. - InvalidSchedule, - /// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`. - InvalidCallFlags, - /// The executed contract exhausted its gas limit. - OutOfGas, - /// The output buffer supplied to a contract API call was too small. - OutputBufferTooSmall, - /// Performing the requested transfer failed. Probably because there isn't enough - /// free balance in the sender's account. - TransferFailed, - /// Performing a call was denied because the calling depth reached the limit - /// of what is specified in the schedule. - MaxCallDepthReached, - /// No contract was found at the specified address. - ContractNotFound, - /// The code supplied to `instantiate_with_code` exceeds the limit specified in the - /// current schedule. - CodeTooLarge, - /// No code could be found at the supplied code hash. - CodeNotFound, - /// No code info could be found at the supplied code hash. - CodeInfoNotFound, - /// A buffer outside of sandbox memory was passed to a contract API function. - OutOfBounds, - /// Input passed to a contract API function failed to decode as expected type. - DecodingFailed, - /// Contract trapped during execution. - ContractTrapped, - /// The size defined in `T::MaxValueSize` was exceeded. - ValueTooLarge, - /// Termination of a contract is not allowed while the contract is already - /// on the call stack. Can be triggered by `seal_terminate`. - TerminatedWhileReentrant, - /// `seal_call` forwarded this contracts input. It therefore is no longer available. - InputForwarded, - /// The subject passed to `seal_random` exceeds the limit. - RandomSubjectTooLong, - /// The amount of topics passed to `seal_deposit_events` exceeds the limit. - TooManyTopics, - /// The chain does not provide a chain extension. Calling the chain extension results - /// in this error. Note that this usually shouldn't happen as deploying such contracts - /// is rejected. - NoChainExtension, - /// Failed to decode the XCM program. - XCMDecodeFailed, - /// A contract with the same AccountId already exists. - DuplicateContract, - /// A contract self destructed in its constructor. - /// - /// This can be triggered by a call to `seal_terminate`. - TerminatedInConstructor, - /// A call tried to invoke a contract that is flagged as non-reentrant. - /// The only other cause is that a call from a contract into the runtime tried to call back - /// into `pallet-contracts`. This would make the whole pallet reentrant with regard to - /// contract code execution which is not supported. - ReentranceDenied, - /// Origin doesn't have enough balance to pay the required storage deposits. - StorageDepositNotEnoughFunds, - /// More storage was created than allowed by the storage deposit limit. - StorageDepositLimitExhausted, - /// Code removal was denied because the code is still in use by at least one contract. - CodeInUse, - /// The contract ran to completion but decided to revert its storage changes. - /// Please note that this error is only returned from extrinsics. When called directly - /// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags - /// to determine whether a reversion has taken place. - ContractReverted, - /// The contract's code was found to be invalid during validation. - /// - /// The most likely cause of this is that an API was used which is not supported by the - /// node. This happens if an older node is used with a new version of ink!. Try updating - /// your node to the newest available version. - /// - /// A more detailed error can be found on the node console if debug messages are enabled - /// by supplying `-lruntime::contracts=debug`. - CodeRejected, - /// An indeterministic code was used in a context where this is not permitted. - Indeterministic, - /// A pending migration needs to complete before the extrinsic can be called. - MigrationInProgress, - /// Migrate dispatch call was attempted but no migration was performed. - NoMigrationPerformed, - /// The contract has reached its maximum number of delegate dependencies. - MaxDelegateDependenciesReached, - /// The dependency was not found in the contract's delegate dependencies. - DelegateDependencyNotFound, - /// The contract already depends on the given delegate dependency. - DelegateDependencyAlreadyExists, - /// Can not add a delegate dependency to the code hash of the contract itself. - CannotAddSelfAsDelegateDependency, -} - -impl TryFrom for Error { - type Error = PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use Error::*; - match status_code { - 0 => Ok(InvalidSchedule), - 1 => Ok(InvalidCallFlags), - 2 => Ok(OutOfGas), - 3 => Ok(OutputBufferTooSmall), - 4 => Ok(TransferFailed), - 5 => Ok(MaxCallDepthReached), - 6 => Ok(ContractNotFound), - 7 => Ok(CodeTooLarge), - 8 => Ok(CodeNotFound), - 9 => Ok(CodeInfoNotFound), - 10 => Ok(OutOfBounds), - 11 => Ok(DecodingFailed), - 12 => Ok(ContractTrapped), - 13 => Ok(ValueTooLarge), - 14 => Ok(TerminatedWhileReentrant), - 15 => Ok(InputForwarded), - 16 => Ok(RandomSubjectTooLong), - 17 => Ok(TooManyTopics), - 18 => Ok(NoChainExtension), - 19 => Ok(XCMDecodeFailed), - 20 => Ok(DuplicateContract), - 21 => Ok(TerminatedInConstructor), - 22 => Ok(ReentranceDenied), - 23 => Ok(StorageDepositNotEnoughFunds), - 24 => Ok(StorageDepositLimitExhausted), - 25 => Ok(CodeInUse), - 26 => Ok(ContractReverted), - 27 => Ok(CodeRejected), - 28 => Ok(Indeterministic), - 29 => Ok(MigrationInProgress), - 30 => Ok(NoMigrationPerformed), - 31 => Ok(MaxDelegateDependenciesReached), - 32 => Ok(DelegateDependencyNotFound), - 33 => Ok(DelegateDependencyAlreadyExists), - 34 => Ok(CannotAddSelfAsDelegateDependency), - _ => Err(UnknownModuleStatusCode(status_code)), - } - } -} - -impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Contracts(e) => e, - _ => panic!("expected balances error"), - } - } -} diff --git a/pop-api/src/v0/cross_chain/mod.rs b/pop-api/src/v0/cross_chain/mod.rs index 1e5afbf5..1d3c5b7d 100644 --- a/pop-api/src/v0/cross_chain/mod.rs +++ b/pop-api/src/v0/cross_chain/mod.rs @@ -1,8 +1,8 @@ pub mod coretime; -use crate::{PopApiError::UnknownModuleStatusCode, *}; +use crate::error::PopApiError; -type Result = core::result::Result; +type Result = core::result::Result; #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] @@ -92,16 +92,7 @@ impl TryFrom for Error { 21 => Ok(InvalidAssetUnknownReserve), 22 => Ok(InvalidAssetUnsupportedReserve), 23 => Ok(TooManyReserves), - _ => Err(UnknownModuleStatusCode(status_code)), - } - } -} - -impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Xcm(e) => e, - _ => panic!("expected xcm error"), + _ => todo!(), } } } diff --git a/pop-api/src/v0/dispatch_error.rs b/pop-api/src/v0/dispatch_error.rs deleted file mode 100644 index 6ed40ce5..00000000 --- a/pop-api/src/v0/dispatch_error.rs +++ /dev/null @@ -1,57 +0,0 @@ -use super::*; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub(crate) enum TokenError { - /// Funds are unavailable. - FundsUnavailable, - /// Some part of the balance gives the only provider reference to the account and thus cannot - /// be (re)moved. - OnlyProvider, - /// Account cannot exist with the funds that would be given. - BelowMinimum, - /// Account cannot be created. - CannotCreate, - /// The asset in question is unknown. - UnknownAsset, - /// Funds exist but are frozen. - Frozen, - /// Operation is not supported by the asset. - Unsupported, - /// Account cannot be created for a held balance. - CannotCreateHold, - /// Withdrawal would cause unwanted loss of account. - NotExpendable, - /// Account cannot receive the assets. - Blocked, -} - -impl TryFrom for TokenError { - type Error = crate::PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use TokenError::*; - match status_code { - 0 => Ok(FundsUnavailable), - 1 => Ok(OnlyProvider), - 2 => Ok(BelowMinimum), - 3 => Ok(CannotCreate), - 4 => Ok(UnknownAsset), - 5 => Ok(Frozen), - 6 => Ok(Unsupported), - 7 => Ok(CannotCreateHold), - 8 => Ok(NotExpendable), - 9 => Ok(Blocked), - _ => todo!(), - } - } -} - -impl From for TokenError { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::TokenError(e) => e, - _ => todo!(), - } - } -} diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 02169c22..75bcb878 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -5,9 +5,7 @@ use crate::{ pub mod assets; pub mod balances; -pub mod contracts; pub mod cross_chain; -pub mod dispatch_error; pub mod nfts; pub mod state; @@ -22,5 +20,5 @@ pub(crate) enum RuntimeCall { #[codec(index = 50)] Nfts(nfts::NftCalls), #[codec(index = 52)] - Assets(assets::fungibles::AssetsCall), + Assets(assets::pallets::assets::AssetsCall), } diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index 946a3eca..2de306a9 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -1,12 +1,12 @@ use super::RuntimeCall; -use crate::{PopApiError::UnknownModuleStatusCode, *}; +use crate::{PopApiError, *}; use ink::prelude::vec::Vec; use primitives::{ApprovalsLimit, BoundedBTreeMap, KeyLimit, MultiAddress}; pub use primitives::{CollectionId, ItemId}; use scale::Encode; pub use types::*; -type Result = core::result::Result; +type Result = core::result::Result; /// Issue a new collection of non-fungible items pub fn create( @@ -660,16 +660,7 @@ impl TryFrom for Error { 42 => Ok(WrongNamespace), 43 => Ok(CollectionNotEmpty), 44 => Ok(WitnessRequired), - _ => Err(UnknownModuleStatusCode(status_code)), - } - } -} - -impl From for Error { - fn from(error: PopApiError) -> Self { - match error { - PopApiError::Nfts(e) => e, - _ => panic!("unexpected pallet nfts error. This error is unknown to pallet nfts"), + _ => todo!(), } } } diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index 67448842..fc7234aa 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -1,5 +1,4 @@ use super::*; -// use scale::{Decode, Encode, MaxEncodedLen}; #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum RuntimeStateKeys { @@ -28,8 +27,6 @@ pub enum NftsKeys { Owner(CollectionId, ItemId), /// Get the attribute value of `item` of `collection` corresponding to `key`. Attribute(CollectionId, ItemId, BoundedVec), - // /// Get the custom attribute value of `item` of `collection` corresponding to `key`. - // CustomAttribute(AccountId, CollectionId, ItemId, BoundedVec), /// Get the system attribute value of `item` of `collection` corresponding to `key` SystemAttribute(CollectionId, Option, BoundedVec), /// Get the attribute value of `item` of `collection` corresponding to `key`. diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index d4fe2923..46208d8f 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -91,6 +91,7 @@ parachain-info.workspace = true env_logger = "0.11.2" hex = "0.4.3" enumflags2 = "0.7.9" +pop-api = { path = "../../pop-api", default-features = false } [features] default = ["std"] @@ -138,6 +139,7 @@ std = [ "polkadot-parachain-primitives/std", "polkadot-runtime-common/std", "pop-primitives/std", + "pop-api/std", "scale-info/std", "sp-api/std", "sp-io/std", diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions.rs similarity index 97% rename from runtime/devnet/src/extensions/mod.rs rename to runtime/devnet/src/extensions.rs index d2129c4f..014893f9 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions.rs @@ -17,10 +17,7 @@ use pop_primitives::{ AssetId, CollectionId, ItemId, }; use sp_core::crypto::UncheckedFrom; -use sp_runtime::{ - traits::{BlockNumberProvider, Dispatchable}, - DispatchError, -}; +use sp_runtime::traits::{BlockNumberProvider, Dispatchable}; use sp_std::{boxed::Box, vec::Vec}; use xcm::{ latest::{prelude::*, OriginKind::SovereignAccount}, @@ -32,9 +29,6 @@ use crate::{ RuntimeOrigin, UNIT, }; -#[cfg(test)] -mod tests; - const LOG_TARGET: &str = "pop-api::extension"; type ContractSchedule = ::Schedule; @@ -42,6 +36,7 @@ type ContractSchedule = ::Schedule; #[derive(Default)] pub struct PopApiExtension; +// TODO: check removal or simplification of trait bounds. impl ChainExtension for PopApiExtension where T: pallet_contracts::Config @@ -59,31 +54,12 @@ where fn call(&mut self, env: Environment) -> Result where E: Ext, - // T::AccountId: UncheckedFrom + AsRef<[u8]>, { log::debug!(target:LOG_TARGET, " extension called "); match v0::FuncId::try_from(env.func_id())? { - v0::FuncId::Dispatch => { - match dispatch::(env) { - Ok(()) => Ok(RetVal::Converging(0)), - Err(DispatchError::Module(error)) => { - // encode status code = pallet index in runtime + error index, allowing for - // 999 errors - let first = (3u32 * 1_000_000u32) - + (error.index as u32 * 1_000u32) - + u32::from_le_bytes(error.error); - Ok(RetVal::Converging( - // (3u32 * 1_000_000u32) - // + (error.index as u32 * 1_000u32) - // + u32::from_le_bytes(error.error), - first, - )) - }, - Err(DispatchError::Token(error)) => { - Ok(RetVal::Converging((7u32 * 1_000_000u32) + error as u32)) - }, - Err(e) => Err(e), - } + v0::FuncId::Dispatch => match dispatch::(env) { + Ok(()) => Ok(RetVal::Converging(0)), + Err(e) => Ok(RetVal::Converging(convert_to_status_code(e))), }, v0::FuncId::ReadState => { read_state::(env)?; @@ -97,6 +73,17 @@ where } } +pub(crate) fn convert_to_status_code(error: DispatchError) -> u32 { + match error { + _ => { + let mut encoded_error = error.encode(); + // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). + encoded_error.resize(4, 0); + u32::decode(&mut &encoded_error[..]).unwrap() + }, + } +} + pub mod v0 { #[derive(Debug)] pub enum FuncId { diff --git a/runtime/devnet/src/extensions/tests/mod.rs b/runtime/devnet/src/extensions/tests/mod.rs deleted file mode 100644 index cbd13d62..00000000 --- a/runtime/devnet/src/extensions/tests/mod.rs +++ /dev/null @@ -1,89 +0,0 @@ -#![cfg(test)] -use super::*; -use crate::{Assets, Balances, Contracts, Runtime, System}; -use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; -use sp_runtime::{traits::Hash, AccountId32, BuildStorage}; - -mod local_fungibles; - -type Balance = u128; -type AssetId = u32; -const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; - -const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); -const BOB: AccountId32 = AccountId32::new([2_u8; 32]); -const INIT_AMOUNT: Balance = 100_000_000 * UNIT; -const INIT_VALUE: Balance = 100 * UNIT; -const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); - -fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default() - .build_storage() - .expect("Frame system builds valid default genesis config"); - - pallet_balances::GenesisConfig:: { - balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT)], - } - .assimilate_storage(&mut t) - .expect("Pallet balances storage can be assimilated"); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext -} - -fn load_wasm_module(path: &str) -> std::io::Result<(Vec, ::Output)> -where - T: frame_system::Config, -{ - let wasm_binary = std::fs::read(path)?; - let code_hash = T::Hashing::hash(&wasm_binary); - Ok((wasm_binary, code_hash)) -} - -fn function_selector(name: &str) -> Vec { - let hash = sp_io::hashing::blake2_256(name.as_bytes()); - [hash[0..4].to_vec()].concat() -} - -fn do_bare_call( - addr: AccountId32, - input: Vec, - value: u128, -) -> Result { - let result = Contracts::bare_call( - ALICE, - addr.into(), - value.into(), - GAS_LIMIT, - None, - input, - DEBUG_OUTPUT, - CollectEvents::Skip, - Determinism::Enforced, - ); - log::debug!("Contract debug buffer - {:?}", String::from_utf8(result.debug_message.clone())); - log::debug!("result: {:?}", result); - result.result -} - -// Deploy, instantiate and return contract address. -fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { - let (wasm_binary, _) = - load_wasm_module::(contract).expect("could not read .wasm file"); - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - salt, - DEBUG_OUTPUT, - CollectEvents::Skip, - ) - .result - .unwrap(); - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - result.account_id -} diff --git a/runtime/devnet/src/lib.rs b/runtime/devnet/src/lib.rs index a82be804..416a3298 100644 --- a/runtime/devnet/src/lib.rs +++ b/runtime/devnet/src/lib.rs @@ -10,6 +10,8 @@ mod extensions; mod weights; // Public due to integration tests crate. pub mod config; +#[cfg(test)] +mod tests; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; diff --git a/runtime/devnet/src/extensions/tests/local_fungibles.rs b/runtime/devnet/src/tests/local_fungibles.rs similarity index 70% rename from runtime/devnet/src/extensions/tests/local_fungibles.rs rename to runtime/devnet/src/tests/local_fungibles.rs index 5de162c9..bc13fbde 100644 --- a/runtime/devnet/src/extensions/tests/local_fungibles.rs +++ b/runtime/devnet/src/tests/local_fungibles.rs @@ -2,31 +2,10 @@ use super::*; -#[derive(Decode, Encode, Debug, Eq, PartialEq)] -enum FungiblesError { - /// The asset is not live; either frozen or being destroyed. - AssetNotLive, - /// The amount to mint is less than the existential deposit. - BelowMinimum, - /// Unspecified dispatch error, providing the index and optionally its error index. - DispatchError { index: u8, error: Option }, - /// Not enough allowance to fulfill a request is available. - InsufficientAllowance, - /// Not enough balance to fulfill a request is available. - InsufficientBalance, - /// The asset ID is already taken. - InUse, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// Unspecified pallet error, providing pallet index and error index. - ModuleError { pallet: u8, error: u16 }, - /// The account to alter does not exist. - NoAccount, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, -} +use pop_api::{ + error::{ArithmeticError::*, PopApiError::*, TokenError::*}, + v0::assets::use_cases::fungibles::FungiblesError::*, +}; const ASSET_ID: AssetId = 1; @@ -119,8 +98,7 @@ fn transfer_from( do_bare_call(addr, params, 0).expect("should work") } -// Create an asset and mint to owner. -fn create_asset(asset_id: AssetId, owner: AccountId32, min_balance: Balance) -> AssetId { +fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { assert_eq!( Assets::create( RuntimeOrigin::signed(owner.clone()), @@ -133,31 +111,34 @@ fn create_asset(asset_id: AssetId, owner: AccountId32, min_balance: Balance) -> asset_id } -// Create an asset and mint to owner. +fn mint_asset(owner: AccountId32, asset_id: AssetId, to: AccountId32, value: Balance) -> AssetId { + assert_eq!( + Assets::mint(RuntimeOrigin::signed(owner.clone()), asset_id.into(), to.into(), value), + Ok(()) + ); + asset_id +} + fn create_asset_and_mint_to( - asset_id: AssetId, owner: AccountId32, + asset_id: AssetId, to: AccountId32, value: Balance, ) -> AssetId { - create_asset(asset_id, owner.clone(), 1); - assert_eq!( - Assets::mint(RuntimeOrigin::signed(owner.into()), asset_id.into(), to.into(), value,), - Ok(()) - ); - asset_id + create_asset(owner.clone(), asset_id, 1); + mint_asset(owner, asset_id, to, value) } // Create an asset, mints to, and approves spender. fn create_asset_mint_and_approve( - asset_id: AssetId, owner: AccountId32, + asset_id: AssetId, to: AccountId32, mint: Balance, spender: AccountId32, approve: Balance, ) { - create_asset_and_mint_to(asset_id, owner.clone(), to.clone(), mint); + create_asset_and_mint_to(owner.clone(), asset_id, to.clone(), mint); assert_eq!( Assets::approve_transfer( RuntimeOrigin::signed(to.into()), @@ -199,7 +180,7 @@ fn total_supply_works() { assert_eq!(Assets::total_supply(ASSET_ID), total_supply(addr.clone(), ASSET_ID)); // Tokens in circulation. - create_asset_and_mint_to(ASSET_ID, addr.clone(), BOB, 100); + create_asset_and_mint_to(addr.clone(), ASSET_ID, BOB, 100); assert_eq!(Assets::total_supply(ASSET_ID), total_supply(addr, ASSET_ID)); }); } @@ -219,7 +200,7 @@ fn balance_of_works() { assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr.clone(), ASSET_ID, BOB)); // Tokens in circulation. - create_asset_and_mint_to(ASSET_ID, addr.clone(), BOB, 100); + create_asset_and_mint_to(addr.clone(), ASSET_ID, BOB, 100); assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr, ASSET_ID, BOB)); }); } @@ -242,7 +223,7 @@ fn allowance_works() { ); // Tokens in circulation. - create_asset_mint_and_approve(ASSET_ID, addr.clone(), BOB, 100, ALICE, 50); + create_asset_mint_and_approve(addr.clone(), ASSET_ID, BOB, 100, ALICE, 50); assert_eq!( Assets::allowance(ASSET_ID, &BOB, &ALICE), allowance(addr, ASSET_ID, BOB, ALICE) @@ -265,7 +246,7 @@ fn asset_exists_works() { assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr.clone(), ASSET_ID)); // Tokens in circulation. - create_asset(ASSET_ID, addr.clone(), 1); + create_asset(addr.clone(), ASSET_ID, 1); assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr, ASSET_ID)); }); } @@ -276,34 +257,52 @@ fn asset_exists_works() { // - reserve(): Overflow, LiquidityRestrictions; frozen // - Callback // - StorageDepositLimitExhausted +// todo: errors: +// - TokenErrors +// - Arithmetic +// - https://github.com/paritytech/polkadot-sdk/blob/3977f389cce4a00fd7100f95262e0563622b9aa4/substrate/frame/assets/src/functions.rs#L125 #[test] #[ignore] fn create_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); let new_asset = 2; + // Instantiate a contract without balance (relay token). let addr = instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); - + // No balance to pay for fees. assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), - FungiblesError::InsufficientBalance + decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), + UseCaseError(NoBalance) ); + // Instantiate a contract without balance (relay token). + let addr = + instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 100, vec![2]); + // TODO: make sure it has enough for the fees but not for the deposit. + // No balance to pay fe deposit. + assert_eq!( + decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), + UseCaseError(NoBalance) + ); + // Instantiate a contract with balance. let addr = instantiate( "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1], ); - create_asset(ASSET_ID, ALICE, 1); + create_asset(ALICE, ASSET_ID, 1); + // Asset ID is already taken. assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), - FungiblesError::InUse + decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), + UseCaseError(InUse) ); + // The minimal balance for an asset must be non zero. assert_eq!( - decoded::(create(addr.clone(), new_asset, BOB, 0)), - FungiblesError::MinBalanceZero + decoded::(create(addr.clone(), new_asset, BOB, 0)), + UseCaseError(MinBalanceZero) ); - assert!(!create(addr.clone(), new_asset, BOB, 1).did_revert(), "Contract reverted!"); + let result = create(addr.clone(), new_asset, BOB, 1); + assert!(!result.did_revert(), "Contract reverted!"); }); } @@ -318,17 +317,12 @@ fn set_metadata_works() { vec![], ); - create_asset(ASSET_ID, addr.clone(), 1); - + create_asset(addr.clone(), ASSET_ID, 1); let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); assert!(!result.did_revert(), "Contract reverted!"); }); } -// todo: errors: -// - TokenErrors -// - Arithmetic -// - https://github.com/paritytech/polkadot-sdk/blob/3977f389cce4a00fd7100f95262e0563622b9aa4/substrate/frame/assets/src/functions.rs#L125 #[test] #[ignore] fn transfer_from_mint_works() { @@ -341,20 +335,15 @@ fn transfer_from_mint_works() { ); let amount: Balance = 100 * UNIT; + // Asset does not exist. assert_eq!( - decoded::(transfer_from( - addr.clone(), - 1, - None, - Some(BOB), - amount, - &[0u8] - )), - FungiblesError::Unknown + decoded::(transfer_from(addr.clone(), 1, None, Some(BOB), amount, &[0u8])), + Token(UnknownAsset) ); - let asset = create_asset(1, ALICE, 2); + let asset = create_asset(ALICE, 1, 2); + // Minting can only be done by the owner. assert_eq!( - decoded::(transfer_from( + decoded::(transfer_from( addr.clone(), asset, None, @@ -362,23 +351,18 @@ fn transfer_from_mint_works() { amount, &[0u8] )), - FungiblesError::NoPermission + UseCaseError(NoPermission) ); + // Minimum balance of an asset can not be zero. assert_eq!( - decoded::(transfer_from( - addr.clone(), - asset, - None, - Some(BOB), - 1, - &[0u8] - )), - FungiblesError::BelowMinimum + decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), 1, &[0u8])), + Token(BelowMinimum) ); - let asset = create_asset(2, addr.clone(), 2); + let asset = create_asset(addr.clone(), 2, 2); + // Asset is not live, i.e. frozen or being destroyed. freeze_asset(asset, addr.clone()); assert_eq!( - decoded::(transfer_from( + decoded::(transfer_from( addr.clone(), asset, None, @@ -386,17 +370,31 @@ fn transfer_from_mint_works() { amount, &[0u8] )), - FungiblesError::AssetNotLive + UseCaseError(AssetNotLive) ); thaw_asset(asset, addr.clone()); + // Successful mint. let bob_balance_before_mint = Assets::balance(asset, &BOB); let result = transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8]); assert!(!result.did_revert(), "Contract reverted!"); let bob_balance_after_mint = Assets::balance(asset, &BOB); assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount); + // Can not mint more tokens than Balance::MAX. + assert_eq!( + decoded::(transfer_from( + addr.clone(), + asset, + None, + Some(BOB), + Balance::MAX, + &[0u8] + )), + Arithmetic(Overflow) + ); + // Asset is not live, i.e. frozen or being destroyed. start_destroy_asset(asset, addr.clone()); assert_eq!( - decoded::(transfer_from( + decoded::(transfer_from( addr.clone(), asset, None, @@ -404,17 +402,15 @@ fn transfer_from_mint_works() { amount, &[0u8] )), - FungiblesError::AssetNotLive + UseCaseError(AssetNotLive) ); }); } // Todo: error: -// - Frozen: account is frozen, who do you freeze an account? // - https://github.com/paritytech/polkadot-sdk/blob/2460cddf57660a88844d201f769eb17a7accce5a/substrate/frame/assets/src/functions.rs#L161 // - ArithmeticError: Underflow, Overflow // - https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/functions.rs#L125 -// - #[test] #[ignore] fn transfer_works() { @@ -427,35 +423,46 @@ fn transfer_works() { ); let amount: Balance = 100 * UNIT; + // Asset does not exist. assert_eq!( - decoded::(transfer(addr.clone(), 1, BOB, amount,)), - FungiblesError::Unknown + decoded::(transfer(addr.clone(), 1, BOB, amount,)), + UseCaseError(Unknown) ); - let asset = create_asset_and_mint_to(1, ALICE, addr.clone(), amount); + // Create asset with Alice as owner and mint `amount` to contract address. + let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); + // Asset is not live, i.e. frozen or being destroyed. freeze_asset(asset, ALICE); assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount,)), - FungiblesError::AssetNotLive + decoded::(transfer(addr.clone(), asset, BOB, amount,)), + UseCaseError(AssetNotLive) ); thaw_asset(asset, ALICE); + // Not enough balance. assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), - FungiblesError::InsufficientBalance + decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), + UseCaseError(InsufficientBalance) ); - // Errors due to ED. Could be Belowminimum + // Not enough balance due to ED. assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount)), - FungiblesError::InsufficientBalance + decoded::(transfer(addr.clone(), asset, BOB, amount)), + UseCaseError(InsufficientBalance) ); + // Successful transfer. let bob_balance_before_mint = Assets::balance(asset, &BOB); let result = transfer(addr.clone(), asset, BOB, amount / 2); assert!(!result.did_revert(), "Contract reverted!"); let bob_balance_after_mint = Assets::balance(asset, &BOB); assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); + // Transfer asset to account that does not exist. + assert_eq!( + decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), + Token(CannotCreate) + ); + // Asset is not live, i.e. frozen or being destroyed. start_destroy_asset(asset, ALICE); assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), - FungiblesError::AssetNotLive + decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), + UseCaseError(AssetNotLive) ); }); } diff --git a/runtime/devnet/src/tests/mod.rs b/runtime/devnet/src/tests/mod.rs new file mode 100644 index 00000000..c13030a3 --- /dev/null +++ b/runtime/devnet/src/tests/mod.rs @@ -0,0 +1,262 @@ +#![cfg(test)] + +use crate::{ + config::assets::TrustBackedAssetsInstance, Assets, Contracts, Runtime, RuntimeOrigin, System, + Weight, UNIT, +}; +use codec::{Decode, Encode}; +use frame_support::traits::fungibles::{approvals::Inspect as ApprovalInspect, Inspect}; +use frame_system::Config; +use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; +use pop_api::error::{ArithmeticError, PopApiError, TokenError, TransactionalError}; +use sp_runtime::{traits::Hash, AccountId32, BuildStorage, DispatchError}; + +mod local_fungibles; + +type Balance = u128; +type AssetId = u32; +const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; + +const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); +const BOB: AccountId32 = AccountId32::new([2_u8; 32]); +// FERDIE has no initial balance. +const FERDIE: AccountId32 = AccountId32::new([3_u8; 32]); +const INIT_AMOUNT: Balance = 100_000_000 * UNIT; +const INIT_VALUE: Balance = 100 * UNIT; +const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); + +fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT)], + } + .assimilate_storage(&mut t) + .expect("Pallet balances storage can be assimilated"); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +fn load_wasm_module(path: &str) -> std::io::Result<(Vec, ::Output)> +where + T: frame_system::Config, +{ + let wasm_binary = std::fs::read(path)?; + let code_hash = T::Hashing::hash(&wasm_binary); + Ok((wasm_binary, code_hash)) +} + +fn function_selector(name: &str) -> Vec { + let hash = sp_io::hashing::blake2_256(name.as_bytes()); + [hash[0..4].to_vec()].concat() +} + +fn do_bare_call( + addr: AccountId32, + input: Vec, + value: u128, +) -> Result { + let result = Contracts::bare_call( + ALICE, + addr.into(), + value.into(), + GAS_LIMIT, + None, + input, + DEBUG_OUTPUT, + CollectEvents::Skip, + Determinism::Enforced, + ); + log::debug!("Contract debug buffer - {:?}", String::from_utf8(result.debug_message.clone())); + log::debug!("result: {:?}", result); + result.result +} + +// Deploy, instantiate and return contract address. +fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { + let (wasm_binary, _) = + load_wasm_module::(contract).expect("could not read .wasm file"); + let result = Contracts::bare_instantiate( + ALICE, + init_value, + GAS_LIMIT, + None, + Code::Upload(wasm_binary), + function_selector("new"), + salt, + DEBUG_OUTPUT, + CollectEvents::Skip, + ) + .result + .unwrap(); + assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); + result.account_id +} + +pub fn get_pallet_index() -> u8 { + // Get the index of the pallet (module) + <::PalletInfo as frame_support::traits::PalletInfo>::index::() + .expect("Every active module has an index in the runtime; qed") as u8 +} + +#[test] +fn encoding_decoding_dispatch_error() { + use codec::{Decode, Encode}; + use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; + + new_test_ext().execute_with(|| { + let error = DispatchError::Module(ModuleError { + index: 255, + error: [2, 0, 0, 0], + message: Some("error message"), + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); + assert_eq!( + decoded, + // `message` is skipped for encoding. + DispatchError::Module(ModuleError { index: 255, error: [2, 0, 0, 0], message: None }) + ); + println!("Encoded Module Error: {:?}", encoded); + + // Example pallet assets Error into ModuleError + let index = get_pallet_index::(); + let mut error = + pallet_assets::Error::NotFrozen::.encode(); + error.resize(sp_runtime::MAX_MODULE_ERROR_ENCODED_SIZE, 0); + let message = None; + let error = DispatchError::Module(ModuleError { + index, + error: TryInto::try_into(error).expect("should work"), + message, + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 52, 18, 0, 0, 0]); + assert_eq!( + decoded, + DispatchError::Module(ModuleError { index: 52, error: [18, 0, 0, 0], message: None }) + ); + println!("Encoded Module Error: {:?}", encoded); + + // Example DispatchError::Token + let error = DispatchError::Token(TokenError::UnknownAsset); + let encoded = error.encode(); + assert_eq!(encoded, vec![7, 4]); + println!("Encoded Token Error: {:?}", encoded); + + // Example DispatchError::Arithmetic + let error = DispatchError::Arithmetic(ArithmeticError::Overflow); + let encoded = error.encode(); + assert_eq!(encoded, vec![8, 1]); + println!("Encoded Arithmetic Error: {:?}", encoded); + }); +} + +#[test] +fn encoding_of_enum() { + use codec::{Decode, Encode}; + + // Comprehensive enum with all different type of variants. + #[derive(Debug, PartialEq, Encode, Decode)] + enum ComprehensiveEnum { + SimpleVariant, + DataVariant(u8), + NamedFields { w: u8 }, + NestedEnum(InnerEnum), + OptionVariant(Option), + VecVariant(Vec), + TupleVariant(u8, u8), + NestedStructVariant(NestedStruct), + NestedEnumStructVariant(NestedEnumStruct), + } + + #[derive(Debug, PartialEq, Encode, Decode)] + enum InnerEnum { + A, + B { inner_data: u8 }, + C(u8), + } + + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedStruct { + x: u8, + y: u8, + } + + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedEnumStruct { + inner_enum: InnerEnum, + } + + // Creating each possible variant for an enum. + let enum_simple = ComprehensiveEnum::SimpleVariant; + let enum_data = ComprehensiveEnum::DataVariant(42); + let enum_named = ComprehensiveEnum::NamedFields { w: 42 }; + let enum_nested = ComprehensiveEnum::NestedEnum(InnerEnum::B { inner_data: 42 }); + let enum_option = ComprehensiveEnum::OptionVariant(Some(42)); + let enum_vec = ComprehensiveEnum::VecVariant(vec![1, 2, 3, 4, 5]); + let enum_tuple = ComprehensiveEnum::TupleVariant(42, 42); + let enum_nested_struct = ComprehensiveEnum::NestedStructVariant(NestedStruct { x: 42, y: 42 }); + let enum_nested_enum_struct = ComprehensiveEnum::NestedEnumStructVariant(NestedEnumStruct { + inner_enum: InnerEnum::C(42), + }); + + // Encode and print each variant individually to see their encoded values. + println!("{:?} -> {:?}", enum_simple, enum_simple.encode()); + println!("{:?} -> {:?}", enum_data, enum_data.encode()); + println!("{:?} -> {:?}", enum_named, enum_named.encode()); + println!("{:?} -> {:?}", enum_nested, enum_nested.encode()); + println!("{:?} -> {:?}", enum_option, enum_option.encode()); + println!("{:?} -> {:?}", enum_vec, enum_vec.encode()); + println!("{:?} -> {:?}", enum_tuple, enum_tuple.encode()); + println!("{:?} -> {:?}", enum_nested_struct, enum_nested_struct.encode()); + println!("{:?} -> {:?}", enum_nested_enum_struct, enum_nested_enum_struct.encode()); +} + +#[test] +fn dispatch_error_to_status_code_to_pop_api_error_works() { + // Create all the different `DispatchError` variants with its respective `PopApiError`. + let test_cases = vec![ + (DispatchError::CannotLookup, PopApiError::CannotLookup), + (DispatchError::BadOrigin, PopApiError::BadOrigin), + ( + DispatchError::Module(sp_runtime::ModuleError { + index: 1, + error: [2, 0, 0, 0], + message: Some("hallo"), + }), + PopApiError::Module { index: 1, error: 2 }, + ), + (DispatchError::ConsumerRemaining, PopApiError::ConsumerRemaining), + (DispatchError::NoProviders, PopApiError::NoProviders), + (DispatchError::TooManyConsumers, PopApiError::TooManyConsumers), + ( + DispatchError::Token(sp_runtime::TokenError::FundsUnavailable), + PopApiError::Token(TokenError::FundsUnavailable), + ), + ( + DispatchError::Arithmetic(sp_runtime::ArithmeticError::Overflow), + PopApiError::Arithmetic(ArithmeticError::Overflow), + ), + ( + DispatchError::Transactional(sp_runtime::TransactionalError::LimitReached), + PopApiError::Transactional(TransactionalError::LimitReached), + ), + (DispatchError::Exhausted, PopApiError::Exhausted), + (DispatchError::Corruption, PopApiError::Corruption), + (DispatchError::Unavailable, PopApiError::Unavailable), + (DispatchError::RootNotAllowed, PopApiError::RootNotAllowed), + ]; + for (error, pop_api_error) in test_cases { + // Show that the encoding and decoding of the PopApiError <> u32 (status code) works. + let status_code = crate::extensions::convert_to_status_code(error); + let error = pop_api::error::convert_to_pop_api_error(status_code); + assert_eq!(pop_api_error, error,); + } +} From f824801e092ac5a6224779bbf06f93ec3b04402b Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 20 Jun 2024 15:50:00 +0200 Subject: [PATCH 08/27] refactor: error handling --- pop-api/src/lib.rs | 2 +- pop-api/src/v0/assets/pallets/assets.rs | 3 ++- pop-api/src/v0/balances.rs | 3 ++- primitives/Cargo.toml | 5 ----- primitives/src/lib.rs | 7 +------ runtime/devnet/src/tests/local_fungibles.rs | 22 ++++++++------------- runtime/testnet/src/extensions.rs | 5 ++++- 7 files changed, 18 insertions(+), 29 deletions(-) diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index a785aebe..e78aff9e 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -13,7 +13,7 @@ pub mod primitives; pub mod v0; type AccountId = AccountId32; -// TODO: do the same as above and check expanded code. +// TODO: do the same as above and check expanded macro code. type Balance = ::Balance; type BlockNumber = ::BlockNumber; type StringLimit = u32; diff --git a/pop-api/src/v0/assets/pallets/assets.rs b/pop-api/src/v0/assets/pallets/assets.rs index 7a575e08..b28d3086 100644 --- a/pop-api/src/v0/assets/pallets/assets.rs +++ b/pop-api/src/v0/assets/pallets/assets.rs @@ -1,4 +1,3 @@ -// TODO: what to put in this file? #![allow(dead_code)] use crate::{Balance, RuntimeCall, *}; @@ -412,6 +411,8 @@ pub(crate) enum AssetsCall { Block { id: AssetIdParameter, who: MultiAddress }, } +// TODO: do we want add this. Not being used atm but necessary if we want to provide access to the +// rest of the pallet. #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum AssetsError { diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index 5d38d851..c9759a45 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -1,4 +1,3 @@ -// TODO: what to put in this file? use crate::{dispatch, error::PopApiError, primitives::MultiAddress, v0::RuntimeCall, AccountId}; type Result = core::result::Result; @@ -24,6 +23,8 @@ pub enum BalancesCall { }, } +// TODO: do we want add this. Not being used atm but necessary if we want to provide access to the +// rest of the pallet. #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum BalancesError { diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 1098b557..e7237b51 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -12,11 +12,6 @@ scale-decode = { version = "0.10.0", default-features = false, features = ["deri scale-encode = { version = "0.5.0", default-features = false, features = ["derive"], optional = true } scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } -#scale = { workspace = true, features = ["max-encoded-len"] } -#scale-decode = { workspace = true, features = ["derive"], optional = true } -#scale-encode = { workspace = true, features = ["derive"], optional = true } -#scale-info = { workspace = true, features = ["derive"], optional = true } - [features] default = ["std"] std = [ diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 7c1672b8..1e008c31 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -3,12 +3,7 @@ pub use bounded_collections::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec, ConstU32}; use scale::{Decode, Encode, MaxEncodedLen}; #[cfg(feature = "std")] -use { - scale_decode::DecodeAsType, - scale_encode::EncodeAsType, - scale_info::TypeInfo, -}; - +use {scale_decode::DecodeAsType, scale_encode::EncodeAsType, scale_info::TypeInfo}; pub mod cross_chain; pub mod storage_keys; diff --git a/runtime/devnet/src/tests/local_fungibles.rs b/runtime/devnet/src/tests/local_fungibles.rs index bc13fbde..b1ddda2e 100644 --- a/runtime/devnet/src/tests/local_fungibles.rs +++ b/runtime/devnet/src/tests/local_fungibles.rs @@ -1,3 +1,11 @@ +// Todo - errors: +// - Badorigin: contract is always signed +// - Lookup: is a valid AccountId due to the contract +// - Many errors can occur from calling a dispatchable. As of now, most of the DispatchErrors are +// handled by the pop api but not all of them are tested. How should I approach this? I.e.: +// - Arithmetic errors +// - Token errors +// - others (besides Module errors) that I might haven't found yet. #![cfg(test)] use super::*; @@ -251,16 +259,6 @@ fn asset_exists_works() { }); } -// Todo - errors: -// - Badorigin: contract is always signed -// - Lookup: is a valid AccountId due to the contract -// - reserve(): Overflow, LiquidityRestrictions; frozen -// - Callback -// - StorageDepositLimitExhausted -// todo: errors: -// - TokenErrors -// - Arithmetic -// - https://github.com/paritytech/polkadot-sdk/blob/3977f389cce4a00fd7100f95262e0563622b9aa4/substrate/frame/assets/src/functions.rs#L125 #[test] #[ignore] fn create_works() { @@ -407,10 +405,6 @@ fn transfer_from_mint_works() { }); } -// Todo: error: -// - https://github.com/paritytech/polkadot-sdk/blob/2460cddf57660a88844d201f769eb17a7accce5a/substrate/frame/assets/src/functions.rs#L161 -// - ArithmeticError: Underflow, Overflow -// - https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/functions.rs#L125 #[test] #[ignore] fn transfer_works() { diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index 6bbfaa36..4e7402a7 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -86,6 +86,7 @@ impl TryFrom for v0::FuncId { 0x1 => Self::ReadState, _ => { log::error!("called an unregistered `func_id`: {:}", func_id); + // TODO: Other error. return Err(DispatchError::Other("unimplemented func_id")); }, }; @@ -206,6 +207,7 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, + _ => Err(DispatchError::Other("Unknown state keys")), }? .encode(); @@ -215,7 +217,8 @@ where ); env.write(&result, false, None).map_err(|e| { log::trace!(target: LOG_TARGET, "{:?}", e); - DispatchError::Other("unable to write results to contract memory") + // TODO: Other error. + DispatchError::Other("Unable to write results to contract memory") }) } From 467050307884c6692bcbbbfa6b704f0c42f4ab16 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 20 Jun 2024 18:49:18 +0200 Subject: [PATCH 09/27] refactor: clarify todos --- pop-api/src/lib.rs | 2 +- pop-api/src/v0/assets/pallets/assets.rs | 4 ++-- pop-api/src/v0/balances.rs | 4 ++-- runtime/devnet/src/extensions.rs | 2 ++ runtime/devnet/src/tests/local_fungibles.rs | 8 +++----- runtime/testnet/src/extensions.rs | 1 + 6 files changed, 11 insertions(+), 10 deletions(-) diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index e78aff9e..d00f1e9a 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -13,7 +13,7 @@ pub mod primitives; pub mod v0; type AccountId = AccountId32; -// TODO: do the same as above and check expanded macro code. +// TODO: do the same as the AccountId above and check expanded macro code. type Balance = ::Balance; type BlockNumber = ::BlockNumber; type StringLimit = u32; diff --git a/pop-api/src/v0/assets/pallets/assets.rs b/pop-api/src/v0/assets/pallets/assets.rs index b28d3086..87695b81 100644 --- a/pop-api/src/v0/assets/pallets/assets.rs +++ b/pop-api/src/v0/assets/pallets/assets.rs @@ -411,8 +411,8 @@ pub(crate) enum AssetsCall { Block { id: AssetIdParameter, who: MultiAddress }, } -// TODO: do we want add this. Not being used atm but necessary if we want to provide access to the -// rest of the pallet. +// TODO: Not being used atm but necessary if we want to provide access to the +// rest of the pallet, outside of the use cases. #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum AssetsError { diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index c9759a45..56c3ca72 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -23,8 +23,8 @@ pub enum BalancesCall { }, } -// TODO: do we want add this. Not being used atm but necessary if we want to provide access to the -// rest of the pallet. +// TODO: Not being used atm but necessary if we want to provide access to the +// rest of the pallet, outside of the use cases. #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum BalancesError { diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs index 014893f9..32667d16 100644 --- a/runtime/devnet/src/extensions.rs +++ b/runtime/devnet/src/extensions.rs @@ -103,6 +103,7 @@ impl TryFrom for v0::FuncId { 0x2 => Self::SendXcm, _ => { log::error!("called an unregistered `func_id`: {:}", func_id); + // TODO: Other error. return Err(DispatchError::Other("unimplemented func_id")); }, }; @@ -236,6 +237,7 @@ where ); env.write(&result, false, None).map_err(|e| { log::trace!(target: LOG_TARGET, "{:?}", e); + // TODO: Other error. DispatchError::Other("unable to write results to contract memory") }) } diff --git a/runtime/devnet/src/tests/local_fungibles.rs b/runtime/devnet/src/tests/local_fungibles.rs index b1ddda2e..9f208b15 100644 --- a/runtime/devnet/src/tests/local_fungibles.rs +++ b/runtime/devnet/src/tests/local_fungibles.rs @@ -1,11 +1,9 @@ // Todo - errors: // - Badorigin: contract is always signed // - Lookup: is a valid AccountId due to the contract -// - Many errors can occur from calling a dispatchable. As of now, most of the DispatchErrors are -// handled by the pop api but not all of them are tested. How should I approach this? I.e.: -// - Arithmetic errors -// - Token errors -// - others (besides Module errors) that I might haven't found yet. +// - Many errors can occur from calling a dispatchable. All the DispatchErrors are handled by the +// pop api but not all the possible errors for each dipatchable are tested. How should I approach +// this? #![cfg(test)] use super::*; diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index 4e7402a7..a3284ad4 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -207,6 +207,7 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, + // TODO: devnet / testnet feature. _ => Err(DispatchError::Other("Unknown state keys")), }? .encode(); From 2283161fdf9334697cbc84b9437767b189b9ce06 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Mon, 24 Jun 2024 17:38:28 +0200 Subject: [PATCH 10/27] refactor: error handling comments part 1 --- pop-api/Cargo.toml | 4 + pop-api/examples/fungibles/Cargo.toml | 2 +- pop-api/examples/fungibles/lib.rs | 25 +- pop-api/src/error.rs | 341 +++++++----- pop-api/src/lib.rs | 27 +- .../v0/assets/{use_cases => }/fungibles.rs | 74 ++- pop-api/src/v0/assets/mod.rs | 496 +++++++++++++++++- pop-api/src/v0/assets/pallets/assets.rs | 492 ----------------- pop-api/src/v0/assets/pallets/mod.rs | 1 - pop-api/src/v0/assets/use_cases/mod.rs | 1 - pop-api/src/v0/balances.rs | 6 +- pop-api/src/v0/cross_chain/mod.rs | 13 +- pop-api/src/v0/mod.rs | 26 +- pop-api/src/v0/nfts.rs | 8 +- pop-api/src/v0/state.rs | 3 +- runtime/devnet/Cargo.toml | 2 +- runtime/devnet/src/extensions.rs | 13 +- runtime/devnet/src/tests/local_fungibles.rs | 24 +- runtime/devnet/src/tests/mod.rs | 4 +- 19 files changed, 816 insertions(+), 746 deletions(-) rename pop-api/src/v0/assets/{use_cases => }/fungibles.rs (86%) delete mode 100644 pop-api/src/v0/assets/pallets/assets.rs delete mode 100644 pop-api/src/v0/assets/pallets/mod.rs delete mode 100644 pop-api/src/v0/assets/use_cases/mod.rs diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index 80818235..b80cb3b0 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -31,3 +31,7 @@ std = [ "sp-io/std", "sp-runtime/std", ] +assets = [] +balances = [] +nfts = [] +cross-chain = [] diff --git a/pop-api/examples/fungibles/Cargo.toml b/pop-api/examples/fungibles/Cargo.toml index 1fe32d6d..514f000f 100755 --- a/pop-api/examples/fungibles/Cargo.toml +++ b/pop-api/examples/fungibles/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] ink = { version = "5.0.0", default-features = false } -pop-api = { path = "../../../pop-api", default-features = false } +pop-api = { path = "../../../pop-api", default-features = false, features = ["assets"] } scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 59040590..161c7fdd 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -7,12 +7,12 @@ /// use ink::prelude::vec::Vec; use pop_api::{ - assets::use_cases::fungibles as api, - error::PopApiError, + assets::fungibles::{self as api, FungiblesError}, + error::{PopApiError, StatusCode}, primitives::{AccountId as AccountId32, AssetId}, }; -pub type Result = core::result::Result; +pub type Result = core::result::Result; #[ink::contract(env = pop_api::Environment)] mod fungibles { @@ -41,12 +41,12 @@ mod fungibles { #[ink(message)] pub fn total_supply(&self, id: AssetId) -> Result { - api::total_supply(id) + api::total_supply(id).map_err(|e| e.into()) } #[ink(message)] pub fn balance_of(&self, id: AssetId, owner: AccountId32) -> Result { - api::balance_of(id, owner) + api::balance_of(id, owner).map_err(|e| e.into()) } #[ink(message)] @@ -56,7 +56,7 @@ mod fungibles { owner: AccountId32, spender: AccountId32, ) -> Result { - api::allowance(id, owner, spender) + api::allowance(id, owner, spender).map_err(|e| e.into()) } #[ink(message)] @@ -68,7 +68,7 @@ mod fungibles { value, ); - let result = api::transfer(id, to, value); + let result = api::transfer(id, to, value).map_err(|e| e.into()); ink::env::debug_println!("Result: {:?}", result); result } @@ -80,8 +80,7 @@ mod fungibles { from: Option, to: Option, value: Balance, - // In the standard a `[u8]`, but the size needs to be known at compile time ink's `Vec` - // has to be used. + // In the standard a `[u8]`, but the size needs to be known at compile time. data: Vec, ) -> Result<()> { ink::env::debug_println!( @@ -92,7 +91,7 @@ mod fungibles { value, ); - let result = api::transfer_from(id, from, to, value, &data); + let result = api::transfer_from(id, from, to, value, &data).map_err(|e| e.into()); ink::env::debug_println!("Result: {:?}", result); result } @@ -119,7 +118,7 @@ mod fungibles { admin, min_balance, ); - let result = api::create(id, admin, min_balance); + let result = api::create(id, admin, min_balance).map_err(|e| e.into()); ink::env::debug_println!("Result: {:?}", result); result } @@ -139,14 +138,14 @@ mod fungibles { symbol, decimals, ); - let result = api::set_metadata(id, name, symbol, decimals); + let result = api::set_metadata(id, name, symbol, decimals).map_err(|e| e.into()); ink::env::debug_println!("Result: {:?}", result); result } #[ink(message)] pub fn asset_exists(&self, id: AssetId) -> Result { - api::asset_exists(id) + api::asset_exists(id).map_err(|e| e.into()) } } diff --git a/pop-api/src/error.rs b/pop-api/src/error.rs index 92da4045..4d5a8fb9 100644 --- a/pop-api/src/error.rs +++ b/pop-api/src/error.rs @@ -1,8 +1,35 @@ -use crate::assets::use_cases::fungibles::{convert_to_fungibles_error, FungiblesError}; use ink::env::chain_extension::FromStatusCode; use scale::{Decode, Encode}; use PopApiError::*; +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub struct StatusCode(pub u32); + +impl From for StatusCode { + fn from(value: u32) -> Self { + StatusCode(value) + } +} +impl FromStatusCode for StatusCode { + fn from_status_code(status_code: u32) -> Result<(), Self> { + match status_code { + 0 => Ok(()), + _ => { + let mut encoded = status_code.to_le_bytes(); + convert_unknown_errors(&mut encoded); + Err(StatusCode::from(u32::from_le_bytes(encoded))) + }, + } + } +} + +impl From for StatusCode { + fn from(_: scale::Error) -> Self { + DecodingFailed.into() + } +} + #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] #[repr(u8)] @@ -46,79 +73,87 @@ pub enum PopApiError { Unavailable = 12, /// Root origin is not allowed. RootNotAllowed = 13, - // TODO: make generic and add docs. - UseCaseError(FungiblesError) = 254, DecodingFailed = 255, } -impl FromStatusCode for PopApiError { - fn from_status_code(status_code: u32) -> core::result::Result<(), Self> { - match status_code { - 0 => Ok(()), - _ => Err(convert_to_pop_api_error(status_code)), - } +impl From for StatusCode { + fn from(value: PopApiError) -> Self { + let mut encoded_error = value.encode(); + // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). + encoded_error.resize(4, 0); + StatusCode::from( + u32::decode(&mut &encoded_error[..]).expect("qid, resized to 4 bytes line above"), + ) } } -// `pub` because it is used in `runtime/devnet/src/extensions/tests/mod.rs`'s test: -// `dispatch_error_to_status_code_to_pop_api_error_works` -// -// This function converts a given `status_code` (u32) into a `PopApiError`. First it encodes the -// status code into a 4-byte array and checks for unknown nested errors. If decoding into -// `PopApiError` fails (e.g. a breaking change in the `DispatchError`), it handles the error by -// converting it to the `Other` variant by shifting each byte one position forward (the last byte is -// not used for anything)and setting the first byte to 0. If decoding succeeds, it checks if the -// error is of the `Module` variant and performs any necessary conversion based on the use case. -pub fn convert_to_pop_api_error(status_code: u32) -> PopApiError { - let mut encoded: [u8; 4] = - status_code.encode().try_into().expect("qid u32 always encodes to 4 bytes"); - encoded = check_for_unknown_nesting(encoded); - let error = match PopApiError::decode(&mut &encoded[..]) { - Err(_) => { - encoded[3] = encoded[2]; - encoded[2] = encoded[1]; - encoded[1] = encoded[0]; - encoded[0] = 0; - PopApiError::decode(&mut &encoded[..]).unwrap().into() - }, - Ok(error) => { - if let crate::PopApiError::Module { index, error } = error { - // TODO: make generic. - convert_to_fungibles_error(index, error) - } else { - error - } - }, - }; - ink::env::debug_println!("PopApiError: {:?}", error); - error +impl From for PopApiError { + // `pub` because it is used in `runtime/devnet/src/extensions/tests/mod.rs`'s test: + // `dispatch_error_to_status_code_to_pop_api_error_works` + // + // This function converts a given `status_code` (u32) into a `PopApiError`. + fn from(value: StatusCode) -> Self { + let encoded: [u8; 4] = value.0.to_le_bytes(); + PopApiError::decode(&mut &encoded[..]).unwrap_or(DecodingFailed) + } } -// If a unknown nested variant of the `DispatchError` is detected meaning any of the subsequent -// bytes are non-zero (e.g. breaking change in the DispatchError), the error needs to be converted -// into `PopApiError::Other`'s encoded value. This conversion is done by shifting the bytes one -// position forward (the last byte is discarded as it is not being used) and replacing the first -// byte with the `Other` encoded value (0u8). This ensures that the error is correctly categorized -// as an `Other` variant. -fn check_for_unknown_nesting(encoded_error: [u8; 4]) -> [u8; 4] { - if non_nested_pop_api_errors().contains(&encoded_error[0]) - && encoded_error[1..].iter().any(|x| *x != 0u8) - { - [0u8, encoded_error[0], encoded_error[1], encoded_error[2]] - } else if singular_nested_pop_api_errors().contains(&encoded_error[0]) +// If an unknown nested variant of the `DispatchError` is detected (i.e., any of the subsequent +// bytes are non-zero, indicating a breaking change in the `DispatchError`), the error needs to be +// converted into the encoded value of `PopApiError::Other`. This conversion is performed by +// shifting the bytes one position forward (discarding the last byte as it is not used) and setting +// the first byte to the encoded value of `Other` (0u8). This ensures the error is correctly +// categorized as an `Other` variant. +// +// Byte layout explanation: +// - Byte 0: PopApiError +// - Byte 1: +// - Must be zero for `UNIT_ERRORS`. +// - Represents the nested error in `SINGLE_NESTED_ERRORS`. +// - Represents the first level of nesting in `DOUBLE_NESTED_ERRORS`. +// - Byte 2: +// - Represents the second level of nesting in `DOUBLE_NESTED_ERRORS`. +// - Byte 3: +// - Unused or represents further nested information. +// +// This mechanism ensures backward compatibility by correctly categorizing any unknown nested errors +// into the `Other` variant, thus preventing issues caused by new or unexpected error formats. +pub(crate) fn convert_unknown_nested_errors(encoded_error: &mut [u8; 4]) { + // Converts single nested errors that are known to the Pop API as unit errors into `Other`. + if UNIT_ERRORS.contains(&encoded_error[0]) && encoded_error[1..].iter().any(|x| *x != 0u8) { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; + // Converts double nested errors that are known to the Pop API as single nested errors into + // `Other`. + } else if SINGLE_NESTED_ERRORS.contains(&encoded_error[0]) && encoded_error[2..].iter().any(|x| *x != 0u8) { - [0u8, encoded_error[0], encoded_error[1], encoded_error[2]] - } else { - encoded_error + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; + } else if DOUBLE_NESTED_ERRORS.contains(&encoded_error[0]) + && encoded_error[3..].iter().any(|x| *x != 0u8) + { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; } } -impl From for PopApiError { - fn from(_: scale::Error) -> Self { - DecodingFailed +pub(crate) fn convert_unknown_errors(encoded_error: &mut [u8; 4]) { + let all_errors = [ + UNIT_ERRORS.as_slice(), + SINGLE_NESTED_ERRORS.as_slice(), + DOUBLE_NESTED_ERRORS.as_slice(), + // `DecodingFailed`. + &[255u8], + ] + .concat(); + if !all_errors.contains(&encoded_error[0]) { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; } + convert_unknown_nested_errors(encoded_error); } + #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum TokenError { @@ -165,91 +200,129 @@ pub enum TransactionalError { NoLayer, } -fn singular_nested_pop_api_errors() -> [u8; 3] { - const TOKEN_ERROR: u8 = 7; - const ARITHMETIC_ERROR: u8 = 8; - const TRANSACTION_ERROR: u8 = 9; - [TOKEN_ERROR, ARITHMETIC_ERROR, TRANSACTION_ERROR] -} +// Unit `DispatchError` variants (variant: index): +// - CannotLookup: 1, +// - BadOrigin: 2, +// - ConsumerRemaining: 4, +// - NoProviders: 5, +// - TooManyConsumers: 6, +// - Exhausted: 10, +// - Corruption: 11, +// - Unavailable: 12, +// - RootNotAllowed: 13, +const UNIT_ERRORS: [u8; 9] = [1, 2, 4, 5, 6, 10, 11, 12, 13]; -fn non_nested_pop_api_errors() -> [u8; 9] { - const CANNOT_LOOKUP: u8 = 1; - const BAD_ORIGIN: u8 = 2; - const CONSUMER_REMAINING: u8 = 4; - const NO_PROVIDERS: u8 = 5; - const TOO_MANY_CONSUMERS: u8 = 6; - const EXHAUSTED: u8 = 10; - const CORRUPTION: u8 = 11; - const UNAVAILABLE: u8 = 12; - const ROOT_NOT_ALLOWED: u8 = 13; - [ - CANNOT_LOOKUP, - BAD_ORIGIN, - CONSUMER_REMAINING, - NO_PROVIDERS, - TOO_MANY_CONSUMERS, - EXHAUSTED, - CORRUPTION, - UNAVAILABLE, - ROOT_NOT_ALLOWED, - ] -} +// Single nested `DispatchError` variants (variant: index): +// - Token: 3, +// - Arithmetic: 8, +// - Transaction: 9, +const SINGLE_NESTED_ERRORS: [u8; 3] = [7, 8, 9]; -#[test] -fn u32_always_encodes_to_4_bytes() { - assert_eq!(0u32.encode().len(), 4); - assert_eq!(u32::MAX.encode().len(), 4); -} +const DOUBLE_NESTED_ERRORS: [u8; 1] = [3]; -// If decoding failed the encoded value is converted to the `PopApiError::Other`. This handles -// unknown errors coming from the runtime. This could happen if a contract is not upgraded to the -// latest Pop API version. -#[test] -fn test_non_existing_pop_api_errors() { - let encoded_error = [7u8, 100u8, 0u8, 0u8]; - let status_code = u32::decode(&mut &encoded_error[..]).unwrap(); - let pop_api_error = ::from_status_code(status_code); - assert_eq!(Err(Other { dispatch_error_index: 7, error_index: 100, error: 0 }), pop_api_error); -} +#[cfg(test)] +mod tests { + use super::*; + use crate::error::{ArithmeticError::*, TokenError::*, TransactionalError::*}; + + #[test] + fn u32_always_encodes_to_4_bytes() { + assert_eq!(0u32.encode().len(), 4); + assert_eq!(u32::MAX.encode().len(), 4); + } -// If the encoded value indicates a nested PopApiError which is not handled by the Pop API version, -// the encoded value is converted into `PopApiError::Other`. -#[test] -fn check_for_unknown_nested_pop_api_errors_works() { - for &error_code in &non_nested_pop_api_errors() { - let encoded_error = [error_code, 1, 2, 3]; - let result = check_for_unknown_nesting(encoded_error); - let decoded = PopApiError::decode(&mut &result[..]).unwrap(); + // Decodes into `StatusCode(u32)` and converts it into the `PopApiError`. + fn into_pop_api_error(encoded_error: [u8; 4]) -> PopApiError { + let status_code = + StatusCode::from_status_code(u32::decode(&mut &encoded_error[..]).unwrap()) + .unwrap_err(); + status_code.into() + } + // Tests for the `From` implementation for `PopApiError`. + // + // If the encoded value indicates a nested `PopApiError` which is not handled by the Pop API + // version, the encoded value is converted into `PopApiError::Other`. + #[test] + fn test_unit_pop_api_error_variants() { + let errors = vec![ + CannotLookup, + BadOrigin, + ConsumerRemaining, + NoProviders, + TooManyConsumers, + Exhausted, + Corruption, + Unavailable, + RootNotAllowed, + ]; + for (i, &error_code) in UNIT_ERRORS.iter().enumerate() { + assert_eq!(into_pop_api_error([error_code, 0, 0, 0]), errors[i]); + assert_eq!( + into_pop_api_error([error_code, 1, 0, 0]), + Other { dispatch_error_index: error_code, error_index: 1, error: 0 }, + ); + assert_eq!( + into_pop_api_error([error_code, 1, 1, 0]), + Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, + ); + assert_eq!( + into_pop_api_error([error_code, 1, 1, 1]), + Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, + ); + } + } + + #[test] + fn test_single_nested_pop_api_error_variants() { + let errors = vec![ + [Token(FundsUnavailable), Token(OnlyProvider)], + [Arithmetic(Underflow), Arithmetic(Overflow)], + [Transactional(LimitReached), Transactional(NoLayer)], + ]; + for (i, &error_code) in SINGLE_NESTED_ERRORS.iter().enumerate() { + assert_eq!(into_pop_api_error([error_code, 0, 0, 0]), errors[i][0]); + assert_eq!(into_pop_api_error([error_code, 1, 0, 0]), errors[i][1]); + assert_eq!( + into_pop_api_error([error_code, 1, 1, 0]), + Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, + ); + assert_eq!( + into_pop_api_error([error_code, 1, 1, 1]), + Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, + ); + } + } + + #[test] + fn test_double_nested_pop_api_error_variants() { + assert_eq!(into_pop_api_error([3, 0, 0, 0]), Module { index: 0, error: 0 }); + assert_eq!(into_pop_api_error([3, 1, 0, 0]), Module { index: 1, error: 0 }); + assert_eq!(into_pop_api_error([3, 1, 1, 0]), Module { index: 1, error: 1 }); + // TODO: doesn't make sense. assert_eq!( - decoded, - Other { dispatch_error_index: error_code, error_index: 1, error: 2 }, - "Failed for error code: {}", - error_code + into_pop_api_error([3, 1, 1, 1]), + Other { dispatch_error_index: 3, error_index: 1, error: 1 }, ); } - for &error_code in &singular_nested_pop_api_errors() { - let encoded_error = [error_code, 1, 2, 3]; - let result = check_for_unknown_nesting(encoded_error); - let decoded = PopApiError::decode(&mut &result[..]).unwrap(); + #[test] + fn test_decoding_failed() { + assert_eq!(into_pop_api_error([255, 0, 0, 0]), DecodingFailed); + assert_eq!(into_pop_api_error([255, 255, 0, 0]), DecodingFailed); + assert_eq!(into_pop_api_error([255, 255, 255, 0]), DecodingFailed); + assert_eq!(into_pop_api_error([255, 255, 255, 255]), DecodingFailed); + } + + #[test] + fn test_random_encoded_values() { + assert_eq!( + into_pop_api_error([100, 100, 100, 100]), + Other { dispatch_error_index: 100, error_index: 100, error: 100 } + ); assert_eq!( - decoded, - Other { dispatch_error_index: error_code, error_index: 1, error: 2 }, - "Failed for error code: {}", - error_code + into_pop_api_error([200, 200, 200, 200]), + Other { dispatch_error_index: 200, error_index: 200, error: 200 } ); } } - -// This test ensures that a non-zero value for unused bytes does not interfere with the correct -// decoding of the error. It verifies that even with an additional byte, the errors are correctly -// decoded and represented in its correct variant. -#[test] -fn extra_byte_does_not_mess_up_decoding() { - // Module error - let encoded_error = [3u8, 4u8, 5u8, 6u8]; - let status_code = u32::decode(&mut &encoded_error[..]).unwrap(); - let pop_api_error = ::from_status_code(status_code); - assert_eq!(Err(Module { index: 4, error: 5 }), pop_api_error); -} diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index d00f1e9a..90c81998 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,12 +1,19 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -use crate::error::PopApiError; use ink::{prelude::vec::Vec, ChainExtensionInstance}; -use primitives::{cross_chain::*, storage_keys::*, AccountId as AccountId32}; -use scale::Encode; pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; -use v0::RuntimeCall; -pub use v0::{assets, balances, cross_chain, nfts, relay_chain_block_number, state}; + +use crate::error::{PopApiError, StatusCode}; +use primitives::{storage_keys::*, AccountId as AccountId32}; +#[cfg(feature = "assets")] +pub use v0::assets; +#[cfg(feature = "balances")] +pub use v0::balances; +#[cfg(feature = "cross-chain")] +pub use v0::cross_chain; +#[cfg(feature = "nfts")] +pub use v0::nfts; +use v0::{state, RuntimeCall}; pub mod error; pub mod primitives; @@ -15,11 +22,7 @@ pub mod v0; type AccountId = AccountId32; // TODO: do the same as the AccountId above and check expanded macro code. type Balance = ::Balance; -type BlockNumber = ::BlockNumber; -type StringLimit = u32; -type MaxTips = u32; - -pub type Result = core::result::Result; +pub type Result = core::result::Result; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] @@ -40,7 +43,7 @@ impl ink::env::Environment for Environment { #[ink::chain_extension(extension = 909)] pub trait PopApi { - type ErrorCode = PopApiError; + type ErrorCode = StatusCode; #[ink(function = 0)] #[allow(private_interfaces)] @@ -50,6 +53,7 @@ pub trait PopApi { #[allow(private_interfaces)] fn read_state(key: RuntimeStateKeys) -> Result>; + #[cfg(feature = "cross-chain")] #[ink(function = 2)] #[allow(private_interfaces)] fn send_xcm(xcm: CrossChainMessage) -> Result<()>; @@ -67,6 +71,7 @@ fn read_state(key: RuntimeStateKeys) -> Result> { .read_state(key) } +#[cfg(feature = "cross-chain")] fn send_xcm(xcm: CrossChainMessage) -> Result<()> { <::ChainExtension as ChainExtensionInstance>::instantiate( ) diff --git a/pop-api/src/v0/assets/use_cases/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs similarity index 86% rename from pop-api/src/v0/assets/use_cases/fungibles.rs rename to pop-api/src/v0/assets/fungibles.rs index 4af5d97e..b1bb86a7 100644 --- a/pop-api/src/v0/assets/use_cases/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -1,12 +1,8 @@ -use crate::{ - assets::pallets, - error::PopApiError::{self, *}, - AccountId, Balance, *, -}; +use crate::{assets, primitives::AssetId, AccountId, Balance, MultiAddress, StatusCode}; use ink::prelude::vec::Vec; -use primitives::AssetId; +use scale::Encode; -type Result = core::result::Result; +type Result = core::result::Result; /// Local Fungibles: /// 1. PSP-22 Interface @@ -31,7 +27,7 @@ type Result = core::result::Result; /// # Returns /// The total supply of the token, or an error if the operation fails. pub fn total_supply(id: AssetId) -> Result { - pallets::assets::total_supply(id) + assets::total_supply(id) } /// Returns the account balance for the specified `owner` for a given asset ID. Returns `0` if @@ -44,7 +40,7 @@ pub fn total_supply(id: AssetId) -> Result { /// # Returns /// The balance of the specified account, or an error if the operation fails. pub fn balance_of(id: AssetId, owner: AccountId) -> Result { - pallets::assets::balance_of(id, owner) + assets::balance_of(id, owner) } /// Returns the amount which `spender` is still allowed to withdraw from `owner` for a given @@ -58,7 +54,7 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Result { /// # Returns /// The remaining allowance, or an error if the operation fails. pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { - pallets::assets::allowance(id, owner, spender) + assets::allowance(id, owner, spender) } /// Transfers `value` amount of tokens from the caller's account to account `to`, with additional @@ -76,7 +72,7 @@ pub fn transfer( to: impl Into>, value: Balance, ) -> Result<()> { - pallets::assets::transfer(id, to, value) + assets::transfer(id, to, value) } /// Transfers `value` tokens on behalf of `from` to account `to` with additional `data` @@ -99,9 +95,9 @@ pub fn transfer_from( _data: &[u8], ) -> Result<()> { match (from, to) { - (None, Some(to)) => pallets::assets::mint(id, to, value), - (Some(from), None) => pallets::assets::burn(id, from, value), - (Some(from), Some(to)) => pallets::assets::transfer_approved(id, from, to, value), + (None, Some(to)) => assets::mint(id, to, value), + (Some(from), None) => assets::burn(id, from, value), + (Some(from), Some(to)) => assets::transfer_approved(id, from, to, value), _ => Ok(()), } } @@ -232,7 +228,7 @@ pub fn create( admin: impl Into>, min_balance: Balance, ) -> Result<()> { - pallets::assets::create(id, admin, min_balance) + assets::create(id, admin, min_balance) } /// Start the process of destroying a token with a given asset ID. @@ -295,7 +291,7 @@ pub fn create( /// # Returns /// Returns `Ok(())` if successful, or an error if the operation fails. pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { - pallets::assets::set_metadata(id, name, symbol, decimals) + assets::set_metadata(id, name, symbol, decimals) } /// Clear the metadata for a token with a given asset ID. @@ -312,12 +308,13 @@ pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) - // } pub fn asset_exists(id: AssetId) -> Result { - pallets::assets::asset_exists(id) + assets::asset_exists(id) } #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum FungiblesError { + Other(StatusCode), /// The asset is not live; either frozen or being destroyed. AssetNotLive, /// Not enough allowance to fulfill a request is available. @@ -341,32 +338,21 @@ pub enum FungiblesError { NoBalance, } -// TODO: make generic. -pub(crate) fn convert_to_fungibles_error(index: u8, error: u8) -> PopApiError { - match index { - 10 => balance_into(error), - 52 => assets_into(error), - _ => Module { index, error }, - } -} - -fn balance_into(error: u8) -> PopApiError { - match error { - 2 => UseCaseError(FungiblesError::NoBalance), - _ => Module { index: 10, error }, - } -} - -fn assets_into(error: u8) -> PopApiError { - match error { - 0 => UseCaseError(FungiblesError::InsufficientBalance), - 1 => UseCaseError(FungiblesError::NoAccount), - 2 => UseCaseError(FungiblesError::NoPermission), - 3 => UseCaseError(FungiblesError::Unknown), - 5 => UseCaseError(FungiblesError::InUse), - 7 => UseCaseError(FungiblesError::MinBalanceZero), - 10 => UseCaseError(FungiblesError::InsufficientAllowance), - 16 => UseCaseError(FungiblesError::AssetNotLive), - _ => Module { index: 52, error }, +impl From for FungiblesError { + fn from(value: StatusCode) -> Self { + let encoded = value.0.to_le_bytes(); + match encoded { + // Balances. + [3, 10, 2, _] => FungiblesError::NoBalance, + // Assets. + [3, 52, 0, _] => FungiblesError::NoAccount, + [3, 52, 1, _] => FungiblesError::NoPermission, + [3, 52, 2, _] => FungiblesError::Unknown, + [3, 52, 3, _] => FungiblesError::InUse, + [3, 52, 5, _] => FungiblesError::MinBalanceZero, + [3, 52, 7, _] => FungiblesError::InsufficientAllowance, + [3, 52, 10, _] => FungiblesError::AssetNotLive, + _ => FungiblesError::Other(value), + } } } diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 736ccc0e..4ce68219 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,2 +1,494 @@ -pub(crate) mod pallets; -pub mod use_cases; +#![allow(dead_code)] + +use crate::{Balance, RuntimeCall, *}; +use ink::prelude::vec::Vec; +use primitives::{AssetId, MultiAddress}; +use scale::{Compact, Encode}; + +pub mod fungibles; + +type Result = core::result::Result; + +/// [Pallet Assets](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/lib.rs): +/// 1. Dispatchables +/// 2. Read state functions +/// +/// 1. Dispatchables within pallet assets (TrustBackedAssets instance) that can be used via the pop api on Pop Network: +/// - create +/// - start_destroy +/// - destroy_accounts +/// - destroy_approvals +/// - finish_destroy +/// - mint +/// - burn +/// - transfer +/// - transfer_keep_alive +/// - force_transfer +/// - freeze +/// - thaw +/// - freeze_asset +/// - thaw_asset +/// - transfer_ownership +/// - set_team +/// - set_metadata +/// - clear_metadata +/// - approve_transfer +/// - cancel_approval +/// - force_cancel_approval +/// - transfer_approved +/// - touch +/// - refund +/// - set_min_balance +/// - touch_other +/// - refund_other +/// - block + +/// Issue a new class of fungible assets from a public origin. +pub(crate) fn create( + id: AssetId, + admin: impl Into>, + min_balance: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Create { + id: id.into(), + admin: admin.into(), + min_balance, + })) +} + +/// Start the process of destroying a fungible asset class. +pub(crate) fn start_destroy(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { id: id.into() })) +} + +/// Destroy all accounts associated with a given asset. +pub(crate) fn destroy_accounts(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { id: id.into() })) +} + +/// Destroy all approvals associated with a given asset up to the max (see runtime configuration Assets `RemoveItemsLimit`). +pub(crate) fn destroy_approvals(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { id: id.into() })) +} + +/// Complete destroying asset and unreserve currency. +pub(crate) fn finish_destroy(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { id: id.into() })) +} + +/// Mint assets of a particular class. +pub(crate) fn mint( + id: AssetId, + beneficiary: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Mint { + id: id.into(), + beneficiary: beneficiary.into(), + amount: Compact(amount), + })) +} + +/// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`. +pub(crate) fn burn( + id: AssetId, + who: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Burn { + id: id.into(), + who: who.into(), + amount: Compact(amount), + })) +} + +/// Move some assets from the sender account to another. +pub(crate) fn transfer( + id: AssetId, + target: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { + id: id.into(), + target: target.into(), + amount: Compact(amount), + })) +} + +/// Move some assets from the sender account to another, keeping the sender account alive. +pub(crate) fn transfer_keep_alive( + id: AssetId, + target: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { + id: id.into(), + target: target.into(), + amount: Compact(amount), + })) +} + +/// Move some assets from one account to another. Sender should be the Admin of the asset `id`. +pub(crate) fn force_transfer( + id: AssetId, + source: impl Into>, + dest: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ForceTransfer { + id: id.into(), + source: source.into(), + dest: dest.into(), + amount: Compact(amount), + })) +} + +/// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` +/// must already exist as an entry in `Account`s of the asset. If you want to freeze an +/// account that does not have an entry, use `touch_other` first. +pub(crate) fn freeze(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Freeze { id: id.into(), who: who.into() })) +} + +/// Allow unprivileged transfers to and from an account again. +pub(crate) fn thaw(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Thaw { id: id.into(), who: who.into() })) +} + +/// Disallow further unprivileged transfers for the asset class. +pub(crate) fn freeze_asset(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::FreezeAsset { id: id.into() })) +} + +/// Allow unprivileged transfers for the asset again. +pub(crate) fn thaw_asset(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ThawAsset { id: id.into() })) +} + +/// Change the Owner of an asset. +pub(crate) fn transfer_ownership( + id: AssetId, + owner: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferOwnership { + id: id.into(), + owner: owner.into(), + })) +} + +/// Change the Issuer, Admin and Freezer of an asset. +pub(crate) fn set_team( + id: AssetId, + issuer: impl Into>, + admin: impl Into>, + freezer: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::SetTeam { + id: id.into(), + issuer: issuer.into(), + admin: admin.into(), + freezer: freezer.into(), + })) +} + +/// Set the metadata for an asset. +pub(crate) fn set_metadata( + id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::SetMetadata { id: id.into(), name, symbol, decimals })) +} + +/// Clear the metadata for an asset. +pub(crate) fn clear_metadata(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { id: id.into() })) +} + +/// Approve an amount of asset for transfer by a delegated third-party account. +pub(crate) fn approve_transfer( + id: AssetId, + delegate: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { + id: id.into(), + delegate: delegate.into(), + amount: Compact(amount), + })) +} + +/// Cancel all of some asset approved for delegated transfer by a third-party account. +pub(crate) fn cancel_approval( + id: AssetId, + delegate: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { + id: id.into(), + delegate: delegate.into(), + })) +} + +/// Cancel all of some asset approved for delegated transfer by a third-party account. +pub(crate) fn force_cancel_approval( + id: AssetId, + owner: impl Into>, + delegate: impl Into>, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::ForceCancelApproval { + id: id.into(), + owner: owner.into(), + delegate: delegate.into(), + })) +} + +/// Transfer some asset balance from a previously delegated account to some third-party +/// account. +pub(crate) fn transfer_approved( + id: AssetId, + owner: impl Into>, + destination: impl Into>, + amount: Balance, +) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { + id: id.into(), + owner: owner.into(), + destination: destination.into(), + amount: Compact(amount), + })) +} + +/// Create an asset account for non-provider assets. +pub(crate) fn touch(id: AssetId) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Touch { id: id.into() })) +} + +/// Return the deposit (if any) of an asset account or a consumer reference (if any) of an +/// account. +pub(crate) fn refund(id: AssetId, allow_burn: bool) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Refund { id: id.into(), allow_burn })) +} + +/// Sets the minimum balance of an asset. +pub(crate) fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::SetMinBalance { + id: id.into(), + min_balance: Compact(min_balance), + })) +} + +/// Create an asset account for `who`. +pub(crate) fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::TouchOther { id: id.into(), who: who.into() })) +} + +/// Return the deposit (if any) of a target asset account. Useful if you are the depositor. +pub(crate) fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::RefundOther { id: id.into(), who: who.into() })) +} + +/// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. +pub(crate) fn block(id: AssetId, who: impl Into>) -> Result<()> { + dispatch(RuntimeCall::Assets(AssetsCall::Block { id: id.into(), who: who.into() })) +} + +/// 2. Read state functions +/// - total_supply +/// - + +pub(crate) fn total_supply(id: AssetId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))).into() +} + +pub(crate) fn balance_of(id: AssetId, owner: AccountId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))).into() +} + +pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))).into() +} +pub(crate) fn asset_exists(id: AssetId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))).into() +} + +// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected +// to be compact encoded. The pop api handles that for the developer. +// +// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development +// +// Asset id that is compact encoded. +type AssetIdParameter = Compact; +// Balance amount that is compact encoded. +type BalanceParameter = Compact; + +#[derive(Encode)] +pub(crate) enum AssetsCall { + #[codec(index = 0)] + Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, + #[codec(index = 2)] + StartDestroy { id: AssetIdParameter }, + #[codec(index = 3)] + DestroyAccounts { id: AssetIdParameter }, + #[codec(index = 4)] + DestroyApprovals { id: AssetIdParameter }, + #[codec(index = 5)] + FinishDestroy { id: AssetIdParameter }, + #[codec(index = 6)] + Mint { + id: AssetIdParameter, + beneficiary: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 7)] + Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, + #[codec(index = 8)] + Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, + #[codec(index = 9)] + TransferKeepAlive { + id: AssetIdParameter, + target: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 10)] + ForceTransfer { + id: AssetIdParameter, + source: MultiAddress, + dest: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 11)] + Freeze { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 12)] + Thaw { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 13)] + FreezeAsset { id: AssetIdParameter }, + #[codec(index = 14)] + ThawAsset { id: AssetIdParameter }, + #[codec(index = 15)] + TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, + #[codec(index = 16)] + SetTeam { + id: AssetIdParameter, + issuer: MultiAddress, + admin: MultiAddress, + freezer: MultiAddress, + }, + #[codec(index = 17)] + SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, + #[codec(index = 18)] + ClearMetadata { id: AssetIdParameter }, + #[codec(index = 22)] + ApproveTransfer { + id: AssetIdParameter, + delegate: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 23)] + CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, + #[codec(index = 24)] + ForceCancelApproval { + id: AssetIdParameter, + owner: MultiAddress, + delegate: MultiAddress, + }, + #[codec(index = 25)] + TransferApproved { + id: AssetIdParameter, + owner: MultiAddress, + destination: MultiAddress, + amount: BalanceParameter, + }, + #[codec(index = 26)] + Touch { id: AssetIdParameter }, + #[codec(index = 27)] + Refund { id: AssetIdParameter, allow_burn: bool }, + #[codec(index = 28)] + SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, + #[codec(index = 29)] + TouchOther { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 30)] + RefundOther { id: AssetIdParameter, who: MultiAddress }, + #[codec(index = 31)] + Block { id: AssetIdParameter, who: MultiAddress }, +} + +// TODO: Not being used atm but necessary if we want to provide access to the +// rest of the pallet, outside of the use cases. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum AssetsError { + /// Account balance must be greater than or equal to the transfer amount. + BalanceLow, + /// The account to alter does not exist. + NoAccount, + /// The signing account has no permission to do the operation. + NoPermission, + /// The given asset ID is unknown. + Unknown, + /// The origin account is frozen. + Frozen, + /// The asset ID is already taken. + InUse, + /// Invalid witness data given. + BadWitness, + /// Minimum balance should be non-zero. + MinBalanceZero, + /// Unable to increment the consumer reference counters on the account. Either no provider + /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one + /// fewer then the maximum number of consumers has been reached. + UnavailableConsumer, + /// Invalid metadata given. + BadMetadata, + /// No approval exists that would allow the transfer. + Unapproved, + /// The source account would not survive the transfer and it needs to stay alive. + WouldDie, + /// The asset-account already exists. + AlreadyExists, + /// The asset-account doesn't have an associated deposit. + NoDeposit, + /// The operation would result in funds being burned. + WouldBurn, + /// The asset is a live asset and is actively being used. Usually emit for operations such + /// as `start_destroy` which require the asset to be in a destroying state. + LiveAsset, + /// The asset is not live, and likely being destroyed. + AssetNotLive, + /// The asset status is not the expected status. + IncorrectStatus, + /// The asset should be frozen before the given operation. + NotFrozen, + /// Callback action resulted in error. + CallbackFailed, +} + +impl TryFrom for AssetsError { + type Error = PopApiError; + + fn try_from(status_code: u32) -> core::result::Result { + use AssetsError::*; + match status_code { + 0 => Ok(BalanceLow), + 1 => Ok(NoAccount), + 2 => Ok(NoPermission), + 3 => Ok(Unknown), + 4 => Ok(Frozen), + 5 => Ok(InUse), + 6 => Ok(BadWitness), + 7 => Ok(MinBalanceZero), + 8 => Ok(UnavailableConsumer), + 9 => Ok(BadMetadata), + 10 => Ok(Unapproved), + 11 => Ok(WouldDie), + 12 => Ok(AlreadyExists), + 13 => Ok(NoDeposit), + 14 => Ok(WouldBurn), + 15 => Ok(LiveAsset), + 16 => Ok(AssetNotLive), + 17 => Ok(IncorrectStatus), + 18 => Ok(NotFrozen), + _ => todo!(), + } + } +} diff --git a/pop-api/src/v0/assets/pallets/assets.rs b/pop-api/src/v0/assets/pallets/assets.rs deleted file mode 100644 index 87695b81..00000000 --- a/pop-api/src/v0/assets/pallets/assets.rs +++ /dev/null @@ -1,492 +0,0 @@ -#![allow(dead_code)] - -use crate::{Balance, RuntimeCall, *}; -use ink::prelude::vec::Vec; -use primitives::{AssetId, MultiAddress}; -use scale::{Compact, Encode}; - -type Result = core::result::Result; - -/// [Pallet Assets](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/lib.rs): -/// 1. Dispatchables -/// 2. Read state functions -/// -/// 1. Dispatchables within pallet assets (TrustBackedAssets instance) that can be used via the pop api on Pop Network: -/// - create -/// - start_destroy -/// - destroy_accounts -/// - destroy_approvals -/// - finish_destroy -/// - mint -/// - burn -/// - transfer -/// - transfer_keep_alive -/// - force_transfer -/// - freeze -/// - thaw -/// - freeze_asset -/// - thaw_asset -/// - transfer_ownership -/// - set_team -/// - set_metadata -/// - clear_metadata -/// - approve_transfer -/// - cancel_approval -/// - force_cancel_approval -/// - transfer_approved -/// - touch -/// - refund -/// - set_min_balance -/// - touch_other -/// - refund_other -/// - block - -/// Issue a new class of fungible assets from a public origin. -pub(crate) fn create( - id: AssetId, - admin: impl Into>, - min_balance: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Create { - id: id.into(), - admin: admin.into(), - min_balance, - })) -} - -/// Start the process of destroying a fungible asset class. -pub(crate) fn start_destroy(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { id: id.into() })) -} - -/// Destroy all accounts associated with a given asset. -pub(crate) fn destroy_accounts(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { id: id.into() })) -} - -/// Destroy all approvals associated with a given asset up to the max (see runtime configuration Assets `RemoveItemsLimit`). -pub(crate) fn destroy_approvals(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { id: id.into() })) -} - -/// Complete destroying asset and unreserve currency. -pub(crate) fn finish_destroy(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { id: id.into() })) -} - -/// Mint assets of a particular class. -pub(crate) fn mint( - id: AssetId, - beneficiary: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Mint { - id: id.into(), - beneficiary: beneficiary.into(), - amount: Compact(amount), - })) -} - -/// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`. -pub(crate) fn burn( - id: AssetId, - who: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Burn { - id: id.into(), - who: who.into(), - amount: Compact(amount), - })) -} - -/// Move some assets from the sender account to another. -pub(crate) fn transfer( - id: AssetId, - target: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { - id: id.into(), - target: target.into(), - amount: Compact(amount), - })) -} - -/// Move some assets from the sender account to another, keeping the sender account alive. -pub(crate) fn transfer_keep_alive( - id: AssetId, - target: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { - id: id.into(), - target: target.into(), - amount: Compact(amount), - })) -} - -/// Move some assets from one account to another. Sender should be the Admin of the asset `id`. -pub(crate) fn force_transfer( - id: AssetId, - source: impl Into>, - dest: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ForceTransfer { - id: id.into(), - source: source.into(), - dest: dest.into(), - amount: Compact(amount), - })) -} - -/// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` -/// must already exist as an entry in `Account`s of the asset. If you want to freeze an -/// account that does not have an entry, use `touch_other` first. -pub(crate) fn freeze(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Freeze { id: id.into(), who: who.into() })) -} - -/// Allow unprivileged transfers to and from an account again. -pub(crate) fn thaw(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Thaw { id: id.into(), who: who.into() })) -} - -/// Disallow further unprivileged transfers for the asset class. -pub(crate) fn freeze_asset(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::FreezeAsset { id: id.into() })) -} - -/// Allow unprivileged transfers for the asset again. -pub(crate) fn thaw_asset(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ThawAsset { id: id.into() })) -} - -/// Change the Owner of an asset. -pub(crate) fn transfer_ownership( - id: AssetId, - owner: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferOwnership { - id: id.into(), - owner: owner.into(), - })) -} - -/// Change the Issuer, Admin and Freezer of an asset. -pub(crate) fn set_team( - id: AssetId, - issuer: impl Into>, - admin: impl Into>, - freezer: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::SetTeam { - id: id.into(), - issuer: issuer.into(), - admin: admin.into(), - freezer: freezer.into(), - })) -} - -/// Set the metadata for an asset. -pub(crate) fn set_metadata( - id: AssetId, - name: Vec, - symbol: Vec, - decimals: u8, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::SetMetadata { id: id.into(), name, symbol, decimals })) -} - -/// Clear the metadata for an asset. -pub(crate) fn clear_metadata(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { id: id.into() })) -} - -/// Approve an amount of asset for transfer by a delegated third-party account. -pub(crate) fn approve_transfer( - id: AssetId, - delegate: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { - id: id.into(), - delegate: delegate.into(), - amount: Compact(amount), - })) -} - -/// Cancel all of some asset approved for delegated transfer by a third-party account. -pub(crate) fn cancel_approval( - id: AssetId, - delegate: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { - id: id.into(), - delegate: delegate.into(), - })) -} - -/// Cancel all of some asset approved for delegated transfer by a third-party account. -pub(crate) fn force_cancel_approval( - id: AssetId, - owner: impl Into>, - delegate: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ForceCancelApproval { - id: id.into(), - owner: owner.into(), - delegate: delegate.into(), - })) -} - -/// Transfer some asset balance from a previously delegated account to some third-party -/// account. -pub(crate) fn transfer_approved( - id: AssetId, - owner: impl Into>, - destination: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { - id: id.into(), - owner: owner.into(), - destination: destination.into(), - amount: Compact(amount), - })) -} - -/// Create an asset account for non-provider assets. -pub(crate) fn touch(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Touch { id: id.into() })) -} - -/// Return the deposit (if any) of an asset account or a consumer reference (if any) of an -/// account. -pub(crate) fn refund(id: AssetId, allow_burn: bool) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Refund { id: id.into(), allow_burn })) -} - -/// Sets the minimum balance of an asset. -pub(crate) fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::SetMinBalance { - id: id.into(), - min_balance: Compact(min_balance), - })) -} - -/// Create an asset account for `who`. -pub(crate) fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TouchOther { id: id.into(), who: who.into() })) -} - -/// Return the deposit (if any) of a target asset account. Useful if you are the depositor. -pub(crate) fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::RefundOther { id: id.into(), who: who.into() })) -} - -/// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. -pub(crate) fn block(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Block { id: id.into(), who: who.into() })) -} - -/// 2. Read state functions -/// - total_supply -/// - - -pub(crate) fn total_supply(id: AssetId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))).into() -} - -pub(crate) fn balance_of(id: AssetId, owner: AccountId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))).into() -} - -pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))).into() -} -pub(crate) fn asset_exists(id: AssetId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))).into() -} - -// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected -// to be compact encoded. The pop api handles that for the developer. -// -// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development -// -// Asset id that is compact encoded. -type AssetIdParameter = Compact; -// Balance amount that is compact encoded. -type BalanceParameter = Compact; - -#[derive(Encode)] -pub(crate) enum AssetsCall { - #[codec(index = 0)] - Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, - #[codec(index = 2)] - StartDestroy { id: AssetIdParameter }, - #[codec(index = 3)] - DestroyAccounts { id: AssetIdParameter }, - #[codec(index = 4)] - DestroyApprovals { id: AssetIdParameter }, - #[codec(index = 5)] - FinishDestroy { id: AssetIdParameter }, - #[codec(index = 6)] - Mint { - id: AssetIdParameter, - beneficiary: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 7)] - Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, - #[codec(index = 8)] - Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, - #[codec(index = 9)] - TransferKeepAlive { - id: AssetIdParameter, - target: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 10)] - ForceTransfer { - id: AssetIdParameter, - source: MultiAddress, - dest: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 11)] - Freeze { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 12)] - Thaw { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 13)] - FreezeAsset { id: AssetIdParameter }, - #[codec(index = 14)] - ThawAsset { id: AssetIdParameter }, - #[codec(index = 15)] - TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, - #[codec(index = 16)] - SetTeam { - id: AssetIdParameter, - issuer: MultiAddress, - admin: MultiAddress, - freezer: MultiAddress, - }, - #[codec(index = 17)] - SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, - #[codec(index = 18)] - ClearMetadata { id: AssetIdParameter }, - #[codec(index = 22)] - ApproveTransfer { - id: AssetIdParameter, - delegate: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 23)] - CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, - #[codec(index = 24)] - ForceCancelApproval { - id: AssetIdParameter, - owner: MultiAddress, - delegate: MultiAddress, - }, - #[codec(index = 25)] - TransferApproved { - id: AssetIdParameter, - owner: MultiAddress, - destination: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 26)] - Touch { id: AssetIdParameter }, - #[codec(index = 27)] - Refund { id: AssetIdParameter, allow_burn: bool }, - #[codec(index = 28)] - SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, - #[codec(index = 29)] - TouchOther { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 30)] - RefundOther { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 31)] - Block { id: AssetIdParameter, who: MultiAddress }, -} - -// TODO: Not being used atm but necessary if we want to provide access to the -// rest of the pallet, outside of the use cases. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum AssetsError { - /// Account balance must be greater than or equal to the transfer amount. - BalanceLow, - /// The account to alter does not exist. - NoAccount, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, - /// The origin account is frozen. - Frozen, - /// The asset ID is already taken. - InUse, - /// Invalid witness data given. - BadWitness, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// Unable to increment the consumer reference counters on the account. Either no provider - /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one - /// fewer then the maximum number of consumers has been reached. - UnavailableConsumer, - /// Invalid metadata given. - BadMetadata, - /// No approval exists that would allow the transfer. - Unapproved, - /// The source account would not survive the transfer and it needs to stay alive. - WouldDie, - /// The asset-account already exists. - AlreadyExists, - /// The asset-account doesn't have an associated deposit. - NoDeposit, - /// The operation would result in funds being burned. - WouldBurn, - /// The asset is a live asset and is actively being used. Usually emit for operations such - /// as `start_destroy` which require the asset to be in a destroying state. - LiveAsset, - /// The asset is not live, and likely being destroyed. - AssetNotLive, - /// The asset status is not the expected status. - IncorrectStatus, - /// The asset should be frozen before the given operation. - NotFrozen, - /// Callback action resulted in error. - CallbackFailed, -} - -impl TryFrom for AssetsError { - type Error = PopApiError; - - fn try_from(status_code: u32) -> core::result::Result { - use AssetsError::*; - match status_code { - 0 => Ok(BalanceLow), - 1 => Ok(NoAccount), - 2 => Ok(NoPermission), - 3 => Ok(Unknown), - 4 => Ok(Frozen), - 5 => Ok(InUse), - 6 => Ok(BadWitness), - 7 => Ok(MinBalanceZero), - 8 => Ok(UnavailableConsumer), - 9 => Ok(BadMetadata), - 10 => Ok(Unapproved), - 11 => Ok(WouldDie), - 12 => Ok(AlreadyExists), - 13 => Ok(NoDeposit), - 14 => Ok(WouldBurn), - 15 => Ok(LiveAsset), - 16 => Ok(AssetNotLive), - 17 => Ok(IncorrectStatus), - 18 => Ok(NotFrozen), - _ => todo!(), - } - } -} diff --git a/pop-api/src/v0/assets/pallets/mod.rs b/pop-api/src/v0/assets/pallets/mod.rs deleted file mode 100644 index 0b8a53a0..00000000 --- a/pop-api/src/v0/assets/pallets/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) mod assets; diff --git a/pop-api/src/v0/assets/use_cases/mod.rs b/pop-api/src/v0/assets/use_cases/mod.rs deleted file mode 100644 index 182590df..00000000 --- a/pop-api/src/v0/assets/use_cases/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod fungibles; diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index 56c3ca72..ae2709e7 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -1,6 +1,8 @@ -use crate::{dispatch, error::PopApiError, primitives::MultiAddress, v0::RuntimeCall, AccountId}; +use crate::{ + dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, PopApiError, StatusCode, +}; -type Result = core::result::Result; +type Result = core::result::Result; pub fn transfer_keep_alive( dest: impl Into>, diff --git a/pop-api/src/v0/cross_chain/mod.rs b/pop-api/src/v0/cross_chain/mod.rs index 1d3c5b7d..583447b1 100644 --- a/pop-api/src/v0/cross_chain/mod.rs +++ b/pop-api/src/v0/cross_chain/mod.rs @@ -1,8 +1,15 @@ pub mod coretime; -use crate::error::PopApiError; +use crate::StatusCode; -type Result = core::result::Result; +type Result = core::result::Result; +type BlockNumber = ::BlockNumber; + +pub fn relay_chain_block_number() -> std::result::Result { + crate::v0::state::read(RuntimeStateKeys::ParachainSystem( + ParachainSystemKeys::LastRelayChainBlockNumber, + )) +} #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] @@ -63,7 +70,7 @@ pub enum Error { } impl TryFrom for Error { - type Error = PopApiError; + type Error = Error; fn try_from(status_code: u32) -> core::result::Result { use Error::*; diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 75bcb878..41574cfb 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -1,24 +1,22 @@ -use crate::{ - primitives::storage_keys::{ParachainSystemKeys, RuntimeStateKeys}, - BlockNumber, PopApiError, -}; - +#[cfg(feature = "assets")] pub mod assets; +#[cfg(feature = "balances")] pub mod balances; +#[cfg(feature = "cross-chain")] pub mod cross_chain; +#[cfg(feature = "nfts")] pub mod nfts; pub mod state; -pub fn relay_chain_block_number() -> Result { - state::read(RuntimeStateKeys::ParachainSystem(ParachainSystemKeys::LastRelayChainBlockNumber)) -} - #[derive(scale::Encode)] pub(crate) enum RuntimeCall { - #[codec(index = 10)] - Balances(balances::BalancesCall), - #[codec(index = 50)] - Nfts(nfts::NftCalls), + // #[codec(index = 10)] + // #[cfg(feature = "balances")] + // Balances(balances::BalancesCall), + // #[codec(index = 50)] + // #[cfg(feature = "nfts")] + // Nfts(nfts::NftCalls), #[codec(index = 52)] - Assets(assets::pallets::assets::AssetsCall), + #[cfg(feature = "assets")] + Assets(assets::AssetsCall), } diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index 2de306a9..1e4406e5 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -1,12 +1,14 @@ use super::RuntimeCall; -use crate::{PopApiError, *}; +use crate::*; use ink::prelude::vec::Vec; use primitives::{ApprovalsLimit, BoundedBTreeMap, KeyLimit, MultiAddress}; pub use primitives::{CollectionId, ItemId}; use scale::Encode; pub use types::*; -type Result = core::result::Result; +type Result = core::result::Result; +type StringLimit = u32; +type MaxTips = u32; /// Issue a new collection of non-fungible items pub fn create( @@ -610,7 +612,7 @@ pub enum Error { } impl TryFrom for Error { - type Error = PopApiError; + type Error = Error; fn try_from(status_code: u32) -> core::result::Result { use Error::*; diff --git a/pop-api/src/v0/state.rs b/pop-api/src/v0/state.rs index 9f5e4c0c..1aca01cf 100644 --- a/pop-api/src/v0/state.rs +++ b/pop-api/src/v0/state.rs @@ -2,5 +2,6 @@ use crate::{primitives::storage_keys::RuntimeStateKeys, read_state, PopApiError} use scale::Decode; pub fn read(key: RuntimeStateKeys) -> crate::Result { - read_state(key).and_then(|v| T::decode(&mut &v[..]).map_err(|_e| PopApiError::DecodingFailed)) + read_state(key) + .and_then(|v| T::decode(&mut &v[..]).map_err(|_e| PopApiError::DecodingFailed.into())) } diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index 46208d8f..daa5457e 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -91,7 +91,7 @@ parachain-info.workspace = true env_logger = "0.11.2" hex = "0.4.3" enumflags2 = "0.7.9" -pop-api = { path = "../../pop-api", default-features = false } +pop-api = { path = "../../pop-api", defeult-features = false, features = ["assets"] } [features] default = ["std"] diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs index 32667d16..b4c6ba84 100644 --- a/runtime/devnet/src/extensions.rs +++ b/runtime/devnet/src/extensions.rs @@ -72,16 +72,11 @@ where } } } - pub(crate) fn convert_to_status_code(error: DispatchError) -> u32 { - match error { - _ => { - let mut encoded_error = error.encode(); - // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). - encoded_error.resize(4, 0); - u32::decode(&mut &encoded_error[..]).unwrap() - }, - } + let mut encoded_error = error.encode(); + // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). + encoded_error.resize(4, 0); + u32::decode(&mut &encoded_error[..]).expect("qid, resized to 4 bytes line above") } pub mod v0 { diff --git a/runtime/devnet/src/tests/local_fungibles.rs b/runtime/devnet/src/tests/local_fungibles.rs index 9f208b15..154e9897 100644 --- a/runtime/devnet/src/tests/local_fungibles.rs +++ b/runtime/devnet/src/tests/local_fungibles.rs @@ -269,7 +269,7 @@ fn create_works() { // No balance to pay for fees. assert_eq!( decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), - UseCaseError(NoBalance) + Module { index: 10, error: 2 }, ); // Instantiate a contract without balance (relay token). let addr = @@ -278,7 +278,7 @@ fn create_works() { // No balance to pay fe deposit. assert_eq!( decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), - UseCaseError(NoBalance) + Module { index: 10, error: 2 }, ); // Instantiate a contract with balance. let addr = instantiate( @@ -290,12 +290,12 @@ fn create_works() { // Asset ID is already taken. assert_eq!( decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), - UseCaseError(InUse) + Module { index: 52, error: 5 }, ); // The minimal balance for an asset must be non zero. assert_eq!( decoded::(create(addr.clone(), new_asset, BOB, 0)), - UseCaseError(MinBalanceZero) + Module { index: 52, error: 7 }, ); let result = create(addr.clone(), new_asset, BOB, 1); assert!(!result.did_revert(), "Contract reverted!"); @@ -347,7 +347,7 @@ fn transfer_from_mint_works() { amount, &[0u8] )), - UseCaseError(NoPermission) + Module { index: 52, error: 2 }, ); // Minimum balance of an asset can not be zero. assert_eq!( @@ -366,7 +366,7 @@ fn transfer_from_mint_works() { amount, &[0u8] )), - UseCaseError(AssetNotLive) + Module { index: 52, error: 16 }, ); thaw_asset(asset, addr.clone()); // Successful mint. @@ -398,7 +398,7 @@ fn transfer_from_mint_works() { amount, &[0u8] )), - UseCaseError(AssetNotLive) + Module { index: 52, error: 16 }, ); }); } @@ -418,7 +418,7 @@ fn transfer_works() { // Asset does not exist. assert_eq!( decoded::(transfer(addr.clone(), 1, BOB, amount,)), - UseCaseError(Unknown) + Module { index: 52, error: 3 }, ); // Create asset with Alice as owner and mint `amount` to contract address. let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); @@ -426,18 +426,18 @@ fn transfer_works() { freeze_asset(asset, ALICE); assert_eq!( decoded::(transfer(addr.clone(), asset, BOB, amount,)), - UseCaseError(AssetNotLive) + Module { index: 52, error: 16 }, ); thaw_asset(asset, ALICE); // Not enough balance. assert_eq!( decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), - UseCaseError(InsufficientBalance) + Module { index: 52, error: 0 }, ); // Not enough balance due to ED. assert_eq!( decoded::(transfer(addr.clone(), asset, BOB, amount)), - UseCaseError(InsufficientBalance) + Module { index: 52, error: 0 }, ); // Successful transfer. let bob_balance_before_mint = Assets::balance(asset, &BOB); @@ -454,7 +454,7 @@ fn transfer_works() { start_destroy_asset(asset, ALICE); assert_eq!( decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), - UseCaseError(AssetNotLive) + Module { index: 52, error: 16 }, ); }); } diff --git a/runtime/devnet/src/tests/mod.rs b/runtime/devnet/src/tests/mod.rs index c13030a3..dcb97ae1 100644 --- a/runtime/devnet/src/tests/mod.rs +++ b/runtime/devnet/src/tests/mod.rs @@ -256,7 +256,7 @@ fn dispatch_error_to_status_code_to_pop_api_error_works() { for (error, pop_api_error) in test_cases { // Show that the encoding and decoding of the PopApiError <> u32 (status code) works. let status_code = crate::extensions::convert_to_status_code(error); - let error = pop_api::error::convert_to_pop_api_error(status_code); - assert_eq!(pop_api_error, error,); + // let error = pop_api::error::convert_to_pop_api_error(status_code); + // assert_eq!(pop_api_error, error,); } } From f88dd89b8fbbfebc28126f0262fc8b5397b903d6 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Tue, 25 Jun 2024 16:58:18 +0200 Subject: [PATCH 11/27] refactor: apply comments part 2 --- pop-api/Cargo.toml | 6 +- .../{balance-transfer => }/.gitignore | 2 +- pop-api/examples/fungibles/.gitignore | 9 - pop-api/examples/fungibles/lib.rs | 2 +- pop-api/examples/nfts/.gitignore | 9 - pop-api/examples/place-spot-order/.gitignore | 9 - .../examples/read-runtime-state/.gitignore | 9 - pop-api/src/error.rs | 317 ++++++++++------- pop-api/src/lib.rs | 12 +- pop-api/src/primitives.rs | 1 - pop-api/src/v0/assets/fungibles.rs | 64 ++++ pop-api/src/v0/assets/mod.rs | 8 +- pop-api/src/v0/balances.rs | 6 +- pop-api/src/v0/cross_chain/mod.rs | 9 +- pop-api/src/v0/mod.rs | 12 +- pop-api/src/v0/nfts.rs | 318 +++++++++--------- pop-api/src/v0/state.rs | 5 +- primitives/Cargo.toml | 5 +- primitives/src/lib.rs | 25 +- primitives/src/storage_keys.rs | 10 +- runtime/devnet/Cargo.toml | 4 +- runtime/devnet/src/extensions.rs | 19 +- runtime/devnet/src/lib.rs | 4 +- runtime/devnet/src/tests/local_fungibles.rs | 57 +--- runtime/devnet/src/tests/mod.rs | 311 ++++++++--------- runtime/testnet/Cargo.toml | 2 +- runtime/testnet/src/extensions.rs | 6 +- runtime/testnet/src/lib.rs | 4 +- 28 files changed, 677 insertions(+), 568 deletions(-) rename pop-api/examples/{balance-transfer => }/.gitignore (93%) delete mode 100755 pop-api/examples/fungibles/.gitignore delete mode 100755 pop-api/examples/nfts/.gitignore delete mode 100755 pop-api/examples/place-spot-order/.gitignore delete mode 100755 pop-api/examples/read-runtime-state/.gitignore diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index b80cb3b0..9a868cfa 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -31,7 +31,7 @@ std = [ "sp-io/std", "sp-runtime/std", ] -assets = [] +assets = ["pop-primitives/assets"] balances = [] -nfts = [] -cross-chain = [] +nfts = ["pop-primitives/nfts"] +cross-chain = ["pop-primitives/cross-chain"] diff --git a/pop-api/examples/balance-transfer/.gitignore b/pop-api/examples/.gitignore similarity index 93% rename from pop-api/examples/balance-transfer/.gitignore rename to pop-api/examples/.gitignore index 8de8f877..e0caa493 100755 --- a/pop-api/examples/balance-transfer/.gitignore +++ b/pop-api/examples/.gitignore @@ -1,5 +1,5 @@ # Ignore build artifacts from the local tests sub-crate. -/target/ +/fungibles/target/ # Ignore backup files creates by cargo fmt. **/*.rs.bk diff --git a/pop-api/examples/fungibles/.gitignore b/pop-api/examples/fungibles/.gitignore deleted file mode 100755 index 8de8f877..00000000 --- a/pop-api/examples/fungibles/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# Ignore build artifacts from the local tests sub-crate. -/target/ - -# Ignore backup files creates by cargo fmt. -**/*.rs.bk - -# Remove Cargo.lock when creating an executable, leave it for libraries -# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 161c7fdd..41ea1b14 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -8,7 +8,7 @@ use ink::prelude::vec::Vec; use pop_api::{ assets::fungibles::{self as api, FungiblesError}, - error::{PopApiError, StatusCode}, + error::{Error, StatusCode}, primitives::{AccountId as AccountId32, AssetId}, }; diff --git a/pop-api/examples/nfts/.gitignore b/pop-api/examples/nfts/.gitignore deleted file mode 100755 index 8de8f877..00000000 --- a/pop-api/examples/nfts/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# Ignore build artifacts from the local tests sub-crate. -/target/ - -# Ignore backup files creates by cargo fmt. -**/*.rs.bk - -# Remove Cargo.lock when creating an executable, leave it for libraries -# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock diff --git a/pop-api/examples/place-spot-order/.gitignore b/pop-api/examples/place-spot-order/.gitignore deleted file mode 100755 index 8de8f877..00000000 --- a/pop-api/examples/place-spot-order/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# Ignore build artifacts from the local tests sub-crate. -/target/ - -# Ignore backup files creates by cargo fmt. -**/*.rs.bk - -# Remove Cargo.lock when creating an executable, leave it for libraries -# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock diff --git a/pop-api/examples/read-runtime-state/.gitignore b/pop-api/examples/read-runtime-state/.gitignore deleted file mode 100755 index 8de8f877..00000000 --- a/pop-api/examples/read-runtime-state/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# Ignore build artifacts from the local tests sub-crate. -/target/ - -# Ignore backup files creates by cargo fmt. -**/*.rs.bk - -# Remove Cargo.lock when creating an executable, leave it for libraries -# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock diff --git a/pop-api/src/error.rs b/pop-api/src/error.rs index 4d5a8fb9..b8a56f55 100644 --- a/pop-api/src/error.rs +++ b/pop-api/src/error.rs @@ -1,6 +1,7 @@ use ink::env::chain_extension::FromStatusCode; use scale::{Decode, Encode}; -use PopApiError::*; + +use Error::*; #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] @@ -30,10 +31,69 @@ impl From for StatusCode { } } +// If an unknown variant of the `DispatchError` is detected the error needs to be converted +// into the encoded value of `Error::Other`. This conversion is performed by shifting the bytes one +// position forward (discarding the last byte as it is not used) and setting the first byte to the +// encoded value of `Other` (0u8). This ensures the error is correctly categorized as an `Other` +// variant which provides all the necessary information to debug which error occurred in the runtime. +// +// Byte layout explanation: +// - Byte 0: index of the variant within `Error` +// - Byte 1: +// - Must be zero for `UNIT_ERRORS`. +// - Represents the nested error in `SINGLE_NESTED_ERRORS`. +// - Represents the first level of nesting in `DOUBLE_NESTED_ERRORS`. +// - Byte 2: +// - Represents the second level of nesting in `DOUBLE_NESTED_ERRORS`. +// - Byte 3: +// - Unused or represents further nested information. +// +// This mechanism ensures backward compatibility by correctly categorizing any unknown errors +// into the `Other` variant, thus preventing issues caused by breaking changes. +fn convert_unknown_errors(encoded_error: &mut [u8; 4]) { + let all_errors = [ + UNIT_ERRORS.as_slice(), + SINGLE_NESTED_ERRORS.as_slice(), + DOUBLE_NESTED_ERRORS.as_slice(), + // `DecodingFailed`. + &[255u8], + ] + .concat(); + // Unknown errors, i.e. an encoded value where the first byte is non-zero (indicating a variant + // in `Error`) but unknown. + if !all_errors.contains(&encoded_error[0]) { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; + } + convert_unknown_nested_errors(encoded_error); +} + +// If an unknown nested variant of the `DispatchError` is detected (i.e. when any of the subsequent +// bytes are non-zero). +fn convert_unknown_nested_errors(encoded_error: &mut [u8; 4]) { + // Converts single nested errors that are known to the Pop API as unit errors into `Other`. + if UNIT_ERRORS.contains(&encoded_error[0]) && encoded_error[1..].iter().any(|x| *x != 0u8) { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; + // Converts double nested errors that are known to the Pop API as single nested errors into + // `Other`. + } else if SINGLE_NESTED_ERRORS.contains(&encoded_error[0]) + && encoded_error[2..].iter().any(|x| *x != 0u8) + { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; + } else if DOUBLE_NESTED_ERRORS.contains(&encoded_error[0]) + && encoded_error[3..].iter().any(|x| *x != 0u8) + { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; + } +} + #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] #[repr(u8)] -pub enum PopApiError { +pub enum Error { /// Some unknown error occurred. Go to the Pop API docs section `Pop API error`. Other { // Index within the `DispatchError` @@ -76,8 +136,34 @@ pub enum PopApiError { DecodingFailed = 255, } -impl From for StatusCode { - fn from(value: PopApiError) -> Self { +// Unit `Error` variants. +// (variant: index): +// - CannotLookup: 1, +// - BadOrigin: 2, +// - ConsumerRemaining: 4, +// - NoProviders: 5, +// - TooManyConsumers: 6, +// - Exhausted: 10, +// - Corruption: 11, +// - Unavailable: 12, +// - RootNotAllowed: 13, +// - DecodingFailed: 255, +const UNIT_ERRORS: [u8; 10] = [1, 2, 4, 5, 6, 10, 11, 12, 13, 255]; + +// Single nested `Error` variants. +// (variant: index): +// - Token: 7, +// - Arithmetic: 8, +// - Transaction: 9, +const SINGLE_NESTED_ERRORS: [u8; 3] = [7, 8, 9]; + +// Double nested `Error` variants +// (variant: index): +// - Module: 3, +const DOUBLE_NESTED_ERRORS: [u8; 1] = [3]; + +impl From for StatusCode { + fn from(value: Error) -> Self { let mut encoded_error = value.encode(); // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). encoded_error.resize(4, 0); @@ -87,71 +173,11 @@ impl From for StatusCode { } } -impl From for PopApiError { - // `pub` because it is used in `runtime/devnet/src/extensions/tests/mod.rs`'s test: - // `dispatch_error_to_status_code_to_pop_api_error_works` - // - // This function converts a given `status_code` (u32) into a `PopApiError`. +impl From for Error { fn from(value: StatusCode) -> Self { let encoded: [u8; 4] = value.0.to_le_bytes(); - PopApiError::decode(&mut &encoded[..]).unwrap_or(DecodingFailed) - } -} - -// If an unknown nested variant of the `DispatchError` is detected (i.e., any of the subsequent -// bytes are non-zero, indicating a breaking change in the `DispatchError`), the error needs to be -// converted into the encoded value of `PopApiError::Other`. This conversion is performed by -// shifting the bytes one position forward (discarding the last byte as it is not used) and setting -// the first byte to the encoded value of `Other` (0u8). This ensures the error is correctly -// categorized as an `Other` variant. -// -// Byte layout explanation: -// - Byte 0: PopApiError -// - Byte 1: -// - Must be zero for `UNIT_ERRORS`. -// - Represents the nested error in `SINGLE_NESTED_ERRORS`. -// - Represents the first level of nesting in `DOUBLE_NESTED_ERRORS`. -// - Byte 2: -// - Represents the second level of nesting in `DOUBLE_NESTED_ERRORS`. -// - Byte 3: -// - Unused or represents further nested information. -// -// This mechanism ensures backward compatibility by correctly categorizing any unknown nested errors -// into the `Other` variant, thus preventing issues caused by new or unexpected error formats. -pub(crate) fn convert_unknown_nested_errors(encoded_error: &mut [u8; 4]) { - // Converts single nested errors that are known to the Pop API as unit errors into `Other`. - if UNIT_ERRORS.contains(&encoded_error[0]) && encoded_error[1..].iter().any(|x| *x != 0u8) { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; - // Converts double nested errors that are known to the Pop API as single nested errors into - // `Other`. - } else if SINGLE_NESTED_ERRORS.contains(&encoded_error[0]) - && encoded_error[2..].iter().any(|x| *x != 0u8) - { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; - } else if DOUBLE_NESTED_ERRORS.contains(&encoded_error[0]) - && encoded_error[3..].iter().any(|x| *x != 0u8) - { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; - } -} - -pub(crate) fn convert_unknown_errors(encoded_error: &mut [u8; 4]) { - let all_errors = [ - UNIT_ERRORS.as_slice(), - SINGLE_NESTED_ERRORS.as_slice(), - DOUBLE_NESTED_ERRORS.as_slice(), - // `DecodingFailed`. - &[255u8], - ] - .concat(); - if !all_errors.contains(&encoded_error[0]) { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; + Error::decode(&mut &encoded[..]).unwrap_or(DecodingFailed) } - convert_unknown_nested_errors(encoded_error); } #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] @@ -200,26 +226,6 @@ pub enum TransactionalError { NoLayer, } -// Unit `DispatchError` variants (variant: index): -// - CannotLookup: 1, -// - BadOrigin: 2, -// - ConsumerRemaining: 4, -// - NoProviders: 5, -// - TooManyConsumers: 6, -// - Exhausted: 10, -// - Corruption: 11, -// - Unavailable: 12, -// - RootNotAllowed: 13, -const UNIT_ERRORS: [u8; 9] = [1, 2, 4, 5, 6, 10, 11, 12, 13]; - -// Single nested `DispatchError` variants (variant: index): -// - Token: 3, -// - Arithmetic: 8, -// - Transaction: 9, -const SINGLE_NESTED_ERRORS: [u8; 3] = [7, 8, 9]; - -const DOUBLE_NESTED_ERRORS: [u8; 1] = [3]; - #[cfg(test)] mod tests { use super::*; @@ -231,20 +237,30 @@ mod tests { assert_eq!(u32::MAX.encode().len(), 4); } - // Decodes into `StatusCode(u32)` and converts it into the `PopApiError`. - fn into_pop_api_error(encoded_error: [u8; 4]) -> PopApiError { - let status_code = - StatusCode::from_status_code(u32::decode(&mut &encoded_error[..]).unwrap()) - .unwrap_err(); + // Decodes 4 bytes into a `u32` and converts it into `StatusCode`. + fn into_status_code(encoded_error: [u8; 4]) -> StatusCode { + let decoded_u32 = u32::decode(&mut &encoded_error[..]).unwrap(); + StatusCode::from_status_code(decoded_u32).unwrap_err() + } + + // Decodes 4 bytes into a `u32` and converts it into `Error`. + fn into_error(encoded_error: [u8; 4]) -> Error { + let decoded_u32 = u32::decode(&mut &encoded_error[..]).unwrap(); + let status_code = StatusCode::from_status_code(decoded_u32).unwrap_err(); status_code.into() } - // Tests for the `From` implementation for `PopApiError`. + // Tests the `From` implementation for `Error`. // - // If the encoded value indicates a nested `PopApiError` which is not handled by the Pop API - // version, the encoded value is converted into `PopApiError::Other`. + // Unit variants: + // If the encoded value indicates a nested `Error` which is known by the Pop API version as a + // unit variant, the encoded value is converted into `Error::Other`. + // + // Example: the error `BadOrigin` (encoded: `[2, 0, 0, 0]`) with a non-zero value for one + // of the bytes [1..4]: `[2, 0, 1, 0]` is converted into `[0, 2, 0, 1]`. This is decoded to + // `Error::Other { dispatch_error: 2, index: 0, error: 1 }`. #[test] - fn test_unit_pop_api_error_variants() { + fn unit_error_variants() { let errors = vec![ CannotLookup, BadOrigin, @@ -255,73 +271,134 @@ mod tests { Corruption, Unavailable, RootNotAllowed, + DecodingFailed, ]; + // Four scenarios, 2 tests each: + // 1. Compare a `StatusCode`, which is converted from an encoded value, with a `StatusCode` + // converted from an `Error`. + // 2. Compare an `Error, which is converted from an encoded value, with the expected `Error`. for (i, &error_code) in UNIT_ERRORS.iter().enumerate() { - assert_eq!(into_pop_api_error([error_code, 0, 0, 0]), errors[i]); + // No nesting and unit variant correctly returned. + assert_eq!(into_status_code([error_code, 0, 0, 0]), errors[i].into()); + assert_eq!(into_error([error_code, 0, 0, 0]), errors[i]); + // Unexpected second byte nested. + assert_eq!( + into_status_code([error_code, 1, 0, 0]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 0 }).into(), + ); assert_eq!( - into_pop_api_error([error_code, 1, 0, 0]), + into_error([error_code, 1, 0, 0]), Other { dispatch_error_index: error_code, error_index: 1, error: 0 }, ); + // Unexpected third byte nested. + assert_eq!( + into_status_code([error_code, 1, 1, 0]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), + ); assert_eq!( - into_pop_api_error([error_code, 1, 1, 0]), + into_error([error_code, 1, 1, 0]), Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, ); + // Unexpected fourth byte nested. assert_eq!( - into_pop_api_error([error_code, 1, 1, 1]), + into_status_code([error_code, 1, 1, 1]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), + ); + assert_eq!( + into_error([error_code, 1, 1, 1]), Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, ); } } + // Single nested variants: + // If the encoded value indicates a double nested `Error` which is known by the Pop API version + // as a single nested variant, the encoded value is converted into `Error::Other`. + // + // Example: the error `Arithmetic(Overflow)` (encoded: `[8, 1, 0, 0]`) with a non-zero + // value for one of the bytes [2..4]: `[8, 1, 1, 0]` is converted into `[0, 8, 1, 1]`. This is + // decoded to `Error::Other { dispatch_error: 8, index: 1, error: 1 }`. #[test] - fn test_single_nested_pop_api_error_variants() { + fn single_nested_error_variants() { let errors = vec![ [Token(FundsUnavailable), Token(OnlyProvider)], [Arithmetic(Underflow), Arithmetic(Overflow)], [Transactional(LimitReached), Transactional(NoLayer)], ]; + // Four scenarios, 2 tests each: + // 1. Compare a `StatusCode`, which is converted from an encoded value, with a `StatusCode` + // converted from an `Error`. + // 2. Compare an `Error, which is converted from an encoded value, with the expected `Error`. for (i, &error_code) in SINGLE_NESTED_ERRORS.iter().enumerate() { - assert_eq!(into_pop_api_error([error_code, 0, 0, 0]), errors[i][0]); - assert_eq!(into_pop_api_error([error_code, 1, 0, 0]), errors[i][1]); + // No nesting and unit variant correctly returned. + assert_eq!(into_status_code([error_code, 0, 0, 0]), errors[i][0].into()); + assert_eq!(into_error([error_code, 0, 0, 0]), errors[i][0]); + // Allowed single nesting variant correctly returned. + assert_eq!(into_status_code([error_code, 1, 0, 0]), errors[i][1].into()); + assert_eq!(into_error([error_code, 1, 0, 0]), errors[i][1]); + // Unexpected third byte nested. + assert_eq!( + into_status_code([error_code, 1, 1, 0]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), + ); assert_eq!( - into_pop_api_error([error_code, 1, 1, 0]), + into_error([error_code, 1, 1, 0]), Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, ); + // Unexpected fourth byte nested. + assert_eq!( + into_status_code([error_code, 1, 1, 1]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), + ); assert_eq!( - into_pop_api_error([error_code, 1, 1, 1]), + into_error([error_code, 1, 1, 1]), Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, ); } } + // Double nested variants: + // If the encoded value indicates a triple nested `Error` which is known by the Pop API version + // as a double nested variant, the encoded value is converted into `Error::Other`. + // + // Example: the error `Module { index: 10, error 5 }` (encoded: `[3, 10, 5, 0]`) with a non-zero + // value for the last byte: `[3, 10, 5, 3]` is converted into `[0, 3, 10, 5]`. This is + // decoded to `Error::Other { dispatch_error: 3, index: 10, error: 5 }`. #[test] - fn test_double_nested_pop_api_error_variants() { - assert_eq!(into_pop_api_error([3, 0, 0, 0]), Module { index: 0, error: 0 }); - assert_eq!(into_pop_api_error([3, 1, 0, 0]), Module { index: 1, error: 0 }); - assert_eq!(into_pop_api_error([3, 1, 1, 0]), Module { index: 1, error: 1 }); - // TODO: doesn't make sense. + fn double_nested_error_variants() { + // Four scenarios, 2 tests each: + // 1. Compare a `StatusCode`, which is converted from an encoded value, with a `StatusCode` + // converted from an `Error`. + // 2. Compare an `Error, which is converted from an encoded value, with the expected `Error`. + // + // No nesting and unit variant correctly returned. + assert_eq!(into_status_code([3, 0, 0, 0]), (Module { index: 0, error: 0 }).into()); + assert_eq!(into_error([3, 0, 0, 0]), Module { index: 0, error: 0 }); + // Allowed single nesting and variant correctly returned. + assert_eq!(into_status_code([3, 1, 0, 0]), (Module { index: 1, error: 0 }).into()); + assert_eq!(into_error([3, 1, 0, 0]), Module { index: 1, error: 0 }); + // Allowed double nesting and variant correctly returned. + assert_eq!(into_status_code([3, 1, 1, 0]), (Module { index: 1, error: 1 }).into()); + assert_eq!(into_error([3, 1, 1, 0]), Module { index: 1, error: 1 }); + // Unexpected fourth byte nested. assert_eq!( - into_pop_api_error([3, 1, 1, 1]), + into_status_code([3, 1, 1, 1]), + (Other { dispatch_error_index: 3, error_index: 1, error: 1 }).into(), + ); + assert_eq!( + into_error([3, 1, 1, 1]), Other { dispatch_error_index: 3, error_index: 1, error: 1 }, ); } - #[test] - fn test_decoding_failed() { - assert_eq!(into_pop_api_error([255, 0, 0, 0]), DecodingFailed); - assert_eq!(into_pop_api_error([255, 255, 0, 0]), DecodingFailed); - assert_eq!(into_pop_api_error([255, 255, 255, 0]), DecodingFailed); - assert_eq!(into_pop_api_error([255, 255, 255, 255]), DecodingFailed); - } - #[test] fn test_random_encoded_values() { assert_eq!( - into_pop_api_error([100, 100, 100, 100]), + into_error([100, 100, 100, 100]), Other { dispatch_error_index: 100, error_index: 100, error: 100 } ); assert_eq!( - into_pop_api_error([200, 200, 200, 200]), + into_error([200, 200, 200, 200]), Other { dispatch_error_index: 200, error_index: 200, error: 200 } ); } diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 90c81998..3e9ead7f 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -3,7 +3,7 @@ use ink::{prelude::vec::Vec, ChainExtensionInstance}; pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; -use crate::error::{PopApiError, StatusCode}; +use crate::error::{Error, StatusCode}; use primitives::{storage_keys::*, AccountId as AccountId32}; #[cfg(feature = "assets")] pub use v0::assets; @@ -21,7 +21,11 @@ pub mod v0; type AccountId = AccountId32; // TODO: do the same as the AccountId above and check expanded macro code. -type Balance = ::Balance; +// type Balance = ::Balance; +type Balance = u128; +#[cfg(any(feature = "nfts", feature = "cross-chain"))] +type BlockNumber = ::BlockNumber; + pub type Result = core::result::Result; #[derive(Debug, Clone, PartialEq, Eq)] @@ -56,7 +60,7 @@ pub trait PopApi { #[cfg(feature = "cross-chain")] #[ink(function = 2)] #[allow(private_interfaces)] - fn send_xcm(xcm: CrossChainMessage) -> Result<()>; + fn send_xcm(xcm: primitives::cross_chain::CrossChainMessage) -> Result<()>; } fn dispatch(call: RuntimeCall) -> Result<()> { @@ -72,7 +76,7 @@ fn read_state(key: RuntimeStateKeys) -> Result> { } #[cfg(feature = "cross-chain")] -fn send_xcm(xcm: CrossChainMessage) -> Result<()> { +fn send_xcm(xcm: primitives::cross_chain::CrossChainMessage) -> Result<()> { <::ChainExtension as ChainExtensionInstance>::instantiate( ) .send_xcm(xcm) diff --git a/pop-api/src/primitives.rs b/pop-api/src/primitives.rs index e8098f69..e174a111 100644 --- a/pop-api/src/primitives.rs +++ b/pop-api/src/primitives.rs @@ -1,2 +1 @@ pub use pop_primitives::*; -pub use sp_runtime::{BoundedVec, MultiAddress}; diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index b1bb86a7..eaf1c6f5 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -356,3 +356,67 @@ impl From for FungiblesError { } } } + +#[cfg(test)] +mod tests { + use super::FungiblesError; + use crate::error::{ + ArithmeticError::*, + Error::{self, *}, + StatusCode, + TokenError::*, + TransactionalError::*, + }; + + fn into_fungibles_error(error: Error) -> FungiblesError { + let status_code: StatusCode = error.into(); + status_code.into() + } + + #[test] + fn conversion_status_code_into_fungibles_error_works() { + let errors = vec![ + Other { dispatch_error_index: 5, error_index: 5, error: 1 }, + CannotLookup, + BadOrigin, + Module { index: 2, error: 5 }, + ConsumerRemaining, + NoProviders, + TooManyConsumers, + Token(OnlyProvider), + Arithmetic(Overflow), + Transactional(NoLayer), + Exhausted, + Corruption, + Unavailable, + RootNotAllowed, + DecodingFailed, + ]; + for error in errors { + let status_code: StatusCode = error.into(); + let fungibles_error: FungiblesError = status_code.into(); + assert_eq!(fungibles_error, FungiblesError::Other(status_code)) + } + + assert_eq!(into_fungibles_error(Module { index: 10, error: 2 }), FungiblesError::NoBalance); + assert_eq!(into_fungibles_error(Module { index: 52, error: 0 }), FungiblesError::NoAccount); + assert_eq!( + into_fungibles_error(Module { index: 52, error: 1 }), + FungiblesError::NoPermission + ); + assert_eq!(into_fungibles_error(Module { index: 52, error: 2 }), FungiblesError::Unknown); + assert_eq!(into_fungibles_error(Module { index: 52, error: 3 }), FungiblesError::InUse); + assert_eq!( + into_fungibles_error(Module { index: 52, error: 5 }), + FungiblesError::MinBalanceZero + ); + assert_eq!( + into_fungibles_error(Module { index: 52, error: 7 }), + FungiblesError::InsufficientAllowance + ); + assert_eq!( + into_fungibles_error(Module { index: 52, error: 10 }), + FungiblesError::AssetNotLive + ); + } +} diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 4ce68219..d67d30bd 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,8 +1,8 @@ #![allow(dead_code)] -use crate::{Balance, RuntimeCall, *}; +use crate::{Balance, MultiAddress, RuntimeCall, *}; use ink::prelude::vec::Vec; -use primitives::{AssetId, MultiAddress}; +use primitives::AssetId; use scale::{Compact, Encode}; pub mod fungibles; @@ -13,7 +13,7 @@ type Result = core::result::Result; /// 1. Dispatchables /// 2. Read state functions /// -/// 1. Dispatchables within pallet assets (TrustBackedAssets instance) that can be used via the pop api on Pop Network: +/// 1. Dispatchables within pallet assets (TrustBackedAssets instance): /// - create /// - start_destroy /// - destroy_accounts @@ -464,7 +464,7 @@ pub enum AssetsError { } impl TryFrom for AssetsError { - type Error = PopApiError; + type Error = Error; fn try_from(status_code: u32) -> core::result::Result { use AssetsError::*; diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index ae2709e7..e14e6e32 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -1,6 +1,4 @@ -use crate::{ - dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, PopApiError, StatusCode, -}; +use crate::{dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, Error, StatusCode}; type Result = core::result::Result; @@ -57,7 +55,7 @@ pub enum BalancesError { } impl TryFrom for BalancesError { - type Error = PopApiError; + type Error = Error; fn try_from(status_code: u32) -> core::result::Result { use BalancesError::*; diff --git a/pop-api/src/v0/cross_chain/mod.rs b/pop-api/src/v0/cross_chain/mod.rs index 583447b1..5a0dda6c 100644 --- a/pop-api/src/v0/cross_chain/mod.rs +++ b/pop-api/src/v0/cross_chain/mod.rs @@ -1,11 +1,8 @@ -pub mod coretime; - -use crate::StatusCode; +use crate::{BlockNumber, ParachainSystemKeys, Result, RuntimeStateKeys}; -type Result = core::result::Result; -type BlockNumber = ::BlockNumber; +pub mod coretime; -pub fn relay_chain_block_number() -> std::result::Result { +pub fn relay_chain_block_number() -> Result { crate::v0::state::read(RuntimeStateKeys::ParachainSystem( ParachainSystemKeys::LastRelayChainBlockNumber, )) diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 41574cfb..20dc6476 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -10,12 +10,12 @@ pub mod state; #[derive(scale::Encode)] pub(crate) enum RuntimeCall { - // #[codec(index = 10)] - // #[cfg(feature = "balances")] - // Balances(balances::BalancesCall), - // #[codec(index = 50)] - // #[cfg(feature = "nfts")] - // Nfts(nfts::NftCalls), + #[codec(index = 10)] + #[cfg(feature = "balances")] + Balances(balances::BalancesCall), + #[codec(index = 50)] + #[cfg(feature = "nfts")] + Nfts(nfts::NftCalls), #[codec(index = 52)] #[cfg(feature = "assets")] Assets(assets::AssetsCall), diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index 1e4406e5..29219c66 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -1,9 +1,15 @@ -use super::RuntimeCall; -use crate::*; use ink::prelude::vec::Vec; -use primitives::{ApprovalsLimit, BoundedBTreeMap, KeyLimit, MultiAddress}; -pub use primitives::{CollectionId, ItemId}; use scale::Encode; + +use crate::{ + dispatch, + primitives::{ + nfts::{ApprovalsLimit, CollectionId, ItemId, KeyLimit}, + BoundedBTreeMap, + }, + state, AccountId, Balance, BlockNumber, BoundedVec, MultiAddress, NftsKeys, RuntimeCall, + RuntimeStateKeys, StatusCode, +}; pub use types::*; type Result = core::result::Result; @@ -515,163 +521,163 @@ pub(crate) enum NftCalls { receive_item: ItemId, }, } - -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { - /// The signing account has no permission to do the operation. - NoPermission, - /// The given item ID is unknown. - UnknownCollection, - /// The item ID has already been used for an item. - AlreadyExists, - /// The approval had a deadline that expired, so the approval isn't valid anymore. - ApprovalExpired, - /// The owner turned out to be different to what was expected. - WrongOwner, - /// The witness data given does not match the current state of the chain. - BadWitness, - /// Collection ID is already taken. - CollectionIdInUse, - /// Items within that collection are non-transferable. - ItemsNonTransferable, - /// The provided account is not a delegate. - NotDelegate, - /// The delegate turned out to be different to what was expected. - WrongDelegate, - /// No approval exists that would allow the transfer. - Unapproved, - /// The named owner has not signed ownership acceptance of the collection. - Unaccepted, - /// The item is locked (non-transferable). - ItemLocked, - /// Item's attributes are locked. - LockedItemAttributes, - /// Collection's attributes are locked. - LockedCollectionAttributes, - /// Item's metadata is locked. - LockedItemMetadata, - /// Collection's metadata is locked. - LockedCollectionMetadata, - /// All items have been minted. - MaxSupplyReached, - /// The max supply is locked and can't be changed. - MaxSupplyLocked, - /// The provided max supply is less than the number of items a collection already has. - MaxSupplyTooSmall, - /// The given item ID is unknown. - UnknownItem, - /// Swap doesn't exist. - UnknownSwap, - /// The given item has no metadata set. - MetadataNotFound, - /// The provided attribute can't be found. - AttributeNotFound, - /// Item is not for sale. - NotForSale, - /// The provided bid is too low. - BidTooLow, - /// The item has reached its approval limit. - ReachedApprovalLimit, - /// The deadline has already expired. - DeadlineExpired, - /// The duration provided should be less than or equal to `MaxDeadlineDuration`. - WrongDuration, - /// The method is disabled by system settings. - MethodDisabled, - /// The provided setting can't be set. - WrongSetting, - /// Item's config already exists and should be equal to the provided one. - InconsistentItemConfig, - /// Config for a collection or an item can't be found. - NoConfig, - /// Some roles were not cleared. - RolesNotCleared, - /// Mint has not started yet. - MintNotStarted, - /// Mint has already ended. - MintEnded, - /// The provided Item was already used for claiming. - AlreadyClaimed, - /// The provided data is incorrect. - IncorrectData, - /// The extrinsic was sent by the wrong origin. - WrongOrigin, - /// The provided signature is incorrect. - WrongSignature, - /// The provided metadata might be too long. - IncorrectMetadata, - /// Can't set more attributes per one call. - MaxAttributesLimitReached, - /// The provided namespace isn't supported in this call. - WrongNamespace, - /// Can't delete non-empty collections. - CollectionNotEmpty, - /// The witness data should be provided. - WitnessRequired, -} - -impl TryFrom for Error { - type Error = Error; - - fn try_from(status_code: u32) -> core::result::Result { - use Error::*; - match status_code { - 0 => Ok(NoPermission), - 1 => Ok(UnknownCollection), - 2 => Ok(AlreadyExists), - 3 => Ok(ApprovalExpired), - 4 => Ok(WrongOwner), - 5 => Ok(BadWitness), - 6 => Ok(CollectionIdInUse), - 7 => Ok(ItemsNonTransferable), - 8 => Ok(NotDelegate), - 9 => Ok(WrongDelegate), - 10 => Ok(Unapproved), - 11 => Ok(Unaccepted), - 12 => Ok(ItemLocked), - 13 => Ok(LockedItemAttributes), - 14 => Ok(LockedCollectionAttributes), - 15 => Ok(LockedItemMetadata), - 16 => Ok(LockedCollectionMetadata), - 17 => Ok(MaxSupplyReached), - 18 => Ok(MaxSupplyLocked), - 19 => Ok(MaxSupplyTooSmall), - 20 => Ok(UnknownItem), - 21 => Ok(UnknownSwap), - 22 => Ok(MetadataNotFound), - 23 => Ok(AttributeNotFound), - 24 => Ok(NotForSale), - 25 => Ok(BidTooLow), - 26 => Ok(ReachedApprovalLimit), - 27 => Ok(DeadlineExpired), - 28 => Ok(WrongDuration), - 29 => Ok(MethodDisabled), - 30 => Ok(WrongSetting), - 31 => Ok(InconsistentItemConfig), - 32 => Ok(NoConfig), - 33 => Ok(RolesNotCleared), - 34 => Ok(MintNotStarted), - 35 => Ok(MintEnded), - 36 => Ok(AlreadyClaimed), - 37 => Ok(IncorrectData), - 38 => Ok(WrongOrigin), - 39 => Ok(WrongSignature), - 40 => Ok(IncorrectMetadata), - 41 => Ok(MaxAttributesLimitReached), - 42 => Ok(WrongNamespace), - 43 => Ok(CollectionNotEmpty), - 44 => Ok(WitnessRequired), - _ => todo!(), - } - } -} +// +// #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +// #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +// pub enum Error { +// /// The signing account has no permission to do the operation. +// NoPermission, +// /// The given item ID is unknown. +// UnknownCollection, +// /// The item ID has already been used for an item. +// AlreadyExists, +// /// The approval had a deadline that expired, so the approval isn't valid anymore. +// ApprovalExpired, +// /// The owner turned out to be different to what was expected. +// WrongOwner, +// /// The witness data given does not match the current state of the chain. +// BadWitness, +// /// Collection ID is already taken. +// CollectionIdInUse, +// /// Items within that collection are non-transferable. +// ItemsNonTransferable, +// /// The provided account is not a delegate. +// NotDelegate, +// /// The delegate turned out to be different to what was expected. +// WrongDelegate, +// /// No approval exists that would allow the transfer. +// Unapproved, +// /// The named owner has not signed ownership acceptance of the collection. +// Unaccepted, +// /// The item is locked (non-transferable). +// ItemLocked, +// /// Item's attributes are locked. +// LockedItemAttributes, +// /// Collection's attributes are locked. +// LockedCollectionAttributes, +// /// Item's metadata is locked. +// LockedItemMetadata, +// /// Collection's metadata is locked. +// LockedCollectionMetadata, +// /// All items have been minted. +// MaxSupplyReached, +// /// The max supply is locked and can't be changed. +// MaxSupplyLocked, +// /// The provided max supply is less than the number of items a collection already has. +// MaxSupplyTooSmall, +// /// The given item ID is unknown. +// UnknownItem, +// /// Swap doesn't exist. +// UnknownSwap, +// /// The given item has no metadata set. +// MetadataNotFound, +// /// The provided attribute can't be found. +// AttributeNotFound, +// /// Item is not for sale. +// NotForSale, +// /// The provided bid is too low. +// BidTooLow, +// /// The item has reached its approval limit. +// ReachedApprovalLimit, +// /// The deadline has already expired. +// DeadlineExpired, +// /// The duration provided should be less than or equal to `MaxDeadlineDuration`. +// WrongDuration, +// /// The method is disabled by system settings. +// MethodDisabled, +// /// The provided setting can't be set. +// WrongSetting, +// /// Item's config already exists and should be equal to the provided one. +// InconsistentItemConfig, +// /// Config for a collection or an item can't be found. +// NoConfig, +// /// Some roles were not cleared. +// RolesNotCleared, +// /// Mint has not started yet. +// MintNotStarted, +// /// Mint has already ended. +// MintEnded, +// /// The provided Item was already used for claiming. +// AlreadyClaimed, +// /// The provided data is incorrect. +// IncorrectData, +// /// The extrinsic was sent by the wrong origin. +// WrongOrigin, +// /// The provided signature is incorrect. +// WrongSignature, +// /// The provided metadata might be too long. +// IncorrectMetadata, +// /// Can't set more attributes per one call. +// MaxAttributesLimitReached, +// /// The provided namespace isn't supported in this call. +// WrongNamespace, +// /// Can't delete non-empty collections. +// CollectionNotEmpty, +// /// The witness data should be provided. +// WitnessRequired, +// } +// +// impl TryFrom for Error { +// type Error = Error; +// +// fn try_from(status_code: u32) -> core::result::Result { +// use Error::*; +// match status_code { +// 0 => Ok(NoPermission), +// 1 => Ok(UnknownCollection), +// 2 => Ok(AlreadyExists), +// 3 => Ok(ApprovalExpired), +// 4 => Ok(WrongOwner), +// 5 => Ok(BadWitness), +// 6 => Ok(CollectionIdInUse), +// 7 => Ok(ItemsNonTransferable), +// 8 => Ok(NotDelegate), +// 9 => Ok(WrongDelegate), +// 10 => Ok(Unapproved), +// 11 => Ok(Unaccepted), +// 12 => Ok(ItemLocked), +// 13 => Ok(LockedItemAttributes), +// 14 => Ok(LockedCollectionAttributes), +// 15 => Ok(LockedItemMetadata), +// 16 => Ok(LockedCollectionMetadata), +// 17 => Ok(MaxSupplyReached), +// 18 => Ok(MaxSupplyLocked), +// 19 => Ok(MaxSupplyTooSmall), +// 20 => Ok(UnknownItem), +// 21 => Ok(UnknownSwap), +// 22 => Ok(MetadataNotFound), +// 23 => Ok(AttributeNotFound), +// 24 => Ok(NotForSale), +// 25 => Ok(BidTooLow), +// 26 => Ok(ReachedApprovalLimit), +// 27 => Ok(DeadlineExpired), +// 28 => Ok(WrongDuration), +// 29 => Ok(MethodDisabled), +// 30 => Ok(WrongSetting), +// 31 => Ok(InconsistentItemConfig), +// 32 => Ok(NoConfig), +// 33 => Ok(RolesNotCleared), +// 34 => Ok(MintNotStarted), +// 35 => Ok(MintEnded), +// 36 => Ok(AlreadyClaimed), +// 37 => Ok(IncorrectData), +// 38 => Ok(WrongOrigin), +// 39 => Ok(WrongSignature), +// 40 => Ok(IncorrectMetadata), +// 41 => Ok(MaxAttributesLimitReached), +// 42 => Ok(WrongNamespace), +// 43 => Ok(CollectionNotEmpty), +// 44 => Ok(WitnessRequired), +// _ => todo!(), +// } +// } +// } // Local implementations of pallet-nfts types mod types { use super::*; use crate::{ - primitives::{CollectionId, ItemId}, + primitives::nfts::{CollectionId, ItemId}, Balance, BlockNumber, }; pub use enumflags2::{bitflags, BitFlags}; diff --git a/pop-api/src/v0/state.rs b/pop-api/src/v0/state.rs index 1aca01cf..e3d38129 100644 --- a/pop-api/src/v0/state.rs +++ b/pop-api/src/v0/state.rs @@ -1,7 +1,6 @@ -use crate::{primitives::storage_keys::RuntimeStateKeys, read_state, PopApiError}; +use crate::{primitives::storage_keys::RuntimeStateKeys, read_state, Error}; use scale::Decode; pub fn read(key: RuntimeStateKeys) -> crate::Result { - read_state(key) - .and_then(|v| T::decode(&mut &v[..]).map_err(|_e| PopApiError::DecodingFailed.into())) + read_state(key).and_then(|v| T::decode(&mut &v[..]).map_err(|_e| Error::DecodingFailed.into())) } diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index e7237b51..6ba3fea7 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -22,4 +22,7 @@ std = [ "scale-info/std", ] devnet = [] -testnet = [] \ No newline at end of file +testnet = [] +assets = [] +cross-chain = [] +nfts = [] diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 1e008c31..3b91f713 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -1,10 +1,11 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -pub use bounded_collections::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec, ConstU32}; +pub use bounded_collections::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec}; use scale::{Decode, Encode, MaxEncodedLen}; #[cfg(feature = "std")] use {scale_decode::DecodeAsType, scale_encode::EncodeAsType, scale_info::TypeInfo}; +#[cfg(feature = "cross-chain")] pub mod cross_chain; pub mod storage_keys; @@ -14,11 +15,17 @@ pub struct AccountId(pub [u8; 32]); // Identifier for the class of asset. pub type AssetId = u32; -// Id used for identifying non-fungible collections. -pub type CollectionId = u32; -// Id used for identifying non-fungible items. -pub type ItemId = u32; -/// The maximum length of an attribute key. -pub type KeyLimit = ConstU32<64>; -/// The maximum approvals an item could have. -pub type ApprovalsLimit = ConstU32<20>; + +#[cfg(feature = "nfts")] +pub mod nfts { + use bounded_collections::ConstU32; + + // Id used for identifying non-fungible collections. + pub type CollectionId = u32; + // Id used for identifying non-fungible items. + pub type ItemId = u32; + /// The maximum length of an attribute key. + pub type KeyLimit = ConstU32<64>; + /// The maximum approvals an item could have. + pub type ApprovalsLimit = ConstU32<20>; +} diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index fc7234aa..4be95986 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -1,13 +1,18 @@ +#[cfg(feature = "nfts")] +use super::nfts::*; use super::*; #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum RuntimeStateKeys { + #[cfg(feature = "nfts")] Nfts(NftsKeys), + #[cfg(feature = "cross-chain")] ParachainSystem(ParachainSystemKeys), - #[cfg(feature = "devnet")] + #[cfg(feature = "assets")] Assets(AssetsKeys), } +#[cfg(feature = "cross-chain")] #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum ParachainSystemKeys { /// Get the last relay chain block number seen by the parachain. @@ -15,6 +20,7 @@ pub enum ParachainSystemKeys { } // https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/nfts/src/impl_nonfungibles.rs +#[cfg(feature = "nfts")] #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum NftsKeys { // Get the details of a collection. @@ -34,7 +40,7 @@ pub enum NftsKeys { } /// The required input for state queries in pallet assets. -#[cfg(feature = "devnet")] +#[cfg(feature = "assets")] #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum AssetsKeys { Allowance(AssetId, AccountId, AccountId), diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index daa5457e..b72bf4f7 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -22,7 +22,7 @@ scale-info.workspace = true smallvec.workspace = true # Local -pop-primitives = { workspace = true, default-features = false, features = ["devnet"] } +pop-primitives = { workspace = true, default-features = false, features = ["assets", "cross-chain", "nfts"] } pop-runtime-common = { workspace = true, default-features = false } # Substrate @@ -91,7 +91,7 @@ parachain-info.workspace = true env_logger = "0.11.2" hex = "0.4.3" enumflags2 = "0.7.9" -pop-api = { path = "../../pop-api", defeult-features = false, features = ["assets"] } +pop-api = { path = "../../pop-api", features = ["assets", "cross-chain", "nfts"] } [features] default = ["std"] diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs index b4c6ba84..9db31e83 100644 --- a/runtime/devnet/src/extensions.rs +++ b/runtime/devnet/src/extensions.rs @@ -11,11 +11,6 @@ use frame_support::{ use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, }; -use pop_primitives::{ - cross_chain::CrossChainMessage, - storage_keys::{AssetsKeys, NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, - AssetId, CollectionId, ItemId, -}; use sp_core::crypto::UncheckedFrom; use sp_runtime::traits::{BlockNumberProvider, Dispatchable}; use sp_std::{boxed::Box, vec::Vec}; @@ -25,9 +20,15 @@ use xcm::{ }; use crate::{ - config::assets::TrustBackedAssetsInstance, AccountId, AllowedPopApiCalls, RuntimeCall, + config::assets::TrustBackedAssetsInstance, AccountId, AllowedApiCalls, RuntimeCall, RuntimeOrigin, UNIT, }; +use pop_primitives::{ + cross_chain::CrossChainMessage, + nfts::{CollectionId, ItemId}, + storage_keys::{AssetsKeys, NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, + AssetId, +}; const LOG_TARGET: &str = "pop-api::extension"; @@ -122,7 +123,7 @@ where log::debug!(target:LOG_TARGET, "{} Inputted RuntimeCall: {:?}", log_prefix, call); - origin.add_filter(AllowedPopApiCalls::contains); + origin.add_filter(AllowedApiCalls::contains); match call.dispatch(origin) { Ok(info) => { @@ -222,7 +223,7 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, - RuntimeStateKeys::Assets(key) => read_trust_backed_assets_state::(key, &mut env), + RuntimeStateKeys::Assets(key) => read_assets_state::(key, &mut env), }? .encode(); @@ -299,7 +300,7 @@ where } } -fn read_trust_backed_assets_state( +fn read_assets_state( key: AssetsKeys, env: &mut Environment, ) -> Result, DispatchError> diff --git a/runtime/devnet/src/lib.rs b/runtime/devnet/src/lib.rs index 416a3298..b03bdac6 100644 --- a/runtime/devnet/src/lib.rs +++ b/runtime/devnet/src/lib.rs @@ -253,8 +253,8 @@ impl Contains for FilteredCalls { } /// A type to identify allowed calls to the Runtime from contracts. Used by Pop API -pub struct AllowedPopApiCalls; -impl Contains for crate::AllowedPopApiCalls { +pub struct AllowedApiCalls; +impl Contains for crate::AllowedApiCalls { fn contains(c: &RuntimeCall) -> bool { use config::assets::AssetsCall; use pallet_nfts::Call as NftsCall; diff --git a/runtime/devnet/src/tests/local_fungibles.rs b/runtime/devnet/src/tests/local_fungibles.rs index 154e9897..ac2b8ca0 100644 --- a/runtime/devnet/src/tests/local_fungibles.rs +++ b/runtime/devnet/src/tests/local_fungibles.rs @@ -9,8 +9,8 @@ use super::*; use pop_api::{ - error::{ArithmeticError::*, PopApiError::*, TokenError::*}, - v0::assets::use_cases::fungibles::FungiblesError::*, + error::{ArithmeticError::*, Error::*, TokenError::*}, + v0::assets::fungibles::FungiblesError::*, }; const ASSET_ID: AssetId = 1; @@ -268,7 +268,7 @@ fn create_works() { instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); // No balance to pay for fees. assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), + decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), Module { index: 10, error: 2 }, ); // Instantiate a contract without balance (relay token). @@ -277,7 +277,7 @@ fn create_works() { // TODO: make sure it has enough for the fees but not for the deposit. // No balance to pay fe deposit. assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), + decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), Module { index: 10, error: 2 }, ); // Instantiate a contract with balance. @@ -289,12 +289,12 @@ fn create_works() { create_asset(ALICE, ASSET_ID, 1); // Asset ID is already taken. assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), + decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), Module { index: 52, error: 5 }, ); // The minimal balance for an asset must be non zero. assert_eq!( - decoded::(create(addr.clone(), new_asset, BOB, 0)), + decoded::(create(addr.clone(), new_asset, BOB, 0)), Module { index: 52, error: 7 }, ); let result = create(addr.clone(), new_asset, BOB, 1); @@ -333,39 +333,25 @@ fn transfer_from_mint_works() { // Asset does not exist. assert_eq!( - decoded::(transfer_from(addr.clone(), 1, None, Some(BOB), amount, &[0u8])), + decoded::(transfer_from(addr.clone(), 1, None, Some(BOB), amount, &[0u8])), Token(UnknownAsset) ); let asset = create_asset(ALICE, 1, 2); // Minting can only be done by the owner. assert_eq!( - decoded::(transfer_from( - addr.clone(), - asset, - None, - Some(BOB), - amount, - &[0u8] - )), + decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), Module { index: 52, error: 2 }, ); // Minimum balance of an asset can not be zero. assert_eq!( - decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), 1, &[0u8])), + decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), 1, &[0u8])), Token(BelowMinimum) ); let asset = create_asset(addr.clone(), 2, 2); // Asset is not live, i.e. frozen or being destroyed. freeze_asset(asset, addr.clone()); assert_eq!( - decoded::(transfer_from( - addr.clone(), - asset, - None, - Some(BOB), - amount, - &[0u8] - )), + decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), Module { index: 52, error: 16 }, ); thaw_asset(asset, addr.clone()); @@ -377,7 +363,7 @@ fn transfer_from_mint_works() { assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount); // Can not mint more tokens than Balance::MAX. assert_eq!( - decoded::(transfer_from( + decoded::(transfer_from( addr.clone(), asset, None, @@ -390,14 +376,7 @@ fn transfer_from_mint_works() { // Asset is not live, i.e. frozen or being destroyed. start_destroy_asset(asset, addr.clone()); assert_eq!( - decoded::(transfer_from( - addr.clone(), - asset, - None, - Some(BOB), - amount, - &[0u8] - )), + decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), Module { index: 52, error: 16 }, ); }); @@ -417,7 +396,7 @@ fn transfer_works() { // Asset does not exist. assert_eq!( - decoded::(transfer(addr.clone(), 1, BOB, amount,)), + decoded::(transfer(addr.clone(), 1, BOB, amount,)), Module { index: 52, error: 3 }, ); // Create asset with Alice as owner and mint `amount` to contract address. @@ -425,18 +404,18 @@ fn transfer_works() { // Asset is not live, i.e. frozen or being destroyed. freeze_asset(asset, ALICE); assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount,)), + decoded::(transfer(addr.clone(), asset, BOB, amount,)), Module { index: 52, error: 16 }, ); thaw_asset(asset, ALICE); // Not enough balance. assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), + decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), Module { index: 52, error: 0 }, ); // Not enough balance due to ED. assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount)), + decoded::(transfer(addr.clone(), asset, BOB, amount)), Module { index: 52, error: 0 }, ); // Successful transfer. @@ -447,13 +426,13 @@ fn transfer_works() { assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); // Transfer asset to account that does not exist. assert_eq!( - decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), + decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), Token(CannotCreate) ); // Asset is not live, i.e. frozen or being destroyed. start_destroy_asset(asset, ALICE); assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), + decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), Module { index: 52, error: 16 }, ); }); diff --git a/runtime/devnet/src/tests/mod.rs b/runtime/devnet/src/tests/mod.rs index dcb97ae1..828aa06b 100644 --- a/runtime/devnet/src/tests/mod.rs +++ b/runtime/devnet/src/tests/mod.rs @@ -1,16 +1,13 @@ #![cfg(test)] -use crate::{ - config::assets::TrustBackedAssetsInstance, Assets, Contracts, Runtime, RuntimeOrigin, System, - Weight, UNIT, -}; use codec::{Decode, Encode}; use frame_support::traits::fungibles::{approvals::Inspect as ApprovalInspect, Inspect}; use frame_system::Config; use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; -use pop_api::error::{ArithmeticError, PopApiError, TokenError, TransactionalError}; use sp_runtime::{traits::Hash, AccountId32, BuildStorage, DispatchError}; +use crate::{Assets, Contracts, Runtime, RuntimeOrigin, System, Weight, UNIT}; + mod local_fungibles; type Balance = u128; @@ -97,166 +94,174 @@ fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { result.account_id } -pub fn get_pallet_index() -> u8 { - // Get the index of the pallet (module) - <::PalletInfo as frame_support::traits::PalletInfo>::index::() - .expect("Every active module has an index in the runtime; qed") as u8 -} - -#[test] -fn encoding_decoding_dispatch_error() { - use codec::{Decode, Encode}; - use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; +mod encoding { + use super::*; + use crate::config::assets::TrustBackedAssetsInstance; + use crate::Runtime; + use sp_runtime::DispatchError; - new_test_ext().execute_with(|| { - let error = DispatchError::Module(ModuleError { - index: 255, - error: [2, 0, 0, 0], - message: Some("error message"), - }); - let encoded = error.encode(); - let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); - assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); - assert_eq!( - decoded, - // `message` is skipped for encoding. - DispatchError::Module(ModuleError { index: 255, error: [2, 0, 0, 0], message: None }) - ); - println!("Encoded Module Error: {:?}", encoded); + #[test] + fn encoding_decoding_dispatch_error() { + use codec::{Decode, Encode}; + use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; - // Example pallet assets Error into ModuleError - let index = get_pallet_index::(); - let mut error = - pallet_assets::Error::NotFrozen::.encode(); - error.resize(sp_runtime::MAX_MODULE_ERROR_ENCODED_SIZE, 0); - let message = None; - let error = DispatchError::Module(ModuleError { - index, - error: TryInto::try_into(error).expect("should work"), - message, - }); - let encoded = error.encode(); - let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); - assert_eq!(encoded, vec![3, 52, 18, 0, 0, 0]); - assert_eq!( - decoded, - DispatchError::Module(ModuleError { index: 52, error: [18, 0, 0, 0], message: None }) - ); - println!("Encoded Module Error: {:?}", encoded); + new_test_ext().execute_with(|| { + let error = DispatchError::Module(ModuleError { + index: 255, + error: [2, 0, 0, 0], + message: Some("error message"), + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); + assert_eq!( + decoded, + // `message` is skipped for encoding. + DispatchError::Module(ModuleError { + index: 255, + error: [2, 0, 0, 0], + message: None + }) + ); + println!("Encoded Module Error: {:?}", encoded); - // Example DispatchError::Token - let error = DispatchError::Token(TokenError::UnknownAsset); - let encoded = error.encode(); - assert_eq!(encoded, vec![7, 4]); - println!("Encoded Token Error: {:?}", encoded); + // Example pallet assets Error into ModuleError. + let index = + <::PalletInfo as frame_support::traits::PalletInfo>::index::< + Assets, + >() + .expect("Every active module has an index in the runtime; qed") as u8; - // Example DispatchError::Arithmetic - let error = DispatchError::Arithmetic(ArithmeticError::Overflow); - let encoded = error.encode(); - assert_eq!(encoded, vec![8, 1]); - println!("Encoded Arithmetic Error: {:?}", encoded); - }); -} + let mut error = + pallet_assets::Error::NotFrozen::.encode(); + error.resize(sp_runtime::MAX_MODULE_ERROR_ENCODED_SIZE, 0); + let error = DispatchError::Module(ModuleError { + index, + error: TryInto::try_into(error).expect("should work"), + message: None, + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 52, 18, 0, 0, 0]); + assert_eq!( + decoded, + DispatchError::Module(ModuleError { + index: 52, + error: [18, 0, 0, 0], + message: None + }) + ); + println!("Encoded Module Error: {:?}", encoded); -#[test] -fn encoding_of_enum() { - use codec::{Decode, Encode}; + // Example DispatchError::Token + let error = DispatchError::Token(TokenError::UnknownAsset); + let encoded = error.encode(); + assert_eq!(encoded, vec![7, 4]); + println!("Encoded Token Error: {:?}", encoded); - // Comprehensive enum with all different type of variants. - #[derive(Debug, PartialEq, Encode, Decode)] - enum ComprehensiveEnum { - SimpleVariant, - DataVariant(u8), - NamedFields { w: u8 }, - NestedEnum(InnerEnum), - OptionVariant(Option), - VecVariant(Vec), - TupleVariant(u8, u8), - NestedStructVariant(NestedStruct), - NestedEnumStructVariant(NestedEnumStruct), + // Example DispatchError::Arithmetic + let error = DispatchError::Arithmetic(ArithmeticError::Overflow); + let encoded = error.encode(); + assert_eq!(encoded, vec![8, 1]); + println!("Encoded Arithmetic Error: {:?}", encoded); + }); } - #[derive(Debug, PartialEq, Encode, Decode)] - enum InnerEnum { - A, - B { inner_data: u8 }, - C(u8), - } + #[test] + fn encoding_of_enum() { + use codec::{Decode, Encode}; - #[derive(Debug, PartialEq, Encode, Decode)] - struct NestedStruct { - x: u8, - y: u8, - } + // Comprehensive enum with all different type of variants. + #[derive(Debug, PartialEq, Encode, Decode)] + enum ComprehensiveEnum { + SimpleVariant, + DataVariant(u8), + NamedFields { w: u8 }, + NestedEnum(InnerEnum), + OptionVariant(Option), + VecVariant(Vec), + TupleVariant(u8, u8), + NestedStructVariant(NestedStruct), + NestedEnumStructVariant(NestedEnumStruct), + } - #[derive(Debug, PartialEq, Encode, Decode)] - struct NestedEnumStruct { - inner_enum: InnerEnum, - } + #[derive(Debug, PartialEq, Encode, Decode)] + enum InnerEnum { + A, + B { inner_data: u8 }, + C(u8), + } - // Creating each possible variant for an enum. - let enum_simple = ComprehensiveEnum::SimpleVariant; - let enum_data = ComprehensiveEnum::DataVariant(42); - let enum_named = ComprehensiveEnum::NamedFields { w: 42 }; - let enum_nested = ComprehensiveEnum::NestedEnum(InnerEnum::B { inner_data: 42 }); - let enum_option = ComprehensiveEnum::OptionVariant(Some(42)); - let enum_vec = ComprehensiveEnum::VecVariant(vec![1, 2, 3, 4, 5]); - let enum_tuple = ComprehensiveEnum::TupleVariant(42, 42); - let enum_nested_struct = ComprehensiveEnum::NestedStructVariant(NestedStruct { x: 42, y: 42 }); - let enum_nested_enum_struct = ComprehensiveEnum::NestedEnumStructVariant(NestedEnumStruct { - inner_enum: InnerEnum::C(42), - }); + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedStruct { + x: u8, + y: u8, + } - // Encode and print each variant individually to see their encoded values. - println!("{:?} -> {:?}", enum_simple, enum_simple.encode()); - println!("{:?} -> {:?}", enum_data, enum_data.encode()); - println!("{:?} -> {:?}", enum_named, enum_named.encode()); - println!("{:?} -> {:?}", enum_nested, enum_nested.encode()); - println!("{:?} -> {:?}", enum_option, enum_option.encode()); - println!("{:?} -> {:?}", enum_vec, enum_vec.encode()); - println!("{:?} -> {:?}", enum_tuple, enum_tuple.encode()); - println!("{:?} -> {:?}", enum_nested_struct, enum_nested_struct.encode()); - println!("{:?} -> {:?}", enum_nested_enum_struct, enum_nested_enum_struct.encode()); -} + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedEnumStruct { + inner_enum: InnerEnum, + } -#[test] -fn dispatch_error_to_status_code_to_pop_api_error_works() { - // Create all the different `DispatchError` variants with its respective `PopApiError`. - let test_cases = vec![ - (DispatchError::CannotLookup, PopApiError::CannotLookup), - (DispatchError::BadOrigin, PopApiError::BadOrigin), - ( - DispatchError::Module(sp_runtime::ModuleError { - index: 1, - error: [2, 0, 0, 0], - message: Some("hallo"), - }), - PopApiError::Module { index: 1, error: 2 }, - ), - (DispatchError::ConsumerRemaining, PopApiError::ConsumerRemaining), - (DispatchError::NoProviders, PopApiError::NoProviders), - (DispatchError::TooManyConsumers, PopApiError::TooManyConsumers), - ( - DispatchError::Token(sp_runtime::TokenError::FundsUnavailable), - PopApiError::Token(TokenError::FundsUnavailable), - ), - ( - DispatchError::Arithmetic(sp_runtime::ArithmeticError::Overflow), - PopApiError::Arithmetic(ArithmeticError::Overflow), - ), - ( - DispatchError::Transactional(sp_runtime::TransactionalError::LimitReached), - PopApiError::Transactional(TransactionalError::LimitReached), - ), - (DispatchError::Exhausted, PopApiError::Exhausted), - (DispatchError::Corruption, PopApiError::Corruption), - (DispatchError::Unavailable, PopApiError::Unavailable), - (DispatchError::RootNotAllowed, PopApiError::RootNotAllowed), - ]; - for (error, pop_api_error) in test_cases { - // Show that the encoding and decoding of the PopApiError <> u32 (status code) works. - let status_code = crate::extensions::convert_to_status_code(error); - // let error = pop_api::error::convert_to_pop_api_error(status_code); - // assert_eq!(pop_api_error, error,); + // Creating each possible variant for an enum. + let enum_simple = ComprehensiveEnum::SimpleVariant; + let enum_data = ComprehensiveEnum::DataVariant(42); + let enum_named = ComprehensiveEnum::NamedFields { w: 42 }; + let enum_nested = ComprehensiveEnum::NestedEnum(InnerEnum::B { inner_data: 42 }); + let enum_option = ComprehensiveEnum::OptionVariant(Some(42)); + let enum_vec = ComprehensiveEnum::VecVariant(vec![1, 2, 3, 4, 5]); + let enum_tuple = ComprehensiveEnum::TupleVariant(42, 42); + let enum_nested_struct = + ComprehensiveEnum::NestedStructVariant(NestedStruct { x: 42, y: 42 }); + let enum_nested_enum_struct = + ComprehensiveEnum::NestedEnumStructVariant(NestedEnumStruct { + inner_enum: InnerEnum::C(42), + }); + + // Encode and print each variant individually to see their encoded values. + println!("{:?} -> {:?}", enum_simple, enum_simple.encode()); + println!("{:?} -> {:?}", enum_data, enum_data.encode()); + println!("{:?} -> {:?}", enum_named, enum_named.encode()); + println!("{:?} -> {:?}", enum_nested, enum_nested.encode()); + println!("{:?} -> {:?}", enum_option, enum_option.encode()); + println!("{:?} -> {:?}", enum_vec, enum_vec.encode()); + println!("{:?} -> {:?}", enum_tuple, enum_tuple.encode()); + println!("{:?} -> {:?}", enum_nested_struct, enum_nested_struct.encode()); + println!("{:?} -> {:?}", enum_nested_enum_struct, enum_nested_enum_struct.encode()); + } + + #[test] + fn dispatch_error_to_status_code() { + // Create all the different `DispatchError` variants with its respective `PopApiError`. + let test_cases = vec![ + (DispatchError::Other("hallo"), [0, 0, 0, 0]), + (DispatchError::CannotLookup, [1, 0, 0, 0]), + (DispatchError::BadOrigin, [2, 0, 0, 0]), + ( + DispatchError::Module(sp_runtime::ModuleError { + index: 1, + error: [2, 0, 0, 0], + message: Some("hallo"), + }), + [3, 1, 2, 0], + ), + (DispatchError::ConsumerRemaining, [4, 0, 0, 0]), + (DispatchError::NoProviders, [5, 0, 0, 0]), + (DispatchError::TooManyConsumers, [6, 0, 0, 0]), + (DispatchError::Token(sp_runtime::TokenError::BelowMinimum), [7, 2, 0, 0]), + (DispatchError::Arithmetic(sp_runtime::ArithmeticError::Overflow), [8, 1, 0, 0]), + ( + DispatchError::Transactional(sp_runtime::TransactionalError::LimitReached), + [9, 0, 0, 0], + ), + (DispatchError::Exhausted, [10, 0, 0, 0]), + (DispatchError::Corruption, [11, 0, 0, 0]), + (DispatchError::Unavailable, [12, 0, 0, 0]), + (DispatchError::RootNotAllowed, [13, 0, 0, 0]), + ]; + for (error, encoded_error) in test_cases { + let status_code = crate::extensions::convert_to_status_code(error); + assert_eq!(status_code, u32::decode(&mut &encoded_error[..]).unwrap()); + } } } diff --git a/runtime/testnet/Cargo.toml b/runtime/testnet/Cargo.toml index 43b1e310..b7aa7b76 100644 --- a/runtime/testnet/Cargo.toml +++ b/runtime/testnet/Cargo.toml @@ -22,7 +22,7 @@ scale-info.workspace = true smallvec.workspace = true # Local -pop-primitives = { workspace = true, features = ["testnet"] } +pop-primitives = { workspace = true, features = ["assets", "nfts", "cross-chain"] } pop-runtime-common = { workspace = true, default-features = false } # Substrate diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index a3284ad4..dd2c52bb 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -9,8 +9,8 @@ use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, }; use pop_primitives::{ + nfts::{CollectionId, ItemId}, storage_keys::{NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, - CollectionId, ItemId, }; use sp_core::crypto::UncheckedFrom; use sp_runtime::{ @@ -19,7 +19,7 @@ use sp_runtime::{ }; use sp_std::vec::Vec; -use crate::{AccountId, AllowedPopApiCalls, RuntimeCall, RuntimeOrigin}; +use crate::{AccountId, AllowedApiCalls, RuntimeCall, RuntimeOrigin}; const LOG_TARGET: &str = "pop-api::extension"; @@ -110,7 +110,7 @@ where log::debug!(target:LOG_TARGET, "{} inputted RuntimeCall: {:?}", log_prefix, call); - origin.add_filter(AllowedPopApiCalls::contains); + origin.add_filter(AllowedApiCalls::contains); match call.dispatch(origin) { Ok(info) => { diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index 66a5092c..c4178011 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -250,8 +250,8 @@ impl Contains for FilteredCalls { } /// A type to identify allowed calls to the Runtime from contracts. Used by Pop API -pub struct AllowedPopApiCalls; -impl Contains for crate::AllowedPopApiCalls { +pub struct AllowedApiCalls; +impl Contains for AllowedApiCalls { fn contains(c: &RuntimeCall) -> bool { use pallet_nfts::Call as NftsCall; matches!( From 61b3a17d39b9bbbc76f87665a9546da9e0b58f89 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Wed, 26 Jun 2024 10:48:23 +0200 Subject: [PATCH 12/27] refactor: tests local fungibles --- Cargo.lock | 2787 ++++++----------- Cargo.toml | 28 +- pop-api/Cargo.toml | 6 +- pop-api/examples/.gitignore | 4 +- pop-api/examples/fungibles/lib.rs | 18 +- pop-api/integration-tests/Cargo.toml | 31 + pop-api/integration-tests/src/lib.rs | 95 + .../integration-tests/src}/local_fungibles.rs | 71 +- pop-api/src/lib.rs | 3 +- pop-api/src/v0/assets/mod.rs | 8 +- primitives/Cargo.toml | 4 +- primitives/src/storage_keys.rs | 4 +- runtime/devnet/Cargo.toml | 2 - runtime/devnet/src/extensions.rs | 180 ++ runtime/devnet/src/lib.rs | 2 - runtime/devnet/src/tests/mod.rs | 267 -- 16 files changed, 1331 insertions(+), 2179 deletions(-) create mode 100644 pop-api/integration-tests/Cargo.toml create mode 100644 pop-api/integration-tests/src/lib.rs rename {runtime/devnet/src/tests => pop-api/integration-tests/src}/local_fungibles.rs (88%) delete mode 100644 runtime/devnet/src/tests/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 77c563fb..d798562b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -343,7 +343,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" dependencies = [ "num-traits", - "rand 0.8.5", + "rand", ] [[package]] @@ -358,12 +358,6 @@ version = "6.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f840fb7195bcfc5e17ea40c26e5ce6d5b9ce5d584466e17703209657e459ae0" -[[package]] -name = "array-init" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" - [[package]] name = "arrayref" version = "0.3.7" @@ -379,12 +373,6 @@ dependencies = [ "nodrop", ] -[[package]] -name = "arrayvec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" - [[package]] name = "arrayvec" version = "0.7.4" @@ -416,7 +404,7 @@ dependencies = [ "proc-macro2", "quote", "syn 1.0.109", - "synstructure 0.12.6", + "synstructure", ] [[package]] @@ -498,17 +486,17 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-consensus-aura", - "sp-core 29.0.0", + "sp-core", "sp-genesis-builder", "sp-inherents", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", - "sp-std 14.0.0", - "sp-storage 20.0.0", + "sp-std", + "sp-storage", "sp-transaction-pool", "sp-version", - "sp-weights 28.0.0", + "sp-weights", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -537,9 +525,9 @@ dependencies = [ "parachains-common", "parachains-runtimes-test-utils", "parity-scale-codec", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -563,8 +551,8 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -921,7 +909,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93f2635620bf0b9d4576eb7bb9a38a55df78bd1205d26fa994b25911a69f212f" dependencies = [ "bitcoin_hashes", - "rand 0.8.5", + "rand", "rand_core 0.6.4", "serde", "unicode-normalization", @@ -1024,18 +1012,6 @@ dependencies = [ "constant_time_eq 0.3.0", ] -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding", - "byte-tools", - "byteorder", - "generic-array 0.12.4", -] - [[package]] name = "block-buffer" version = "0.9.0" @@ -1054,15 +1030,6 @@ dependencies = [ "generic-array 0.14.7", ] -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", -] - [[package]] name = "blocking" version = "1.5.1" @@ -1149,7 +1116,7 @@ dependencies = [ "frame-system", "polkadot-primitives", "sp-api", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -1163,8 +1130,8 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -1178,8 +1145,8 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -1195,9 +1162,9 @@ dependencies = [ "scale-info", "serde", "sp-consensus-grandpa", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -1212,8 +1179,8 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-std", ] [[package]] @@ -1229,9 +1196,9 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -1248,9 +1215,9 @@ dependencies = [ "parity-util-mem", "scale-info", "serde", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -1264,8 +1231,8 @@ dependencies = [ "frame-support", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -1283,13 +1250,13 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", - "trie-db 0.28.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-trie", + "trie-db", ] [[package]] @@ -1302,15 +1269,15 @@ dependencies = [ "bp-parachains", "bp-polkadot-core", "bp-runtime", - "ed25519-dalek 2.1.1", + "ed25519-dalek", "finality-grandpa", "parity-scale-codec", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-grandpa", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-core", + "sp-runtime", + "sp-std", + "sp-trie", ] [[package]] @@ -1319,7 +1286,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6663e0179d475e30cfcf28cf597cdc8f4bb1c2c39a557b4cbe0057db0657fb67" dependencies = [ - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -1330,8 +1297,8 @@ checksum = "86ff4abe93be7bc1663adc41817b1aa3476fbec953ce361537419924310d5dd4" dependencies = [ "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", ] [[package]] @@ -1361,11 +1328,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-trie", "staging-xcm", "staging-xcm-builder", ] @@ -1778,26 +1745,6 @@ dependencies = [ "tiny-keccak", ] -[[package]] -name = "const_env" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e9e4f72c6e3398ca6da372abd9affd8f89781fe728869bbf986206e9af9627e" -dependencies = [ - "const_env_impl", -] - -[[package]] -name = "const_env_impl" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a4f51209740b5e1589e702b3044cdd4562cef41b6da404904192ffffb852d62" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "constant_time_eq" version = "0.1.5" @@ -2097,8 +2044,8 @@ dependencies = [ "sc-client-api", "sc-service", "sp-blockchain", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "url", ] @@ -2121,8 +2068,8 @@ dependencies = [ "sc-client-api", "sp-api", "sp-consensus", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "tracing", ] @@ -2154,16 +2101,16 @@ dependencies = [ "sc-telemetry", "schnellru", "sp-api", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-keystore", + "sp-runtime", + "sp-state-machine", "sp-timestamp", "substrate-prometheus-endpoint", "tracing", @@ -2191,10 +2138,10 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-slots", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "sp-timestamp", - "sp-trie 30.0.0", + "sp-trie", "substrate-prometheus-endpoint", "tracing", ] @@ -2210,8 +2157,8 @@ dependencies = [ "cumulus-primitives-parachain-inherent", "sp-consensus", "sp-inherents", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-runtime", + "sp-state-machine", "thiserror", ] @@ -2233,9 +2180,9 @@ dependencies = [ "sc-client-api", "sp-blockchain", "sp-consensus", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-core", + "sp-runtime", + "sp-state-machine", "tracing", ] @@ -2256,11 +2203,11 @@ dependencies = [ "sp-api", "sp-crypto-hashing", "sp-inherents", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-storage 20.0.0", - "sp-trie 30.0.0", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-storage", + "sp-trie", "tracing", ] @@ -2280,12 +2227,12 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-overseer", "polkadot-primitives", - "rand 0.8.5", + "rand", "sc-client-api", "sc-consensus", "sp-consensus", "sp-maybe-compressed-blob", - "sp-runtime 32.0.0", + "sp-runtime", "tracing", ] @@ -2321,8 +2268,8 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "sp-transaction-pool", ] @@ -2339,10 +2286,10 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-aura", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -2368,17 +2315,17 @@ dependencies = [ "polkadot-runtime-common", "polkadot-runtime-parachains", "scale-info", - "sp-core 29.0.0", - "sp-externalities 0.26.0", + "sp-core", + "sp-externalities", "sp-inherents", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-io", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-trie", "sp-version", "staging-xcm", - "trie-db 0.28.0", + "trie-db", ] [[package]] @@ -2404,8 +2351,8 @@ dependencies = [ "frame-system", "pallet-session", "parity-scale-codec", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -2419,9 +2366,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", ] @@ -2443,10 +2390,10 @@ dependencies = [ "polkadot-runtime-common", "polkadot-runtime-parachains", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-executor", ] @@ -2462,8 +2409,8 @@ dependencies = [ "polkadot-primitives", "sp-api", "sp-consensus-aura", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -2478,9 +2425,9 @@ dependencies = [ "polkadot-primitives", "scale-info", "sp-api", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-runtime", + "sp-std", + "sp-trie", "staging-xcm", ] @@ -2494,10 +2441,10 @@ dependencies = [ "cumulus-primitives-core", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-std", + "sp-trie", ] [[package]] @@ -2506,9 +2453,9 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b74f9141190b9f4bf96a947ade46da64097b77f1ebfa8d611c81724250e119" dependencies = [ - "sp-externalities 0.26.0", - "sp-runtime-interface 25.0.0", - "sp-trie 30.0.0", + "sp-externalities", + "sp-runtime-interface", + "sp-trie", ] [[package]] @@ -2524,9 +2471,9 @@ dependencies = [ "parity-scale-codec", "polkadot-runtime-common", "polkadot-runtime-parachains", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -2552,9 +2499,9 @@ dependencies = [ "sc-tracing", "sp-api", "sp-consensus", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-core", + "sp-runtime", + "sp-state-machine", ] [[package]] @@ -2572,7 +2519,7 @@ dependencies = [ "sc-client-api", "sp-api", "sp-blockchain", - "sp-state-machine 0.36.0", + "sp-state-machine", "thiserror", ] @@ -2612,7 +2559,7 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-runtime 32.0.0", + "sp-runtime", "substrate-prometheus-endpoint", "tokio", "tracing", @@ -2634,7 +2581,7 @@ dependencies = [ "parity-scale-codec", "pin-project", "polkadot-overseer", - "rand 0.8.5", + "rand", "sc-client-api", "sc-rpc-api", "sc-service", @@ -2646,10 +2593,10 @@ dependencies = [ "sp-api", "sp-authority-discovery", "sp-consensus-babe", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-storage 20.0.0", + "sp-core", + "sp-runtime", + "sp-state-machine", + "sp-storage", "sp-version", "thiserror", "tokio", @@ -2667,23 +2614,10 @@ dependencies = [ "cumulus-primitives-core", "parity-scale-codec", "polkadot-primitives", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", -] - -[[package]] -name = "curve25519-dalek" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a9b85542f99a2dfa2a1b8e192662741c9859a846b296bef1c92ef9b58b5a216" -dependencies = [ - "byteorder", - "digest 0.8.1", - "rand_core 0.5.1", - "subtle 2.5.0", - "zeroize", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-trie", ] [[package]] @@ -3130,19 +3064,10 @@ dependencies = [ "digest 0.10.7", "elliptic-curve", "rfc6979", - "signature 2.2.0", + "signature", "spki", ] -[[package]] -name = "ed25519" -version = "1.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7" -dependencies = [ - "signature 1.6.4", -] - [[package]] name = "ed25519" version = "2.2.3" @@ -3150,19 +3075,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ "pkcs8", - "signature 2.2.0", -] - -[[package]] -name = "ed25519-dalek" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d" -dependencies = [ - "curve25519-dalek 3.2.0", - "ed25519 1.5.3", - "sha2 0.9.9", - "zeroize", + "signature", ] [[package]] @@ -3172,7 +3085,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" dependencies = [ "curve25519-dalek 4.1.2", - "ed25519 2.2.3", + "ed25519", "rand_core 0.6.4", "serde", "sha2 0.10.8", @@ -3201,7 +3114,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d9ce6874da5d4415896cd45ffbc4d1cfc0c4f9c079427bd870742c30f2f65a9" dependencies = [ "curve25519-dalek 4.1.2", - "ed25519 2.2.3", + "ed25519", "hashbrown 0.14.3", "hex", "rand_core 0.6.4", @@ -3261,8 +3174,8 @@ dependencies = [ "sc-consensus-grandpa", "sp-authority-discovery", "sp-consensus-babe", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "staging-xcm", "xcm-emulator", ] @@ -3509,12 +3422,6 @@ dependencies = [ "syn 2.0.58", ] -[[package]] -name = "fake-simd" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" - [[package]] name = "fallible-iterator" version = "0.2.0" @@ -3632,7 +3539,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" dependencies = [ "byteorder", - "rand 0.8.5", + "rand", "rustc-hex", "static_assertions", ] @@ -3709,13 +3616,13 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-runtime-interface 25.0.0", - "sp-std 14.0.0", - "sp-storage 20.0.0", + "sp-application-crypto", + "sp-core", + "sp-io", + "sp-runtime", + "sp-runtime-interface", + "sp-std", + "sp-storage", "static_assertions", ] @@ -3740,7 +3647,7 @@ dependencies = [ "linked-hash-map", "log", "parity-scale-codec", - "rand 0.8.5", + "rand", "rand_pcg", "sc-block-builder", "sc-cli", @@ -3753,17 +3660,17 @@ dependencies = [ "serde_json", "sp-api", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-database", - "sp-externalities 0.26.0", + "sp-externalities", "sp-inherents", - "sp-io 31.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-storage 20.0.0", - "sp-trie 30.0.0", - "sp-wasm-interface 20.0.0", + "sp-io", + "sp-keystore", + "sp-runtime", + "sp-state-machine", + "sp-storage", + "sp-trie", + "sp-wasm-interface", "thiserror", "thousands", ] @@ -3791,11 +3698,11 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", + "sp-arithmetic", + "sp-core", "sp-npos-elections", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -3810,11 +3717,11 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-tracing 16.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-tracing", ] [[package]] @@ -3852,11 +3759,11 @@ dependencies = [ "log", "parity-scale-codec", "serde", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-io", + "sp-runtime", + "sp-state-machine", "spinners", "substrate-rpc-client", "tokio", @@ -3887,20 +3794,20 @@ dependencies = [ "serde_json", "smallvec", "sp-api", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", + "sp-arithmetic", + "sp-core", "sp-crypto-hashing-proc-macro", - "sp-debug-derive 14.0.0", + "sp-debug-derive", "sp-genesis-builder", "sp-inherents", - "sp-io 31.0.0", + "sp-io", "sp-metadata-ir", - "sp-runtime 32.0.0", + "sp-runtime", "sp-staking", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-tracing 16.0.0", - "sp-weights 28.0.0", + "sp-state-machine", + "sp-std", + "sp-tracing", + "sp-weights", "static_assertions", "tt-call", ] @@ -3962,12 +3869,12 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "sp-version", - "sp-weights 28.0.0", + "sp-weights", ] [[package]] @@ -3981,9 +3888,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -4005,8 +3912,8 @@ dependencies = [ "frame-support", "parity-scale-codec", "sp-api", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -4256,7 +4163,7 @@ version = "0.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea1015b5a70616b688dc230cfe50c8af89d972cb132d5a622814d29773b10b9" dependencies = [ - "rand 0.8.5", + "rand", "rand_core 0.6.4", ] @@ -4762,206 +4669,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "ink" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d4a862aedbfda93175ddf75c9aaa2ae4c4b39ee5cee06c16d50bccce05bf5c7" -dependencies = [ - "derive_more", - "ink_env", - "ink_macro", - "ink_metadata", - "ink_prelude", - "ink_primitives", - "ink_storage", - "pallet-contracts-uapi-next", - "parity-scale-codec", - "scale-info", -] - -[[package]] -name = "ink_allocator" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cee56055bac6d928d425e944c5f3b69baa33c9635822fd1c00cd4afc70fde3e" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "ink_codegen" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70a1f8473fa09e0f9b6f3cb3f8d18c07c14ebf9ea1f7cdfee270f009d45ee8e9" -dependencies = [ - "blake2 0.10.6", - "derive_more", - "either", - "heck 0.4.1", - "impl-serde", - "ink_ir", - "ink_primitives", - "itertools 0.12.1", - "parity-scale-codec", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn 2.0.58", -] - -[[package]] -name = "ink_engine" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f357e2e867f4e222ffc4015a6e61d1073548de89f70a4e36a8b0385562777fa" -dependencies = [ - "blake2 0.10.6", - "derive_more", - "ink_primitives", - "pallet-contracts-uapi-next", - "parity-scale-codec", - "secp256k1 0.28.2", - "sha2 0.10.8", - "sha3", -] - -[[package]] -name = "ink_env" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42cec50b7e4f8406aab25801b015d3802a52d76cfbe48ce11cfb4200fa88e296" -dependencies = [ - "blake2 0.10.6", - "cfg-if", - "const_env", - "derive_more", - "ink_allocator", - "ink_engine", - "ink_prelude", - "ink_primitives", - "ink_storage_traits", - "num-traits", - "pallet-contracts-uapi-next", - "parity-scale-codec", - "paste", - "rlibc", - "scale-decode", - "scale-encode", - "scale-info", - "schnorrkel 0.11.4", - "secp256k1 0.28.2", - "sha2 0.10.8", - "sha3", - "static_assertions", -] - -[[package]] -name = "ink_ir" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1ad2975551c4ed800af971289ed6d2c68ac41ffc03a42010b3e01d7360dfb2" -dependencies = [ - "blake2 0.10.6", - "either", - "impl-serde", - "ink_prelude", - "itertools 0.12.1", - "proc-macro2", - "quote", - "syn 2.0.58", -] - -[[package]] -name = "ink_macro" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aee1a546f37eae3b3cd223832d31702033c5369dcfa3405899587c110a7908d3" -dependencies = [ - "ink_codegen", - "ink_ir", - "ink_primitives", - "parity-scale-codec", - "proc-macro2", - "quote", - "syn 2.0.58", - "synstructure 0.13.1", -] - -[[package]] -name = "ink_metadata" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a98fcc0ff9292ff68c7ee7b84c93533c9ff13859ec3b148faa822e2da9954fe6" -dependencies = [ - "derive_more", - "impl-serde", - "ink_prelude", - "ink_primitives", - "linkme", - "parity-scale-codec", - "scale-info", - "schemars", - "serde", -] - -[[package]] -name = "ink_prelude" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea1734d058c80aa72e59c8ae75624fd8a51791efba21469f273156c0f4cad5c9" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "ink_primitives" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec35ef7f45e67a53b6142d7e7f18e6d9292d76c3a2a1da14cf8423e481813d" -dependencies = [ - "derive_more", - "ink_prelude", - "parity-scale-codec", - "scale-decode", - "scale-encode", - "scale-info", - "xxhash-rust", -] - -[[package]] -name = "ink_storage" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbdb04cad74df858c05bc9cb6f30bbf12da33c3e2cb7ca211749c001fa761aa9" -dependencies = [ - "array-init", - "cfg-if", - "derive_more", - "ink_env", - "ink_metadata", - "ink_prelude", - "ink_primitives", - "ink_storage_traits", - "pallet-contracts-uapi-next", - "parity-scale-codec", - "scale-info", -] - -[[package]] -name = "ink_storage_traits" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83ce49e3d2935fc1ec3e73117119712b187d3123339f6a31624e92f75fa2293d" -dependencies = [ - "ink_metadata", - "ink_prelude", - "ink_primitives", - "parity-scale-codec", - "scale-info", -] - [[package]] name = "inout" version = "0.1.3" @@ -5019,8 +4726,8 @@ dependencies = [ "sp-consensus-babe", "sp-consensus-beefy", "sp-consensus-grandpa", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "staging-xcm", "staging-xcm-executor", "tracing-subscriber 0.3.18", @@ -5216,7 +4923,7 @@ dependencies = [ "hyper", "jsonrpsee-types 0.20.3", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "rustc-hash", "serde", "serde_json", @@ -5549,7 +5256,7 @@ dependencies = [ "parking_lot 0.12.1", "pin-project", "quick-protobuf", - "rand 0.8.5", + "rand", "rw-stream-sink", "smallvec", "thiserror", @@ -5600,12 +5307,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "276bb57e7af15d8f100d3c11cbdd32c6752b7eef4ba7a18ecf464972c07abcce" dependencies = [ "bs58 0.4.0", - "ed25519-dalek 2.1.1", + "ed25519-dalek", "log", "multiaddr", "multihash 0.17.0", "quick-protobuf", - "rand 0.8.5", + "rand", "sha2 0.10.8", "thiserror", "zeroize", @@ -5630,7 +5337,7 @@ dependencies = [ "libp2p-swarm", "log", "quick-protobuf", - "rand 0.8.5", + "rand", "sha2 0.10.8", "smallvec", "thiserror", @@ -5652,7 +5359,7 @@ dependencies = [ "libp2p-identity", "libp2p-swarm", "log", - "rand 0.8.5", + "rand", "smallvec", "socket2 0.4.10", "tokio", @@ -5688,7 +5395,7 @@ dependencies = [ "log", "once_cell", "quick-protobuf", - "rand 0.8.5", + "rand", "sha2 0.10.8", "snow", "static_assertions", @@ -5710,7 +5417,7 @@ dependencies = [ "libp2p-core", "libp2p-swarm", "log", - "rand 0.8.5", + "rand", "void", ] @@ -5730,7 +5437,7 @@ dependencies = [ "log", "parking_lot 0.12.1", "quinn-proto", - "rand 0.8.5", + "rand", "rustls 0.20.9", "thiserror", "tokio", @@ -5748,7 +5455,7 @@ dependencies = [ "libp2p-core", "libp2p-identity", "libp2p-swarm", - "rand 0.8.5", + "rand", "smallvec", ] @@ -5767,7 +5474,7 @@ dependencies = [ "libp2p-identity", "libp2p-swarm-derive", "log", - "rand 0.8.5", + "rand", "smallvec", "tokio", "void", @@ -5903,7 +5610,7 @@ dependencies = [ "libsecp256k1-core", "libsecp256k1-gen-ecmult", "libsecp256k1-gen-genmult", - "rand 0.8.5", + "rand", "serde", "sha2 0.9.9", "typenum", @@ -5973,26 +5680,6 @@ dependencies = [ "linked-hash-map", ] -[[package]] -name = "linkme" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccb76662d78edc9f9bf56360d6919bdacc8b7761227727e5082f128eeb90bbf5" -dependencies = [ - "linkme-impl", -] - -[[package]] -name = "linkme-impl" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dccda732e04fa3baf2e17cf835bfe2601c7c2edafd64417c627dabae3a8cda" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.58", -] - [[package]] name = "linregress" version = "0.5.3" @@ -6264,18 +5951,6 @@ dependencies = [ "hash-db", ] -[[package]] -name = "merlin" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e261cf0f8b3c42ded9f7d2bb59dea03aa52bc8a1cbc7482f9fc3fd1229d3b42" -dependencies = [ - "byteorder", - "keccak", - "rand_core 0.5.1", - "zeroize", -] - [[package]] name = "merlin" version = "3.0.0" @@ -6295,7 +5970,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69672161530e8aeca1d1400fbf3f1a1747ff60ea604265a4e906c2442df20532" dependencies = [ "futures", - "rand 0.8.5", + "rand", "thrift", ] @@ -6342,7 +6017,7 @@ dependencies = [ "lioness", "log", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "rand_distr", "subtle 2.5.0", @@ -6365,9 +6040,9 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-beefy", - "sp-core 29.0.0", + "sp-core", "sp-mmr-primitives", - "sp-runtime 32.0.0", + "sp-runtime", ] [[package]] @@ -6381,9 +6056,9 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-mmr-primitives", - "sp-runtime 32.0.0", + "sp-runtime", ] [[package]] @@ -6514,7 +6189,7 @@ dependencies = [ "proc-macro2", "quote", "syn 1.0.109", - "synstructure 0.12.6", + "synstructure", ] [[package]] @@ -6539,7 +6214,7 @@ dependencies = [ "proc-macro2", "quote", "syn 1.0.109", - "synstructure 0.12.6", + "synstructure", ] [[package]] @@ -6595,7 +6270,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7bddcd3bf5144b6392de80e04c347cd7fab2508f6df16a85fc496ecd5cec39bc" dependencies = [ - "rand 0.8.5", + "rand", ] [[package]] @@ -6923,11 +6598,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -6942,8 +6617,8 @@ dependencies = [ "pallet-transaction-payment", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -6957,9 +6632,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -6975,10 +6650,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -6993,9 +6668,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -7010,10 +6685,10 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-aura", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7027,10 +6702,10 @@ dependencies = [ "pallet-session", "parity-scale-codec", "scale-info", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-authority-discovery", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7044,8 +6719,8 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7063,14 +6738,14 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-babe", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-io", + "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7089,18 +6764,18 @@ dependencies = [ "pallet-balances", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-tracing 16.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-tracing", ] [[package]] name = "pallet-balances" -version = "29.0.1" +version = "29.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e27946a57494d7c6231ae8909275bbd3cb5460ee3d27b7a5774a8b8e64d3ab92" +checksum = "a9a54b5d0c7c4c3731883d6b1ac18aff44db20c3d0a3470c8861001a17afdc85" dependencies = [ "docify", "frame-benchmarking", @@ -7109,8 +6784,8 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7128,10 +6803,10 @@ dependencies = [ "scale-info", "serde", "sp-consensus-beefy", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7153,11 +6828,11 @@ dependencies = [ "serde", "sp-api", "sp-consensus-beefy", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-state-machine", + "sp-std", ] [[package]] @@ -7173,10 +6848,10 @@ dependencies = [ "pallet-treasury", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7196,9 +6871,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-consensus-grandpa", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-runtime", + "sp-std", + "sp-trie", ] [[package]] @@ -7216,8 +6891,8 @@ dependencies = [ "num-traits", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7237,9 +6912,9 @@ dependencies = [ "pallet-bridge-grandpa", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-runtime", + "sp-std", + "sp-trie", ] [[package]] @@ -7258,27 +6933,28 @@ dependencies = [ "pallet-bridge-messages", "parity-scale-codec", "scale-info", - "sp-arithmetic 24.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-broker" -version = "0.7.0" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd8cfe04e8c3f9ca8342ac785f2b1aee6140e1809546fc6f3a99fad20a8dfbf9" +checksum = "574c52fd629191c374c24a18036acac008ea92142309e5dd05e7f03149a667c3" dependencies = [ "bitvec", "frame-benchmarking", "frame-support", "frame-system", + "log", "parity-scale-codec", "scale-info", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -7295,30 +6971,31 @@ dependencies = [ "pallet-treasury", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-collator-selection" -version = "10.0.0" +version = "10.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b5ad46601c613396e92292a24c5b5d76e904c456ece9deb10913f6ea2e2999" +checksum = "49d1157d9a4b7966040158a7b4f1fb29f0cefa8deb6eb9b3452df7ce4161a31c" dependencies = [ "frame-benchmarking", "frame-support", "frame-system", "log", "pallet-authorship", + "pallet-balances", "pallet-session", "parity-scale-codec", - "rand 0.8.5", + "rand", "scale-info", - "sp-runtime 32.0.0", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7333,10 +7010,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7356,16 +7033,16 @@ dependencies = [ "pallet-contracts-proc-macro", "pallet-contracts-uapi", "parity-scale-codec", - "rand 0.8.5", + "rand", "rand_pcg", "scale-info", "serde", "smallvec", "sp-api", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", "wasm-instrument", @@ -7396,17 +7073,6 @@ dependencies = [ "scale-info", ] -[[package]] -name = "pallet-contracts-uapi-next" -version = "6.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd549c16296ea5b2eb7c65c56aba548b286c1be4d7675b424ff6ccb8319c97a9" -dependencies = [ - "bitflags 1.3.2", - "paste", - "polkavm-derive", -] - [[package]] name = "pallet-conviction-voting" version = "29.0.0" @@ -7420,9 +7086,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7438,10 +7104,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7457,14 +7123,14 @@ dependencies = [ "log", "pallet-election-provider-support-benchmarking", "parity-scale-codec", - "rand 0.8.5", + "rand", "scale-info", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", + "sp-arithmetic", + "sp-core", + "sp-io", "sp-npos-elections", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "strum 0.24.1", ] @@ -7479,8 +7145,8 @@ dependencies = [ "frame-system", "parity-scale-codec", "sp-npos-elections", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7495,12 +7161,12 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", + "sp-core", + "sp-io", "sp-npos-elections", - "sp-runtime 32.0.0", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7517,10 +7183,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", + "sp-io", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7537,21 +7203,21 @@ dependencies = [ "pallet-session", "parity-scale-codec", "scale-info", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-grandpa", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-io", + "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] name = "pallet-identity" -version = "29.0.0" +version = "29.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9e1cae19e30e7dc822c419988b30bb1318d79a8d5da92733822d0e84fe760ca" +checksum = "452bba25325b7f0148eeecbde13e7c26dfb677ad46b3f160b359d7643b44c94b" dependencies = [ "enumflags2", "frame-benchmarking", @@ -7560,9 +7226,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7578,12 +7244,12 @@ dependencies = [ "pallet-authorship", "parity-scale-codec", "scale-info", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", + "sp-application-crypto", + "sp-core", + "sp-io", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7597,11 +7263,11 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", + "sp-core", + "sp-io", "sp-keyring", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7616,10 +7282,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7635,12 +7301,12 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-weights 28.0.0", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-weights", ] [[package]] @@ -7655,11 +7321,11 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", + "sp-core", + "sp-io", "sp-mmr-primitives", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7674,9 +7340,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7693,8 +7359,8 @@ dependencies = [ "pallet-nfts", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -7710,10 +7376,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7725,7 +7391,7 @@ dependencies = [ "pallet-nfts", "parity-scale-codec", "sp-api", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7739,10 +7405,10 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -7757,12 +7423,12 @@ dependencies = [ "pallet-balances", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-io", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", - "sp-tracing 16.0.0", + "sp-std", + "sp-tracing", ] [[package]] @@ -7780,10 +7446,10 @@ dependencies = [ "pallet-staking", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-runtime-interface 25.0.0", + "sp-runtime", + "sp-runtime-interface", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7795,7 +7461,7 @@ dependencies = [ "pallet-nomination-pools", "parity-scale-codec", "sp-api", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7811,9 +7477,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-runtime 32.0.0", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7836,9 +7502,9 @@ dependencies = [ "pallet-staking", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -7853,10 +7519,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7870,9 +7536,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7888,11 +7554,11 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7906,9 +7572,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7925,10 +7591,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-arithmetic 24.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7941,10 +7607,10 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7960,10 +7626,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-weights 28.0.0", + "sp-io", + "sp-runtime", + "sp-std", + "sp-weights", ] [[package]] @@ -7979,14 +7645,14 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-io", + "sp-runtime", "sp-session", "sp-staking", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-state-machine", + "sp-std", + "sp-trie", ] [[package]] @@ -8001,10 +7667,10 @@ dependencies = [ "pallet-session", "pallet-staking", "parity-scale-codec", - "rand 0.8.5", - "sp-runtime 32.0.0", + "rand", + "sp-runtime", "sp-session", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -8020,17 +7686,17 @@ dependencies = [ "parity-scale-codec", "rand_chacha 0.2.2", "scale-info", - "sp-arithmetic 24.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-staking" -version = "29.0.2" +version = "29.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "668b7d28c499f0d9f295fad26cf6c342472e21842e3b13bcaaac8536358b2d6c" +checksum = "061b00814eb794a40df4eca7972a7c67b26473cd85cc7c54f5816ae49ad6e11b" dependencies = [ "frame-benchmarking", "frame-election-provider-support", @@ -8043,11 +7709,11 @@ dependencies = [ "rand_chacha 0.2.2", "scale-info", "serde", - "sp-application-crypto 31.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", + "sp-application-crypto", + "sp-io", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -8069,7 +7735,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "505d45e08bad052f55fb51f00a6b6244d23ee46ffdc8091f6cddf4e3a880319d" dependencies = [ "log", - "sp-arithmetic 24.0.0", + "sp-arithmetic", ] [[package]] @@ -8095,10 +7761,10 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -8113,9 +7779,9 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -8132,10 +7798,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-inherents", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-storage 20.0.0", + "sp-io", + "sp-runtime", + "sp-std", + "sp-storage", "sp-timestamp", ] @@ -8153,27 +7819,27 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-transaction-payment" -version = "29.0.0" +version = "29.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39f690f5c287ad34b28ca951ef7fae80b08cc9218d970723b7a70e4d29396872" +checksum = "0b0c408252aefe10cff96af1e54f06f45cb0dd184b4e450e9a2ecf837dfe506e" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -8187,10 +7853,10 @@ dependencies = [ "parity-scale-codec", "sp-api", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-rpc", - "sp-runtime 32.0.0", - "sp-weights 28.0.0", + "sp-runtime", + "sp-weights", ] [[package]] @@ -8202,15 +7868,15 @@ dependencies = [ "pallet-transaction-payment", "parity-scale-codec", "sp-api", - "sp-runtime 32.0.0", - "sp-weights 28.0.0", + "sp-runtime", + "sp-weights", ] [[package]] name = "pallet-treasury" -version = "28.0.0" +version = "28.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1605eb5083a2cd172544f33c6e59eca2e23ac49f02f13d1562b1b8a409df9c60" +checksum = "3eca44990d0d759213744f2d1f6fe1fadec1079a3e4e4da40556d6b4e42abbcd" dependencies = [ "docify", "frame-benchmarking", @@ -8221,9 +7887,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -8238,8 +7904,8 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -8253,10 +7919,10 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -8271,8 +7937,8 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -8287,15 +7953,15 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-xcm" -version = "8.0.1" +version = "8.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b0bade2eb6ce40af35a5af150692b4e150638f7f68c15735ab9cdf79650d68e" +checksum = "ba9138b04168b07b1aff4a2079f5514753c31dddba40e5fb471b9cda7da27ad6" dependencies = [ "bounded-collections 0.2.0", "frame-benchmarking", @@ -8306,10 +7972,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -8327,9 +7993,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -8348,9 +8014,9 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", ] @@ -8377,10 +8043,10 @@ dependencies = [ "polkadot-primitives", "scale-info", "sp-consensus-aura", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "staging-parachain-info", "staging-xcm", "staging-xcm-executor", @@ -8407,11 +8073,11 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "sp-consensus-aura", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-tracing 16.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-tracing", "staging-parachain-info", "staging-xcm", "staging-xcm-executor", @@ -8439,7 +8105,7 @@ dependencies = [ "lz4", "memmap2 0.5.10", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "siphasher 0.3.11", "snap", "winapi", @@ -8504,7 +8170,7 @@ checksum = "f557c32c6d268a07c921471619c0295f5efad3a0e76d4f97a05c091a51d110b2" dependencies = [ "proc-macro2", "syn 1.0.109", - "synstructure 0.12.6", + "synstructure", ] [[package]] @@ -8590,18 +8256,9 @@ dependencies = [ [[package]] name = "pbkdf2" -version = "0.11.0" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "pbkdf2" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", ] @@ -8770,7 +8427,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "tracing-gum", ] @@ -8787,7 +8444,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "tracing-gum", ] @@ -8807,10 +8464,10 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "schnellru", - "sp-core 29.0.0", - "sp-keystore 0.35.0", + "sp-core", + "sp-keystore", "thiserror", "tracing-gum", ] @@ -8831,7 +8488,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "sc-network", "schnellru", "thiserror", @@ -8859,8 +8516,8 @@ dependencies = [ "sc-storage-monitor", "sc-sysinfo", "sc-tracing", - "sp-core 29.0.0", - "sp-io 31.0.0", + "sp-core", + "sp-io", "sp-keyring", "sp-maybe-compressed-blob", "substrate-build-script-utils", @@ -8883,9 +8540,9 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-core 29.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-keystore", + "sp-runtime", "thiserror", "tokio-util", "tracing-gum", @@ -8899,9 +8556,9 @@ checksum = "b6a08e4e014c853b252ecbbe3ccd67b2d33d78e46988d309b8cccf4ac06e25ef" dependencies = [ "parity-scale-codec", "scale-info", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -8924,8 +8581,8 @@ dependencies = [ "polkadot-primitives", "sc-network", "schnellru", - "sp-application-crypto 31.0.0", - "sp-keystore 0.35.0", + "sp-application-crypto", + "sp-keystore", "thiserror", "tracing-gum", ] @@ -8940,8 +8597,8 @@ dependencies = [ "polkadot-node-primitives", "polkadot-primitives", "reed-solomon-novelpoly", - "sp-core 29.0.0", - "sp-trie 30.0.0", + "sp-core", + "sp-trie", "thiserror", ] @@ -8957,14 +8614,14 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "sc-network", "sc-network-common", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", + "sp-application-crypto", + "sp-core", "sp-crypto-hashing", - "sp-keystore 0.35.0", + "sp-keystore", "tracing-gum", ] @@ -9005,7 +8662,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-core 29.0.0", + "sp-core", "sp-maybe-compressed-blob", "thiserror", "tracing-gum", @@ -9023,7 +8680,7 @@ dependencies = [ "futures-timer", "itertools 0.10.5", "kvdb", - "merlin 3.0.0", + "merlin", "parity-scale-codec", "polkadot-node-jaeger", "polkadot-node-primitives", @@ -9031,16 +8688,16 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "rand_core 0.6.4", "sc-keystore", "schnellru", "schnorrkel 0.11.4", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus", "sp-consensus-slots", - "sp-runtime 32.0.0", + "sp-runtime", "thiserror", "tracing-gum", ] @@ -9084,7 +8741,7 @@ dependencies = [ "polkadot-primitives", "polkadot-statement-table", "schnellru", - "sp-keystore 0.35.0", + "sp-keystore", "thiserror", "tracing-gum", ] @@ -9099,7 +8756,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-keystore 0.35.0", + "sp-keystore", "thiserror", "tracing-gum", "wasm-timer", @@ -9257,11 +8914,11 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-parachain-primitives", "polkadot-primitives", - "rand 0.8.5", + "rand", "slotmap", - "sp-core 29.0.0", + "sp-core", "sp-maybe-compressed-blob", - "sp-wasm-interface 20.0.0", + "sp-wasm-interface", "tempfile", "thiserror", "tokio", @@ -9280,7 +8937,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-primitives", - "sp-keystore 0.35.0", + "sp-keystore", "thiserror", "tracing-gum", ] @@ -9304,11 +8961,11 @@ dependencies = [ "sc-executor-common", "sc-executor-wasmtime", "seccompiler", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", - "sp-externalities 0.26.0", - "sp-io 31.0.0", - "sp-tracing 16.0.0", + "sp-externalities", + "sp-io", + "sp-tracing", "thiserror", "tracing-gum", ] @@ -9343,7 +9000,7 @@ dependencies = [ "polkadot-node-primitives", "polkadot-primitives", "sc-network", - "sp-core 29.0.0", + "sp-core", "thiserror", "tokio", ] @@ -9385,7 +9042,7 @@ dependencies = [ "polkadot-node-jaeger", "polkadot-node-primitives", "polkadot-primitives", - "rand 0.8.5", + "rand", "sc-authority-discovery", "sc-network", "strum 0.24.1", @@ -9407,12 +9064,12 @@ dependencies = [ "polkadot-primitives", "schnorrkel 0.11.4", "serde", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-babe", - "sp-core 29.0.0", - "sp-keystore 0.35.0", + "sp-core", + "sp-keystore", "sp-maybe-compressed-blob", - "sp-runtime 32.0.0", + "sp-runtime", "thiserror", "zstd 0.12.4", ] @@ -9452,7 +9109,7 @@ dependencies = [ "sp-authority-discovery", "sp-blockchain", "sp-consensus-babe", - "sp-runtime 32.0.0", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", ] @@ -9483,12 +9140,12 @@ dependencies = [ "polkadot-overseer", "polkadot-primitives", "prioritized-metered-channel", - "rand 0.8.5", + "rand", "sc-client-api", "schnellru", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", - "sp-keystore 0.35.0", + "sp-application-crypto", + "sp-core", + "sp-keystore", "thiserror", "tracing-gum", ] @@ -9511,7 +9168,7 @@ dependencies = [ "polkadot-primitives", "sc-client-api", "sp-api", - "sp-core 29.0.0", + "sp-core", "tikv-jemalloc-ctl", "tracing-gum", ] @@ -9528,10 +9185,10 @@ dependencies = [ "polkadot-core-primitives", "scale-info", "serde", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-weights 28.0.0", + "sp-core", + "sp-runtime", + "sp-std", + "sp-weights", ] [[package]] @@ -9549,17 +9206,17 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto 31.0.0", - "sp-arithmetic 24.0.0", + "sp-application-crypto", + "sp-arithmetic", "sp-authority-discovery", "sp-consensus-slots", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-io 31.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-io", + "sp-keystore", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -9590,17 +9247,17 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-keystore", + "sp-runtime", "substrate-frame-rpc-system", "substrate-state-trie-migration-rpc", ] [[package]] name = "polkadot-runtime-common" -version = "8.0.1" +version = "8.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06afbb3bd10245ad1907242a98ddffc3c0c1e209738b8382bc5bcfc1f28c0429" +checksum = "d815f0ff0a69dce7235d42c6e7d5e2b8b7429cba1252b4802ddc7879e2e74d4a" dependencies = [ "bitvec", "frame-benchmarking", @@ -9634,14 +9291,14 @@ dependencies = [ "serde_derive", "slot-range-helper", "sp-api", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-io 31.0.0", + "sp-io", "sp-npos-elections", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -9658,15 +9315,15 @@ dependencies = [ "frame-benchmarking", "parity-scale-codec", "polkadot-primitives", - "sp-std 14.0.0", - "sp-tracing 16.0.0", + "sp-std", + "sp-tracing", ] [[package]] name = "polkadot-runtime-parachains" -version = "8.0.1" +version = "8.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bcfd672be236fd1c38c702e7e99fe3f3e54df0ddb8127e542423221d1f50669" +checksum = "b8d37cd3e014b06daf396d1483b5327782a0ebadc816423419665166b75b3e3e" dependencies = [ "bitflags 1.3.2", "bitvec", @@ -9691,22 +9348,22 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-metrics", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "rustc-hex", "scale-info", "serde", "sp-api", - "sp-application-crypto 31.0.0", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", + "sp-application-crypto", + "sp-arithmetic", + "sp-core", "sp-inherents", - "sp-io 31.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-io", + "sp-keystore", + "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", + "sp-std", "staging-xcm", "staging-xcm-executor", "static_assertions", @@ -9809,21 +9466,21 @@ dependencies = [ "sp-consensus-babe", "sp-consensus-beefy", "sp-consensus-grandpa", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-io 31.0.0", + "sp-io", "sp-keyring", - "sp-keystore 0.35.0", + "sp-keystore", "sp-mmr-primitives", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", - "sp-state-machine 0.36.0", - "sp-storage 20.0.0", + "sp-state-machine", + "sp-storage", "sp-timestamp", "sp-transaction-pool", "sp-version", - "sp-weights 28.0.0", + "sp-weights", "substrate-prometheus-endpoint", "thiserror", "tracing-gum", @@ -9848,7 +9505,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", - "sp-keystore 0.35.0", + "sp-keystore", "sp-staking", "thiserror", "tracing-gum", @@ -9862,7 +9519,7 @@ checksum = "de5e010da3c6a65d8f263d0f825a04d995ffc8a37f886f674fcbbc73bf158d01" dependencies = [ "parity-scale-codec", "polkadot-primitives", - "sp-core 29.0.0", + "sp-core", "tracing-gum", ] @@ -9948,19 +9605,6 @@ dependencies = [ "universal-hash", ] -[[package]] -name = "pop-api" -version = "0.0.0" -dependencies = [ - "enumflags2", - "ink", - "parity-scale-codec", - "pop-primitives", - "scale-info", - "sp-io 23.0.0", - "sp-runtime 24.0.0", -] - [[package]] name = "pop-node" version = "0.1.0-alpha" @@ -10011,11 +9655,11 @@ dependencies = [ "sp-block-builder", "sp-blockchain", "sp-consensus-aura", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-keystore 0.35.0", + "sp-core", + "sp-io", + "sp-keystore", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", "sp-timestamp", "sp-transaction-pool", @@ -10045,8 +9689,8 @@ dependencies = [ "parity-scale-codec", "polkadot-primitives", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -10098,7 +9742,6 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "polkadot-runtime-common", - "pop-api", "pop-primitives", "pop-runtime-common", "scale-info", @@ -10106,14 +9749,14 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-consensus-aura", - "sp-core 29.0.0", + "sp-core", "sp-genesis-builder", "sp-inherents", - "sp-io 31.0.0", + "sp-io", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", - "sp-std 14.0.0", + "sp-std", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -10179,14 +9822,14 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-consensus-aura", - "sp-core 29.0.0", + "sp-core", "sp-genesis-builder", "sp-inherents", - "sp-io 31.0.0", + "sp-io", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", - "sp-std 14.0.0", + "sp-std", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -10546,7 +10189,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94b0b33c13a79f669c85defaf4c275dc86a0c0372807d0ca3d78e0bb87274863" dependencies = [ "bytes", - "rand 0.8.5", + "rand", "ring 0.16.20", "rustc-hash", "rustls 0.20.9", @@ -10572,19 +10215,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" -[[package]] -name = "rand" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" -dependencies = [ - "getrandom 0.1.16", - "libc", - "rand_chacha 0.2.2", - "rand_core 0.5.1", - "rand_hc", -] - [[package]] name = "rand" version = "0.8.5" @@ -10641,16 +10271,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ "num-traits", - "rand 0.8.5", -] - -[[package]] -name = "rand_hc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -dependencies = [ - "rand_core 0.5.1", + "rand", ] [[package]] @@ -10876,12 +10497,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "rlibc" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc874b127765f014d792f16763a81245ab80500e2ad921ed4ee9e82481ee08fe" - [[package]] name = "rlp" version = "0.5.2" @@ -10974,22 +10589,22 @@ dependencies = [ "serde_derive", "smallvec", "sp-api", - "sp-arithmetic 24.0.0", + "sp-arithmetic", "sp-authority-discovery", "sp-block-builder", "sp-consensus-babe", "sp-consensus-beefy", - "sp-core 29.0.0", + "sp-core", "sp-genesis-builder", "sp-inherents", - "sp-io 31.0.0", + "sp-io", "sp-mmr-primitives", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", - "sp-storage 20.0.0", + "sp-std", + "sp-storage", "sp-transaction-pool", "sp-version", "staging-xcm", @@ -11009,9 +10624,9 @@ dependencies = [ "polkadot-primitives", "polkadot-runtime-common", "smallvec", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-weights 28.0.0", + "sp-core", + "sp-runtime", + "sp-weights", "staging-xcm", "staging-xcm-builder", ] @@ -11314,8 +10929,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357127c91373ed6d1ae582f6e3300ab5b13bcde43bbf270a891f44194ef48b70" dependencies = [ "log", - "sp-core 29.0.0", - "sp-wasm-interface 20.0.0", + "sp-core", + "sp-wasm-interface", "thiserror", ] @@ -11336,15 +10951,15 @@ dependencies = [ "parity-scale-codec", "prost 0.12.3", "prost-build", - "rand 0.8.5", + "rand", "sc-client-api", "sc-network", "sp-api", "sp-authority-discovery", "sp-blockchain", - "sp-core 29.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-keystore", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", ] @@ -11366,9 +10981,9 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-runtime 32.0.0", + "sp-runtime", "substrate-prometheus-endpoint", ] @@ -11382,10 +10997,10 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-runtime 32.0.0", - "sp-trie 30.0.0", + "sp-runtime", + "sp-trie", ] [[package]] @@ -11407,12 +11022,12 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", "sp-genesis-builder", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-io", + "sp-runtime", + "sp-state-machine", ] [[package]] @@ -11444,7 +11059,7 @@ dependencies = [ "log", "names", "parity-scale-codec", - "rand 0.8.5", + "rand", "regex", "rpassword", "sc-client-api", @@ -11459,11 +11074,11 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-keyring", - "sp-keystore 0.35.0", - "sp-panic-handler 13.0.0", - "sp-runtime 32.0.0", + "sp-keystore", + "sp-panic-handler", + "sp-runtime", "sp-version", "thiserror", "tokio", @@ -11486,14 +11101,14 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core 29.0.0", + "sp-core", "sp-database", - "sp-externalities 0.26.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-externalities", + "sp-runtime", + "sp-state-machine", "sp-statement-store", - "sp-storage 20.0.0", - "sp-trie 30.0.0", + "sp-storage", + "sp-trie", "substrate-prometheus-endpoint", ] @@ -11515,13 +11130,13 @@ dependencies = [ "sc-client-api", "sc-state-db", "schnellru", - "sp-arithmetic 24.0.0", + "sp-arithmetic", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-database", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-trie 30.0.0", + "sp-runtime", + "sp-state-machine", + "sp-trie", ] [[package]] @@ -11543,9 +11158,9 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-core", + "sp-runtime", + "sp-state-machine", "substrate-prometheus-endpoint", "thiserror", ] @@ -11566,16 +11181,16 @@ dependencies = [ "sc-consensus-slots", "sc-telemetry", "sp-api", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", "sp-consensus-slots", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-keystore", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", ] @@ -11602,17 +11217,17 @@ dependencies = [ "sc-telemetry", "sc-transaction-pool-api", "sp-api", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-babe", "sp-consensus-slots", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", "sp-inherents", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-keystore", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", ] @@ -11630,13 +11245,13 @@ dependencies = [ "sc-rpc-api", "serde", "sp-api", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-core 29.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-keystore", + "sp-runtime", "thiserror", ] @@ -11661,16 +11276,16 @@ dependencies = [ "sc-network-sync", "sc-utils", "sp-api", - "sp-application-crypto 31.0.0", - "sp-arithmetic 24.0.0", + "sp-application-crypto", + "sp-arithmetic", "sp-blockchain", "sp-consensus", "sp-consensus-beefy", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", - "sp-keystore 0.35.0", + "sp-keystore", "sp-mmr-primitives", - "sp-runtime 32.0.0", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -11692,8 +11307,8 @@ dependencies = [ "sc-rpc", "serde", "sp-consensus-beefy", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "thiserror", ] @@ -11708,7 +11323,7 @@ dependencies = [ "sc-client-api", "sc-consensus", "sp-blockchain", - "sp-runtime 32.0.0", + "sp-runtime", ] [[package]] @@ -11728,7 +11343,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -11742,15 +11357,15 @@ dependencies = [ "sc-utils", "serde_json", "sp-api", - "sp-application-crypto 31.0.0", - "sp-arithmetic 24.0.0", + "sp-application-crypto", + "sp-arithmetic", "sp-blockchain", "sp-consensus", "sp-consensus-grandpa", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-keystore", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", ] @@ -11771,8 +11386,8 @@ dependencies = [ "sc-rpc", "serde", "sp-blockchain", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "thiserror", ] @@ -11790,14 +11405,14 @@ dependencies = [ "sc-client-api", "sc-consensus", "sc-telemetry", - "sp-arithmetic 24.0.0", + "sp-arithmetic", "sp-blockchain", "sp-consensus", "sp-consensus-slots", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-runtime", + "sp-state-machine", ] [[package]] @@ -11812,14 +11427,14 @@ dependencies = [ "sc-executor-wasmtime", "schnellru", "sp-api", - "sp-core 29.0.0", - "sp-externalities 0.26.0", - "sp-io 31.0.0", - "sp-panic-handler 13.0.0", - "sp-runtime-interface 25.0.0", - "sp-trie 30.0.0", + "sp-core", + "sp-externalities", + "sp-io", + "sp-panic-handler", + "sp-runtime-interface", + "sp-trie", "sp-version", - "sp-wasm-interface 20.0.0", + "sp-wasm-interface", "tracing", ] @@ -11831,7 +11446,7 @@ checksum = "07498138dee3ddf2c71299ca372d8449880bb3a8a8a299a483094e9c26b0823e" dependencies = [ "sc-allocator", "sp-maybe-compressed-blob", - "sp-wasm-interface 20.0.0", + "sp-wasm-interface", "thiserror", "wasm-instrument", ] @@ -11850,8 +11465,8 @@ dependencies = [ "rustix 0.36.17", "sc-allocator", "sc-executor-common", - "sp-runtime-interface 25.0.0", - "sp-wasm-interface 20.0.0", + "sp-runtime-interface", + "sp-wasm-interface", "wasmtime", ] @@ -11870,7 +11485,7 @@ dependencies = [ "sc-network-common", "sc-network-sync", "sp-blockchain", - "sp-runtime 32.0.0", + "sp-runtime", ] [[package]] @@ -11882,9 +11497,9 @@ dependencies = [ "array-bytes 6.2.2", "parking_lot 0.12.1", "serde_json", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", - "sp-keystore 0.35.0", + "sp-application-crypto", + "sp-core", + "sp-keystore", "thiserror", ] @@ -11911,10 +11526,10 @@ dependencies = [ "sc-transaction-pool-api", "sp-api", "sp-consensus", - "sp-core 29.0.0", - "sp-keystore 0.35.0", + "sp-core", + "sp-keystore", "sp-mixnet", - "sp-runtime 32.0.0", + "sp-runtime", "thiserror", ] @@ -11942,17 +11557,17 @@ dependencies = [ "parking_lot 0.12.1", "partial_sort", "pin-project", - "rand 0.8.5", + "rand", "sc-client-api", "sc-network-common", "sc-utils", "serde", "serde_json", "smallvec", - "sp-arithmetic 24.0.0", + "sp-arithmetic", "sp-blockchain", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -11978,7 +11593,7 @@ dependencies = [ "sc-client-api", "sc-network", "sp-blockchain", - "sp-runtime 32.0.0", + "sp-runtime", "thiserror", "unsigned-varint", ] @@ -11998,7 +11613,7 @@ dependencies = [ "sc-consensus", "sp-consensus", "sp-consensus-grandpa", - "sp-runtime 32.0.0", + "sp-runtime", ] [[package]] @@ -12016,7 +11631,7 @@ dependencies = [ "sc-network-common", "sc-network-sync", "schnellru", - "sp-runtime 32.0.0", + "sp-runtime", "substrate-prometheus-endpoint", "tracing", ] @@ -12038,8 +11653,8 @@ dependencies = [ "sc-client-api", "sc-network", "sp-blockchain", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "thiserror", ] @@ -12068,12 +11683,12 @@ dependencies = [ "sc-utils", "schnellru", "smallvec", - "sp-arithmetic 24.0.0", + "sp-arithmetic", "sp-blockchain", "sp-consensus", "sp-consensus-grandpa", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "substrate-prometheus-endpoint", "thiserror", "tokio", @@ -12096,7 +11711,7 @@ dependencies = [ "sc-network-sync", "sc-utils", "sp-consensus", - "sp-runtime 32.0.0", + "sp-runtime", "substrate-prometheus-endpoint", ] @@ -12119,18 +11734,18 @@ dependencies = [ "once_cell", "parity-scale-codec", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "sc-client-api", "sc-network", "sc-network-common", "sc-transaction-pool-api", "sc-utils", "sp-api", - "sp-core 29.0.0", - "sp-externalities 0.26.0", - "sp-keystore 0.35.0", + "sp-core", + "sp-externalities", + "sp-keystore", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "threadpool", "tracing", ] @@ -12167,11 +11782,11 @@ dependencies = [ "serde_json", "sp-api", "sp-blockchain", - "sp-core 29.0.0", - "sp-keystore 0.35.0", + "sp-core", + "sp-keystore", "sp-offchain", "sp-rpc", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", "sp-statement-store", "sp-version", @@ -12192,9 +11807,9 @@ dependencies = [ "scale-info", "serde", "serde_json", - "sp-core 29.0.0", + "sp-core", "sp-rpc", - "sp-runtime 32.0.0", + "sp-runtime", "sp-version", "thiserror", ] @@ -12237,9 +11852,9 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-rpc", - "sp-runtime 32.0.0", + "sp-runtime", "sp-version", "thiserror", "tokio", @@ -12262,7 +11877,7 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.1", "pin-project", - "rand 0.8.5", + "rand", "sc-chain-spec", "sc-client-api", "sc-client-db", @@ -12290,16 +11905,16 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-consensus", - "sp-core 29.0.0", - "sp-externalities 0.26.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-externalities", + "sp-keystore", + "sp-runtime", "sp-session", - "sp-state-machine 0.36.0", - "sp-storage 20.0.0", + "sp-state-machine", + "sp-storage", "sp-transaction-pool", "sp-transaction-storage-proof", - "sp-trie 30.0.0", + "sp-trie", "sp-version", "static_init", "substrate-prometheus-endpoint", @@ -12319,7 +11934,7 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", - "sp-core 29.0.0", + "sp-core", ] [[package]] @@ -12331,7 +11946,7 @@ dependencies = [ "clap", "fs4", "log", - "sp-core 29.0.0", + "sp-core", "thiserror", "tokio", ] @@ -12352,7 +11967,7 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-runtime 32.0.0", + "sp-runtime", "thiserror", ] @@ -12366,16 +11981,16 @@ dependencies = [ "futures", "libc", "log", - "rand 0.8.5", + "rand", "rand_pcg", "regex", "sc-telemetry", "serde", "serde_json", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", - "sp-io 31.0.0", - "sp-std 14.0.0", + "sp-io", + "sp-std", ] [[package]] @@ -12390,7 +12005,7 @@ dependencies = [ "log", "parking_lot 0.12.1", "pin-project", - "rand 0.8.5", + "rand", "sc-utils", "serde", "serde_json", @@ -12419,10 +12034,10 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-rpc", - "sp-runtime 32.0.0", - "sp-tracing 16.0.0", + "sp-runtime", + "sp-tracing", "thiserror", "tracing", "tracing-log 0.1.4", @@ -12460,10 +12075,10 @@ dependencies = [ "serde", "sp-api", "sp-blockchain", - "sp-core 29.0.0", + "sp-core", "sp-crypto-hashing", - "sp-runtime 32.0.0", - "sp-tracing 16.0.0", + "sp-runtime", + "sp-tracing", "sp-transaction-pool", "substrate-prometheus-endpoint", "thiserror", @@ -12481,8 +12096,8 @@ dependencies = [ "parity-scale-codec", "serde", "sp-blockchain", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "thiserror", ] @@ -12499,7 +12114,7 @@ dependencies = [ "log", "parking_lot 0.12.1", "prometheus", - "sp-arithmetic 24.0.0", + "sp-arithmetic", ] [[package]] @@ -12580,7 +12195,6 @@ dependencies = [ "derive_more", "parity-scale-codec", "scale-info-derive", - "schemars", "serde", ] @@ -12638,30 +12252,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "schemars" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09c024468a378b7e36765cd36702b7a90cc3cba11654f6685c8f233408e89e92" -dependencies = [ - "dyn-clone", - "schemars_derive", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1eee588578aff73f856ab961cd2f79e36bc45d7ded33a7562adba4667aecc0e" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 2.0.58", -] - [[package]] name = "schnellru" version = "0.2.1" @@ -12673,24 +12263,6 @@ dependencies = [ "hashbrown 0.13.2", ] -[[package]] -name = "schnorrkel" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "021b403afe70d81eea68f6ea12f6b3c9588e5d536a94c3bf80f15e7faa267862" -dependencies = [ - "arrayref", - "arrayvec 0.5.2", - "curve25519-dalek 2.1.3", - "getrandom 0.1.16", - "merlin 2.0.1", - "rand 0.7.3", - "rand_core 0.5.1", - "sha2 0.8.2", - "subtle 2.5.0", - "zeroize", -] - [[package]] name = "schnorrkel" version = "0.10.2" @@ -12700,7 +12272,7 @@ dependencies = [ "arrayref", "arrayvec 0.7.4", "curve25519-dalek-ng", - "merlin 3.0.0", + "merlin", "rand_core 0.6.4", "sha2 0.9.9", "subtle-ng", @@ -12718,7 +12290,7 @@ dependencies = [ "arrayvec 0.7.4", "curve25519-dalek 4.1.2", "getrandom_or_panic", - "merlin 3.0.0", + "merlin", "rand_core 0.6.4", "serde_bytes", "sha2 0.10.8", @@ -12771,31 +12343,13 @@ dependencies = [ "libc", ] -[[package]] -name = "secp256k1" -version = "0.24.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1629c9c557ef9b293568b338dddfc8208c98a18c59d722a9d53f859d9c9b62" -dependencies = [ - "secp256k1-sys 0.6.1", -] - [[package]] name = "secp256k1" version = "0.28.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d24b59d129cdadea20aea4fb2352fa053712e5d713eee47d700cd4b2bc002f10" dependencies = [ - "secp256k1-sys 0.9.2", -] - -[[package]] -name = "secp256k1-sys" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83080e2c2fc1006e625be82e5d1eb6a43b7fd9578b617fcc55814daf286bba4b" -dependencies = [ - "cc", + "secp256k1-sys", ] [[package]] @@ -12901,17 +12455,6 @@ dependencies = [ "syn 2.0.58", ] -[[package]] -name = "serde_derive_internals" -version = "0.29.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.58", -] - [[package]] name = "serde_json" version = "1.0.115" @@ -12956,18 +12499,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "sha2" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "fake-simd", - "opaque-debug 0.2.3", -] - [[package]] name = "sha2" version = "0.9.9" @@ -13026,12 +12557,6 @@ dependencies = [ "libc", ] -[[package]] -name = "signature" -version = "1.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" - [[package]] name = "signature" version = "2.2.0" @@ -13097,8 +12622,8 @@ dependencies = [ "enumn", "parity-scale-codec", "paste", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -13177,7 +12702,7 @@ dependencies = [ "hmac 0.12.1", "itertools 0.11.0", "libsecp256k1", - "merlin 3.0.0", + "merlin", "no-std-net", "nom", "num-bigint", @@ -13186,7 +12711,7 @@ dependencies = [ "pbkdf2 0.12.2", "pin-project", "poly1305", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "ruzstd 0.4.0", "schnorrkel 0.10.2", @@ -13232,7 +12757,7 @@ dependencies = [ "itertools 0.12.1", "libm", "libsecp256k1", - "merlin 3.0.0", + "merlin", "no-std-net", "nom", "num-bigint", @@ -13241,7 +12766,7 @@ dependencies = [ "pbkdf2 0.12.2", "pin-project", "poly1305", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "ruzstd 0.5.0", "schnorrkel 0.11.4", @@ -13284,7 +12809,7 @@ dependencies = [ "no-std-net", "parking_lot 0.12.1", "pin-project", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "serde", "serde_json", @@ -13320,7 +12845,7 @@ dependencies = [ "no-std-net", "parking_lot 0.12.1", "pin-project", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "serde", "serde_json", @@ -13380,10 +12905,10 @@ dependencies = [ "serde", "snowbridge-ethereum", "snowbridge-milagro-bls", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "ssz_rs", "ssz_rs_derive", "static_assertions", @@ -13404,11 +12929,11 @@ dependencies = [ "scale-info", "serde", "snowbridge-beacon-primitives", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", ] @@ -13430,10 +12955,10 @@ dependencies = [ "scale-info", "serde", "serde-big-array", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -13445,7 +12970,7 @@ dependencies = [ "hex", "lazy_static", "parity-scale-codec", - "rand 0.8.5", + "rand", "scale-info", "snowbridge-amcl", "zeroize", @@ -13466,10 +12991,10 @@ dependencies = [ "scale-info", "serde", "snowbridge-core", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -13508,37 +13033,37 @@ dependencies = [ "http", "httparse", "log", - "rand 0.8.5", + "rand", "sha-1", ] [[package]] name = "sp-api" -version = "27.0.0" +version = "27.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef42aa652381ade883c14ffbbb5c0fec36d382d2217b5bace01b8a0e8634778" +checksum = "2e4f8702afd77f14a32733e2b589c02694bf79d0b3a641963c508016208724d0" dependencies = [ "hash-db", "log", "parity-scale-codec", "scale-info", "sp-api-proc-macro", - "sp-core 29.0.0", - "sp-externalities 0.26.0", + "sp-core", + "sp-externalities", "sp-metadata-ir", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-trie", "sp-version", "thiserror", ] [[package]] name = "sp-api-proc-macro" -version = "15.0.0" +version = "15.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0694be2891593450916d6b53a274d234bccbc86bcbada36ba23fc356989070c7" +checksum = "0301e2f77afb450fbf2b093f8b324c7ad88cc82e5e69bd5dc8658a1f068b2a96" dependencies = [ "Inflector", "blake2 0.10.6", @@ -13549,20 +13074,6 @@ dependencies = [ "syn 2.0.58", ] -[[package]] -name = "sp-application-crypto" -version = "23.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899492ea547816d5dfe9a5a2ecc32f65a7110805af6da3380aa4902371b31dc2" -dependencies = [ - "parity-scale-codec", - "scale-info", - "serde", - "sp-core 21.0.0", - "sp-io 23.0.0", - "sp-std 8.0.0", -] - [[package]] name = "sp-application-crypto" version = "31.0.0" @@ -13572,24 +13083,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-std 14.0.0", -] - -[[package]] -name = "sp-arithmetic" -version = "16.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb6020576e544c6824a51d651bc8df8e6ab67cd59f1c9ac09868bb81a5199ded" -dependencies = [ - "integer-sqrt", - "num-traits", - "parity-scale-codec", - "scale-info", - "serde", - "sp-std 8.0.0", - "static_assertions", + "sp-core", + "sp-io", + "sp-std", ] [[package]] @@ -13603,7 +13099,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std 14.0.0", + "sp-std", "static_assertions", ] @@ -13616,9 +13112,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-application-crypto 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-application-crypto", + "sp-runtime", + "sp-std", ] [[package]] @@ -13629,8 +13125,8 @@ checksum = "1b36ce171caa7eb2bbe682c089f755fdefa71d3702e4fb1ba30d10146aef99d5" dependencies = [ "sp-api", "sp-inherents", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -13647,8 +13143,8 @@ dependencies = [ "sp-api", "sp-consensus", "sp-database", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-runtime", + "sp-state-machine", "thiserror", ] @@ -13661,10 +13157,10 @@ dependencies = [ "async-trait", "futures", "log", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-runtime", + "sp-state-machine", "thiserror", ] @@ -13678,11 +13174,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-slots", "sp-inherents", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "sp-timestamp", ] @@ -13697,12 +13193,12 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto 31.0.0", + "sp-application-crypto", "sp-consensus-slots", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "sp-timestamp", ] @@ -13717,13 +13213,13 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", + "sp-application-crypto", + "sp-core", "sp-crypto-hashing", - "sp-io 31.0.0", + "sp-io", "sp-mmr-primitives", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "strum 0.24.1", ] @@ -13739,11 +13235,11 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-application-crypto", + "sp-core", + "sp-keystore", + "sp-runtime", + "sp-std", ] [[package]] @@ -13755,55 +13251,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std 14.0.0", + "sp-std", "sp-timestamp", ] -[[package]] -name = "sp-core" -version = "21.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f18d9e2f67d8661f9729f35347069ac29d92758b59135176799db966947a7336" -dependencies = [ - "array-bytes 4.2.0", - "bitflags 1.3.2", - "blake2 0.10.6", - "bounded-collections 0.1.9", - "bs58 0.4.0", - "dyn-clonable", - "ed25519-zebra 3.1.0", - "futures", - "hash-db", - "hash256-std-hasher", - "impl-serde", - "lazy_static", - "libsecp256k1", - "log", - "merlin 2.0.1", - "parity-scale-codec", - "parking_lot 0.12.1", - "paste", - "primitive-types", - "rand 0.8.5", - "regex", - "scale-info", - "schnorrkel 0.9.1", - "secp256k1 0.24.3", - "secrecy", - "serde", - "sp-core-hashing 9.0.0", - "sp-debug-derive 8.0.0", - "sp-externalities 0.19.0", - "sp-runtime-interface 17.0.0", - "sp-std 8.0.0", - "sp-storage 13.0.0", - "ss58-registry", - "substrate-bip39", - "thiserror", - "tiny-bip39", - "zeroize", -] - [[package]] name = "sp-core" version = "29.0.0" @@ -13825,23 +13276,23 @@ dependencies = [ "itertools 0.10.5", "libsecp256k1", "log", - "merlin 3.0.0", + "merlin", "parity-scale-codec", "parking_lot 0.12.1", "paste", "primitive-types", - "rand 0.8.5", + "rand", "scale-info", "schnorrkel 0.11.4", - "secp256k1 0.28.2", + "secp256k1", "secrecy", "serde", "sp-crypto-hashing", - "sp-debug-derive 14.0.0", - "sp-externalities 0.26.0", - "sp-runtime-interface 25.0.0", - "sp-std 14.0.0", - "sp-storage 20.0.0", + "sp-debug-derive", + "sp-externalities", + "sp-runtime-interface", + "sp-std", + "sp-storage", "ss58-registry", "substrate-bip39", "thiserror", @@ -13850,21 +13301,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "sp-core-hashing" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee599a8399448e65197f9a6cee338ad192e9023e35e31f22382964c3c174c68" -dependencies = [ - "blake2b_simd", - "byteorder", - "digest 0.10.7", - "sha2 0.10.8", - "sha3", - "sp-std 8.0.0", - "twox-hash", -] - [[package]] name = "sp-core-hashing" version = "15.0.0" @@ -13914,17 +13350,6 @@ dependencies = [ "parking_lot 0.12.1", ] -[[package]] -name = "sp-debug-derive" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f531814d2f16995144c74428830ccf7d94ff4a7749632b83ad8199b181140c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.58", -] - [[package]] name = "sp-debug-derive" version = "14.0.0" @@ -13936,18 +13361,6 @@ dependencies = [ "syn 2.0.58", ] -[[package]] -name = "sp-externalities" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0f71c671e01a8ca60da925d43a1b351b69626e268b8837f8371e320cf1dd100" -dependencies = [ - "environmental", - "parity-scale-codec", - "sp-std 8.0.0", - "sp-storage 13.0.0", -] - [[package]] name = "sp-externalities" version = "0.26.0" @@ -13956,8 +13369,8 @@ checksum = "e7096ed024cec397804864898b093b51e14c7299f1d00c67dd5800330e02bb82" dependencies = [ "environmental", "parity-scale-codec", - "sp-std 14.0.0", - "sp-storage 20.0.0", + "sp-std", + "sp-storage", ] [[package]] @@ -13968,8 +13381,8 @@ checksum = "fd865540ec19479c7349b584ccd78cc34c3f3a628a2a69dbb6365ceec36295ee" dependencies = [ "serde_json", "sp-api", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -13982,38 +13395,11 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "thiserror", ] -[[package]] -name = "sp-io" -version = "23.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d597e35a9628fe7454b08965b2442e3ec0f264b0a90d41328e87422cec02e99" -dependencies = [ - "bytes", - "ed25519 1.5.3", - "ed25519-dalek 1.0.1", - "futures", - "libsecp256k1", - "log", - "parity-scale-codec", - "rustversion", - "secp256k1 0.24.3", - "sp-core 21.0.0", - "sp-externalities 0.19.0", - "sp-keystore 0.27.0", - "sp-runtime-interface 17.0.0", - "sp-state-machine 0.28.0", - "sp-std 8.0.0", - "sp-tracing 10.0.0", - "sp-trie 22.0.0", - "tracing", - "tracing-core", -] - [[package]] name = "sp-io" version = "31.0.0" @@ -14021,21 +13407,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec43aa073eab35fcb920d7592474d5427ea3be2bf938706a3ad955d7ba54fd8d" dependencies = [ "bytes", - "ed25519-dalek 2.1.1", + "ed25519-dalek", "libsecp256k1", "log", "parity-scale-codec", "rustversion", - "secp256k1 0.28.2", - "sp-core 29.0.0", + "secp256k1", + "sp-core", "sp-crypto-hashing", - "sp-externalities 0.26.0", - "sp-keystore 0.35.0", - "sp-runtime-interface 25.0.0", - "sp-state-machine 0.36.0", - "sp-std 14.0.0", - "sp-tracing 16.0.0", - "sp-trie 30.0.0", + "sp-externalities", + "sp-keystore", + "sp-runtime-interface", + "sp-state-machine", + "sp-std", + "sp-tracing", + "sp-trie", "tracing", "tracing-core", ] @@ -14046,25 +13432,11 @@ version = "32.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cf0a2f881958466fc92bc9b39bbc2c0d815ded4a21f8f953372b0ac2e11b02" dependencies = [ - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", "strum 0.24.1", ] -[[package]] -name = "sp-keystore" -version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be3cdd67cc1d9c1db17c5cbc4ec4924054a8437009d167f21f6590797e4aa45" -dependencies = [ - "futures", - "parity-scale-codec", - "parking_lot 0.12.1", - "sp-core 21.0.0", - "sp-externalities 0.19.0", - "thiserror", -] - [[package]] name = "sp-keystore" version = "0.35.0" @@ -14073,8 +13445,8 @@ checksum = "444f2d53968b1ce5e908882710ff1f3873fcf3e95f59d57432daf685bbacb959" dependencies = [ "parity-scale-codec", "parking_lot 0.12.1", - "sp-core 29.0.0", - "sp-externalities 0.26.0", + "sp-core", + "sp-externalities", "thiserror", ] @@ -14097,7 +13469,7 @@ dependencies = [ "frame-metadata 16.0.0", "parity-scale-codec", "scale-info", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -14109,8 +13481,8 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-application-crypto 31.0.0", - "sp-std 14.0.0", + "sp-application-crypto", + "sp-std", ] [[package]] @@ -14125,10 +13497,10 @@ dependencies = [ "scale-info", "serde", "sp-api", - "sp-core 29.0.0", - "sp-debug-derive 14.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-core", + "sp-debug-derive", + "sp-runtime", + "sp-std", "thiserror", ] @@ -14141,10 +13513,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -14154,19 +13526,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d83b955dce0b6d143bec3f60571311168f362b1c16cf044da7037a407b66c19" dependencies = [ "sp-api", - "sp-core 29.0.0", - "sp-runtime 32.0.0", -] - -[[package]] -name = "sp-panic-handler" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebd2de46003fa8212426838ca71cd42ee36a26480ba9ffea983506ce03131033" -dependencies = [ - "backtrace", - "lazy_static", - "regex", + "sp-core", + "sp-runtime", ] [[package]] @@ -14188,30 +13549,7 @@ checksum = "9af4b73fe7ddd88b1641cca90048c4e525e721763199e6fd29c4f590884f4d16" dependencies = [ "rustc-hash", "serde", - "sp-core 29.0.0", -] - -[[package]] -name = "sp-runtime" -version = "24.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21c5bfc764a1a8259d7e8f7cfd22c84006275a512c958d3ff966c92151e134d5" -dependencies = [ - "either", - "hash256-std-hasher", - "impl-trait-for-tuples", - "log", - "parity-scale-codec", - "paste", - "rand 0.8.5", - "scale-info", - "serde", - "sp-application-crypto 23.0.0", - "sp-arithmetic 16.0.0", - "sp-core 21.0.0", - "sp-io 23.0.0", - "sp-std 8.0.0", - "sp-weights 20.0.0", + "sp-core", ] [[package]] @@ -14227,35 +13565,16 @@ dependencies = [ "log", "parity-scale-codec", "paste", - "rand 0.8.5", + "rand", "scale-info", "serde", "simple-mermaid", - "sp-application-crypto 31.0.0", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-std 14.0.0", - "sp-weights 28.0.0", -] - -[[package]] -name = "sp-runtime-interface" -version = "17.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e676128182f90015e916f806cba635c8141e341e7abbc45d25525472e1bbce8" -dependencies = [ - "bytes", - "impl-trait-for-tuples", - "parity-scale-codec", - "primitive-types", - "sp-externalities 0.19.0", - "sp-runtime-interface-proc-macro 11.0.0", - "sp-std 8.0.0", - "sp-storage 13.0.0", - "sp-tracing 10.0.0", - "sp-wasm-interface 14.0.0", - "static_assertions", + "sp-application-crypto", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-std", + "sp-weights", ] [[package]] @@ -14268,28 +13587,15 @@ dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", "primitive-types", - "sp-externalities 0.26.0", - "sp-runtime-interface-proc-macro 17.0.0", - "sp-std 14.0.0", - "sp-storage 20.0.0", - "sp-tracing 16.0.0", - "sp-wasm-interface 20.0.0", + "sp-externalities", + "sp-runtime-interface-proc-macro", + "sp-std", + "sp-storage", + "sp-tracing", + "sp-wasm-interface", "static_assertions", ] -[[package]] -name = "sp-runtime-interface-proc-macro" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d5bd5566fe5633ec48dfa35ab152fd29f8a577c21971e1c6db9f28afb9bbb9" -dependencies = [ - "Inflector", - "proc-macro-crate 1.3.1", - "proc-macro2", - "quote", - "syn 2.0.58", -] - [[package]] name = "sp-runtime-interface-proc-macro" version = "17.0.0" @@ -14313,11 +13619,11 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-core 29.0.0", - "sp-keystore 0.35.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-keystore", + "sp-runtime", "sp-staking", - "sp-std 14.0.0", + "sp-std", ] [[package]] @@ -14330,30 +13636,9 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", -] - -[[package]] -name = "sp-state-machine" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ef45d31f9e7ac648f8899a0cd038a3608f8499028bff55b6c799702592325b6" -dependencies = [ - "hash-db", - "log", - "parity-scale-codec", - "parking_lot 0.12.1", - "rand 0.8.5", - "smallvec", - "sp-core 21.0.0", - "sp-externalities 0.19.0", - "sp-panic-handler 8.0.0", - "sp-std 8.0.0", - "sp-trie 22.0.0", - "thiserror", - "tracing", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] @@ -14366,16 +13651,16 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "smallvec", - "sp-core 29.0.0", - "sp-externalities 0.26.0", - "sp-panic-handler 13.0.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", + "sp-core", + "sp-externalities", + "sp-panic-handler", + "sp-std", + "sp-trie", "thiserror", "tracing", - "trie-db 0.28.0", + "trie-db", ] [[package]] @@ -14386,50 +13671,30 @@ checksum = "309a9ae4e8134bbed8ffc510cf4d461a4a651f9250b556de782cedd876abe1ff" dependencies = [ "aes-gcm", "curve25519-dalek 4.1.2", - "ed25519-dalek 2.1.1", + "ed25519-dalek", "hkdf", "parity-scale-codec", - "rand 0.8.5", + "rand", "scale-info", "sha2 0.10.8", "sp-api", - "sp-application-crypto 31.0.0", - "sp-core 29.0.0", + "sp-application-crypto", + "sp-core", "sp-crypto-hashing", - "sp-externalities 0.26.0", - "sp-runtime 32.0.0", - "sp-runtime-interface 25.0.0", - "sp-std 14.0.0", + "sp-externalities", + "sp-runtime", + "sp-runtime-interface", + "sp-std", "thiserror", "x25519-dalek 2.0.1", ] -[[package]] -name = "sp-std" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53458e3c57df53698b3401ec0934bea8e8cfce034816873c0b0abbd83d7bac0d" - [[package]] name = "sp-std" version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12f8ee986414b0a9ad741776762f4083cd3a5128449b982a3919c4df36874834" -[[package]] -name = "sp-storage" -version = "13.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94294be83f11d4958cfea89ed5798f0b6605f5defc3a996948848458abbcc18e" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "ref-cast", - "serde", - "sp-debug-derive 8.0.0", - "sp-std 8.0.0", -] - [[package]] name = "sp-storage" version = "20.0.0" @@ -14440,8 +13705,8 @@ dependencies = [ "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive 14.0.0", - "sp-std 14.0.0", + "sp-debug-derive", + "sp-std", ] [[package]] @@ -14453,24 +13718,11 @@ dependencies = [ "async-trait", "parity-scale-codec", "sp-inherents", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "thiserror", ] -[[package]] -name = "sp-tracing" -version = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357f7591980dd58305956d32f8f6646d0a8ea9ea0e7e868e46f53b68ddf00cec" -dependencies = [ - "parity-scale-codec", - "sp-std 8.0.0", - "tracing", - "tracing-core", - "tracing-subscriber 0.2.25", -] - [[package]] name = "sp-tracing" version = "16.0.0" @@ -14478,7 +13730,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0351810b9d074df71c4514c5228ed05c250607cba131c1c9d1526760ab69c05c" dependencies = [ "parity-scale-codec", - "sp-std 14.0.0", + "sp-std", "tracing", "tracing-core", "tracing-subscriber 0.2.25", @@ -14491,7 +13743,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9742861c5330bdcb42856a6eed3d3745b58ee1c92ca4c9260032ff4e6c387165" dependencies = [ "sp-api", - "sp-runtime 32.0.0", + "sp-runtime", ] [[package]] @@ -14503,35 +13755,11 @@ dependencies = [ "async-trait", "parity-scale-codec", "scale-info", - "sp-core 29.0.0", + "sp-core", "sp-inherents", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-trie 30.0.0", -] - -[[package]] -name = "sp-trie" -version = "22.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e4eeb7ef23f79eba8609db79ef9cef242f994f1f87a3c0387b4b5f177fda74" -dependencies = [ - "ahash 0.8.11", - "hash-db", - "hashbrown 0.13.2", - "lazy_static", - "memory-db", - "nohash-hasher", - "parity-scale-codec", - "parking_lot 0.12.1", - "scale-info", - "schnellru", - "sp-core 21.0.0", - "sp-std 8.0.0", - "thiserror", - "tracing", - "trie-db 0.27.1", - "trie-root", + "sp-runtime", + "sp-std", + "sp-trie", ] [[package]] @@ -14547,15 +13775,15 @@ dependencies = [ "nohash-hasher", "parity-scale-codec", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "scale-info", "schnellru", - "sp-core 29.0.0", - "sp-externalities 0.26.0", - "sp-std 14.0.0", + "sp-core", + "sp-externalities", + "sp-std", "thiserror", "tracing", - "trie-db 0.28.0", + "trie-db", "trie-root", ] @@ -14571,8 +13799,8 @@ dependencies = [ "scale-info", "serde", "sp-crypto-hashing-proc-macro", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", "sp-version-proc-macro", "thiserror", ] @@ -14589,20 +13817,6 @@ dependencies = [ "syn 2.0.58", ] -[[package]] -name = "sp-wasm-interface" -version = "14.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19c122609ca5d8246be6386888596320d03c7bc880959eaa2c36bcd5acd6846" -dependencies = [ - "anyhow", - "impl-trait-for-tuples", - "log", - "parity-scale-codec", - "sp-std 8.0.0", - "wasmtime", -] - [[package]] name = "sp-wasm-interface" version = "20.0.0" @@ -14613,26 +13827,10 @@ dependencies = [ "impl-trait-for-tuples", "log", "parity-scale-codec", - "sp-std 14.0.0", + "sp-std", "wasmtime", ] -[[package]] -name = "sp-weights" -version = "20.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45d084c735544f70625b821c3acdbc7a2fc1893ca98b85f1942631284692c75b" -dependencies = [ - "parity-scale-codec", - "scale-info", - "serde", - "smallvec", - "sp-arithmetic 16.0.0", - "sp-core 21.0.0", - "sp-debug-derive 8.0.0", - "sp-std 8.0.0", -] - [[package]] name = "sp-weights" version = "28.0.0" @@ -14644,9 +13842,9 @@ dependencies = [ "scale-info", "serde", "smallvec", - "sp-arithmetic 24.0.0", - "sp-debug-derive 14.0.0", - "sp-std 14.0.0", + "sp-arithmetic", + "sp-debug-derive", + "sp-std", ] [[package]] @@ -14737,8 +13935,8 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "sp-runtime 32.0.0", - "sp-std 14.0.0", + "sp-runtime", + "sp-std", ] [[package]] @@ -14756,15 +13954,15 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-weights 28.0.0", + "sp-weights", "xcm-procedural", ] [[package]] name = "staging-xcm-builder" -version = "8.0.1" +version = "8.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f6cfc27c1d45f9a67e20ed3f7e60296299688825350291606add10bf3bbff2" +checksum = "988d765ad5ab3b5cc90bb1dd143153ebdbe2b7600e10d5ef3a7f3e8df1bdac5d" dependencies = [ "frame-support", "frame-system", @@ -14774,20 +13972,20 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "scale-info", - "sp-arithmetic 24.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-weights 28.0.0", + "sp-arithmetic", + "sp-io", + "sp-runtime", + "sp-std", + "sp-weights", "staging-xcm", "staging-xcm-executor", ] [[package]] name = "staging-xcm-executor" -version = "8.0.1" +version = "8.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a638f4c8735cc04b5c93920a1f59e679f48b131315a07d146798e0decebf7720" +checksum = "74b5c5f2a1d610c5e20e5fae2680c9a28380f305afafeed62f341bfbce57b79a" dependencies = [ "environmental", "frame-benchmarking", @@ -14796,12 +13994,12 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-weights 28.0.0", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-weights", "staging-xcm", ] @@ -14940,8 +14138,8 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-blockchain", - "sp-core 29.0.0", - "sp-runtime 32.0.0", + "sp-core", + "sp-runtime", ] [[package]] @@ -14968,7 +14166,7 @@ dependencies = [ "log", "sc-rpc-api", "serde", - "sp-runtime 32.0.0", + "sp-runtime", ] [[package]] @@ -14982,18 +14180,18 @@ dependencies = [ "sc-client-api", "sc-rpc-api", "serde", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", - "sp-trie 30.0.0", - "trie-db 0.28.0", + "sp-core", + "sp-runtime", + "sp-state-machine", + "sp-trie", + "trie-db", ] [[package]] name = "substrate-wasm-builder" -version = "18.0.0" +version = "18.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "511bbc2df035f5fe2556d855369a1bbb45df620360391a1f6e3fa1a1d64af79a" +checksum = "4a39a20e17c24ede36b5bd5e7543a4cef8d8a0daf6e1a046dc31832b837a54a0" dependencies = [ "build-helper", "cargo_metadata", @@ -15052,7 +14250,7 @@ dependencies = [ "scale-value", "serde", "serde_json", - "sp-core-hashing 15.0.0", + "sp-core-hashing", "subxt-lightclient", "subxt-macro", "subxt-metadata", @@ -15124,7 +14322,7 @@ dependencies = [ "frame-metadata 16.0.0", "parity-scale-codec", "scale-info", - "sp-core-hashing 15.0.0", + "sp-core-hashing", "thiserror", ] @@ -15141,10 +14339,10 @@ dependencies = [ "pbkdf2 0.12.2", "regex", "schnorrkel 0.11.4", - "secp256k1 0.28.2", + "secp256k1", "secrecy", "sha2 0.10.8", - "sp-core-hashing 15.0.0", + "sp-core-hashing", "subxt", "thiserror", "zeroize", @@ -15184,17 +14382,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "synstructure" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.58", -] - [[package]] name = "system-configuration" version = "0.5.1" @@ -15275,7 +14462,7 @@ dependencies = [ "polkadot-core-primitives", "rococo-runtime-constants", "smallvec", - "sp-runtime 32.0.0", + "sp-runtime", "staging-xcm", "westend-runtime-constants", ] @@ -15410,25 +14597,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny-bip39" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62cc94d358b5a1e84a5cb9109f559aa3c4d634d2b1b4de3d0fa4adc7c78e2861" -dependencies = [ - "anyhow", - "hmac 0.12.1", - "once_cell", - "pbkdf2 0.11.0", - "rand 0.8.5", - "rustc-hash", - "sha2 0.10.8", - "thiserror", - "unicode-normalization", - "wasm-bindgen", - "zeroize", -] - [[package]] name = "tiny-keccak" version = "2.0.2" @@ -15490,7 +14658,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f57eb36ecbe0fc510036adff84824dd3c24bb781e21bfa67b69d556aa85214f" dependencies = [ "pin-project", - "rand 0.8.5", + "rand", "tokio", ] @@ -15802,19 +14970,6 @@ dependencies = [ "tracing-log 0.2.0", ] -[[package]] -name = "trie-db" -version = "0.27.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "767abe6ffed88a1889671a102c2861ae742726f52e0a5a425b92c9fbfa7e9c85" -dependencies = [ - "hash-db", - "hashbrown 0.13.2", - "log", - "rustc-hex", - "smallvec", -] - [[package]] name = "trie-db" version = "0.28.0" @@ -15853,7 +15008,7 @@ dependencies = [ "idna 0.2.3", "ipnet", "lazy_static", - "rand 0.8.5", + "rand", "smallvec", "socket2 0.4.10", "thiserror", @@ -15909,19 +15064,19 @@ dependencies = [ "sp-api", "sp-consensus-aura", "sp-consensus-babe", - "sp-core 29.0.0", - "sp-debug-derive 14.0.0", - "sp-externalities 0.26.0", + "sp-core", + "sp-debug-derive", + "sp-externalities", "sp-inherents", - "sp-io 31.0.0", - "sp-keystore 0.35.0", + "sp-io", + "sp-keystore", "sp-rpc", - "sp-runtime 32.0.0", - "sp-state-machine 0.36.0", + "sp-runtime", + "sp-state-machine", "sp-timestamp", "sp-transaction-storage-proof", "sp-version", - "sp-weights 28.0.0", + "sp-weights", "substrate-rpc-client", "zstd 0.12.4", ] @@ -15940,7 +15095,7 @@ checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", "digest 0.10.7", - "rand 0.8.5", + "rand", "static_assertions", ] @@ -16091,7 +15246,7 @@ dependencies = [ "arrayref", "constcat", "digest 0.10.7", - "rand 0.8.5", + "rand", "rand_chacha 0.3.1", "rand_core 0.6.4", "sha2 0.10.8", @@ -16501,7 +15656,7 @@ dependencies = [ "memfd", "memoffset", "paste", - "rand 0.8.5", + "rand", "rustix 0.36.17", "wasmtime-asm-macros", "wasmtime-environ", @@ -16630,24 +15785,24 @@ dependencies = [ "serde_derive", "smallvec", "sp-api", - "sp-application-crypto 31.0.0", - "sp-arithmetic 24.0.0", + "sp-application-crypto", + "sp-arithmetic", "sp-authority-discovery", "sp-block-builder", "sp-consensus-babe", "sp-consensus-beefy", - "sp-core 29.0.0", + "sp-core", "sp-genesis-builder", "sp-inherents", - "sp-io 31.0.0", + "sp-io", "sp-mmr-primitives", "sp-npos-elections", "sp-offchain", - "sp-runtime 32.0.0", + "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", - "sp-storage 20.0.0", + "sp-std", + "sp-storage", "sp-transaction-pool", "sp-version", "staging-xcm", @@ -16667,9 +15822,9 @@ dependencies = [ "polkadot-primitives", "polkadot-runtime-common", "smallvec", - "sp-core 29.0.0", - "sp-runtime 32.0.0", - "sp-weights 28.0.0", + "sp-core", + "sp-runtime", + "sp-weights", "staging-xcm", "staging-xcm-builder", ] @@ -17061,13 +16216,13 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-parachains", - "sp-arithmetic 24.0.0", - "sp-core 29.0.0", + "sp-arithmetic", + "sp-core", "sp-crypto-hashing", - "sp-io 31.0.0", - "sp-runtime 32.0.0", - "sp-std 14.0.0", - "sp-tracing 16.0.0", + "sp-io", + "sp-runtime", + "sp-std", + "sp-tracing", "staging-xcm", "staging-xcm-executor", ] @@ -17084,12 +16239,6 @@ dependencies = [ "syn 2.0.58", ] -[[package]] -name = "xxhash-rust" -version = "0.8.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927da81e25be1e1a2901d59b81b37dd2efd1fc9c9345a55007f09bf5a2d3ee03" - [[package]] name = "yamux" version = "0.10.2" @@ -17100,7 +16249,7 @@ dependencies = [ "log", "nohash-hasher", "parking_lot 0.12.1", - "rand 0.8.5", + "rand", "static_assertions", ] diff --git a/Cargo.toml b/Cargo.toml index 3f1d6e1c..3719e83d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ subxt-signer = "0.34.0" tokio = { version = "1.36", features = ["macros", "time", "rt-multi-thread"] } # Build -substrate-wasm-builder = "18.0.0" +substrate-wasm-builder = "18.0.1" substrate-build-script-utils = "11.0.0" # Local @@ -76,7 +76,7 @@ sc-transaction-pool-api = "29.0.0" frame-benchmarking = { version = "29.0.0", default-features = false } frame-benchmarking-cli = "33.0.0" frame-executive = { version = "29.0.0", default-features = false } -frame-support = { version = "29.0.0", default-features = false } +frame-support = { version = "29.0.2", default-features = false } frame-system = { version = "29.0.0", default-features = false } frame-system-benchmarking = { version = "29.0.0", default-features = false } frame-system-rpc-runtime-api = { version = "27.0.0", default-features = false } @@ -84,7 +84,7 @@ frame-try-runtime = { version = "0.35.0", default-features = false } pallet-aura = { version = "28.0.0", default-features = false } pallet-authorship = { version = "29.0.0", default-features = false } pallet-assets = { version = "30.0.0", default-features = false } -pallet-balances = { version = "29.0.0", default-features = false } +pallet-balances = { version = "29.0.2", default-features = false } pallet-contracts = { version = "28.0.0", default-features = false } pallet-message-queue = { version = "32.0.0", default-features = false } pallet-multisig = { version = "29.0.0", default-features = false } @@ -97,11 +97,11 @@ pallet-scheduler = { version = "30.0.0", default-features = false } pallet-session = { version = "29.0.0", default-features = false } pallet-sudo = { version = "29.0.0", default-features = false } pallet-timestamp = { version = "28.0.0", default-features = false } -pallet-transaction-payment = { version = "29.0.0", default-features = false } +pallet-transaction-payment = { version = "29.0.1", default-features = false } pallet-transaction-payment-rpc = "31.0.0" pallet-transaction-payment-rpc-runtime-api = { version = "29.0.0", default-features = false } pallet-utility = { version = "29.0.0", default-features = false } -sp-api = { version = "27.0.0", default-features = false } +sp-api = { version = "27.0.1", default-features = false } sp-authority-discovery = { version = "27.0.0", default-features = false } sp-block-builder = { version = "27.0.0", default-features = false } sp-blockchain = "29.0.0" @@ -125,17 +125,17 @@ sp-transaction-pool = { version = "27.0.0", default-features = false } sp-version = { version = "30.0.0", default-features = false } # Polkadot -pallet-xcm = { version = "=8.0.1", default-features = false } +pallet-xcm = { version = "8.0.5", default-features = false } polkadot-cli = "8.0.0" polkadot-parachain-primitives = { version = "7.0.0", default-features = false } -polkadot-runtime-parachains = { version = "8.0.1", default-features = false } +polkadot-runtime-parachains = { version = "8.0.3", default-features = false } polkadot-primitives = { version = "8.0.1", default-features = false } -polkadot-runtime-common = { version = "8.0.1", default-features = false } +polkadot-runtime-common = { version = "8.0.2", default-features = false } rococo-runtime-constants = { version = "8.0.0", default-features = false } rococo-runtime = { version = "8.0.0", default-features = false } -xcm = { package = "staging-xcm", version = "8.0.1", default-features = false } -xcm-builder = { package = "staging-xcm-builder", version = "8.0.1", default-features = false } -xcm-executor = { package = "staging-xcm-executor", version = "8.0.1", default-features = false } +xcm = { version = "8.0.1", package = "staging-xcm", default-features = false } +xcm-builder = { version = "8.0.2", package = "staging-xcm-builder", default-features = false } +xcm-executor = { version = "8.0.2", package = "staging-xcm-executor", default-features = false } # Cumulus asset-hub-rococo-runtime = { version = "0.12.0", default-features = false } @@ -149,9 +149,9 @@ cumulus-primitives-aura = { version = "0.8.0", default-features = false } cumulus-primitives-core = { version = "0.8.0", default-features = false } cumulus-primitives-utility = { version = "0.8.1", default-features = false } emulated-integration-tests-common = { version = "4.0.0", default-features = false } -pallet-collator-selection = { version = "10.0.0", default-features = false } +pallet-collator-selection = { version = "10.0.2", default-features = false } parachains-common = { version = "8.0.0", default-features = false } -parachain-info = { package = "staging-parachain-info", version = "0.8.0", default-features = false } +parachain-info = { version = "0.8.0", package = "staging-parachain-info", default-features = false } cumulus-primitives-parachain-inherent = "0.8.0" cumulus-relay-chain-interface = "0.8.0" color-print = "0.3.4" @@ -160,4 +160,4 @@ cumulus-client-collator = "0.8.0" cumulus-client-consensus-aura = "0.8.0" cumulus-client-consensus-common = "0.8.0" cumulus-client-consensus-proposer = "0.8.0" -cumulus-client-service = "0.8.0" \ No newline at end of file +cumulus-client-service = "0.8.0" diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index 9a868cfa..2dd4519c 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -9,9 +9,9 @@ edition = "2021" enumflags2 = { version = "0.7.7" } ink = { version = "5.0.0", default-features = false } scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } -scale-info = { version = "2.6", default-features = false, features = ["derive"] } -sp-io = { version = "23.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } -sp-runtime = { version = "24.0", default-features = false } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +sp-io = { version = "31.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } +sp-runtime = { version = "32.0.0", default-features = false } pop-primitives = { path = "../primitives", features = ["devnet"], default-features = false } diff --git a/pop-api/examples/.gitignore b/pop-api/examples/.gitignore index e0caa493..d60800c8 100755 --- a/pop-api/examples/.gitignore +++ b/pop-api/examples/.gitignore @@ -1,9 +1,9 @@ # Ignore build artifacts from the local tests sub-crate. -/fungibles/target/ +**/target/ # Ignore backup files creates by cargo fmt. **/*.rs.bk # Remove Cargo.lock when creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock -Cargo.lock +**/Cargo.lock diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 41ea1b14..35719ac6 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -12,7 +12,7 @@ use pop_api::{ primitives::{AccountId as AccountId32, AssetId}, }; -pub type Result = core::result::Result; +pub type Result = core::result::Result; #[ink::contract(env = pop_api::Environment)] mod fungibles { @@ -68,9 +68,9 @@ mod fungibles { value, ); - let result = api::transfer(id, to, value).map_err(|e| e.into()); + let result = api::transfer(id, to, value); ink::env::debug_println!("Result: {:?}", result); - result + result.map_err(|e| e.into()) } #[ink(message)] @@ -91,9 +91,9 @@ mod fungibles { value, ); - let result = api::transfer_from(id, from, to, value, &data).map_err(|e| e.into()); + let result = api::transfer_from(id, from, to, value, &data); ink::env::debug_println!("Result: {:?}", result); - result + result.map_err(|e| e.into()) } /// 2. PSP-22 Metadata Interface: @@ -118,9 +118,9 @@ mod fungibles { admin, min_balance, ); - let result = api::create(id, admin, min_balance).map_err(|e| e.into()); + let result = api::create(id, admin, min_balance); ink::env::debug_println!("Result: {:?}", result); - result + result.map_err(|e| e.into()) } #[ink(message)] @@ -138,9 +138,9 @@ mod fungibles { symbol, decimals, ); - let result = api::set_metadata(id, name, symbol, decimals).map_err(|e| e.into()); + let result = api::set_metadata(id, name, symbol, decimals); ink::env::debug_println!("Result: {:?}", result); - result + result.map_err(|e| e.into()) } #[ink(message)] diff --git a/pop-api/integration-tests/Cargo.toml b/pop-api/integration-tests/Cargo.toml new file mode 100644 index 00000000..84769433 --- /dev/null +++ b/pop-api/integration-tests/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "integration-tests" +version = "0.1.0" +edition = "2021" + +[dev-dependencies] +env_logger = "0.11.2" +scale = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +frame-support = { version = "29.0.0", default-features = false } +frame-system = { version = "29.0.0", default-features = false } +pallet-balances = { version = "29.0.2", default-features = false } +pallet-contracts = { version = "28.0.0", default-features = false } +pop-api = { path = "../.", default-features = false, features = ["assets"] } +pop-runtime-devnet = { path = "../../runtime/devnet", default-features = false } +sp-io = { version = "31.0.0", default-features = false } +sp-runtime = { version = "32.0.0", default-features = false } + + +[features] +default = ["std"] +std = [ + "frame-support/std", + "frame-system/std", + "pallet-balances/std", + "pallet-contracts/std", + "pop-api/std", + "pop-runtime-devnet/std", + "scale/std", + "sp-io/std", + "sp-runtime/std", +] \ No newline at end of file diff --git a/pop-api/integration-tests/src/lib.rs b/pop-api/integration-tests/src/lib.rs new file mode 100644 index 00000000..624c3000 --- /dev/null +++ b/pop-api/integration-tests/src/lib.rs @@ -0,0 +1,95 @@ +#![cfg(test)] + +use frame_support::{ + traits::fungibles::{approvals::Inspect as ApprovalInspect, Inspect}, + weights::Weight, +}; +use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; +use scale::{Decode, Encode}; +use sp_runtime::{traits::Hash, AccountId32, BuildStorage, DispatchError}; + +use pop_runtime_devnet::{Assets, Contracts, Runtime, RuntimeOrigin, System, UNIT}; + +mod local_fungibles; + +type Balance = u128; +type AssetId = u32; +const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; + +const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); +const BOB: AccountId32 = AccountId32::new([2_u8; 32]); +// FERDIE has no initial balance. +const FERDIE: AccountId32 = AccountId32::new([3_u8; 32]); +const INIT_AMOUNT: Balance = 100_000_000 * UNIT; +const INIT_VALUE: Balance = 100 * UNIT; +const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); + +fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT)], + } + .assimilate_storage(&mut t) + .expect("Pallet balances storage can be assimilated"); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +fn load_wasm_module(path: &str) -> std::io::Result<(Vec, ::Output)> +where + T: frame_system::Config, +{ + let wasm_binary = std::fs::read(path)?; + let code_hash = T::Hashing::hash(&wasm_binary); + Ok((wasm_binary, code_hash)) +} + +fn function_selector(name: &str) -> Vec { + let hash = sp_io::hashing::blake2_256(name.as_bytes()); + [hash[0..4].to_vec()].concat() +} + +fn do_bare_call( + addr: AccountId32, + input: Vec, + value: u128, +) -> Result { + let result = Contracts::bare_call( + ALICE, + addr.into(), + value.into(), + GAS_LIMIT, + None, + input, + DEBUG_OUTPUT, + CollectEvents::Skip, + Determinism::Enforced, + ); + result.result +} + +// Deploy, instantiate and return contract address. +fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { + let (wasm_binary, _) = + load_wasm_module::(contract).expect("could not read .wasm file"); + let result = Contracts::bare_instantiate( + ALICE, + init_value, + GAS_LIMIT, + None, + Code::Upload(wasm_binary), + function_selector("new"), + salt, + DEBUG_OUTPUT, + CollectEvents::Skip, + ) + .result + .unwrap(); + assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); + result.account_id +} diff --git a/runtime/devnet/src/tests/local_fungibles.rs b/pop-api/integration-tests/src/local_fungibles.rs similarity index 88% rename from runtime/devnet/src/tests/local_fungibles.rs rename to pop-api/integration-tests/src/local_fungibles.rs index ac2b8ca0..1b3c6633 100644 --- a/runtime/devnet/src/tests/local_fungibles.rs +++ b/pop-api/integration-tests/src/local_fungibles.rs @@ -1,16 +1,8 @@ -// Todo - errors: -// - Badorigin: contract is always signed -// - Lookup: is a valid AccountId due to the contract -// - Many errors can occur from calling a dispatchable. All the DispatchErrors are handled by the -// pop api but not all the possible errors for each dipatchable are tested. How should I approach -// this? -#![cfg(test)] - use super::*; - -use pop_api::{ - error::{ArithmeticError::*, Error::*, TokenError::*}, - v0::assets::fungibles::FungiblesError::*, +use pop_api::error::{ + ArithmeticError::*, + Error::{self, *}, + TokenError::*, }; const ASSET_ID: AssetId = 1; @@ -196,11 +188,8 @@ fn total_supply_works() { fn balance_of_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate( - "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", - INIT_VALUE, - vec![], - ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); // No tokens in circulation. assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr.clone(), ASSET_ID, BOB)); @@ -216,11 +205,8 @@ fn balance_of_works() { fn allowance_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate( - "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", - INIT_VALUE, - vec![], - ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); // No tokens in circulation. assert_eq!( @@ -242,11 +228,8 @@ fn allowance_works() { fn asset_exists_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate( - "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", - INIT_VALUE, - vec![], - ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); // No tokens in circulation. assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr.clone(), ASSET_ID)); @@ -264,16 +247,14 @@ fn create_works() { let _ = env_logger::try_init(); let new_asset = 2; // Instantiate a contract without balance (relay token). - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); + let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); // No balance to pay for fees. assert_eq!( decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), Module { index: 10, error: 2 }, ); // Instantiate a contract without balance (relay token). - let addr = - instantiate("../../pop-api/examples/fungibles/target/ink/fungibles.wasm", 100, vec![2]); + let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 100, vec![2]); // TODO: make sure it has enough for the fees but not for the deposit. // No balance to pay fe deposit. assert_eq!( @@ -281,11 +262,8 @@ fn create_works() { Module { index: 10, error: 2 }, ); // Instantiate a contract with balance. - let addr = instantiate( - "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", - INIT_VALUE, - vec![1], - ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); create_asset(ALICE, ASSET_ID, 1); // Asset ID is already taken. assert_eq!( @@ -307,11 +285,8 @@ fn create_works() { fn set_metadata_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate( - "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", - INIT_VALUE, - vec![], - ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); create_asset(addr.clone(), ASSET_ID, 1); let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); @@ -324,11 +299,8 @@ fn set_metadata_works() { fn transfer_from_mint_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate( - "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", - INIT_VALUE, - vec![], - ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); let amount: Balance = 100 * UNIT; // Asset does not exist. @@ -387,11 +359,8 @@ fn transfer_from_mint_works() { fn transfer_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate( - "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", - INIT_VALUE, - vec![], - ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); let amount: Balance = 100 * UNIT; // Asset does not exist. diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 3e9ead7f..c516adff 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -21,8 +21,7 @@ pub mod v0; type AccountId = AccountId32; // TODO: do the same as the AccountId above and check expanded macro code. -// type Balance = ::Balance; -type Balance = u128; +type Balance = ::Balance; #[cfg(any(feature = "nfts", feature = "cross-chain"))] type BlockNumber = ::BlockNumber; diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index d67d30bd..778387cb 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -298,18 +298,18 @@ pub(crate) fn block(id: AssetId, who: impl Into>) -> /// - pub(crate) fn total_supply(id: AssetId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))).into() + state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))) } pub(crate) fn balance_of(id: AssetId, owner: AccountId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))).into() + state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))) } pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))).into() + state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))) } pub(crate) fn asset_exists(id: AssetId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))).into() + state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))) } // Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 6ba3fea7..cb19b0ab 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -7,10 +7,10 @@ edition = "2021" [dependencies] bounded-collections = { version = "0.1", default-features = false } -scale = { package = "parity-scale-codec", version = "3.6.9", default-features = false, features = ["derive"] } +scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } scale-decode = { version = "0.10.0", default-features = false, features = ["derive"], optional = true } scale-encode = { version = "0.5.0", default-features = false, features = ["derive"], optional = true } -scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } +scale-info = { version = "2.10", default-features = false, features = ["derive"], optional = true } [features] default = ["std"] diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index 4be95986..5fc7cdb3 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -4,12 +4,12 @@ use super::*; #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum RuntimeStateKeys { + #[cfg(feature = "assets")] + Assets(AssetsKeys), #[cfg(feature = "nfts")] Nfts(NftsKeys), #[cfg(feature = "cross-chain")] ParachainSystem(ParachainSystemKeys), - #[cfg(feature = "assets")] - Assets(AssetsKeys), } #[cfg(feature = "cross-chain")] diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index b72bf4f7..5f52b855 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -91,7 +91,6 @@ parachain-info.workspace = true env_logger = "0.11.2" hex = "0.4.3" enumflags2 = "0.7.9" -pop-api = { path = "../../pop-api", features = ["assets", "cross-chain", "nfts"] } [features] default = ["std"] @@ -139,7 +138,6 @@ std = [ "polkadot-parachain-primitives/std", "polkadot-runtime-common/std", "pop-primitives/std", - "pop-api/std", "scale-info/std", "sp-api/std", "sp-io/std", diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs index 9db31e83..904d18ce 100644 --- a/runtime/devnet/src/extensions.rs +++ b/runtime/devnet/src/extensions.rs @@ -390,6 +390,186 @@ where dispatch_call::(&mut env, call, origin, LOG_PREFIX) } +#[cfg(test)] +mod tests { + use super::*; + use crate::{Assets, Runtime, System}; + use sp_runtime::BuildStorage; + + fn new_test_ext() -> sp_io::TestExternalities { + let t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } + + #[test] + fn encoding_decoding_dispatch_error() { + use codec::{Decode, Encode}; + use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; + + new_test_ext().execute_with(|| { + let error = DispatchError::Module(ModuleError { + index: 255, + error: [2, 0, 0, 0], + message: Some("error message"), + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); + assert_eq!( + decoded, + // `message` is skipped for encoding. + DispatchError::Module(ModuleError { + index: 255, + error: [2, 0, 0, 0], + message: None + }) + ); + println!("Encoded Module Error: {:?}", encoded); + + // Example pallet assets Error into ModuleError. + let index = + <::PalletInfo as frame_support::traits::PalletInfo>::index::< + Assets, + >() + .expect("Every active module has an index in the runtime; qed") as u8; + + let mut error = + pallet_assets::Error::NotFrozen::.encode(); + error.resize(MAX_MODULE_ERROR_ENCODED_SIZE, 0); + let error = DispatchError::Module(ModuleError { + index, + error: TryInto::try_into(error).expect("should work"), + message: None, + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 52, 18, 0, 0, 0]); + assert_eq!( + decoded, + DispatchError::Module(ModuleError { + index: 52, + error: [18, 0, 0, 0], + message: None + }) + ); + println!("Encoded Module Error: {:?}", encoded); + + // Example DispatchError::Token + let error = DispatchError::Token(TokenError::UnknownAsset); + let encoded = error.encode(); + assert_eq!(encoded, vec![7, 4]); + println!("Encoded Token Error: {:?}", encoded); + + // Example DispatchError::Arithmetic + let error = DispatchError::Arithmetic(ArithmeticError::Overflow); + let encoded = error.encode(); + assert_eq!(encoded, vec![8, 1]); + println!("Encoded Arithmetic Error: {:?}", encoded); + }); + } + + #[test] + fn encoding_of_enum() { + use codec::{Decode, Encode}; + + // Comprehensive enum with all different type of variants. + #[derive(Debug, PartialEq, Encode, Decode)] + enum ComprehensiveEnum { + SimpleVariant, + DataVariant(u8), + NamedFields { w: u8 }, + NestedEnum(InnerEnum), + OptionVariant(Option), + VecVariant(Vec), + TupleVariant(u8, u8), + NestedStructVariant(NestedStruct), + NestedEnumStructVariant(NestedEnumStruct), + } + + #[derive(Debug, PartialEq, Encode, Decode)] + enum InnerEnum { + A, + B { inner_data: u8 }, + C(u8), + } + + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedStruct { + x: u8, + y: u8, + } + + #[derive(Debug, PartialEq, Encode, Decode)] + struct NestedEnumStruct { + inner_enum: InnerEnum, + } + + // Creating each possible variant for an enum. + let enum_simple = ComprehensiveEnum::SimpleVariant; + let enum_data = ComprehensiveEnum::DataVariant(42); + let enum_named = ComprehensiveEnum::NamedFields { w: 42 }; + let enum_nested = ComprehensiveEnum::NestedEnum(InnerEnum::B { inner_data: 42 }); + let enum_option = ComprehensiveEnum::OptionVariant(Some(42)); + let enum_vec = ComprehensiveEnum::VecVariant(vec![1, 2, 3, 4, 5]); + let enum_tuple = ComprehensiveEnum::TupleVariant(42, 42); + let enum_nested_struct = + ComprehensiveEnum::NestedStructVariant(NestedStruct { x: 42, y: 42 }); + let enum_nested_enum_struct = + ComprehensiveEnum::NestedEnumStructVariant(NestedEnumStruct { + inner_enum: InnerEnum::C(42), + }); + + // Encode and print each variant individually to see their encoded values. + println!("{:?} -> {:?}", enum_simple, enum_simple.encode()); + println!("{:?} -> {:?}", enum_data, enum_data.encode()); + println!("{:?} -> {:?}", enum_named, enum_named.encode()); + println!("{:?} -> {:?}", enum_nested, enum_nested.encode()); + println!("{:?} -> {:?}", enum_option, enum_option.encode()); + println!("{:?} -> {:?}", enum_vec, enum_vec.encode()); + println!("{:?} -> {:?}", enum_tuple, enum_tuple.encode()); + println!("{:?} -> {:?}", enum_nested_struct, enum_nested_struct.encode()); + println!("{:?} -> {:?}", enum_nested_enum_struct, enum_nested_enum_struct.encode()); + } + + #[test] + fn dispatch_error_to_status_code() { + // Create all the different `DispatchError` variants with its respective `PopApiError`. + let test_cases = vec![ + (DispatchError::Other("hallo"), [0, 0, 0, 0]), + (DispatchError::CannotLookup, [1, 0, 0, 0]), + (DispatchError::BadOrigin, [2, 0, 0, 0]), + ( + DispatchError::Module(sp_runtime::ModuleError { + index: 1, + error: [2, 0, 0, 0], + message: Some("hallo"), + }), + [3, 1, 2, 0], + ), + (DispatchError::ConsumerRemaining, [4, 0, 0, 0]), + (DispatchError::NoProviders, [5, 0, 0, 0]), + (DispatchError::TooManyConsumers, [6, 0, 0, 0]), + (DispatchError::Token(sp_runtime::TokenError::BelowMinimum), [7, 2, 0, 0]), + (DispatchError::Arithmetic(sp_runtime::ArithmeticError::Overflow), [8, 1, 0, 0]), + ( + DispatchError::Transactional(sp_runtime::TransactionalError::LimitReached), + [9, 0, 0, 0], + ), + (DispatchError::Exhausted, [10, 0, 0, 0]), + (DispatchError::Corruption, [11, 0, 0, 0]), + (DispatchError::Unavailable, [12, 0, 0, 0]), + (DispatchError::RootNotAllowed, [13, 0, 0, 0]), + ]; + for (error, encoded_error) in test_cases { + let status_code = crate::extensions::convert_to_status_code(error); + assert_eq!(status_code, u32::decode(&mut &encoded_error[..]).unwrap()); + } + } +} // use enumflags2::BitFlags; // use pallet_nfts::{CollectionConfig, CollectionSetting, CollectionSettings, MintSettings}; // use parachains_common::CollectionId; diff --git a/runtime/devnet/src/lib.rs b/runtime/devnet/src/lib.rs index b03bdac6..9ab64043 100644 --- a/runtime/devnet/src/lib.rs +++ b/runtime/devnet/src/lib.rs @@ -10,8 +10,6 @@ mod extensions; mod weights; // Public due to integration tests crate. pub mod config; -#[cfg(test)] -mod tests; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; diff --git a/runtime/devnet/src/tests/mod.rs b/runtime/devnet/src/tests/mod.rs deleted file mode 100644 index 828aa06b..00000000 --- a/runtime/devnet/src/tests/mod.rs +++ /dev/null @@ -1,267 +0,0 @@ -#![cfg(test)] - -use codec::{Decode, Encode}; -use frame_support::traits::fungibles::{approvals::Inspect as ApprovalInspect, Inspect}; -use frame_system::Config; -use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; -use sp_runtime::{traits::Hash, AccountId32, BuildStorage, DispatchError}; - -use crate::{Assets, Contracts, Runtime, RuntimeOrigin, System, Weight, UNIT}; - -mod local_fungibles; - -type Balance = u128; -type AssetId = u32; -const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; - -const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); -const BOB: AccountId32 = AccountId32::new([2_u8; 32]); -// FERDIE has no initial balance. -const FERDIE: AccountId32 = AccountId32::new([3_u8; 32]); -const INIT_AMOUNT: Balance = 100_000_000 * UNIT; -const INIT_VALUE: Balance = 100 * UNIT; -const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); - -fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default() - .build_storage() - .expect("Frame system builds valid default genesis config"); - - pallet_balances::GenesisConfig:: { - balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT)], - } - .assimilate_storage(&mut t) - .expect("Pallet balances storage can be assimilated"); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext -} - -fn load_wasm_module(path: &str) -> std::io::Result<(Vec, ::Output)> -where - T: frame_system::Config, -{ - let wasm_binary = std::fs::read(path)?; - let code_hash = T::Hashing::hash(&wasm_binary); - Ok((wasm_binary, code_hash)) -} - -fn function_selector(name: &str) -> Vec { - let hash = sp_io::hashing::blake2_256(name.as_bytes()); - [hash[0..4].to_vec()].concat() -} - -fn do_bare_call( - addr: AccountId32, - input: Vec, - value: u128, -) -> Result { - let result = Contracts::bare_call( - ALICE, - addr.into(), - value.into(), - GAS_LIMIT, - None, - input, - DEBUG_OUTPUT, - CollectEvents::Skip, - Determinism::Enforced, - ); - log::debug!("Contract debug buffer - {:?}", String::from_utf8(result.debug_message.clone())); - log::debug!("result: {:?}", result); - result.result -} - -// Deploy, instantiate and return contract address. -fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { - let (wasm_binary, _) = - load_wasm_module::(contract).expect("could not read .wasm file"); - let result = Contracts::bare_instantiate( - ALICE, - init_value, - GAS_LIMIT, - None, - Code::Upload(wasm_binary), - function_selector("new"), - salt, - DEBUG_OUTPUT, - CollectEvents::Skip, - ) - .result - .unwrap(); - assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); - result.account_id -} - -mod encoding { - use super::*; - use crate::config::assets::TrustBackedAssetsInstance; - use crate::Runtime; - use sp_runtime::DispatchError; - - #[test] - fn encoding_decoding_dispatch_error() { - use codec::{Decode, Encode}; - use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; - - new_test_ext().execute_with(|| { - let error = DispatchError::Module(ModuleError { - index: 255, - error: [2, 0, 0, 0], - message: Some("error message"), - }); - let encoded = error.encode(); - let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); - assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); - assert_eq!( - decoded, - // `message` is skipped for encoding. - DispatchError::Module(ModuleError { - index: 255, - error: [2, 0, 0, 0], - message: None - }) - ); - println!("Encoded Module Error: {:?}", encoded); - - // Example pallet assets Error into ModuleError. - let index = - <::PalletInfo as frame_support::traits::PalletInfo>::index::< - Assets, - >() - .expect("Every active module has an index in the runtime; qed") as u8; - - let mut error = - pallet_assets::Error::NotFrozen::.encode(); - error.resize(sp_runtime::MAX_MODULE_ERROR_ENCODED_SIZE, 0); - let error = DispatchError::Module(ModuleError { - index, - error: TryInto::try_into(error).expect("should work"), - message: None, - }); - let encoded = error.encode(); - let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); - assert_eq!(encoded, vec![3, 52, 18, 0, 0, 0]); - assert_eq!( - decoded, - DispatchError::Module(ModuleError { - index: 52, - error: [18, 0, 0, 0], - message: None - }) - ); - println!("Encoded Module Error: {:?}", encoded); - - // Example DispatchError::Token - let error = DispatchError::Token(TokenError::UnknownAsset); - let encoded = error.encode(); - assert_eq!(encoded, vec![7, 4]); - println!("Encoded Token Error: {:?}", encoded); - - // Example DispatchError::Arithmetic - let error = DispatchError::Arithmetic(ArithmeticError::Overflow); - let encoded = error.encode(); - assert_eq!(encoded, vec![8, 1]); - println!("Encoded Arithmetic Error: {:?}", encoded); - }); - } - - #[test] - fn encoding_of_enum() { - use codec::{Decode, Encode}; - - // Comprehensive enum with all different type of variants. - #[derive(Debug, PartialEq, Encode, Decode)] - enum ComprehensiveEnum { - SimpleVariant, - DataVariant(u8), - NamedFields { w: u8 }, - NestedEnum(InnerEnum), - OptionVariant(Option), - VecVariant(Vec), - TupleVariant(u8, u8), - NestedStructVariant(NestedStruct), - NestedEnumStructVariant(NestedEnumStruct), - } - - #[derive(Debug, PartialEq, Encode, Decode)] - enum InnerEnum { - A, - B { inner_data: u8 }, - C(u8), - } - - #[derive(Debug, PartialEq, Encode, Decode)] - struct NestedStruct { - x: u8, - y: u8, - } - - #[derive(Debug, PartialEq, Encode, Decode)] - struct NestedEnumStruct { - inner_enum: InnerEnum, - } - - // Creating each possible variant for an enum. - let enum_simple = ComprehensiveEnum::SimpleVariant; - let enum_data = ComprehensiveEnum::DataVariant(42); - let enum_named = ComprehensiveEnum::NamedFields { w: 42 }; - let enum_nested = ComprehensiveEnum::NestedEnum(InnerEnum::B { inner_data: 42 }); - let enum_option = ComprehensiveEnum::OptionVariant(Some(42)); - let enum_vec = ComprehensiveEnum::VecVariant(vec![1, 2, 3, 4, 5]); - let enum_tuple = ComprehensiveEnum::TupleVariant(42, 42); - let enum_nested_struct = - ComprehensiveEnum::NestedStructVariant(NestedStruct { x: 42, y: 42 }); - let enum_nested_enum_struct = - ComprehensiveEnum::NestedEnumStructVariant(NestedEnumStruct { - inner_enum: InnerEnum::C(42), - }); - - // Encode and print each variant individually to see their encoded values. - println!("{:?} -> {:?}", enum_simple, enum_simple.encode()); - println!("{:?} -> {:?}", enum_data, enum_data.encode()); - println!("{:?} -> {:?}", enum_named, enum_named.encode()); - println!("{:?} -> {:?}", enum_nested, enum_nested.encode()); - println!("{:?} -> {:?}", enum_option, enum_option.encode()); - println!("{:?} -> {:?}", enum_vec, enum_vec.encode()); - println!("{:?} -> {:?}", enum_tuple, enum_tuple.encode()); - println!("{:?} -> {:?}", enum_nested_struct, enum_nested_struct.encode()); - println!("{:?} -> {:?}", enum_nested_enum_struct, enum_nested_enum_struct.encode()); - } - - #[test] - fn dispatch_error_to_status_code() { - // Create all the different `DispatchError` variants with its respective `PopApiError`. - let test_cases = vec![ - (DispatchError::Other("hallo"), [0, 0, 0, 0]), - (DispatchError::CannotLookup, [1, 0, 0, 0]), - (DispatchError::BadOrigin, [2, 0, 0, 0]), - ( - DispatchError::Module(sp_runtime::ModuleError { - index: 1, - error: [2, 0, 0, 0], - message: Some("hallo"), - }), - [3, 1, 2, 0], - ), - (DispatchError::ConsumerRemaining, [4, 0, 0, 0]), - (DispatchError::NoProviders, [5, 0, 0, 0]), - (DispatchError::TooManyConsumers, [6, 0, 0, 0]), - (DispatchError::Token(sp_runtime::TokenError::BelowMinimum), [7, 2, 0, 0]), - (DispatchError::Arithmetic(sp_runtime::ArithmeticError::Overflow), [8, 1, 0, 0]), - ( - DispatchError::Transactional(sp_runtime::TransactionalError::LimitReached), - [9, 0, 0, 0], - ), - (DispatchError::Exhausted, [10, 0, 0, 0]), - (DispatchError::Corruption, [11, 0, 0, 0]), - (DispatchError::Unavailable, [12, 0, 0, 0]), - (DispatchError::RootNotAllowed, [13, 0, 0, 0]), - ]; - for (error, encoded_error) in test_cases { - let status_code = crate::extensions::convert_to_status_code(error); - assert_eq!(status_code, u32::decode(&mut &encoded_error[..]).unwrap()); - } - } -} From c1616a3611f73f0185f822339c452549c63b2926 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Wed, 26 Jun 2024 15:41:18 +0200 Subject: [PATCH 13/27] refactor: naming pallet error --- pop-api/Cargo.toml | 6 +- pop-api/src/lib.rs | 2 +- pop-api/src/v0/cross_chain/mod.rs | 8 +- pop-api/src/v0/nfts.rs | 308 +++++++++++++++--------------- primitives/src/storage_keys.rs | 11 +- 5 files changed, 170 insertions(+), 165 deletions(-) diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index 2dd4519c..8454c1fa 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -5,12 +5,15 @@ license = "GPL-3.0-only" version = "0.0.0" edition = "2021" +[workspace] +exclude = [ + "integration-tests", +] [dependencies] enumflags2 = { version = "0.7.7" } ink = { version = "5.0.0", default-features = false } scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-io = { version = "31.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } sp-runtime = { version = "32.0.0", default-features = false } pop-primitives = { path = "../primitives", features = ["devnet"], default-features = false } @@ -28,7 +31,6 @@ std = [ "pop-primitives/std", "scale/std", "scale-info/std", - "sp-io/std", "sp-runtime/std", ] assets = ["pop-primitives/assets"] diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index c516adff..04d08bce 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,7 +1,7 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] use ink::{prelude::vec::Vec, ChainExtensionInstance}; -pub use sp_runtime::{BoundedVec, MultiAddress, MultiSignature}; +pub use sp_runtime::{MultiAddress, MultiSignature}; use crate::error::{Error, StatusCode}; use primitives::{storage_keys::*, AccountId as AccountId32}; diff --git a/pop-api/src/v0/cross_chain/mod.rs b/pop-api/src/v0/cross_chain/mod.rs index 5a0dda6c..ad58e0e8 100644 --- a/pop-api/src/v0/cross_chain/mod.rs +++ b/pop-api/src/v0/cross_chain/mod.rs @@ -10,7 +10,7 @@ pub fn relay_chain_block_number() -> Result { #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum Error { +pub enum CrossChainError { /// The desired destination was unreachable, generally because there is a no way of routing /// to it. Unreachable, @@ -66,11 +66,11 @@ pub enum Error { LocalExecutionIncomplete, } -impl TryFrom for Error { - type Error = Error; +impl TryFrom for CrossChainError { + type Error = crate::error::Error; fn try_from(status_code: u32) -> core::result::Result { - use Error::*; + use CrossChainError::*; match status_code { 0 => Ok(Unreachable), 1 => Ok(SendFailure), diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index 29219c66..32539576 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -5,10 +5,10 @@ use crate::{ dispatch, primitives::{ nfts::{ApprovalsLimit, CollectionId, ItemId, KeyLimit}, - BoundedBTreeMap, + BoundedBTreeMap, BoundedVec, }, - state, AccountId, Balance, BlockNumber, BoundedVec, MultiAddress, NftsKeys, RuntimeCall, - RuntimeStateKeys, StatusCode, + state, AccountId, Balance, BlockNumber, MultiAddress, NftsKeys, RuntimeCall, RuntimeStateKeys, + StatusCode, }; pub use types::*; @@ -521,157 +521,157 @@ pub(crate) enum NftCalls { receive_item: ItemId, }, } -// -// #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -// #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -// pub enum Error { -// /// The signing account has no permission to do the operation. -// NoPermission, -// /// The given item ID is unknown. -// UnknownCollection, -// /// The item ID has already been used for an item. -// AlreadyExists, -// /// The approval had a deadline that expired, so the approval isn't valid anymore. -// ApprovalExpired, -// /// The owner turned out to be different to what was expected. -// WrongOwner, -// /// The witness data given does not match the current state of the chain. -// BadWitness, -// /// Collection ID is already taken. -// CollectionIdInUse, -// /// Items within that collection are non-transferable. -// ItemsNonTransferable, -// /// The provided account is not a delegate. -// NotDelegate, -// /// The delegate turned out to be different to what was expected. -// WrongDelegate, -// /// No approval exists that would allow the transfer. -// Unapproved, -// /// The named owner has not signed ownership acceptance of the collection. -// Unaccepted, -// /// The item is locked (non-transferable). -// ItemLocked, -// /// Item's attributes are locked. -// LockedItemAttributes, -// /// Collection's attributes are locked. -// LockedCollectionAttributes, -// /// Item's metadata is locked. -// LockedItemMetadata, -// /// Collection's metadata is locked. -// LockedCollectionMetadata, -// /// All items have been minted. -// MaxSupplyReached, -// /// The max supply is locked and can't be changed. -// MaxSupplyLocked, -// /// The provided max supply is less than the number of items a collection already has. -// MaxSupplyTooSmall, -// /// The given item ID is unknown. -// UnknownItem, -// /// Swap doesn't exist. -// UnknownSwap, -// /// The given item has no metadata set. -// MetadataNotFound, -// /// The provided attribute can't be found. -// AttributeNotFound, -// /// Item is not for sale. -// NotForSale, -// /// The provided bid is too low. -// BidTooLow, -// /// The item has reached its approval limit. -// ReachedApprovalLimit, -// /// The deadline has already expired. -// DeadlineExpired, -// /// The duration provided should be less than or equal to `MaxDeadlineDuration`. -// WrongDuration, -// /// The method is disabled by system settings. -// MethodDisabled, -// /// The provided setting can't be set. -// WrongSetting, -// /// Item's config already exists and should be equal to the provided one. -// InconsistentItemConfig, -// /// Config for a collection or an item can't be found. -// NoConfig, -// /// Some roles were not cleared. -// RolesNotCleared, -// /// Mint has not started yet. -// MintNotStarted, -// /// Mint has already ended. -// MintEnded, -// /// The provided Item was already used for claiming. -// AlreadyClaimed, -// /// The provided data is incorrect. -// IncorrectData, -// /// The extrinsic was sent by the wrong origin. -// WrongOrigin, -// /// The provided signature is incorrect. -// WrongSignature, -// /// The provided metadata might be too long. -// IncorrectMetadata, -// /// Can't set more attributes per one call. -// MaxAttributesLimitReached, -// /// The provided namespace isn't supported in this call. -// WrongNamespace, -// /// Can't delete non-empty collections. -// CollectionNotEmpty, -// /// The witness data should be provided. -// WitnessRequired, -// } -// -// impl TryFrom for Error { -// type Error = Error; -// -// fn try_from(status_code: u32) -> core::result::Result { -// use Error::*; -// match status_code { -// 0 => Ok(NoPermission), -// 1 => Ok(UnknownCollection), -// 2 => Ok(AlreadyExists), -// 3 => Ok(ApprovalExpired), -// 4 => Ok(WrongOwner), -// 5 => Ok(BadWitness), -// 6 => Ok(CollectionIdInUse), -// 7 => Ok(ItemsNonTransferable), -// 8 => Ok(NotDelegate), -// 9 => Ok(WrongDelegate), -// 10 => Ok(Unapproved), -// 11 => Ok(Unaccepted), -// 12 => Ok(ItemLocked), -// 13 => Ok(LockedItemAttributes), -// 14 => Ok(LockedCollectionAttributes), -// 15 => Ok(LockedItemMetadata), -// 16 => Ok(LockedCollectionMetadata), -// 17 => Ok(MaxSupplyReached), -// 18 => Ok(MaxSupplyLocked), -// 19 => Ok(MaxSupplyTooSmall), -// 20 => Ok(UnknownItem), -// 21 => Ok(UnknownSwap), -// 22 => Ok(MetadataNotFound), -// 23 => Ok(AttributeNotFound), -// 24 => Ok(NotForSale), -// 25 => Ok(BidTooLow), -// 26 => Ok(ReachedApprovalLimit), -// 27 => Ok(DeadlineExpired), -// 28 => Ok(WrongDuration), -// 29 => Ok(MethodDisabled), -// 30 => Ok(WrongSetting), -// 31 => Ok(InconsistentItemConfig), -// 32 => Ok(NoConfig), -// 33 => Ok(RolesNotCleared), -// 34 => Ok(MintNotStarted), -// 35 => Ok(MintEnded), -// 36 => Ok(AlreadyClaimed), -// 37 => Ok(IncorrectData), -// 38 => Ok(WrongOrigin), -// 39 => Ok(WrongSignature), -// 40 => Ok(IncorrectMetadata), -// 41 => Ok(MaxAttributesLimitReached), -// 42 => Ok(WrongNamespace), -// 43 => Ok(CollectionNotEmpty), -// 44 => Ok(WitnessRequired), -// _ => todo!(), -// } -// } -// } + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +pub enum NftsError { + /// The signing account has no permission to do the operation. + NoPermission, + /// The given item ID is unknown. + UnknownCollection, + /// The item ID has already been used for an item. + AlreadyExists, + /// The approval had a deadline that expired, so the approval isn't valid anymore. + ApprovalExpired, + /// The owner turned out to be different to what was expected. + WrongOwner, + /// The witness data given does not match the current state of the chain. + BadWitness, + /// Collection ID is already taken. + CollectionIdInUse, + /// Items within that collection are non-transferable. + ItemsNonTransferable, + /// The provided account is not a delegate. + NotDelegate, + /// The delegate turned out to be different to what was expected. + WrongDelegate, + /// No approval exists that would allow the transfer. + Unapproved, + /// The named owner has not signed ownership acceptance of the collection. + Unaccepted, + /// The item is locked (non-transferable). + ItemLocked, + /// Item's attributes are locked. + LockedItemAttributes, + /// Collection's attributes are locked. + LockedCollectionAttributes, + /// Item's metadata is locked. + LockedItemMetadata, + /// Collection's metadata is locked. + LockedCollectionMetadata, + /// All items have been minted. + MaxSupplyReached, + /// The max supply is locked and can't be changed. + MaxSupplyLocked, + /// The provided max supply is less than the number of items a collection already has. + MaxSupplyTooSmall, + /// The given item ID is unknown. + UnknownItem, + /// Swap doesn't exist. + UnknownSwap, + /// The given item has no metadata set. + MetadataNotFound, + /// The provided attribute can't be found. + AttributeNotFound, + /// Item is not for sale. + NotForSale, + /// The provided bid is too low. + BidTooLow, + /// The item has reached its approval limit. + ReachedApprovalLimit, + /// The deadline has already expired. + DeadlineExpired, + /// The duration provided should be less than or equal to `MaxDeadlineDuration`. + WrongDuration, + /// The method is disabled by system settings. + MethodDisabled, + /// The provided setting can't be set. + WrongSetting, + /// Item's config already exists and should be equal to the provided one. + InconsistentItemConfig, + /// Config for a collection or an item can't be found. + NoConfig, + /// Some roles were not cleared. + RolesNotCleared, + /// Mint has not started yet. + MintNotStarted, + /// Mint has already ended. + MintEnded, + /// The provided Item was already used for claiming. + AlreadyClaimed, + /// The provided data is incorrect. + IncorrectData, + /// The extrinsic was sent by the wrong origin. + WrongOrigin, + /// The provided signature is incorrect. + WrongSignature, + /// The provided metadata might be too long. + IncorrectMetadata, + /// Can't set more attributes per one call. + MaxAttributesLimitReached, + /// The provided namespace isn't supported in this call. + WrongNamespace, + /// Can't delete non-empty collections. + CollectionNotEmpty, + /// The witness data should be provided. + WitnessRequired, +} + +impl TryFrom for NftsError { + type Error = crate::error::Error; + + fn try_from(status_code: u32) -> core::result::Result { + use NftsError::*; + match status_code { + 0 => Ok(NoPermission), + 1 => Ok(UnknownCollection), + 2 => Ok(AlreadyExists), + 3 => Ok(ApprovalExpired), + 4 => Ok(WrongOwner), + 5 => Ok(BadWitness), + 6 => Ok(CollectionIdInUse), + 7 => Ok(ItemsNonTransferable), + 8 => Ok(NotDelegate), + 9 => Ok(WrongDelegate), + 10 => Ok(Unapproved), + 11 => Ok(Unaccepted), + 12 => Ok(ItemLocked), + 13 => Ok(LockedItemAttributes), + 14 => Ok(LockedCollectionAttributes), + 15 => Ok(LockedItemMetadata), + 16 => Ok(LockedCollectionMetadata), + 17 => Ok(MaxSupplyReached), + 18 => Ok(MaxSupplyLocked), + 19 => Ok(MaxSupplyTooSmall), + 20 => Ok(UnknownItem), + 21 => Ok(UnknownSwap), + 22 => Ok(MetadataNotFound), + 23 => Ok(AttributeNotFound), + 24 => Ok(NotForSale), + 25 => Ok(BidTooLow), + 26 => Ok(ReachedApprovalLimit), + 27 => Ok(DeadlineExpired), + 28 => Ok(WrongDuration), + 29 => Ok(MethodDisabled), + 30 => Ok(WrongSetting), + 31 => Ok(InconsistentItemConfig), + 32 => Ok(NoConfig), + 33 => Ok(RolesNotCleared), + 34 => Ok(MintNotStarted), + 35 => Ok(MintEnded), + 36 => Ok(AlreadyClaimed), + 37 => Ok(IncorrectData), + 38 => Ok(WrongOrigin), + 39 => Ok(WrongSignature), + 40 => Ok(IncorrectMetadata), + 41 => Ok(MaxAttributesLimitReached), + 42 => Ok(WrongNamespace), + 43 => Ok(CollectionNotEmpty), + 44 => Ok(WitnessRequired), + _ => todo!(), + } + } +} // Local implementations of pallet-nfts types mod types { diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index 5fc7cdb3..748d0662 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -4,12 +4,15 @@ use super::*; #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum RuntimeStateKeys { - #[cfg(feature = "assets")] - Assets(AssetsKeys), - #[cfg(feature = "nfts")] - Nfts(NftsKeys), #[cfg(feature = "cross-chain")] + #[codec(index = 1)] ParachainSystem(ParachainSystemKeys), + #[cfg(feature = "nfts")] + #[codec(index = 50)] + Nfts(NftsKeys), + #[cfg(feature = "assets")] + #[codec(index = 52)] + Assets(AssetsKeys), } #[cfg(feature = "cross-chain")] From 13e947e74f82430bc50865ca6a44ec234620728e Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Wed, 26 Jun 2024 17:10:42 +0200 Subject: [PATCH 14/27] refactor: optimising pop api and additional logic + test --- pop-api/Cargo.toml | 6 +- pop-api/examples/fungibles/lib.rs | 161 +++++-- pop-api/src/error.rs | 166 ++----- pop-api/src/lib.rs | 6 +- pop-api/src/primitives.rs | 1 + pop-api/src/v0/assets/fungibles.rs | 314 +++++++------ pop-api/src/v0/assets/mod.rs | 718 +++++++++++++++-------------- pop-api/src/v0/state.rs | 5 +- primitives/src/lib.rs | 2 +- primitives/src/storage_keys.rs | 7 +- 10 files changed, 710 insertions(+), 676 deletions(-) diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index 8454c1fa..a88d8892 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -5,15 +5,12 @@ license = "GPL-3.0-only" version = "0.0.0" edition = "2021" -[workspace] -exclude = [ - "integration-tests", -] [dependencies] enumflags2 = { version = "0.7.7" } ink = { version = "5.0.0", default-features = false } scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +sp-io = { version = "31.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } sp-runtime = { version = "32.0.0", default-features = false } pop-primitives = { path = "../primitives", features = ["devnet"], default-features = false } @@ -31,6 +28,7 @@ std = [ "pop-primitives/std", "scale/std", "scale-info/std", +"sp-io/std", "sp-runtime/std", ] assets = ["pop-primitives/assets"] diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 35719ac6..bd51d760 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -7,12 +7,12 @@ /// use ink::prelude::vec::Vec; use pop_api::{ - assets::fungibles::{self as api, FungiblesError}, - error::{Error, StatusCode}, + assets::fungibles::{self as api}, + error::StatusCode, primitives::{AccountId as AccountId32, AssetId}, }; -pub type Result = core::result::Result; +pub type Result = core::result::Result; #[ink::contract(env = pop_api::Environment)] mod fungibles { @@ -41,12 +41,14 @@ mod fungibles { #[ink(message)] pub fn total_supply(&self, id: AssetId) -> Result { - api::total_supply(id).map_err(|e| e.into()) + // api::total_supply(id).map_err(|e| e.into()) + api::total_supply(id) } #[ink(message)] pub fn balance_of(&self, id: AssetId, owner: AccountId32) -> Result { - api::balance_of(id, owner).map_err(|e| e.into()) + // api::balance_of(id, owner).map_err(|e| e.into()) + api::balance_of(id, owner) } #[ink(message)] @@ -56,7 +58,8 @@ mod fungibles { owner: AccountId32, spender: AccountId32, ) -> Result { - api::allowance(id, owner, spender).map_err(|e| e.into()) + // api::allowance(id, owner, spender).map_err(|e| e.into()) + api::allowance(id, owner, spender) } #[ink(message)] @@ -70,15 +73,16 @@ mod fungibles { let result = api::transfer(id, to, value); ink::env::debug_println!("Result: {:?}", result); - result.map_err(|e| e.into()) + // result.map_err(|e| e.into()) + result } #[ink(message)] pub fn transfer_from( &self, id: AssetId, - from: Option, - to: Option, + from: AccountId32, + to: AccountId32, value: Balance, // In the standard a `[u8]`, but the size needs to be known at compile time. data: Vec, @@ -93,60 +97,137 @@ mod fungibles { let result = api::transfer_from(id, from, to, value, &data); ink::env::debug_println!("Result: {:?}", result); - result.map_err(|e| e.into()) + // result.map_err(|e| e.into()) + result } - /// 2. PSP-22 Metadata Interface: - /// - token_name - /// - token_symbol - /// - token_decimals + #[ink(message)] + pub fn approve(&self, id: AssetId, spender: AccountId32, value: Balance) -> Result<()> { + ink::env::debug_println!( + "PopApiFungiblesExample::approve: id: {:?}, spender {:?}, value: {:?}", + id, + spender, + value, + ); - /// 3. Asset Management: - /// - create - /// - start_destroy - /// - destroy_accounts - /// - destroy_approvals - /// - finish_destroy - /// - set_metadata - /// - clear_metadata + let result = api::approve(id, spender, value); + ink::env::debug_println!("Result: {:?}", result); + // result.map_err(|e| e.into()) + result + } #[ink(message)] - pub fn create(&self, id: AssetId, admin: AccountId32, min_balance: Balance) -> Result<()> { + pub fn increase_allowance( + &self, + id: AssetId, + spender: AccountId32, + value: Balance, + ) -> Result<()> { ink::env::debug_println!( - "PopApiFungiblesExample::create: id: {:?} admin: {:?} min_balance: {:?}", + "PopApiFungiblesExample::increase_allowance: id: {:?}, spender {:?}, value: {:?}", id, - admin, - min_balance, + spender, + value, ); - let result = api::create(id, admin, min_balance); + + let result = api::increase_allowance(id, spender, value); ink::env::debug_println!("Result: {:?}", result); - result.map_err(|e| e.into()) + // result.map_err(|e| e.into()) + result } #[ink(message)] - pub fn set_metadata( + pub fn decrease_allowance( &self, id: AssetId, - name: Vec, - symbol: Vec, - decimals: u8, + spender: AccountId32, + value: Balance, ) -> Result<()> { ink::env::debug_println!( - "PopApiFungiblesExample::set_metadata: id: {:?} name: {:?} symbol: {:?}, decimals: {:?}", + "PopApiFungiblesExample::decrease_allowance: id: {:?}, spender {:?}, value: {:?}", id, - name, - symbol, - decimals, + spender, + value, ); - let result = api::set_metadata(id, name, symbol, decimals); + + let result = api::decrease_allowance(id, spender, value); ink::env::debug_println!("Result: {:?}", result); - result.map_err(|e| e.into()) + // result.map_err(|e| e.into()) + result + } + + /// 2. PSP-22 Metadata Interface: + /// - token_name + /// - token_symbol + /// - token_decimals + + #[ink(message)] + pub fn token_name(&self, id: AssetId) -> Result> { + // api::token_name(id).map_err(|e| e.into()) + api::token_name(id) } #[ink(message)] - pub fn asset_exists(&self, id: AssetId) -> Result { - api::asset_exists(id).map_err(|e| e.into()) + pub fn token_symbol(&self, id: AssetId) -> Result> { + // api::token_symbol(id).map_err(|e| e.into()) + api::token_symbol(id) } + + #[ink(message)] + pub fn token_decimals(&self, id: AssetId) -> Result { + // api::token_decimals(id).map_err(|e| e.into()) + api::token_decimals(id) + } + + // 3. Asset Management: + // - create + // - start_destroy + // - destroy_accounts + // - destroy_approvals + // - finish_destroy + // - set_metadata + // - clear_metadata + + // #[ink(message)] + // pub fn create(&self, id: AssetId, admin: AccountId32, min_balance: Balance) -> Result<()> { + // ink::env::debug_println!( + // "PopApiFungiblesExample::create: id: {:?} admin: {:?} min_balance: {:?}", + // id, + // admin, + // min_balance, + // ); + // let result = api::create(id, admin, min_balance); + // ink::env::debug_println!("Result: {:?}", result); + // // result.map_err(|e| e.into()) + // result + // } + + // #[ink(message)] + // pub fn set_metadata( + // &self, + // id: AssetId, + // name: Vec, + // symbol: Vec, + // decimals: u8, + // ) -> Result<()> { + // ink::env::debug_println!( + // "PopApiFungiblesExample::set_metadata: id: {:?} name: {:?} symbol: {:?}, decimals: {:?}", + // id, + // name, + // symbol, + // decimals, + // ); + // let result = api::set_metadata(id, name, symbol, decimals); + // ink::env::debug_println!("Result: {:?}", result); + // // result.map_err(|e| e.into()) + // result + // } + // + // #[ink(message)] + // pub fn asset_exists(&self, id: AssetId) -> Result { + // // api::asset_exists(id).map_err(|e| e.into()) + // api::asset_exists(id) + // } } #[cfg(test)] diff --git a/pop-api/src/error.rs b/pop-api/src/error.rs index b8a56f55..54681e6d 100644 --- a/pop-api/src/error.rs +++ b/pop-api/src/error.rs @@ -14,79 +14,16 @@ impl From for StatusCode { } impl FromStatusCode for StatusCode { fn from_status_code(status_code: u32) -> Result<(), Self> { - match status_code { - 0 => Ok(()), - _ => { - let mut encoded = status_code.to_le_bytes(); - convert_unknown_errors(&mut encoded); - Err(StatusCode::from(u32::from_le_bytes(encoded))) - }, + if status_code == 0 { + return Ok(()); } + Err(StatusCode(status_code)) } } impl From for StatusCode { fn from(_: scale::Error) -> Self { - DecodingFailed.into() - } -} - -// If an unknown variant of the `DispatchError` is detected the error needs to be converted -// into the encoded value of `Error::Other`. This conversion is performed by shifting the bytes one -// position forward (discarding the last byte as it is not used) and setting the first byte to the -// encoded value of `Other` (0u8). This ensures the error is correctly categorized as an `Other` -// variant which provides all the necessary information to debug which error occurred in the runtime. -// -// Byte layout explanation: -// - Byte 0: index of the variant within `Error` -// - Byte 1: -// - Must be zero for `UNIT_ERRORS`. -// - Represents the nested error in `SINGLE_NESTED_ERRORS`. -// - Represents the first level of nesting in `DOUBLE_NESTED_ERRORS`. -// - Byte 2: -// - Represents the second level of nesting in `DOUBLE_NESTED_ERRORS`. -// - Byte 3: -// - Unused or represents further nested information. -// -// This mechanism ensures backward compatibility by correctly categorizing any unknown errors -// into the `Other` variant, thus preventing issues caused by breaking changes. -fn convert_unknown_errors(encoded_error: &mut [u8; 4]) { - let all_errors = [ - UNIT_ERRORS.as_slice(), - SINGLE_NESTED_ERRORS.as_slice(), - DOUBLE_NESTED_ERRORS.as_slice(), - // `DecodingFailed`. - &[255u8], - ] - .concat(); - // Unknown errors, i.e. an encoded value where the first byte is non-zero (indicating a variant - // in `Error`) but unknown. - if !all_errors.contains(&encoded_error[0]) { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; - } - convert_unknown_nested_errors(encoded_error); -} - -// If an unknown nested variant of the `DispatchError` is detected (i.e. when any of the subsequent -// bytes are non-zero). -fn convert_unknown_nested_errors(encoded_error: &mut [u8; 4]) { - // Converts single nested errors that are known to the Pop API as unit errors into `Other`. - if UNIT_ERRORS.contains(&encoded_error[0]) && encoded_error[1..].iter().any(|x| *x != 0u8) { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; - // Converts double nested errors that are known to the Pop API as single nested errors into - // `Other`. - } else if SINGLE_NESTED_ERRORS.contains(&encoded_error[0]) - && encoded_error[2..].iter().any(|x| *x != 0u8) - { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; - } else if DOUBLE_NESTED_ERRORS.contains(&encoded_error[0]) - && encoded_error[3..].iter().any(|x| *x != 0u8) - { - encoded_error[..].rotate_right(1); - encoded_error[0] = 0u8; + StatusCode(255u32) } } @@ -136,32 +73,7 @@ pub enum Error { DecodingFailed = 255, } -// Unit `Error` variants. -// (variant: index): -// - CannotLookup: 1, -// - BadOrigin: 2, -// - ConsumerRemaining: 4, -// - NoProviders: 5, -// - TooManyConsumers: 6, -// - Exhausted: 10, -// - Corruption: 11, -// - Unavailable: 12, -// - RootNotAllowed: 13, -// - DecodingFailed: 255, -const UNIT_ERRORS: [u8; 10] = [1, 2, 4, 5, 6, 10, 11, 12, 13, 255]; - -// Single nested `Error` variants. -// (variant: index): -// - Token: 7, -// - Arithmetic: 8, -// - Transaction: 9, -const SINGLE_NESTED_ERRORS: [u8; 3] = [7, 8, 9]; - -// Double nested `Error` variants -// (variant: index): -// - Module: 3, -const DOUBLE_NESTED_ERRORS: [u8; 1] = [3]; - +#[cfg(test)] impl From for StatusCode { fn from(value: Error) -> Self { let mut encoded_error = value.encode(); @@ -175,8 +87,15 @@ impl From for StatusCode { impl From for Error { fn from(value: StatusCode) -> Self { - let encoded: [u8; 4] = value.0.to_le_bytes(); - Error::decode(&mut &encoded[..]).unwrap_or(DecodingFailed) + let mut encoded: [u8; 4] = value.0.to_le_bytes(); + match Error::decode(&mut &encoded[..]) { + Err(_) => { + encoded[..].rotate_right(1); + encoded[0] = 0u8; + Error::decode(&mut &encoded[..]).unwrap_or(DecodingFailed) + }, + Ok(error) => error, + } } } @@ -286,28 +205,19 @@ mod tests { into_status_code([error_code, 1, 0, 0]), (Other { dispatch_error_index: error_code, error_index: 1, error: 0 }).into(), ); - assert_eq!( - into_error([error_code, 1, 0, 0]), - Other { dispatch_error_index: error_code, error_index: 1, error: 0 }, - ); + assert_eq!(into_error([error_code, 1, 0, 0]), errors[i]); // Unexpected third byte nested. assert_eq!( into_status_code([error_code, 1, 1, 0]), (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), ); - assert_eq!( - into_error([error_code, 1, 1, 0]), - Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, - ); + assert_eq!(into_error([error_code, 1, 1, 0]), errors[i]); // Unexpected fourth byte nested. assert_eq!( into_status_code([error_code, 1, 1, 1]), (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), ); - assert_eq!( - into_error([error_code, 1, 1, 1]), - Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, - ); + assert_eq!(into_error([error_code, 1, 1, 1]), errors[i]); } } @@ -341,19 +251,13 @@ mod tests { into_status_code([error_code, 1, 1, 0]), (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), ); - assert_eq!( - into_error([error_code, 1, 1, 0]), - Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, - ); + assert_eq!(into_error([error_code, 1, 1, 0]), errors[i][1]); // Unexpected fourth byte nested. assert_eq!( into_status_code([error_code, 1, 1, 1]), (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), ); - assert_eq!( - into_error([error_code, 1, 1, 1]), - Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, - ); + assert_eq!(into_error([error_code, 1, 1, 1]), errors[i][1]); } } @@ -385,9 +289,37 @@ mod tests { into_status_code([3, 1, 1, 1]), (Other { dispatch_error_index: 3, error_index: 1, error: 1 }).into(), ); + assert_eq!(into_error([3, 1, 1, 1]), Module { index: 1, error: 1 }); + } + + #[test] + fn single_nested_unknown_variants() { + // Unknown `TokenError` variant. + assert_eq!( + into_error([7, 10, 0, 0]), + Other { dispatch_error_index: 7, error_index: 10, error: 0 } + ); + assert_eq!( + into_status_code([7, 10, 0, 0]), + Other { dispatch_error_index: 7, error_index: 10, error: 0 }.into() + ); + // Unknown `Arithmetic` variant. + assert_eq!( + into_error([8, 3, 0, 0]), + Other { dispatch_error_index: 8, error_index: 3, error: 0 } + ); + assert_eq!( + into_status_code([8, 3, 0, 0]), + Other { dispatch_error_index: 8, error_index: 3, error: 0 }.into() + ); + // Unknown `Transactional` variant. + assert_eq!( + into_error([9, 2, 0, 0]), + Other { dispatch_error_index: 9, error_index: 2, error: 0 } + ); assert_eq!( - into_error([3, 1, 1, 1]), - Other { dispatch_error_index: 3, error_index: 1, error: 1 }, + into_status_code([9, 2, 0, 0]), + Other { dispatch_error_index: 9, error_index: 2, error: 0 }.into() ); } diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 04d08bce..53bbadc6 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,9 +1,9 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] use ink::{prelude::vec::Vec, ChainExtensionInstance}; -pub use sp_runtime::{MultiAddress, MultiSignature}; +pub use sp_runtime::MultiAddress; -use crate::error::{Error, StatusCode}; +use crate::error::StatusCode; use primitives::{storage_keys::*, AccountId as AccountId32}; #[cfg(feature = "assets")] pub use v0::assets; @@ -62,12 +62,14 @@ pub trait PopApi { fn send_xcm(xcm: primitives::cross_chain::CrossChainMessage) -> Result<()>; } +#[inline] fn dispatch(call: RuntimeCall) -> Result<()> { <::ChainExtension as ChainExtensionInstance>::instantiate( ) .dispatch(call) } +#[inline] fn read_state(key: RuntimeStateKeys) -> Result> { <::ChainExtension as ChainExtensionInstance>::instantiate( ) diff --git a/pop-api/src/primitives.rs b/pop-api/src/primitives.rs index e174a111..17419d5b 100644 --- a/pop-api/src/primitives.rs +++ b/pop-api/src/primitives.rs @@ -1 +1,2 @@ pub use pop_primitives::*; +pub use sp_runtime::MultiAddress; diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index eaf1c6f5..e7c3f41c 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -1,7 +1,12 @@ -use crate::{assets, primitives::AssetId, AccountId, Balance, MultiAddress, StatusCode}; use ink::prelude::vec::Vec; use scale::Encode; +use crate::{ + assets, + primitives::{AssetId, MultiAddress}, + AccountId, Balance, StatusCode, +}; + type Result = core::result::Result; /// Local Fungibles: @@ -26,6 +31,7 @@ type Result = core::result::Result; /// /// # Returns /// The total supply of the token, or an error if the operation fails. +#[inline] pub fn total_supply(id: AssetId) -> Result { assets::total_supply(id) } @@ -39,6 +45,7 @@ pub fn total_supply(id: AssetId) -> Result { /// /// # Returns /// The balance of the specified account, or an error if the operation fails. +#[inline] pub fn balance_of(id: AssetId, owner: AccountId) -> Result { assets::balance_of(id, owner) } @@ -53,6 +60,7 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Result { /// /// # Returns /// The remaining allowance, or an error if the operation fails. +#[inline] pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { assets::allowance(id, owner, spender) } @@ -67,6 +75,7 @@ pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result>, @@ -87,19 +96,15 @@ pub fn transfer( /// /// # Returns /// Returns `Ok(())` if successful, or an error if the transfer fails. +#[inline] pub fn transfer_from( id: AssetId, - from: Option>>, - to: Option>>, + from: impl Into>, + to: impl Into>, value: Balance, _data: &[u8], ) -> Result<()> { - match (from, to) { - (None, Some(to)) => assets::mint(id, to, value), - (Some(from), None) => assets::burn(id, from, value), - (Some(from), Some(to)) => assets::transfer_approved(id, from, to, value), - _ => Ok(()), - } + assets::transfer_approved(id, from, to, value) } /// Approves an account to spend a specified number of tokens on behalf of the caller. @@ -111,16 +116,10 @@ pub fn transfer_from( /// /// # Returns /// Returns `Ok(())` if successful, or an error if the approval fails. -// #[allow(unused_variables)] -// fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { -// todo!() -// // TODO: read allowance and increase or decrease. -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { -// // id: id.into(), -// // delegate: spender.into(), -// // amount: Compact(value), -// // }))?) -// } +#[inline] +pub fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + assets::approve_transfer(id, spender, value) +} /// Increases the allowance of a spender. /// @@ -131,13 +130,10 @@ pub fn transfer_from( /// /// # Returns /// Returns `Ok(())` if successful, or an error if the operation fails. -// fn increase_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { -// id: id.into(), -// delegate: spender.into(), -// amount: Compact(value), -// }))?) -// } +#[inline] +pub fn increase_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + assets::approve_transfer(id, spender, value) +} /// Decreases the allowance of a spender. /// @@ -148,20 +144,11 @@ pub fn transfer_from( /// /// # Returns /// Returns `Ok(())` if successful, or an error if the operation fails. -// #[allow(unused_variables)] -// fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { -// todo!() -// // TODO: cancel_approval + approve_transfer -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { -// // id: id.into(), -// // delegate: delegate.into(), -// // }))?) -// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { -// // id: id.into(), -// // delegate: spender.into(), -// // amount: Compact(value), -// // }))?) -// } +#[inline] +pub fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + assets::cancel_approval(id, spender.clone())?; + assets::approve_transfer(id, spender, value) +} /// 2. PSP-22 Metadata Interface: /// - token_name @@ -175,11 +162,10 @@ pub fn transfer_from( /// /// # Returns /// The name of the token as a byte vector, or an error if the operation fails. -// #[allow(unused_variables)] -// pub fn token_name(id: AssetId) -> Result>> { -// todo!() -// // Ok(state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id)))?) -// } +#[inline] +pub fn token_name(id: AssetId) -> Result> { + assets::token_name(id) +} /// Returns the token symbol for a given asset ID. /// @@ -188,10 +174,10 @@ pub fn transfer_from( /// /// # Returns /// The symbol of the token as a byte vector, or an error if the operation fails. -// #[allow(unused_variables)] -// fn token_symbol(id: AssetId) -> Result>> { -// todo!() -// } +#[inline] +pub fn token_symbol(id: AssetId) -> Result> { + assets::token_symbol(id) +} /// Returns the token decimals for a given asset ID. /// @@ -200,118 +186,114 @@ pub fn transfer_from( /// /// # Returns /// The number of decimals of the token as a byte vector, or an error if the operation fails. -// #[allow(unused_variables)] -// fn token_decimals(id: AssetId) -> Result>> { -// todo!() -// } - -/// 3. Asset Management: -/// - create -/// - start_destroy -/// - destroy_accounts -/// - destroy_approvals -/// - finish_destroy -/// - set_metadata -/// - clear_metadata - -/// Create a new token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// * `admin` - The account that will administer the asset. -/// * `min_balance` - The minimum balance required for accounts holding this asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the creation fails. -pub fn create( - id: AssetId, - admin: impl Into>, - min_balance: Balance, -) -> Result<()> { - assets::create(id, admin, min_balance) +#[inline] +pub fn token_decimals(id: AssetId) -> Result { + assets::token_decimals(id) } -/// Start the process of destroying a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn start_destroy(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { -// id: id.into(), -// }))?) +// /// 3. Asset Management: +// /// - create +// /// - start_destroy +// /// - destroy_accounts +// /// - destroy_approvals +// /// - finish_destroy +// /// - set_metadata +// /// - clear_metadata +// +// /// Create a new token with a given asset ID. +// /// +// /// # Arguments +// /// * `id` - The ID of the asset. +// /// * `admin` - The account that will administer the asset. +// /// * `min_balance` - The minimum balance required for accounts holding this asset. +// /// +// /// # Returns +// /// Returns `Ok(())` if successful, or an error if the creation fails. +// // pub fn create(id: AssetId, admin: impl Into>, min_balance: Balance) -> Result<()> { +// // assets::create(id, admin, min_balance) +// // } +// +// /// Start the process of destroying a token with a given asset ID. +// /// +// /// # Arguments +// /// * `id` - The ID of the asset. +// /// +// /// # Returns +// /// Returns `Ok(())` if successful, or an error if the operation fails. +// // fn start_destroy(id: AssetId) -> Result<()> { +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { +// // id: id.into(), +// // }))?) +// // } +// +// /// Destroy all accounts associated with a token with a given asset ID. +// /// +// /// # Arguments +// /// * `id` - The ID of the asset. +// /// +// /// # Returns +// /// Returns `Ok(())` if successful, or an error if the operation fails. +// // fn destroy_accounts(id: AssetId) -> Result<()> { +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { +// // id: id.into(), +// // }))?) +// // } +// +// /// Destroy all approvals associated with a token with a given asset ID. +// /// +// /// # Arguments +// /// * `id` - The ID of the asset. +// /// +// /// # Returns +// /// Returns `Ok(())` if successful, or an error if the operation fails. +// // fn destroy_approvals(id: AssetId) -> Result<()> { +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { +// // id: id.into(), +// // }))?) +// // } +// +// /// Complete the process of destroying a token with a given asset ID. +// /// +// /// # Arguments +// /// * `id` - The ID of the asset. +// /// +// /// # Returns +// /// Returns `Ok(())` if successful, or an error if the operation fails. +// // fn finish_destroy(id: AssetId) -> Result<()> { +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { +// // id: id.into(), +// // }))?) +// // } +// +// /// Set the metadata for a token with a given asset ID. +// /// +// /// # Arguments +// /// * `id` - The ID of the asset. +// /// +// /// # Returns +// /// Returns `Ok(())` if successful, or an error if the operation fails. +// // pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { +// // assets::set_metadata(id, name, symbol, decimals) +// // } +// +// /// Clear the metadata for a token with a given asset ID. +// /// +// /// # Arguments +// /// * `id` - The ID of the asset. +// /// +// /// # Returns +// /// Returns `Ok(())` if successful, or an error if the operation fails. +// // fn clear_metadata(id: AssetId) -> Result<()> { +// // Ok(dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { +// // id: id.into(), +// // }))?) +// // } +// +// pub fn asset_exists(id: AssetId) -> Result { +// assets::asset_exists(id) // } -/// Destroy all accounts associated with a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn destroy_accounts(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { -// id: id.into(), -// }))?) -// } - -/// Destroy all approvals associated with a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn destroy_approvals(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { -// id: id.into(), -// }))?) -// } - -/// Complete the process of destroying a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn finish_destroy(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { -// id: id.into(), -// }))?) -// } - -/// Set the metadata for a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -pub fn set_metadata(id: AssetId, name: Vec, symbol: Vec, decimals: u8) -> Result<()> { - assets::set_metadata(id, name, symbol, decimals) -} - -/// Clear the metadata for a token with a given asset ID. -/// -/// # Arguments -/// * `id` - The ID of the asset. -/// -/// # Returns -/// Returns `Ok(())` if successful, or an error if the operation fails. -// fn clear_metadata(id: AssetId) -> Result<()> { -// Ok(dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { -// id: id.into(), -// }))?) -// } - -pub fn asset_exists(id: AssetId) -> Result { - assets::asset_exists(id) -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] +#[derive(Encode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum FungiblesError { Other(StatusCode), @@ -359,11 +341,13 @@ impl From for FungiblesError { #[cfg(test)] mod tests { + use scale::Decode; + use super::FungiblesError; - use crate::error::{ + use crate::StatusCode; + use pop_primitives::{ ArithmeticError::*, Error::{self, *}, - StatusCode, TokenError::*, TransactionalError::*, }; @@ -373,6 +357,18 @@ mod tests { status_code.into() } + #[test] + fn status_code_vs_encoded() { + assert_eq!(u32::decode(&mut &[3u8, 10, 2, 0][..]).unwrap(), 133635u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 0, 0][..]).unwrap(), 13315u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 1, 0][..]).unwrap(), 78851u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 2, 0][..]).unwrap(), 144387u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 3, 0][..]).unwrap(), 209923u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 5, 0][..]).unwrap(), 340995u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 7, 0][..]).unwrap(), 472067u32); + assert_eq!(u32::decode(&mut &[3u8, 52, 10, 0][..]).unwrap(), 668675u32); + } + #[test] fn conversion_status_code_into_fungibles_error_works() { let errors = vec![ diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 778387cb..22e32d47 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,10 +1,9 @@ -#![allow(dead_code)] - -use crate::{Balance, MultiAddress, RuntimeCall, *}; use ink::prelude::vec::Vec; -use primitives::AssetId; use scale::{Compact, Encode}; +use crate::{state::read, Balance, RuntimeCall, *}; +use primitives::{AssetId, MultiAddress}; + pub mod fungibles; type Result = core::result::Result; @@ -44,65 +43,62 @@ type Result = core::result::Result; /// - block /// Issue a new class of fungible assets from a public origin. -pub(crate) fn create( - id: AssetId, - admin: impl Into>, - min_balance: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Create { - id: id.into(), - admin: admin.into(), - min_balance, - })) -} - -/// Start the process of destroying a fungible asset class. -pub(crate) fn start_destroy(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { id: id.into() })) -} - -/// Destroy all accounts associated with a given asset. -pub(crate) fn destroy_accounts(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { id: id.into() })) -} - -/// Destroy all approvals associated with a given asset up to the max (see runtime configuration Assets `RemoveItemsLimit`). -pub(crate) fn destroy_approvals(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { id: id.into() })) -} - -/// Complete destroying asset and unreserve currency. -pub(crate) fn finish_destroy(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { id: id.into() })) -} - -/// Mint assets of a particular class. -pub(crate) fn mint( - id: AssetId, - beneficiary: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Mint { - id: id.into(), - beneficiary: beneficiary.into(), - amount: Compact(amount), - })) -} - -/// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`. -pub(crate) fn burn( - id: AssetId, - who: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Burn { - id: id.into(), - who: who.into(), - amount: Compact(amount), - })) -} - -/// Move some assets from the sender account to another. +// pub(crate) fn create( +// id: AssetId, +// admin: impl Into>, +// min_balance: Balance, +// ) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Create { +// id: id.into(), +// admin: admin.into(), +// min_balance, +// })) +// } +// +// /// Start the process of destroying a fungible asset class. +// pub(crate) fn start_destroy(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::StartDestroy { id: id.into() })) +// } +// +// /// Destroy all accounts associated with a given asset. +// pub(crate) fn destroy_accounts(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::DestroyAccounts { id: id.into() })) +// } +// +// /// Destroy all approvals associated with a given asset up to the max (see runtime configuration Assets `RemoveItemsLimit`). +// pub(crate) fn destroy_approvals(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::DestroyApprovals { id: id.into() })) +// } +// +// /// Complete destroying asset and unreserve currency. +// pub(crate) fn finish_destroy(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::FinishDestroy { id: id.into() })) +// } + +// /// Mint assets of a particular class. +// pub(crate) fn mint( +// id: AssetId, +// beneficiary: impl Into>, +// amount: Balance, +// ) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Mint { +// id: id.into(), +// beneficiary: beneficiary.into(), +// amount: Compact(amount), +// })) +// } +// +// /// Reduce the balance of `who` by as much as possible up to `amount` assets of `id`. +// pub(crate) fn burn(id: AssetId, who: impl Into>, amount: Balance) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Burn { +// id: id.into(), +// who: who.into(), +// amount: Compact(amount), +// })) +// } + +// /// Move some assets from the sender account to another. +#[inline] pub(crate) fn transfer( id: AssetId, target: impl Into>, @@ -115,98 +111,96 @@ pub(crate) fn transfer( })) } -/// Move some assets from the sender account to another, keeping the sender account alive. -pub(crate) fn transfer_keep_alive( - id: AssetId, - target: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { - id: id.into(), - target: target.into(), - amount: Compact(amount), - })) -} - -/// Move some assets from one account to another. Sender should be the Admin of the asset `id`. -pub(crate) fn force_transfer( - id: AssetId, - source: impl Into>, - dest: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ForceTransfer { - id: id.into(), - source: source.into(), - dest: dest.into(), - amount: Compact(amount), - })) -} - -/// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` -/// must already exist as an entry in `Account`s of the asset. If you want to freeze an -/// account that does not have an entry, use `touch_other` first. -pub(crate) fn freeze(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Freeze { id: id.into(), who: who.into() })) -} - -/// Allow unprivileged transfers to and from an account again. -pub(crate) fn thaw(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Thaw { id: id.into(), who: who.into() })) -} - -/// Disallow further unprivileged transfers for the asset class. -pub(crate) fn freeze_asset(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::FreezeAsset { id: id.into() })) -} - -/// Allow unprivileged transfers for the asset again. -pub(crate) fn thaw_asset(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ThawAsset { id: id.into() })) -} - -/// Change the Owner of an asset. -pub(crate) fn transfer_ownership( - id: AssetId, - owner: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferOwnership { - id: id.into(), - owner: owner.into(), - })) -} - -/// Change the Issuer, Admin and Freezer of an asset. -pub(crate) fn set_team( - id: AssetId, - issuer: impl Into>, - admin: impl Into>, - freezer: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::SetTeam { - id: id.into(), - issuer: issuer.into(), - admin: admin.into(), - freezer: freezer.into(), - })) -} +// /// Move some assets from the sender account to another, keeping the sender account alive. +// pub(crate) fn transfer_keep_alive( +// id: AssetId, +// target: impl Into>, +// amount: Balance, +// ) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { +// id: id.into(), +// target: target.into(), +// amount: Compact(amount), +// })) +// } +// +// /// Move some assets from one account to another. Sender should be the Admin of the asset `id`. +// pub(crate) fn force_transfer( +// id: AssetId, +// source: impl Into>, +// dest: impl Into>, +// amount: Balance, +// ) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::ForceTransfer { +// id: id.into(), +// source: source.into(), +// dest: dest.into(), +// amount: Compact(amount), +// })) +// } +// +// /// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` +// /// must already exist as an entry in `Account`s of the asset. If you want to freeze an +// /// account that does not have an entry, use `touch_other` first. +// pub(crate) fn freeze(id: AssetId, who: impl Into>) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Freeze { id: id.into(), who: who.into() })) +// } +// +// /// Allow unprivileged transfers to and from an account again. +// pub(crate) fn thaw(id: AssetId, who: impl Into>) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Thaw { id: id.into(), who: who.into() })) +// } +// +// /// Disallow further unprivileged transfers for the asset class. +// pub(crate) fn freeze_asset(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::FreezeAsset { id: id.into() })) +// } +// +// /// Allow unprivileged transfers for the asset again. +// pub(crate) fn thaw_asset(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::ThawAsset { id: id.into() })) +// } +// +// /// Change the Owner of an asset. +// pub(crate) fn transfer_ownership(id: AssetId, owner: impl Into>) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::TransferOwnership { +// id: id.into(), +// owner: owner.into(), +// })) +// } +// +// /// Change the Issuer, Admin and Freezer of an asset. +// pub(crate) fn set_team( +// id: AssetId, +// issuer: impl Into>, +// admin: impl Into>, +// freezer: impl Into>, +// ) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::SetTeam { +// id: id.into(), +// issuer: issuer.into(), +// admin: admin.into(), +// freezer: freezer.into(), +// })) +// } /// Set the metadata for an asset. -pub(crate) fn set_metadata( - id: AssetId, - name: Vec, - symbol: Vec, - decimals: u8, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::SetMetadata { id: id.into(), name, symbol, decimals })) -} - -/// Clear the metadata for an asset. -pub(crate) fn clear_metadata(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { id: id.into() })) -} - -/// Approve an amount of asset for transfer by a delegated third-party account. +// pub(crate) fn set_metadata( +// id: AssetId, +// name: Vec, +// symbol: Vec, +// decimals: u8, +// ) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::SetMetadata { id: id.into(), name, symbol, decimals })) +// } + +// /// Clear the metadata for an asset. +// pub(crate) fn clear_metadata(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { id: id.into() })) +// } + +// /// Approve an amount of asset for transfer by a delegated third-party account. +#[inline] pub(crate) fn approve_transfer( id: AssetId, delegate: impl Into>, @@ -220,6 +214,7 @@ pub(crate) fn approve_transfer( } /// Cancel all of some asset approved for delegated transfer by a third-party account. +#[inline] pub(crate) fn cancel_approval( id: AssetId, delegate: impl Into>, @@ -230,21 +225,22 @@ pub(crate) fn cancel_approval( })) } -/// Cancel all of some asset approved for delegated transfer by a third-party account. -pub(crate) fn force_cancel_approval( - id: AssetId, - owner: impl Into>, - delegate: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ForceCancelApproval { - id: id.into(), - owner: owner.into(), - delegate: delegate.into(), - })) -} +// /// Cancel all of some asset approved for delegated transfer by a third-party account. +// pub(crate) fn force_cancel_approval( +// id: AssetId, +// owner: impl Into>, +// delegate: impl Into>, +// ) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::ForceCancelApproval { +// id: id.into(), +// owner: owner.into(), +// delegate: delegate.into(), +// })) +// } /// Transfer some asset balance from a previously delegated account to some third-party /// account. +#[inline] pub(crate) fn transfer_approved( id: AssetId, owner: impl Into>, @@ -258,58 +254,81 @@ pub(crate) fn transfer_approved( amount: Compact(amount), })) } - -/// Create an asset account for non-provider assets. -pub(crate) fn touch(id: AssetId) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Touch { id: id.into() })) -} - -/// Return the deposit (if any) of an asset account or a consumer reference (if any) of an -/// account. -pub(crate) fn refund(id: AssetId, allow_burn: bool) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Refund { id: id.into(), allow_burn })) -} - -/// Sets the minimum balance of an asset. -pub(crate) fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::SetMinBalance { - id: id.into(), - min_balance: Compact(min_balance), - })) -} - -/// Create an asset account for `who`. -pub(crate) fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TouchOther { id: id.into(), who: who.into() })) -} - -/// Return the deposit (if any) of a target asset account. Useful if you are the depositor. -pub(crate) fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::RefundOther { id: id.into(), who: who.into() })) -} - -/// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. -pub(crate) fn block(id: AssetId, who: impl Into>) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::Block { id: id.into(), who: who.into() })) -} +// +// /// Create an asset account for non-provider assets. +// pub(crate) fn touch(id: AssetId) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Touch { id: id.into() })) +// } +// +// /// Return the deposit (if any) of an asset account or a consumer reference (if any) of an +// /// account. +// pub(crate) fn refund(id: AssetId, allow_burn: bool) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Refund { id: id.into(), allow_burn })) +// } +// +// /// Sets the minimum balance of an asset. +// pub(crate) fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::SetMinBalance { +// id: id.into(), +// min_balance: Compact(min_balance), +// })) +// } +// +// /// Create an asset account for `who`. +// pub(crate) fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::TouchOther { id: id.into(), who: who.into() })) +// } +// +// /// Return the deposit (if any) of a target asset account. Useful if you are the depositor. +// pub(crate) fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::RefundOther { id: id.into(), who: who.into() })) +// } +// +// /// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. +// pub(crate) fn block(id: AssetId, who: impl Into>) -> Result<()> { +// dispatch(RuntimeCall::Assets(AssetsCall::Block { id: id.into(), who: who.into() })) +// } /// 2. Read state functions /// - total_supply -/// - - +/// - balance_of +/// - allowance +/// - asset_exists +/// - token_name +/// - token_symbol +/// - token_decimals +// +#[inline] pub(crate) fn total_supply(id: AssetId) -> Result { state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))) } +#[inline] pub(crate) fn balance_of(id: AssetId, owner: AccountId) -> Result { state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))) } +#[inline] pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))) } -pub(crate) fn asset_exists(id: AssetId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))) +// pub(crate) fn asset_exists(id: AssetId) -> Result { +// state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))) +// } + +#[inline] +pub(crate) fn token_name(id: AssetId) -> Result> { + state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id))) +} +// +#[inline] +pub(crate) fn token_symbol(id: AssetId) -> Result> { + state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenSymbol(id))) +} + +#[inline] +pub(crate) fn token_decimals(id: AssetId) -> Result { + state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenDecimals(id))) } // Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected @@ -321,63 +340,63 @@ pub(crate) fn asset_exists(id: AssetId) -> Result { type AssetIdParameter = Compact; // Balance amount that is compact encoded. type BalanceParameter = Compact; - +// #[derive(Encode)] pub(crate) enum AssetsCall { - #[codec(index = 0)] - Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, - #[codec(index = 2)] - StartDestroy { id: AssetIdParameter }, - #[codec(index = 3)] - DestroyAccounts { id: AssetIdParameter }, - #[codec(index = 4)] - DestroyApprovals { id: AssetIdParameter }, - #[codec(index = 5)] - FinishDestroy { id: AssetIdParameter }, - #[codec(index = 6)] - Mint { - id: AssetIdParameter, - beneficiary: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 7)] - Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, - #[codec(index = 8)] - Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, + // #[codec(index = 0)] + // Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, + // #[codec(index = 2)] + // StartDestroy { id: AssetIdParameter }, + // #[codec(index = 3)] + // DestroyAccounts { id: AssetIdParameter }, + // #[codec(index = 4)] + // DestroyApprovals { id: AssetIdParameter }, + // #[codec(index = 5)] + // FinishDestroy { id: AssetIdParameter }, + // #[codec(index = 6)] + // Mint { + // id: AssetIdParameter, + // beneficiary: MultiAddress, + // amount: BalanceParameter, + // }, + // #[codec(index = 7)] + // Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, + // #[codec(index = 8)] + // Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, #[codec(index = 9)] TransferKeepAlive { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter, }, - #[codec(index = 10)] - ForceTransfer { - id: AssetIdParameter, - source: MultiAddress, - dest: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 11)] - Freeze { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 12)] - Thaw { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 13)] - FreezeAsset { id: AssetIdParameter }, - #[codec(index = 14)] - ThawAsset { id: AssetIdParameter }, - #[codec(index = 15)] - TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, - #[codec(index = 16)] - SetTeam { - id: AssetIdParameter, - issuer: MultiAddress, - admin: MultiAddress, - freezer: MultiAddress, - }, - #[codec(index = 17)] - SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, - #[codec(index = 18)] - ClearMetadata { id: AssetIdParameter }, + // #[codec(index = 10)] + // ForceTransfer { + // id: AssetIdParameter, + // source: MultiAddress, + // dest: MultiAddress, + // amount: BalanceParameter, + // }, + // #[codec(index = 11)] + // Freeze { id: AssetIdParameter, who: MultiAddress }, + // #[codec(index = 12)] + // Thaw { id: AssetIdParameter, who: MultiAddress }, + // #[codec(index = 13)] + // FreezeAsset { id: AssetIdParameter }, + // #[codec(index = 14)] + // ThawAsset { id: AssetIdParameter }, + // #[codec(index = 15)] + // TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, + // #[codec(index = 16)] + // SetTeam { + // id: AssetIdParameter, + // issuer: MultiAddress, + // admin: MultiAddress, + // freezer: MultiAddress, + // }, + // #[codec(index = 17)] + // SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, + // #[codec(index = 18)] + // ClearMetadata { id: AssetIdParameter }, #[codec(index = 22)] ApproveTransfer { id: AssetIdParameter, @@ -386,12 +405,12 @@ pub(crate) enum AssetsCall { }, #[codec(index = 23)] CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, - #[codec(index = 24)] - ForceCancelApproval { - id: AssetIdParameter, - owner: MultiAddress, - delegate: MultiAddress, - }, + // #[codec(index = 24)] + // ForceCancelApproval { + // id: AssetIdParameter, + // owner: MultiAddress, + // delegate: MultiAddress, + // }, #[codec(index = 25)] TransferApproved { id: AssetIdParameter, @@ -399,96 +418,97 @@ pub(crate) enum AssetsCall { destination: MultiAddress, amount: BalanceParameter, }, - #[codec(index = 26)] - Touch { id: AssetIdParameter }, - #[codec(index = 27)] - Refund { id: AssetIdParameter, allow_burn: bool }, - #[codec(index = 28)] - SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, - #[codec(index = 29)] - TouchOther { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 30)] - RefundOther { id: AssetIdParameter, who: MultiAddress }, - #[codec(index = 31)] - Block { id: AssetIdParameter, who: MultiAddress }, -} - -// TODO: Not being used atm but necessary if we want to provide access to the -// rest of the pallet, outside of the use cases. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum AssetsError { - /// Account balance must be greater than or equal to the transfer amount. - BalanceLow, - /// The account to alter does not exist. - NoAccount, - /// The signing account has no permission to do the operation. - NoPermission, - /// The given asset ID is unknown. - Unknown, - /// The origin account is frozen. - Frozen, - /// The asset ID is already taken. - InUse, - /// Invalid witness data given. - BadWitness, - /// Minimum balance should be non-zero. - MinBalanceZero, - /// Unable to increment the consumer reference counters on the account. Either no provider - /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one - /// fewer then the maximum number of consumers has been reached. - UnavailableConsumer, - /// Invalid metadata given. - BadMetadata, - /// No approval exists that would allow the transfer. - Unapproved, - /// The source account would not survive the transfer and it needs to stay alive. - WouldDie, - /// The asset-account already exists. - AlreadyExists, - /// The asset-account doesn't have an associated deposit. - NoDeposit, - /// The operation would result in funds being burned. - WouldBurn, - /// The asset is a live asset and is actively being used. Usually emit for operations such - /// as `start_destroy` which require the asset to be in a destroying state. - LiveAsset, - /// The asset is not live, and likely being destroyed. - AssetNotLive, - /// The asset status is not the expected status. - IncorrectStatus, - /// The asset should be frozen before the given operation. - NotFrozen, - /// Callback action resulted in error. - CallbackFailed, + // // #[codec(index = 26)] + // // Touch { id: AssetIdParameter }, + // // #[codec(index = 27)] + // // Refund { id: AssetIdParameter, allow_burn: bool }, + // // #[codec(index = 28)] + // // SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, + // // #[codec(index = 29)] + // // TouchOther { id: AssetIdParameter, who: MultiAddress }, + // // #[codec(index = 30)] + // // RefundOther { id: AssetIdParameter, who: MultiAddress }, + // // #[codec(index = 31)] + // // Block { id: AssetIdParameter, who: MultiAddress }, + // } + + // // TODO: Not being used atm but necessary if we want to provide access to the + // // rest of the pallet, outside of the use cases. + // #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] + // #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] + // pub enum AssetsError { + // /// Account balance must be greater than or equal to the transfer amount. + // BalanceLow, + // /// The account to alter does not exist. + // NoAccount, + // /// The signing account has no permission to do the operation. + // NoPermission, + // /// The given asset ID is unknown. + // Unknown, + // /// The origin account is frozen. + // Frozen, + // /// The asset ID is already taken. + // InUse, + // /// Invalid witness data given. + // BadWitness, + // /// Minimum balance should be non-zero. + // MinBalanceZero, + // /// Unable to increment the consumer reference counters on the account. Either no provider + // /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one + // /// fewer then the maximum number of consumers has been reached. + // UnavailableConsumer, + // /// Invalid metadata given. + // BadMetadata, + // /// No approval exists that would allow the transfer. + // Unapproved, + // /// The source account would not survive the transfer and it needs to stay alive. + // WouldDie, + // /// The asset-account already exists. + // AlreadyExists, + // /// The asset-account doesn't have an associated deposit. + // NoDeposit, + // /// The operation would result in funds being burned. + // WouldBurn, + // /// The asset is a live asset and is actively being used. Usually emit for operations such + // /// as `start_destroy` which require the asset to be in a destroying state. + // LiveAsset, + // /// The asset is not live, and likely being destroyed. + // AssetNotLive, + // /// The asset status is not the expected status. + // IncorrectStatus, + // /// The asset should be frozen before the given operation. + // NotFrozen, + // /// Callback action resulted in error. + // CallbackFailed, } -impl TryFrom for AssetsError { - type Error = Error; - - fn try_from(status_code: u32) -> core::result::Result { - use AssetsError::*; - match status_code { - 0 => Ok(BalanceLow), - 1 => Ok(NoAccount), - 2 => Ok(NoPermission), - 3 => Ok(Unknown), - 4 => Ok(Frozen), - 5 => Ok(InUse), - 6 => Ok(BadWitness), - 7 => Ok(MinBalanceZero), - 8 => Ok(UnavailableConsumer), - 9 => Ok(BadMetadata), - 10 => Ok(Unapproved), - 11 => Ok(WouldDie), - 12 => Ok(AlreadyExists), - 13 => Ok(NoDeposit), - 14 => Ok(WouldBurn), - 15 => Ok(LiveAsset), - 16 => Ok(AssetNotLive), - 17 => Ok(IncorrectStatus), - 18 => Ok(NotFrozen), - _ => todo!(), - } - } -} +// +// impl TryFrom for AssetsError { +// type Error = Error; +// +// fn try_from(status_code: u32) -> core::result::Result { +// use AssetsError::*; +// match status_code { +// 0 => Ok(BalanceLow), +// 1 => Ok(NoAccount), +// 2 => Ok(NoPermission), +// 3 => Ok(Unknown), +// 4 => Ok(Frozen), +// 5 => Ok(InUse), +// 6 => Ok(BadWitness), +// 7 => Ok(MinBalanceZero), +// 8 => Ok(UnavailableConsumer), +// 9 => Ok(BadMetadata), +// 10 => Ok(Unapproved), +// 11 => Ok(WouldDie), +// 12 => Ok(AlreadyExists), +// 13 => Ok(NoDeposit), +// 14 => Ok(WouldBurn), +// 15 => Ok(LiveAsset), +// 16 => Ok(AssetNotLive), +// 17 => Ok(IncorrectStatus), +// 18 => Ok(NotFrozen), +// _ => todo!(), +// } +// } +// } diff --git a/pop-api/src/v0/state.rs b/pop-api/src/v0/state.rs index e3d38129..914a9603 100644 --- a/pop-api/src/v0/state.rs +++ b/pop-api/src/v0/state.rs @@ -1,6 +1,7 @@ -use crate::{primitives::storage_keys::RuntimeStateKeys, read_state, Error}; +use crate::{error::StatusCode, primitives::storage_keys::RuntimeStateKeys, read_state}; use scale::Decode; +#[inline] pub fn read(key: RuntimeStateKeys) -> crate::Result { - read_state(key).and_then(|v| T::decode(&mut &v[..]).map_err(|_e| Error::DecodingFailed.into())) + read_state(key).and_then(|v| T::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) } diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 3b91f713..dc0a5245 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -9,7 +9,7 @@ use {scale_decode::DecodeAsType, scale_encode::EncodeAsType, scale_info::TypeInf pub mod cross_chain; pub mod storage_keys; -#[derive(Encode, Decode, Debug, MaxEncodedLen, Eq, PartialEq, Ord, PartialOrd)] +#[derive(Encode, Decode, Clone, Debug, MaxEncodedLen, Eq, PartialEq, Ord, PartialOrd)] #[cfg_attr(feature = "std", derive(TypeInfo, DecodeAsType, EncodeAsType))] pub struct AccountId(pub [u8; 32]); diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index 748d0662..7992089b 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -47,10 +47,13 @@ pub enum NftsKeys { #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum AssetsKeys { Allowance(AssetId, AccountId, AccountId), - /// Check if the asset exists. - AssetExists(AssetId), + // /// Check if the asset exists. + // // AssetExists(AssetId), /// Check balance. BalanceOf(AssetId, AccountId), /// Returns the total token supply for a given asset ID. TotalSupply(AssetId), + TokenDecimals(AssetId), + TokenSymbol(AssetId), + TokenName(AssetId), } From 7757319213cab9de78b0a3f26eda15cf513af454 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Wed, 3 Jul 2024 08:18:27 +0200 Subject: [PATCH 15/27] refactor: runtime --- pop-api/Cargo.toml | 6 +- pop-api/examples/fungibles/Cargo.toml | 4 - pop-api/examples/fungibles/lib.rs | 4 +- pop-api/src/error.rs | 38 ++-- pop-api/src/lib.rs | 4 +- pop-api/src/v0/assets/fungibles.rs | 10 +- pop-api/src/v0/assets/mod.rs | 22 +- pop-api/src/v0/mod.rs | 3 +- pop-api/src/v0/state.rs | 2 +- runtime/devnet/src/extensions.rs | 295 +++++++++++--------------- 10 files changed, 168 insertions(+), 220 deletions(-) diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index a88d8892..82ee7613 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -8,8 +8,6 @@ edition = "2021" [dependencies] enumflags2 = { version = "0.7.7" } ink = { version = "5.0.0", default-features = false } -scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } -scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } sp-io = { version = "31.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } sp-runtime = { version = "32.0.0", default-features = false } @@ -26,9 +24,7 @@ std = [ "enumflags2/std", "ink/std", "pop-primitives/std", - "scale/std", - "scale-info/std", -"sp-io/std", + "sp-io/std", "sp-runtime/std", ] assets = ["pop-primitives/assets"] diff --git a/pop-api/examples/fungibles/Cargo.toml b/pop-api/examples/fungibles/Cargo.toml index 514f000f..565b0554 100755 --- a/pop-api/examples/fungibles/Cargo.toml +++ b/pop-api/examples/fungibles/Cargo.toml @@ -7,8 +7,6 @@ edition = "2021" [dependencies] ink = { version = "5.0.0", default-features = false } pop-api = { path = "../../../pop-api", default-features = false, features = ["assets"] } -scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } -scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true } [lib] path = "lib.rs" @@ -18,8 +16,6 @@ default = ["std"] std = [ "ink/std", "pop-api/std", - "scale/std", - "scale-info/std", ] ink-as-dependency = [] e2e-tests = [] diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index bd51d760..1794fbe5 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -85,7 +85,7 @@ mod fungibles { to: AccountId32, value: Balance, // In the standard a `[u8]`, but the size needs to be known at compile time. - data: Vec, + _data: Vec, ) -> Result<()> { ink::env::debug_println!( "PopApiFungiblesExample::transfer_from: id: {:?}, from: {:?}, to: {:?} value: {:?}", @@ -95,7 +95,7 @@ mod fungibles { value, ); - let result = api::transfer_from(id, from, to, value, &data); + let result = api::transfer_from(id, from, to, value); ink::env::debug_println!("Result: {:?}", result); // result.map_err(|e| e.into()) result diff --git a/pop-api/src/error.rs b/pop-api/src/error.rs index 54681e6d..8989464f 100644 --- a/pop-api/src/error.rs +++ b/pop-api/src/error.rs @@ -1,10 +1,7 @@ -use ink::env::chain_extension::FromStatusCode; -use scale::{Decode, Encode}; +use ink::{env::chain_extension::FromStatusCode, scale::Decode}; -use Error::*; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub struct StatusCode(pub u32); impl From for StatusCode { @@ -14,21 +11,21 @@ impl From for StatusCode { } impl FromStatusCode for StatusCode { fn from_status_code(status_code: u32) -> Result<(), Self> { - if status_code == 0 { - return Ok(()); + match status_code { + 0 => Ok(()), + _ => Err(StatusCode(status_code)), } - Err(StatusCode(status_code)) } } -impl From for StatusCode { - fn from(_: scale::Error) -> Self { +impl From for StatusCode { + fn from(_: ink::scale::Error) -> Self { StatusCode(255u32) } } -#[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] #[repr(u8)] pub enum Error { /// Some unknown error occurred. Go to the Pop API docs section `Pop API error`. @@ -70,6 +67,7 @@ pub enum Error { Unavailable = 12, /// Root origin is not allowed. RootNotAllowed = 13, + UnknownFunctionId = 254, DecodingFailed = 255, } @@ -92,15 +90,15 @@ impl From for Error { Err(_) => { encoded[..].rotate_right(1); encoded[0] = 0u8; - Error::decode(&mut &encoded[..]).unwrap_or(DecodingFailed) + Error::decode(&mut &encoded[..]).unwrap_or(Error::DecodingFailed) }, Ok(error) => error, } } } -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum TokenError { /// Funds are unavailable. FundsUnavailable, @@ -125,8 +123,8 @@ pub enum TokenError { Blocked, } -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum ArithmeticError { /// Underflow. Underflow, @@ -136,8 +134,8 @@ pub enum ArithmeticError { DivisionByZero, } -#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum TransactionalError { /// Too many transactional layers have been spawned. LimitReached, diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 53bbadc6..55307f3e 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -27,8 +27,8 @@ type BlockNumber = ::BlockNumber; pub type Result = core::result::Result; -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[derive(Debug, PartialEq, Eq, Clone)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum Environment {} impl ink::env::Environment for Environment { diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index e7c3f41c..376ca898 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -1,5 +1,4 @@ use ink::prelude::vec::Vec; -use scale::Encode; use crate::{ assets, @@ -102,7 +101,6 @@ pub fn transfer_from( from: impl Into>, to: impl Into>, value: Balance, - _data: &[u8], ) -> Result<()> { assets::transfer_approved(id, from, to, value) } @@ -293,8 +291,8 @@ pub fn token_decimals(id: AssetId) -> Result { // assets::asset_exists(id) // } -#[derive(Encode)] -#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum FungiblesError { Other(StatusCode), /// The asset is not live; either frozen or being destroyed. @@ -344,13 +342,13 @@ mod tests { use scale::Decode; use super::FungiblesError; - use crate::StatusCode; - use pop_primitives::{ + use crate::error::{ ArithmeticError::*, Error::{self, *}, TokenError::*, TransactionalError::*, }; + use crate::StatusCode; fn into_fungibles_error(error: Error) -> FungiblesError { let status_code: StatusCode = error.into(); diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 22e32d47..241c5020 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,5 +1,4 @@ -use ink::prelude::vec::Vec; -use scale::{Compact, Encode}; +use ink::{prelude::vec::Vec, scale::Compact}; use crate::{state::read, Balance, RuntimeCall, *}; use primitives::{AssetId, MultiAddress}; @@ -97,7 +96,7 @@ type Result = core::result::Result; // })) // } -// /// Move some assets from the sender account to another. +/// Move some assets from the sender account to another. #[inline] pub(crate) fn transfer( id: AssetId, @@ -199,7 +198,7 @@ pub(crate) fn transfer( // dispatch(RuntimeCall::Assets(AssetsCall::ClearMetadata { id: id.into() })) // } -// /// Approve an amount of asset for transfer by a delegated third-party account. +/// Approve an amount of asset for transfer by a delegated third-party account. #[inline] pub(crate) fn approve_transfer( id: AssetId, @@ -300,17 +299,17 @@ pub(crate) fn transfer_approved( // #[inline] pub(crate) fn total_supply(id: AssetId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))) + read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))) } #[inline] pub(crate) fn balance_of(id: AssetId, owner: AccountId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))) + read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))) } #[inline] pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))) + read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))) } // pub(crate) fn asset_exists(id: AssetId) -> Result { // state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))) @@ -318,17 +317,17 @@ pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Re #[inline] pub(crate) fn token_name(id: AssetId) -> Result> { - state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id))) + read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id))) } // #[inline] pub(crate) fn token_symbol(id: AssetId) -> Result> { - state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenSymbol(id))) + read(RuntimeStateKeys::Assets(AssetsKeys::TokenSymbol(id))) } #[inline] pub(crate) fn token_decimals(id: AssetId) -> Result { - state::read(RuntimeStateKeys::Assets(AssetsKeys::TokenDecimals(id))) + read(RuntimeStateKeys::Assets(AssetsKeys::TokenDecimals(id))) } // Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected @@ -341,7 +340,8 @@ type AssetIdParameter = Compact; // Balance amount that is compact encoded. type BalanceParameter = Compact; // -#[derive(Encode)] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub(crate) enum AssetsCall { // #[codec(index = 0)] // Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 20dc6476..f91c4271 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -8,7 +8,8 @@ pub mod cross_chain; pub mod nfts; pub mod state; -#[derive(scale::Encode)] +#[derive(Debug, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] pub(crate) enum RuntimeCall { #[codec(index = 10)] #[cfg(feature = "balances")] diff --git a/pop-api/src/v0/state.rs b/pop-api/src/v0/state.rs index 914a9603..afe48ba8 100644 --- a/pop-api/src/v0/state.rs +++ b/pop-api/src/v0/state.rs @@ -1,5 +1,5 @@ use crate::{error::StatusCode, primitives::storage_keys::RuntimeStateKeys, read_state}; -use scale::Decode; +use ink::scale::Decode; #[inline] pub fn read(key: RuntimeStateKeys) -> crate::Result { diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions.rs index 904d18ce..6f98bf96 100644 --- a/runtime/devnet/src/extensions.rs +++ b/runtime/devnet/src/extensions.rs @@ -57,24 +57,132 @@ where E: Ext, { log::debug!(target:LOG_TARGET, " extension called "); - match v0::FuncId::try_from(env.func_id())? { - v0::FuncId::Dispatch => match dispatch::(env) { - Ok(()) => Ok(RetVal::Converging(0)), - Err(e) => Ok(RetVal::Converging(convert_to_status_code(e))), - }, - v0::FuncId::ReadState => { - read_state::(env)?; - Ok(RetVal::Converging(0)) - }, - v0::FuncId::SendXcm => { - send_xcm::(env)?; - Ok(RetVal::Converging(0)) + let mut env = env.buf_in_buf_out(); + let contract_host_weight = ContractSchedule::::get().host_fn_weights; + // debug_message weight is a good approximation of the additional overhead of going + // from contract layer to substrate layer. + // reference: https://github.com/paritytech/ink-examples/blob/b8d2caa52cf4691e0ddd7c919e4462311deb5ad0/psp22-extension/runtime/psp22-extension-example.rs#L236 + env.charge_weight(contract_host_weight.debug_message)?; + + let result = match v0::FuncId::try_from(env.func_id()) { + Ok(function) => { + // calculate weight for reading bytes of `len` + // reference: https://github.com/paritytech/polkadot-sdk/blob/117a9433dac88d5ac00c058c9b39c511d47749d2/substrate/frame/contracts/src/wasm/runtime.rs#L267 + let len = env.in_len(); + env.charge_weight(contract_host_weight.return_per_byte.saturating_mul(len.into()))?; + match function { + v0::FuncId::Dispatch => dispatch::(&mut env, len), + v0::FuncId::ReadState => read_state::(&mut env), + v0::FuncId::SendXcm => send_xcm::(&mut env), + } }, + Err(e) => Err(e), + }; + + // Convert any error to a status code and return Ok with RetVal::Converging + match result { + Ok(_) => Ok(RetVal::Converging(0)), + Err(e) => Ok(RetVal::Converging(convert_to_status_code(e))), } } } + +fn dispatch(env: &mut Environment, len: u32) -> Result<(), DispatchError> +where + T: pallet_contracts::Config + + frame_system::Config, + RuntimeOrigin: From>, + E: Ext, +{ + const LOG_PREFIX: &str = " dispatch |"; + + // read the input as RuntimeCall + let call: RuntimeCall = env.read_as_unbounded(len)?; + log::debug!(target: LOG_TARGET, "Read input as call successfully"); + // contract is the origin by default + let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into(); + dispatch_call::(env, call, origin, LOG_PREFIX) +} + +fn read_state(env: &mut Environment) -> Result<(), DispatchError> +where + T: pallet_contracts::Config + + pallet_assets::Config + + pallet_nfts::Config + + cumulus_pallet_parachain_system::Config + + frame_system::Config, + E: Ext, +{ + const LOG_PREFIX: &str = " read_state |"; + + let key: RuntimeStateKeys = env.read_as()?; + let result = match key { + RuntimeStateKeys::Nfts(key) => read_nfts_state::(key, env), + RuntimeStateKeys::ParachainSystem(key) => read_parachain_system_state::(key, env), + RuntimeStateKeys::Assets(key) => read_assets_state::(key, env), + }? + .encode(); + + log::trace!( + target:LOG_TARGET, + "{} result: {:?}.", LOG_PREFIX, result + ); + env.write(&result, false, None) +} + +fn send_xcm(env: &mut Environment) -> Result<(), DispatchError> +where + T: pallet_contracts::Config + + frame_system::Config< + RuntimeOrigin = RuntimeOrigin, + AccountId = AccountId, + RuntimeCall = RuntimeCall, + >, + E: Ext, +{ + const LOG_PREFIX: &str = " send_xcm |"; + + // read the input as CrossChainMessage + let xc_call: CrossChainMessage = env.read_as::()?; + // Determine the call to dispatch + let (dest, message) = match xc_call { + CrossChainMessage::Relay(message) => { + let dest = Location::parent().into_versioned(); + let assets: Asset = (Here, 10 * UNIT).into(); + let beneficiary: Location = + AccountId32 { id: (env.ext().address().clone()).into(), network: None }.into(); + let message = Xcm::builder() + .withdraw_asset(assets.clone().into()) + .buy_execution(assets.clone(), Unlimited) + .transact( + SovereignAccount, + Weight::from_parts(250_000_000, 10_000), + message.encode().into(), + ) + .refund_surplus() + .deposit_asset(assets.into(), beneficiary) + .build(); + (dest, message) + }, + }; + + // TODO: revisit to replace with signed contract origin + let origin: RuntimeOrigin = RawOrigin::Root.into(); + + // Generate runtime call to dispatch + let call = RuntimeCall::PolkadotXcm(pallet_xcm::Call::send { + dest: Box::new(dest), + message: Box::new(VersionedXcm::V4(message)), + }); + + dispatch_call::(env, call, origin, LOG_PREFIX) +} + pub(crate) fn convert_to_status_code(error: DispatchError) -> u32 { - let mut encoded_error = error.encode(); + let mut encoded_error = match error { + DispatchError::Other("UnknownFunctionId") => vec![254, 0, 0, 0], + _ => error.encode(), + }; // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). encoded_error.resize(4, 0); u32::decode(&mut &encoded_error[..]).expect("qid, resized to 4 bytes line above") @@ -99,8 +207,7 @@ impl TryFrom for v0::FuncId { 0x2 => Self::SendXcm, _ => { log::error!("called an unregistered `func_id`: {:}", func_id); - // TODO: Other error. - return Err(DispatchError::Other("unimplemented func_id")); + return Err(DispatchError::Other("UnknownFuncId")); }, }; @@ -143,101 +250,6 @@ where } } -fn charge_overhead_weight( - env: &mut Environment, - len: u32, - log_prefix: &str, -) -> Result -where - T: pallet_contracts::Config, - E: Ext, -{ - let contract_host_weight = ContractSchedule::::get().host_fn_weights; - - // calculate weight for reading bytes of `len` - // reference: https://github.com/paritytech/polkadot-sdk/blob/117a9433dac88d5ac00c058c9b39c511d47749d2/substrate/frame/contracts/src/wasm/runtime.rs#L267 - let base_weight: Weight = contract_host_weight.return_per_byte.saturating_mul(len.into()); - - // debug_message weight is a good approximation of the additional overhead of going - // from contract layer to substrate layer. - // reference: https://github.com/paritytech/ink-examples/blob/b8d2caa52cf4691e0ddd7c919e4462311deb5ad0/psp22-extension/runtime/psp22-extension-example.rs#L236 - let overhead = contract_host_weight.debug_message; - - let charged_weight = env.charge_weight(base_weight.saturating_add(overhead))?; - log::debug!(target: LOG_TARGET, "{} charged weight: {:?}", log_prefix, charged_weight); - - Ok(charged_weight) -} - -fn dispatch(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config - + frame_system::Config, - RuntimeOrigin: From>, - E: Ext, -{ - const LOG_PREFIX: &str = " dispatch |"; - - let mut env = env.buf_in_buf_out(); - let len = env.in_len(); - - charge_overhead_weight::(&mut env, len, LOG_PREFIX)?; - - // read the input as RuntimeCall - let call: RuntimeCall = env.read_as_unbounded(len)?; - - log::debug!(target: LOG_TARGET, "Read input as call successfully"); - - // contract is the origin by default - let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into(); - - dispatch_call::(&mut env, call, origin, LOG_PREFIX) -} - -fn read_state(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config - + pallet_assets::Config - + pallet_nfts::Config - + cumulus_pallet_parachain_system::Config - + frame_system::Config, - E: Ext, -{ - const LOG_PREFIX: &str = " read_state |"; - - let mut env = env.buf_in_buf_out(); - - // To be conservative, we charge the weight for reading the input bytes of a fixed-size type. - let base_weight: Weight = ContractSchedule::::get() - .host_fn_weights - .return_per_byte - .saturating_mul(env.in_len().into()); - let charged_weight = env.charge_weight(base_weight)?; - - log::debug!(target:LOG_TARGET, "{} charged weight: {:?}", LOG_PREFIX, charged_weight); - - let key: RuntimeStateKeys = env.read_as()?; - - let result = match key { - RuntimeStateKeys::Nfts(key) => read_nfts_state::(key, &mut env), - RuntimeStateKeys::ParachainSystem(key) => { - read_parachain_system_state::(key, &mut env) - }, - RuntimeStateKeys::Assets(key) => read_assets_state::(key, &mut env), - }? - .encode(); - - log::trace!( - target:LOG_TARGET, - "{} result: {:?}.", LOG_PREFIX, result - ); - env.write(&result, false, None).map_err(|e| { - log::trace!(target: LOG_TARGET, "{:?}", e); - // TODO: Other error. - DispatchError::Other("unable to write results to contract memory") - }) -} - fn read_parachain_system_state( key: ParachainSystemKeys, env: &mut Environment, @@ -320,10 +332,10 @@ where ) .encode()) }, - AssetsKeys::AssetExists(id) => { - env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_assets::Pallet::::asset_exists(id).encode()) - }, + // AssetsKeys::AssetExists(id) => { + // env.charge_weight(T::DbWeight::get().reads(1_u64))?; + // Ok(pallet_assets::Pallet::::asset_exists(id).encode()) + // }, AssetsKeys::BalanceOf(id, owner) => { env.charge_weight(T::DbWeight::get().reads(1_u64))?; Ok(pallet_assets::Pallet::::balance(id, &owner.0.into()) @@ -333,63 +345,10 @@ where env.charge_weight(T::DbWeight::get().reads(1_u64))?; Ok(pallet_assets::Pallet::::total_supply(id).encode()) }, + _ => todo!(), } } -fn send_xcm(env: Environment) -> Result<(), DispatchError> -where - T: pallet_contracts::Config - + frame_system::Config< - RuntimeOrigin = RuntimeOrigin, - AccountId = AccountId, - RuntimeCall = RuntimeCall, - >, - E: Ext, -{ - const LOG_PREFIX: &str = " send_xcm |"; - - let mut env = env.buf_in_buf_out(); - let len = env.in_len(); - - let _ = charge_overhead_weight::(&mut env, len, LOG_PREFIX)?; - - // read the input as CrossChainMessage - let xc_call: CrossChainMessage = env.read_as::()?; - - // Determine the call to dispatch - let (dest, message) = match xc_call { - CrossChainMessage::Relay(message) => { - let dest = Location::parent().into_versioned(); - let assets: Asset = (Here, 10 * UNIT).into(); - let beneficiary: Location = - AccountId32 { id: (env.ext().address().clone()).into(), network: None }.into(); - let message = Xcm::builder() - .withdraw_asset(assets.clone().into()) - .buy_execution(assets.clone(), Unlimited) - .transact( - SovereignAccount, - Weight::from_parts(250_000_000, 10_000), - message.encode().into(), - ) - .refund_surplus() - .deposit_asset(assets.into(), beneficiary) - .build(); - (dest, message) - }, - }; - - // TODO: revisit to replace with signed contract origin - let origin: RuntimeOrigin = RawOrigin::Root.into(); - - // Generate runtime call to dispatch - let call = RuntimeCall::PolkadotXcm(pallet_xcm::Call::send { - dest: Box::new(dest), - message: Box::new(VersionedXcm::V4(message)), - }); - - dispatch_call::(&mut env, call, origin, LOG_PREFIX) -} - #[cfg(test)] mod tests { use super::*; From 924df85ebd353cd56ff816f722fc8cdb4a6c5956 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Tue, 2 Jul 2024 15:51:16 +0200 Subject: [PATCH 16/27] refactor: draft final design --- Cargo.lock | 3 +- pop-api/Cargo.toml | 4 +- pop-api/examples/fungibles/lib.rs | 119 ++--- pop-api/integration-tests/Cargo.toml | 4 +- .../integration-tests/src/local_fungibles.rs | 11 +- pop-api/src/error.rs | 335 ------------ pop-api/src/lib.rs | 85 ++- pop-api/src/primitives.rs | 1 - pop-api/src/v0/assets/fungibles.rs | 45 +- pop-api/src/v0/assets/mod.rs | 446 +++------------- pop-api/src/v0/balances.rs | 30 +- pop-api/src/v0/cross_chain/mod.rs | 29 +- pop-api/src/v0/mod.rs | 15 - pop-api/src/v0/nfts.rs | 37 +- pop-api/src/v0/state.rs | 7 - primitives/Cargo.toml | 7 - primitives/src/lib.rs | 124 ++++- primitives/src/storage_keys.rs | 13 +- runtime/devnet/Cargo.toml | 3 +- .../src/{extensions.rs => extensions/mod.rs} | 496 +++++++++++------- runtime/devnet/src/extensions/v0/assets.rs | 39 ++ runtime/devnet/src/extensions/v0/error.rs | 298 +++++++++++ runtime/devnet/src/extensions/v0/mod.rs | 2 + runtime/testnet/Cargo.toml | 2 +- runtime/testnet/src/extensions.rs | 18 +- 25 files changed, 1013 insertions(+), 1160 deletions(-) delete mode 100644 pop-api/src/error.rs delete mode 100644 pop-api/src/v0/state.rs rename runtime/devnet/src/{extensions.rs => extensions/mod.rs} (79%) create mode 100644 runtime/devnet/src/extensions/v0/assets.rs create mode 100644 runtime/devnet/src/extensions/v0/error.rs create mode 100644 runtime/devnet/src/extensions/v0/mod.rs diff --git a/Cargo.lock b/Cargo.lock index d798562b..cf7abf73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9675,8 +9675,6 @@ version = "0.0.0" dependencies = [ "bounded-collections 0.1.9", "parity-scale-codec", - "scale-decode", - "scale-encode", "scale-info", ] @@ -9744,6 +9742,7 @@ dependencies = [ "polkadot-runtime-common", "pop-primitives", "pop-runtime-common", + "rand", "scale-info", "smallvec", "sp-api", diff --git a/pop-api/Cargo.toml b/pop-api/Cargo.toml index 82ee7613..dc48ea8a 100644 --- a/pop-api/Cargo.toml +++ b/pop-api/Cargo.toml @@ -9,9 +9,8 @@ edition = "2021" enumflags2 = { version = "0.7.7" } ink = { version = "5.0.0", default-features = false } sp-io = { version = "31.0.0", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] } -sp-runtime = { version = "32.0.0", default-features = false } -pop-primitives = { path = "../primitives", features = ["devnet"], default-features = false } +pop-primitives = { path = "../primitives", default-features = false } [lib] name = "pop_api" @@ -25,7 +24,6 @@ std = [ "ink/std", "pop-primitives/std", "sp-io/std", - "sp-runtime/std", ] assets = ["pop-primitives/assets"] balances = [] diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 1794fbe5..03841b74 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -8,13 +8,13 @@ use ink::prelude::vec::Vec; use pop_api::{ assets::fungibles::{self as api}, - error::StatusCode, - primitives::{AccountId as AccountId32, AssetId}, + primitives::AssetId, + StatusCode, }; pub type Result = core::result::Result; -#[ink::contract(env = pop_api::Environment)] +#[ink::contract] mod fungibles { use super::*; @@ -41,141 +41,84 @@ mod fungibles { #[ink(message)] pub fn total_supply(&self, id: AssetId) -> Result { - // api::total_supply(id).map_err(|e| e.into()) api::total_supply(id) } #[ink(message)] - pub fn balance_of(&self, id: AssetId, owner: AccountId32) -> Result { - // api::balance_of(id, owner).map_err(|e| e.into()) + pub fn balance_of(&self, id: AssetId, owner: AccountId) -> Balance { api::balance_of(id, owner) } #[ink(message)] - pub fn allowance( - &self, - id: AssetId, - owner: AccountId32, - spender: AccountId32, - ) -> Result { - // api::allowance(id, owner, spender).map_err(|e| e.into()) + pub fn allowance(&self, id: AssetId, owner: AccountId, spender: AccountId) -> Balance { api::allowance(id, owner, spender) } #[ink(message)] - pub fn transfer(&self, id: AssetId, to: AccountId32, value: Balance) -> Result<()> { - ink::env::debug_println!( - "PopApiFungiblesExample::transfer: id: {:?}, to: {:?} value: {:?}", - id, - to, - value, - ); - - let result = api::transfer(id, to, value); - ink::env::debug_println!("Result: {:?}", result); - // result.map_err(|e| e.into()) - result + pub fn transfer(&self, id: AssetId, to: AccountId, value: Balance) -> Result<()> { + api::transfer(id, to, value)?; + Ok(()) } #[ink(message)] pub fn transfer_from( &self, id: AssetId, - from: AccountId32, - to: AccountId32, + from: AccountId, + to: AccountId, value: Balance, // In the standard a `[u8]`, but the size needs to be known at compile time. _data: Vec, ) -> Result<()> { - ink::env::debug_println!( - "PopApiFungiblesExample::transfer_from: id: {:?}, from: {:?}, to: {:?} value: {:?}", - id, - from, - to, - value, - ); - - let result = api::transfer_from(id, from, to, value); - ink::env::debug_println!("Result: {:?}", result); - // result.map_err(|e| e.into()) - result + api::transfer_from(id, from, to, value)?; + Ok(()) } #[ink(message)] - pub fn approve(&self, id: AssetId, spender: AccountId32, value: Balance) -> Result<()> { - ink::env::debug_println!( - "PopApiFungiblesExample::approve: id: {:?}, spender {:?}, value: {:?}", - id, - spender, - value, - ); - - let result = api::approve(id, spender, value); - ink::env::debug_println!("Result: {:?}", result); - // result.map_err(|e| e.into()) - result + pub fn approve(&self, id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + api::approve(id, spender, value)?; + Ok(()) } #[ink(message)] pub fn increase_allowance( &self, id: AssetId, - spender: AccountId32, + spender: AccountId, value: Balance, ) -> Result<()> { - ink::env::debug_println!( - "PopApiFungiblesExample::increase_allowance: id: {:?}, spender {:?}, value: {:?}", - id, - spender, - value, - ); - - let result = api::increase_allowance(id, spender, value); - ink::env::debug_println!("Result: {:?}", result); - // result.map_err(|e| e.into()) - result + api::increase_allowance(id, spender, value)?; + Ok(()) } #[ink(message)] pub fn decrease_allowance( &self, id: AssetId, - spender: AccountId32, + spender: AccountId, value: Balance, ) -> Result<()> { - ink::env::debug_println!( - "PopApiFungiblesExample::decrease_allowance: id: {:?}, spender {:?}, value: {:?}", - id, - spender, - value, - ); - - let result = api::decrease_allowance(id, spender, value); - ink::env::debug_println!("Result: {:?}", result); - // result.map_err(|e| e.into()) - result + api::decrease_allowance(id, spender, value)?; + Ok(()) } - /// 2. PSP-22 Metadata Interface: - /// - token_name - /// - token_symbol - /// - token_decimals + // 2. PSP-22 Metadata Interface: + // - token_name + // - token_symbol + // - token_decimals #[ink(message)] - pub fn token_name(&self, id: AssetId) -> Result> { - // api::token_name(id).map_err(|e| e.into()) + pub fn token_name(&self, id: AssetId) -> Vec { api::token_name(id) } #[ink(message)] - pub fn token_symbol(&self, id: AssetId) -> Result> { - // api::token_symbol(id).map_err(|e| e.into()) + pub fn token_symbol(&self, id: AssetId) -> Vec { api::token_symbol(id) } #[ink(message)] - pub fn token_decimals(&self, id: AssetId) -> Result { - // api::token_decimals(id).map_err(|e| e.into()) + pub fn token_decimals(&self, id: AssetId) -> u8 { api::token_decimals(id) } @@ -189,7 +132,7 @@ mod fungibles { // - clear_metadata // #[ink(message)] - // pub fn create(&self, id: AssetId, admin: AccountId32, min_balance: Balance) -> Result<()> { + // pub fn create(&self, id: AssetId, admin: AccountId, min_balance: Balance) -> Result<()> { // ink::env::debug_println!( // "PopApiFungiblesExample::create: id: {:?} admin: {:?} min_balance: {:?}", // id, @@ -198,8 +141,8 @@ mod fungibles { // ); // let result = api::create(id, admin, min_balance); // ink::env::debug_println!("Result: {:?}", result); - // // result.map_err(|e| e.into()) - // result + // result.map_err(|e| e.into()) + // result // } // #[ink(message)] diff --git a/pop-api/integration-tests/Cargo.toml b/pop-api/integration-tests/Cargo.toml index 84769433..c855a884 100644 --- a/pop-api/integration-tests/Cargo.toml +++ b/pop-api/integration-tests/Cargo.toml @@ -10,7 +10,7 @@ frame-support = { version = "29.0.0", default-features = false } frame-system = { version = "29.0.0", default-features = false } pallet-balances = { version = "29.0.2", default-features = false } pallet-contracts = { version = "28.0.0", default-features = false } -pop-api = { path = "../.", default-features = false, features = ["assets"] } +pop-primitives = { path = "../../primitives", default-features = false, features = ["assets"] } pop-runtime-devnet = { path = "../../runtime/devnet", default-features = false } sp-io = { version = "31.0.0", default-features = false } sp-runtime = { version = "32.0.0", default-features = false } @@ -23,7 +23,7 @@ std = [ "frame-system/std", "pallet-balances/std", "pallet-contracts/std", - "pop-api/std", + "pop-primitives/std", "pop-runtime-devnet/std", "scale/std", "sp-io/std", diff --git a/pop-api/integration-tests/src/local_fungibles.rs b/pop-api/integration-tests/src/local_fungibles.rs index 1b3c6633..968c43eb 100644 --- a/pop-api/integration-tests/src/local_fungibles.rs +++ b/pop-api/integration-tests/src/local_fungibles.rs @@ -1,5 +1,5 @@ use super::*; -use pop_api::error::{ +use pop_primitives::error::{ ArithmeticError::*, Error::{self, *}, TokenError::*, @@ -8,7 +8,10 @@ use pop_api::error::{ const ASSET_ID: AssetId = 1; fn decoded(result: ExecReturnValue) -> T { - ::decode(&mut &result.data[2..]).unwrap() + match ::decode(&mut &result.data[2..]) { + Ok(value) => value, + Err(_) => panic!("\nTest failed by trying to decode result: {:?} into `T`\n", result), + } } fn allowance( @@ -78,7 +81,9 @@ fn transfer( ) -> ExecReturnValue { let function = function_selector("transfer"); let params = [function, asset_id.encode(), to.encode(), value.encode()].concat(); - do_bare_call(addr, params, 0).expect("should work") + let result = do_bare_call(addr, params, 0).expect("should work"); + println!("Transfer result: {:?}", result); + result } fn transfer_from( diff --git a/pop-api/src/error.rs b/pop-api/src/error.rs deleted file mode 100644 index 8989464f..00000000 --- a/pop-api/src/error.rs +++ /dev/null @@ -1,335 +0,0 @@ -use ink::{env::chain_extension::FromStatusCode, scale::Decode}; - -#[derive(Debug, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -pub struct StatusCode(pub u32); - -impl From for StatusCode { - fn from(value: u32) -> Self { - StatusCode(value) - } -} -impl FromStatusCode for StatusCode { - fn from_status_code(status_code: u32) -> Result<(), Self> { - match status_code { - 0 => Ok(()), - _ => Err(StatusCode(status_code)), - } - } -} - -impl From for StatusCode { - fn from(_: ink::scale::Error) -> Self { - StatusCode(255u32) - } -} - -#[derive(Debug, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -#[repr(u8)] -pub enum Error { - /// Some unknown error occurred. Go to the Pop API docs section `Pop API error`. - Other { - // Index within the `DispatchError` - dispatch_error_index: u8, - // Index within the `DispatchError` variant. - error_index: u8, - // Index for further nesting, e.g. pallet error. - error: u8, - } = 0, - /// Failed to lookup some data. - CannotLookup = 1, - /// A bad origin. - BadOrigin = 2, - /// A custom error in a module. - Module { - index: u8, - error: u8, - } = 3, - /// At least one consumer is remaining so the account cannot be destroyed. - ConsumerRemaining = 4, - /// There are no providers so the account cannot be created. - NoProviders = 5, - /// There are too many consumers so the account cannot be created. - TooManyConsumers = 6, - /// An error to do with tokens. - Token(TokenError) = 7, - /// An arithmetic error. - Arithmetic(ArithmeticError) = 8, - /// The number of transactional layers has been reached, or we are not in a transactional - /// layer. - Transactional(TransactionalError) = 9, - /// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate. - Exhausted = 10, - /// The state is corrupt; this is generally not going to fix itself. - Corruption = 11, - /// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later. - Unavailable = 12, - /// Root origin is not allowed. - RootNotAllowed = 13, - UnknownFunctionId = 254, - DecodingFailed = 255, -} - -#[cfg(test)] -impl From for StatusCode { - fn from(value: Error) -> Self { - let mut encoded_error = value.encode(); - // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). - encoded_error.resize(4, 0); - StatusCode::from( - u32::decode(&mut &encoded_error[..]).expect("qid, resized to 4 bytes line above"), - ) - } -} - -impl From for Error { - fn from(value: StatusCode) -> Self { - let mut encoded: [u8; 4] = value.0.to_le_bytes(); - match Error::decode(&mut &encoded[..]) { - Err(_) => { - encoded[..].rotate_right(1); - encoded[0] = 0u8; - Error::decode(&mut &encoded[..]).unwrap_or(Error::DecodingFailed) - }, - Ok(error) => error, - } - } -} - -#[derive(Debug, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -pub enum TokenError { - /// Funds are unavailable. - FundsUnavailable, - /// Some part of the balance gives the only provider reference to the account and thus cannot - /// be (re)moved. - OnlyProvider, - /// Account cannot exist with the funds that would be given. - BelowMinimum, - /// Account cannot be created. - CannotCreate, - /// The asset in question is unknown. - UnknownAsset, - /// Funds exist but are frozen. - Frozen, - /// Operation is not supported by the asset. - Unsupported, - /// Account cannot be created for a held balance. - CannotCreateHold, - /// Withdrawal would cause unwanted loss of account. - NotExpendable, - /// Account cannot receive the assets. - Blocked, -} - -#[derive(Debug, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -pub enum ArithmeticError { - /// Underflow. - Underflow, - /// Overflow. - Overflow, - /// Division by zero. - DivisionByZero, -} - -#[derive(Debug, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -pub enum TransactionalError { - /// Too many transactional layers have been spawned. - LimitReached, - /// A transactional layer was expected, but does not exist. - NoLayer, -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::error::{ArithmeticError::*, TokenError::*, TransactionalError::*}; - - #[test] - fn u32_always_encodes_to_4_bytes() { - assert_eq!(0u32.encode().len(), 4); - assert_eq!(u32::MAX.encode().len(), 4); - } - - // Decodes 4 bytes into a `u32` and converts it into `StatusCode`. - fn into_status_code(encoded_error: [u8; 4]) -> StatusCode { - let decoded_u32 = u32::decode(&mut &encoded_error[..]).unwrap(); - StatusCode::from_status_code(decoded_u32).unwrap_err() - } - - // Decodes 4 bytes into a `u32` and converts it into `Error`. - fn into_error(encoded_error: [u8; 4]) -> Error { - let decoded_u32 = u32::decode(&mut &encoded_error[..]).unwrap(); - let status_code = StatusCode::from_status_code(decoded_u32).unwrap_err(); - status_code.into() - } - - // Tests the `From` implementation for `Error`. - // - // Unit variants: - // If the encoded value indicates a nested `Error` which is known by the Pop API version as a - // unit variant, the encoded value is converted into `Error::Other`. - // - // Example: the error `BadOrigin` (encoded: `[2, 0, 0, 0]`) with a non-zero value for one - // of the bytes [1..4]: `[2, 0, 1, 0]` is converted into `[0, 2, 0, 1]`. This is decoded to - // `Error::Other { dispatch_error: 2, index: 0, error: 1 }`. - #[test] - fn unit_error_variants() { - let errors = vec![ - CannotLookup, - BadOrigin, - ConsumerRemaining, - NoProviders, - TooManyConsumers, - Exhausted, - Corruption, - Unavailable, - RootNotAllowed, - DecodingFailed, - ]; - // Four scenarios, 2 tests each: - // 1. Compare a `StatusCode`, which is converted from an encoded value, with a `StatusCode` - // converted from an `Error`. - // 2. Compare an `Error, which is converted from an encoded value, with the expected `Error`. - for (i, &error_code) in UNIT_ERRORS.iter().enumerate() { - // No nesting and unit variant correctly returned. - assert_eq!(into_status_code([error_code, 0, 0, 0]), errors[i].into()); - assert_eq!(into_error([error_code, 0, 0, 0]), errors[i]); - // Unexpected second byte nested. - assert_eq!( - into_status_code([error_code, 1, 0, 0]), - (Other { dispatch_error_index: error_code, error_index: 1, error: 0 }).into(), - ); - assert_eq!(into_error([error_code, 1, 0, 0]), errors[i]); - // Unexpected third byte nested. - assert_eq!( - into_status_code([error_code, 1, 1, 0]), - (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), - ); - assert_eq!(into_error([error_code, 1, 1, 0]), errors[i]); - // Unexpected fourth byte nested. - assert_eq!( - into_status_code([error_code, 1, 1, 1]), - (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), - ); - assert_eq!(into_error([error_code, 1, 1, 1]), errors[i]); - } - } - - // Single nested variants: - // If the encoded value indicates a double nested `Error` which is known by the Pop API version - // as a single nested variant, the encoded value is converted into `Error::Other`. - // - // Example: the error `Arithmetic(Overflow)` (encoded: `[8, 1, 0, 0]`) with a non-zero - // value for one of the bytes [2..4]: `[8, 1, 1, 0]` is converted into `[0, 8, 1, 1]`. This is - // decoded to `Error::Other { dispatch_error: 8, index: 1, error: 1 }`. - #[test] - fn single_nested_error_variants() { - let errors = vec![ - [Token(FundsUnavailable), Token(OnlyProvider)], - [Arithmetic(Underflow), Arithmetic(Overflow)], - [Transactional(LimitReached), Transactional(NoLayer)], - ]; - // Four scenarios, 2 tests each: - // 1. Compare a `StatusCode`, which is converted from an encoded value, with a `StatusCode` - // converted from an `Error`. - // 2. Compare an `Error, which is converted from an encoded value, with the expected `Error`. - for (i, &error_code) in SINGLE_NESTED_ERRORS.iter().enumerate() { - // No nesting and unit variant correctly returned. - assert_eq!(into_status_code([error_code, 0, 0, 0]), errors[i][0].into()); - assert_eq!(into_error([error_code, 0, 0, 0]), errors[i][0]); - // Allowed single nesting variant correctly returned. - assert_eq!(into_status_code([error_code, 1, 0, 0]), errors[i][1].into()); - assert_eq!(into_error([error_code, 1, 0, 0]), errors[i][1]); - // Unexpected third byte nested. - assert_eq!( - into_status_code([error_code, 1, 1, 0]), - (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), - ); - assert_eq!(into_error([error_code, 1, 1, 0]), errors[i][1]); - // Unexpected fourth byte nested. - assert_eq!( - into_status_code([error_code, 1, 1, 1]), - (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }).into(), - ); - assert_eq!(into_error([error_code, 1, 1, 1]), errors[i][1]); - } - } - - // Double nested variants: - // If the encoded value indicates a triple nested `Error` which is known by the Pop API version - // as a double nested variant, the encoded value is converted into `Error::Other`. - // - // Example: the error `Module { index: 10, error 5 }` (encoded: `[3, 10, 5, 0]`) with a non-zero - // value for the last byte: `[3, 10, 5, 3]` is converted into `[0, 3, 10, 5]`. This is - // decoded to `Error::Other { dispatch_error: 3, index: 10, error: 5 }`. - #[test] - fn double_nested_error_variants() { - // Four scenarios, 2 tests each: - // 1. Compare a `StatusCode`, which is converted from an encoded value, with a `StatusCode` - // converted from an `Error`. - // 2. Compare an `Error, which is converted from an encoded value, with the expected `Error`. - // - // No nesting and unit variant correctly returned. - assert_eq!(into_status_code([3, 0, 0, 0]), (Module { index: 0, error: 0 }).into()); - assert_eq!(into_error([3, 0, 0, 0]), Module { index: 0, error: 0 }); - // Allowed single nesting and variant correctly returned. - assert_eq!(into_status_code([3, 1, 0, 0]), (Module { index: 1, error: 0 }).into()); - assert_eq!(into_error([3, 1, 0, 0]), Module { index: 1, error: 0 }); - // Allowed double nesting and variant correctly returned. - assert_eq!(into_status_code([3, 1, 1, 0]), (Module { index: 1, error: 1 }).into()); - assert_eq!(into_error([3, 1, 1, 0]), Module { index: 1, error: 1 }); - // Unexpected fourth byte nested. - assert_eq!( - into_status_code([3, 1, 1, 1]), - (Other { dispatch_error_index: 3, error_index: 1, error: 1 }).into(), - ); - assert_eq!(into_error([3, 1, 1, 1]), Module { index: 1, error: 1 }); - } - - #[test] - fn single_nested_unknown_variants() { - // Unknown `TokenError` variant. - assert_eq!( - into_error([7, 10, 0, 0]), - Other { dispatch_error_index: 7, error_index: 10, error: 0 } - ); - assert_eq!( - into_status_code([7, 10, 0, 0]), - Other { dispatch_error_index: 7, error_index: 10, error: 0 }.into() - ); - // Unknown `Arithmetic` variant. - assert_eq!( - into_error([8, 3, 0, 0]), - Other { dispatch_error_index: 8, error_index: 3, error: 0 } - ); - assert_eq!( - into_status_code([8, 3, 0, 0]), - Other { dispatch_error_index: 8, error_index: 3, error: 0 }.into() - ); - // Unknown `Transactional` variant. - assert_eq!( - into_error([9, 2, 0, 0]), - Other { dispatch_error_index: 9, error_index: 2, error: 0 } - ); - assert_eq!( - into_status_code([9, 2, 0, 0]), - Other { dispatch_error_index: 9, error_index: 2, error: 0 }.into() - ); - } - - #[test] - fn test_random_encoded_values() { - assert_eq!( - into_error([100, 100, 100, 100]), - Other { dispatch_error_index: 100, error_index: 100, error: 100 } - ); - assert_eq!( - into_error([200, 200, 200, 200]), - Other { dispatch_error_index: 200, error_index: 200, error: 200 } - ); - } -} diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 55307f3e..cb27b17f 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,10 +1,8 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -use ink::{prelude::vec::Vec, ChainExtensionInstance}; -pub use sp_runtime::MultiAddress; +use ink::env::{chain_extension::FromStatusCode, DefaultEnvironment, Environment}; +use primitives::error::Error; -use crate::error::StatusCode; -use primitives::{storage_keys::*, AccountId as AccountId32}; #[cfg(feature = "assets")] pub use v0::assets; #[cfg(feature = "balances")] @@ -13,72 +11,49 @@ pub use v0::balances; pub use v0::cross_chain; #[cfg(feature = "nfts")] pub use v0::nfts; -use v0::{state, RuntimeCall}; -pub mod error; pub mod primitives; pub mod v0; -type AccountId = AccountId32; -// TODO: do the same as the AccountId above and check expanded macro code. -type Balance = ::Balance; +type AccountId = ::AccountId; +type Balance = ::Balance; #[cfg(any(feature = "nfts", feature = "cross-chain"))] -type BlockNumber = ::BlockNumber; +type BlockNumber = ::BlockNumber; pub type Result = core::result::Result; -#[derive(Debug, PartialEq, Eq, Clone)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[ink::scale_derive(Encode, Decode, TypeInfo)] -pub enum Environment {} +pub struct StatusCode(pub u32); -impl ink::env::Environment for Environment { - const MAX_EVENT_TOPICS: usize = - ::MAX_EVENT_TOPICS; - - type AccountId = ::AccountId; - type Balance = ::Balance; - type Hash = ::Hash; - type BlockNumber = ::BlockNumber; - type Timestamp = ::Timestamp; - - type ChainExtension = PopApi; +impl From for StatusCode { + fn from(value: u32) -> Self { + StatusCode(value) + } } - -#[ink::chain_extension(extension = 909)] -pub trait PopApi { - type ErrorCode = StatusCode; - - #[ink(function = 0)] - #[allow(private_interfaces)] - fn dispatch(call: RuntimeCall) -> Result<()>; - - #[ink(function = 1)] - #[allow(private_interfaces)] - fn read_state(key: RuntimeStateKeys) -> Result>; - - #[cfg(feature = "cross-chain")] - #[ink(function = 2)] - #[allow(private_interfaces)] - fn send_xcm(xcm: primitives::cross_chain::CrossChainMessage) -> Result<()>; +impl FromStatusCode for StatusCode { + fn from_status_code(status_code: u32) -> Result<()> { + match status_code { + 0 => Ok(()), + _ => Err(StatusCode(status_code)), + } + } } -#[inline] -fn dispatch(call: RuntimeCall) -> Result<()> { - <::ChainExtension as ChainExtensionInstance>::instantiate( - ) - .dispatch(call) +impl From for StatusCode { + fn from(_: ink::scale::Error) -> Self { + StatusCode(255u32) + } } -#[inline] -fn read_state(key: RuntimeStateKeys) -> Result> { - <::ChainExtension as ChainExtensionInstance>::instantiate( - ) - .read_state(key) +impl From for Error { + fn from(value: StatusCode) -> Self { + value.0.into() + } } -#[cfg(feature = "cross-chain")] -fn send_xcm(xcm: primitives::cross_chain::CrossChainMessage) -> Result<()> { - <::ChainExtension as ChainExtensionInstance>::instantiate( - ) - .send_xcm(xcm) +impl From for StatusCode { + fn from(value: Error) -> Self { + StatusCode::from(u32::from(value)) + } } diff --git a/pop-api/src/primitives.rs b/pop-api/src/primitives.rs index 17419d5b..e174a111 100644 --- a/pop-api/src/primitives.rs +++ b/pop-api/src/primitives.rs @@ -1,2 +1 @@ pub use pop_primitives::*; -pub use sp_runtime::MultiAddress; diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index 376ca898..8d0de768 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -1,12 +1,6 @@ use ink::prelude::vec::Vec; -use crate::{ - assets, - primitives::{AssetId, MultiAddress}, - AccountId, Balance, StatusCode, -}; - -type Result = core::result::Result; +use crate::{assets, primitives::AssetId, AccountId, Balance, Result, StatusCode}; /// Local Fungibles: /// 1. PSP-22 Interface @@ -45,7 +39,7 @@ pub fn total_supply(id: AssetId) -> Result { /// # Returns /// The balance of the specified account, or an error if the operation fails. #[inline] -pub fn balance_of(id: AssetId, owner: AccountId) -> Result { +pub fn balance_of(id: AssetId, owner: AccountId) -> Balance { assets::balance_of(id, owner) } @@ -60,7 +54,7 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Result { /// # Returns /// The remaining allowance, or an error if the operation fails. #[inline] -pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { +pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Balance { assets::allowance(id, owner, spender) } @@ -75,11 +69,7 @@ pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result>, - value: Balance, -) -> Result<()> { +pub fn transfer(id: AssetId, to: AccountId, value: Balance) -> Result<()> { assets::transfer(id, to, value) } @@ -96,12 +86,7 @@ pub fn transfer( /// # Returns /// Returns `Ok(())` if successful, or an error if the transfer fails. #[inline] -pub fn transfer_from( - id: AssetId, - from: impl Into>, - to: impl Into>, - value: Balance, -) -> Result<()> { +pub fn transfer_from(id: AssetId, from: AccountId, to: AccountId, value: Balance) -> Result<()> { assets::transfer_approved(id, from, to, value) } @@ -161,7 +146,7 @@ pub fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Re /// # Returns /// The name of the token as a byte vector, or an error if the operation fails. #[inline] -pub fn token_name(id: AssetId) -> Result> { +pub fn token_name(id: AssetId) -> Vec { assets::token_name(id) } @@ -173,7 +158,7 @@ pub fn token_name(id: AssetId) -> Result> { /// # Returns /// The symbol of the token as a byte vector, or an error if the operation fails. #[inline] -pub fn token_symbol(id: AssetId) -> Result> { +pub fn token_symbol(id: AssetId) -> Vec { assets::token_symbol(id) } @@ -185,7 +170,7 @@ pub fn token_symbol(id: AssetId) -> Result> { /// # Returns /// The number of decimals of the token as a byte vector, or an error if the operation fails. #[inline] -pub fn token_decimals(id: AssetId) -> Result { +pub fn token_decimals(id: AssetId) -> u8 { assets::token_decimals(id) } @@ -291,6 +276,7 @@ pub fn token_decimals(id: AssetId) -> Result { // assets::asset_exists(id) // } +// TODO: further implement the rest of the interfaces and conclude on the FungiblesError. #[derive(Debug, PartialEq, Eq)] #[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum FungiblesError { @@ -311,13 +297,13 @@ pub enum FungiblesError { NoPermission, /// The given asset ID is unknown. Unknown, - // // TODO: - // // - Originally `InsufficientBalance` for the deposit but this would result in the same error - // // as the error when there is insufficient balance for transferring an asset. + // - Originally `InsufficientBalance` for the deposit but this would result in the same error + // as the error when there is insufficient balance for transferring an asset. /// No balance for creation of assets or fees. NoBalance, } +// TODO: include conversions from TokenError and add conversions based on added interfaces. impl From for FungiblesError { fn from(value: StatusCode) -> Self { let encoded = value.0.to_le_bytes(); @@ -339,10 +325,10 @@ impl From for FungiblesError { #[cfg(test)] mod tests { - use scale::Decode; + use ink::scale::Decode; use super::FungiblesError; - use crate::error::{ + use crate::primitives::error::{ ArithmeticError::*, Error::{self, *}, TokenError::*, @@ -355,6 +341,7 @@ mod tests { status_code.into() } + // If we ever want to change the conversion from bytes to `u32`. #[test] fn status_code_vs_encoded() { assert_eq!(u32::decode(&mut &[3u8, 10, 2, 0][..]).unwrap(), 133635u32); @@ -373,6 +360,7 @@ mod tests { Other { dispatch_error_index: 5, error_index: 5, error: 1 }, CannotLookup, BadOrigin, + // `ModuleError` other than assets module. Module { index: 2, error: 5 }, ConsumerRemaining, NoProviders, @@ -384,6 +372,7 @@ mod tests { Corruption, Unavailable, RootNotAllowed, + UnknownFunctionId, DecodingFailed, ]; for error in errors { diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 241c5020..22657323 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,17 +1,18 @@ -use ink::{prelude::vec::Vec, scale::Compact}; +use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec, scale::Decode}; -use crate::{state::read, Balance, RuntimeCall, *}; -use primitives::{AssetId, MultiAddress}; +use crate::{primitives::AssetId, AccountId, Balance, Result, StatusCode}; pub mod fungibles; -type Result = core::result::Result; +const ASSETS_MODULE: u8 = 52; +const VERSION: u8 = 0; /// [Pallet Assets](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/lib.rs): /// 1. Dispatchables /// 2. Read state functions /// /// 1. Dispatchables within pallet assets (TrustBackedAssets instance): +const DISPATCH: u8 = 0; /// - create /// - start_destroy /// - destroy_accounts @@ -21,25 +22,12 @@ type Result = core::result::Result; /// - burn /// - transfer /// - transfer_keep_alive -/// - force_transfer -/// - freeze -/// - thaw -/// - freeze_asset -/// - thaw_asset -/// - transfer_ownership -/// - set_team +const TRANSFER_KEEP_ALIVE: u8 = 9; /// - set_metadata /// - clear_metadata /// - approve_transfer /// - cancel_approval -/// - force_cancel_approval /// - transfer_approved -/// - touch -/// - refund -/// - set_min_balance -/// - touch_other -/// - refund_other -/// - block /// Issue a new class of fungible assets from a public origin. // pub(crate) fn create( @@ -98,16 +86,18 @@ type Result = core::result::Result; /// Move some assets from the sender account to another. #[inline] -pub(crate) fn transfer( - id: AssetId, - target: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { - id: id.into(), - target: target.into(), - amount: Compact(amount), - })) +pub fn transfer(id: AssetId, target: AccountId, amount: Balance) -> Result<()> { + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + DISPATCH, + ASSETS_MODULE, + // TODO: E.D. is always respected with transferring tokens via the API. + TRANSFER_KEEP_ALIVE, + ])) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, target, amount)) } // /// Move some assets from the sender account to another, keeping the sender account alive. @@ -122,68 +112,8 @@ pub(crate) fn transfer( // amount: Compact(amount), // })) // } -// -// /// Move some assets from one account to another. Sender should be the Admin of the asset `id`. -// pub(crate) fn force_transfer( -// id: AssetId, -// source: impl Into>, -// dest: impl Into>, -// amount: Balance, -// ) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::ForceTransfer { -// id: id.into(), -// source: source.into(), -// dest: dest.into(), -// amount: Compact(amount), -// })) -// } -// -// /// Disallow further unprivileged transfers of an asset `id` from an account `who`. `who` -// /// must already exist as an entry in `Account`s of the asset. If you want to freeze an -// /// account that does not have an entry, use `touch_other` first. -// pub(crate) fn freeze(id: AssetId, who: impl Into>) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::Freeze { id: id.into(), who: who.into() })) -// } -// -// /// Allow unprivileged transfers to and from an account again. -// pub(crate) fn thaw(id: AssetId, who: impl Into>) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::Thaw { id: id.into(), who: who.into() })) -// } -// -// /// Disallow further unprivileged transfers for the asset class. -// pub(crate) fn freeze_asset(id: AssetId) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::FreezeAsset { id: id.into() })) -// } -// -// /// Allow unprivileged transfers for the asset again. -// pub(crate) fn thaw_asset(id: AssetId) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::ThawAsset { id: id.into() })) -// } -// -// /// Change the Owner of an asset. -// pub(crate) fn transfer_ownership(id: AssetId, owner: impl Into>) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::TransferOwnership { -// id: id.into(), -// owner: owner.into(), -// })) -// } -// -// /// Change the Issuer, Admin and Freezer of an asset. -// pub(crate) fn set_team( -// id: AssetId, -// issuer: impl Into>, -// admin: impl Into>, -// freezer: impl Into>, -// ) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::SetTeam { -// id: id.into(), -// issuer: issuer.into(), -// admin: admin.into(), -// freezer: freezer.into(), -// })) -// } -/// Set the metadata for an asset. +// /// Set the metadata for an asset. // pub(crate) fn set_metadata( // id: AssetId, // name: Vec, @@ -200,315 +130,111 @@ pub(crate) fn transfer( /// Approve an amount of asset for transfer by a delegated third-party account. #[inline] -pub(crate) fn approve_transfer( - id: AssetId, - delegate: impl Into>, - amount: Balance, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::ApproveTransfer { - id: id.into(), - delegate: delegate.into(), - amount: Compact(amount), - })) +pub fn approve_transfer(id: AssetId, delegate: AccountId, amount: Balance) -> Result<()> { + ChainExtensionMethod::build(u32::from_le_bytes([0u8, 0, 52, 69])) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, delegate, amount)) } /// Cancel all of some asset approved for delegated transfer by a third-party account. #[inline] -pub(crate) fn cancel_approval( - id: AssetId, - delegate: impl Into>, -) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::CancelApproval { - id: id.into(), - delegate: delegate.into(), - })) +pub fn cancel_approval(id: AssetId, delegate: AccountId) -> Result<()> { + ChainExtensionMethod::build(0) + .input::<(AssetId, AccountId)>() + .output::, true>() + .handle_error_code::() + .call(&(id, delegate)) } -// /// Cancel all of some asset approved for delegated transfer by a third-party account. -// pub(crate) fn force_cancel_approval( -// id: AssetId, -// owner: impl Into>, -// delegate: impl Into>, -// ) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::ForceCancelApproval { -// id: id.into(), -// owner: owner.into(), -// delegate: delegate.into(), -// })) -// } - /// Transfer some asset balance from a previously delegated account to some third-party /// account. #[inline] -pub(crate) fn transfer_approved( +pub fn transfer_approved( id: AssetId, - owner: impl Into>, - destination: impl Into>, + from: AccountId, + to: AccountId, amount: Balance, ) -> Result<()> { - dispatch(RuntimeCall::Assets(AssetsCall::TransferApproved { - id: id.into(), - owner: owner.into(), - destination: destination.into(), - amount: Compact(amount), - })) + ChainExtensionMethod::build(0) + .input::<(AssetId, AccountId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, from, to, amount)) } -// -// /// Create an asset account for non-provider assets. -// pub(crate) fn touch(id: AssetId) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::Touch { id: id.into() })) -// } -// -// /// Return the deposit (if any) of an asset account or a consumer reference (if any) of an -// /// account. -// pub(crate) fn refund(id: AssetId, allow_burn: bool) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::Refund { id: id.into(), allow_burn })) -// } -// -// /// Sets the minimum balance of an asset. -// pub(crate) fn set_min_balance(id: AssetId, min_balance: Balance) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::SetMinBalance { -// id: id.into(), -// min_balance: Compact(min_balance), -// })) -// } -// -// /// Create an asset account for `who`. -// pub(crate) fn touch_other(id: AssetId, who: impl Into>) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::TouchOther { id: id.into(), who: who.into() })) -// } -// -// /// Return the deposit (if any) of a target asset account. Useful if you are the depositor. -// pub(crate) fn refund_other(id: AssetId, who: impl Into>) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::RefundOther { id: id.into(), who: who.into() })) -// } -// -// /// Disallow further unprivileged transfers of an asset `id` to and from an account `who`. -// pub(crate) fn block(id: AssetId, who: impl Into>) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::Block { id: id.into(), who: who.into() })) -// } /// 2. Read state functions +const READ_STATE: u8 = 1; /// - total_supply +const TOTAL_SUPPLY: u8 = 0; /// - balance_of /// - allowance /// - asset_exists /// - token_name /// - token_symbol /// - token_decimals -// + #[inline] -pub(crate) fn total_supply(id: AssetId) -> Result { - read(RuntimeStateKeys::Assets(AssetsKeys::TotalSupply(id))) +pub fn total_supply(id: AssetId) -> Result { + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + READ_STATE, + ASSETS_MODULE, + TOTAL_SUPPLY, + ])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) } #[inline] -pub(crate) fn balance_of(id: AssetId, owner: AccountId) -> Result { - read(RuntimeStateKeys::Assets(AssetsKeys::BalanceOf(id, owner))) +pub fn balance_of(id: AssetId, owner: AccountId) -> Balance { + ChainExtensionMethod::build(1) + .input::<(AssetId, AccountId)>() + .output::() + .ignore_error_code() + .call(&(id, owner)) } #[inline] -pub(crate) fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { - read(RuntimeStateKeys::Assets(AssetsKeys::Allowance(id, owner, spender))) +pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Balance { + ChainExtensionMethod::build(1) + .input::<(AssetId, AccountId, AccountId)>() + .output::() + .ignore_error_code() + .call(&(id, owner, spender)) } -// pub(crate) fn asset_exists(id: AssetId) -> Result { -// state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))) -// } #[inline] -pub(crate) fn token_name(id: AssetId) -> Result> { - read(RuntimeStateKeys::Assets(AssetsKeys::TokenName(id))) +pub fn token_name(id: AssetId) -> Vec { + ChainExtensionMethod::build(1) + .input::() + .output::, false>() + .ignore_error_code() + .call(&(id)) } // #[inline] -pub(crate) fn token_symbol(id: AssetId) -> Result> { - read(RuntimeStateKeys::Assets(AssetsKeys::TokenSymbol(id))) +pub fn token_symbol(id: AssetId) -> Vec { + ChainExtensionMethod::build(1) + .input::() + .output::, false>() + .ignore_error_code() + .call(&(id)) } #[inline] -pub(crate) fn token_decimals(id: AssetId) -> Result { - read(RuntimeStateKeys::Assets(AssetsKeys::TokenDecimals(id))) +pub fn token_decimals(id: AssetId) -> u8 { + ChainExtensionMethod::build(1) + .input::() + .output::() + .ignore_error_code() + .call(&(id)) } -// Parameters to extrinsics representing an asset id (`AssetIdParameter`) and a balance amount (`Balance`) are expected -// to be compact encoded. The pop api handles that for the developer. -// -// reference: https://substrate.stackexchange.com/questions/1873/what-is-the-meaning-of-palletcompact-in-pallet-development -// -// Asset id that is compact encoded. -type AssetIdParameter = Compact; -// Balance amount that is compact encoded. -type BalanceParameter = Compact; -// -#[derive(Debug, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -pub(crate) enum AssetsCall { - // #[codec(index = 0)] - // Create { id: AssetIdParameter, admin: MultiAddress, min_balance: Balance }, - // #[codec(index = 2)] - // StartDestroy { id: AssetIdParameter }, - // #[codec(index = 3)] - // DestroyAccounts { id: AssetIdParameter }, - // #[codec(index = 4)] - // DestroyApprovals { id: AssetIdParameter }, - // #[codec(index = 5)] - // FinishDestroy { id: AssetIdParameter }, - // #[codec(index = 6)] - // Mint { - // id: AssetIdParameter, - // beneficiary: MultiAddress, - // amount: BalanceParameter, - // }, - // #[codec(index = 7)] - // Burn { id: AssetIdParameter, who: MultiAddress, amount: BalanceParameter }, - // #[codec(index = 8)] - // Transfer { id: AssetIdParameter, target: MultiAddress, amount: BalanceParameter }, - #[codec(index = 9)] - TransferKeepAlive { - id: AssetIdParameter, - target: MultiAddress, - amount: BalanceParameter, - }, - // #[codec(index = 10)] - // ForceTransfer { - // id: AssetIdParameter, - // source: MultiAddress, - // dest: MultiAddress, - // amount: BalanceParameter, - // }, - // #[codec(index = 11)] - // Freeze { id: AssetIdParameter, who: MultiAddress }, - // #[codec(index = 12)] - // Thaw { id: AssetIdParameter, who: MultiAddress }, - // #[codec(index = 13)] - // FreezeAsset { id: AssetIdParameter }, - // #[codec(index = 14)] - // ThawAsset { id: AssetIdParameter }, - // #[codec(index = 15)] - // TransferOwnership { id: AssetIdParameter, owner: MultiAddress }, - // #[codec(index = 16)] - // SetTeam { - // id: AssetIdParameter, - // issuer: MultiAddress, - // admin: MultiAddress, - // freezer: MultiAddress, - // }, - // #[codec(index = 17)] - // SetMetadata { id: AssetIdParameter, name: Vec, symbol: Vec, decimals: u8 }, - // #[codec(index = 18)] - // ClearMetadata { id: AssetIdParameter }, - #[codec(index = 22)] - ApproveTransfer { - id: AssetIdParameter, - delegate: MultiAddress, - amount: BalanceParameter, - }, - #[codec(index = 23)] - CancelApproval { id: AssetIdParameter, delegate: MultiAddress }, - // #[codec(index = 24)] - // ForceCancelApproval { - // id: AssetIdParameter, - // owner: MultiAddress, - // delegate: MultiAddress, - // }, - #[codec(index = 25)] - TransferApproved { - id: AssetIdParameter, - owner: MultiAddress, - destination: MultiAddress, - amount: BalanceParameter, - }, - // // #[codec(index = 26)] - // // Touch { id: AssetIdParameter }, - // // #[codec(index = 27)] - // // Refund { id: AssetIdParameter, allow_burn: bool }, - // // #[codec(index = 28)] - // // SetMinBalance { id: AssetIdParameter, min_balance: BalanceParameter }, - // // #[codec(index = 29)] - // // TouchOther { id: AssetIdParameter, who: MultiAddress }, - // // #[codec(index = 30)] - // // RefundOther { id: AssetIdParameter, who: MultiAddress }, - // // #[codec(index = 31)] - // // Block { id: AssetIdParameter, who: MultiAddress }, - // } - - // // TODO: Not being used atm but necessary if we want to provide access to the - // // rest of the pallet, outside of the use cases. - // #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] - // #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] - // pub enum AssetsError { - // /// Account balance must be greater than or equal to the transfer amount. - // BalanceLow, - // /// The account to alter does not exist. - // NoAccount, - // /// The signing account has no permission to do the operation. - // NoPermission, - // /// The given asset ID is unknown. - // Unknown, - // /// The origin account is frozen. - // Frozen, - // /// The asset ID is already taken. - // InUse, - // /// Invalid witness data given. - // BadWitness, - // /// Minimum balance should be non-zero. - // MinBalanceZero, - // /// Unable to increment the consumer reference counters on the account. Either no provider - // /// reference exists to allow a non-zero balance of a non-self-sufficient asset, or one - // /// fewer then the maximum number of consumers has been reached. - // UnavailableConsumer, - // /// Invalid metadata given. - // BadMetadata, - // /// No approval exists that would allow the transfer. - // Unapproved, - // /// The source account would not survive the transfer and it needs to stay alive. - // WouldDie, - // /// The asset-account already exists. - // AlreadyExists, - // /// The asset-account doesn't have an associated deposit. - // NoDeposit, - // /// The operation would result in funds being burned. - // WouldBurn, - // /// The asset is a live asset and is actively being used. Usually emit for operations such - // /// as `start_destroy` which require the asset to be in a destroying state. - // LiveAsset, - // /// The asset is not live, and likely being destroyed. - // AssetNotLive, - // /// The asset status is not the expected status. - // IncorrectStatus, - // /// The asset should be frozen before the given operation. - // NotFrozen, - // /// Callback action resulted in error. - // CallbackFailed, -} - -// -// impl TryFrom for AssetsError { -// type Error = Error; -// -// fn try_from(status_code: u32) -> core::result::Result { -// use AssetsError::*; -// match status_code { -// 0 => Ok(BalanceLow), -// 1 => Ok(NoAccount), -// 2 => Ok(NoPermission), -// 3 => Ok(Unknown), -// 4 => Ok(Frozen), -// 5 => Ok(InUse), -// 6 => Ok(BadWitness), -// 7 => Ok(MinBalanceZero), -// 8 => Ok(UnavailableConsumer), -// 9 => Ok(BadMetadata), -// 10 => Ok(Unapproved), -// 11 => Ok(WouldDie), -// 12 => Ok(AlreadyExists), -// 13 => Ok(NoDeposit), -// 14 => Ok(WouldBurn), -// 15 => Ok(LiveAsset), -// 16 => Ok(AssetNotLive), -// 17 => Ok(IncorrectStatus), -// 18 => Ok(NotFrozen), -// _ => todo!(), -// } -// } +// pub(crate) fn asset_exists(id: AssetId) -> Result { +// state::read(RuntimeStateKeys::Assets(AssetsKeys::AssetExists(id))) // } diff --git a/pop-api/src/v0/balances.rs b/pop-api/src/v0/balances.rs index e14e6e32..bf029178 100644 --- a/pop-api/src/v0/balances.rs +++ b/pop-api/src/v0/balances.rs @@ -1,6 +1,9 @@ -use crate::{dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, Error, StatusCode}; +use crate::{ + dispatch, primitives::MultiAddress, v0::RuntimeCall, AccountId, PopApiError, + PopApiError::UnknownStatusCode, +}; -type Result = core::result::Result; +type Result = core::result::Result; pub fn transfer_keep_alive( dest: impl Into>, @@ -14,7 +17,7 @@ pub fn transfer_keep_alive( #[derive(scale::Encode)] #[allow(dead_code)] -pub enum BalancesCall { +pub(crate) enum BalancesCall { #[codec(index = 3)] TransferKeepAlive { dest: MultiAddress, @@ -23,11 +26,9 @@ pub enum BalancesCall { }, } -// TODO: Not being used atm but necessary if we want to provide access to the -// rest of the pallet, outside of the use cases. #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum BalancesError { +pub enum Error { /// Vesting balance too high to send value. VestingBalance, /// Account liquidity restrictions prevent withdrawal. @@ -54,11 +55,11 @@ pub enum BalancesError { DeltaZero, } -impl TryFrom for BalancesError { - type Error = Error; +impl TryFrom for Error { + type Error = PopApiError; fn try_from(status_code: u32) -> core::result::Result { - use BalancesError::*; + use Error::*; match status_code { 0 => Ok(VestingBalance), 1 => Ok(LiquidityRestrictions), @@ -72,7 +73,16 @@ impl TryFrom for BalancesError { 9 => Ok(TooManyFreezes), 10 => Ok(IssuanceDeactivated), 11 => Ok(DeltaZero), - _ => todo!(), + _ => Err(UnknownStatusCode(status_code)), + } + } +} + +impl From for Error { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::Balances(e) => e, + _ => panic!("expected balances error"), } } } diff --git a/pop-api/src/v0/cross_chain/mod.rs b/pop-api/src/v0/cross_chain/mod.rs index ad58e0e8..6732c119 100644 --- a/pop-api/src/v0/cross_chain/mod.rs +++ b/pop-api/src/v0/cross_chain/mod.rs @@ -1,16 +1,12 @@ -use crate::{BlockNumber, ParachainSystemKeys, Result, RuntimeStateKeys}; - pub mod coretime; -pub fn relay_chain_block_number() -> Result { - crate::v0::state::read(RuntimeStateKeys::ParachainSystem( - ParachainSystemKeys::LastRelayChainBlockNumber, - )) -} +use crate::{PopApiError::UnknownStatusCode, *}; + +type Result = core::result::Result; #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum CrossChainError { +pub enum Error { /// The desired destination was unreachable, generally because there is a no way of routing /// to it. Unreachable, @@ -66,11 +62,11 @@ pub enum CrossChainError { LocalExecutionIncomplete, } -impl TryFrom for CrossChainError { - type Error = crate::error::Error; +impl TryFrom for Error { + type Error = PopApiError; fn try_from(status_code: u32) -> core::result::Result { - use CrossChainError::*; + use Error::*; match status_code { 0 => Ok(Unreachable), 1 => Ok(SendFailure), @@ -96,7 +92,16 @@ impl TryFrom for CrossChainError { 21 => Ok(InvalidAssetUnknownReserve), 22 => Ok(InvalidAssetUnsupportedReserve), 23 => Ok(TooManyReserves), - _ => todo!(), + _ => Err(UnknownStatusCode(status_code)), + } + } +} + +impl From for Error { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::Xcm(e) => e, + _ => panic!("expected xcm error"), } } } diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index f91c4271..310b360c 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -6,18 +6,3 @@ pub mod balances; pub mod cross_chain; #[cfg(feature = "nfts")] pub mod nfts; -pub mod state; - -#[derive(Debug, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -pub(crate) enum RuntimeCall { - #[codec(index = 10)] - #[cfg(feature = "balances")] - Balances(balances::BalancesCall), - #[codec(index = 50)] - #[cfg(feature = "nfts")] - Nfts(nfts::NftCalls), - #[codec(index = 52)] - #[cfg(feature = "assets")] - Assets(assets::AssetsCall), -} diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index 32539576..e111c8dc 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -1,21 +1,17 @@ +use super::RuntimeCall; +use crate::{PopApiError::UnknownStatusCode, *}; use ink::prelude::vec::Vec; +use primitives::{ApprovalsLimit, BoundedBTreeMap, KeyLimit, MultiAddress}; +pub use primitives::{CollectionId, ItemId}; use scale::Encode; - -use crate::{ - dispatch, - primitives::{ - nfts::{ApprovalsLimit, CollectionId, ItemId, KeyLimit}, - BoundedBTreeMap, BoundedVec, - }, - state, AccountId, Balance, BlockNumber, MultiAddress, NftsKeys, RuntimeCall, RuntimeStateKeys, - StatusCode, -}; pub use types::*; type Result = core::result::Result; type StringLimit = u32; type MaxTips = u32; +type Result = core::result::Result; + /// Issue a new collection of non-fungible items pub fn create( admin: impl Into>, @@ -524,7 +520,7 @@ pub(crate) enum NftCalls { #[derive(Debug, Copy, Clone, PartialEq, Eq, Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] -pub enum NftsError { +pub enum Error { /// The signing account has no permission to do the operation. NoPermission, /// The given item ID is unknown. @@ -617,11 +613,11 @@ pub enum NftsError { WitnessRequired, } -impl TryFrom for NftsError { - type Error = crate::error::Error; +impl TryFrom for Error { + type Error = PopApiError; fn try_from(status_code: u32) -> core::result::Result { - use NftsError::*; + use Error::*; match status_code { 0 => Ok(NoPermission), 1 => Ok(UnknownCollection), @@ -668,7 +664,16 @@ impl TryFrom for NftsError { 42 => Ok(WrongNamespace), 43 => Ok(CollectionNotEmpty), 44 => Ok(WitnessRequired), - _ => todo!(), + _ => Err(UnknownStatusCode(status_code)), + } + } +} + +impl From for Error { + fn from(error: PopApiError) -> Self { + match error { + PopApiError::Nfts(e) => e, + _ => panic!("expected nfts error"), } } } @@ -677,7 +682,7 @@ impl TryFrom for NftsError { mod types { use super::*; use crate::{ - primitives::nfts::{CollectionId, ItemId}, + primitives::{CollectionId, ItemId}, Balance, BlockNumber, }; pub use enumflags2::{bitflags, BitFlags}; diff --git a/pop-api/src/v0/state.rs b/pop-api/src/v0/state.rs deleted file mode 100644 index afe48ba8..00000000 --- a/pop-api/src/v0/state.rs +++ /dev/null @@ -1,7 +0,0 @@ -use crate::{error::StatusCode, primitives::storage_keys::RuntimeStateKeys, read_state}; -use ink::scale::Decode; - -#[inline] -pub fn read(key: RuntimeStateKeys) -> crate::Result { - read_state(key).and_then(|v| T::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) -} diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index cb19b0ab..5cbd6d6c 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -6,10 +6,7 @@ edition = "2021" [dependencies] bounded-collections = { version = "0.1", default-features = false } - scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } -scale-decode = { version = "0.10.0", default-features = false, features = ["derive"], optional = true } -scale-encode = { version = "0.5.0", default-features = false, features = ["derive"], optional = true } scale-info = { version = "2.10", default-features = false, features = ["derive"], optional = true } [features] @@ -17,12 +14,8 @@ default = ["std"] std = [ "bounded-collections/std", "scale/std", - "scale-decode/std", - "scale-encode/std", "scale-info/std", ] -devnet = [] -testnet = [] assets = [] cross-chain = [] nfts = [] diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index dc0a5245..9d31653a 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -3,14 +3,15 @@ pub use bounded_collections::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec}; use scale::{Decode, Encode, MaxEncodedLen}; #[cfg(feature = "std")] -use {scale_decode::DecodeAsType, scale_encode::EncodeAsType, scale_info::TypeInfo}; +use scale_info::TypeInfo; +pub use v0::error; #[cfg(feature = "cross-chain")] pub mod cross_chain; pub mod storage_keys; -#[derive(Encode, Decode, Clone, Debug, MaxEncodedLen, Eq, PartialEq, Ord, PartialOrd)] -#[cfg_attr(feature = "std", derive(TypeInfo, DecodeAsType, EncodeAsType))] +#[derive(Encode, Decode, Debug, MaxEncodedLen, Eq, PartialEq)] +#[cfg_attr(feature = "std", derive(TypeInfo))] pub struct AccountId(pub [u8; 32]); // Identifier for the class of asset. @@ -29,3 +30,120 @@ pub mod nfts { /// The maximum approvals an item could have. pub type ApprovalsLimit = ConstU32<20>; } + +pub mod v0 { + use super::*; + pub mod error { + use super::*; + + #[derive(Encode, Decode, Debug, Eq, PartialEq)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + #[repr(u8)] + pub enum Error { + /// Some unknown error occurred. Go to the Pop API docs section `Pop API error`. + Other { + // Index within the `DispatchError` + dispatch_error_index: u8, + // Index within the `DispatchError` variant. + error_index: u8, + // Index for further nesting, e.g. pallet error. + error: u8, + } = 0, + /// Failed to lookup some data. + CannotLookup = 1, + /// A bad origin. + BadOrigin = 2, + /// A custom error in a module. + Module { index: u8, error: u8 } = 3, + /// At least one consumer is remaining so the account cannot be destroyed. + ConsumerRemaining = 4, + /// There are no providers so the account cannot be created. + NoProviders = 5, + /// There are too many consumers so the account cannot be created. + TooManyConsumers = 6, + /// An error to do with tokens. + Token(TokenError) = 7, + /// An arithmetic error. + Arithmetic(ArithmeticError) = 8, + /// The number of transactional layers has been reached, or we are not in a transactional + /// layer. + Transactional(TransactionalError) = 9, + /// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate. + Exhausted = 10, + /// The state is corrupt; this is generally not going to fix itself. + Corruption = 11, + /// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later. + Unavailable = 12, + /// Root origin is not allowed. + RootNotAllowed = 13, + /// Unknown function id. + UnknownFunctionId = 254, + /// Decoding failed on the runtime. + DecodingFailed = 255, + } + + impl From for Error { + fn from(value: u32) -> Self { + let encoded = value.to_le_bytes(); + Error::decode(&mut &encoded[..]).unwrap_or(Error::DecodingFailed) + } + } + + impl From for u32 { + fn from(value: Error) -> Self { + let mut encoded_error = value.encode(); + // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). + encoded_error.resize(4, 0); + u32::from_le_bytes( + encoded_error.try_into().expect("qid, resized to 4 bytes line above"), + ) + } + } + + #[derive(Encode, Decode, Clone, Debug, MaxEncodedLen, Eq, PartialEq, Ord, PartialOrd)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + pub enum TokenError { + /// Funds are unavailable. + FundsUnavailable, + /// Some part of the balance gives the only provider reference to the account and thus cannot + /// be (re)moved. + OnlyProvider, + /// Account cannot exist with the funds that would be given. + BelowMinimum, + /// Account cannot be created. + CannotCreate, + /// The asset in question is unknown. + UnknownAsset, + /// Funds exist but are frozen. + Frozen, + /// Operation is not supported by the asset. + Unsupported, + /// Account cannot be created for a held balance. + CannotCreateHold, + /// Withdrawal would cause unwanted loss of account. + NotExpendable, + /// Account cannot receive the assets. + Blocked, + } + + #[derive(Encode, Decode, Debug, Eq, PartialEq)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + pub enum ArithmeticError { + /// Underflow. + Underflow, + /// Overflow. + Overflow, + /// Division by zero. + DivisionByZero, + } + + #[derive(Encode, Decode, Debug, Eq, PartialEq)] + #[cfg_attr(feature = "std", derive(TypeInfo))] + pub enum TransactionalError { + /// Too many transactional layers have been spawned. + LimitReached, + /// A transactional layer was expected, but does not exist. + NoLayer, + } + } +} diff --git a/primitives/src/storage_keys.rs b/primitives/src/storage_keys.rs index 7992089b..e42dbca0 100644 --- a/primitives/src/storage_keys.rs +++ b/primitives/src/storage_keys.rs @@ -46,14 +46,11 @@ pub enum NftsKeys { #[cfg(feature = "assets")] #[derive(Encode, Decode, Debug, MaxEncodedLen)] pub enum AssetsKeys { - Allowance(AssetId, AccountId, AccountId), - // /// Check if the asset exists. - // // AssetExists(AssetId), - /// Check balance. - BalanceOf(AssetId, AccountId), - /// Returns the total token supply for a given asset ID. TotalSupply(AssetId), - TokenDecimals(AssetId), - TokenSymbol(AssetId), + BalanceOf(AssetId, AccountId), + Allowance(AssetId, AccountId, AccountId), TokenName(AssetId), + TokenSymbol(AssetId), + TokenDecimals(AssetId), + // AssetExists(AssetId), } diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index 5f52b855..7db68576 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -89,8 +89,9 @@ parachain-info.workspace = true [dev-dependencies] env_logger = "0.11.2" -hex = "0.4.3" enumflags2 = "0.7.9" +hex = "0.4.3" +rand = "0.8.5" [features] default = ["std"] diff --git a/runtime/devnet/src/extensions.rs b/runtime/devnet/src/extensions/mod.rs similarity index 79% rename from runtime/devnet/src/extensions.rs rename to runtime/devnet/src/extensions/mod.rs index 6f98bf96..ac52d5bd 100644 --- a/runtime/devnet/src/extensions.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -1,18 +1,22 @@ +use codec::{Compact, Decode, Encode}; use cumulus_pallet_parachain_system::RelaychainDataProvider; use frame_support::traits::{Contains, OriginTrait}; use frame_support::{ dispatch::{GetDispatchInfo, RawOrigin}, pallet_prelude::*, traits::{ - fungibles::{approvals::Inspect as ApprovalInspect, Inspect}, + fungibles::approvals::Inspect as ApprovalInspect, nonfungibles_v2::Inspect as NonFungiblesInspect, }, }; use pallet_contracts::chain_extension::{ - BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, + BufInBufOutState, ChainExtension, Environment, Ext, InitState, RetVal, }; use sp_core::crypto::UncheckedFrom; -use sp_runtime::traits::{BlockNumberProvider, Dispatchable}; +use sp_runtime::{ + traits::{BlockNumberProvider, Dispatchable}, + DispatchError, MultiAddress, +}; use sp_std::{boxed::Box, vec::Vec}; use xcm::{ latest::{prelude::*, OriginKind::SovereignAccount}, @@ -20,17 +24,24 @@ use xcm::{ }; use crate::{ - config::assets::TrustBackedAssetsInstance, AccountId, AllowedApiCalls, RuntimeCall, - RuntimeOrigin, UNIT, + config::assets::TrustBackedAssetsInstance, AccountId, AllowedApiCalls, Balance, Runtime, + RuntimeCall, RuntimeOrigin, UNIT, }; use pop_primitives::{ cross_chain::CrossChainMessage, nfts::{CollectionId, ItemId}, - storage_keys::{AssetsKeys, NftsKeys, ParachainSystemKeys, RuntimeStateKeys}, + storage_keys::{ + AssetsKeys::{self, *}, + NftsKeys, ParachainSystemKeys, RuntimeStateKeys, + }, AssetId, }; +mod v0; + const LOG_TARGET: &str = "pop-api::extension"; +// Versions: +const V0: u8 = 0; type ContractSchedule = ::Schedule; @@ -58,53 +69,162 @@ where { log::debug!(target:LOG_TARGET, " extension called "); let mut env = env.buf_in_buf_out(); - let contract_host_weight = ContractSchedule::::get().host_fn_weights; - // debug_message weight is a good approximation of the additional overhead of going + // Charge weight for making a call from a contract to the runtime. + // `debug_message` weight is a good approximation of the additional overhead of going // from contract layer to substrate layer. // reference: https://github.com/paritytech/ink-examples/blob/b8d2caa52cf4691e0ddd7c919e4462311deb5ad0/psp22-extension/runtime/psp22-extension-example.rs#L236 + let contract_host_weight = ContractSchedule::::get().host_fn_weights; env.charge_weight(contract_host_weight.debug_message)?; - let result = match v0::FuncId::try_from(env.func_id()) { - Ok(function) => { - // calculate weight for reading bytes of `len` + // Extract version and function_id from first two bytes. + let (version, function_id) = { + let bytes = env.func_id().to_le_bytes(); + (bytes[0], bytes[1]) + }; + // Extract pallet index and call / key index from last two bytes. + let (pallet_index, call_index) = { + let bytes = env.ext_id().to_le_bytes(); + (bytes[0], bytes[1]) + }; + + let result = match FuncId::try_from(function_id) { + Ok(function_id) => { + // Read encoded parameters from buffer and calculate weight for reading `len` bytes`. // reference: https://github.com/paritytech/polkadot-sdk/blob/117a9433dac88d5ac00c058c9b39c511d47749d2/substrate/frame/contracts/src/wasm/runtime.rs#L267 let len = env.in_len(); env.charge_weight(contract_host_weight.return_per_byte.saturating_mul(len.into()))?; - match function { - v0::FuncId::Dispatch => dispatch::(&mut env, len), - v0::FuncId::ReadState => read_state::(&mut env), - v0::FuncId::SendXcm => send_xcm::(&mut env), + let params = env.read(len)?; + log::debug!(target: LOG_TARGET, "Read input successfully"); + match function_id { + FuncId::Dispatch => { + dispatch::(&mut env, version, pallet_index, call_index, params) + }, + FuncId::ReadState => { + read_state::(&mut env, version, pallet_index, call_index, params) + }, + // TODO + FuncId::SendXcm => send_xcm::(&mut env), } }, Err(e) => Err(e), }; - // Convert any error to a status code and return Ok with RetVal::Converging match result { Ok(_) => Ok(RetVal::Converging(0)), - Err(e) => Ok(RetVal::Converging(convert_to_status_code(e))), + Err(e) => Ok(RetVal::Converging(convert_to_status_code(e, version))), } } } -fn dispatch(env: &mut Environment, len: u32) -> Result<(), DispatchError> +fn dispatch( + env: &mut Environment, + version: u8, + pallet_index: u8, + call_index: u8, + params: Vec, +) -> Result<(), DispatchError> where - T: pallet_contracts::Config - + frame_system::Config, + T: frame_system::Config, RuntimeOrigin: From>, E: Ext, { const LOG_PREFIX: &str = " dispatch |"; - - // read the input as RuntimeCall - let call: RuntimeCall = env.read_as_unbounded(len)?; - log::debug!(target: LOG_TARGET, "Read input as call successfully"); - // contract is the origin by default + let call = construct_call(version, pallet_index, call_index, params) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + // Contract is the origin by default. let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into(); dispatch_call::(env, call, origin, LOG_PREFIX) } -fn read_state(env: &mut Environment) -> Result<(), DispatchError> +fn dispatch_call( + env: &mut Environment, + call: RuntimeCall, + mut origin: RuntimeOrigin, + log_prefix: &str, +) -> Result<(), DispatchError> +where + T: frame_system::Config, + RuntimeOrigin: From>, + E: Ext, +{ + let charged_dispatch_weight = env.charge_weight(call.get_dispatch_info().weight)?; + log::debug!(target:LOG_TARGET, "{} Inputted RuntimeCall: {:?}", log_prefix, call); + origin.add_filter(AllowedApiCalls::contains); + match call.dispatch(origin) { + Ok(info) => { + log::debug!(target:LOG_TARGET, "{} success, actual weight: {:?}", log_prefix, info.actual_weight); + // Refund weight if the actual weight is less than the charged weight. + if let Some(actual_weight) = info.actual_weight { + env.adjust_weight(charged_dispatch_weight, actual_weight); + } + Ok(()) + }, + Err(err) => { + log::debug!(target:LOG_TARGET, "{} failed: error: {:?}", log_prefix, err.error); + Err(err.error) + }, + } +} + +fn construct_call( + version: u8, + pallet_index: u8, + call_index: u8, + params: Vec, +) -> Result { + match pallet_index { + 52 => { + let call = versioned_construct_assets_call(version, call_index, params)?; + Ok(RuntimeCall::Assets(call)) + }, + _ => Err(DispatchError::Other("UnknownFunctionId")), + } +} + +fn construct_key( + version: u8, + pallet_index: u8, + call_index: u8, + params: Vec, +) -> Result { + match pallet_index { + 52 => { + let key = versioned_construct_assets_key(version, call_index, params)?; + Ok(RuntimeStateKeys::Assets(key)) + }, + _ => Err(DispatchError::Other("UnknownFunctionId")), + } +} + +fn versioned_construct_assets_call( + version: u8, + call_index: u8, + params: Vec, +) -> Result, DispatchError> { + match version { + V0 => v0::assets::construct_assets_call(call_index, params), + _ => Err(DispatchError::Other("UnknownFunctionId")), + } +} + +fn versioned_construct_assets_key( + version: u8, + call_index: u8, + params: Vec, +) -> Result { + match version { + V0 => v0::assets::construct_assets_key(call_index, params), + _ => Err(DispatchError::Other("UnknownFunctionId")), + } +} + +fn read_state( + env: &mut Environment, + version: u8, + pallet_index: u8, + call_index: u8, + params: Vec, +) -> Result<(), DispatchError> where T: pallet_contracts::Config + pallet_assets::Config @@ -114,15 +234,13 @@ where E: Ext, { const LOG_PREFIX: &str = " read_state |"; - - let key: RuntimeStateKeys = env.read_as()?; + let key = construct_key(version, pallet_index, call_index, params)?; let result = match key { RuntimeStateKeys::Nfts(key) => read_nfts_state::(key, env), RuntimeStateKeys::ParachainSystem(key) => read_parachain_system_state::(key, env), RuntimeStateKeys::Assets(key) => read_assets_state::(key, env), }? .encode(); - log::trace!( target:LOG_TARGET, "{} result: {:?}.", LOG_PREFIX, result @@ -141,10 +259,9 @@ where E: Ext, { const LOG_PREFIX: &str = " send_xcm |"; - - // read the input as CrossChainMessage + // Read the input as CrossChainMessage. let xc_call: CrossChainMessage = env.read_as::()?; - // Determine the call to dispatch + // Determine the call to dispatch. let (dest, message) = match xc_call { CrossChainMessage::Relay(message) => { let dest = Location::parent().into_versioned(); @@ -165,91 +282,85 @@ where (dest, message) }, }; - // TODO: revisit to replace with signed contract origin let origin: RuntimeOrigin = RawOrigin::Root.into(); - - // Generate runtime call to dispatch + // Generate runtime call to dispatch. let call = RuntimeCall::PolkadotXcm(pallet_xcm::Call::send { dest: Box::new(dest), message: Box::new(VersionedXcm::V4(message)), }); - dispatch_call::(env, call, origin, LOG_PREFIX) } -pub(crate) fn convert_to_status_code(error: DispatchError) -> u32 { +// Converts a `DispatchError` to a `u32` status code based on the version of the API the contract uses. +// The contract calling the chain extension can convert the status code to the descriptive `Error`. +// +// For `Error` see `pop_primitives::::error::Error`. +// +// The error encoding can vary per version, allowing for flexible and backward-compatible error handling. +// As a result, contracts maintain compatibility across different versions of the runtime. +// +// # Parameters +// +// - `error`: The `DispatchError` encountered during contract execution. +// - `version`: The version of the chain extension, used to determine the known errors. +pub(crate) fn convert_to_status_code(error: DispatchError, version: u8) -> u32 { + // "UnknownFunctionId" and "DecodingFailed" are mapped to specific errors in the API and will + // never change. let mut encoded_error = match error { DispatchError::Other("UnknownFunctionId") => vec![254, 0, 0, 0], + DispatchError::Other("DecodingFailed") => vec![255, 0, 0, 0], _ => error.encode(), }; // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). encoded_error.resize(4, 0); - u32::decode(&mut &encoded_error[..]).expect("qid, resized to 4 bytes line above") + let mut encoded_error = encoded_error.try_into().expect("qid, resized to 4 bytes line above"); + match version { + // If an unknown variant of the `DispatchError` is detected the error needs to be converted + // into the encoded value of `Error::Other`. This conversion is performed by shifting the bytes one + // position forward (discarding the last byte as it is not used) and setting the first byte to the + // encoded value of `Other` (0u8). This ensures the error is correctly categorized as an `Other` + // variant which provides all the necessary information to debug which error occurred in the runtime. + // + // Byte layout explanation: + // - Byte 0: index of the variant within `Error` + // - Byte 1: + // - Must be zero for `UNIT_ERRORS`. + // - Represents the nested error in `SINGLE_NESTED_ERRORS`. + // - Represents the first level of nesting in `DOUBLE_NESTED_ERRORS`. + // - Byte 2: + // - Represents the second level of nesting in `DOUBLE_NESTED_ERRORS`. + // - Byte 3: + // - Unused or represents further nested information. + 0 => v0::error::handle_unknown_error(&mut encoded_error), + _ => encoded_error = [254, 0, 0, 0], + } + u32::from_le_bytes(encoded_error) } -pub mod v0 { - #[derive(Debug)] - pub enum FuncId { - Dispatch, - ReadState, - SendXcm, - } +#[derive(Debug)] +pub enum FuncId { + Dispatch, + ReadState, + SendXcm, } -impl TryFrom for v0::FuncId { +impl TryFrom for FuncId { type Error = DispatchError; - fn try_from(func_id: u16) -> Result { + fn try_from(func_id: u8) -> Result { let id = match func_id { - 0x0 => Self::Dispatch, - 0x1 => Self::ReadState, - 0x2 => Self::SendXcm, + 0 => Self::Dispatch, + 1 => Self::ReadState, + 2 => Self::SendXcm, _ => { - log::error!("called an unregistered `func_id`: {:}", func_id); return Err(DispatchError::Other("UnknownFuncId")); }, }; - Ok(id) } } -fn dispatch_call( - env: &mut Environment, - call: RuntimeCall, - mut origin: RuntimeOrigin, - log_prefix: &str, -) -> Result<(), DispatchError> -where - T: frame_system::Config, - RuntimeOrigin: From>, - E: Ext, -{ - let charged_dispatch_weight = env.charge_weight(call.get_dispatch_info().weight)?; - - log::debug!(target:LOG_TARGET, "{} Inputted RuntimeCall: {:?}", log_prefix, call); - - origin.add_filter(AllowedApiCalls::contains); - - match call.dispatch(origin) { - Ok(info) => { - log::debug!(target:LOG_TARGET, "{} success, actual weight: {:?}", log_prefix, info.actual_weight); - - // refund weight if the actual weight is less than the charged weight - if let Some(actual_weight) = info.actual_weight { - env.adjust_weight(charged_dispatch_weight, actual_weight); - } - - Ok(()) - }, - Err(err) => { - log::debug!(target:LOG_TARGET, "{} failed: error: {:?}", log_prefix, err.error); - Err(err.error) - }, - } -} - fn read_parachain_system_state( key: ParachainSystemKeys, env: &mut Environment, @@ -323,7 +434,7 @@ where T: frame_system::Config, { match key { - AssetsKeys::Allowance(id, owner, spender) => { + Allowance(id, owner, spender) => { env.charge_weight(T::DbWeight::get().reads(1_u64))?; Ok(pallet_assets::Pallet::::allowance( id, @@ -336,12 +447,12 @@ where // env.charge_weight(T::DbWeight::get().reads(1_u64))?; // Ok(pallet_assets::Pallet::::asset_exists(id).encode()) // }, - AssetsKeys::BalanceOf(id, owner) => { + BalanceOf(id, owner) => { env.charge_weight(T::DbWeight::get().reads(1_u64))?; Ok(pallet_assets::Pallet::::balance(id, &owner.0.into()) .encode()) }, - AssetsKeys::TotalSupply(id) => { + TotalSupply(id) => { env.charge_weight(T::DbWeight::get().reads(1_u64))?; Ok(pallet_assets::Pallet::::total_supply(id).encode()) }, @@ -354,88 +465,51 @@ mod tests { use super::*; use crate::{Assets, Runtime, System}; use sp_runtime::BuildStorage; + // Test ensuring `func_id()` and `ext_id()` work as expected, i.e. extracting the first two + // bytes and the last two bytes, respectively, from a 4 byte array. + #[test] + fn test_byte_extraction() { + use rand::Rng; - fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::::default() - .build_storage() - .expect("Frame system builds valid default genesis config"); - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext - } + // Helper functions + fn func_id(id: u32) -> u16 { + (id & 0x0000FFFF) as u16 + } + fn ext_id(id: u32) -> u16 { + (id >> 16) as u16 + } - #[test] - fn encoding_decoding_dispatch_error() { - use codec::{Decode, Encode}; - use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; + // Number of test iterations + let test_iterations = 1_000_000; - new_test_ext().execute_with(|| { - let error = DispatchError::Module(ModuleError { - index: 255, - error: [2, 0, 0, 0], - message: Some("error message"), - }); - let encoded = error.encode(); - let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); - assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); - assert_eq!( - decoded, - // `message` is skipped for encoding. - DispatchError::Module(ModuleError { - index: 255, - error: [2, 0, 0, 0], - message: None - }) - ); - println!("Encoded Module Error: {:?}", encoded); + // Create a random number generator + let mut rng = rand::thread_rng(); - // Example pallet assets Error into ModuleError. - let index = - <::PalletInfo as frame_support::traits::PalletInfo>::index::< - Assets, - >() - .expect("Every active module has an index in the runtime; qed") as u8; + // Run the test for a large number of random 4-byte arrays + for _ in 0..test_iterations { + // Generate a random 4-byte array + let bytes: [u8; 4] = rng.gen(); - let mut error = - pallet_assets::Error::NotFrozen::.encode(); - error.resize(MAX_MODULE_ERROR_ENCODED_SIZE, 0); - let error = DispatchError::Module(ModuleError { - index, - error: TryInto::try_into(error).expect("should work"), - message: None, - }); - let encoded = error.encode(); - let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); - assert_eq!(encoded, vec![3, 52, 18, 0, 0, 0]); - assert_eq!( - decoded, - DispatchError::Module(ModuleError { - index: 52, - error: [18, 0, 0, 0], - message: None - }) - ); - println!("Encoded Module Error: {:?}", encoded); + // Convert the 4-byte array to a u32 value + let value = u32::from_le_bytes(bytes); - // Example DispatchError::Token - let error = DispatchError::Token(TokenError::UnknownAsset); - let encoded = error.encode(); - assert_eq!(encoded, vec![7, 4]); - println!("Encoded Token Error: {:?}", encoded); + // Extract the first two bytes (least significant 2 bytes) + let first_two_bytes = func_id(value); - // Example DispatchError::Arithmetic - let error = DispatchError::Arithmetic(ArithmeticError::Overflow); - let encoded = error.encode(); - assert_eq!(encoded, vec![8, 1]); - println!("Encoded Arithmetic Error: {:?}", encoded); - }); + // Extract the last two bytes (most significant 2 bytes) + let last_two_bytes = ext_id(value); + + // Check if the first two bytes match the expected value + assert_eq!([bytes[0], bytes[1]], first_two_bytes.to_le_bytes()); + + // Check if the last two bytes match the expected value + assert_eq!([bytes[2], bytes[3]], last_two_bytes.to_le_bytes()); + } } + // Test showing all the different type of variants and its encoding. #[test] fn encoding_of_enum() { - use codec::{Decode, Encode}; - - // Comprehensive enum with all different type of variants. #[derive(Debug, PartialEq, Encode, Decode)] enum ComprehensiveEnum { SimpleVariant, @@ -494,39 +568,77 @@ mod tests { println!("{:?} -> {:?}", enum_nested_enum_struct, enum_nested_enum_struct.encode()); } + fn new_test_ext() -> sp_io::TestExternalities { + let t = frame_system::GenesisConfig::::default() + .build_storage() + .expect("Frame system builds valid default genesis config"); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } + #[test] - fn dispatch_error_to_status_code() { - // Create all the different `DispatchError` variants with its respective `PopApiError`. - let test_cases = vec![ - (DispatchError::Other("hallo"), [0, 0, 0, 0]), - (DispatchError::CannotLookup, [1, 0, 0, 0]), - (DispatchError::BadOrigin, [2, 0, 0, 0]), - ( - DispatchError::Module(sp_runtime::ModuleError { - index: 1, + fn encoding_decoding_dispatch_error() { + use sp_runtime::{ArithmeticError, DispatchError, ModuleError, TokenError}; + + new_test_ext().execute_with(|| { + let error = DispatchError::Module(ModuleError { + index: 255, + error: [2, 0, 0, 0], + message: Some("error message"), + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 255, 2, 0, 0, 0]); + assert_eq!( + decoded, + // `message` is skipped for encoding. + DispatchError::Module(ModuleError { + index: 255, error: [2, 0, 0, 0], - message: Some("hallo"), - }), - [3, 1, 2, 0], - ), - (DispatchError::ConsumerRemaining, [4, 0, 0, 0]), - (DispatchError::NoProviders, [5, 0, 0, 0]), - (DispatchError::TooManyConsumers, [6, 0, 0, 0]), - (DispatchError::Token(sp_runtime::TokenError::BelowMinimum), [7, 2, 0, 0]), - (DispatchError::Arithmetic(sp_runtime::ArithmeticError::Overflow), [8, 1, 0, 0]), - ( - DispatchError::Transactional(sp_runtime::TransactionalError::LimitReached), - [9, 0, 0, 0], - ), - (DispatchError::Exhausted, [10, 0, 0, 0]), - (DispatchError::Corruption, [11, 0, 0, 0]), - (DispatchError::Unavailable, [12, 0, 0, 0]), - (DispatchError::RootNotAllowed, [13, 0, 0, 0]), - ]; - for (error, encoded_error) in test_cases { - let status_code = crate::extensions::convert_to_status_code(error); - assert_eq!(status_code, u32::decode(&mut &encoded_error[..]).unwrap()); - } + message: None + }) + ); + + // Example pallet assets Error into ModuleError. + let index = <::PalletInfo as frame_support::traits::PalletInfo>::index::< + Assets, + >() + .expect("Every active module has an index in the runtime; qed") as u8; + let mut error = + pallet_assets::Error::NotFrozen::.encode(); + error.resize(MAX_MODULE_ERROR_ENCODED_SIZE, 0); + let error = DispatchError::Module(ModuleError { + index, + error: TryInto::try_into(error).expect("should work"), + message: None, + }); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![3, 52, 18, 0, 0, 0]); + assert_eq!( + decoded, + DispatchError::Module(ModuleError { + index: 52, + error: [18, 0, 0, 0], + message: None + }) + ); + + // Example DispatchError::Token + let error = DispatchError::Token(TokenError::UnknownAsset); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![7, 4]); + assert_eq!(decoded, error); + + // Example DispatchError::Arithmetic + let error = DispatchError::Arithmetic(ArithmeticError::Overflow); + let encoded = error.encode(); + let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); + assert_eq!(encoded, vec![8, 1]); + assert_eq!(decoded, error); + }); } } // use enumflags2::BitFlags; diff --git a/runtime/devnet/src/extensions/v0/assets.rs b/runtime/devnet/src/extensions/v0/assets.rs new file mode 100644 index 00000000..912b116f --- /dev/null +++ b/runtime/devnet/src/extensions/v0/assets.rs @@ -0,0 +1,39 @@ +use crate::extensions::{ + AccountId, AssetId, + AssetsKeys::{self, TotalSupply}, + Balance, Compact, Decode, DispatchError, MultiAddress, Runtime, TrustBackedAssetsInstance, +}; + +pub(crate) fn construct_assets_key( + call_index: u8, + params: Vec, +) -> Result { + match call_index { + 0 => { + let id = ::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(TotalSupply(id)) + }, + // other calls + _ => Err(DispatchError::Other("UnknownFunctionId")), + } +} + +pub(crate) fn construct_assets_call( + call_index: u8, + params: Vec, +) -> Result, DispatchError> { + match call_index { + 9 => { + let (id, target, amount) = <(AssetId, AccountId, Balance)>::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(pallet_assets::Call::::transfer_keep_alive { + id: Compact(id), + target: MultiAddress::Id(target), + amount, + }) + }, + // other calls + _ => Err(DispatchError::Other("UnknownFunctionId")), + } +} diff --git a/runtime/devnet/src/extensions/v0/error.rs b/runtime/devnet/src/extensions/v0/error.rs new file mode 100644 index 00000000..b8af2250 --- /dev/null +++ b/runtime/devnet/src/extensions/v0/error.rs @@ -0,0 +1,298 @@ +#[cfg(test)] +use crate::extensions::convert_to_status_code; + +pub(crate) fn handle_unknown_error(encoded_error: &mut [u8; 4]) { + let unknown = match encoded_error[0] { + code if UNIT_ERRORS.contains(&code) => nested_errors(&encoded_error[1..], None), + // Single nested errors with a limit in their nesting. + // + // `TokenError`: has ten variants - translated to a limit of nine. + 7 => nested_errors(&encoded_error[1..], Some(9)), + // `ArithmeticError`: has 3 variants - translated to a limit of two. + 8 => nested_errors(&encoded_error[1..], Some(2)), + // `TransactionalError`: has 2 variants - translated to a limit of one. + 9 => nested_errors(&encoded_error[1..], Some(1)), + code if DOUBLE_NESTED_ERRORS.contains(&code) => nested_errors(&encoded_error[3..], None), + _ => true, + }; + if unknown { + encoded_error[..].rotate_right(1); + encoded_error[0] = 0u8; + } +} + +// Unit `Error` variants. +// (variant: index): +// - CannotLookup: 1, +// - BadOrigin: 2, +// - ConsumerRemaining: 4, +// - NoProviders: 5, +// - TooManyConsumers: 6, +// - Exhausted: 10, +// - Corruption: 11, +// - Unavailable: 12, +// - RootNotAllowed: 13, +// - UnknownFunctionId: 254, +// - DecodingFailed: 255, +const UNIT_ERRORS: [u8; 11] = [1, 2, 4, 5, 6, 10, 11, 12, 13, 254, 255]; + +#[cfg(test)] +const SINGLE_NESTED_ERRORS: [u8; 3] = [7, 8, 9]; + +// Double nested `Error` variants +// (variant: index): +// - Module: 3, +const DOUBLE_NESTED_ERRORS: [u8; 1] = [3]; + +// Checks for unknown nested errors within the `DispatchError`. +// - For single nested errors with a limit, it verifies if the nested value exceeds the limit. +// - For other nested errors, it checks if any subsequent bytes are non-zero. +// +// `nested_error` - The slice of bytes representing the nested error. +// `limit` - An optional limit for single nested errors. +fn nested_errors(nested_error: &[u8], limit: Option) -> bool { + match limit { + Some(l) => nested_error[0] > l || nested_error[1..].iter().any(|&x| x != 0u8), + None => nested_error.iter().any(|&x| x != 0u8), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pop_primitives::error::{ + ArithmeticError::*, + Error::{self, *}, + TokenError::*, + TransactionalError::*, + }; + use sp_runtime::DispatchError; + + // Compare all the different `DispatchError` variants with the expected `Error`. + #[test] + fn dispatch_error_to_error() { + let test_cases = vec![ + ( + DispatchError::Other(""), + (Other { dispatch_error_index: 0, error_index: 0, error: 0 }), + ), + (DispatchError::Other("UnknownFunctionId"), UnknownFunctionId), + (DispatchError::Other("DecodingFailed"), DecodingFailed), + (DispatchError::CannotLookup, CannotLookup), + (DispatchError::BadOrigin, BadOrigin), + ( + DispatchError::Module(sp_runtime::ModuleError { + index: 1, + error: [2, 0, 0, 0], + message: Some("hallo"), + }), + Module { index: 1, error: 2 }, + ), + (DispatchError::ConsumerRemaining, ConsumerRemaining), + (DispatchError::NoProviders, NoProviders), + (DispatchError::TooManyConsumers, TooManyConsumers), + (DispatchError::Token(sp_runtime::TokenError::BelowMinimum), Token(BelowMinimum)), + ( + DispatchError::Arithmetic(sp_runtime::ArithmeticError::Overflow), + Arithmetic(Overflow), + ), + ( + DispatchError::Transactional(sp_runtime::TransactionalError::LimitReached), + Transactional(LimitReached), + ), + (DispatchError::Exhausted, Exhausted), + (DispatchError::Corruption, Corruption), + (DispatchError::Unavailable, Unavailable), + (DispatchError::RootNotAllowed, RootNotAllowed), + ]; + for (dispatch_error, expected) in test_cases { + let status_code = crate::extensions::convert_to_status_code(dispatch_error, 0); + let error: Error = status_code.into(); + assert_eq!(error, expected); + } + } + + // Compare all the different `DispatchError::Other` possibilities with the expected `Error`. + #[test] + fn other_error() { + let test_cases = vec![ + ( + DispatchError::Other("Random"), + (Other { dispatch_error_index: 0, error_index: 0, error: 0 }), + ), + (DispatchError::Other("UnknownFunctionId"), UnknownFunctionId), + (DispatchError::Other("DecodingFailed"), DecodingFailed), + ]; + for (dispatch_error, expected) in test_cases { + let status_code = convert_to_status_code(dispatch_error, 0); + let error: Error = status_code.into(); + assert_eq!(error, expected); + } + } + + // Compare all the different `DispatchError::Module` nesting possibilities, which can not be + // handled, with the expected `Error`. See `double_nested_error_variants` fourth byte nesting. + #[test] + fn test_module_error() { + let test_cases = vec![ + DispatchError::Module(sp_runtime::ModuleError { + index: 1, + error: [2, 2, 0, 0], + message: Some("Random"), + }), + DispatchError::Module(sp_runtime::ModuleError { + index: 1, + error: [2, 2, 2, 0], + message: Some("Random"), + }), + DispatchError::Module(sp_runtime::ModuleError { + index: 1, + error: [2, 2, 2, 2], + message: Some("Random"), + }), + ]; + for dispatch_error in test_cases { + let status_code = convert_to_status_code(dispatch_error, 0); + let error: Error = status_code.into(); + assert_eq!(error, Other { dispatch_error_index: 3, error_index: 1, error: 2 }); + } + } + + // Converts 4 bytes into `Error` and handles unknown errors (used in `convert_to_status_code`). + fn into_error(mut error_bytes: [u8; 4]) -> Error { + handle_unknown_error(&mut error_bytes); + u32::from_le_bytes(error_bytes).into() + } + + // Tests the `handle_unknown_error` for `Error`, version 0. + // + // Unit variants: + // If the encoded value indicates a nested `Error` which is known by V0 as a + // unit variant, the encoded value is converted into `Error::Other`. + // + // Example: the error `BadOrigin` (encoded: `[2, 0, 0, 0]`) with a non-zero value for one + // of the bytes [1..4]: `[2, 0, 1, 0]` is converted into `[0, 2, 0, 1]` (shifting the bits + // one forward). This is decoded to `Error::Other { dispatch_error: 2, index: 0, error: 1 }`. + #[test] + fn unit_error_variants() { + let errors = vec![ + CannotLookup, + BadOrigin, + ConsumerRemaining, + NoProviders, + TooManyConsumers, + Exhausted, + Corruption, + Unavailable, + RootNotAllowed, + UnknownFunctionId, + DecodingFailed, + ]; + // Compare an `Error`, which is converted from an encoded value, with the expected `Error`. + for (i, &error_code) in UNIT_ERRORS.iter().enumerate() { + // No nesting and unit variant correctly returned. + assert_eq!(into_error([error_code, 0, 0, 0]), errors[i]); + // Unexpected second byte nested. + assert_eq!( + into_error([error_code, 1, 0, 0]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 0 }), + ); + // Unexpected third byte nested. + assert_eq!( + into_error([error_code, 1, 1, 0]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }), + ); + // Unexpected fourth byte nested. + assert_eq!( + into_error([error_code, 1, 1, 1]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }), + ); + } + } + + // Single nested variants: + // If the encoded value indicates a double nested `Error` which is known by V0 + // as a single nested variant, the encoded value is converted into `Error::Other`. + // + // Example: the error `Arithmetic(Overflow)` (encoded: `[8, 1, 0, 0]`) with a non-zero + // value for one of the bytes [2..4]: `[8, 1, 1, 0]` is converted into `[0, 8, 1, 1]`. This is + // decoded to `Error::Other { dispatch_error: 8, index: 1, error: 1 }`. + #[test] + fn single_nested_error_variants() { + let errors = vec![ + [Token(FundsUnavailable), Token(OnlyProvider)], + [Arithmetic(Underflow), Arithmetic(Overflow)], + [Transactional(LimitReached), Transactional(NoLayer)], + ]; + // Compare an `Error`, which is converted from an encoded value, with the expected `Error`. + for (i, &error_code) in SINGLE_NESTED_ERRORS.iter().enumerate() { + // No nested and single nested variant correctly returned. + assert_eq!(into_error([error_code, 0, 0, 0]), errors[i][0]); + assert_eq!(into_error([error_code, 1, 0, 0]), errors[i][1]); + // Unexpected third byte nested. + assert_eq!( + into_error([error_code, 1, 1, 0]), + (Other { dispatch_error_index: error_code, error_index: 1, error: 1 }), + ); + // Unexpected fourth byte nested. + assert_eq!( + into_error([error_code, 1, 1, 1]), + Other { dispatch_error_index: error_code, error_index: 1, error: 1 }, + ); + } + } + + #[test] + fn single_nested_unknown_variants() { + // Unknown `TokenError` variant. + assert_eq!( + into_error([7, 10, 0, 0]), + Other { dispatch_error_index: 7, error_index: 10, error: 0 } + ); + // Unknown `Arithmetic` variant. + assert_eq!( + into_error([8, 3, 0, 0]), + Other { dispatch_error_index: 8, error_index: 3, error: 0 } + ); + // Unknown `Transactional` variant. + assert_eq!( + into_error([9, 2, 0, 0]), + Other { dispatch_error_index: 9, error_index: 2, error: 0 } + ); + } + + // Double nested variants: + // If the encoded value indicates a triple nested `Error` which is known by V0 + // as a double nested variant, the encoded value is converted into `Error::Other`. + // + // Example: the error `Module { index: 10, error 5 }` (encoded: `[3, 10, 5, 0]`) with a non-zero + // value for the last byte: `[3, 10, 5, 3]` is converted into `[0, 3, 10, 5]`. This is + // decoded to `Error::Other { dispatch_error: 3, index: 10, error: 5 }`. + #[test] + fn double_nested_error_variants() { + // Compare an `Error`, which is converted from an encoded value, with the expected `Error`. + // No nesting and unit variant correctly returned. + assert_eq!(into_error([3, 0, 0, 0]), Module { index: 0, error: 0 }); + // Allowed single nesting and variant correctly returned. + assert_eq!(into_error([3, 1, 0, 0]), Module { index: 1, error: 0 }); + // Allowed double nesting and variant correctly returned. + assert_eq!(into_error([3, 1, 1, 0]), Module { index: 1, error: 1 }); + // Unexpected fourth byte nested. + assert_eq!( + into_error([3, 1, 1, 1]), + Other { dispatch_error_index: 3, error_index: 1, error: 1 }, + ); + } + + #[test] + fn test_random_encoded_values() { + assert_eq!( + into_error([100, 100, 100, 100]), + Other { dispatch_error_index: 100, error_index: 100, error: 100 } + ); + assert_eq!( + into_error([200, 200, 200, 200]), + Other { dispatch_error_index: 200, error_index: 200, error: 200 } + ); + } +} diff --git a/runtime/devnet/src/extensions/v0/mod.rs b/runtime/devnet/src/extensions/v0/mod.rs new file mode 100644 index 00000000..6406e08f --- /dev/null +++ b/runtime/devnet/src/extensions/v0/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod assets; +pub(crate) mod error; diff --git a/runtime/testnet/Cargo.toml b/runtime/testnet/Cargo.toml index b7aa7b76..b04c3102 100644 --- a/runtime/testnet/Cargo.toml +++ b/runtime/testnet/Cargo.toml @@ -22,7 +22,7 @@ scale-info.workspace = true smallvec.workspace = true # Local -pop-primitives = { workspace = true, features = ["assets", "nfts", "cross-chain"] } +pop-primitives = { workspace = true, features = ["nfts", "cross-chain"] } pop-runtime-common = { workspace = true, default-features = false } # Substrate diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index dd2c52bb..4c224544 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -3,7 +3,7 @@ use frame_support::traits::{Contains, OriginTrait}; use frame_support::{ dispatch::{GetDispatchInfo, RawOrigin}, pallet_prelude::*, - traits::nonfungibles_v2::Inspect as NonFungiblesInspect, + traits::nonfungibles_v2::Inspect, }; use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, @@ -86,7 +86,6 @@ impl TryFrom for v0::FuncId { 0x1 => Self::ReadState, _ => { log::error!("called an unregistered `func_id`: {:}", func_id); - // TODO: Other error. return Err(DispatchError::Other("unimplemented func_id")); }, }; @@ -207,8 +206,6 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, - // TODO: devnet / testnet feature. - _ => Err(DispatchError::Other("Unknown state keys")), }? .encode(); @@ -218,8 +215,7 @@ where ); env.write(&result, false, None).map_err(|e| { log::trace!(target: LOG_TARGET, "{:?}", e); - // TODO: Other error. - DispatchError::Other("Unable to write results to contract memory") + DispatchError::Other("unable to write results to contract memory") }) } @@ -485,7 +481,7 @@ mod tests { log::debug!("result: {:?}", result); } - // Check for revert. + // check for revert assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); assert_eq!(Nfts::owner(collection_id, item_id), Some(BOB.into())); @@ -550,7 +546,7 @@ mod tests { log::debug!("result: {:?}", result); } - // Check for revert with expected error. + // check for revert with expected error let result = result.result.unwrap(); assert!(result.did_revert()); }); @@ -610,7 +606,7 @@ mod tests { log::debug!("result: {:?}", result); } - // Check for revert. + // check for revert assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); }); } @@ -673,7 +669,7 @@ mod tests { log::debug!("result: {:?}", result); } - // Check for revert. + // check for revert assert!( result.result.is_err(), "Contract execution should have failed - unimplemented runtime call!" @@ -735,7 +731,7 @@ mod tests { log::debug!("filtered result: {:?}", result); } - // Check for revert. + // check for revert assert!(!result.result.unwrap().did_revert(), "Contract reverted!"); }); } From 972e4c9e1519279ad351d4d900c65e3a375a6d29 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Fri, 5 Jul 2024 19:13:57 +0200 Subject: [PATCH 17/27] feat: add more interfaces --- pop-api/examples/fungibles/lib.rs | 38 +- pop-api/integration-tests/Cargo.toml | 2 + pop-api/integration-tests/src/lib.rs | 9 +- .../integration-tests/src/local_fungibles.rs | 440 ++++++++++++++---- pop-api/src/v0/assets/fungibles.rs | 19 +- pop-api/src/v0/assets/mod.rs | 140 ++++-- runtime/devnet/src/config/mod.rs | 2 +- runtime/devnet/src/extensions/mod.rs | 45 +- runtime/devnet/src/extensions/v0/assets.rs | 42 +- 9 files changed, 554 insertions(+), 183 deletions(-) diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 03841b74..2abc422c 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -45,19 +45,23 @@ mod fungibles { } #[ink(message)] - pub fn balance_of(&self, id: AssetId, owner: AccountId) -> Balance { + pub fn balance_of(&self, id: AssetId, owner: AccountId) -> Result { api::balance_of(id, owner) } #[ink(message)] - pub fn allowance(&self, id: AssetId, owner: AccountId, spender: AccountId) -> Balance { + pub fn allowance( + &self, + id: AssetId, + owner: AccountId, + spender: AccountId, + ) -> Result { api::allowance(id, owner, spender) } #[ink(message)] pub fn transfer(&self, id: AssetId, to: AccountId, value: Balance) -> Result<()> { - api::transfer(id, to, value)?; - Ok(()) + api::transfer(id, to, value) } #[ink(message)] @@ -70,14 +74,12 @@ mod fungibles { // In the standard a `[u8]`, but the size needs to be known at compile time. _data: Vec, ) -> Result<()> { - api::transfer_from(id, from, to, value)?; - Ok(()) + api::transfer_from(id, from, to, value) } #[ink(message)] pub fn approve(&self, id: AssetId, spender: AccountId, value: Balance) -> Result<()> { - api::approve(id, spender, value)?; - Ok(()) + api::approve(id, spender, value) } #[ink(message)] @@ -87,8 +89,7 @@ mod fungibles { spender: AccountId, value: Balance, ) -> Result<()> { - api::increase_allowance(id, spender, value)?; - Ok(()) + api::increase_allowance(id, spender, value) } #[ink(message)] @@ -98,27 +99,26 @@ mod fungibles { spender: AccountId, value: Balance, ) -> Result<()> { - api::decrease_allowance(id, spender, value)?; - Ok(()) + api::decrease_allowance(id, spender, value) } - // 2. PSP-22 Metadata Interface: - // - token_name - // - token_symbol - // - token_decimals + /// 2. PSP-22 Metadata Interface: + /// - token_name + /// - token_symbol + /// - token_decimals #[ink(message)] - pub fn token_name(&self, id: AssetId) -> Vec { + pub fn token_name(&self, id: AssetId) -> Result> { api::token_name(id) } #[ink(message)] - pub fn token_symbol(&self, id: AssetId) -> Vec { + pub fn token_symbol(&self, id: AssetId) -> Result> { api::token_symbol(id) } #[ink(message)] - pub fn token_decimals(&self, id: AssetId) -> u8 { + pub fn token_decimals(&self, id: AssetId) -> Result { api::token_decimals(id) } diff --git a/pop-api/integration-tests/Cargo.toml b/pop-api/integration-tests/Cargo.toml index c855a884..94c0ba83 100644 --- a/pop-api/integration-tests/Cargo.toml +++ b/pop-api/integration-tests/Cargo.toml @@ -9,6 +9,7 @@ scale = { package = "parity-scale-codec", version = "3.0.0", default-features = frame-support = { version = "29.0.0", default-features = false } frame-system = { version = "29.0.0", default-features = false } pallet-balances = { version = "29.0.2", default-features = false } +pallet-assets = { version = "30.0.0", default-features = false } pallet-contracts = { version = "28.0.0", default-features = false } pop-primitives = { path = "../../primitives", default-features = false, features = ["assets"] } pop-runtime-devnet = { path = "../../runtime/devnet", default-features = false } @@ -22,6 +23,7 @@ std = [ "frame-support/std", "frame-system/std", "pallet-balances/std", + "pallet-assets/std", "pallet-contracts/std", "pop-primitives/std", "pop-runtime-devnet/std", diff --git a/pop-api/integration-tests/src/lib.rs b/pop-api/integration-tests/src/lib.rs index 624c3000..c6732d91 100644 --- a/pop-api/integration-tests/src/lib.rs +++ b/pop-api/integration-tests/src/lib.rs @@ -1,14 +1,19 @@ #![cfg(test)] use frame_support::{ - traits::fungibles::{approvals::Inspect as ApprovalInspect, Inspect}, + traits::fungibles::{ + approvals::Inspect as ApprovalInspect, metadata::Inspect as MetadataInspect, Inspect, + }, weights::Weight, }; use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; use scale::{Decode, Encode}; use sp_runtime::{traits::Hash, AccountId32, BuildStorage, DispatchError}; -use pop_runtime_devnet::{Assets, Contracts, Runtime, RuntimeOrigin, System, UNIT}; +use pop_runtime_devnet::{ + config::assets::TrustBackedAssetsInstance, Assets, Contracts, Runtime, RuntimeOrigin, System, + UNIT, +}; mod local_fungibles; diff --git a/pop-api/integration-tests/src/local_fungibles.rs b/pop-api/integration-tests/src/local_fungibles.rs index 968c43eb..d0229c84 100644 --- a/pop-api/integration-tests/src/local_fungibles.rs +++ b/pop-api/integration-tests/src/local_fungibles.rs @@ -10,10 +10,27 @@ const ASSET_ID: AssetId = 1; fn decoded(result: ExecReturnValue) -> T { match ::decode(&mut &result.data[2..]) { Ok(value) => value, - Err(_) => panic!("\nTest failed by trying to decode result: {:?} into `T`\n", result), + Err(_) => panic!("\nTest failed by trying to decode `{:?}` into `T`\n", result), } } +// Call total_supply contract message. +fn total_supply(addr: AccountId32, asset_id: AssetId) -> Balance { + let function = function_selector("total_supply"); + let params = [function, asset_id.encode()].concat(); + let result = do_bare_call(addr, params, 0).expect("should work"); + decoded::(result) +} + +// Call balance_of contract message. +fn balance_of(addr: AccountId32, asset_id: AssetId, owner: AccountId32) -> Balance { + let function = function_selector("balance_of"); + let params = [function, asset_id.encode(), owner.encode()].concat(); + let result = do_bare_call(addr, params, 0).expect("should work"); + decoded::(result) +} + +// Call allowance contract message. fn allowance( addr: AccountId32, asset_id: AssetId, @@ -26,20 +43,28 @@ fn allowance( decoded::(result) } -// Call balance_of contract message. -fn balance_of(addr: AccountId32, asset_id: AssetId, owner: AccountId32) -> Balance { - let function = function_selector("balance_of"); - let params = [function, asset_id.encode(), owner.encode()].concat(); +// Call token_name contract message. +fn token_name(addr: AccountId32, asset_id: AssetId) -> Vec { + let function = function_selector("token_name"); + let params = [function, asset_id.encode()].concat(); let result = do_bare_call(addr, params, 0).expect("should work"); - decoded::(result) + decoded::>(result) } -// Call total_supply contract message. -fn total_supply(addr: AccountId32, asset_id: AssetId) -> Balance { - let function = function_selector("total_supply"); +// Call token_symbol contract message. +fn token_symbol(addr: AccountId32, asset_id: AssetId) -> Vec { + let function = function_selector("token_symbol"); let params = [function, asset_id.encode()].concat(); let result = do_bare_call(addr, params, 0).expect("should work"); - decoded::(result) + decoded::>(result) +} + +// Call token_decimals contract message. +fn token_decimals(addr: AccountId32, asset_id: AssetId) -> u8 { + let function = function_selector("token_decimals"); + let params = [function, asset_id.encode()].concat(); + let result = do_bare_call(addr, params, 0).expect("should work"); + decoded::(result) } fn asset_exists(addr: AccountId32, asset_id: AssetId) -> bool { @@ -82,7 +107,6 @@ fn transfer( let function = function_selector("transfer"); let params = [function, asset_id.encode(), to.encode(), value.encode()].concat(); let result = do_bare_call(addr, params, 0).expect("should work"); - println!("Transfer result: {:?}", result); result } @@ -101,6 +125,18 @@ fn transfer_from( do_bare_call(addr, params, 0).expect("should work") } +fn increase_allowance( + addr: AccountId32, + asset_id: AssetId, + spender: AccountId32, + value: Balance, +) -> ExecReturnValue { + let function = function_selector("increase_allowance"); + let params = [function, asset_id.encode(), spender.encode(), value.encode()].concat(); + let result = do_bare_call(addr, params, 0).expect("should work"); + result +} + fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { assert_eq!( Assets::create( @@ -154,20 +190,88 @@ fn create_asset_mint_and_approve( } // Freeze an asset. -fn freeze_asset(asset_id: AssetId, owner: AccountId32) { +fn freeze_asset(owner: AccountId32, asset_id: AssetId) { assert_eq!(Assets::freeze_asset(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); } // Thaw an asset. -fn thaw_asset(asset_id: AssetId, owner: AccountId32) { +fn thaw_asset(owner: AccountId32, asset_id: AssetId) { assert_eq!(Assets::thaw_asset(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); } // Start destroying an asset. -fn start_destroy_asset(asset_id: AssetId, owner: AccountId32) { +fn start_destroy_asset(owner: AccountId32, asset_id: AssetId) { assert_eq!(Assets::start_destroy(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); } +// Create an asset and set metadata. +fn create_asset_and_set_metadata( + owner: AccountId32, + asset_id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) { + assert_eq!( + Assets::create( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + owner.clone().into(), + 100 + ), + Ok(()) + ); + set_metadata_asset(owner, asset_id, name, symbol, decimals); +} + +// Set metadata of an asset. +fn set_metadata_asset( + owner: AccountId32, + asset_id: AssetId, + name: Vec, + symbol: Vec, + decimals: u8, +) { + assert_eq!( + Assets::set_metadata( + RuntimeOrigin::signed(owner.into()), + asset_id.into(), + name, + symbol, + decimals + ), + Ok(()) + ); +} + +fn token_name_asset(asset_id: AssetId) -> Vec { + as MetadataInspect>::name( + asset_id, + ) +} + +fn token_symbol_asset(asset_id: AssetId) -> Vec { + as MetadataInspect>::symbol( + asset_id, + ) +} + +fn token_decimals_asset(asset_id: AssetId) -> u8 { + as MetadataInspect>::decimals( + asset_id, + ) +} + +/// 1. PSP-22 Interface: +/// - total_supply +/// - balance_of +/// - allowance +/// - transfer +/// - transfer_from +/// - approve +/// - increase_allowance +/// - decrease_allowance + #[test] #[ignore] fn total_supply_works() { @@ -181,10 +285,12 @@ fn total_supply_works() { // No tokens in circulation. assert_eq!(Assets::total_supply(ASSET_ID), total_supply(addr.clone(), ASSET_ID)); + assert_eq!(0, total_supply(addr.clone(), ASSET_ID)); // Tokens in circulation. create_asset_and_mint_to(addr.clone(), ASSET_ID, BOB, 100); - assert_eq!(Assets::total_supply(ASSET_ID), total_supply(addr, ASSET_ID)); + assert_eq!(Assets::total_supply(ASSET_ID), total_supply(addr.clone(), ASSET_ID)); + assert_eq!(100, total_supply(addr, ASSET_ID)); }); } @@ -198,10 +304,12 @@ fn balance_of_works() { // No tokens in circulation. assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr.clone(), ASSET_ID, BOB)); + assert_eq!(0, balance_of(addr.clone(), ASSET_ID, BOB)); // Tokens in circulation. create_asset_and_mint_to(addr.clone(), ASSET_ID, BOB, 100); - assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr, ASSET_ID, BOB)); + assert_eq!(Assets::balance(ASSET_ID, BOB), balance_of(addr.clone(), ASSET_ID, BOB)); + assert_eq!(100, balance_of(addr, ASSET_ID, BOB)); }); } @@ -218,90 +326,240 @@ fn allowance_works() { Assets::allowance(ASSET_ID, &BOB, &ALICE), allowance(addr.clone(), ASSET_ID, BOB, ALICE) ); + assert_eq!(0, allowance(addr.clone(), ASSET_ID, BOB, ALICE)); // Tokens in circulation. create_asset_mint_and_approve(addr.clone(), ASSET_ID, BOB, 100, ALICE, 50); assert_eq!( Assets::allowance(ASSET_ID, &BOB, &ALICE), - allowance(addr, ASSET_ID, BOB, ALICE) + allowance(addr.clone(), ASSET_ID, BOB, ALICE) ); + assert_eq!(50, allowance(addr, ASSET_ID, BOB, ALICE)); }); } #[test] #[ignore] -fn asset_exists_works() { +fn transfer_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); + let amount: Balance = 100 * UNIT; - // No tokens in circulation. - assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr.clone(), ASSET_ID)); - - // Tokens in circulation. - create_asset(addr.clone(), ASSET_ID, 1); - assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr, ASSET_ID)); + // Asset does not exist. + assert_eq!( + decoded::(transfer(addr.clone(), 1, BOB, amount,)), + Module { index: 52, error: 3 }, + ); + // Create asset with Alice as owner and mint `amount` to contract address. + let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(ALICE, asset); + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount,)), + Module { index: 52, error: 16 }, + ); + thaw_asset(ALICE, asset); + // Not enough balance. + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), + Module { index: 52, error: 0 }, + ); + // Not enough balance due to ED. + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount)), + Module { index: 52, error: 0 }, + ); + // Successful transfer. + let bob_balance_before_mint = Assets::balance(asset, &BOB); + let result = transfer(addr.clone(), asset, BOB, amount / 2); + assert!(!result.did_revert(), "Contract reverted!"); + let bob_balance_after_mint = Assets::balance(asset, &BOB); + assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); + // Transfer asset to account that does not exist. + assert_eq!( + decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), + Token(CannotCreate) + ); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(ALICE, asset); + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), + Module { index: 52, error: 16 }, + ); }); } #[test] #[ignore] -fn create_works() { +fn increase_allowance_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let new_asset = 2; - // Instantiate a contract without balance (relay token). - let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); - // No balance to pay for fees. + let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![]); + let amount: Balance = 100 * UNIT; + let asset = 0; + create_asset_and_mint_to(ALICE, asset, addr.clone(), amount); assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), - Module { index: 10, error: 2 }, + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + ConsumerRemaining ); - // Instantiate a contract without balance (relay token). - let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 100, vec![2]); - // TODO: make sure it has enough for the fees but not for the deposit. - // No balance to pay fe deposit. + + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); + // Asset does not exist. + let asset = 1; assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), - Module { index: 10, error: 2 }, + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + Module { index: 52, error: 3 }, ); - // Instantiate a contract with balance. + // Create asset with Alice as owner and mint `amount` to contract address. + create_asset_and_mint_to(ALICE, asset, addr.clone(), amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(ALICE, asset); + assert_eq!( + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + Module { index: 52, error: 16 }, + ); + thaw_asset(ALICE, asset); + // Successful approval. + assert_eq!(0, Assets::allowance(asset, &addr, &BOB)); + assert!( + !increase_allowance(addr.clone(), asset, BOB, amount).did_revert(), + "Contract reverted!" + ); + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount); + // Additive. + assert!( + !increase_allowance(addr.clone(), asset, BOB, amount).did_revert(), + "Contract reverted!" + ); + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount * 2); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(ALICE, asset); + assert_eq!( + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + Module { index: 52, error: 16 }, + ); + }); +} + +#[test] +#[ignore] +fn transfer_from_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); - create_asset(ALICE, ASSET_ID, 1); - // Asset ID is already taken. + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); + let amount: Balance = 100 * UNIT; + + // Asset does not exist. assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), - Module { index: 52, error: 5 }, + decoded::(transfer(addr.clone(), 1, BOB, amount,)), + Module { index: 52, error: 3 }, ); - // The minimal balance for an asset must be non zero. + // Create asset with Alice as owner and mint `amount` to contract address. + let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); + // Asset is not live, i.e. frozen or being destroyed. + freeze_asset(ALICE, asset); assert_eq!( - decoded::(create(addr.clone(), new_asset, BOB, 0)), - Module { index: 52, error: 7 }, + decoded::(transfer(addr.clone(), asset, BOB, amount,)), + Module { index: 52, error: 16 }, ); - let result = create(addr.clone(), new_asset, BOB, 1); + thaw_asset(ALICE, asset); + // Not enough balance. + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), + Module { index: 52, error: 0 }, + ); + // Not enough balance due to ED. + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount)), + Module { index: 52, error: 0 }, + ); + // Successful transfer. + let bob_balance_before_mint = Assets::balance(asset, &BOB); + let result = transfer(addr.clone(), asset, BOB, amount / 2); assert!(!result.did_revert(), "Contract reverted!"); + let bob_balance_after_mint = Assets::balance(asset, &BOB); + assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); + // Transfer asset to account that does not exist. + assert_eq!( + decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), + Token(CannotCreate) + ); + // Asset is not live, i.e. frozen or being destroyed. + start_destroy_asset(ALICE, asset); + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), + Module { index: 52, error: 16 }, + ); }); } +/// 2. PSP-22 Metadata Interface: +/// - token_name +/// - token_symbol +/// - token_decimals + #[test] #[ignore] -fn set_metadata_works() { +fn token_metadata_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = instantiate( + "../../pop-api/examples/fungibles/target/ink/fungibles.wasm", + INIT_VALUE, + vec![], + ); + + let name: Vec = vec![11, 12, 13]; + let symbol: Vec = vec![21, 22, 23]; + let decimals: u8 = 69; + // Token does not exist. + assert_eq!(token_name_asset(ASSET_ID), token_name(addr.clone(), ASSET_ID)); + assert_eq!(Vec::::new(), token_name(addr.clone(), ASSET_ID)); + assert_eq!(token_symbol_asset(ASSET_ID), token_symbol(addr.clone(), ASSET_ID)); + assert_eq!(Vec::::new(), token_symbol(addr.clone(), ASSET_ID)); + assert_eq!(token_decimals_asset(ASSET_ID), token_decimals(addr.clone(), ASSET_ID)); + assert_eq!(0, token_decimals(addr.clone(), ASSET_ID)); + + create_asset_and_set_metadata( + addr.clone(), + ASSET_ID, + name.clone(), + symbol.clone(), + decimals, + ); + assert_eq!(token_name_asset(ASSET_ID), token_name(addr.clone(), ASSET_ID)); + assert_eq!(name, token_name(addr.clone(), ASSET_ID)); + assert_eq!(token_symbol_asset(ASSET_ID), token_symbol(addr.clone(), ASSET_ID)); + assert_eq!(symbol, token_symbol(addr.clone(), ASSET_ID)); + assert_eq!(token_decimals_asset(ASSET_ID), token_decimals(addr.clone(), ASSET_ID)); + assert_eq!(decimals, token_decimals(addr.clone(), ASSET_ID)); + }); +} + +#[test] +#[ignore] +fn asset_exists_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); + // No tokens in circulation. + assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr.clone(), ASSET_ID)); + + // Tokens in circulation. create_asset(addr.clone(), ASSET_ID, 1); - let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); - assert!(!result.did_revert(), "Contract reverted!"); + assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr, ASSET_ID)); }); } #[test] #[ignore] -fn transfer_from_mint_works() { +fn mint_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); let addr = @@ -326,12 +584,12 @@ fn transfer_from_mint_works() { ); let asset = create_asset(addr.clone(), 2, 2); // Asset is not live, i.e. frozen or being destroyed. - freeze_asset(asset, addr.clone()); + freeze_asset(addr.clone(), asset); assert_eq!( decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), Module { index: 52, error: 16 }, ); - thaw_asset(asset, addr.clone()); + thaw_asset(addr.clone(), asset); // Successful mint. let bob_balance_before_mint = Assets::balance(asset, &BOB); let result = transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8]); @@ -351,7 +609,7 @@ fn transfer_from_mint_works() { Arithmetic(Overflow) ); // Asset is not live, i.e. frozen or being destroyed. - start_destroy_asset(asset, addr.clone()); + start_destroy_asset(addr.clone(), asset); assert_eq!( decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), Module { index: 52, error: 16 }, @@ -361,53 +619,53 @@ fn transfer_from_mint_works() { #[test] #[ignore] -fn transfer_works() { +fn create_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); - let amount: Balance = 100 * UNIT; - - // Asset does not exist. + // Instantiate a contract without balance (relay token). + let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); + // No balance to pay for fees. assert_eq!( - decoded::(transfer(addr.clone(), 1, BOB, amount,)), - Module { index: 52, error: 3 }, + decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), + Module { index: 10, error: 2 }, ); - // Create asset with Alice as owner and mint `amount` to contract address. - let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); - // Asset is not live, i.e. frozen or being destroyed. - freeze_asset(asset, ALICE); + // Instantiate a contract without balance (relay token). + let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 100, vec![2]); + // No balance to pay the deposit. assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount,)), - Module { index: 52, error: 16 }, + decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), + Module { index: 10, error: 2 }, ); - thaw_asset(asset, ALICE); - // Not enough balance. + // Instantiate a contract with balance. + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), - Module { index: 52, error: 0 }, + decoded::(create(addr.clone(), ASSET_ID, BOB, 0)), + Module { index: 52, error: 7 }, ); - // Not enough balance due to ED. + create_asset(ALICE, ASSET_ID, 1); + // Asset ID is already taken. assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount)), - Module { index: 52, error: 0 }, + decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), + Module { index: 52, error: 5 }, ); - // Successful transfer. - let bob_balance_before_mint = Assets::balance(asset, &BOB); - let result = transfer(addr.clone(), asset, BOB, amount / 2); + // The minimal balance for an asset must be non zero. + let new_asset = 2; + let result = create(addr.clone(), new_asset, BOB, 1); + assert!(!result.did_revert(), "Contract reverted!"); + }); +} + +#[test] +#[ignore] +fn set_metadata_works() { + new_test_ext().execute_with(|| { + let _ = env_logger::try_init(); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); + + create_asset(addr.clone(), ASSET_ID, 1); + let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); assert!(!result.did_revert(), "Contract reverted!"); - let bob_balance_after_mint = Assets::balance(asset, &BOB); - assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); - // Transfer asset to account that does not exist. - assert_eq!( - decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), - Token(CannotCreate) - ); - // Asset is not live, i.e. frozen or being destroyed. - start_destroy_asset(asset, ALICE); - assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), - Module { index: 52, error: 16 }, - ); }); } diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index 8d0de768..5325cad3 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -39,7 +39,7 @@ pub fn total_supply(id: AssetId) -> Result { /// # Returns /// The balance of the specified account, or an error if the operation fails. #[inline] -pub fn balance_of(id: AssetId, owner: AccountId) -> Balance { +pub fn balance_of(id: AssetId, owner: AccountId) -> Result { assets::balance_of(id, owner) } @@ -54,7 +54,7 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Balance { /// # Returns /// The remaining allowance, or an error if the operation fails. #[inline] -pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Balance { +pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { assets::allowance(id, owner, spender) } @@ -101,6 +101,7 @@ pub fn transfer_from(id: AssetId, from: AccountId, to: AccountId, value: Balance /// Returns `Ok(())` if successful, or an error if the approval fails. #[inline] pub fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { + assets::cancel_approval(id, spender)?; assets::approve_transfer(id, spender, value) } @@ -128,9 +129,11 @@ pub fn increase_allowance(id: AssetId, spender: AccountId, value: Balance) -> Re /// # Returns /// Returns `Ok(())` if successful, or an error if the operation fails. #[inline] -pub fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { - assets::cancel_approval(id, spender.clone())?; - assets::approve_transfer(id, spender, value) +pub fn decrease_allowance(_id: AssetId, _spender: AccountId, _value: Balance) -> Result<()> { + // let allowance = assets::allowance(id, owner, spender)?; + // assets::cancel_approval(id, spender.clone())?; + // assets::approve_transfer(id, spender, value) + Ok(()) } /// 2. PSP-22 Metadata Interface: @@ -146,7 +149,7 @@ pub fn decrease_allowance(id: AssetId, spender: AccountId, value: Balance) -> Re /// # Returns /// The name of the token as a byte vector, or an error if the operation fails. #[inline] -pub fn token_name(id: AssetId) -> Vec { +pub fn token_name(id: AssetId) -> Result> { assets::token_name(id) } @@ -158,7 +161,7 @@ pub fn token_name(id: AssetId) -> Vec { /// # Returns /// The symbol of the token as a byte vector, or an error if the operation fails. #[inline] -pub fn token_symbol(id: AssetId) -> Vec { +pub fn token_symbol(id: AssetId) -> Result> { assets::token_symbol(id) } @@ -170,7 +173,7 @@ pub fn token_symbol(id: AssetId) -> Vec { /// # Returns /// The number of decimals of the token as a byte vector, or an error if the operation fails. #[inline] -pub fn token_decimals(id: AssetId) -> u8 { +pub fn token_decimals(id: AssetId) -> Result { assets::token_decimals(id) } diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 22657323..d14c3322 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -26,8 +26,11 @@ const TRANSFER_KEEP_ALIVE: u8 = 9; /// - set_metadata /// - clear_metadata /// - approve_transfer +const APPROVE_TRANSFER: u8 = 22; /// - cancel_approval +const CANCEL_APPROVAL: u8 = 23; /// - transfer_approved +const TRANSFER_APPROVED: u8 = 25; /// Issue a new class of fungible assets from a public origin. // pub(crate) fn create( @@ -91,7 +94,7 @@ pub fn transfer(id: AssetId, target: AccountId, amount: Balance) -> Result<()> { VERSION, DISPATCH, ASSETS_MODULE, - // TODO: E.D. is always respected with transferring tokens via the API. + // E.D. is always respected with transferring tokens via the API. TRANSFER_KEEP_ALIVE, ])) .input::<(AssetId, AccountId, Balance)>() @@ -131,21 +134,31 @@ pub fn transfer(id: AssetId, target: AccountId, amount: Balance) -> Result<()> { /// Approve an amount of asset for transfer by a delegated third-party account. #[inline] pub fn approve_transfer(id: AssetId, delegate: AccountId, amount: Balance) -> Result<()> { - ChainExtensionMethod::build(u32::from_le_bytes([0u8, 0, 52, 69])) - .input::<(AssetId, AccountId, Balance)>() - .output::, true>() - .handle_error_code::() - .call(&(id, delegate, amount)) + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + DISPATCH, + ASSETS_MODULE, + APPROVE_TRANSFER, + ])) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, delegate, amount)) } /// Cancel all of some asset approved for delegated transfer by a third-party account. #[inline] pub fn cancel_approval(id: AssetId, delegate: AccountId) -> Result<()> { - ChainExtensionMethod::build(0) - .input::<(AssetId, AccountId)>() - .output::, true>() - .handle_error_code::() - .call(&(id, delegate)) + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + DISPATCH, + ASSETS_MODULE, + CANCEL_APPROVAL, + ])) + .input::<(AssetId, AccountId)>() + .output::, true>() + .handle_error_code::() + .call(&(id, delegate)) } /// Transfer some asset balance from a previously delegated account to some third-party @@ -157,23 +170,33 @@ pub fn transfer_approved( to: AccountId, amount: Balance, ) -> Result<()> { - ChainExtensionMethod::build(0) - .input::<(AssetId, AccountId, AccountId, Balance)>() - .output::, true>() - .handle_error_code::() - .call(&(id, from, to, amount)) + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + DISPATCH, + ASSETS_MODULE, + TRANSFER_APPROVED, + ])) + .input::<(AssetId, AccountId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, from, to, amount)) } -/// 2. Read state functions +/// 2. Read state functions: const READ_STATE: u8 = 1; /// - total_supply const TOTAL_SUPPLY: u8 = 0; /// - balance_of +const BALANCE_OF: u8 = 1; /// - allowance -/// - asset_exists +const ALLOWANCE: u8 = 2; /// - token_name +const TOKEN_NAME: u8 = 3; /// - token_symbol +const TOKEN_SYMBOL: u8 = 4; /// - token_decimals +const TOKEN_DECIMALS: u8 = 5; +/// - asset_exists #[inline] pub fn total_supply(id: AssetId) -> Result { @@ -191,48 +214,73 @@ pub fn total_supply(id: AssetId) -> Result { } #[inline] -pub fn balance_of(id: AssetId, owner: AccountId) -> Balance { - ChainExtensionMethod::build(1) - .input::<(AssetId, AccountId)>() - .output::() - .ignore_error_code() - .call(&(id, owner)) +pub fn balance_of(id: AssetId, owner: AccountId) -> Result { + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + READ_STATE, + ASSETS_MODULE, + BALANCE_OF, + ])) + .input::<(AssetId, AccountId)>() + .output::>, true>() + .handle_error_code::() + .call(&(id, owner)) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) } #[inline] -pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Balance { - ChainExtensionMethod::build(1) +pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { + ChainExtensionMethod::build(u32::from_le_bytes([VERSION, READ_STATE, ASSETS_MODULE, ALLOWANCE])) .input::<(AssetId, AccountId, AccountId)>() - .output::() - .ignore_error_code() + .output::>, true>() + .handle_error_code::() .call(&(id, owner, spender)) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) } #[inline] -pub fn token_name(id: AssetId) -> Vec { - ChainExtensionMethod::build(1) - .input::() - .output::, false>() - .ignore_error_code() - .call(&(id)) +pub fn token_name(id: AssetId) -> Result> { + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + READ_STATE, + ASSETS_MODULE, + TOKEN_NAME, + ])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) } // #[inline] -pub fn token_symbol(id: AssetId) -> Vec { - ChainExtensionMethod::build(1) - .input::() - .output::, false>() - .ignore_error_code() - .call(&(id)) +pub fn token_symbol(id: AssetId) -> Result> { + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + READ_STATE, + ASSETS_MODULE, + TOKEN_SYMBOL, + ])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) } #[inline] -pub fn token_decimals(id: AssetId) -> u8 { - ChainExtensionMethod::build(1) - .input::() - .output::() - .ignore_error_code() - .call(&(id)) +pub fn token_decimals(id: AssetId) -> Result { + ChainExtensionMethod::build(u32::from_le_bytes([ + VERSION, + READ_STATE, + ASSETS_MODULE, + TOKEN_DECIMALS, + ])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| ::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) } // pub(crate) fn asset_exists(id: AssetId) -> Result { diff --git a/runtime/devnet/src/config/mod.rs b/runtime/devnet/src/config/mod.rs index c370bb1d..e0aaa3a1 100644 --- a/runtime/devnet/src/config/mod.rs +++ b/runtime/devnet/src/config/mod.rs @@ -1,4 +1,4 @@ -pub(crate) mod assets; +pub mod assets; mod contracts; mod proxy; // Public due to integration tests crate. diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index ac52d5bd..8f0a6eda 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -5,7 +5,7 @@ use frame_support::{ dispatch::{GetDispatchInfo, RawOrigin}, pallet_prelude::*, traits::{ - fungibles::approvals::Inspect as ApprovalInspect, + fungibles::{approvals::Inspect as ApprovalInspect, metadata::Inspect as MetadataInspect}, nonfungibles_v2::Inspect as NonFungiblesInspect, }, }; @@ -129,8 +129,7 @@ where E: Ext, { const LOG_PREFIX: &str = " dispatch |"; - let call = construct_call(version, pallet_index, call_index, params) - .map_err(|_| DispatchError::Other("DecodingFailed"))?; + let call = construct_call(version, pallet_index, call_index, params)?; // Contract is the origin by default. let origin: RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into(); dispatch_call::(env, call, origin, LOG_PREFIX) @@ -434,6 +433,15 @@ where T: frame_system::Config, { match key { + TotalSupply(id) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::total_supply(id).encode()) + }, + BalanceOf(id, owner) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok(pallet_assets::Pallet::::balance(id, &owner.0.into()) + .encode()) + }, Allowance(id, owner, spender) => { env.charge_weight(T::DbWeight::get().reads(1_u64))?; Ok(pallet_assets::Pallet::::allowance( @@ -443,20 +451,31 @@ where ) .encode()) }, - // AssetsKeys::AssetExists(id) => { - // env.charge_weight(T::DbWeight::get().reads(1_u64))?; - // Ok(pallet_assets::Pallet::::asset_exists(id).encode()) - // }, - BalanceOf(id, owner) => { + TokenName(id) => { env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_assets::Pallet::::balance(id, &owner.0.into()) - .encode()) + Ok( as MetadataInspect< + AccountId, + >>::name(id) + .encode()) }, - TotalSupply(id) => { + TokenSymbol(id) => { env.charge_weight(T::DbWeight::get().reads(1_u64))?; - Ok(pallet_assets::Pallet::::total_supply(id).encode()) + Ok( as MetadataInspect< + AccountId, + >>::symbol(id) + .encode()) }, - _ => todo!(), + TokenDecimals(id) => { + env.charge_weight(T::DbWeight::get().reads(1_u64))?; + Ok( as MetadataInspect< + AccountId, + >>::decimals(id) + .encode()) + }, + // AssetsKeys::AssetExists(id) => { + // env.charge_weight(T::DbWeight::get().reads(1_u64))?; + // Ok(pallet_assets::Pallet::::asset_exists(id).encode()) + // }, } } diff --git a/runtime/devnet/src/extensions/v0/assets.rs b/runtime/devnet/src/extensions/v0/assets.rs index 912b116f..407b0d55 100644 --- a/runtime/devnet/src/extensions/v0/assets.rs +++ b/runtime/devnet/src/extensions/v0/assets.rs @@ -1,8 +1,9 @@ use crate::extensions::{ - AccountId, AssetId, - AssetsKeys::{self, TotalSupply}, + AccountId as AccountId32, AssetId, + AssetsKeys::{self, *}, Balance, Compact, Decode, DispatchError, MultiAddress, Runtime, TrustBackedAssetsInstance, }; +use pop_primitives::AccountId; pub(crate) fn construct_assets_key( call_index: u8, @@ -14,6 +15,31 @@ pub(crate) fn construct_assets_key( .map_err(|_| DispatchError::Other("DecodingFailed"))?; Ok(TotalSupply(id)) }, + 1 => { + let (id, owner) = <(AssetId, AccountId)>::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(BalanceOf(id, owner)) + }, + 2 => { + let (id, owner, spender) = <(AssetId, AccountId, AccountId)>::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(Allowance(id, owner, spender)) + }, + 3 => { + let id = ::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(TokenName(id)) + }, + 4 => { + let id = ::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(TokenSymbol(id)) + }, + 5 => { + let id = ::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(TokenDecimals(id)) + }, // other calls _ => Err(DispatchError::Other("UnknownFunctionId")), } @@ -25,7 +51,7 @@ pub(crate) fn construct_assets_call( ) -> Result, DispatchError> { match call_index { 9 => { - let (id, target, amount) = <(AssetId, AccountId, Balance)>::decode(&mut ¶ms[..]) + let (id, target, amount) = <(AssetId, AccountId32, Balance)>::decode(&mut ¶ms[..]) .map_err(|_| DispatchError::Other("DecodingFailed"))?; Ok(pallet_assets::Call::::transfer_keep_alive { id: Compact(id), @@ -33,6 +59,16 @@ pub(crate) fn construct_assets_call( amount, }) }, + 22 => { + let (id, delegate, amount) = + <(AssetId, AccountId32, Balance)>::decode(&mut ¶ms[..]) + .map_err(|_| DispatchError::Other("DecodingFailed"))?; + Ok(pallet_assets::Call::::approve_transfer { + id: Compact(id), + delegate: MultiAddress::Id(delegate), + amount, + }) + }, // other calls _ => Err(DispatchError::Other("UnknownFunctionId")), } From 47e2ea6770d0b6fe8fe5b611570cdfa772ed4c04 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Fri, 5 Jul 2024 23:49:03 +0200 Subject: [PATCH 18/27] refactor: final bits --- pop-api/src/v0/assets/fungibles.rs | 10 +++++----- pop-api/src/v0/assets/mod.rs | 17 ++--------------- runtime/devnet/src/extensions/mod.rs | 1 + runtime/devnet/src/extensions/v0/assets.rs | 1 + runtime/testnet/src/extensions.rs | 1 + 5 files changed, 10 insertions(+), 20 deletions(-) diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index 5325cad3..4abd46a6 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -70,7 +70,7 @@ pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result Result<()> { - assets::transfer(id, to, value) + assets::transfer_keep_alive(id, to, value) } /// Transfers `value` tokens on behalf of `from` to account `to` with additional `data` @@ -279,7 +279,6 @@ pub fn token_decimals(id: AssetId) -> Result { // assets::asset_exists(id) // } -// TODO: further implement the rest of the interfaces and conclude on the FungiblesError. #[derive(Debug, PartialEq, Eq)] #[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum FungiblesError { @@ -300,13 +299,14 @@ pub enum FungiblesError { NoPermission, /// The given asset ID is unknown. Unknown, - // - Originally `InsufficientBalance` for the deposit but this would result in the same error - // as the error when there is insufficient balance for transferring an asset. /// No balance for creation of assets or fees. + // + // Originally `pallet_balances::Error::InsufficientBalance` but collides with the + // `InsufficientBalance` error that is used for `pallet_assets::Error::BalanceLow` to adhere to + // standard. NoBalance, } -// TODO: include conversions from TokenError and add conversions based on added interfaces. impl From for FungiblesError { fn from(value: StatusCode) -> Self { let encoded = value.0.to_le_bytes(); diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index d14c3322..ea8991a7 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -87,9 +87,9 @@ const TRANSFER_APPROVED: u8 = 25; // })) // } -/// Move some assets from the sender account to another. +/// Move some assets from the sender account to another, keeping the sender account alive. #[inline] -pub fn transfer(id: AssetId, target: AccountId, amount: Balance) -> Result<()> { +pub fn transfer_keep_alive(id: AssetId, target: AccountId, amount: Balance) -> Result<()> { ChainExtensionMethod::build(u32::from_le_bytes([ VERSION, DISPATCH, @@ -103,19 +103,6 @@ pub fn transfer(id: AssetId, target: AccountId, amount: Balance) -> Result<()> { .call(&(id, target, amount)) } -// /// Move some assets from the sender account to another, keeping the sender account alive. -// pub(crate) fn transfer_keep_alive( -// id: AssetId, -// target: impl Into>, -// amount: Balance, -// ) -> Result<()> { -// dispatch(RuntimeCall::Assets(AssetsCall::TransferKeepAlive { -// id: id.into(), -// target: target.into(), -// amount: Compact(amount), -// })) -// } - // /// Set the metadata for an asset. // pub(crate) fn set_metadata( // id: AssetId, diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index 8f0a6eda..aa58bcea 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -304,6 +304,7 @@ where // - `error`: The `DispatchError` encountered during contract execution. // - `version`: The version of the chain extension, used to determine the known errors. pub(crate) fn convert_to_status_code(error: DispatchError, version: u8) -> u32 { + use sp_std::vec; // "UnknownFunctionId" and "DecodingFailed" are mapped to specific errors in the API and will // never change. let mut encoded_error = match error { diff --git a/runtime/devnet/src/extensions/v0/assets.rs b/runtime/devnet/src/extensions/v0/assets.rs index 407b0d55..c6b15b4e 100644 --- a/runtime/devnet/src/extensions/v0/assets.rs +++ b/runtime/devnet/src/extensions/v0/assets.rs @@ -4,6 +4,7 @@ use crate::extensions::{ Balance, Compact, Decode, DispatchError, MultiAddress, Runtime, TrustBackedAssetsInstance, }; use pop_primitives::AccountId; +use sp_std::vec::Vec; pub(crate) fn construct_assets_key( call_index: u8, diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index 4c224544..a5eeb3c3 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -206,6 +206,7 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, + _ => Ok(vec![0]), }? .encode(); From 9dcfccbe414ef4de57d12e59db6841fcbed9eeee Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Sat, 6 Jul 2024 10:05:17 +0200 Subject: [PATCH 19/27] fix: compiling --- Cargo.lock | 46 +++++++++++++++++++--------- Cargo.toml | 14 ++++----- runtime/devnet/src/extensions/mod.rs | 1 - runtime/testnet/src/extensions.rs | 2 +- 4 files changed, 40 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cf7abf73..e0c87955 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -426,9 +426,9 @@ checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" [[package]] name = "asset-hub-rococo-runtime" -version = "0.12.0" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e80dcb69497d50ceef11a046720e1c5a0feeb5575239c5ccb4b0be14a49bcfa" +checksum = "af52c4d3011936f615f3469b3c20f8b13b861f4c06d097bc1922200ce44781d9" dependencies = [ "assets-common", "bp-asset-hub-rococo", @@ -445,6 +445,7 @@ dependencies = [ "cumulus-primitives-utility", "frame-benchmarking", "frame-executive", + "frame-metadata-hash-extension", "frame-support", "frame-system", "frame-system-benchmarking", @@ -3747,6 +3748,22 @@ dependencies = [ "serde", ] +[[package]] +name = "frame-metadata-hash-extension" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bb1eec9eb46d3e016c95b2fa875118c04609f2150013c56a894cae00581e265" +dependencies = [ + "array-bytes 6.2.2", + "docify", + "frame-support", + "frame-system", + "log", + "parity-scale-codec", + "scale-info", + "sp-runtime", +] + [[package]] name = "frame-remote-externalities" version = "0.36.0" @@ -6979,9 +6996,9 @@ dependencies = [ [[package]] name = "pallet-collator-selection" -version = "10.0.2" +version = "10.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49d1157d9a4b7966040158a7b4f1fb29f0cefa8deb6eb9b3452df7ce4161a31c" +checksum = "a36858c4275b7d19671b321e95f545e07c9643f97dffed1b333774cb391a4456" dependencies = [ "frame-benchmarking", "frame-support", @@ -7827,9 +7844,9 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" -version = "29.0.1" +version = "29.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b0c408252aefe10cff96af1e54f06f45cb0dd184b4e450e9a2ecf837dfe506e" +checksum = "5a5ba71f06f09e955b80dc313c333be3f8d9e8505b051558e0b7af4806b13310" dependencies = [ "frame-support", "frame-system", @@ -8023,9 +8040,9 @@ dependencies = [ [[package]] name = "parachains-common" -version = "8.0.0" +version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34aa00981a24a2b772afaa49e258f9bcd6bb372db060a05614becc1c74d4456" +checksum = "711a4c073e7c83aac7e414ba16c7c641d6d9e22e6d32f9775ff35b2464ffd7ff" dependencies = [ "cumulus-primitives-core", "cumulus-primitives-utility", @@ -9255,9 +9272,9 @@ dependencies = [ [[package]] name = "polkadot-runtime-common" -version = "8.0.2" +version = "8.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d815f0ff0a69dce7235d42c6e7d5e2b8b7429cba1252b4802ddc7879e2e74d4a" +checksum = "12a70422ca43d30457e2d9502a5e4af35e20fa2ff3f7cd46e0d2997c784f2665" dependencies = [ "bitvec", "frame-benchmarking", @@ -10518,13 +10535,14 @@ dependencies = [ [[package]] name = "rococo-runtime" -version = "8.0.0" +version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d089e93be2b8b76dd0d4b794a6a995ca3a1d6cb0ea3dd1cd42462f048bcfc926" +checksum = "cfa4cc054efdd3bfbec965da01b1ae16475031308c109c173347717091f6e3a5" dependencies = [ "binary-merkle-tree", "frame-benchmarking", "frame-executive", + "frame-metadata-hash-extension", "frame-support", "frame-system", "frame-system-benchmarking", @@ -13959,9 +13977,9 @@ dependencies = [ [[package]] name = "staging-xcm-builder" -version = "8.0.2" +version = "8.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "988d765ad5ab3b5cc90bb1dd143153ebdbe2b7600e10d5ef3a7f3e8df1bdac5d" +checksum = "78b7447c38be3ca9fb21c7434de2243aa6ac74acde8944cda7bb6e2a4f765801" dependencies = [ "frame-support", "frame-system", diff --git a/Cargo.toml b/Cargo.toml index 3719e83d..6b3cde02 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,7 +97,7 @@ pallet-scheduler = { version = "30.0.0", default-features = false } pallet-session = { version = "29.0.0", default-features = false } pallet-sudo = { version = "29.0.0", default-features = false } pallet-timestamp = { version = "28.0.0", default-features = false } -pallet-transaction-payment = { version = "29.0.1", default-features = false } +pallet-transaction-payment = { version = "29.0.2", default-features = false } pallet-transaction-payment-rpc = "31.0.0" pallet-transaction-payment-rpc-runtime-api = { version = "29.0.0", default-features = false } pallet-utility = { version = "29.0.0", default-features = false } @@ -130,15 +130,15 @@ polkadot-cli = "8.0.0" polkadot-parachain-primitives = { version = "7.0.0", default-features = false } polkadot-runtime-parachains = { version = "8.0.3", default-features = false } polkadot-primitives = { version = "8.0.1", default-features = false } -polkadot-runtime-common = { version = "8.0.2", default-features = false } +polkadot-runtime-common = { version = "8.0.3", default-features = false } rococo-runtime-constants = { version = "8.0.0", default-features = false } -rococo-runtime = { version = "8.0.0", default-features = false } +rococo-runtime = { version = "8.0.1", default-features = false } xcm = { version = "8.0.1", package = "staging-xcm", default-features = false } -xcm-builder = { version = "8.0.2", package = "staging-xcm-builder", default-features = false } +xcm-builder = { version = "8.0.3", package = "staging-xcm-builder", default-features = false } xcm-executor = { version = "8.0.2", package = "staging-xcm-executor", default-features = false } # Cumulus -asset-hub-rococo-runtime = { version = "0.12.0", default-features = false } +asset-hub-rococo-runtime = { version = "0.12.3", default-features = false } asset-test-utils = { version = "8.0.1", default-features = false } cumulus-pallet-aura-ext = { version = "0.8.0", default-features = false } cumulus-pallet-parachain-system = { version = "0.8.1", default-features = false, features = ["parameterized-consensus-hook"] } @@ -149,8 +149,8 @@ cumulus-primitives-aura = { version = "0.8.0", default-features = false } cumulus-primitives-core = { version = "0.8.0", default-features = false } cumulus-primitives-utility = { version = "0.8.1", default-features = false } emulated-integration-tests-common = { version = "4.0.0", default-features = false } -pallet-collator-selection = { version = "10.0.2", default-features = false } -parachains-common = { version = "8.0.0", default-features = false } +pallet-collator-selection = { version = "10.0.3", default-features = false } +parachains-common = { version = "8.0.1", default-features = false } parachain-info = { version = "0.8.0", package = "staging-parachain-info", default-features = false } cumulus-primitives-parachain-inherent = "0.8.0" cumulus-relay-chain-interface = "0.8.0" diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index aa58bcea..8f0a6eda 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -304,7 +304,6 @@ where // - `error`: The `DispatchError` encountered during contract execution. // - `version`: The version of the chain extension, used to determine the known errors. pub(crate) fn convert_to_status_code(error: DispatchError, version: u8) -> u32 { - use sp_std::vec; // "UnknownFunctionId" and "DecodingFailed" are mapped to specific errors in the API and will // never change. let mut encoded_error = match error { diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index a5eeb3c3..61d3cb43 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -206,7 +206,7 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, - _ => Ok(vec![0]), + _ => Ok(vec![0u8]), }? .encode(); From b067edac54c1cb375dfa72472c03fab75aaa99d2 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Tue, 16 Jul 2024 18:27:27 +0200 Subject: [PATCH 20/27] fix: cannot find macro vec error --- Cargo.lock | 1489 +++++++++++++------------- runtime/devnet/Cargo.toml | 2 +- runtime/devnet/src/extensions/mod.rs | 4 +- runtime/testnet/src/extensions.rs | 2 +- 4 files changed, 755 insertions(+), 742 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0c87955..1983b157 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,11 +23,11 @@ dependencies = [ [[package]] name = "addr2line" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" dependencies = [ - "gimli 0.28.1", + "gimli 0.29.0", ] [[package]] @@ -68,7 +68,7 @@ dependencies = [ "cipher 0.4.4", "ctr", "ghash", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -77,7 +77,7 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" dependencies = [ - "getrandom 0.2.12", + "getrandom 0.2.15", "once_cell", "version_check", ] @@ -89,7 +89,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ "cfg-if", - "getrandom 0.2.12", + "getrandom 0.2.15", "once_cell", "version_check", "zerocopy", @@ -106,9 +106,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.16" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" +checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" [[package]] name = "always-assert" @@ -142,47 +142,48 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.13" +version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", + "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" -version = "1.0.6" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" +checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" [[package]] name = "anstyle-parse" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" +checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.0.2" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" +checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.2" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" +checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" dependencies = [ "anstyle", "windows-sys 0.52.0", @@ -190,9 +191,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.81" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "approx" @@ -214,7 +215,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -354,9 +355,9 @@ checksum = "f52f63c5c1316a16a4b35eaac8b76a98248961a533f061684cb2a7cb0eafb6c6" [[package]] name = "array-bytes" -version = "6.2.2" +version = "6.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f840fb7195bcfc5e17ea40c26e5ce6d5b9ce5d584466e17703209657e459ae0" +checksum = "5d5dde061bd34119e902bbb2d9b90c5692635cf59fb91d582c2b68043f1b8293" [[package]] name = "arrayref" @@ -404,7 +405,7 @@ dependencies = [ "proc-macro2", "quote", "syn 1.0.109", - "synstructure", + "synstructure 0.12.6", ] [[package]] @@ -573,27 +574,25 @@ dependencies = [ [[package]] name = "async-channel" -version = "2.2.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28243a43d821d11341ab73c80bed182dc015c514b951616cf79bd4af39af0c3" +checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" dependencies = [ "concurrent-queue", - "event-listener 5.2.0", - "event-listener-strategy 0.5.1", + "event-listener-strategy", "futures-core", "pin-project-lite 0.2.14", ] [[package]] name = "async-executor" -version = "1.9.1" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10b3e585719c2358d2660232671ca8ca4ddb4be4ce8a1842d6c2dc8685303316" +checksum = "d7ebdfa2ebdab6b1760375fa7d6f382b9f486eac35fc994625a00e89280bdbb7" dependencies = [ - "async-lock 3.3.0", "async-task", "concurrent-queue", - "fastrand 2.0.2", + "fastrand 2.1.0", "futures-lite 2.3.0", "slab", ] @@ -612,11 +611,11 @@ dependencies = [ [[package]] name = "async-fs" -version = "2.1.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc19683171f287921f2405677dd2ed2549c3b3bda697a563ebc3a121ace2aba1" +checksum = "ebcd09b382f40fcd159c2d695175b2ae620ffa5f3bd6f664131efff4e8b9e04a" dependencies = [ - "async-lock 3.3.0", + "async-lock 3.4.0", "blocking", "futures-lite 2.3.0", ] @@ -643,18 +642,18 @@ dependencies = [ [[package]] name = "async-io" -version = "2.3.2" +version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcccb0f599cfa2f8ace422d3555572f47424da5648a4382a9dd0310ff8210884" +checksum = "0d6baa8f0178795da0e71bc42c9e5d13261aac7ee549853162e66a241ba17964" dependencies = [ - "async-lock 3.3.0", + "async-lock 3.4.0", "cfg-if", "concurrent-queue", "futures-io", "futures-lite 2.3.0", "parking", - "polling 3.6.0", - "rustix 0.38.32", + "polling 3.7.2", + "rustix 0.38.34", "slab", "tracing", "windows-sys 0.52.0", @@ -671,12 +670,12 @@ dependencies = [ [[package]] name = "async-lock" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d034b430882f8381900d3fe6f0aaa3ad94f2cb4ac519b429692a1bc2dda4ae7b" +checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ - "event-listener 4.0.3", - "event-listener-strategy 0.4.0", + "event-listener 5.3.1", + "event-listener-strategy", "pin-project-lite 0.2.14", ] @@ -697,7 +696,7 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7" dependencies = [ - "async-io 2.3.2", + "async-io 2.3.3", "blocking", "futures-lite 2.3.0", ] @@ -715,61 +714,63 @@ dependencies = [ "cfg-if", "event-listener 3.1.0", "futures-lite 1.13.0", - "rustix 0.38.32", + "rustix 0.38.34", "windows-sys 0.48.0", ] [[package]] name = "async-process" -version = "2.1.0" +version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "451e3cf68011bd56771c79db04a9e333095ab6349f7e47592b788e9b98720cc8" +checksum = "f7eda79bbd84e29c2b308d1dc099d7de8dcc7035e48f4bf5dc4a531a44ff5e2a" dependencies = [ - "async-channel 2.2.0", - "async-io 2.3.2", - "async-lock 3.3.0", + "async-channel 2.3.1", + "async-io 2.3.3", + "async-lock 3.4.0", "async-signal", + "async-task", "blocking", "cfg-if", - "event-listener 5.2.0", + "event-listener 5.3.1", "futures-lite 2.3.0", - "rustix 0.38.32", + "rustix 0.38.34", + "tracing", "windows-sys 0.52.0", ] [[package]] name = "async-signal" -version = "0.2.5" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e47d90f65a225c4527103a8d747001fc56e375203592b25ad103e1ca13124c5" +checksum = "794f185324c2f00e771cd9f1ae8b5ac68be2ca7abb129a87afd6e86d228bc54d" dependencies = [ - "async-io 2.3.2", - "async-lock 2.8.0", + "async-io 2.3.3", + "async-lock 3.4.0", "atomic-waker", "cfg-if", "futures-core", "futures-io", - "rustix 0.38.32", + "rustix 0.38.34", "signal-hook-registry", "slab", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "async-task" -version = "4.7.0" +version = "4.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbb36e985947064623dbd357f727af08ffd077f93d696782f3c56365fa2e2799" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.79" +version = "0.1.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681" +checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -799,22 +800,22 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "backtrace" -version = "0.3.71" +version = "0.3.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" +checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ - "addr2line 0.21.0", + "addr2line 0.22.0", "cc", "cfg-if", "libc", "miniz_oxide", - "object 0.32.2", + "object 0.36.1", "rustc-demangle", ] @@ -848,6 +849,12 @@ version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64ct" version = "1.6.0" @@ -894,13 +901,13 @@ dependencies = [ "lazy_static", "lazycell", "peeking_take_while", - "prettyplease 0.2.17", + "prettyplease 0.2.20", "proc-macro2", "quote", "regex", "rustc-hash", "shlex", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -930,9 +937,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "bitvec" @@ -1002,9 +1009,9 @@ dependencies = [ [[package]] name = "blake3" -version = "1.5.1" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30cca6d3674597c30ddf2c587bf8d9d65c9a84d2326d941cc79c9842dfe0ef52" +checksum = "e9ec96fe9a81b5e365f9db71fe00edc4fe4ca2cc7dcb7861f0603012a7caa210" dependencies = [ "arrayref", "arrayvec 0.7.4", @@ -1033,18 +1040,15 @@ dependencies = [ [[package]] name = "blocking" -version = "1.5.1" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a37913e8dc4ddcc604f0c6d3bf2887c995153af3611de9e23c352b44c1b9118" +checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" dependencies = [ - "async-channel 2.2.0", - "async-lock 3.3.0", + "async-channel 2.3.1", "async-task", - "fastrand 2.0.2", "futures-io", "futures-lite 2.3.0", "piper", - "tracing", ] [[package]] @@ -1152,9 +1156,9 @@ dependencies = [ [[package]] name = "bp-header-chain" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96157f586811969b3911d26cc79e02b28cfbecf859d96d7c12b6af10b9ea9350" +checksum = "1c4d2c457d5e18a5dbfe47a2ecd01f95036930a4a7ac0f3e47c2843bb067331b" dependencies = [ "bp-runtime", "finality-grandpa", @@ -1364,9 +1368,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.15.4" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" [[package]] name = "byte-slice-cast" @@ -1382,9 +1386,9 @@ checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" [[package]] name = "bytemuck" -version = "1.15.0" +version = "1.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15" +checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e" [[package]] name = "byteorder" @@ -1394,9 +1398,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" +checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" [[package]] name = "bzip2-sys" @@ -1421,9 +1425,9 @@ dependencies = [ [[package]] name = "camino" -version = "1.1.6" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c" +checksum = "e0ec6b951b160caa93cc0c7b209e5a3bff7aae9062213451ac99493cd844c239" dependencies = [ "serde", ] @@ -1445,7 +1449,7 @@ checksum = "eee4243f1f26fc7a42710e7439c149e2b10b05472f88090acce52632f231a73a" dependencies = [ "camino", "cargo-platform", - "semver 1.0.22", + "semver 1.0.23", "serde", "serde_json", "thiserror", @@ -1453,9 +1457,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.90" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5" +checksum = "324c74f2155653c90b04f25b2a47a8a631360cb908f92a772695f430c7e31052" dependencies = [ "jobserver", "libc", @@ -1472,9 +1476,9 @@ dependencies = [ [[package]] name = "cfg-expr" -version = "0.15.7" +version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa50868b64a9a6fda9d593ce778849ea8715cd2a3d2cc17ffdb4a2f2f2f1961d" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" dependencies = [ "smallvec", ] @@ -1527,16 +1531,16 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.37" +version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", "num-traits", "wasm-bindgen", - "windows-targets 0.52.4", + "windows-targets 0.52.6", ] [[package]] @@ -1583,9 +1587,9 @@ dependencies = [ [[package]] name = "clang-sys" -version = "1.7.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" dependencies = [ "glob", "libc", @@ -1594,9 +1598,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.4" +version = "4.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" +checksum = "64acc1846d54c1fe936a78dc189c34e28d3f5afc348403f28ecf53660b9b8462" dependencies = [ "clap_builder", "clap_derive", @@ -1604,9 +1608,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.2" +version = "4.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" +checksum = "6fb8393d67ba2e7bfaf28a23458e4e2b543cc73a99595511eb207fdb8aede942" dependencies = [ "anstream", "anstyle", @@ -1617,21 +1621,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.4" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" +checksum = "2bac35c6dafb060fd4d275d9a4ffae97917c13a6327903a8be2153cd964f7085" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "clap_lex" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" +checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" [[package]] name = "coarsetime" @@ -1656,39 +1660,39 @@ dependencies = [ [[package]] name = "color-print" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a858372ff14bab9b1b30ea504f2a4bc534582aee3e42ba2d41d2a7baba63d5d" +checksum = "1ee543c60ff3888934877a5671f45494dd27ed4ba25c6670b9a7576b7ed7a8c0" dependencies = [ "color-print-proc-macro", ] [[package]] name = "color-print-proc-macro" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57e37866456a721d0a404439a1adae37a31be4e0055590d053dfe6981e05003f" +checksum = "77ff1a80c5f3cb1ca7c06ffdd71b6a6dd6d8f896c42141fbd43f50ed28dcdb93" dependencies = [ "nom", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.71", ] [[package]] name = "colorchoice" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" +checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" [[package]] name = "comfy-table" -version = "7.1.0" +version = "7.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c64043d6c7b7a4c58e39e7efccfdea7b93d885a795d0c054a69dbbf4dd52686" +checksum = "b34115915337defe99b2aff5c2ce6771e5fbc4079f4b506301f5cf394c8452f7" dependencies = [ - "strum 0.25.0", - "strum_macros 0.25.3", + "strum 0.26.3", + "strum_macros 0.26.4", "unicode-width", ] @@ -1700,9 +1704,9 @@ checksum = "2382f75942f4b3be3690fe4f86365e9c853c1587d6ee58212cebf6e2a9ccd101" [[package]] name = "concurrent-queue" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d16048cd947b08fa32c24458a22f5dc5e835264f689f4f5653210c69fd107363" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" dependencies = [ "crossbeam-utils", ] @@ -1741,7 +1745,7 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" dependencies = [ - "getrandom 0.2.12", + "getrandom 0.2.15", "once_cell", "tiny-keccak", ] @@ -1923,9 +1927,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.4.0" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" dependencies = [ "cfg-if", ] @@ -1960,9 +1964,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.19" +version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" [[package]] name = "crunchy" @@ -1978,7 +1982,7 @@ checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array 0.14.7", "rand_core 0.6.4", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] @@ -2010,7 +2014,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" dependencies = [ "generic-array 0.14.7", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -2020,7 +2024,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25fab6889090c8133f3deb8f73ba3c65a7f456f66436fc012a1b1e272b1e103e" dependencies = [ "generic-array 0.14.7", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -2061,7 +2065,7 @@ dependencies = [ "cumulus-primitives-core", "futures", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-overseer", @@ -2174,7 +2178,7 @@ dependencies = [ "futures", "futures-timer", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "polkadot-node-primitives", "polkadot-parachain-primitives", "polkadot-primitives", @@ -2338,7 +2342,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -2530,13 +2534,13 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7718fe298d567adc44fae3dd7024418d6eff08264041e4b0544d1892861cd6" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "async-trait", "cumulus-primitives-core", "cumulus-relay-chain-interface", "cumulus-relay-chain-rpc-interface", "futures", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "polkadot-availability-recovery", "polkadot-collator-protocol", "polkadot-core-primitives", @@ -2630,24 +2634,23 @@ dependencies = [ "byteorder", "digest 0.9.0", "rand_core 0.5.1", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] [[package]] name = "curve25519-dalek" -version = "4.1.2" +version = "4.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a677b8922c94e01bdbb12126b0bc852f00447528dee1782229af9c720c3f348" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" dependencies = [ "cfg-if", "cpufeatures", "curve25519-dalek-derive", "digest 0.10.7", "fiat-crypto", - "platforms", "rustc_version", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] @@ -2659,7 +2662,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -2677,9 +2680,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.120" +version = "1.0.124" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff4dc7287237dd438b926a81a1a5605dad33d286870e5eee2db17bf2bcd9e92a" +checksum = "273dcfd3acd4e1e276af13ed2a43eea7001318823e7a726a6b3ed39b4acc0b82" dependencies = [ "cc", "cxxbridge-flags", @@ -2689,9 +2692,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.120" +version = "1.0.124" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f47c6c8ad7c1a10d3ef0fe3ff6733f4db0d78f08ef0b13121543163ef327058b" +checksum = "d8b2766fbd92be34e9ed143898fce6c572dc009de39506ed6903e5a05b68914e" dependencies = [ "cc", "codespan-reporting", @@ -2699,24 +2702,24 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "cxxbridge-flags" -version = "1.0.120" +version = "1.0.124" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "701a1ac7a697e249cdd8dc026d7a7dafbfd0dbcd8bd24ec55889f2bc13dd6287" +checksum = "839fcd5e43464614ffaa989eaf1c139ef1f0c51672a1ed08023307fa1b909ccd" [[package]] name = "cxxbridge-macro" -version = "1.0.120" +version = "1.0.124" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b404f596046b0bb2d903a9c786b875a126261b52b7c3a64bbb66382c41c771df" +checksum = "4b2c1c1776b986979be68bb2285da855f8d8a35851a769fca8740df7c3d07877" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -2731,12 +2734,12 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.8" +version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391" +checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" dependencies = [ - "darling_core 0.20.8", - "darling_macro 0.20.8", + "darling_core 0.20.10", + "darling_macro 0.20.10", ] [[package]] @@ -2755,16 +2758,16 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.8" +version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f" +checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", - "strsim 0.10.0", - "syn 2.0.58", + "strsim 0.11.1", + "syn 2.0.71", ] [[package]] @@ -2780,26 +2783,26 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.20.8" +version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" +checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ - "darling_core 0.20.8", + "darling_core 0.20.10", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "data-encoding" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e962a19be5cfc3f3bf6dd8f61eb50107f356ad6270fbb3ed41476571db78be5" +checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" [[package]] name = "data-encoding-macro" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20c01c06f5f429efdf2bae21eb67c28b3df3cf85b7dd2d8ef09c0838dac5d33e" +checksum = "f1559b6cba622276d6d63706db152618eeb15b89b3e4041446b05876e352e639" dependencies = [ "data-encoding", "data-encoding-macro-internal", @@ -2807,9 +2810,9 @@ dependencies = [ [[package]] name = "data-encoding-macro-internal" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0047d07f2c89b17dd631c80450d69841a6b5d7fb17278cbc43d7e4cfcf2576f3" +checksum = "332d754c0af53bc87c108fed664d121ecf59207ec4196041f04d6ab9002ad33f" dependencies = [ "data-encoding", "syn 1.0.109", @@ -2878,20 +2881,20 @@ checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "derive_more" -version = "0.99.17" +version = "0.99.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" dependencies = [ "convert_case", "proc-macro2", "quote", "rustc_version", - "syn 1.0.109", + "syn 2.0.71", ] [[package]] @@ -2927,7 +2930,7 @@ dependencies = [ "block-buffer 0.10.4", "const-oid", "crypto-common", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -2974,13 +2977,13 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3004,9 +3007,9 @@ dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.58", + "syn 2.0.71", "termcolor", - "toml 0.8.12", + "toml 0.8.14", "walkdir", ] @@ -3018,9 +3021,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "downcast-rs" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" [[package]] name = "dtoa" @@ -3085,12 +3088,12 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" dependencies = [ - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "ed25519", "rand_core 0.6.4", "serde", "sha2 0.10.8", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] @@ -3114,9 +3117,9 @@ version = "4.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d9ce6874da5d4415896cd45ffbc4d1cfc0c4f9c079427bd870742c30f2f65a9" dependencies = [ - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "ed25519", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "hex", "rand_core 0.6.4", "sha2 0.10.8", @@ -3125,9 +3128,9 @@ dependencies = [ [[package]] name = "either" -version = "1.10.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "elliptic-curve" @@ -3144,7 +3147,7 @@ dependencies = [ "pkcs8", "rand_core 0.6.4", "sec1", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] @@ -3201,22 +3204,22 @@ dependencies = [ [[package]] name = "enumflags2" -version = "0.7.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3278c9d5fb675e0a51dabcf4c0d355f692b064171535ba72361be1528a9d8e8d" +checksum = "d232db7f5956f3f14313dc2f87985c58bd2c695ce124c8cdd984e08e15ac133d" dependencies = [ "enumflags2_derive", ] [[package]] name = "enumflags2_derive" -version = "0.7.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c785274071b1b420972453b306eeca06acf4633829db4223b58a2a8c5953bc4" +checksum = "de0d48a183585823424a4ce1aa132d174a6a81bd540895822eb4c8373a8e49e8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3227,7 +3230,7 @@ checksum = "6fd000fd6988e73bbe993ea3db9b1aa64906ab88766d654973924340c8cddb42" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3280,9 +3283,9 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" +checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys 0.52.0", @@ -3353,15 +3356,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b215c49b2b248c855fb73579eb1f4f26c38ffdc12973e20e07b91d78d5646e" dependencies = [ "concurrent-queue", - "parking", "pin-project-lite 0.2.14", ] [[package]] name = "event-listener" -version = "5.2.0" +version = "5.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" +checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" dependencies = [ "concurrent-queue", "parking", @@ -3370,21 +3372,11 @@ dependencies = [ [[package]] name = "event-listener-strategy" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "958e4d70b6d5e81971bebec42271ec641e7ff4e170a6fa605f2b8a8b65cb97d3" -dependencies = [ - "event-listener 4.0.3", - "pin-project-lite 0.2.14", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "332f51cb23d20b0de8458b86580878211da09bcd4503cb579c225b3d124cabb3" +checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ - "event-listener 5.2.0", + "event-listener 5.3.1", "pin-project-lite 0.2.14", ] @@ -3411,16 +3403,17 @@ dependencies = [ [[package]] name = "expander" -version = "2.1.0" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00e83c02035136f1592a47964ea60c05a50e4ed8b5892cfac197063850898d4d" +checksum = "e2c470c71d91ecbd179935b24170459e926382eaaa86b590b78814e180d8a8e2" dependencies = [ "blake2 0.10.6", + "file-guard", "fs-err", - "prettier-please", + "prettyplease 0.2.20", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3440,9 +3433,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.2" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "fatality" @@ -3462,7 +3455,7 @@ checksum = "f5aa1e3ae159e592ad222dc90c5acbad632b527779ba88486abe92782ab268bd" dependencies = [ "expander 0.0.4", "indexmap 1.9.3", - "proc-macro-crate 1.3.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn 1.0.109", @@ -3486,14 +3479,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" dependencies = [ "rand_core 0.6.4", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] name = "fiat-crypto" -version = "0.2.7" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c007b1ae3abe1cb6f85a16305acd418b7ca6343b953633fee2b76d8f108b830f" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "file-guard" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21ef72acf95ec3d7dbf61275be556299490a245f017cf084bd23b4f68cf9407c" +dependencies = [ + "libc", + "winapi", +] [[package]] name = "file-per-thread-logger" @@ -3529,7 +3532,7 @@ dependencies = [ "log", "num-traits", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "scale-info", ] @@ -3553,9 +3556,9 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" [[package]] name = "flate2" -version = "1.0.28" +version = "1.0.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46303f565772937ffe1d394a4fac6f411c6013172fadde9dcdb1e147a086940e" +checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae" dependencies = [ "crc32fast", "libz-sys", @@ -3634,7 +3637,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "efe02c96362e3c7308cdea7545859f767194a1f3f00928f0e1357f4b8a0b3b2c" dependencies = [ "Inflector", - "array-bytes 6.2.2", + "array-bytes 6.2.3", "chrono", "clap", "comfy-table", @@ -3685,7 +3688,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3754,7 +3757,7 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bb1eec9eb46d3e016c95b2fa875118c04609f2150013c56a894cae00581e265" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "docify", "frame-support", "frame-system", @@ -3794,7 +3797,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e52c84b611d2049d9253f83a62ab0f093e4be5c42a7ef42ea5bb16d6611e32" dependencies = [ "aquamarine", - "array-bytes 6.2.2", + "array-bytes 6.2.3", "bitflags 1.3.2", "docify", "environmental", @@ -3838,7 +3841,7 @@ dependencies = [ "Inflector", "cfg-expr", "derive-syn-parse 0.1.5", - "expander 2.1.0", + "expander 2.2.1", "frame-support-procedural-tools", "itertools 0.10.5", "macro_magic", @@ -3846,7 +3849,7 @@ dependencies = [ "proc-macro2", "quote", "sp-crypto-hashing", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3859,7 +3862,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3870,7 +3873,7 @@ checksum = "68672b9ec6fe72d259d3879dc212c5e42e977588cdac830c76f54d9f492aeb58" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -3958,7 +3961,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29f9df8a11882c4e3335eb2d18a0137c505d9ca927470b0cac9c6f0ae07d28f7" dependencies = [ - "rustix 0.38.32", + "rustix 0.38.34", "windows-sys 0.48.0", ] @@ -4048,7 +4051,7 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ - "fastrand 2.0.2", + "fastrand 2.1.0", "futures-core", "futures-io", "parking", @@ -4063,7 +4066,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -4165,9 +4168,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.12" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", @@ -4207,9 +4210,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" [[package]] name = "glob" @@ -4225,7 +4228,7 @@ checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", "rand_core 0.6.4", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -4296,9 +4299,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.3" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash 0.8.11", "allocator-api2", @@ -4311,7 +4314,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ - "hashbrown 0.14.3", + "hashbrown 0.14.5", ] [[package]] @@ -4332,6 +4335,12 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + [[package]] name = "hex" version = "0.4.3" @@ -4443,9 +4452,9 @@ checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" [[package]] name = "httparse" -version = "1.8.0" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" +checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" [[package]] name = "httpdate" @@ -4461,9 +4470,9 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "hyper" -version = "0.14.28" +version = "0.14.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80" +checksum = "a152ddd61dfaec7273fe8419ab357f33aee0d914c5f4efbf0d96fa749eea5ec9" dependencies = [ "bytes", "futures-channel", @@ -4476,7 +4485,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite 0.2.14", - "socket2 0.5.6", + "socket2 0.5.7", "tokio", "tower-service", "tracing", @@ -4493,7 +4502,7 @@ dependencies = [ "http", "hyper", "log", - "rustls 0.21.10", + "rustls 0.21.12", "rustls-native-certs 0.6.3", "tokio", "tokio-rustls 0.24.1", @@ -4565,7 +4574,7 @@ version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6b0422c86d7ce0e97169cc42e04ae643caf278874a7a3c87b8150a220dc7e1e" dependencies = [ - "async-io 2.3.2", + "async-io 2.3.3", "core-foundation", "fnv", "futures", @@ -4629,18 +4638,18 @@ dependencies = [ [[package]] name = "include_dir" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18762faeff7122e89e0857b02f7ce6fcc0d101d5e9ad2ad7846cc01d61b7f19e" +checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" dependencies = [ "include_dir_macros", ] [[package]] name = "include_dir_macros" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b139284b5cf57ecfa712bcc66950bb635b31aff41c188e8a4cfc758eca374a3f" +checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" dependencies = [ "proc-macro2", "quote", @@ -4664,7 +4673,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", - "hashbrown 0.14.3", + "hashbrown 0.14.5", ] [[package]] @@ -4697,9 +4706,9 @@ dependencies = [ [[package]] name = "instant" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" dependencies = [ "cfg-if", ] @@ -4756,7 +4765,7 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", "windows-sys 0.48.0", ] @@ -4773,7 +4782,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b58db92f96b720de98181bbbe63c831e87005ab460c1bf306eb2622b4707997f" dependencies = [ - "socket2 0.5.6", + "socket2 0.5.7", "widestring", "windows-sys 0.48.0", "winreg", @@ -4791,7 +4800,7 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", "windows-sys 0.52.0", ] @@ -4805,6 +4814,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" + [[package]] name = "itertools" version = "0.10.5" @@ -4840,9 +4855,9 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jobserver" -version = "0.1.28" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab46a6e9526ddef3ae7f787c06f0f2600639ba80ea3eade3d8e670a2230f51d6" +checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e" dependencies = [ "libc", ] @@ -4914,7 +4929,7 @@ dependencies = [ "http", "jsonrpsee-core 0.21.0", "pin-project", - "rustls-native-certs 0.7.0", + "rustls-native-certs 0.7.1", "rustls-pki-types", "soketto", "thiserror", @@ -4939,7 +4954,7 @@ dependencies = [ "futures-util", "hyper", "jsonrpsee-types 0.20.3", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "rustc-hash", "serde", @@ -4957,7 +4972,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "776d009e2f591b78c038e0d053a796f94575d66ca4e77dd84bfc5e81419e436c" dependencies = [ "anyhow", - "async-lock 3.3.0", + "async-lock 3.4.0", "async-trait", "beef", "futures-timer", @@ -5021,7 +5036,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29110019693a4fa2dbda04876499d098fa16d70eba06b1e6e2b3f1b251419515" dependencies = [ "heck 0.4.1", - "proc-macro-crate 1.3.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn 1.0.109", @@ -5134,7 +5149,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf7a85fe66f9ff9cd74e169fdd2c94c6e1e74c412c99a73b4df3200b5d3760b2" dependencies = [ "kvdb", - "parking_lot 0.12.1", + "parking_lot 0.12.3", ] [[package]] @@ -5145,7 +5160,7 @@ checksum = "b644c70b92285f66bfc2032922a79000ea30af7bc2ab31902992a5dcb9b434f6" dependencies = [ "kvdb", "num_cpus", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "regex", "rocksdb", "smallvec", @@ -5164,9 +5179,9 @@ dependencies = [ [[package]] name = "lazy_static" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "lazycell" @@ -5176,18 +5191,18 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.153" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libloading" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" +checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" dependencies = [ "cfg-if", - "windows-targets 0.52.4", + "windows-targets 0.52.6", ] [[package]] @@ -5205,7 +5220,7 @@ dependencies = [ "bytes", "futures", "futures-timer", - "getrandom 0.2.12", + "getrandom 0.2.15", "instant", "libp2p-allow-block-list", "libp2p-connection-limits", @@ -5270,7 +5285,7 @@ dependencies = [ "multihash 0.17.0", "multistream-select", "once_cell", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "pin-project", "quick-protobuf", "rand", @@ -5290,7 +5305,7 @@ dependencies = [ "futures", "libp2p-core", "log", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "smallvec", "trust-dns-resolver", ] @@ -5452,7 +5467,7 @@ dependencies = [ "libp2p-identity", "libp2p-tls", "log", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "quinn-proto", "rand", "rustls 0.20.9", @@ -5568,7 +5583,7 @@ dependencies = [ "futures-rustls", "libp2p-core", "log", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "quicksink", "rw-stream-sink", "soketto", @@ -5595,7 +5610,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "libc", ] @@ -5641,7 +5656,7 @@ checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" dependencies = [ "crunchy", "digest 0.9.0", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -5664,9 +5679,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.16" +version = "1.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e143b5e666b2695d28f6bca6497720813f699c9602dd7f5cac91008b8ada7f9" +checksum = "c15da26e5af7e25c90b37a2d75cdbf940cf4a55316de9d84c679c9b8bfabf82e" dependencies = [ "cc", "pkg-config", @@ -5720,9 +5735,9 @@ checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "linux-raw-sys" -version = "0.4.13" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "lioness" @@ -5738,9 +5753,9 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" dependencies = [ "autocfg", "scopeguard", @@ -5748,9 +5763,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "lru" @@ -5782,7 +5797,7 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc" dependencies = [ - "hashbrown 0.14.3", + "hashbrown 0.14.5", ] [[package]] @@ -5796,9 +5811,9 @@ dependencies = [ [[package]] name = "lz4" -version = "1.24.0" +version = "1.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e9e2dd86df36ce760a60f6ff6ad526f7ba1f14ba0356f8254fb6905e6494df1" +checksum = "d6eab492fe7f8651add23237ea56dbf11b3c4ff762ab83d40a47f11433421f91" dependencies = [ "libc", "lz4-sys", @@ -5806,9 +5821,9 @@ dependencies = [ [[package]] name = "lz4-sys" -version = "1.9.4" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57d27b317e207b10f69f5e75494119e391a96f48861ae870d1da6edac98ca900" +checksum = "e9764018d143cc854c9f17f0b907de70f14393b1f502da6375dce70f00514eb3" dependencies = [ "cc", "libc", @@ -5825,50 +5840,50 @@ dependencies = [ [[package]] name = "macro_magic" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e03844fc635e92f3a0067e25fa4bf3e3dbf3f2927bf3aa01bb7bc8f1c428949d" +checksum = "cc33f9f0351468d26fbc53d9ce00a096c8522ecb42f19b50f34f2c422f76d21d" dependencies = [ "macro_magic_core", "macro_magic_macros", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "macro_magic_core" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "468155613a44cfd825f1fb0ffa532b018253920d404e6fca1e8d43155198a46d" +checksum = "1687dc887e42f352865a393acae7cf79d98fab6351cde1f58e9e057da89bf150" dependencies = [ "const-random", - "derive-syn-parse 0.1.5", + "derive-syn-parse 0.2.0", "macro_magic_core_macros", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "macro_magic_core_macros" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ea73aa640dc01d62a590d48c0c3521ed739d53b27f919b25c3551e233481654" +checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "macro_magic_macros" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef9d79ae96aaba821963320eb2b6e34d17df1e5a83d8a1985c29cc5be59577b3" +checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" dependencies = [ "macro_magic_core", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -5919,9 +5934,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.7.2" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memfd" @@ -5929,7 +5944,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2cffa4ad52c6f791f4f8b15f0c05f9824b2ced1160e88cc393d64fff9a8ac64" dependencies = [ - "rustix 0.38.32", + "rustix 0.38.34", ] [[package]] @@ -5999,9 +6014,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" dependencies = [ "adler", ] @@ -6028,16 +6043,16 @@ dependencies = [ "bitflags 1.3.2", "blake2 0.10.6", "c2-chacha", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "either", "hashlink", "lioness", "log", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "rand_chacha 0.3.1", "rand_distr", - "subtle 2.5.0", + "subtle 2.6.1", "thiserror", "zeroize", ] @@ -6146,7 +6161,7 @@ dependencies = [ "blake3", "core2", "digest 0.10.7", - "multihash-derive 0.8.0", + "multihash-derive 0.8.1", "sha2 0.10.8", "sha3", "unsigned-varint", @@ -6160,7 +6175,7 @@ checksum = "cfd8a792c1694c6da4f68db0a9d707c72bd260994da179e6030a5dcee00bb815" dependencies = [ "core2", "digest 0.10.7", - "multihash-derive 0.8.0", + "multihash-derive 0.8.1", "sha2 0.10.8", "unsigned-varint", ] @@ -6197,16 +6212,16 @@ dependencies = [ [[package]] name = "multihash-derive" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc076939022111618a5026d3be019fd8b366e76314538ff9a1b59ffbcbf98bcd" +checksum = "1d6d4752e6230d8ef7adf7bd5d8c4b1f6561c1014c5ba9a37445ccefe18aa1db" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate 1.1.3", "proc-macro-error", "proc-macro2", "quote", "syn 1.0.109", - "synstructure", + "synstructure 0.12.6", ] [[package]] @@ -6222,16 +6237,16 @@ dependencies = [ [[package]] name = "multihash-derive-impl" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38685e08adb338659871ecfc6ee47ba9b22dcc8abcf6975d379cc49145c3040" +checksum = "3958713ce794e12f7c6326fac9aa274c68d74c4881dd37b3e2662b8a2046bb19" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate 2.0.0", "proc-macro-error", "proc-macro2", "quote", - "syn 1.0.109", - "synstructure", + "syn 2.0.71", + "synstructure 0.13.1", ] [[package]] @@ -6256,9 +6271,9 @@ dependencies = [ [[package]] name = "nalgebra" -version = "0.32.5" +version = "0.32.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ea4908d4f23254adda3daa60ffef0f1ac7b8c3e9a864cf3cc154b251908a2ef" +checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4" dependencies = [ "approx", "matrixmultiply", @@ -6272,13 +6287,13 @@ dependencies = [ [[package]] name = "nalgebra-macros" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91761aed67d03ad966ef783ae962ef9bbaca728d2dd7ceb7939ec110fffad998" +checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.71", ] [[package]] @@ -6379,7 +6394,7 @@ version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "cfg-if", "libc", ] @@ -6420,20 +6435,19 @@ checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" [[package]] name = "num-bigint" -version = "0.4.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" dependencies = [ - "autocfg", "num-integer", "num-traits", ] [[package]] name = "num-complex" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23c6602fda94a57c990fe0df199a035d83576b496aa29f4e634a8ac6004e68a6" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ "num-traits", ] @@ -6465,11 +6479,10 @@ dependencies = [ [[package]] name = "num-rational" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "autocfg", "num-bigint", "num-integer", "num-traits", @@ -6477,9 +6490,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.18" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", "libm", @@ -6491,7 +6504,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", ] @@ -6515,9 +6528,9 @@ dependencies = [ [[package]] name = "object" -version = "0.32.2" +version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" +checksum = "081b846d1d56ddfc18fdf1a922e4f6e07a11768ea1b92dec44e42b72712ccfce" dependencies = [ "memchr", ] @@ -6563,9 +6576,9 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "orchestra" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2356622ffdfe72362a45a1e5e87bb113b8327e596e39b91f11f0ef4395c8da79" +checksum = "92829eef0328a3d1cd22a02c0e51deb92a5362df3e7d21a4e9bdc38934694e66" dependencies = [ "async-trait", "dyn-clonable", @@ -6580,15 +6593,15 @@ dependencies = [ [[package]] name = "orchestra-proc-macro" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eedb646674596266dc9bb2b5c7eea7c36b32ecc7777eba0d510196972d72c4fd" +checksum = "1344346d5af32c95bbddea91b18a88cc83eac394192d20ef2fc4c40a74332355" dependencies = [ - "expander 2.1.0", + "expander 2.2.1", "indexmap 2.2.6", "itertools 0.11.0", "petgraph", - "proc-macro-crate 1.3.1", + "proc-macro-crate 3.1.0", "proc-macro2", "quote", "syn 1.0.109", @@ -6832,7 +6845,7 @@ version = "29.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d334f24d3c0c016d16aa87d069485847d622e8ebebace18ec5cf56609ca3a67" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "binary-merkle-tree", "frame-support", "frame-system", @@ -7074,7 +7087,7 @@ checksum = "3163c6bc21b55a0ccb74c546ba784d9c9e69beb9240c059d28a3052f4cbce509" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -7430,9 +7443,9 @@ dependencies = [ [[package]] name = "pallet-nomination-pools" -version = "26.0.0" +version = "26.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f14519c1c613d2f8c95c27015864c11a37969a23deeba9f6dbaff4276e1b81c" +checksum = "b62091305ec7426e71c3da2b0944c2df5a804109ee4d2e8f4fe34865e049f8ac" dependencies = [ "frame-support", "frame-system", @@ -7742,7 +7755,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -7757,9 +7770,9 @@ dependencies = [ [[package]] name = "pallet-staking-runtime-api" -version = "15.0.0" +version = "15.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "237d7b5a10cb6cba727c3e957fb241776302aa3cce589e6759ba53f50129c1a5" +checksum = "e47c73850103db30b61ef170107afe1ef0dab6905c495bd6dfb57b3c1dd81bc7" dependencies = [ "parity-scale-codec", "sp-api", @@ -8121,7 +8134,7 @@ dependencies = [ "log", "lz4", "memmap2 0.5.10", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "siphasher 0.3.11", "snap", @@ -8130,9 +8143,9 @@ dependencies = [ [[package]] name = "parity-scale-codec" -version = "3.6.9" +version = "3.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "881331e34fa842a2fb61cc2db9643a8fedc615e47cfcc52597d1af0db9a7e8fe" +checksum = "306800abfa29c7f16596b5970a588435e3d5b3149683d00c12b699cc19f895ee" dependencies = [ "arrayvec 0.7.4", "bitvec", @@ -8145,11 +8158,11 @@ dependencies = [ [[package]] name = "parity-scale-codec-derive" -version = "3.6.9" +version = "3.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be30eaf4b0a9fba5336683b38de57bb86d179a35862ba6bfcf57625d006bde5b" +checksum = "d830939c76d294956402033aee57a6da7b438f2294eb94864c37b0569053a42c" dependencies = [ - "proc-macro-crate 2.0.0", + "proc-macro-crate 3.1.0", "proc-macro2", "quote", "syn 1.0.109", @@ -8173,7 +8186,7 @@ dependencies = [ "impl-trait-for-tuples", "lru 0.8.1", "parity-util-mem-derive", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "primitive-types", "smallvec", "winapi", @@ -8187,7 +8200,7 @@ checksum = "f557c32c6d268a07c921471619c0295f5efad3a0e76d4f97a05c091a51d110b2" dependencies = [ "proc-macro2", "syn 1.0.109", - "synstructure", + "synstructure 0.12.6", ] [[package]] @@ -8215,12 +8228,12 @@ dependencies = [ [[package]] name = "parking_lot" -version = "0.12.1" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", - "parking_lot_core 0.9.9", + "parking_lot_core 0.9.10", ] [[package]] @@ -8239,15 +8252,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.9" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.4.1", + "redox_syscall 0.5.3", "smallvec", - "windows-targets 0.48.5", + "windows-targets 0.52.6", ] [[package]] @@ -8258,9 +8271,9 @@ checksum = "7924d1d0ad836f665c9065e26d016c673ece3993f30d340068b16f282afc1156" [[package]] name = "paste" -version = "1.0.14" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" [[package]] name = "pbkdf2" @@ -8303,9 +8316,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.9" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "311fb059dee1a7b802f036316d790138c613a4e8b180c822e3925a662e9f0c95" +checksum = "cd53dff83f26735fdc1ca837098ccf133605d794cdae66acfc2bfac3ec809d95" dependencies = [ "memchr", "thiserror", @@ -8314,9 +8327,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.9" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f73541b156d32197eecda1a4014d7f868fd2bcb3c550d5386087cfba442bf69c" +checksum = "2a548d2beca6773b1c244554d36fcf8548a8a58e74156968211567250e48e49a" dependencies = [ "pest", "pest_generator", @@ -8324,22 +8337,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.9" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c35eeed0a3fab112f75165fdc026b3913f4183133f19b49be773ac9ea966e8bd" +checksum = "3c93a82e8d145725dcbaf44e5ea887c8a869efdcc28706df2d08c69e17077183" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "pest_meta" -version = "2.7.9" +version = "2.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2adbf29bb9776f28caece835398781ab24435585fe0d4dc1374a61db5accedca" +checksum = "a941429fea7e08bedec25e4f6785b6ffaacc6b755da98df5ef3e7dcf4a124c4f" dependencies = [ "once_cell", "pest", @@ -8348,9 +8361,9 @@ dependencies = [ [[package]] name = "petgraph" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d3afd2628e69da2be385eb6f2fd57c8ac7977ceeff6dc166ff1657b0e386a9" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" dependencies = [ "fixedbitset", "indexmap 2.2.6", @@ -8373,7 +8386,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -8396,12 +8409,12 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "piper" -version = "0.2.1" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "668d31b1c4eba19242f2088b2bf3316b82ca31082a8335764db4e083db7485d4" +checksum = "ae1d5c74c9876f070d3e8fd503d748c7d974c3e48da8f41350fa5222ef9b4391" dependencies = [ "atomic-waker", - "fastrand 2.0.2", + "fastrand 2.1.0", "futures-io", ] @@ -8421,12 +8434,6 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" -[[package]] -name = "platforms" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db23d408679286588f4d4644f965003d056e3dd5abcaaa938116871d7ce2fee7" - [[package]] name = "polkadot-approval-distribution" version = "8.0.0" @@ -8654,7 +8661,7 @@ dependencies = [ "fatality", "futures", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "polkadot-node-metrics", "polkadot-node-network-protocol", "polkadot-node-subsystem", @@ -8915,7 +8922,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3bbb1b5f4b966f21a0336e94c0a0222958d2f3cba451da1157af271d07f9748" dependencies = [ "always-assert", - "array-bytes 6.2.2", + "array-bytes 6.2.3", "blake3", "cfg-if", "futures", @@ -9013,7 +9020,7 @@ dependencies = [ "log", "mick-jaeger", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "polkadot-node-primitives", "polkadot-primitives", "sc-network", @@ -9146,7 +9153,7 @@ dependencies = [ "kvdb", "parity-db", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "pin-project", "polkadot-node-jaeger", "polkadot-node-metrics", @@ -9177,7 +9184,7 @@ dependencies = [ "futures", "futures-timer", "orchestra", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "polkadot-node-metrics", "polkadot-node-network-protocol", "polkadot-node-primitives", @@ -9412,7 +9419,7 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api", "parity-db", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "polkadot-approval-distribution", "polkadot-availability-bitfield-distribution", "polkadot-availability-distribution", @@ -9553,7 +9560,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6380dbe1fb03ecc74ad55d841cfc75480222d153ba69ddcb00977866cbdabdb8" dependencies = [ "polkavm-derive-impl", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -9565,7 +9572,7 @@ dependencies = [ "polkavm-common", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -9586,15 +9593,15 @@ dependencies = [ [[package]] name = "polling" -version = "3.6.0" +version = "3.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0c976a60b2d7e99d6f229e414670a9b85d13ac305cc6d1e9c134de58c5aaaf6" +checksum = "a3ed00ed3fbf728b5816498ecd316d1716eecaced9c0c8d2c5a6740ca214985b" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi", + "hermit-abi 0.4.0", "pin-project-lite 0.2.14", - "rustix 0.38.32", + "rustix 0.38.34", "tracing", "windows-sys 0.52.0", ] @@ -9903,21 +9910,11 @@ dependencies = [ "termtree", ] -[[package]] -name = "prettier-please" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22020dfcf177fcc7bf5deaf7440af371400c67c0de14c399938d8ed4fb4645d3" -dependencies = [ - "proc-macro2", - "syn 2.0.58", -] - [[package]] name = "prettyplease" -version = "0.1.11" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28f53e8b192565862cf99343194579a022eb9c7dd3a8d03134734803c7b3125" +checksum = "6c8646e95016a7a6c4adea95bafa8a16baab64b583356217f2c85db4a39d9a86" dependencies = [ "proc-macro2", "syn 1.0.109", @@ -9925,12 +9922,12 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.17" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3928fb5db768cb86f891ff014f0144589297e3c6a1aba6ed7cecfdace270c7" +checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" dependencies = [ "proc-macro2", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -9966,12 +9963,12 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "1.3.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" dependencies = [ - "once_cell", - "toml_edit 0.19.15", + "thiserror", + "toml 0.5.11", ] [[package]] @@ -10024,29 +10021,29 @@ checksum = "834da187cfe638ae8abb0203f0b33e5ccdb02a28e7199f2f47b3e2754f50edca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "proc-macro2" -version = "1.0.79" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "prometheus" -version = "0.13.3" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "449811d15fbdf5ceb5c1144416066429cf82316e2ec8ce0c1f6f8a02e7bbcf8c" +checksum = "3d33c28a30771f7f96db69893f78b857f7450d7e0237e9c8fc6427a81bae7ed1" dependencies = [ "cfg-if", "fnv", "lazy_static", "memchr", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "thiserror", ] @@ -10058,7 +10055,7 @@ checksum = "5d6fa99d535dd930d1249e6c79cb3c2915f9172a540fe2b02a4c8f9ca954721e" dependencies = [ "dtoa", "itoa", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "prometheus-client-derive-encode", ] @@ -10070,7 +10067,7 @@ checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -10085,12 +10082,12 @@ dependencies = [ [[package]] name = "prost" -version = "0.12.3" +version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c289cda302b98a28d40c8b3b90498d6e526dd24ac2ecea73e4e491685b94a" +checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" dependencies = [ "bytes", - "prost-derive 0.12.3", + "prost-derive 0.12.6", ] [[package]] @@ -10106,7 +10103,7 @@ dependencies = [ "log", "multimap", "petgraph", - "prettyplease 0.1.11", + "prettyplease 0.1.25", "prost 0.11.9", "prost-types", "regex", @@ -10130,15 +10127,15 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.12.3" +version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efb6c9a1dd1def8e2124d17e83a20af56f1570d6c2d2bd9e266ccb768df3840e" +checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" dependencies = [ "anyhow", - "itertools 0.11.0", + "itertools 0.12.1", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -10218,9 +10215,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -10277,7 +10274,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom 0.2.12", + "getrandom 0.2.15", ] [[package]] @@ -10355,13 +10352,22 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "redox_syscall" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" +dependencies = [ + "bitflags 2.6.0", +] + [[package]] name = "redox_users" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" dependencies = [ - "getrandom 0.2.12", + "getrandom 0.2.15", "libredox", "thiserror", ] @@ -10380,22 +10386,22 @@ dependencies = [ [[package]] name = "ref-cast" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4846d4c50d1721b1a3bef8af76924eef20d5e723647333798c1b519b3a9473f" +checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fddb4f8d99b0a2ebafc65a87a69a7b9875e4b1ae1f00db265d300ef7f28bccc" +checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -10412,14 +10418,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.4" +version = "1.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" +checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.6", - "regex-syntax 0.8.3", + "regex-automata 0.4.7", + "regex-syntax 0.8.4", ] [[package]] @@ -10433,13 +10439,13 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" +checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.3", + "regex-syntax 0.8.4", ] [[package]] @@ -10450,9 +10456,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" +checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" [[package]] name = "resolv-conf" @@ -10471,7 +10477,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ "hmac 0.12.1", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -10497,7 +10503,7 @@ checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" dependencies = [ "cc", "cfg-if", - "getrandom 0.2.12", + "getrandom 0.2.15", "libc", "spin 0.9.8", "untrusted 0.9.0", @@ -10692,9 +10698,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.23" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustc-hash" @@ -10714,7 +10720,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver 1.0.22", + "semver 1.0.23", ] [[package]] @@ -10756,14 +10762,14 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.32" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "errno", "libc", - "linux-raw-sys 0.4.13", + "linux-raw-sys 0.4.14", "windows-sys 0.52.0", ] @@ -10781,9 +10787,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.10" +version = "0.21.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" dependencies = [ "log", "ring 0.17.8", @@ -10793,15 +10799,15 @@ dependencies = [ [[package]] name = "rustls" -version = "0.22.3" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99008d7ad0bbbea527ec27bddbc0e432c5b87d8175178cee68d2eec9c4a1813c" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" dependencies = [ "log", "ring 0.17.8", "rustls-pki-types", - "rustls-webpki 0.102.2", - "subtle 2.5.0", + "rustls-webpki 0.102.5", + "subtle 2.6.1", "zeroize", ] @@ -10819,12 +10825,12 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fb85efa936c42c6d5fc28d2629bb51e4b2f4b8a5211e297d599cc5a093792" +checksum = "a88d6d420651b496bdd98684116959239430022a115c1240e6c3993be0b15fba" dependencies = [ "openssl-probe", - "rustls-pemfile 2.1.1", + "rustls-pemfile 2.1.2", "rustls-pki-types", "schannel", "security-framework", @@ -10841,19 +10847,19 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "2.1.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f48172685e6ff52a556baa527774f61fcaa884f59daf3375c62a3f1cd2549dab" +checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "rustls-pki-types", ] [[package]] name = "rustls-pki-types" -version = "1.4.1" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247" +checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" [[package]] name = "rustls-webpki" @@ -10867,9 +10873,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.102.2" +version = "0.102.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faaa0a62740bedb9b2ef5afa303da42764c012f743917351dc9a237ea1663610" +checksum = "f9a6fccd794a42c2c105b513a2f62bc3fd8f3ba57a4593677ceb0bd035164d78" dependencies = [ "ring 0.17.8", "rustls-pki-types", @@ -10878,9 +10884,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.14" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" +checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" [[package]] name = "ruzstd" @@ -10917,15 +10923,15 @@ dependencies = [ [[package]] name = "ryu" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "safe_arch" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f398075ce1e6a179b46f51bd88d0598b92b00d3551f1a2d4ac49e771b56ac354" +checksum = "c3460605018fdc9612bce72735cba0d27efbcd9904780d44c7e3a9948f96148a" dependencies = [ "bytemuck", ] @@ -10966,7 +10972,7 @@ dependencies = [ "multihash 0.18.1", "multihash-codetable", "parity-scale-codec", - "prost 0.12.3", + "prost 0.12.6", "prost-build", "rand", "sc-client-api", @@ -11026,7 +11032,7 @@ version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f73880050f8b04fed7f6301279ef3899df13a3891bd06156d56f9a1c50fefba" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "docify", "log", "memmap2 0.9.4", @@ -11056,7 +11062,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -11065,7 +11071,7 @@ version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8a284c10ea92b1fe789b9f0e5815d393f3a1e3bf6a4adaa884f24e36143b83b" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "bip39", "chrono", "clap", @@ -11111,7 +11117,7 @@ dependencies = [ "futures", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-executor", "sc-transaction-pool-api", "sc-utils", @@ -11143,7 +11149,7 @@ dependencies = [ "log", "parity-db", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-client-api", "sc-state-db", "schnellru", @@ -11168,7 +11174,7 @@ dependencies = [ "libp2p-identity", "log", "mockall", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-client-api", "sc-utils", "serde", @@ -11226,7 +11232,7 @@ dependencies = [ "num-rational", "num-traits", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-client-api", "sc-consensus", "sc-consensus-epochs", @@ -11278,14 +11284,14 @@ version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9ce3ee15eff7fa642791966d427f185184df3c7f4e58893705f3e7781da8ef5" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "async-channel 1.9.0", "async-trait", "fnv", "futures", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-client-api", "sc-consensus", "sc-network", @@ -11319,7 +11325,7 @@ dependencies = [ "jsonrpsee 0.20.3", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-consensus-beefy", "sc-rpc", "serde", @@ -11350,7 +11356,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ae91e5b5a120be4d13a59eaf94fd85d7c7af528482b8e21d861fa1167df3083" dependencies = [ "ahash 0.8.11", - "array-bytes 6.2.2", + "array-bytes 6.2.3", "async-trait", "dyn-clone", "finality-grandpa", @@ -11359,7 +11365,7 @@ dependencies = [ "futures-timer", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "sc-block-builder", "sc-chain-spec", @@ -11439,7 +11445,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa2ac6c356538d67987bbb867e11a12a84ba87250c70fd50005b6d74f570a4f7" dependencies = [ "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-executor-common", "sc-executor-wasmtime", "schnellru", @@ -11478,7 +11484,7 @@ dependencies = [ "cfg-if", "libc", "log", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rustix 0.36.17", "sc-allocator", "sc-executor-common", @@ -11511,8 +11517,8 @@ version = "26.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cc4f6a558dd23e3bae2e9f195da822465258b9aaf211c34360d7f6efb944e54" dependencies = [ - "array-bytes 6.2.2", - "parking_lot 0.12.1", + "array-bytes 6.2.3", + "parking_lot 0.12.3", "serde_json", "sp-application-crypto", "sp-core", @@ -11537,7 +11543,7 @@ dependencies = [ "mixnet", "multiaddr", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-client-api", "sc-network", "sc-transaction-pool-api", @@ -11556,7 +11562,7 @@ version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f231c7d5e749ec428b4cfa669d759ae76cd3da4f50d7352a2d711acdc7532891" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "async-channel 1.9.0", "async-trait", "asynchronous-codec", @@ -11571,7 +11577,7 @@ dependencies = [ "log", "mockall", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "partial_sort", "pin-project", "rand", @@ -11605,7 +11611,7 @@ dependencies = [ "futures", "libp2p-identity", "log", - "prost 0.12.3", + "prost 0.12.6", "prost-build", "sc-client-api", "sc-network", @@ -11659,13 +11665,13 @@ version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38d84ef0b212c775f58e0304ec09166089f6b09afddf559b7c2b5702933b3be4" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "async-channel 1.9.0", "futures", "libp2p-identity", "log", "parity-scale-codec", - "prost 0.12.3", + "prost 0.12.6", "prost-build", "sc-client-api", "sc-network", @@ -11681,7 +11687,7 @@ version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9aa9377059deece4e7d419d9ec456f657268c0c603e1cf98df4a920f6da83461" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "async-channel 1.9.0", "async-trait", "fork-tree", @@ -11691,7 +11697,7 @@ dependencies = [ "log", "mockall", "parity-scale-codec", - "prost 0.12.3", + "prost 0.12.6", "prost-build", "sc-client-api", "sc-consensus", @@ -11718,7 +11724,7 @@ version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16c9cad4baf348725bd82eadcd1747fc112ec49c76b863755ce79c588fa73fe4" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "futures", "libp2p", "log", @@ -11738,7 +11744,7 @@ version = "30.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aee89f2abd406356bfd688bd7a51155dc963259e4b752bb85d1f8a061a194fd" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "bytes", "fnv", "futures", @@ -11750,7 +11756,7 @@ dependencies = [ "num_cpus", "once_cell", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "sc-client-api", "sc-network", @@ -11787,7 +11793,7 @@ dependencies = [ "jsonrpsee 0.20.3", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-block-builder", "sc-chain-spec", "sc-client-api", @@ -11853,14 +11859,14 @@ version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7f10275c62296a785f6e2ac716521e3b6e0fae470416fdf86491cbbfcc2e23d" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "futures", "futures-util", "hex", "jsonrpsee 0.20.3", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-chain-spec", "sc-client-api", "sc-rpc", @@ -11892,7 +11898,7 @@ dependencies = [ "jsonrpsee 0.20.3", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "pin-project", "rand", "sc-chain-spec", @@ -11950,7 +11956,7 @@ checksum = "aa842052c41ad379eaecdfddc0d5c953d57e311ae688233f68f461b91d38da0a" dependencies = [ "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sp-core", ] @@ -12020,7 +12026,7 @@ dependencies = [ "futures", "libp2p", "log", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "pin-project", "rand", "sc-utils", @@ -12043,7 +12049,7 @@ dependencies = [ "libc", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "regex", "rustc-hash", "sc-client-api", @@ -12070,7 +12076,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -12085,7 +12091,7 @@ dependencies = [ "linked-hash-map", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sc-client-api", "sc-transaction-pool-api", "sc-utils", @@ -12129,7 +12135,7 @@ dependencies = [ "futures-timer", "lazy_static", "log", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "prometheus", "sp-arithmetic", ] @@ -12167,7 +12173,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3475108a1b62c7efd1b5c65974f30109a598b2f45f23c9ae030acb9686966db" dependencies = [ "darling 0.14.4", - "proc-macro-crate 1.3.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn 1.0.109", @@ -12195,7 +12201,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "995491f110efdc6bea96d6a746140e32bfceb4ea47510750a5467295a4707a25" dependencies = [ "darling 0.14.4", - "proc-macro-crate 1.3.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn 1.0.109", @@ -12203,9 +12209,9 @@ dependencies = [ [[package]] name = "scale-info" -version = "2.11.1" +version = "2.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "788745a868b0e751750388f4e6546eb921ef714a4317fa6954f7cde114eb2eb7" +checksum = "eca070c12893629e2cc820a9761bedf6ce1dcddc9852984d1dc734b8bd9bd024" dependencies = [ "bitvec", "cfg-if", @@ -12217,11 +12223,11 @@ dependencies = [ [[package]] name = "scale-info-derive" -version = "2.11.1" +version = "2.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dc2f4e8bc344b9fc3d5f74f72c2e55bfc38d28dc2ebc69c194a3df424e4d9ac" +checksum = "2d35494501194174bda522a32605929eefc9ecf7e0a326c26db1fdd85881eb62" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate 3.1.0", "proc-macro2", "quote", "syn 1.0.109", @@ -12236,7 +12242,7 @@ dependencies = [ "proc-macro2", "quote", "scale-info", - "syn 2.0.58", + "syn 2.0.71", "thiserror", ] @@ -12271,9 +12277,9 @@ dependencies = [ [[package]] name = "schnellru" -version = "0.2.1" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "772575a524feeb803e5b0fcbc6dd9f367e579488197c94c6e4023aad2305774d" +checksum = "c9a8ef13a93c54d20580de1e5c413e624e53121d42fc7e2c11d10ef7f8b02367" dependencies = [ "ahash 0.8.11", "cfg-if", @@ -12305,13 +12311,13 @@ dependencies = [ "aead", "arrayref", "arrayvec 0.7.4", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "getrandom_or_panic", "merlin", "rand_core 0.6.4", "serde_bytes", "sha2 0.10.8", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] @@ -12347,7 +12353,7 @@ dependencies = [ "der", "generic-array 0.14.7", "pkcs8", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] @@ -12389,11 +12395,11 @@ dependencies = [ [[package]] name = "security-framework" -version = "2.10.0" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.6.0", "core-foundation", "core-foundation-sys", "libc", @@ -12402,9 +12408,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.10.0" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef" +checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf" dependencies = [ "core-foundation-sys", "libc", @@ -12421,9 +12427,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d43fe69e652f3df9bdc2b85b2854a0825b86e4fb76bc44d945137d053639ca" +checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" dependencies = [ "serde", ] @@ -12436,9 +12442,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -version = "1.0.197" +version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" +checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" dependencies = [ "serde_derive", ] @@ -12454,29 +12460,29 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.14" +version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b8497c313fd43ab992087548117643f6fcd935cbf36f176ffda0aacf9591734" +checksum = "387cc504cb06bb40a96c8e04e951fe01854cf6bc921053c954e4a606d9675c6a" dependencies = [ "serde", ] [[package]] name = "serde_derive" -version = "1.0.197" +version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" +checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "serde_json" -version = "1.0.115" +version = "1.0.120" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd" +checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" dependencies = [ "itoa", "ryu", @@ -12485,9 +12491,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" +checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" dependencies = [ "serde", ] @@ -12567,9 +12573,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" dependencies = [ "libc", ] @@ -12681,13 +12687,13 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e635339259e51ef85ac7aa29a1cd991b957047507288697a690e80ab97d07cad" dependencies = [ - "async-channel 2.2.0", + "async-channel 2.3.1", "async-executor", - "async-fs 2.1.1", - "async-io 2.3.2", - "async-lock 3.3.0", + "async-fs 2.1.2", + "async-io 2.3.3", + "async-lock 3.4.0", "async-net 2.0.0", - "async-process 2.1.0", + "async-process 2.2.3", "blocking", "futures-lite 2.3.0", ] @@ -12714,7 +12720,7 @@ dependencies = [ "fnv", "futures-lite 1.13.0", "futures-util", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "hex", "hmac 0.12.1", "itertools 0.11.0", @@ -12753,7 +12759,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d1eaa97d77be4d026a1e7ffad1bb3b78448763b357ea6f8188d3e6f736a9b9" dependencies = [ "arrayvec 0.7.4", - "async-lock 3.3.0", + "async-lock 3.4.0", "atomic-take", "base64 0.21.7", "bip39", @@ -12768,7 +12774,7 @@ dependencies = [ "fnv", "futures-lite 2.3.0", "futures-util", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "hex", "hmac 0.12.1", "itertools 0.12.1", @@ -12818,13 +12824,13 @@ dependencies = [ "futures-channel", "futures-lite 1.13.0", "futures-util", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "hex", "itertools 0.11.0", "log", "lru 0.11.1", "no-std-net", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "pin-project", "rand", "rand_chacha 0.3.1", @@ -12843,8 +12849,8 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5496f2d116b7019a526b1039ec2247dd172b8670633b1a64a614c9ea12c9d8c7" dependencies = [ - "async-channel 2.2.0", - "async-lock 3.3.0", + "async-channel 2.3.1", + "async-lock 3.4.0", "base64 0.21.7", "blake2-rfc", "derive_more", @@ -12854,13 +12860,13 @@ dependencies = [ "futures-channel", "futures-lite 2.3.0", "futures-util", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "hex", "itertools 0.12.1", "log", "lru 0.12.3", "no-std-net", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "pin-project", "rand", "rand_chacha 0.3.1", @@ -12888,12 +12894,12 @@ dependencies = [ "aes-gcm", "blake2 0.10.6", "chacha20poly1305", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "rand_core 0.6.4", "ring 0.17.8", "rustc_version", "sha2 0.10.8", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -12908,9 +12914,9 @@ dependencies = [ [[package]] name = "snowbridge-beacon-primitives" -version = "0.1.0" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a73ef707257064bc4ecce8323cdb7c30e8ecd1ce74aa89a6e82e81fa8b9970" +checksum = "5404af73550b39022e08e5500b30fba627e109a56407b7e80b08da2305b11bfe" dependencies = [ "byte-slice-cast", "frame-support", @@ -12933,9 +12939,9 @@ dependencies = [ [[package]] name = "snowbridge-core" -version = "0.1.1" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a3e2e3b94bfcfc8f363e21a6c5a1d3c67eb4592ada672c868a3236ad1dd563b" +checksum = "aed4ebefed4c40b9c00e9adf5f02ab2760a7a2dad8bf05110c0013a7a59f4097" dependencies = [ "ethabi-decode", "frame-support", @@ -13029,9 +13035,9 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.6" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" dependencies = [ "libc", "windows-sys 0.52.0", @@ -13084,11 +13090,11 @@ checksum = "0301e2f77afb450fbf2b093f8b324c7ad88cc82e5e69bd5dc8658a1f068b2a96" dependencies = [ "Inflector", "blake2 0.10.6", - "expander 2.1.0", + "expander 2.2.1", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -13155,7 +13161,7 @@ dependencies = [ "futures", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "schnellru", "sp-api", "sp-consensus", @@ -13278,7 +13284,7 @@ version = "29.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c33c7a1568175250628567d50c4e1c54a6ac5bc1190413b9be29a9e810cbe73" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "bip39", "bitflags 1.3.2", "blake2 0.10.6", @@ -13295,7 +13301,7 @@ dependencies = [ "log", "merlin", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "paste", "primitive-types", "rand", @@ -13354,7 +13360,7 @@ checksum = "b85d0f1f1e44bd8617eb2a48203ee854981229e3e79e6f468c7175d5fd37489b" dependencies = [ "quote", "sp-crypto-hashing", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -13364,7 +13370,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "722cbecdbf5b94578137dbd07feb51e95f7de221be0c1ff4dcfe0bb4cd986929" dependencies = [ "kvdb", - "parking_lot 0.12.1", + "parking_lot 0.12.3", ] [[package]] @@ -13375,7 +13381,7 @@ checksum = "48d09fa0a5f7299fb81ee25ae3853d26200f7a348148aed6de76be905c007dbe" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -13461,7 +13467,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "444f2d53968b1ce5e908882710ff1f3873fcf3e95f59d57432daf685bbacb959" dependencies = [ "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "sp-core", "sp-externalities", "thiserror", @@ -13620,11 +13626,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfaf6e85b2ec12a4b99cd6d8d57d083e30c94b7f1b0d8f93547121495aae6f0c" dependencies = [ "Inflector", - "expander 2.1.0", + "expander 2.2.1", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -13667,7 +13673,7 @@ dependencies = [ "hash-db", "log", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "smallvec", "sp-core", @@ -13687,7 +13693,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "309a9ae4e8134bbed8ffc510cf4d461a4a651f9250b556de782cedd876abe1ff" dependencies = [ "aes-gcm", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "ed25519-dalek", "hkdf", "parity-scale-codec", @@ -13791,7 +13797,7 @@ dependencies = [ "memory-db", "nohash-hasher", "parity-scale-codec", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "scale-info", "schnellru", @@ -13831,7 +13837,7 @@ dependencies = [ "parity-scale-codec", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -13962,7 +13968,7 @@ version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48fa328b87de3466bc38cc9a07244c42c647b7755b81115e1dfeb47cc13fc6e6" dependencies = [ - "array-bytes 6.2.2", + "array-bytes 6.2.3", "bounded-collections 0.2.0", "derivative", "environmental", @@ -14063,7 +14069,7 @@ dependencies = [ "bitflags 1.3.2", "byteorder", "keccak", - "subtle 2.5.0", + "subtle 2.6.1", "zeroize", ] @@ -14090,9 +14096,9 @@ dependencies = [ [[package]] name = "strum" -version = "0.25.0" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" [[package]] name = "strum_macros" @@ -14109,15 +14115,15 @@ dependencies = [ [[package]] name = "strum_macros" -version = "0.25.3" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "rustversion", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -14218,7 +14224,7 @@ dependencies = [ "sp-maybe-compressed-blob", "strum 0.24.1", "tempfile", - "toml 0.8.12", + "toml 0.8.14", "walkdir", "wasm-opt", ] @@ -14231,9 +14237,9 @@ checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" [[package]] name = "subtle" -version = "2.5.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "subtle-ng" @@ -14293,7 +14299,7 @@ dependencies = [ "scale-info", "scale-typegen", "subxt-metadata", - "syn 2.0.58", + "syn 2.0.71", "thiserror", "tokio", ] @@ -14321,13 +14327,13 @@ version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "365251668613323064803427af8c7c7bc366cd8b28e33639640757669dafebd5" dependencies = [ - "darling 0.20.8", + "darling 0.20.10", "parity-scale-codec", "proc-macro-error", "quote", "scale-typegen", "subxt-codegen", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -14378,9 +14384,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.58" +version = "2.0.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687" +checksum = "b146dcf730474b4bcd16c311627b31ede9ab149045db4d6088b3becaea046462" dependencies = [ "proc-macro2", "quote", @@ -14399,6 +14405,17 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.71", +] + [[package]] name = "system-configuration" version = "0.5.1" @@ -14428,9 +14445,9 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "target-lexicon" -version = "0.12.14" +version = "0.12.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1fc403891a21bcfb7c37834ba66a547a8f402146eba7265b5a6d88059c9ff2f" +checksum = "4873307b7c257eddcb50c9bedf158eb669578359fb28428bef438fec8e6ba7c2" [[package]] name = "tempfile" @@ -14439,8 +14456,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", - "fastrand 2.0.2", - "rustix 0.38.32", + "fastrand 2.1.0", + "rustix 0.38.34", "windows-sys 0.52.0", ] @@ -14459,7 +14476,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21bebf2b7c9e0a515f6e0f8c51dc0f8e4696391e6f1ff30379559f8365fb0df7" dependencies = [ - "rustix 0.38.32", + "rustix 0.38.34", "windows-sys 0.48.0", ] @@ -14486,9 +14503,9 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.58" +version = "1.0.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297" +checksum = "f2675633b1499176c2dff06b0856a27976a8f9d436737b4cf4f312d4d91d8bbb" dependencies = [ "thiserror-impl", ] @@ -14510,18 +14527,18 @@ checksum = "e4c60d69f36615a077cc7663b9cb8e42275722d23e58a7fa3d2c7f2915d09d04" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "thiserror-impl" -version = "1.0.58" +version = "1.0.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" +checksum = "d20468752b09f49e909e55a5d338caa8bedf615594e9d80bc4c565d30faf798c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -14585,9 +14602,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.34" +version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", @@ -14606,9 +14623,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ "num-conv", "time-core", @@ -14625,9 +14642,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.6.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" dependencies = [ "tinyvec_macros", ] @@ -14640,32 +14657,32 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.37.0" +version = "1.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787" +checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" dependencies = [ "backtrace", "bytes", "libc", "mio", "num_cpus", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "pin-project-lite 0.2.14", "signal-hook-registry", - "socket2 0.5.6", + "socket2 0.5.7", "tokio-macros", "windows-sys 0.48.0", ] [[package]] name = "tokio-macros" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" +checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -14685,7 +14702,7 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls 0.21.10", + "rustls 0.21.12", "tokio", ] @@ -14695,7 +14712,7 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" dependencies = [ - "rustls 0.22.3", + "rustls 0.22.4", "rustls-pki-types", "tokio", ] @@ -14714,9 +14731,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.10" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15" +checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" dependencies = [ "bytes", "futures-core", @@ -14724,7 +14741,6 @@ dependencies = [ "futures-sink", "pin-project-lite 0.2.14", "tokio", - "tracing", ] [[package]] @@ -14738,36 +14754,25 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.12" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9dd1545e8208b4a5af1aa9bbd0b4cf7e9ea08fabc5d0a5c67fcaafa17433aa3" +checksum = "6f49eb2ab21d2f26bd6db7bf383edc527a7ebaee412d17af4d40fdccd442f335" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.9", + "toml_edit 0.22.15", ] [[package]] name = "toml_datetime" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" +checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" dependencies = [ "serde", ] -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.2.6", - "toml_datetime", - "winnow 0.5.40", -] - [[package]] name = "toml_edit" version = "0.20.7" @@ -14792,15 +14797,15 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.9" +version = "0.22.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e40bb779c5187258fd7aad0eb68cb8706a0a81fa712fbea808ab43c4b8374c4" +checksum = "d59a3a72298453f564e2b111fa896f8d07fabb36f51f06d7e875fc5e0b5a3ef1" dependencies = [ "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.5", + "winnow 0.6.13", ] [[package]] @@ -14824,7 +14829,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "bytes", "futures-core", "futures-util", @@ -14868,7 +14873,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -14909,11 +14914,11 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f074568687ffdfd0adb6005aa8d1d96840197f2c159f80471285f08694cf0ce" dependencies = [ - "expander 2.1.0", + "expander 2.2.1", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -15046,7 +15051,7 @@ dependencies = [ "ipconfig", "lazy_static", "lru-cache", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "resolv-conf", "smallvec", "thiserror", @@ -15163,9 +15168,9 @@ dependencies = [ [[package]] name = "unicode-width" -version = "0.1.11" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" +checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" [[package]] name = "unicode-xid" @@ -15180,7 +15185,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ "crypto-common", - "subtle 2.5.0", + "subtle 2.6.1", ] [[package]] @@ -15209,9 +15214,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.0" +version = "2.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" +checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" dependencies = [ "form_urlencoded", "idna 0.5.0", @@ -15220,9 +15225,9 @@ dependencies = [ [[package]] name = "utf8parse" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "valuable" @@ -15250,9 +15255,9 @@ checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" [[package]] name = "w3f-bls" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7335e4c132c28cc43caef6adb339789e599e39adbe78da0c4d547fad48cbc331" +checksum = "9c5da5fa2c6afa2c9158eaa7cd9aee249765eb32b5fb0c63ad8b9e79336a47ec" dependencies = [ "ark-bls12-377", "ark-bls12-381", @@ -15274,9 +15279,9 @@ dependencies = [ [[package]] name = "waker-fn" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c4517f54858c779bbcbf228f4fca63d121bf85fbecb2dc578cdf4a39395690" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" [[package]] name = "walkdir" @@ -15339,7 +15344,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", "wasm-bindgen-shared", ] @@ -15373,7 +15378,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -15491,9 +15496,9 @@ dependencies = [ [[package]] name = "wasmparser-nostd" -version = "0.100.1" +version = "0.100.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9157cab83003221bfd385833ab587a039f5d6fa7304854042ba358a3b09e0724" +checksum = "d5a015fe95f3504a94bb1462c717aae75253e39b9dd6c3fb1062c934535c64aa" dependencies = [ "indexmap-nostd", ] @@ -15724,15 +15729,16 @@ dependencies = [ [[package]] name = "westend-runtime" -version = "8.0.0" +version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2a5cebb4c678a0d1291bb21f9d44ddebceae044b0fb5200fa3bed108a31595" +checksum = "b4aa5580861b05668a6af845aa271c4f699a2fc26646d524e5b0d9375fb0647e" dependencies = [ "binary-merkle-tree", "bitvec", "frame-benchmarking", "frame-election-provider-support", "frame-executive", + "frame-metadata-hash-extension", "frame-support", "frame-system", "frame-system-benchmarking", @@ -15855,14 +15861,14 @@ dependencies = [ "either", "home", "once_cell", - "rustix 0.38.32", + "rustix 0.38.34", ] [[package]] name = "wide" -version = "0.7.15" +version = "0.7.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89beec544f246e679fc25490e3f8e08003bc4bf612068f325120dad4cea02c1c" +checksum = "2caba658a80831539b30698ae9862a72db6697dfdd7151e46920f5f2755c3ce2" dependencies = [ "bytemuck", "safe_arch", @@ -15870,9 +15876,9 @@ dependencies = [ [[package]] name = "widestring" -version = "1.0.2" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "653f141f39ec16bba3c5abe400a0c60da7468261cc2cbf36805022876bc721a8" +checksum = "7219d36b6eac893fa81e84ebe06485e7dcbb616177469b142df14f1f4deb1311" [[package]] name = "winapi" @@ -15892,11 +15898,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" +checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" dependencies = [ - "winapi", + "windows-sys 0.52.0", ] [[package]] @@ -15930,7 +15936,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.4", + "windows-targets 0.52.6", ] [[package]] @@ -15957,7 +15963,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.4", + "windows-targets 0.52.6", ] [[package]] @@ -15992,17 +15998,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.4" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.4", - "windows_aarch64_msvc 0.52.4", - "windows_i686_gnu 0.52.4", - "windows_i686_msvc 0.52.4", - "windows_x86_64_gnu 0.52.4", - "windows_x86_64_gnullvm 0.52.4", - "windows_x86_64_msvc 0.52.4", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -16019,9 +16026,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.4" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" @@ -16037,9 +16044,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.4" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" @@ -16055,9 +16062,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.4" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" @@ -16073,9 +16086,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.4" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" @@ -16091,9 +16104,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.4" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" @@ -16109,9 +16122,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.4" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" @@ -16127,9 +16140,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.4" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" @@ -16142,9 +16155,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.5" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8" +checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" dependencies = [ "memchr", ] @@ -16185,7 +16198,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" dependencies = [ - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "rand_core 0.6.4", "serde", "zeroize", @@ -16253,7 +16266,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -16265,7 +16278,7 @@ dependencies = [ "futures", "log", "nohash-hasher", - "parking_lot 0.12.1", + "parking_lot 0.12.3", "rand", "static_assertions", ] @@ -16287,29 +16300,29 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.7.32" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.7.32" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] name = "zeroize" -version = "1.7.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" dependencies = [ "zeroize_derive", ] @@ -16322,7 +16335,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.71", ] [[package]] @@ -16365,9 +16378,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.10+zstd.1.5.6" +version = "2.0.12+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa" +checksum = "0a4e40c320c3cb459d9a9ff6de98cff88f4751ee9275d140e2be94a2b74e4c13" dependencies = [ "cc", "pkg-config", diff --git a/runtime/devnet/Cargo.toml b/runtime/devnet/Cargo.toml index 7db68576..70e6e9c9 100644 --- a/runtime/devnet/Cargo.toml +++ b/runtime/devnet/Cargo.toml @@ -22,7 +22,7 @@ scale-info.workspace = true smallvec.workspace = true # Local -pop-primitives = { workspace = true, default-features = false, features = ["assets", "cross-chain", "nfts"] } +pop-primitives = { workspace = true, features = ["assets", "cross-chain", "nfts"] } pop-runtime-common = { workspace = true, default-features = false } # Substrate diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index 8f0a6eda..c6bab850 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -307,8 +307,8 @@ pub(crate) fn convert_to_status_code(error: DispatchError, version: u8) -> u32 { // "UnknownFunctionId" and "DecodingFailed" are mapped to specific errors in the API and will // never change. let mut encoded_error = match error { - DispatchError::Other("UnknownFunctionId") => vec![254, 0, 0, 0], - DispatchError::Other("DecodingFailed") => vec![255, 0, 0, 0], + DispatchError::Other("UnknownFunctionId") => Vec::from([254u8, 0, 0, 0]), + DispatchError::Other("DecodingFailed") => Vec::from([255u8, 0, 0, 0]), _ => error.encode(), }; // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index 61d3cb43..866cb12c 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -206,7 +206,7 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, - _ => Ok(vec![0u8]), + _ => Ok(Vec::from([0u8])), }? .encode(); From 8730f90d07dbd1ce564a14a19bb1288a70ddaa4b Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Wed, 17 Jul 2024 17:47:38 +0200 Subject: [PATCH 21/27] refactor: decoding failed and commenting out unimplemented tests --- .../integration-tests/src/local_fungibles.rs | 448 +++++++++--------- pop-api/src/lib.rs | 4 +- pop-api/src/v0/assets/mod.rs | 14 +- primitives/src/lib.rs | 2 +- runtime/devnet/src/extensions/mod.rs | 2 +- 5 files changed, 236 insertions(+), 234 deletions(-) diff --git a/pop-api/integration-tests/src/local_fungibles.rs b/pop-api/integration-tests/src/local_fungibles.rs index d0229c84..bef3aa6a 100644 --- a/pop-api/integration-tests/src/local_fungibles.rs +++ b/pop-api/integration-tests/src/local_fungibles.rs @@ -67,37 +67,6 @@ fn token_decimals(addr: AccountId32, asset_id: AssetId) -> u8 { decoded::(result) } -fn asset_exists(addr: AccountId32, asset_id: AssetId) -> bool { - let function = function_selector("asset_exists"); - let params = [function, asset_id.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); - decoded::(result) -} - -fn create( - addr: AccountId32, - asset_id: AssetId, - admin: AccountId32, - min_balance: Balance, -) -> ExecReturnValue { - let function = function_selector("create"); - let params = [function, asset_id.encode(), admin.encode(), min_balance.encode()].concat(); - do_bare_call(addr, params, 0).expect("should work") -} - -fn set_metadata( - addr: AccountId32, - asset_id: AssetId, - name: Vec, - symbol: Vec, - decimals: u8, -) -> ExecReturnValue { - let function = function_selector("set_metadata"); - let params = - [function, asset_id.encode(), name.encode(), symbol.encode(), decimals.encode()].concat(); - do_bare_call(addr, params, 0).expect("should work") -} - fn transfer( addr: AccountId32, asset_id: AssetId, @@ -137,18 +106,49 @@ fn increase_allowance( result } -fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { - assert_eq!( - Assets::create( - RuntimeOrigin::signed(owner.clone()), - asset_id.into(), - owner.into(), - min_balance - ), - Ok(()) - ); - asset_id -} +// fn asset_exists(addr: AccountId32, asset_id: AssetId) -> bool { +// let function = function_selector("asset_exists"); +// let params = [function, asset_id.encode()].concat(); +// let result = do_bare_call(addr, params, 0).expect("should work"); +// decoded::(result) +// } +// +// fn create( +// addr: AccountId32, +// asset_id: AssetId, +// admin: AccountId32, +// min_balance: Balance, +// ) -> ExecReturnValue { +// let function = function_selector("create"); +// let params = [function, asset_id.encode(), admin.encode(), min_balance.encode()].concat(); +// do_bare_call(addr, params, 0).expect("should work") +// } +// +// fn set_metadata( +// addr: AccountId32, +// asset_id: AssetId, +// name: Vec, +// symbol: Vec, +// decimals: u8, +// ) -> ExecReturnValue { +// let function = function_selector("set_metadata"); +// let params = +// [function, asset_id.encode(), name.encode(), symbol.encode(), decimals.encode()].concat(); +// do_bare_call(addr, params, 0).expect("should work") +// } +// +// fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { +// assert_eq!( +// Assets::create( +// RuntimeOrigin::signed(owner.clone()), +// asset_id.into(), +// owner.into(), +// min_balance +// ), +// Ok(()) +// ); +// asset_id +// } fn mint_asset(owner: AccountId32, asset_id: AssetId, to: AccountId32, value: Balance) -> AssetId { assert_eq!( @@ -393,52 +393,52 @@ fn transfer_works() { #[test] #[ignore] -fn increase_allowance_works() { +fn transfer_from_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![]); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); let amount: Balance = 100 * UNIT; - let asset = 0; - create_asset_and_mint_to(ALICE, asset, addr.clone(), amount); - assert_eq!( - decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), - ConsumerRemaining - ); - let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); // Asset does not exist. - let asset = 1; assert_eq!( - decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + decoded::(transfer(addr.clone(), 1, BOB, amount,)), Module { index: 52, error: 3 }, ); // Create asset with Alice as owner and mint `amount` to contract address. - create_asset_and_mint_to(ALICE, asset, addr.clone(), amount); + let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); // Asset is not live, i.e. frozen or being destroyed. freeze_asset(ALICE, asset); assert_eq!( - decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + decoded::(transfer(addr.clone(), asset, BOB, amount,)), Module { index: 52, error: 16 }, ); thaw_asset(ALICE, asset); - // Successful approval. - assert_eq!(0, Assets::allowance(asset, &addr, &BOB)); - assert!( - !increase_allowance(addr.clone(), asset, BOB, amount).did_revert(), - "Contract reverted!" + // Not enough balance. + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), + Module { index: 52, error: 0 }, ); - assert_eq!(Assets::allowance(asset, &addr, &BOB), amount); - // Additive. - assert!( - !increase_allowance(addr.clone(), asset, BOB, amount).did_revert(), - "Contract reverted!" + // Not enough balance due to ED. + assert_eq!( + decoded::(transfer(addr.clone(), asset, BOB, amount)), + Module { index: 52, error: 0 }, + ); + // Successful transfer. + let bob_balance_before_mint = Assets::balance(asset, &BOB); + let result = transfer(addr.clone(), asset, BOB, amount / 2); + assert!(!result.did_revert(), "Contract reverted!"); + let bob_balance_after_mint = Assets::balance(asset, &BOB); + assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); + // Transfer asset to account that does not exist. + assert_eq!( + decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), + Token(CannotCreate) ); - assert_eq!(Assets::allowance(asset, &addr, &BOB), amount * 2); // Asset is not live, i.e. frozen or being destroyed. start_destroy_asset(ALICE, asset); assert_eq!( - decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), Module { index: 52, error: 16 }, ); }); @@ -446,52 +446,52 @@ fn increase_allowance_works() { #[test] #[ignore] -fn transfer_from_works() { +fn increase_allowance_works() { new_test_ext().execute_with(|| { let _ = env_logger::try_init(); - let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); + let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![]); let amount: Balance = 100 * UNIT; + let asset = 0; + create_asset_and_mint_to(ALICE, asset, addr.clone(), amount); + assert_eq!( + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), + ConsumerRemaining + ); + let addr = + instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); // Asset does not exist. + let asset = 1; assert_eq!( - decoded::(transfer(addr.clone(), 1, BOB, amount,)), + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), Module { index: 52, error: 3 }, ); // Create asset with Alice as owner and mint `amount` to contract address. - let asset = create_asset_and_mint_to(ALICE, 1, addr.clone(), amount); + create_asset_and_mint_to(ALICE, asset, addr.clone(), amount); // Asset is not live, i.e. frozen or being destroyed. freeze_asset(ALICE, asset); assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount,)), + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), Module { index: 52, error: 16 }, ); thaw_asset(ALICE, asset); - // Not enough balance. - assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount + 1 * UNIT)), - Module { index: 52, error: 0 }, - ); - // Not enough balance due to ED. - assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount)), - Module { index: 52, error: 0 }, + // Successful approval. + assert_eq!(0, Assets::allowance(asset, &addr, &BOB)); + assert!( + !increase_allowance(addr.clone(), asset, BOB, amount).did_revert(), + "Contract reverted!" ); - // Successful transfer. - let bob_balance_before_mint = Assets::balance(asset, &BOB); - let result = transfer(addr.clone(), asset, BOB, amount / 2); - assert!(!result.did_revert(), "Contract reverted!"); - let bob_balance_after_mint = Assets::balance(asset, &BOB); - assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount / 2); - // Transfer asset to account that does not exist. - assert_eq!( - decoded::(transfer(addr.clone(), asset, FERDIE, amount / 4)), - Token(CannotCreate) + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount); + // Additive. + assert!( + !increase_allowance(addr.clone(), asset, BOB, amount).did_revert(), + "Contract reverted!" ); + assert_eq!(Assets::allowance(asset, &addr, &BOB), amount * 2); // Asset is not live, i.e. frozen or being destroyed. start_destroy_asset(ALICE, asset); assert_eq!( - decoded::(transfer(addr.clone(), asset, BOB, amount / 4)), + decoded::(increase_allowance(addr.clone(), asset, BOB, amount)), Module { index: 52, error: 16 }, ); }); @@ -540,132 +540,132 @@ fn token_metadata_works() { }); } -#[test] -#[ignore] -fn asset_exists_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); - - // No tokens in circulation. - assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr.clone(), ASSET_ID)); - - // Tokens in circulation. - create_asset(addr.clone(), ASSET_ID, 1); - assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr, ASSET_ID)); - }); -} - -#[test] -#[ignore] -fn mint_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); - let amount: Balance = 100 * UNIT; - - // Asset does not exist. - assert_eq!( - decoded::(transfer_from(addr.clone(), 1, None, Some(BOB), amount, &[0u8])), - Token(UnknownAsset) - ); - let asset = create_asset(ALICE, 1, 2); - // Minting can only be done by the owner. - assert_eq!( - decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), - Module { index: 52, error: 2 }, - ); - // Minimum balance of an asset can not be zero. - assert_eq!( - decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), 1, &[0u8])), - Token(BelowMinimum) - ); - let asset = create_asset(addr.clone(), 2, 2); - // Asset is not live, i.e. frozen or being destroyed. - freeze_asset(addr.clone(), asset); - assert_eq!( - decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), - Module { index: 52, error: 16 }, - ); - thaw_asset(addr.clone(), asset); - // Successful mint. - let bob_balance_before_mint = Assets::balance(asset, &BOB); - let result = transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8]); - assert!(!result.did_revert(), "Contract reverted!"); - let bob_balance_after_mint = Assets::balance(asset, &BOB); - assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount); - // Can not mint more tokens than Balance::MAX. - assert_eq!( - decoded::(transfer_from( - addr.clone(), - asset, - None, - Some(BOB), - Balance::MAX, - &[0u8] - )), - Arithmetic(Overflow) - ); - // Asset is not live, i.e. frozen or being destroyed. - start_destroy_asset(addr.clone(), asset); - assert_eq!( - decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), - Module { index: 52, error: 16 }, - ); - }); -} - -#[test] -#[ignore] -fn create_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - // Instantiate a contract without balance (relay token). - let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); - // No balance to pay for fees. - assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), - Module { index: 10, error: 2 }, - ); - // Instantiate a contract without balance (relay token). - let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 100, vec![2]); - // No balance to pay the deposit. - assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), - Module { index: 10, error: 2 }, - ); - // Instantiate a contract with balance. - let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); - assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, BOB, 0)), - Module { index: 52, error: 7 }, - ); - create_asset(ALICE, ASSET_ID, 1); - // Asset ID is already taken. - assert_eq!( - decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), - Module { index: 52, error: 5 }, - ); - // The minimal balance for an asset must be non zero. - let new_asset = 2; - let result = create(addr.clone(), new_asset, BOB, 1); - assert!(!result.did_revert(), "Contract reverted!"); - }); -} - -#[test] -#[ignore] -fn set_metadata_works() { - new_test_ext().execute_with(|| { - let _ = env_logger::try_init(); - let addr = - instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); - - create_asset(addr.clone(), ASSET_ID, 1); - let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); - assert!(!result.did_revert(), "Contract reverted!"); - }); -} +// #[test] +// #[ignore] +// fn asset_exists_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// let addr = +// instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); +// +// // No tokens in circulation. +// assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr.clone(), ASSET_ID)); +// +// // Tokens in circulation. +// create_asset(addr.clone(), ASSET_ID, 1); +// assert_eq!(Assets::asset_exists(ASSET_ID), asset_exists(addr, ASSET_ID)); +// }); +// } + +// #[test] +// #[ignore] +// fn mint_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// let addr = +// instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); +// let amount: Balance = 100 * UNIT; +// +// // Asset does not exist. +// assert_eq!( +// decoded::(transfer_from(addr.clone(), 1, None, Some(BOB), amount, &[0u8])), +// Token(UnknownAsset) +// ); +// let asset = create_asset(ALICE, 1, 2); +// // Minting can only be done by the owner. +// assert_eq!( +// decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), +// Module { index: 52, error: 2 }, +// ); +// // Minimum balance of an asset can not be zero. +// assert_eq!( +// decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), 1, &[0u8])), +// Token(BelowMinimum) +// ); +// let asset = create_asset(addr.clone(), 2, 2); +// // Asset is not live, i.e. frozen or being destroyed. +// freeze_asset(addr.clone(), asset); +// assert_eq!( +// decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), +// Module { index: 52, error: 16 }, +// ); +// thaw_asset(addr.clone(), asset); +// // Successful mint. +// let bob_balance_before_mint = Assets::balance(asset, &BOB); +// let result = transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8]); +// assert!(!result.did_revert(), "Contract reverted!"); +// let bob_balance_after_mint = Assets::balance(asset, &BOB); +// assert_eq!(bob_balance_after_mint, bob_balance_before_mint + amount); +// // Can not mint more tokens than Balance::MAX. +// assert_eq!( +// decoded::(transfer_from( +// addr.clone(), +// asset, +// None, +// Some(BOB), +// Balance::MAX, +// &[0u8] +// )), +// Arithmetic(Overflow) +// ); +// // Asset is not live, i.e. frozen or being destroyed. +// start_destroy_asset(addr.clone(), asset); +// assert_eq!( +// decoded::(transfer_from(addr.clone(), asset, None, Some(BOB), amount, &[0u8])), +// Module { index: 52, error: 16 }, +// ); +// }); +// } + +// #[test] +// #[ignore] +// fn create_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// // Instantiate a contract without balance (relay token). +// let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 0, vec![0]); +// // No balance to pay for fees. +// assert_eq!( +// decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), +// Module { index: 10, error: 2 }, +// ); +// // Instantiate a contract without balance (relay token). +// let addr = instantiate("../examples/fungibles/target/ink/fungibles.wasm", 100, vec![2]); +// // No balance to pay the deposit. +// assert_eq!( +// decoded::(create(addr.clone(), ASSET_ID, addr.clone(), 1)), +// Module { index: 10, error: 2 }, +// ); +// // Instantiate a contract with balance. +// let addr = +// instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![1]); +// assert_eq!( +// decoded::(create(addr.clone(), ASSET_ID, BOB, 0)), +// Module { index: 52, error: 7 }, +// ); +// create_asset(ALICE, ASSET_ID, 1); +// // Asset ID is already taken. +// assert_eq!( +// decoded::(create(addr.clone(), ASSET_ID, BOB, 1)), +// Module { index: 52, error: 5 }, +// ); +// // The minimal balance for an asset must be non zero. +// let new_asset = 2; +// let result = create(addr.clone(), new_asset, BOB, 1); +// assert!(!result.did_revert(), "Contract reverted!"); +// }); +// } + +// #[test] +// #[ignore] +// fn set_metadata_works() { +// new_test_ext().execute_with(|| { +// let _ = env_logger::try_init(); +// let addr = +// instantiate("../examples/fungibles/target/ink/fungibles.wasm", INIT_VALUE, vec![]); +// +// create_asset(addr.clone(), ASSET_ID, 1); +// let result = set_metadata(addr.clone(), ASSET_ID, vec![12], vec![12], 12); +// assert!(!result.did_revert(), "Contract reverted!"); +// }); +// } diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index cb27b17f..9e1deefe 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -26,6 +26,8 @@ pub type Result = core::result::Result; #[ink::scale_derive(Encode, Decode, TypeInfo)] pub struct StatusCode(pub u32); +pub(crate) const DECODING_FAILED: u32 = 255; + impl From for StatusCode { fn from(value: u32) -> Self { StatusCode(value) @@ -42,7 +44,7 @@ impl FromStatusCode for StatusCode { impl From for StatusCode { fn from(_: ink::scale::Error) -> Self { - StatusCode(255u32) + StatusCode(DECODING_FAILED) } } diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index ea8991a7..4d942dc6 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,6 +1,6 @@ use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec, scale::Decode}; -use crate::{primitives::AssetId, AccountId, Balance, Result, StatusCode}; +use crate::{primitives::AssetId, AccountId, Balance, Result, StatusCode, DECODING_FAILED}; pub mod fungibles; @@ -197,7 +197,7 @@ pub fn total_supply(id: AssetId) -> Result { .output::>, true>() .handle_error_code::() .call(&(id)) - .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } #[inline] @@ -212,7 +212,7 @@ pub fn balance_of(id: AssetId, owner: AccountId) -> Result { .output::>, true>() .handle_error_code::() .call(&(id, owner)) - .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } #[inline] @@ -222,7 +222,7 @@ pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result>, true>() .handle_error_code::() .call(&(id, owner, spender)) - .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } #[inline] @@ -237,7 +237,7 @@ pub fn token_name(id: AssetId) -> Result> { .output::>, true>() .handle_error_code::() .call(&(id)) - .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) + .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } // #[inline] @@ -252,7 +252,7 @@ pub fn token_symbol(id: AssetId) -> Result> { .output::>, true>() .handle_error_code::() .call(&(id)) - .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) + .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } #[inline] @@ -267,7 +267,7 @@ pub fn token_decimals(id: AssetId) -> Result { .output::>, true>() .handle_error_code::() .call(&(id)) - .and_then(|v| ::decode(&mut &v[..]).map_err(|_e| StatusCode(255u32))) + .and_then(|v| ::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } // pub(crate) fn asset_exists(id: AssetId) -> Result { diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 9d31653a..c0d9f0d3 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -95,7 +95,7 @@ pub mod v0 { // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). encoded_error.resize(4, 0); u32::from_le_bytes( - encoded_error.try_into().expect("qid, resized to 4 bytes line above"), + encoded_error.try_into().expect("qed, resized to 4 bytes line above"), ) } } diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index c6bab850..f126031b 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -313,7 +313,7 @@ pub(crate) fn convert_to_status_code(error: DispatchError, version: u8) -> u32 { }; // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). encoded_error.resize(4, 0); - let mut encoded_error = encoded_error.try_into().expect("qid, resized to 4 bytes line above"); + let mut encoded_error = encoded_error.try_into().expect("qed, resized to 4 bytes line above"); match version { // If an unknown variant of the `DispatchError` is detected the error needs to be converted // into the encoded value of `Error::Other`. This conversion is performed by shifting the bytes one From b591222168e40099c3d2b759da9765f45ee0a488 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Wed, 17 Jul 2024 18:00:11 +0200 Subject: [PATCH 22/27] style: renaming --- pop-api/examples/fungibles/lib.rs | 2 +- pop-api/integration-tests/src/lib.rs | 2 +- .../integration-tests/src/local_fungibles.rs | 50 +++++++++---------- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/pop-api/examples/fungibles/lib.rs b/pop-api/examples/fungibles/lib.rs index 2abc422c..1b42fec4 100755 --- a/pop-api/examples/fungibles/lib.rs +++ b/pop-api/examples/fungibles/lib.rs @@ -71,7 +71,7 @@ mod fungibles { from: AccountId, to: AccountId, value: Balance, - // In the standard a `[u8]`, but the size needs to be known at compile time. + // In the PSP-22 standard a `[u8]`, but the size needs to be known at compile time. _data: Vec, ) -> Result<()> { api::transfer_from(id, from, to, value) diff --git a/pop-api/integration-tests/src/lib.rs b/pop-api/integration-tests/src/lib.rs index c6732d91..8c967855 100644 --- a/pop-api/integration-tests/src/lib.rs +++ b/pop-api/integration-tests/src/lib.rs @@ -59,7 +59,7 @@ fn function_selector(name: &str) -> Vec { [hash[0..4].to_vec()].concat() } -fn do_bare_call( +fn bare_call( addr: AccountId32, input: Vec, value: u128, diff --git a/pop-api/integration-tests/src/local_fungibles.rs b/pop-api/integration-tests/src/local_fungibles.rs index bef3aa6a..f39c2327 100644 --- a/pop-api/integration-tests/src/local_fungibles.rs +++ b/pop-api/integration-tests/src/local_fungibles.rs @@ -18,7 +18,7 @@ fn decoded(result: ExecReturnValue) -> T { fn total_supply(addr: AccountId32, asset_id: AssetId) -> Balance { let function = function_selector("total_supply"); let params = [function, asset_id.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); decoded::(result) } @@ -26,7 +26,7 @@ fn total_supply(addr: AccountId32, asset_id: AssetId) -> Balance { fn balance_of(addr: AccountId32, asset_id: AssetId, owner: AccountId32) -> Balance { let function = function_selector("balance_of"); let params = [function, asset_id.encode(), owner.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); decoded::(result) } @@ -39,7 +39,7 @@ fn allowance( ) -> Balance { let function = function_selector("allowance"); let params = [function, asset_id.encode(), owner.encode(), spender.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); decoded::(result) } @@ -47,7 +47,7 @@ fn allowance( fn token_name(addr: AccountId32, asset_id: AssetId) -> Vec { let function = function_selector("token_name"); let params = [function, asset_id.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); decoded::>(result) } @@ -55,7 +55,7 @@ fn token_name(addr: AccountId32, asset_id: AssetId) -> Vec { fn token_symbol(addr: AccountId32, asset_id: AssetId) -> Vec { let function = function_selector("token_symbol"); let params = [function, asset_id.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); decoded::>(result) } @@ -63,7 +63,7 @@ fn token_symbol(addr: AccountId32, asset_id: AssetId) -> Vec { fn token_decimals(addr: AccountId32, asset_id: AssetId) -> u8 { let function = function_selector("token_decimals"); let params = [function, asset_id.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); decoded::(result) } @@ -75,7 +75,7 @@ fn transfer( ) -> ExecReturnValue { let function = function_selector("transfer"); let params = [function, asset_id.encode(), to.encode(), value.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); result } @@ -91,7 +91,7 @@ fn transfer_from( let params = [function, asset_id.encode(), from.encode(), to.encode(), value.encode(), data.encode()] .concat(); - do_bare_call(addr, params, 0).expect("should work") + bare_call(addr, params, 0).expect("should work") } fn increase_allowance( @@ -102,14 +102,14 @@ fn increase_allowance( ) -> ExecReturnValue { let function = function_selector("increase_allowance"); let params = [function, asset_id.encode(), spender.encode(), value.encode()].concat(); - let result = do_bare_call(addr, params, 0).expect("should work"); + let result = bare_call(addr, params, 0).expect("should work"); result } // fn asset_exists(addr: AccountId32, asset_id: AssetId) -> bool { // let function = function_selector("asset_exists"); // let params = [function, asset_id.encode()].concat(); -// let result = do_bare_call(addr, params, 0).expect("should work"); +// let result = bare_call(addr, params, 0).expect("should work"); // decoded::(result) // } // @@ -121,7 +121,7 @@ fn increase_allowance( // ) -> ExecReturnValue { // let function = function_selector("create"); // let params = [function, asset_id.encode(), admin.encode(), min_balance.encode()].concat(); -// do_bare_call(addr, params, 0).expect("should work") +// bare_call(addr, params, 0).expect("should work") // } // // fn set_metadata( @@ -134,22 +134,22 @@ fn increase_allowance( // let function = function_selector("set_metadata"); // let params = // [function, asset_id.encode(), name.encode(), symbol.encode(), decimals.encode()].concat(); -// do_bare_call(addr, params, 0).expect("should work") -// } -// -// fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { -// assert_eq!( -// Assets::create( -// RuntimeOrigin::signed(owner.clone()), -// asset_id.into(), -// owner.into(), -// min_balance -// ), -// Ok(()) -// ); -// asset_id +// bare_call(addr, params, 0).expect("should work") // } +fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { + assert_eq!( + Assets::create( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + owner.into(), + min_balance + ), + Ok(()) + ); + asset_id +} + fn mint_asset(owner: AccountId32, asset_id: AssetId, to: AccountId32, value: Balance) -> AssetId { assert_eq!( Assets::mint(RuntimeOrigin::signed(owner.clone()), asset_id.into(), to.into(), value), From c2acbb57ae9be348a9b4b0c2d7e81330b3a8ef47 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 18 Jul 2024 11:43:37 +0200 Subject: [PATCH 23/27] refactor: bits and pieces --- pop-api/integration-tests/src/lib.rs | 7 +- .../integration-tests/src/local_fungibles.rs | 78 ++++++++----------- pop-api/src/lib.rs | 36 ++++----- pop-api/src/primitives.rs | 6 ++ pop-api/src/v0/assets/fungibles.rs | 58 +++++++++----- pop-api/src/v0/assets/mod.rs | 12 +-- pop-api/src/v0/mod.rs | 17 ++++ pop-api/src/v0/nfts.rs | 3 - primitives/src/lib.rs | 28 +++---- runtime/devnet/src/extensions/mod.rs | 2 +- runtime/testnet/src/extensions.rs | 4 +- 11 files changed, 138 insertions(+), 113 deletions(-) diff --git a/pop-api/integration-tests/src/lib.rs b/pop-api/integration-tests/src/lib.rs index 8c967855..ea5ccb05 100644 --- a/pop-api/integration-tests/src/lib.rs +++ b/pop-api/integration-tests/src/lib.rs @@ -1,6 +1,7 @@ #![cfg(test)] use frame_support::{ + assert_ok, traits::fungibles::{ approvals::Inspect as ApprovalInspect, metadata::Inspect as MetadataInspect, Inspect, }, @@ -17,17 +18,17 @@ use pop_runtime_devnet::{ mod local_fungibles; -type Balance = u128; type AssetId = u32; -const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; +type Balance = u128; const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); const BOB: AccountId32 = AccountId32::new([2_u8; 32]); +const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; // FERDIE has no initial balance. const FERDIE: AccountId32 = AccountId32::new([3_u8; 32]); +const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); const INIT_AMOUNT: Balance = 100_000_000 * UNIT; const INIT_VALUE: Balance = 100 * UNIT; -const GAS_LIMIT: Weight = Weight::from_parts(100_000_000_000, 3 * 1024 * 1024); fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::::default() diff --git a/pop-api/integration-tests/src/local_fungibles.rs b/pop-api/integration-tests/src/local_fungibles.rs index f39c2327..8f0384c0 100644 --- a/pop-api/integration-tests/src/local_fungibles.rs +++ b/pop-api/integration-tests/src/local_fungibles.rs @@ -138,23 +138,22 @@ fn increase_allowance( // } fn create_asset(owner: AccountId32, asset_id: AssetId, min_balance: Balance) -> AssetId { - assert_eq!( - Assets::create( - RuntimeOrigin::signed(owner.clone()), - asset_id.into(), - owner.into(), - min_balance - ), - Ok(()) - ); + assert_ok!(Assets::create( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + owner.into(), + min_balance + )); asset_id } fn mint_asset(owner: AccountId32, asset_id: AssetId, to: AccountId32, value: Balance) -> AssetId { - assert_eq!( - Assets::mint(RuntimeOrigin::signed(owner.clone()), asset_id.into(), to.into(), value), - Ok(()) - ); + assert_ok!(Assets::mint( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + to.into(), + value + )); asset_id } @@ -178,30 +177,27 @@ fn create_asset_mint_and_approve( approve: Balance, ) { create_asset_and_mint_to(owner.clone(), asset_id, to.clone(), mint); - assert_eq!( - Assets::approve_transfer( - RuntimeOrigin::signed(to.into()), - asset_id.into(), - spender.into(), - approve, - ), - Ok(()) - ); + assert_ok!(Assets::approve_transfer( + RuntimeOrigin::signed(to.into()), + asset_id.into(), + spender.into(), + approve, + )); } // Freeze an asset. fn freeze_asset(owner: AccountId32, asset_id: AssetId) { - assert_eq!(Assets::freeze_asset(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); + assert_ok!(Assets::freeze_asset(RuntimeOrigin::signed(owner.into()), asset_id.into())); } // Thaw an asset. fn thaw_asset(owner: AccountId32, asset_id: AssetId) { - assert_eq!(Assets::thaw_asset(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); + assert_ok!(Assets::thaw_asset(RuntimeOrigin::signed(owner.into()), asset_id.into())); } // Start destroying an asset. fn start_destroy_asset(owner: AccountId32, asset_id: AssetId) { - assert_eq!(Assets::start_destroy(RuntimeOrigin::signed(owner.into()), asset_id.into()), Ok(())); + assert_ok!(Assets::start_destroy(RuntimeOrigin::signed(owner.into()), asset_id.into())); } // Create an asset and set metadata. @@ -212,15 +208,12 @@ fn create_asset_and_set_metadata( symbol: Vec, decimals: u8, ) { - assert_eq!( - Assets::create( - RuntimeOrigin::signed(owner.clone()), - asset_id.into(), - owner.clone().into(), - 100 - ), - Ok(()) - ); + assert_ok!(Assets::create( + RuntimeOrigin::signed(owner.clone()), + asset_id.into(), + owner.clone().into(), + 100 + )); set_metadata_asset(owner, asset_id, name, symbol, decimals); } @@ -232,16 +225,13 @@ fn set_metadata_asset( symbol: Vec, decimals: u8, ) { - assert_eq!( - Assets::set_metadata( - RuntimeOrigin::signed(owner.into()), - asset_id.into(), - name, - symbol, - decimals - ), - Ok(()) - ); + assert_ok!(Assets::set_metadata( + RuntimeOrigin::signed(owner.into()), + asset_id.into(), + name, + symbol, + decimals + )); } fn token_name_asset(asset_id: AssetId) -> Vec { diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 9e1deefe..8d865f0b 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -1,7 +1,8 @@ #![cfg_attr(not(feature = "std"), no_std, no_main)] -use ink::env::{chain_extension::FromStatusCode, DefaultEnvironment, Environment}; -use primitives::error::Error; +use ink::env::chain_extension::FromStatusCode; + +use constants::DECODING_FAILED; #[cfg(feature = "assets")] pub use v0::assets; @@ -15,18 +16,25 @@ pub use v0::nfts; pub mod primitives; pub mod v0; -type AccountId = ::AccountId; -type Balance = ::Balance; -#[cfg(any(feature = "nfts", feature = "cross-chain"))] -type BlockNumber = ::BlockNumber; - pub type Result = core::result::Result; #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[ink::scale_derive(Encode, Decode, TypeInfo)] pub struct StatusCode(pub u32); -pub(crate) const DECODING_FAILED: u32 = 255; +mod constants { + // Errors: + pub(crate) const DECODING_FAILED: u32 = 255; + pub(crate) const MODULE_ERROR: u8 = 3; + + // Function IDs: + pub(crate) const DISPATCH: u8 = 0; + pub(crate) const READ_STATE: u8 = 1; + + // Modules: + pub(crate) const ASSETS_MODULE: u8 = 52; + pub(crate) const BALANCES_MODULE: u8 = 10; +} impl From for StatusCode { fn from(value: u32) -> Self { @@ -47,15 +55,3 @@ impl From for StatusCode { StatusCode(DECODING_FAILED) } } - -impl From for Error { - fn from(value: StatusCode) -> Self { - value.0.into() - } -} - -impl From for StatusCode { - fn from(value: Error) -> Self { - StatusCode::from(u32::from(value)) - } -} diff --git a/pop-api/src/primitives.rs b/pop-api/src/primitives.rs index e174a111..b451ce79 100644 --- a/pop-api/src/primitives.rs +++ b/pop-api/src/primitives.rs @@ -1 +1,7 @@ +use ink::env::{DefaultEnvironment, Environment}; pub use pop_primitives::*; + +pub(crate) type AccountId = ::AccountId; +pub(crate) type Balance = ::Balance; +#[cfg(any(feature = "nfts", feature = "cross-chain"))] +type BlockNumber = ::BlockNumber; diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index 4abd46a6..8bc7d807 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -1,6 +1,11 @@ use ink::prelude::vec::Vec; -use crate::{assets, primitives::AssetId, AccountId, Balance, Result, StatusCode}; +use crate::{ + assets, + constants::{ASSETS_MODULE, BALANCES_MODULE, MODULE_ERROR}, + primitives::{AccountId, AssetId, Balance}, + Result, StatusCode, +}; /// Local Fungibles: /// 1. PSP-22 Interface @@ -101,7 +106,7 @@ pub fn transfer_from(id: AssetId, from: AccountId, to: AccountId, value: Balance /// Returns `Ok(())` if successful, or an error if the approval fails. #[inline] pub fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { - assets::cancel_approval(id, spender)?; + assets::cancel_approval(id, spender.clone())?; assets::approve_transfer(id, spender, value) } @@ -312,15 +317,15 @@ impl From for FungiblesError { let encoded = value.0.to_le_bytes(); match encoded { // Balances. - [3, 10, 2, _] => FungiblesError::NoBalance, + [MODULE_ERROR, BALANCES_MODULE, 2, _] => FungiblesError::NoBalance, // Assets. - [3, 52, 0, _] => FungiblesError::NoAccount, - [3, 52, 1, _] => FungiblesError::NoPermission, - [3, 52, 2, _] => FungiblesError::Unknown, - [3, 52, 3, _] => FungiblesError::InUse, - [3, 52, 5, _] => FungiblesError::MinBalanceZero, - [3, 52, 7, _] => FungiblesError::InsufficientAllowance, - [3, 52, 10, _] => FungiblesError::AssetNotLive, + [MODULE_ERROR, ASSETS_MODULE, 0, _] => FungiblesError::NoAccount, + [MODULE_ERROR, ASSETS_MODULE, 1, _] => FungiblesError::NoPermission, + [MODULE_ERROR, ASSETS_MODULE, 2, _] => FungiblesError::Unknown, + [MODULE_ERROR, ASSETS_MODULE, 3, _] => FungiblesError::InUse, + [MODULE_ERROR, ASSETS_MODULE, 5, _] => FungiblesError::MinBalanceZero, + [MODULE_ERROR, ASSETS_MODULE, 7, _] => FungiblesError::InsufficientAllowance, + [MODULE_ERROR, ASSETS_MODULE, 10, _] => FungiblesError::AssetNotLive, _ => FungiblesError::Other(value), } } @@ -328,6 +333,7 @@ impl From for FungiblesError { #[cfg(test)] mod tests { + use crate::constants::{ASSETS_MODULE, BALANCES_MODULE}; use ink::scale::Decode; use super::FungiblesError; @@ -359,7 +365,7 @@ mod tests { #[test] fn conversion_status_code_into_fungibles_error_works() { - let errors = vec![ + let other_errors = vec![ Other { dispatch_error_index: 5, error_index: 5, error: 1 }, CannotLookup, BadOrigin, @@ -378,30 +384,42 @@ mod tests { UnknownFunctionId, DecodingFailed, ]; - for error in errors { + for error in other_errors { let status_code: StatusCode = error.into(); let fungibles_error: FungiblesError = status_code.into(); assert_eq!(fungibles_error, FungiblesError::Other(status_code)) } - assert_eq!(into_fungibles_error(Module { index: 10, error: 2 }), FungiblesError::NoBalance); - assert_eq!(into_fungibles_error(Module { index: 52, error: 0 }), FungiblesError::NoAccount); assert_eq!( - into_fungibles_error(Module { index: 52, error: 1 }), + into_fungibles_error(Module { index: BALANCES_MODULE, error: 2 }), + FungiblesError::NoBalance + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS_MODULE, error: 0 }), + FungiblesError::NoAccount + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS_MODULE, error: 1 }), FungiblesError::NoPermission ); - assert_eq!(into_fungibles_error(Module { index: 52, error: 2 }), FungiblesError::Unknown); - assert_eq!(into_fungibles_error(Module { index: 52, error: 3 }), FungiblesError::InUse); assert_eq!( - into_fungibles_error(Module { index: 52, error: 5 }), + into_fungibles_error(Module { index: ASSETS_MODULE, error: 2 }), + FungiblesError::Unknown + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS_MODULE, error: 3 }), + FungiblesError::InUse + ); + assert_eq!( + into_fungibles_error(Module { index: ASSETS_MODULE, error: 5 }), FungiblesError::MinBalanceZero ); assert_eq!( - into_fungibles_error(Module { index: 52, error: 7 }), + into_fungibles_error(Module { index: ASSETS_MODULE, error: 7 }), FungiblesError::InsufficientAllowance ); assert_eq!( - into_fungibles_error(Module { index: 52, error: 10 }), + into_fungibles_error(Module { index: ASSETS_MODULE, error: 10 }), FungiblesError::AssetNotLive ); } diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index 4d942dc6..fa7d523b 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,18 +1,19 @@ use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec, scale::Decode}; -use crate::{primitives::AssetId, AccountId, Balance, Result, StatusCode, DECODING_FAILED}; +use crate::{ + constants::{ASSETS_MODULE, DECODING_FAILED, DISPATCH, READ_STATE}, + primitives::{AccountId, AssetId, Balance}, + v0::VERSION, + Result, StatusCode, +}; pub mod fungibles; -const ASSETS_MODULE: u8 = 52; -const VERSION: u8 = 0; - /// [Pallet Assets](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/assets/src/lib.rs): /// 1. Dispatchables /// 2. Read state functions /// /// 1. Dispatchables within pallet assets (TrustBackedAssets instance): -const DISPATCH: u8 = 0; /// - create /// - start_destroy /// - destroy_accounts @@ -170,7 +171,6 @@ pub fn transfer_approved( } /// 2. Read state functions: -const READ_STATE: u8 = 1; /// - total_supply const TOTAL_SUPPLY: u8 = 0; /// - balance_of diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 310b360c..56bccfc1 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -1,3 +1,6 @@ +use crate::StatusCode; +use pop_primitives::error::Error; + #[cfg(feature = "assets")] pub mod assets; #[cfg(feature = "balances")] @@ -6,3 +9,17 @@ pub mod balances; pub mod cross_chain; #[cfg(feature = "nfts")] pub mod nfts; + +pub(crate) const VERSION: u8 = 0; + +impl From for Error { + fn from(value: StatusCode) -> Self { + value.0.into() + } +} + +impl From for StatusCode { + fn from(value: Error) -> Self { + StatusCode::from(u32::from(value)) + } +} diff --git a/pop-api/src/v0/nfts.rs b/pop-api/src/v0/nfts.rs index e111c8dc..63b90a1f 100644 --- a/pop-api/src/v0/nfts.rs +++ b/pop-api/src/v0/nfts.rs @@ -6,12 +6,9 @@ pub use primitives::{CollectionId, ItemId}; use scale::Encode; pub use types::*; -type Result = core::result::Result; type StringLimit = u32; type MaxTips = u32; -type Result = core::result::Result; - /// Issue a new collection of non-fungible items pub fn create( admin: impl Into>, diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index c0d9f0d3..3b3ff16d 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -48,34 +48,34 @@ pub mod v0 { error_index: u8, // Index for further nesting, e.g. pallet error. error: u8, - } = 0, + }, /// Failed to lookup some data. - CannotLookup = 1, + CannotLookup, /// A bad origin. - BadOrigin = 2, + BadOrigin, /// A custom error in a module. - Module { index: u8, error: u8 } = 3, + Module { index: u8, error: u8 }, /// At least one consumer is remaining so the account cannot be destroyed. - ConsumerRemaining = 4, + ConsumerRemaining, /// There are no providers so the account cannot be created. - NoProviders = 5, + NoProviders, /// There are too many consumers so the account cannot be created. - TooManyConsumers = 6, + TooManyConsumers, /// An error to do with tokens. - Token(TokenError) = 7, + Token(TokenError), /// An arithmetic error. - Arithmetic(ArithmeticError) = 8, + Arithmetic(ArithmeticError), /// The number of transactional layers has been reached, or we are not in a transactional /// layer. - Transactional(TransactionalError) = 9, + Transactional(TransactionalError), /// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate. - Exhausted = 10, + Exhausted, /// The state is corrupt; this is generally not going to fix itself. - Corruption = 11, + Corruption, /// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later. - Unavailable = 12, + Unavailable, /// Root origin is not allowed. - RootNotAllowed = 13, + RootNotAllowed, /// Unknown function id. UnknownFunctionId = 254, /// Decoding failed on the runtime. diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index f126031b..720458c8 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -172,7 +172,7 @@ fn construct_call( params: Vec, ) -> Result { match pallet_index { - 52 => { + index if index == super::Assets::index() as u8 => { let call = versioned_construct_assets_call(version, call_index, params)?; Ok(RuntimeCall::Assets(call)) }, diff --git a/runtime/testnet/src/extensions.rs b/runtime/testnet/src/extensions.rs index 866cb12c..bcb0f835 100644 --- a/runtime/testnet/src/extensions.rs +++ b/runtime/testnet/src/extensions.rs @@ -1,9 +1,9 @@ use cumulus_pallet_parachain_system::RelaychainDataProvider; -use frame_support::traits::{Contains, OriginTrait}; use frame_support::{ dispatch::{GetDispatchInfo, RawOrigin}, pallet_prelude::*, traits::nonfungibles_v2::Inspect, + traits::{Contains, OriginTrait}, }; use pallet_contracts::chain_extension::{ BufInBufOutState, ChainExtension, ChargedAmount, Environment, Ext, InitState, RetVal, @@ -206,7 +206,7 @@ where RuntimeStateKeys::ParachainSystem(key) => { read_parachain_system_state::(key, &mut env) }, - _ => Ok(Vec::from([0u8])), + _ => Ok(Vec::default()), }? .encode(); From 363932022c62e88e28b1360ff3e8c2a6a1aa6ffb Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 18 Jul 2024 14:50:52 +0200 Subject: [PATCH 24/27] docs: add docs to code --- pop-api/src/lib.rs | 25 +++++++++++++--- pop-api/src/v0/assets/fungibles.rs | 25 ++++++++++++---- primitives/src/lib.rs | 45 ++++++++++++++++++---------- runtime/devnet/src/extensions/mod.rs | 13 ++++++++ 4 files changed, 84 insertions(+), 24 deletions(-) diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 8d865f0b..7a0fe75b 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -16,12 +16,9 @@ pub use v0::nfts; pub mod primitives; pub mod v0; +/// A result type used by the API, with the `StatusCode` as the error type. pub type Result = core::result::Result; -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[ink::scale_derive(Encode, Decode, TypeInfo)] -pub struct StatusCode(pub u32); - mod constants { // Errors: pub(crate) const DECODING_FAILED: u32 = 255; @@ -36,12 +33,31 @@ mod constants { pub(crate) const BALANCES_MODULE: u8 = 10; } +/// Represents a status code returned by the runtime. +/// +/// `StatusCode` encapsulates a `u32` value that indicates the status of an operation performed +/// by the runtime. It helps to communicate the success or failure of a chain extension method +/// call to the contract, providing a standardized way to handle errors. +/// +/// This status code can be used to determine if an operation succeeded or if it encountered +/// an error. A `StatusCode` of `0` typically indicates success, while any other value represents +/// an error. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[ink::scale_derive(Encode, Decode, TypeInfo)] +pub struct StatusCode(pub u32); + impl From for StatusCode { + /// Converts a `u32` into a `StatusCode`. fn from(value: u32) -> Self { StatusCode(value) } } + impl FromStatusCode for StatusCode { + /// Converts a `u32` status code to a `Result`. + /// + /// `Ok(())` if the status code is `0` and `Err(StatusCode(status_code))` for any other status + /// code. fn from_status_code(status_code: u32) -> Result<()> { match status_code { 0 => Ok(()), @@ -51,6 +67,7 @@ impl FromStatusCode for StatusCode { } impl From for StatusCode { + /// Converts a scale decoding error into a `StatusCode` indicating a decoding failure. fn from(_: ink::scale::Error) -> Self { StatusCode(DECODING_FAILED) } diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index 8bc7d807..e3c9b6be 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -284,9 +284,20 @@ pub fn token_decimals(id: AssetId) -> Result { // assets::asset_exists(id) // } +/// Represents various errors related to local fungible assets in the API. +/// +/// The `FungiblesError` provides a detailed and specific set of error types that can occur when +/// interacting with fungible assets through the Pop API. Each variant signifies a particular error +/// condition, facilitating precise error handling and debugging. +/// +/// It is designed to be lightweight, including only the essential errors relevant to fungible asset +/// operations. The `Other` variant serves as a catch-all for any unexpected errors. For more +/// detailed debugging, the `Other` variant can be converted into the richer `Error` type defined in +/// the primitives crate. #[derive(Debug, PartialEq, Eq)] #[ink::scale_derive(Encode, Decode, TypeInfo)] pub enum FungiblesError { + /// An unspecified or unknown error occurred. Other(StatusCode), /// The asset is not live; either frozen or being destroyed. AssetNotLive, @@ -305,14 +316,18 @@ pub enum FungiblesError { /// The given asset ID is unknown. Unknown, /// No balance for creation of assets or fees. - // - // Originally `pallet_balances::Error::InsufficientBalance` but collides with the - // `InsufficientBalance` error that is used for `pallet_assets::Error::BalanceLow` to adhere to - // standard. + // TODO: Originally `pallet_balances::Error::InsufficientBalance` but collides with the + // `InsufficientBalance` error that is used for `pallet_assets::Error::BalanceLow` to adhere to + // standard. This deserves a second look. NoBalance, } impl From for FungiblesError { + /// Converts a `StatusCode` to a `FungiblesError`. + /// + /// This conversion maps a `StatusCode`, returned by the runtime, to a more descriptive + /// `FungiblesError`. This provides better context and understanding of the error, allowing + /// developers to handle the most important errors effectively. fn from(value: StatusCode) -> Self { let encoded = value.0.to_le_bytes(); match encoded { @@ -381,7 +396,7 @@ mod tests { Corruption, Unavailable, RootNotAllowed, - UnknownFunctionId, + UnknownFunctionCall, DecodingFailed, ]; for error in other_errors { diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 3b3ff16d..d177b60f 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -10,20 +10,21 @@ pub use v0::error; pub mod cross_chain; pub mod storage_keys; +/// An opaque 32-byte cryptographic identifier. #[derive(Encode, Decode, Debug, MaxEncodedLen, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(TypeInfo))] pub struct AccountId(pub [u8; 32]); -// Identifier for the class of asset. +/// Identifier for the class of asset. pub type AssetId = u32; #[cfg(feature = "nfts")] pub mod nfts { use bounded_collections::ConstU32; - // Id used for identifying non-fungible collections. + /// Id used for identifying non-fungible collections. pub type CollectionId = u32; - // Id used for identifying non-fungible items. + /// Id used for identifying non-fungible items. pub type ItemId = u32; /// The maximum length of an attribute key. pub type KeyLimit = ConstU32<64>; @@ -36,24 +37,29 @@ pub mod v0 { pub mod error { use super::*; + /// Reason why a Pop API function call failed. #[derive(Encode, Decode, Debug, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(TypeInfo))] #[repr(u8)] pub enum Error { - /// Some unknown error occurred. Go to the Pop API docs section `Pop API error`. - Other { - // Index within the `DispatchError` - dispatch_error_index: u8, - // Index within the `DispatchError` variant. - error_index: u8, - // Index for further nesting, e.g. pallet error. - error: u8, - }, + /// An unknown error occurred. This variant captures any unexpected errors that the + /// contract cannot specifically handle. It is useful for cases where there are breaking + /// changes in the runtime or when an error falls outside the predefined categories. The + /// variant includes: + /// + /// - `dispatch_error_index`: The index within the `DispatchError`. + /// - `error_index`: The index within the `DispatchError` variant (e.g. a `TokenError`). + /// - `error`: The specific error code or sub-index, providing additional context (e.g. + /// `error` in `ModuleError`). + Other { dispatch_error_index: u8, error_index: u8, error: u8 }, /// Failed to lookup some data. CannotLookup, /// A bad origin. BadOrigin, /// A custom error in a module. + /// + /// - `index`: The pallet index. + /// - `error`: The error within the pallet. Module { index: u8, error: u8 }, /// At least one consumer is remaining so the account cannot be destroyed. ConsumerRemaining, @@ -76,13 +82,18 @@ pub mod v0 { Unavailable, /// Root origin is not allowed. RootNotAllowed, - /// Unknown function id. - UnknownFunctionId = 254, - /// Decoding failed on the runtime. + /// Unknown function called. + UnknownFunctionCall = 254, + /// Decoding failed. DecodingFailed = 255, } impl From for Error { + /// Converts a `u32` status code into an `Error`. + /// + /// This conversion maps a raw status code returned by the runtime into the more + /// descriptive `Error` enum variant, providing better context and understanding of the + /// error. fn from(value: u32) -> Self { let encoded = value.to_le_bytes(); Error::decode(&mut &encoded[..]).unwrap_or(Error::DecodingFailed) @@ -90,6 +101,7 @@ pub mod v0 { } impl From for u32 { + /// Converts an `Error` to a `u32` status code. fn from(value: Error) -> Self { let mut encoded_error = value.encode(); // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). @@ -100,6 +112,7 @@ pub mod v0 { } } + /// Description of what went wrong when trying to complete an operation on a token. #[derive(Encode, Decode, Clone, Debug, MaxEncodedLen, Eq, PartialEq, Ord, PartialOrd)] #[cfg_attr(feature = "std", derive(TypeInfo))] pub enum TokenError { @@ -126,6 +139,7 @@ pub mod v0 { Blocked, } + /// Arithmetic errors. #[derive(Encode, Decode, Debug, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(TypeInfo))] pub enum ArithmeticError { @@ -137,6 +151,7 @@ pub mod v0 { DivisionByZero, } + /// Errors related to transactional storage layers. #[derive(Encode, Decode, Debug, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(TypeInfo))] pub enum TransactionalError { diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index 720458c8..ec2d0bc2 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -337,6 +337,15 @@ pub(crate) fn convert_to_status_code(error: DispatchError, version: u8) -> u32 { u32::from_le_bytes(encoded_error) } +/// Enum representing the different function identifiers used in the Pop API chain extension. +/// +/// The `FuncId` enum specifies the available functions that can be called through the Pop API chain +/// extension. Each variant corresponds to a specific functionality provided by the chain extension, +/// facilitating the interaction between smart contracts and the runtime. +/// +/// - `Dispatch`: Represents a function call to dispatch a runtime call. +/// - `ReadState`: Represents a function call to read the state from the runtime. +/// - `SendXcm`: Represents a function call to send an XCM message. #[derive(Debug)] pub enum FuncId { Dispatch, @@ -347,6 +356,10 @@ pub enum FuncId { impl TryFrom for FuncId { type Error = DispatchError; + /// Attempts to convert a `u8` value to its corresponding `FuncId` variant. + /// + /// If the `u8` value does not match any known function identifier, it returns a + /// `DispatchError::Other` indicating an unknown function ID. fn try_from(func_id: u8) -> Result { let id = match func_id { 0 => Self::Dispatch, From 81e9844f056123abe88985e64463a753d50f004a Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 18 Jul 2024 15:05:42 +0200 Subject: [PATCH 25/27] fix: replace test code to api fungibles --- pop-api/src/v0/assets/fungibles.rs | 15 ++++++++++++--- pop-api/src/v0/mod.rs | 6 ------ primitives/src/lib.rs | 12 ------------ 3 files changed, 12 insertions(+), 21 deletions(-) diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index e3c9b6be..9084708d 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -349,7 +349,7 @@ impl From for FungiblesError { #[cfg(test)] mod tests { use crate::constants::{ASSETS_MODULE, BALANCES_MODULE}; - use ink::scale::Decode; + use ink::scale::{Decode, Encode}; use super::FungiblesError; use crate::primitives::error::{ @@ -360,8 +360,17 @@ mod tests { }; use crate::StatusCode; + fn error_into_status_code(error: Error) -> StatusCode { + let mut encoded_error = error.encode(); + encoded_error.resize(4, 0); + let value = u32::from_le_bytes( + encoded_error.try_into().expect("qed, resized to 4 bytes line above"), + ); + value.into() + } + fn into_fungibles_error(error: Error) -> FungiblesError { - let status_code: StatusCode = error.into(); + let status_code: StatusCode = error_into_status_code(error); status_code.into() } @@ -400,7 +409,7 @@ mod tests { DecodingFailed, ]; for error in other_errors { - let status_code: StatusCode = error.into(); + let status_code: StatusCode = error_into_status_code(error); let fungibles_error: FungiblesError = status_code.into(); assert_eq!(fungibles_error, FungiblesError::Other(status_code)) } diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 56bccfc1..8b7a8469 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -17,9 +17,3 @@ impl From for Error { value.0.into() } } - -impl From for StatusCode { - fn from(value: Error) -> Self { - StatusCode::from(u32::from(value)) - } -} diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index d177b60f..b9caf111 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -100,18 +100,6 @@ pub mod v0 { } } - impl From for u32 { - /// Converts an `Error` to a `u32` status code. - fn from(value: Error) -> Self { - let mut encoded_error = value.encode(); - // Resize the encoded value to 4 bytes in order to decode the value in a u32 (4 bytes). - encoded_error.resize(4, 0); - u32::from_le_bytes( - encoded_error.try_into().expect("qed, resized to 4 bytes line above"), - ) - } - } - /// Description of what went wrong when trying to complete an operation on a token. #[derive(Encode, Decode, Clone, Debug, MaxEncodedLen, Eq, PartialEq, Ord, PartialOrd)] #[cfg_attr(feature = "std", derive(TypeInfo))] From 023d3dcffd96e28fd05dcefe84f088b6b64a4f6a Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Thu, 18 Jul 2024 15:50:44 +0200 Subject: [PATCH 26/27] fix: own review + fixing CI fail --- pop-api/src/lib.rs | 8 +- pop-api/src/primitives.rs | 1 + pop-api/src/v0/assets/fungibles.rs | 57 +++++---- pop-api/src/v0/assets/mod.rs | 140 ++++++++-------------- pop-api/src/v0/mod.rs | 5 +- primitives/src/lib.rs | 6 +- runtime/devnet/src/extensions/mod.rs | 8 +- runtime/devnet/src/extensions/v0/error.rs | 6 +- 8 files changed, 95 insertions(+), 136 deletions(-) diff --git a/pop-api/src/lib.rs b/pop-api/src/lib.rs index 7a0fe75b..86621c51 100644 --- a/pop-api/src/lib.rs +++ b/pop-api/src/lib.rs @@ -29,15 +29,15 @@ mod constants { pub(crate) const READ_STATE: u8 = 1; // Modules: - pub(crate) const ASSETS_MODULE: u8 = 52; - pub(crate) const BALANCES_MODULE: u8 = 10; + pub(crate) const ASSETS: u8 = 52; + pub(crate) const BALANCES: u8 = 10; } /// Represents a status code returned by the runtime. /// /// `StatusCode` encapsulates a `u32` value that indicates the status of an operation performed -/// by the runtime. It helps to communicate the success or failure of a chain extension method -/// call to the contract, providing a standardized way to handle errors. +/// by the runtime. It helps to communicate the success or failure of a Pop API call to the contract, +/// providing a standardized way to handle errors. /// /// This status code can be used to determine if an operation succeeded or if it encountered /// an error. A `StatusCode` of `0` typically indicates success, while any other value represents diff --git a/pop-api/src/primitives.rs b/pop-api/src/primitives.rs index b451ce79..33285044 100644 --- a/pop-api/src/primitives.rs +++ b/pop-api/src/primitives.rs @@ -1,4 +1,5 @@ use ink::env::{DefaultEnvironment, Environment}; + pub use pop_primitives::*; pub(crate) type AccountId = ::AccountId; diff --git a/pop-api/src/v0/assets/fungibles.rs b/pop-api/src/v0/assets/fungibles.rs index 9084708d..255e8502 100644 --- a/pop-api/src/v0/assets/fungibles.rs +++ b/pop-api/src/v0/assets/fungibles.rs @@ -2,7 +2,7 @@ use ink::prelude::vec::Vec; use crate::{ assets, - constants::{ASSETS_MODULE, BALANCES_MODULE, MODULE_ERROR}, + constants::{ASSETS, BALANCES, MODULE_ERROR}, primitives::{AccountId, AssetId, Balance}, Result, StatusCode, }; @@ -106,7 +106,7 @@ pub fn transfer_from(id: AssetId, from: AccountId, to: AccountId, value: Balance /// Returns `Ok(())` if successful, or an error if the approval fails. #[inline] pub fn approve(id: AssetId, spender: AccountId, value: Balance) -> Result<()> { - assets::cancel_approval(id, spender.clone())?; + assets::cancel_approval(id, spender)?; assets::approve_transfer(id, spender, value) } @@ -284,7 +284,7 @@ pub fn token_decimals(id: AssetId) -> Result { // assets::asset_exists(id) // } -/// Represents various errors related to local fungible assets in the API. +/// Represents various errors related to local fungible assets in the Pop API. /// /// The `FungiblesError` provides a detailed and specific set of error types that can occur when /// interacting with fungible assets through the Pop API. Each variant signifies a particular error @@ -332,15 +332,15 @@ impl From for FungiblesError { let encoded = value.0.to_le_bytes(); match encoded { // Balances. - [MODULE_ERROR, BALANCES_MODULE, 2, _] => FungiblesError::NoBalance, + [MODULE_ERROR, BALANCES, 2, _] => FungiblesError::NoBalance, // Assets. - [MODULE_ERROR, ASSETS_MODULE, 0, _] => FungiblesError::NoAccount, - [MODULE_ERROR, ASSETS_MODULE, 1, _] => FungiblesError::NoPermission, - [MODULE_ERROR, ASSETS_MODULE, 2, _] => FungiblesError::Unknown, - [MODULE_ERROR, ASSETS_MODULE, 3, _] => FungiblesError::InUse, - [MODULE_ERROR, ASSETS_MODULE, 5, _] => FungiblesError::MinBalanceZero, - [MODULE_ERROR, ASSETS_MODULE, 7, _] => FungiblesError::InsufficientAllowance, - [MODULE_ERROR, ASSETS_MODULE, 10, _] => FungiblesError::AssetNotLive, + [MODULE_ERROR, ASSETS, 0, _] => FungiblesError::NoAccount, + [MODULE_ERROR, ASSETS, 1, _] => FungiblesError::NoPermission, + [MODULE_ERROR, ASSETS, 2, _] => FungiblesError::Unknown, + [MODULE_ERROR, ASSETS, 3, _] => FungiblesError::InUse, + [MODULE_ERROR, ASSETS, 5, _] => FungiblesError::MinBalanceZero, + [MODULE_ERROR, ASSETS, 7, _] => FungiblesError::InsufficientAllowance, + [MODULE_ERROR, ASSETS, 10, _] => FungiblesError::AssetNotLive, _ => FungiblesError::Other(value), } } @@ -348,17 +348,19 @@ impl From for FungiblesError { #[cfg(test)] mod tests { - use crate::constants::{ASSETS_MODULE, BALANCES_MODULE}; use ink::scale::{Decode, Encode}; use super::FungiblesError; - use crate::primitives::error::{ - ArithmeticError::*, - Error::{self, *}, - TokenError::*, - TransactionalError::*, + use crate::{ + constants::{ASSETS, BALANCES}, + primitives::error::{ + ArithmeticError::*, + Error::{self, *}, + TokenError::*, + TransactionalError::*, + }, + StatusCode, }; - use crate::StatusCode; fn error_into_status_code(error: Error) -> StatusCode { let mut encoded_error = error.encode(); @@ -415,35 +417,32 @@ mod tests { } assert_eq!( - into_fungibles_error(Module { index: BALANCES_MODULE, error: 2 }), + into_fungibles_error(Module { index: BALANCES, error: 2 }), FungiblesError::NoBalance ); assert_eq!( - into_fungibles_error(Module { index: ASSETS_MODULE, error: 0 }), + into_fungibles_error(Module { index: ASSETS, error: 0 }), FungiblesError::NoAccount ); assert_eq!( - into_fungibles_error(Module { index: ASSETS_MODULE, error: 1 }), + into_fungibles_error(Module { index: ASSETS, error: 1 }), FungiblesError::NoPermission ); assert_eq!( - into_fungibles_error(Module { index: ASSETS_MODULE, error: 2 }), + into_fungibles_error(Module { index: ASSETS, error: 2 }), FungiblesError::Unknown ); + assert_eq!(into_fungibles_error(Module { index: ASSETS, error: 3 }), FungiblesError::InUse); assert_eq!( - into_fungibles_error(Module { index: ASSETS_MODULE, error: 3 }), - FungiblesError::InUse - ); - assert_eq!( - into_fungibles_error(Module { index: ASSETS_MODULE, error: 5 }), + into_fungibles_error(Module { index: ASSETS, error: 5 }), FungiblesError::MinBalanceZero ); assert_eq!( - into_fungibles_error(Module { index: ASSETS_MODULE, error: 7 }), + into_fungibles_error(Module { index: ASSETS, error: 7 }), FungiblesError::InsufficientAllowance ); assert_eq!( - into_fungibles_error(Module { index: ASSETS_MODULE, error: 10 }), + into_fungibles_error(Module { index: ASSETS, error: 10 }), FungiblesError::AssetNotLive ); } diff --git a/pop-api/src/v0/assets/mod.rs b/pop-api/src/v0/assets/mod.rs index fa7d523b..00021fc0 100644 --- a/pop-api/src/v0/assets/mod.rs +++ b/pop-api/src/v0/assets/mod.rs @@ -1,9 +1,9 @@ use ink::{env::chain_extension::ChainExtensionMethod, prelude::vec::Vec, scale::Decode}; use crate::{ - constants::{ASSETS_MODULE, DECODING_FAILED, DISPATCH, READ_STATE}, + constants::{ASSETS, DECODING_FAILED, DISPATCH, READ_STATE}, primitives::{AccountId, AssetId, Balance}, - v0::VERSION, + v0::V0, Result, StatusCode, }; @@ -92,9 +92,9 @@ const TRANSFER_APPROVED: u8 = 25; #[inline] pub fn transfer_keep_alive(id: AssetId, target: AccountId, amount: Balance) -> Result<()> { ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, + V0, DISPATCH, - ASSETS_MODULE, + ASSETS, // E.D. is always respected with transferring tokens via the API. TRANSFER_KEEP_ALIVE, ])) @@ -122,31 +122,21 @@ pub fn transfer_keep_alive(id: AssetId, target: AccountId, amount: Balance) -> R /// Approve an amount of asset for transfer by a delegated third-party account. #[inline] pub fn approve_transfer(id: AssetId, delegate: AccountId, amount: Balance) -> Result<()> { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - DISPATCH, - ASSETS_MODULE, - APPROVE_TRANSFER, - ])) - .input::<(AssetId, AccountId, Balance)>() - .output::, true>() - .handle_error_code::() - .call(&(id, delegate, amount)) + ChainExtensionMethod::build(u32::from_le_bytes([V0, DISPATCH, ASSETS, APPROVE_TRANSFER])) + .input::<(AssetId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, delegate, amount)) } /// Cancel all of some asset approved for delegated transfer by a third-party account. #[inline] pub fn cancel_approval(id: AssetId, delegate: AccountId) -> Result<()> { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - DISPATCH, - ASSETS_MODULE, - CANCEL_APPROVAL, - ])) - .input::<(AssetId, AccountId)>() - .output::, true>() - .handle_error_code::() - .call(&(id, delegate)) + ChainExtensionMethod::build(u32::from_le_bytes([V0, DISPATCH, ASSETS, CANCEL_APPROVAL])) + .input::<(AssetId, AccountId)>() + .output::, true>() + .handle_error_code::() + .call(&(id, delegate)) } /// Transfer some asset balance from a previously delegated account to some third-party @@ -158,16 +148,11 @@ pub fn transfer_approved( to: AccountId, amount: Balance, ) -> Result<()> { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - DISPATCH, - ASSETS_MODULE, - TRANSFER_APPROVED, - ])) - .input::<(AssetId, AccountId, AccountId, Balance)>() - .output::, true>() - .handle_error_code::() - .call(&(id, from, to, amount)) + ChainExtensionMethod::build(u32::from_le_bytes([V0, DISPATCH, ASSETS, TRANSFER_APPROVED])) + .input::<(AssetId, AccountId, AccountId, Balance)>() + .output::, true>() + .handle_error_code::() + .call(&(id, from, to, amount)) } /// 2. Read state functions: @@ -187,37 +172,27 @@ const TOKEN_DECIMALS: u8 = 5; #[inline] pub fn total_supply(id: AssetId) -> Result { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - READ_STATE, - ASSETS_MODULE, - TOTAL_SUPPLY, - ])) - .input::() - .output::>, true>() - .handle_error_code::() - .call(&(id)) - .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) + ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, ASSETS, TOTAL_SUPPLY])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } #[inline] pub fn balance_of(id: AssetId, owner: AccountId) -> Result { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - READ_STATE, - ASSETS_MODULE, - BALANCE_OF, - ])) - .input::<(AssetId, AccountId)>() - .output::>, true>() - .handle_error_code::() - .call(&(id, owner)) - .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) + ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, ASSETS, BALANCE_OF])) + .input::<(AssetId, AccountId)>() + .output::>, true>() + .handle_error_code::() + .call(&(id, owner)) + .and_then(|v| Balance::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } #[inline] pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result { - ChainExtensionMethod::build(u32::from_le_bytes([VERSION, READ_STATE, ASSETS_MODULE, ALLOWANCE])) + ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, ASSETS, ALLOWANCE])) .input::<(AssetId, AccountId, AccountId)>() .output::>, true>() .handle_error_code::() @@ -227,47 +202,32 @@ pub fn allowance(id: AssetId, owner: AccountId, spender: AccountId) -> Result Result> { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - READ_STATE, - ASSETS_MODULE, - TOKEN_NAME, - ])) - .input::() - .output::>, true>() - .handle_error_code::() - .call(&(id)) - .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) + ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, ASSETS, TOKEN_NAME])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } // #[inline] pub fn token_symbol(id: AssetId) -> Result> { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - READ_STATE, - ASSETS_MODULE, - TOKEN_SYMBOL, - ])) - .input::() - .output::>, true>() - .handle_error_code::() - .call(&(id)) - .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) + ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, ASSETS, TOKEN_SYMBOL])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| >::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } #[inline] pub fn token_decimals(id: AssetId) -> Result { - ChainExtensionMethod::build(u32::from_le_bytes([ - VERSION, - READ_STATE, - ASSETS_MODULE, - TOKEN_DECIMALS, - ])) - .input::() - .output::>, true>() - .handle_error_code::() - .call(&(id)) - .and_then(|v| ::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) + ChainExtensionMethod::build(u32::from_le_bytes([V0, READ_STATE, ASSETS, TOKEN_DECIMALS])) + .input::() + .output::>, true>() + .handle_error_code::() + .call(&(id)) + .and_then(|v| ::decode(&mut &v[..]).map_err(|_e| StatusCode(DECODING_FAILED))) } // pub(crate) fn asset_exists(id: AssetId) -> Result { diff --git a/pop-api/src/v0/mod.rs b/pop-api/src/v0/mod.rs index 8b7a8469..f7dab6b4 100644 --- a/pop-api/src/v0/mod.rs +++ b/pop-api/src/v0/mod.rs @@ -1,5 +1,4 @@ -use crate::StatusCode; -use pop_primitives::error::Error; +use crate::{primitives::error::Error, StatusCode}; #[cfg(feature = "assets")] pub mod assets; @@ -10,7 +9,7 @@ pub mod cross_chain; #[cfg(feature = "nfts")] pub mod nfts; -pub(crate) const VERSION: u8 = 0; +pub(crate) const V0: u8 = 0; impl From for Error { fn from(value: StatusCode) -> Self { diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index b9caf111..ec6670ba 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -37,7 +37,7 @@ pub mod v0 { pub mod error { use super::*; - /// Reason why a Pop API function call failed. + /// Reason why a Pop API call failed. #[derive(Encode, Decode, Debug, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(TypeInfo))] #[repr(u8)] @@ -82,8 +82,8 @@ pub mod v0 { Unavailable, /// Root origin is not allowed. RootNotAllowed, - /// Unknown function called. - UnknownFunctionCall = 254, + /// Unknown call. + UnknownCall = 254, /// Decoding failed. DecodingFailed = 255, } diff --git a/runtime/devnet/src/extensions/mod.rs b/runtime/devnet/src/extensions/mod.rs index ec2d0bc2..d2bd63e7 100644 --- a/runtime/devnet/src/extensions/mod.rs +++ b/runtime/devnet/src/extensions/mod.rs @@ -337,11 +337,11 @@ pub(crate) fn convert_to_status_code(error: DispatchError, version: u8) -> u32 { u32::from_le_bytes(encoded_error) } -/// Enum representing the different function identifiers used in the Pop API chain extension. +/// Function identifiers used in the Pop API. /// -/// The `FuncId` enum specifies the available functions that can be called through the Pop API chain -/// extension. Each variant corresponds to a specific functionality provided by the chain extension, -/// facilitating the interaction between smart contracts and the runtime. +/// The `FuncId` specifies the available functions that can be called through the Pop API. Each +/// variant corresponds to a specific functionality provided by the API, facilitating the +/// interaction between smart contracts and the runtime. /// /// - `Dispatch`: Represents a function call to dispatch a runtime call. /// - `ReadState`: Represents a function call to read the state from the runtime. diff --git a/runtime/devnet/src/extensions/v0/error.rs b/runtime/devnet/src/extensions/v0/error.rs index b8af2250..b26668f7 100644 --- a/runtime/devnet/src/extensions/v0/error.rs +++ b/runtime/devnet/src/extensions/v0/error.rs @@ -76,7 +76,7 @@ mod tests { DispatchError::Other(""), (Other { dispatch_error_index: 0, error_index: 0, error: 0 }), ), - (DispatchError::Other("UnknownFunctionId"), UnknownFunctionId), + (DispatchError::Other("UnknownFunctionId"), UnknownCall), (DispatchError::Other("DecodingFailed"), DecodingFailed), (DispatchError::CannotLookup, CannotLookup), (DispatchError::BadOrigin, BadOrigin), @@ -120,7 +120,7 @@ mod tests { DispatchError::Other("Random"), (Other { dispatch_error_index: 0, error_index: 0, error: 0 }), ), - (DispatchError::Other("UnknownFunctionId"), UnknownFunctionId), + (DispatchError::Other("UnknownFunctionId"), UnknownCall), (DispatchError::Other("DecodingFailed"), DecodingFailed), ]; for (dispatch_error, expected) in test_cases { @@ -185,7 +185,7 @@ mod tests { Corruption, Unavailable, RootNotAllowed, - UnknownFunctionId, + UnknownCall, DecodingFailed, ]; // Compare an `Error`, which is converted from an encoded value, with the expected `Error`. From e683e160f4a753ecfcd596c823947ab02917c797 Mon Sep 17 00:00:00 2001 From: Daanvdplas Date: Fri, 19 Jul 2024 10:24:21 +0200 Subject: [PATCH 27/27] refactor: add Error variants index + clippy allowance --- primitives/src/lib.rs | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index ec6670ba..376b440d 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -41,6 +41,7 @@ pub mod v0 { #[derive(Encode, Decode, Debug, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(TypeInfo))] #[repr(u8)] + #[allow(clippy::unnecessary_cast)] pub enum Error { /// An unknown error occurred. This variant captures any unexpected errors that the /// contract cannot specifically handle. It is useful for cases where there are breaking @@ -51,37 +52,37 @@ pub mod v0 { /// - `error_index`: The index within the `DispatchError` variant (e.g. a `TokenError`). /// - `error`: The specific error code or sub-index, providing additional context (e.g. /// `error` in `ModuleError`). - Other { dispatch_error_index: u8, error_index: u8, error: u8 }, + Other { dispatch_error_index: u8, error_index: u8, error: u8 } = 0, /// Failed to lookup some data. - CannotLookup, + CannotLookup = 1, /// A bad origin. - BadOrigin, + BadOrigin = 2, /// A custom error in a module. /// /// - `index`: The pallet index. /// - `error`: The error within the pallet. - Module { index: u8, error: u8 }, + Module { index: u8, error: u8 } = 3, /// At least one consumer is remaining so the account cannot be destroyed. - ConsumerRemaining, + ConsumerRemaining = 4, /// There are no providers so the account cannot be created. - NoProviders, + NoProviders = 5, /// There are too many consumers so the account cannot be created. - TooManyConsumers, + TooManyConsumers = 6, /// An error to do with tokens. - Token(TokenError), + Token(TokenError) = 7, /// An arithmetic error. - Arithmetic(ArithmeticError), + Arithmetic(ArithmeticError) = 8, /// The number of transactional layers has been reached, or we are not in a transactional /// layer. - Transactional(TransactionalError), + Transactional(TransactionalError) = 9, /// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate. - Exhausted, + Exhausted = 10, /// The state is corrupt; this is generally not going to fix itself. - Corruption, + Corruption = 11, /// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later. - Unavailable, + Unavailable = 12, /// Root origin is not allowed. - RootNotAllowed, + RootNotAllowed = 13, /// Unknown call. UnknownCall = 254, /// Decoding failed.